0.8.7.52:
[sbcl.git] / src / code / early-setf.lisp
1 ;;;; SETF and friends (except for stuff defined with COLLECT, which
2 ;;;; comes later)
3 ;;;;
4 ;;;; Note: The expansions for SETF and friends sometimes create
5 ;;;; needless LET-bindings of argument values. The compiler will
6 ;;;; remove most of these spurious bindings, so SETF doesn't worry too
7 ;;;; much about creating them.
8
9 ;;;; This software is part of the SBCL system. See the README file for
10 ;;;; more information.
11 ;;;;
12 ;;;; This software is derived from the CMU CL system, which was
13 ;;;; written at Carnegie Mellon University and released into the
14 ;;;; public domain. The software is in the public domain and is
15 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
16 ;;;; files for more information.
17
18 (in-package "SB!IMPL")
19
20 ;;; The inverse for a generalized-variable reference function is stored in
21 ;;; one of two ways:
22 ;;;
23 ;;; A SETF inverse property corresponds to the short form of DEFSETF. It is
24 ;;; the name of a function takes the same args as the reference form, plus a
25 ;;; new-value arg at the end.
26 ;;;
27 ;;; A SETF method expander is created by the long form of DEFSETF or
28 ;;; by DEFINE-SETF-EXPANDER. It is a function that is called on the reference
29 ;;; form and that produces five values: a list of temporary variables, a list
30 ;;; of value forms, a list of the single store-value form, a storing function,
31 ;;; and an accessing function.
32 (declaim (ftype (function (t &optional (or null sb!c::lexenv))) sb!xc:get-setf-expansion))
33 (defun sb!xc:get-setf-expansion (form &optional environment)
34   #!+sb-doc
35   "Return five values needed by the SETF machinery: a list of temporary
36    variables, a list of values with which to fill them, a list of temporaries
37    for the new values, the setting function, and the accessing function."
38   (let (temp)
39     (cond ((symbolp form)
40            (multiple-value-bind (expansion expanded)
41                (sb!xc:macroexpand-1 form environment)
42              (if expanded
43                  (sb!xc:get-setf-expansion expansion environment)
44                  (let ((new-var (gensym)))
45                    (values nil nil (list new-var)
46                            `(setq ,form ,new-var) form)))))
47           ;; Local functions inhibit global SETF methods.
48           ((and environment
49                 (let ((name (car form)))
50                   (dolist (x (sb!c::lexenv-funs environment))
51                     (when (and (eq (car x) name)
52                                (not (sb!c::defined-fun-p (cdr x))))
53                       (return t)))))
54            (expand-or-get-setf-inverse form environment))
55           ((setq temp (info :setf :inverse (car form)))
56            (get-setf-method-inverse form `(,temp) nil))
57           ((setq temp (info :setf :expander (car form)))
58            ;; KLUDGE: It may seem as though this should go through
59            ;; *MACROEXPAND-HOOK*, but the ANSI spec seems fairly explicit
60            ;; that *MACROEXPAND-HOOK* is a hook for MACROEXPAND-1, not
61            ;; for macroexpansion in general. -- WHN 19991128
62            (funcall temp
63                     form
64                     ;; As near as I can tell from the ANSI spec,
65                     ;; macroexpanders have a right to expect an actual
66                     ;; lexical environment, not just a NIL which is to
67                     ;; be interpreted as a null lexical environment.
68                     ;; -- WHN 19991128
69                     (coerce-to-lexenv environment)))
70           (t
71            (expand-or-get-setf-inverse form environment)))))
72
73 ;;; GET-SETF-METHOD existed in pre-ANSI Common Lisp, and various code inherited
74 ;;; from CMU CL uses it repeatedly, so rather than rewrite a lot of code to not
75 ;;; use it, we just define it in terms of ANSI's GET-SETF-EXPANSION (or
76 ;;; actually, the cross-compiler version of that, i.e.
77 ;;; SB!XC:GET-SETF-EXPANSION).
78 (declaim (ftype (function (t &optional (or null sb!c::lexenv))) get-setf-method))
79 (defun get-setf-method (form &optional environment)
80   #!+sb-doc
81   "This is a specialized-for-one-value version of GET-SETF-EXPANSION (and
82 a relic from pre-ANSI Common Lisp). Portable ANSI code should use
83 GET-SETF-EXPANSION directly."
84   (multiple-value-bind (temps value-forms store-vars store-form access-form)
85       (sb!xc:get-setf-expansion form environment)
86     (when (cdr store-vars)
87       (error "GET-SETF-METHOD used for a form with multiple store ~
88               variables:~%  ~S"
89              form))
90     (values temps value-forms store-vars store-form access-form)))
91
92 ;;; If a macro, expand one level and try again. If not, go for the
93 ;;; SETF function.
94 (declaim (ftype (function (t (or null sb!c::lexenv)))
95                 expand-or-get-setf-inverse))
96 (defun expand-or-get-setf-inverse (form environment)
97   (multiple-value-bind (expansion expanded)
98       (sb!xc:macroexpand-1 form environment)
99     (if expanded
100         (sb!xc:get-setf-expansion expansion environment)
101         (get-setf-method-inverse form
102                                  `(funcall #'(setf ,(car form)))
103                                  t))))
104
105 (defun get-setf-method-inverse (form inverse setf-fun)
106   (let ((new-var (gensym))
107         (vars nil)
108         (vals nil))
109     (dolist (x (cdr form))
110       (push (gensym) vars)
111       (push x vals))
112     (setq vals (nreverse vals))
113     (values vars vals (list new-var)
114             (if setf-fun
115                 `(,@inverse ,new-var ,@vars)
116                 `(,@inverse ,@vars ,new-var))
117             `(,(car form) ,@vars))))
118 \f
119 ;;;; SETF itself
120
121 ;;; Except for atoms, we always call GET-SETF-EXPANSION, since it has
122 ;;; some non-trivial semantics. But when there is a setf inverse, and
123 ;;; G-S-E uses it, then we return a call to the inverse, rather than
124 ;;; returning a hairy LET form. This is probably important mainly as a
125 ;;; convenience in allowing the use of SETF inverses without the full
126 ;;; interpreter.
127 (defmacro-mundanely setf (&rest args &environment env)
128   #!+sb-doc
129   "Takes pairs of arguments like SETQ. The first is a place and the second
130   is the value that is supposed to go into that place. Returns the last
131   value. The place argument may be any of the access forms for which SETF
132   knows a corresponding setting form."
133   (let ((nargs (length args)))
134     (cond
135      ((= nargs 2)
136       (let ((place (first args))
137             (value-form (second args)))
138         (if (atom place)
139           `(setq ,place ,value-form)
140           (multiple-value-bind (dummies vals newval setter getter)
141               (sb!xc:get-setf-expansion place env)
142             (declare (ignore getter))
143             (let ((inverse (info :setf :inverse (car place))))
144               (if (and inverse (eq inverse (car setter)))
145                 `(,inverse ,@(cdr place) ,value-form)
146                 `(let* (,@(mapcar #'list dummies vals))
147                    (multiple-value-bind ,newval ,value-form
148                      ,setter))))))))
149      ((oddp nargs)
150       (error "odd number of args to SETF"))
151      (t
152       (do ((a args (cddr a))
153            (reversed-setfs nil))
154           ((null a)
155            `(progn ,@(nreverse reversed-setfs)))
156         (push (list 'setf (car a) (cadr a)) reversed-setfs))))))
157 \f
158 ;;;; various SETF-related macros
159
160 (defmacro-mundanely shiftf (&whole form &rest args &environment env)
161   #!+sb-doc
162   "One or more SETF-style place expressions, followed by a single
163    value expression. Evaluates all of the expressions in turn, then
164    assigns the value of each expression to the place on its left,
165    returning the value of the leftmost."
166   (when (< (length args) 2)
167     (error "~S called with too few arguments: ~S" 'shiftf form))
168   (let ((resultvar (gensym)))
169     (do ((arglist args (cdr arglist))
170          (bindlist nil)
171          (storelist nil)
172          (lastvar resultvar))
173         ((atom (cdr arglist))
174          (push `(,lastvar ,(first arglist)) bindlist)
175          `(let* ,(nreverse bindlist) ,@(nreverse storelist) ,resultvar))
176       (multiple-value-bind (sm1 sm2 sm3 sm4 sm5)
177           (get-setf-method (first arglist) env)
178         (mapc (lambda (var val)
179                 (push `(,var ,val) bindlist))
180               sm1
181               sm2)
182         (push `(,lastvar ,sm5) bindlist)
183         (push sm4 storelist)
184         (setq lastvar (first sm3))))))
185
186 (defmacro-mundanely push (obj place &environment env)
187   #!+sb-doc
188   "Takes an object and a location holding a list. Conses the object onto
189   the list, returning the modified list. OBJ is evaluated before PLACE."
190   (multiple-value-bind (dummies vals newval setter getter)
191       (get-setf-method place env)
192     (let ((g (gensym)))
193       `(let* ((,g ,obj)
194               ,@(mapcar #'list dummies vals)
195               (,(car newval) (cons ,g ,getter)))
196          ,setter))))
197
198 (defmacro-mundanely pushnew (obj place &rest keys &environment env)
199   #!+sb-doc
200   "Takes an object and a location holding a list. If the object is
201   already in the list, does nothing; otherwise, conses the object onto
202   the list. Returns the modified list. If there is a :TEST keyword, this
203   is used for the comparison."
204   (multiple-value-bind (dummies vals newval setter getter)
205       (get-setf-method place env)
206     (let ((g (gensym)))
207       `(let* ((,g ,obj)
208               ,@(mapcar #'list dummies vals)
209               (,(car newval) (adjoin ,g ,getter ,@keys)))
210          ,setter))))
211
212 (defmacro-mundanely pop (place &environment env)
213   #!+sb-doc
214   "The argument is a location holding a list. Pops one item off the front
215   of the list and returns it."
216   (multiple-value-bind (dummies vals newval setter getter)
217       (get-setf-method place env)
218     (do* ((d dummies (cdr d))
219           (v vals (cdr v))
220           (let-list nil))
221          ((null d)
222           (push (list (car newval) getter) let-list)
223           `(let* ,(nreverse let-list)
224              (prog1 (car ,(car newval))
225                (setq ,(car newval) (cdr ,(car newval)))
226                ,setter)))
227       (push (list (car d) (car v)) let-list))))
228
229 (defmacro-mundanely remf (place indicator &environment env)
230   #!+sb-doc
231   "Place may be any place expression acceptable to SETF, and is expected
232   to hold a property list or (). This list is destructively altered to
233   remove the property specified by the indicator. Returns T if such a
234   property was present, NIL if not."
235   (multiple-value-bind (dummies vals newval setter getter)
236       (get-setf-method place env)
237     (do* ((d dummies (cdr d))
238           (v vals (cdr v))
239           (let-list nil)
240           (ind-temp (gensym))
241           (local1 (gensym))
242           (local2 (gensym)))
243          ((null d)
244           (push (list (car newval) getter) let-list)
245           (push (list ind-temp indicator) let-list)
246           `(let* ,(nreverse let-list)
247              (do ((,local1 ,(car newval) (cddr ,local1))
248                   (,local2 nil ,local1))
249                  ((atom ,local1) nil)
250                (cond ((atom (cdr ,local1))
251                       (error "Odd-length property list in REMF."))
252                      ((eq (car ,local1) ,ind-temp)
253                       (cond (,local2
254                              (rplacd (cdr ,local2) (cddr ,local1))
255                              (return t))
256                             (t (setq ,(car newval) (cddr ,(car newval)))
257                                ,setter
258                                (return t))))))))
259       (push (list (car d) (car v)) let-list))))
260 \f
261 ;;;; DEFINE-MODIFY-MACRO stuff
262
263 (def!macro sb!xc:define-modify-macro (name lambda-list function &optional doc-string)
264   #!+sb-doc
265   "Creates a new read-modify-write macro like PUSH or INCF."
266   (let ((other-args nil)
267         (rest-arg nil)
268         (env (gensym))
269         (reference (gensym)))
270     ;; Parse out the variable names and &REST arg from the lambda list.
271     (do ((ll lambda-list (cdr ll))
272          (arg nil))
273         ((null ll))
274       (setq arg (car ll))
275       (cond ((eq arg '&optional))
276             ((eq arg '&rest)
277              (if (symbolp (cadr ll))
278                (setq rest-arg (cadr ll))
279                (error "Non-symbol &REST argument in definition of ~S." name))
280              (if (null (cddr ll))
281                (return nil)
282                (error "Illegal stuff after &REST argument.")))
283             ((memq arg '(&key &allow-other-keys &aux))
284              (error "~S not allowed in DEFINE-MODIFY-MACRO lambda list." arg))
285             ((symbolp arg)
286              (push arg other-args))
287             ((and (listp arg) (symbolp (car arg)))
288              (push (car arg) other-args))
289             (t (error "Illegal stuff in lambda list."))))
290     (setq other-args (nreverse other-args))
291     `(#-sb-xc-host sb!xc:defmacro
292       #+sb-xc-host defmacro-mundanely
293          ,name (,reference ,@lambda-list &environment ,env)
294        ,doc-string
295        (multiple-value-bind (dummies vals newval setter getter)
296            (get-setf-method ,reference ,env)
297          (do ((d dummies (cdr d))
298               (v vals (cdr v))
299               (let-list nil (cons (list (car d) (car v)) let-list)))
300              ((null d)
301               (push (list (car newval)
302                           ,(if rest-arg
303                              `(list* ',function getter ,@other-args ,rest-arg)
304                              `(list ',function getter ,@other-args)))
305                     let-list)
306               `(let* ,(nreverse let-list)
307                  ,setter)))))))
308
309 (sb!xc:define-modify-macro incf (&optional (delta 1)) +
310   #!+sb-doc
311   "The first argument is some location holding a number. This number is
312   incremented by the second argument, DELTA, which defaults to 1.")
313
314 (sb!xc:define-modify-macro decf (&optional (delta 1)) -
315   #!+sb-doc
316   "The first argument is some location holding a number. This number is
317   decremented by the second argument, DELTA, which defaults to 1.")
318 \f
319 ;;;; DEFSETF
320
321 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
322   ;;; Assign SETF macro information for NAME, making all appropriate checks.
323   (defun assign-setf-macro (name expander inverse doc)
324     (cond ((gethash name sb!c:*setf-assumed-fboundp*)
325            (warn
326             "defining setf macro for ~S when ~S was previously ~
327              treated as a function"
328             name
329             `(setf ,name)))
330           ((not (fboundp `(setf ,name)))
331            ;; All is well, we don't need any warnings.
332            (values))
333           ((not (eq (symbol-package name) (symbol-package 'aref)))
334            (style-warn "defining setf macro for ~S when ~S is fbound"
335                        name `(setf ,name))))
336     (remhash name sb!c:*setf-assumed-fboundp*)
337     ;; FIXME: It's probably possible to join these checks into one form which
338     ;; is appropriate both on the cross-compilation host and on the target.
339     (when (or inverse (info :setf :inverse name))
340       (setf (info :setf :inverse name) inverse))
341     (when (or expander (info :setf :expander name))
342       (setf (info :setf :expander name) expander))
343     (when doc
344       (setf (fdocumentation name 'setf) doc))
345     name))
346
347 (def!macro sb!xc:defsetf (access-fn &rest rest)
348   #!+sb-doc
349   "Associates a SETF update function or macro with the specified access
350   function or macro. The format is complex. See the manual for details."
351   (cond ((not (listp (car rest)))
352          `(eval-when (:load-toplevel :compile-toplevel :execute)
353             (assign-setf-macro ',access-fn
354                                nil
355                                ',(car rest)
356                                 ,(when (and (car rest) (stringp (cadr rest)))
357                                    `',(cadr rest)))))
358         ((and (cdr rest) (listp (cadr rest)))
359          (destructuring-bind
360              (lambda-list (&rest store-variables) &body body)
361              rest
362            (let ((arglist-var (gensym "ARGS-"))
363                  (access-form-var (gensym "ACCESS-FORM-"))
364                  (env-var (gensym "ENVIRONMENT-")))
365              (multiple-value-bind (body local-decs doc)
366                  (parse-defmacro `(,lambda-list ,@store-variables)
367                                  arglist-var body access-fn 'defsetf
368                                  :anonymousp t)
369                `(eval-when (:compile-toplevel :load-toplevel :execute)
370                   (assign-setf-macro
371                    ',access-fn
372                    (lambda (,access-form-var ,env-var)
373                      (declare (ignore ,env-var))
374                      (%defsetf ,access-form-var ,(length store-variables)
375                                (lambda (,arglist-var)
376                                  ,@local-decs
377                                  ,body)))
378                    nil
379                    ',doc))))))
380         (t
381          (error "ill-formed DEFSETF for ~S" access-fn))))
382
383 (defun %defsetf (orig-access-form num-store-vars expander)
384   (declare (type function expander))
385   (let (subforms
386         subform-vars
387         subform-exprs
388         store-vars)
389     (dolist (subform (cdr orig-access-form))
390       (if (constantp subform)
391         (push subform subforms)
392         (let ((var (gensym)))
393           (push var subforms)
394           (push var subform-vars)
395           (push subform subform-exprs))))
396     (dotimes (i num-store-vars)
397       (push (gensym) store-vars))
398     (let ((r-subforms (nreverse subforms))
399           (r-subform-vars (nreverse subform-vars))
400           (r-subform-exprs (nreverse subform-exprs))
401           (r-store-vars (nreverse store-vars)))
402       (values r-subform-vars
403               r-subform-exprs
404               r-store-vars
405               (funcall expander (cons r-subforms r-store-vars))
406               `(,(car orig-access-form) ,@r-subforms)))))
407 \f
408 ;;;; DEFMACRO DEFINE-SETF-EXPANDER and various DEFINE-SETF-EXPANDERs
409
410 ;;; DEFINE-SETF-EXPANDER is a lot like DEFMACRO.
411 (def!macro sb!xc:define-setf-expander (access-fn lambda-list &body body)
412   #!+sb-doc
413   "Syntax like DEFMACRO, but creates a Setf-Method generator. The body
414   must be a form that returns the five magical values."
415   (unless (symbolp access-fn)
416     (error "DEFINE-SETF-EXPANDER access-function name ~S is not a symbol."
417            access-fn))
418   (with-unique-names (whole environment)
419     (multiple-value-bind (body local-decs doc)
420         (parse-defmacro lambda-list whole body access-fn
421                         'sb!xc:define-setf-expander
422                         :environment environment)
423       `(eval-when (:compile-toplevel :load-toplevel :execute)
424          (assign-setf-macro ',access-fn
425                             (lambda (,whole ,environment)
426                               ,@local-decs
427                               ,body)
428                             nil
429                             ',doc)))))
430
431 (sb!xc:define-setf-expander getf (place prop
432                                   &optional default
433                                   &environment env)
434   (declare (type sb!c::lexenv env))
435   (multiple-value-bind (temps values stores set get)
436       (get-setf-method place env)
437     (let ((newval (gensym))
438           (ptemp (gensym))
439           (def-temp (if default (gensym))))
440       (values `(,@temps ,ptemp ,@(if default `(,def-temp)))
441               `(,@values ,prop ,@(if default `(,default)))
442               `(,newval)
443               `(let ((,(car stores) (%putf ,get ,ptemp ,newval)))
444                  ,set
445                  ,newval)
446               `(getf ,get ,ptemp ,@(if default `(,def-temp)))))))
447
448 (sb!xc:define-setf-expander get (symbol prop &optional default)
449   (let ((symbol-temp (gensym))
450         (prop-temp (gensym))
451         (def-temp (gensym))
452         (newval (gensym)))
453     (values `(,symbol-temp ,prop-temp ,@(if default `(,def-temp)))
454             `(,symbol ,prop ,@(if default `(,default)))
455             (list newval)
456             `(%put ,symbol-temp ,prop-temp ,newval)
457             `(get ,symbol-temp ,prop-temp ,@(if default `(,def-temp))))))
458
459 (sb!xc:define-setf-expander gethash (key hashtable &optional default)
460   (let ((key-temp (gensym))
461         (hashtable-temp (gensym))
462         (default-temp (gensym))
463         (new-value-temp (gensym)))
464     (values
465      `(,key-temp ,hashtable-temp ,@(if default `(,default-temp)))
466      `(,key ,hashtable ,@(if default `(,default)))
467      `(,new-value-temp)
468      `(%puthash ,key-temp ,hashtable-temp ,new-value-temp)
469      `(gethash ,key-temp ,hashtable-temp ,@(if default `(,default-temp))))))
470
471 (sb!xc:define-setf-expander logbitp (index int &environment env)
472   (declare (type sb!c::lexenv env))
473   (multiple-value-bind (temps vals stores store-form access-form)
474       (get-setf-method int env)
475     (let ((ind (gensym))
476           (store (gensym))
477           (stemp (first stores)))
478       (values `(,ind ,@temps)
479               `(,index
480                 ,@vals)
481               (list store)
482               `(let ((,stemp
483                       (dpb (if ,store 1 0) (byte 1 ,ind) ,access-form)))
484                  ,store-form
485                  ,store)
486               `(logbitp ,ind ,access-form)))))
487
488 ;;; CMU CL had a comment here that:
489 ;;;   Evil hack invented by the gnomes of Vassar Street (though not as evil as
490 ;;;   it used to be.)  The function arg must be constant, and is converted to
491 ;;;   an APPLY of the SETF function, which ought to exist.
492 ;;;
493 ;;; It may not be clear (wasn't to me..) that this is a standard thing, but See
494 ;;; "5.1.2.5 APPLY Forms as Places" in the ANSI spec. I haven't actually
495 ;;; verified that this code has any correspondence to that code, but at least
496 ;;; ANSI has some place for SETF APPLY. -- WHN 19990604
497 (sb!xc:define-setf-expander apply (functionoid &rest args)
498   (unless (and (listp functionoid)
499                (= (length functionoid) 2)
500                (eq (first functionoid) 'function)
501                (symbolp (second functionoid)))
502     (error "SETF of APPLY is only defined for function args like #'SYMBOL."))
503   (let ((function (second functionoid))
504         (new-var (gensym))
505         (vars (make-gensym-list (length args))))
506     (values vars args (list new-var)
507             `(apply #'(setf ,function) ,new-var ,@vars)
508             `(apply #',function ,@vars))))
509
510 ;;; Special-case a BYTE bytespec so that the compiler can recognize it.
511 (sb!xc:define-setf-expander ldb (bytespec place &environment env)
512   #!+sb-doc
513   "The first argument is a byte specifier. The second is any place form
514   acceptable to SETF. Replace the specified byte of the number in this
515   place with bits from the low-order end of the new value."
516   (declare (type sb!c::lexenv env))
517   (multiple-value-bind (dummies vals newval setter getter)
518       (get-setf-method place env)
519     (if (and (consp bytespec) (eq (car bytespec) 'byte))
520         (let ((n-size (gensym))
521               (n-pos (gensym))
522               (n-new (gensym)))
523           (values (list* n-size n-pos dummies)
524                   (list* (second bytespec) (third bytespec) vals)
525                   (list n-new)
526                   `(let ((,(car newval) (dpb ,n-new (byte ,n-size ,n-pos)
527                                              ,getter)))
528                      ,setter
529                      ,n-new)
530                   `(ldb (byte ,n-size ,n-pos) ,getter)))
531         (let ((btemp (gensym))
532               (gnuval (gensym)))
533           (values (cons btemp dummies)
534                   (cons bytespec vals)
535                   (list gnuval)
536                   `(let ((,(car newval) (dpb ,gnuval ,btemp ,getter)))
537                      ,setter
538                      ,gnuval)
539                   `(ldb ,btemp ,getter))))))
540
541 (sb!xc:define-setf-expander mask-field (bytespec place &environment env)
542   #!+sb-doc
543   "The first argument is a byte specifier. The second is any place form
544   acceptable to SETF. Replaces the specified byte of the number in this place
545   with bits from the corresponding position in the new value."
546   (declare (type sb!c::lexenv env))
547   (multiple-value-bind (dummies vals newval setter getter)
548       (get-setf-method place env)
549     (let ((btemp (gensym))
550           (gnuval (gensym)))
551       (values (cons btemp dummies)
552               (cons bytespec vals)
553               (list gnuval)
554               `(let ((,(car newval) (deposit-field ,gnuval ,btemp ,getter)))
555                  ,setter
556                  ,gnuval)
557               `(mask-field ,btemp ,getter)))))
558
559 (sb!xc:define-setf-expander the (type place &environment env)
560   (declare (type sb!c::lexenv env))
561   (multiple-value-bind (dummies vals newval setter getter)
562       (get-setf-method place env)
563     (values dummies
564               vals
565               newval
566               (subst `(the ,type ,(car newval)) (car newval) setter)
567               `(the ,type ,getter))))