1 ;;; gv.el --- generalized variables -*- lexical-binding: t -*-
3 ;; Copyright (C) 2012-2015 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Keywords: extensions
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;; This is a re-implementation of the setf machinery using a different
27 ;; underlying approach than the one used earlier in CL, which was based on
28 ;; define-setf-expander.
29 ;; `define-setf-expander' makes every "place-expander" return a 5-tuple
30 ;; (VARS VALUES STORES GETTER SETTER)
31 ;; where STORES is a list with a single variable (Common-Lisp allows multiple
32 ;; variables for use with multiple-return-values, but this is rarely used and
33 ;; not applicable to Elisp).
34 ;; It basically says that GETTER is an expression that returns the place's
35 ;; value, and (lambda STORES SETTER) is an expression that assigns the value(s)
36 ;; passed to that function to the place, and that you need to wrap the whole
37 ;; thing within a `(let* ,(zip VARS VALUES) ...).
39 ;; Instead, we use here a higher-order approach: instead
40 ;; of a 5-tuple, a place-expander returns a function.
41 ;; If you think about types, the old approach return things of type
42 ;; {vars: List Var, values: List Exp,
43 ;; stores: List Var, getter: Exp, setter: Exp}
44 ;; whereas the new approach returns a function of type
45 ;; (do: ((getter: Exp, setter: ((store: Exp) -> Exp)) -> Exp)) -> Exp.
46 ;; You can get the new function from the old 5-tuple with something like:
48 ;; `(let* ,(zip VARS VALUES)
49 ;; (funcall do GETTER (lambda ,STORES ,SETTER))))
50 ;; You can't easily do the reverse, because this new approach is more
51 ;; expressive than the old one, so we can't provide a backward-compatible
54 ;; While it may seem intimidating for people not used to higher-order
55 ;; functions, you will quickly see that its use (especially with the
56 ;; `gv-letplace' macro) is actually much easier and more elegant than the old
57 ;; approach which is clunky and often leads to unreadable code.
59 ;; Food for thought: the syntax of places does not actually conflict with the
60 ;; pcase patterns. The `cons' gv works just like a `(,a . ,b) pcase
61 ;; pattern, and actually the `logand' gv is even closer since it should
62 ;; arguably fail when trying to set a value outside of the mask.
63 ;; Generally, places are used for destructors (gethash, aref, car, ...)
64 ;; whereas pcase patterns are used for constructors (backquote, constants,
71 ;; What we call a "gvar" is basically a function of type "(getter * setter ->
72 ;; code) -> code", where "getter" is code and setter is "code -> code".
74 ;; (defvar gv--macro-environment nil
75 ;; "Macro expanders for generalized variables.")
78 (defun gv-get (place do
)
79 "Build the code that applies DO to PLACE.
80 PLACE must be a valid generalized variable.
81 DO must be a function; it will be called with 2 arguments: GETTER and SETTER,
82 where GETTER is a (copyable) Elisp expression that returns the value of PLACE,
83 and SETTER is a function which returns the code to set PLACE when called
84 with a (not necessarily copyable) Elisp expression that returns the value to
86 DO must return an Elisp expression."
88 (funcall do place
(lambda (v) `(setq ,place
,v
)))
89 (let* ((head (car place
))
90 (gf (function-get head
'gv-expander
'autoload
)))
91 (if gf
(apply gf do
(cdr place
))
92 (let ((me (macroexpand-1 place
93 ;; (append macroexpand-all-environment
94 ;; gv--macro-environment)
95 macroexpand-all-environment
)))
96 (if (and (eq me place
) (get head
'compiler-macro
))
97 ;; Expand compiler macros: this takes care of all the accessors
98 ;; defined via cl-defsubst, such as cXXXr and defstruct slots.
99 (setq me
(apply (get head
'compiler-macro
) place
(cdr place
))))
100 (if (and (eq me place
) (fboundp head
)
101 (symbolp (symbol-function head
)))
103 (setq me
(cons (symbol-function head
) (cdr place
))))
105 (if (and (symbolp head
) (get head
'setf-method
))
106 (error "Incompatible place needs recompilation: %S" head
)
107 (error "%S is not a valid place expression" place
))
111 (defmacro gv-letplace
(vars place
&rest body
)
112 "Build the code manipulating the generalized variable PLACE.
113 GETTER will be bound to a copyable expression that returns the value
115 SETTER will be bound to a function that takes an expression V and returns
116 a new expression that sets PLACE to V.
117 BODY should return some Elisp expression E manipulating PLACE via GETTER
119 The returned value will then be an Elisp expression that first evaluates
120 all the parts of PLACE that can be evaluated and then runs E.
122 \(fn (GETTER SETTER) PLACE &rest BODY)"
123 (declare (indent 2) (debug (sexp form body
)))
124 `(gv-get ,place
(lambda ,vars
,@body
)))
126 ;; Different ways to declare a generalized variable.
128 (defmacro gv-define-expander
(name handler
)
129 "Use HANDLER to handle NAME as a generalized var.
130 NAME is a symbol: the name of a function, macro, or special form.
131 HANDLER is a function which takes an argument DO followed by the same
132 arguments as NAME. DO is a function as defined in `gv-get'."
133 (declare (indent 1) (debug (sexp form
)))
134 ;; Use eval-and-compile so the method can be used in the same file as it
136 ;; FIXME: Just like byte-compile-macro-environment, we should have something
137 ;; like byte-compile-symbolprop-environment so as to handle these things
138 ;; cleanly without affecting the running Emacs.
139 `(eval-and-compile (put ',name
'gv-expander
,handler
)))
142 (defun gv--defun-declaration (symbol name args handler
&optional fix
)
144 ;; No need to autoload this part, since gv-get will auto-load the
145 ;; function's definition before checking the `gv-expander' property.
147 ,(pcase (cons symbol handler
)
148 (`(gv-expander .
(lambda (,do
) .
,body
))
149 `(gv-define-expander ,name
(lambda (,do
,@args
) ,@body
)))
150 (`(gv-expander .
,(pred symbolp
))
151 `(gv-define-expander ,name
#',handler
))
152 (`(gv-setter .
(lambda (,store
) .
,body
))
153 `(gv-define-setter ,name
(,store
,@args
) ,@body
))
154 (`(gv-setter .
,(pred symbolp
))
155 `(gv-define-simple-setter ,name
,handler
,fix
))
156 ;; (`(expand ,expander) `(gv-define-expand ,name ,expander))
157 (_ (message "Unknown %s declaration %S" symbol handler
) nil
))))
160 (or (assq 'gv-expander defun-declarations-alist
)
161 (push `(gv-expander ,(apply-partially #'gv--defun-declaration
'gv-expander
))
162 defun-declarations-alist
))
164 (or (assq 'gv-setter defun-declarations-alist
)
165 (push `(gv-setter ,(apply-partially #'gv--defun-declaration
'gv-setter
))
166 defun-declarations-alist
))
168 ;; (defmacro gv-define-expand (name expander)
169 ;; "Use EXPANDER to handle NAME as a generalized var.
170 ;; NAME is a symbol: the name of a function, macro, or special form.
171 ;; EXPANDER is a function that will be called as a macro-expander to reduce
172 ;; uses of NAME to some other generalized variable."
173 ;; (declare (debug (sexp form)))
174 ;; `(eval-and-compile
175 ;; (if (not (boundp 'gv--macro-environment))
176 ;; (setq gv--macro-environment nil))
177 ;; (push (cons ',name ,expander) gv--macro-environment)))
179 (defun gv--defsetter (name setter do args
&optional vars
)
180 "Helper function used by code generated by `gv-define-setter'.
181 NAME is the name of the getter function.
182 SETTER is a function that generates the code for the setter.
183 NAME accept ARGS as arguments and SETTER accepts (NEWVAL . ARGS).
184 VARS is used internally for recursive calls."
186 (let ((vars (nreverse vars
)))
187 (funcall do
`(,name
,@vars
) (lambda (v) (apply setter v vars
))))
188 ;; FIXME: Often it would be OK to skip this `let', but in general,
189 ;; `do' may have all kinds of side-effects.
190 (macroexp-let2 nil v
(car args
)
191 (gv--defsetter name setter do
(cdr args
) (cons v vars
)))))
194 (defmacro gv-define-setter
(name arglist
&rest body
)
195 "Define a setter method for generalized variable NAME.
196 This macro is an easy-to-use substitute for `gv-define-expander' that works
197 well for simple place forms.
198 Assignments of VAL to (NAME ARGS...) are expanded by binding the argument
199 forms (VAL ARGS...) according to ARGLIST, then executing BODY, which must
200 return a Lisp form that does the assignment.
201 The first arg in ARGLIST (the one that receives VAL) receives an expression
202 which can do arbitrary things, whereas the other arguments are all guaranteed
203 to be pure and copyable. Example use:
204 (gv-define-setter aref (v a i) `(aset ,a ,i ,v))"
205 (declare (indent 2) (debug (&define name sexp body
)))
206 `(gv-define-expander ,name
207 (lambda (do &rest args
)
208 (gv--defsetter ',name
(lambda ,arglist
,@body
) do args
))))
211 (defmacro gv-define-simple-setter
(name setter
&optional fix-return
)
212 "Define a simple setter method for generalized variable NAME.
213 This macro is an easy-to-use substitute for `gv-define-expander' that works
214 well for simple place forms. Assignments of VAL to (NAME ARGS...) are
215 turned into calls of the form (SETTER ARGS... VAL).
217 If FIX-RETURN is non-nil, then SETTER is not assumed to return VAL and
218 instead the assignment is turned into something equivalent to
220 (SETTER ARGS... temp)
222 so as to preserve the semantics of `setf'."
223 (declare (debug (sexp (&or symbolp lambda-expr
) &optional sexp
)))
224 (when (eq 'lambda
(car-safe setter
))
225 (message "Use `gv-define-setter' or name %s's setter function" name
))
226 `(gv-define-setter ,name
(val &rest args
)
228 `(macroexp-let2 nil v val
230 (,',setter
,@args
,v
)
232 ``(,',setter
,@args
,val
))))
234 ;;; Typical operations on generalized variables.
237 (defmacro setf
(&rest args
)
238 "Set each PLACE to the value of its VAL.
239 This is a generalized version of `setq'; the PLACEs may be symbolic
240 references such as (car x) or (aref x i), as well as plain symbols.
241 For example, (setf (cadr x) y) is equivalent to (setcar (cdr x) y).
242 The return value is the last VAL in the list.
244 \(fn PLACE VAL PLACE VAL ...)"
245 (declare (debug (&rest
[gv-place form
])))
246 (if (and args
(null (cddr args
)))
247 (let ((place (pop args
))
249 (gv-letplace (_getter setter
) place
250 (funcall setter val
)))
252 (while args
(push `(setf ,(pop args
) ,(pop args
)) sets
))
253 (cons 'progn
(nreverse sets
)))))
255 ;; (defmacro gv-pushnew! (val place)
256 ;; "Like `gv-push!' but only adds VAL if it's not yet in PLACE.
257 ;; Presence is checked with `member'.
258 ;; The return value is unspecified."
259 ;; (declare (debug (form gv-place)))
260 ;; (macroexp-let2 macroexp-copyable-p v val
261 ;; (gv-letplace (getter setter) place
262 ;; `(if (member ,v ,getter) nil
263 ;; ,(funcall setter `(cons ,v ,getter))))))
265 ;; (defmacro gv-inc! (place &optional val)
266 ;; "Increment PLACE by VAL (default to 1)."
267 ;; (declare (debug (gv-place &optional form)))
268 ;; (gv-letplace (getter setter) place
269 ;; (funcall setter `(+ ,getter ,(or val 1)))))
271 ;; (defmacro gv-dec! (place &optional val)
272 ;; "Decrement PLACE by VAL (default to 1)."
273 ;; (declare (debug (gv-place &optional form)))
274 ;; (gv-letplace (getter setter) place
275 ;; (funcall setter `(- ,getter ,(or val 1)))))
277 ;; For Edebug, the idea is to let Edebug instrument gv-places just like it does
278 ;; for normal expressions, and then give it a gv-expander to DTRT.
279 ;; Maybe this should really be in edebug.el rather than here.
281 ;; Autoload this `put' since a user might use C-u C-M-x on an expression
282 ;; containing a non-trivial `push' even before gv.el was loaded.
284 (put 'gv-place
'edebug-form-spec
'edebug-match-form
)
285 ;; CL did the equivalent of:
286 ;;(gv-define-macroexpand edebug-after (lambda (before index place) place))
288 (put 'edebug-after
'gv-expander
289 (lambda (do before index place
)
290 (gv-letplace (getter setter
) place
291 (funcall do
`(edebug-after ,before
,index
,getter
)
294 ;;; The common generalized variables.
296 (gv-define-simple-setter aref aset
)
297 (gv-define-simple-setter car setcar
)
298 (gv-define-simple-setter cdr setcdr
)
299 ;; FIXME: add compiler-macros for `cXXr' instead!
300 (gv-define-setter caar
(val x
) `(setcar (car ,x
) ,val
))
301 (gv-define-setter cadr
(val x
) `(setcar (cdr ,x
) ,val
))
302 (gv-define-setter cdar
(val x
) `(setcdr (car ,x
) ,val
))
303 (gv-define-setter cddr
(val x
) `(setcdr (cdr ,x
) ,val
))
304 (gv-define-setter elt
(store seq n
)
305 `(if (listp ,seq
) (setcar (nthcdr ,n
,seq
) ,store
)
306 (aset ,seq
,n
,store
)))
307 (gv-define-simple-setter get put
)
308 (gv-define-setter gethash
(val k h
&optional _d
) `(puthash ,k
,val
,h
))
310 ;; (gv-define-expand nth (lambda (idx list) `(car (nthcdr ,idx ,list))))
311 (put 'nth
'gv-expander
312 (lambda (do idx list
)
313 (macroexp-let2 nil c
`(nthcdr ,idx
,list
)
314 (funcall do
`(car ,c
) (lambda (v) `(setcar ,c
,v
))))))
315 (gv-define-simple-setter symbol-function fset
)
316 (gv-define-simple-setter symbol-plist setplist
)
317 (gv-define-simple-setter symbol-value set
)
319 (put 'nthcdr
'gv-expander
321 (macroexp-let2 nil idx n
322 (gv-letplace (getter setter
) place
323 (funcall do
`(nthcdr ,idx
,getter
)
324 (lambda (v) `(if (<= ,idx
0) ,(funcall setter v
)
325 (setcdr (nthcdr (1- ,idx
) ,getter
) ,v
))))))))
327 ;;; Elisp-specific generalized variables.
329 (gv-define-simple-setter default-value set-default
)
330 (gv-define-simple-setter frame-parameter set-frame-parameter
'fix
)
331 (gv-define-simple-setter terminal-parameter set-terminal-parameter
)
332 (gv-define-simple-setter keymap-parent set-keymap-parent
)
333 (gv-define-simple-setter match-data set-match-data
'fix
)
334 (gv-define-simple-setter overlay-get overlay-put
)
335 (gv-define-setter overlay-start
(store ov
)
336 `(progn (move-overlay ,ov
,store
(overlay-end ,ov
)) ,store
))
337 (gv-define-setter overlay-end
(store ov
)
338 `(progn (move-overlay ,ov
(overlay-start ,ov
) ,store
) ,store
))
339 (gv-define-simple-setter process-buffer set-process-buffer
)
340 (gv-define-simple-setter process-filter set-process-filter
)
341 (gv-define-simple-setter process-sentinel set-process-sentinel
)
342 (gv-define-simple-setter process-get process-put
)
343 (gv-define-simple-setter window-parameter set-window-parameter
)
344 (gv-define-setter window-buffer
(v &optional w
)
345 (macroexp-let2 nil v v
346 `(progn (set-window-buffer ,w
,v
) ,v
)))
347 (gv-define-setter window-display-table
(v &optional w
)
348 (macroexp-let2 nil v v
349 `(progn (set-window-display-table ,w
,v
) ,v
)))
350 (gv-define-setter window-dedicated-p
(v &optional w
)
351 `(set-window-dedicated-p ,w
,v
))
352 (gv-define-setter window-hscroll
(v &optional w
) `(set-window-hscroll ,w
,v
))
353 (gv-define-setter window-point
(v &optional w
) `(set-window-point ,w
,v
))
354 (gv-define-setter window-start
(v &optional w
) `(set-window-start ,w
,v
))
356 (gv-define-setter buffer-local-value
(val var buf
)
357 (macroexp-let2 nil v val
358 `(with-current-buffer ,buf
(set (make-local-variable ,var
) ,v
))))
360 (gv-define-expander alist-get
361 (lambda (do key alist
&optional default remove
)
362 (macroexp-let2 macroexp-copyable-p k key
363 (gv-letplace (getter setter
) alist
364 (macroexp-let2 nil p
`(assq ,k
,getter
)
365 (funcall do
(if (null default
) `(cdr ,p
)
366 `(if ,p
(cdr ,p
) ,default
))
368 (macroexp-let2 nil v v
370 `(if ,p
(setcdr ,p
,v
)
372 `(cons (setq ,p
(cons ,k
,v
))
375 ((null remove
) set-exp
)
377 (and (eq (car-safe v
) 'quote
)
378 (eq (car-safe default
) 'quote
)
379 (eql (cadr v
) (cadr default
))))
380 `(if ,p
,(funcall setter
`(delq ,p
,getter
))))
383 ((not (eql ,default
,v
)) ,set-exp
)
385 `(delq ,p
,getter
)))))))))))))))
388 ;;; Some occasionally handy extensions.
390 ;; While several of the "places" below are not terribly useful for direct use,
391 ;; they can show up as the output of the macro expansion of reasonable places,
392 ;; such as struct-accessors.
394 (put 'progn
'gv-expander
395 (lambda (do &rest exps
)
396 (let ((start (butlast exps
))
397 (end (car (last exps
))))
398 (if (null start
) (gv-get end do
)
399 `(progn ,@start
,(gv-get end do
))))))
403 (lambda (do bindings
&rest body
)
406 (gv-get (macroexp-progn body
) do
)))))))
407 (put 'let
'gv-expander
(funcall let-expander
'let
))
408 (put 'let
* 'gv-expander
(funcall let-expander
'let
*)))
410 (put 'if
'gv-expander
411 (lambda (do test then
&rest else
)
412 (if (or (not lexical-binding
) ;The other code requires lexical-binding.
413 (macroexp-small-p (funcall do
'dummy
(lambda (_) 'dummy
))))
414 ;; This duplicates the `do' code, which is a problem if that
415 ;; code is large, but otherwise results in more efficient code.
416 `(if ,test
,(gv-get then do
)
417 ,@(macroexp-unprogn (gv-get (macroexp-progn else
) do
)))
418 (let ((v (make-symbol "v")))
420 gv
`(if ,test
,(gv-letplace (getter setter
) then
421 `(cons (lambda () ,getter
)
422 (lambda (,v
) ,(funcall setter v
))))
423 ,(gv-letplace (getter setter
) (macroexp-progn else
)
424 `(cons (lambda () ,getter
)
425 (lambda (,v
) ,(funcall setter v
)))))
426 (funcall do
`(funcall (car ,gv
))
427 (lambda (v) `(funcall (cdr ,gv
) ,v
))))))))
429 (put 'cond
'gv-expander
430 (lambda (do &rest branches
)
431 (if (or (not lexical-binding
) ;The other code requires lexical-binding.
432 (macroexp-small-p (funcall do
'dummy
(lambda (_) 'dummy
))))
433 ;; This duplicates the `do' code, which is a problem if that
434 ;; code is large, but otherwise results in more efficient code.
436 ,@(mapcar (lambda (branch)
440 (gv-get (macroexp-progn (cdr branch
)) do
)))
441 (gv-get (car branch
) do
)))
443 (let ((v (make-symbol "v")))
451 (gv-letplace (getter setter
)
452 (macroexp-progn (cdr branch
))
453 `(cons (lambda () ,getter
)
454 (lambda (,v
) ,(funcall setter v
))))))
455 (gv-letplace (getter setter
)
457 `(cons (lambda () ,getter
)
458 (lambda (,v
) ,(funcall setter v
))))))
460 (funcall do
`(funcall (car ,gv
))
461 (lambda (v) `(funcall (cdr ,gv
) ,v
))))))))
463 ;;; Even more debatable extensions.
465 (put 'cons
'gv-expander
467 (gv-letplace (agetter asetter
) a
468 (gv-letplace (dgetter dsetter
) d
470 `(cons ,agetter
,dgetter
)
472 ,(funcall asetter
`(car ,v
))
473 ,(funcall dsetter
`(cdr ,v
)))))))))
475 (put 'logand
'gv-expander
476 (lambda (do place
&rest masks
)
477 (gv-letplace (getter setter
) place
478 (macroexp-let2 macroexp-copyable-p
479 mask
(if (cdr masks
) `(logand ,@masks
) (car masks
))
481 do
`(logand ,getter
,mask
)
484 `(logior (logand ,v
,mask
)
485 (logand ,getter
(lognot ,mask
))))))))))
490 (defmacro gv-ref
(place)
491 "Return a reference to PLACE.
492 This is like the `&' operator of the C language.
493 Note: this only works reliably with lexical binding mode, except for very
494 simple PLACEs such as (function-symbol 'foo) which will also work in dynamic
496 (gv-letplace (getter setter
) place
497 `(cons (lambda () ,getter
)
498 (lambda (gv--val) ,(funcall setter
'gv--val
)))))
500 (defsubst gv-deref
(ref)
501 "Dereference REF, returning the referenced value.
502 This is like the `*' operator of the C language.
503 REF must have been previously obtained with `gv-ref'."
505 ;; Don't use `declare' because it seems to introduce circularity problems:
506 ;; Warning: Eager macro-expansion skipped due to cycle:
507 ;; … => (load "gv.el") => (macroexpand-all (defsubst gv-deref …)) => (macroexpand (defun …)) => (load "gv.el")
508 (gv-define-setter gv-deref
(v ref
) `(funcall (cdr ,ref
) ,v
))
510 ;; (defmacro gv-letref (vars place &rest body)
511 ;; (declare (indent 2) (debug (sexp form &rest body)))
512 ;; (require 'cl-lib) ;Can't require cl-lib at top-level for bootstrap reasons!
513 ;; (gv-letplace (getter setter) place
514 ;; `(cl-macrolet ((,(nth 0 vars) () ',getter)
515 ;; (,(nth 1 vars) (v) (funcall ',setter v)))