Autoload more carefully from Lisp. Follow aliases for function properties.
[bpt/emacs.git] / lisp / emacs-lisp / gv.el
1 ;;; gv.el --- Generalized variables -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2012 Free Software Foundation, Inc.
4
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Keywords: extensions
7
8 ;; This program is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
12
13 ;; This program is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
20
21 ;;; Commentary:
22
23 ;; This is a re-implementation of the setf machinery using a different
24 ;; underlying approach than the one used earlier in CL, which was based on
25 ;; define-setf-expander.
26 ;; `define-setf-expander' makes every "place-expander" return a 5-tuple
27 ;; (VARS VALUES STORES GETTER SETTER)
28 ;; where STORES is a list with a single variable (Common-Lisp allows multiple
29 ;; variables for use with multiple-return-values, but this is rarely used and
30 ;; not applicable to Elisp).
31 ;; It basically says that GETTER is an expression that returns the place's
32 ;; value, and (lambda STORES SETTER) is an expression that assigns the value(s)
33 ;; passed to that function to the place, and that you need to wrap the whole
34 ;; thing within a `(let* ,(zip VARS VALUES) ...).
35 ;;
36 ;; Instead, we use here a higher-order approach: instead
37 ;; of a 5-tuple, a place-expander returns a function.
38 ;; If you think about types, the old approach return things of type
39 ;; {vars: List Var, values: List Exp,
40 ;; stores: List Var, getter: Exp, setter: Exp}
41 ;; whereas the new approach returns a function of type
42 ;; (do: ((getter: Exp, setter: ((store: Exp) -> Exp)) -> Exp)) -> Exp.
43 ;; You can get the new function from the old 5-tuple with something like:
44 ;; (lambda (do)
45 ;; `(let* ,(zip VARS VALUES)
46 ;; (funcall do GETTER (lambda ,STORES ,SETTER))))
47 ;; You can't easily do the reverse, because this new approach is more
48 ;; expressive than the old one, so we can't provide a backward-compatible
49 ;; get-setf-method.
50 ;;
51 ;; While it may seem intimidating for people not used to higher-order
52 ;; functions, you will quickly see that its use (especially with the
53 ;; `gv-letplace' macro) is actually much easier and more elegant than the old
54 ;; approach which is clunky and often leads to unreadable code.
55
56 ;; Food for thought: the syntax of places does not actually conflict with the
57 ;; pcase patterns. The `cons' gv works just like a `(,a . ,b) pcase
58 ;; pattern, and actually the `logand' gv is even closer since it should
59 ;; arguably fail when trying to set a value outside of the mask.
60 ;; Generally, places are used for destructors (gethash, aref, car, ...)
61 ;; whereas pcase patterns are used for constructors (backquote, constants,
62 ;; vectors, ...).
63
64 ;;; Code:
65
66 (require 'macroexp)
67
68 ;; What we call a "gvar" is basically a function of type "(getter * setter ->
69 ;; code) -> code", where "getter" is code and setter is "code -> code".
70
71 ;; (defvar gv--macro-environment nil
72 ;; "Macro expanders for generalized variables.")
73
74 ;;;###autoload
75 (defun gv-get (place do)
76 "Build the code that applies DO to PLACE.
77 PLACE must be a valid generalized variable.
78 DO must be a function; it will be called with 2 arguments: GETTER and SETTER,
79 where GETTER is a (copyable) Elisp expression that returns the value of PLACE,
80 and SETTER is a function which returns the code to set PLACE when called
81 with a (not necessarily copyable) Elisp expression that returns the value to
82 set it to.
83 DO must return an Elisp expression."
84 (if (symbolp place)
85 (funcall do place (lambda (v) `(setq ,place ,v)))
86 (let* ((head (car place))
87 (gf (function-get head 'gv-expander 'autoload)))
88 (if gf (apply gf do (cdr place))
89 (let ((me (macroexpand place ;FIXME: expand one step at a time!
90 ;; (append macroexpand-all-environment
91 ;; gv--macro-environment)
92 macroexpand-all-environment)))
93 (if (and (eq me place) (get head 'compiler-macro))
94 ;; Expand compiler macros: this takes care of all the accessors
95 ;; defined via cl-defsubst, such as cXXXr and defstruct slots.
96 (setq me (apply (get head 'compiler-macro) place (cdr place))))
97 (if (and (eq me place) (fboundp head)
98 (symbolp (symbol-function head)))
99 ;; Follow aliases.
100 (setq me (cons (symbol-function head) (cdr place))))
101 (if (eq me place)
102 (error "%S is not a valid place expression" place)
103 (gv-get me do)))))))
104
105 ;;;###autoload
106 (defmacro gv-letplace (vars place &rest body)
107 "Build the code manipulating the generalized variable PLACE.
108 GETTER will be bound to a copyable expression that returns the value
109 of PLACE.
110 SETTER will be bound to a function that takes an expression V and returns
111 and new expression that sets PLACE to V.
112 BODY should return some Elisp expression E manipulating PLACE via GETTER
113 and SETTER.
114 The returned value will then be an Elisp expression that first evaluates
115 all the parts of PLACE that can be evaluated and then runs E.
116
117 \(fn (GETTER SETTER) PLACE &rest BODY)"
118 (declare (indent 2) (debug (sexp form body)))
119 `(gv-get ,place (lambda ,vars ,@body)))
120
121 ;; Different ways to declare a generalized variable.
122 ;;;###autoload
123 (defmacro gv-define-expander (name handler)
124 "Use HANDLER to handle NAME as a generalized var.
125 NAME is a symbol: the name of a function, macro, or special form.
126 HANDLER is a function which takes an argument DO followed by the same
127 arguments as NAME. DO is a function as defined in `gv-get'."
128 (declare (indent 1) (debug (sexp form)))
129 ;; Use eval-and-compile so the method can be used in the same file as it
130 ;; is defined.
131 ;; FIXME: Just like byte-compile-macro-environment, we should have something
132 ;; like byte-compile-symbolprop-environment so as to handle these things
133 ;; cleanly without affecting the running Emacs.
134 `(eval-and-compile (put ',name 'gv-expander ,handler)))
135
136 ;;;###autoload
137 (defun gv--defun-declaration (symbol name args handler &optional fix)
138 `(progn
139 ;; No need to autoload this part, since gv-get will auto-load the
140 ;; function's definition before checking the `gv-expander' property.
141 :autoload-end
142 ,(pcase (cons symbol handler)
143 (`(gv-expander . (lambda (,do) . ,body))
144 `(gv-define-expander ,name (lambda (,do ,@args) ,@body)))
145 (`(gv-expander . ,(pred symbolp))
146 `(gv-define-expander ,name #',handler))
147 (`(gv-setter . (lambda (,store) . ,body))
148 `(gv-define-setter ,name (,store ,@args) ,@body))
149 (`(gv-setter . ,(pred symbolp))
150 `(gv-define-simple-setter ,name ,handler ,fix))
151 ;; (`(expand ,expander) `(gv-define-expand ,name ,expander))
152 (_ (message "Unknown %s declaration %S" symbol handler) nil))))
153
154 ;;;###autoload
155 (push `(gv-expander ,(apply-partially #'gv--defun-declaration 'gv-expander))
156 defun-declarations-alist)
157 ;;;###autoload
158 (push `(gv-setter ,(apply-partially #'gv--defun-declaration 'gv-setter))
159 defun-declarations-alist)
160
161 ;; (defmacro gv-define-expand (name expander)
162 ;; "Use EXPANDER to handle NAME as a generalized var.
163 ;; NAME is a symbol: the name of a function, macro, or special form.
164 ;; EXPANDER is a function that will be called as a macro-expander to reduce
165 ;; uses of NAME to some other generalized variable."
166 ;; (declare (debug (sexp form)))
167 ;; `(eval-and-compile
168 ;; (if (not (boundp 'gv--macro-environment))
169 ;; (setq gv--macro-environment nil))
170 ;; (push (cons ',name ,expander) gv--macro-environment)))
171
172 (defun gv--defsetter (name setter do args &optional vars)
173 "Helper function used by code generated by `gv-define-setter'.
174 NAME is the name of the getter function.
175 SETTER is a function that generates the code for the setter.
176 NAME accept ARGS as arguments and SETTER accepts (NEWVAL . ARGS).
177 VARS is used internally for recursive calls."
178 (if (null args)
179 (let ((vars (nreverse vars)))
180 (funcall do `(,name ,@vars) (lambda (v) (apply setter v vars))))
181 ;; FIXME: Often it would be OK to skip this `let', but in general,
182 ;; `do' may have all kinds of side-effects.
183 (macroexp-let2 nil v (car args)
184 (gv--defsetter name setter do (cdr args) (cons v vars)))))
185
186 ;;;###autoload
187 (defmacro gv-define-setter (name arglist &rest body)
188 "Define a setter method for generalized variable NAME.
189 This macro is an easy-to-use substitute for `gv-define-expander' that works
190 well for simple place forms.
191 Assignments of VAL to (NAME ARGS...) are expanded by binding the argument
192 forms (VAL ARGS...) according to ARGLIST, then executing BODY, which must
193 return a Lisp form that does the assignment.
194 Actually, ARGLIST may be bound to temporary variables which are introduced
195 automatically to preserve proper execution order of the arguments. Example:
196 (gv-define-setter aref (v a i) `(aset ,a ,i ,v))"
197 (declare (indent 2) (debug (&define name sexp body)))
198 `(gv-define-expander ,name
199 (lambda (do &rest args)
200 (gv--defsetter ',name (lambda ,arglist ,@body) do args))))
201
202 ;;;###autoload
203 (defmacro gv-define-simple-setter (name setter &optional fix-return)
204 "Define a simple setter method for generalized variable NAME.
205 This macro is an easy-to-use substitute for `gv-define-expander' that works
206 well for simple place forms. Assignments of VAL to (NAME ARGS...) are
207 turned into calls of the form (SETTER ARGS... VAL).
208 If FIX-RETURN is non-nil, then SETTER is not assumed to return VAL and
209 instead the assignment is turned into (prog1 VAL (SETTER ARGS... VAL))
210 so as to preserve the semantics of `setf'."
211 (declare (debug (sexp (&or symbolp lambda-expr) &optional sexp)))
212 (let ((set-call `(cons ',setter (append args (list val)))))
213 `(gv-define-setter ,name (val &rest args)
214 ,(if fix-return `(list 'prog1 val ,set-call) set-call))))
215
216 ;;; Typical operations on generalized variables.
217
218 ;;;###autoload
219 (defmacro setf (&rest args)
220 "Set each PLACE to the value of its VAL.
221 This is a generalized version of `setq'; the PLACEs may be symbolic
222 references such as (car x) or (aref x i), as well as plain symbols.
223 For example, (setf (cadr x) y) is equivalent to (setcar (cdr x) y).
224 The return value is the last VAL in the list.
225
226 \(fn PLACE VAL PLACE VAL ...)"
227 (declare (debug (gv-place form)))
228 (if (and args (null (cddr args)))
229 (let ((place (pop args))
230 (val (car args)))
231 (gv-letplace (_getter setter) place
232 (funcall setter val)))
233 (let ((sets nil))
234 (while args (push `(setf ,(pop args) ,(pop args)) sets))
235 (cons 'progn (nreverse sets)))))
236
237 ;; (defmacro gv-pushnew! (val place)
238 ;; "Like `gv-push!' but only adds VAL if it's not yet in PLACE.
239 ;; Presence is checked with `member'.
240 ;; The return value is unspecified."
241 ;; (declare (debug (form gv-place)))
242 ;; (macroexp-let2 macroexp-copyable-p v val
243 ;; (gv-letplace (getter setter) place
244 ;; `(if (member ,v ,getter) nil
245 ;; ,(funcall setter `(cons ,v ,getter))))))
246
247 ;; (defmacro gv-inc! (place &optional val)
248 ;; "Increment PLACE by VAL (default to 1)."
249 ;; (declare (debug (gv-place &optional form)))
250 ;; (gv-letplace (getter setter) place
251 ;; (funcall setter `(+ ,getter ,(or val 1)))))
252
253 ;; (defmacro gv-dec! (place &optional val)
254 ;; "Decrement PLACE by VAL (default to 1)."
255 ;; (declare (debug (gv-place &optional form)))
256 ;; (gv-letplace (getter setter) place
257 ;; (funcall setter `(- ,getter ,(or val 1)))))
258
259 ;; For Edebug, the idea is to let Edebug instrument gv-places just like it does
260 ;; for normal expressions, and then give it a gv-expander to DTRT.
261 ;; Maybe this should really be in edebug.el rather than here.
262
263 ;; Autoload this `put' since a user might use C-u C-M-x on an expression
264 ;; containing a non-trivial `push' even before gv.el was loaded.
265 ;;;###autoload
266 (put 'gv-place 'edebug-form-spec 'edebug-match-form)
267 ;; CL did the equivalent of:
268 ;;(gv-define-expand edebug-after (lambda (before index place) place))
269
270 (put 'edebug-after 'gv-expander
271 (lambda (do before index place)
272 (gv-letplace (getter setter) place
273 (funcall do `(edebug-after ,before ,index ,getter)
274 setter))))
275
276 ;;; The common generalized variables.
277
278 (gv-define-simple-setter aref aset)
279 (gv-define-simple-setter car setcar)
280 (gv-define-simple-setter cdr setcdr)
281 ;; FIXME: add compiler-macros for `cXXr' instead!
282 (gv-define-setter caar (val x) `(setcar (car ,x) ,val))
283 (gv-define-setter cadr (val x) `(setcar (cdr ,x) ,val))
284 (gv-define-setter cdar (val x) `(setcdr (car ,x) ,val))
285 (gv-define-setter cddr (val x) `(setcdr (cdr ,x) ,val))
286 (gv-define-setter elt (store seq n)
287 `(if (listp ,seq) (setcar (nthcdr ,n ,seq) ,store)
288 (aset ,seq ,n ,store)))
289 (gv-define-simple-setter get put)
290 (gv-define-setter gethash (val k h &optional _d) `(puthash ,k ,val ,h))
291
292 ;; (gv-define-expand nth (lambda (idx list) `(car (nthcdr ,idx ,list))))
293 (put 'nth 'gv-expander
294 (lambda (do idx list)
295 (macroexp-let2 nil c `(nthcdr ,idx ,list)
296 (funcall do `(car ,c) (lambda (v) `(setcar ,c ,v))))))
297 (gv-define-simple-setter symbol-function fset)
298 (gv-define-simple-setter symbol-plist setplist)
299 (gv-define-simple-setter symbol-value set)
300
301 (put 'nthcdr 'gv-expander
302 (lambda (do n place)
303 (macroexp-let2 nil idx n
304 (gv-letplace (getter setter) place
305 (funcall do `(nthcdr ,idx ,getter)
306 (lambda (v) `(if (<= ,idx 0) ,(funcall setter v)
307 (setcdr (nthcdr (1- ,idx) ,getter) ,v))))))))
308
309 ;;; Elisp-specific generalized variables.
310
311 (gv-define-simple-setter default-value set-default)
312 (gv-define-simple-setter frame-parameter set-frame-parameter 'fix)
313 (gv-define-simple-setter terminal-parameter set-terminal-parameter)
314 (gv-define-simple-setter keymap-parent set-keymap-parent)
315 (gv-define-simple-setter match-data set-match-data 'fix)
316 (gv-define-simple-setter overlay-get overlay-put)
317 (gv-define-setter overlay-start (store ov)
318 `(progn (move-overlay ,ov ,store (overlay-end ,ov)) ,store))
319 (gv-define-setter overlay-end (store ov)
320 `(progn (move-overlay ,ov (overlay-start ,ov) ,store) ,store))
321 (gv-define-simple-setter process-buffer set-process-buffer)
322 (gv-define-simple-setter process-filter set-process-filter)
323 (gv-define-simple-setter process-sentinel set-process-sentinel)
324 (gv-define-simple-setter process-get process-put)
325 (gv-define-simple-setter window-buffer set-window-buffer)
326 (gv-define-simple-setter window-display-table set-window-display-table 'fix)
327 (gv-define-simple-setter window-dedicated-p set-window-dedicated-p)
328 (gv-define-simple-setter window-hscroll set-window-hscroll)
329 (gv-define-simple-setter window-parameter set-window-parameter)
330 (gv-define-simple-setter window-point set-window-point)
331 (gv-define-simple-setter window-start set-window-start)
332
333 ;;; Some occasionally handy extensions.
334
335 ;; While several of the "places" below are not terribly useful for direct use,
336 ;; they can show up as the output of the macro expansion of reasonable places,
337 ;; such as struct-accessors.
338
339 (put 'progn 'gv-expander
340 (lambda (do &rest exps)
341 (let ((start (butlast exps))
342 (end (car (last exps))))
343 (if (null start) (gv-get end do)
344 `(progn ,@start ,(gv-get end do))))))
345
346 (let ((let-expander
347 (lambda (letsym)
348 (lambda (do bindings &rest body)
349 `(,letsym ,bindings
350 ,@(macroexp-unprogn
351 (gv-get (macroexp-progn body) do)))))))
352 (put 'let 'gv-expander (funcall let-expander 'let))
353 (put 'let* 'gv-expander (funcall let-expander 'let*)))
354
355 (put 'if 'gv-expander
356 (lambda (do test then &rest else)
357 (if (macroexp-small-p (funcall do 'dummy (lambda (_) 'dummy)))
358 ;; This duplicates the `do' code, which is a problem if that
359 ;; code is large, but otherwise results in more efficient code.
360 `(if ,test ,(gv-get then do)
361 ,@(macroexp-unprogn (gv-get (macroexp-progn else) do)))
362 (let ((v (make-symbol "v")))
363 (macroexp-let2 nil
364 gv `(if ,test ,(gv-letplace (getter setter) then
365 `(cons (lambda () ,getter)
366 (lambda (,v) ,(funcall setter v))))
367 ,(gv-letplace (getter setter) (macroexp-progn else)
368 `(cons (lambda () ,getter)
369 (lambda (,v) ,(funcall setter v)))))
370 (funcall do `(funcall (car ,gv))
371 (lambda (v) `(funcall (cdr ,gv) ,v))))))))
372
373 (put 'cond 'gv-expander
374 (lambda (do &rest branches)
375 (if (macroexp-small-p (funcall do 'dummy (lambda (_) 'dummy)))
376 ;; This duplicates the `do' code, which is a problem if that
377 ;; code is large, but otherwise results in more efficient code.
378 `(cond
379 ,@(mapcar (lambda (branch)
380 (if (cdr branch)
381 (cons (car branch)
382 (macroexp-unprogn
383 (gv-get (macroexp-progn (cdr branch)) do)))
384 (gv-get (car branch) do)))
385 branches))
386 (let ((v (make-symbol "v")))
387 (macroexp-let2 nil
388 gv `(cond
389 ,@(mapcar
390 (lambda (branch)
391 (if (cdr branch)
392 `(,(car branch)
393 ,@(macroexp-unprogn
394 (gv-letplace (getter setter)
395 (macroexp-progn (cdr branch))
396 `(cons (lambda () ,getter)
397 (lambda (,v) ,(funcall setter v))))))
398 (gv-letplace (getter setter)
399 (car branch)
400 `(cons (lambda () ,getter)
401 (lambda (,v) ,(funcall setter v))))))
402 branches))
403 (funcall do `(funcall (car ,gv))
404 (lambda (v) `(funcall (cdr ,gv) ,v))))))))
405
406 ;;; Even more debatable extensions.
407
408 (put 'cons 'gv-expander
409 (lambda (do a d)
410 (gv-letplace (agetter asetter) a
411 (gv-letplace (dgetter dsetter) d
412 (funcall do
413 `(cons ,agetter ,dgetter)
414 (lambda (v) `(progn
415 ,(funcall asetter `(car ,v))
416 ,(funcall dsetter `(cdr ,v)))))))))
417
418 (put 'logand 'gv-expander
419 (lambda (do place &rest masks)
420 (gv-letplace (getter setter) place
421 (macroexp-let2 macroexp-copyable-p
422 mask (if (cdr masks) `(logand ,@masks) (car masks))
423 (funcall
424 do `(logand ,getter ,mask)
425 (lambda (v)
426 (funcall setter
427 `(logior (logand ,v ,mask)
428 (logand ,getter (lognot ,mask))))))))))
429
430 ;;; Vaguely related definitions that should be moved elsewhere.
431
432 ;; (defun alist-get (key alist)
433 ;; "Get the value associated to KEY in ALIST."
434 ;; (declare
435 ;; (gv-expander
436 ;; (lambda (do)
437 ;; (macroexp-let2 macroexp-copyable-p k key
438 ;; (gv-letplace (getter setter) alist
439 ;; (macroexp-let2 nil p `(assoc ,k ,getter)
440 ;; (funcall do `(cdr ,p)
441 ;; (lambda (v)
442 ;; `(if ,p (setcdr ,p ,v)
443 ;; ,(funcall setter
444 ;; `(cons (cons ,k ,v) ,getter)))))))))))
445 ;; (cdr (assoc key alist)))
446
447 (provide 'gv)
448 ;;; gv.el ends here