/[cmucl]/src/code/macros.lisp
ViewVC logotype

Contents of /src/code/macros.lisp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.29 - (show annotations)
Tue Mar 31 04:52:29 1992 UTC (22 years ago) by wlott
Branch: MAIN
Changes since 1.28: +136 -110 lines
X3J13 cleanup SETF-MULTIPLE-STORE-VARIABLES:

  Extend the semantics of the macros SETF, PSETF, SHIFTF, ROTATEF, and
  ASSERT to allow "places" whose SETF methods have more than one "store
  variable".  In such cases, the macros accept as many values from the
  newvalue form as there are store variables.  As usual, extra values
  are ignored and missing values default to NIL.

  Extend the long form of DEFSETF to allow the specification of more
  than one "store variable", with the obvious semantics.

  Clarify that GET-SETF-METHOD signals an error if there would be more
  than one store-variable.
1 ;;; -*- Log: code.log; Package: Lisp -*-
2 ;;;
3 ;;; **********************************************************************
4 ;;; This code was written as part of the CMU Common Lisp project at
5 ;;; Carnegie Mellon University, and has been placed in the public domain.
6 ;;; If you want to use this code or any part of CMU Common Lisp, please contact
7 ;;; Scott Fahlman or slisp-group@cs.cmu.edu.
8 ;;;
9 (ext:file-comment
10 "$Header: /tiger/var/lib/cvsroots/cmucl/src/code/macros.lisp,v 1.29 1992/03/31 04:52:29 wlott Exp $")
11 ;;;
12 ;;; **********************************************************************
13 ;;;
14 ;;; This file contains the macros that are part of the standard
15 ;;; Spice Lisp environment.
16 ;;;
17 ;;; Written by Scott Fahlman and Rob MacLachlan.
18 ;;; Modified by Bill Chiles to adhere to the wall.
19 ;;;
20 (in-package "LISP")
21 (export '(defvar defparameter defconstant when unless setf
22 defsetf define-setf-method psetf shiftf rotatef push pushnew pop
23 incf decf remf case typecase with-open-file
24 with-open-stream with-input-from-string with-output-to-string
25 locally etypecase ctypecase ecase ccase
26 get-setf-method get-setf-method-multiple-value
27 define-modify-macro destructuring-bind nth-value
28 otherwise)) ; Sacred to CASE and related macros.
29
30 (in-package "EXTENSIONS")
31 (export '(do-anonymous collect iterate))
32
33 (in-package "LISP")
34
35
36 ;;; Parse-Body -- Public
37 ;;;
38 ;;; Parse out declarations and doc strings, *not* expanding macros.
39 ;;; Eventually the environment arg should be flushed, since macros can't expand
40 ;;; into declarations anymore.
41 ;;;
42 (defun parse-body (body environment &optional (doc-string-allowed t))
43 "This function is to parse the declarations and doc-string out of the body of
44 a defun-like form. Body is the list of stuff which is to be parsed.
45 Environment is ignored. If Doc-String-Allowed is true, then a doc string
46 will be parsed out of the body and returned. If it is false then a string
47 will terminate the search for declarations. Three values are returned: the
48 tail of Body after the declarations and doc strings, a list of declare forms,
49 and the doc-string, or NIL if none."
50 (declare (ignore environment))
51 (let ((decls ())
52 (doc nil))
53 (do ((tail body (cdr tail)))
54 ((endp tail)
55 (values tail (nreverse decls) doc))
56 (let ((form (car tail)))
57 (cond ((and (stringp form) (cdr tail))
58 (if doc-string-allowed
59 (setq doc form)
60 (return (values tail (nreverse decls) doc))))
61 ((not (and (consp form) (symbolp (car form))))
62 (return (values tail (nreverse decls) doc)))
63 ((eq (car form) 'declare)
64 (push form decls))
65 (t
66 (return (values tail (nreverse decls) doc))))))))
67
68
69 ;;;; DEFMACRO:
70
71 ;;; Defmacro -- Public
72 ;;;
73 ;;; Parse the definition and make an expander function. The actual
74 ;;; definition is done by %defmacro which we expand into.
75 ;;;
76 (defmacro defmacro (name lambda-list &body body)
77 (let ((whole (gensym "WHOLE-"))
78 (environment (gensym "ENV-")))
79 (multiple-value-bind
80 (body local-decs doc)
81 (parse-defmacro lambda-list whole body name 'defmacro
82 :environment environment)
83 (let ((def `(lambda (,whole ,environment)
84 ,@local-decs
85 (block ,name
86 ,body))))
87 `(c::%defmacro ',name #',def ',lambda-list ,doc)))))
88
89
90 ;;; %Defmacro, %%Defmacro -- Internal
91 ;;;
92 ;;; Defmacro expands into %Defmacro which is a function that is treated
93 ;;; magically the compiler. After the compiler has gotten the information it
94 ;;; wants out of macro definition, it compiles a call to %%Defmacro which
95 ;;; happens at load time. We have a %Defmacro function which just calls
96 ;;; %%Defmacro in order to keep the interpreter happy.
97 ;;;
98 ;;; Eventually %%Defmacro should deal with clearing old compiler information
99 ;;; for the functional value.
100 ;;;
101 (defun c::%defmacro (name definition lambda-list doc)
102 (assert (eval:interpreted-function-p definition))
103 (setf (eval:interpreted-function-name definition)
104 (format nil "DEFMACRO ~S" name))
105 (setf (eval:interpreted-function-arglist definition) lambda-list)
106 (c::%%defmacro name definition doc))
107 ;;;
108 (defun c::%%defmacro (name definition doc)
109 (clear-info function where-from name)
110 (setf (macro-function name) definition)
111 (setf (documentation name 'function) doc)
112 name)
113
114
115 ;;; DEFTYPE is a lot like DEFMACRO.
116
117 (defmacro deftype (name arglist &body body)
118 "Syntax like DEFMACRO, but defines a new type."
119 (unless (symbolp name)
120 (error "~S -- Type name not a symbol." name))
121
122 (let ((whole (gensym "WHOLE-")))
123 (multiple-value-bind (body local-decs doc)
124 (parse-defmacro arglist whole body name 'deftype
125 :default-default ''*)
126 `(eval-when (compile load eval)
127 (%deftype ',name
128 #'(lambda (,whole)
129 ,@local-decs
130 (block ,name ,body))
131 ,@(when doc `(,doc)))))))
132 ;;;
133 (defun %deftype (name expander &optional doc)
134 (ecase (info type kind name)
135 (:primitive
136 (error "Illegal to redefine standard type: ~S." name))
137 (:structure
138 (warn "Redefining structure type ~S with DEFTYPE." name)
139 (c::undefine-structure (info type structure-info name)))
140 ((nil :defined)))
141 (setf (info type kind name) :defined)
142 (setf (info type expander name) expander)
143 (when doc
144 (setf (documentation name 'type) doc))
145 ;; ### Bootstrap hack -- we need to define types before %note-type-defined
146 ;; is defined.
147 (when (fboundp 'c::%note-type-defined)
148 (c::%note-type-defined name))
149 name)
150
151
152 ;;; And so is DEFINE-SETF-METHOD.
153
154 (defparameter defsetf-error-string "Setf expander for ~S cannot be called with ~S args.")
155
156 (defmacro define-setf-method (access-fn lambda-list &body body)
157 "Syntax like DEFMACRO, but creates a Setf-Method generator. The body
158 must be a form that returns the five magical values."
159 (unless (symbolp access-fn)
160 (error "~S -- Access-function name not a symbol in DEFINE-SETF-METHOD."
161 access-fn))
162
163 (let ((whole (gensym "WHOLE-"))
164 (environment (gensym "ENV-")))
165 (multiple-value-bind (body local-decs doc)
166 (parse-defmacro lambda-list whole body access-fn
167 'define-setf-method
168 :environment environment)
169 `(eval-when (load compile eval)
170 (%define-setf-macro
171 ',access-fn
172 #'(lambda (,whole ,environment)
173 ,@local-decs
174 (block ,access-fn ,body))
175 nil
176 ',doc)))))
177
178
179 ;;; %DEFINE-SETF-MACRO -- Internal
180 ;;;
181 ;;; Do stuff for defining a setf macro.
182 ;;;
183 (defun %define-setf-macro (name expander inverse doc)
184 (cond ((not (fboundp `(setf ,name))))
185 ((info function accessor-for name)
186 (warn "Defining setf macro for destruct slot accessor; redefining as ~
187 a normal function:~% ~S"
188 name)
189 (c::define-function-name name))
190 ((not (eq (symbol-package name) (symbol-package 'aref)))
191 (warn "Defining setf macro for ~S, but ~S is fbound."
192 name `(setf ,name))))
193 (when (or inverse (info setf inverse name))
194 (setf (info setf inverse name) inverse))
195 (when (or expander (info setf expander name))
196 (setf (info setf expander name) expander))
197 (when doc
198 (setf (documentation name 'setf) doc))
199 name)
200
201
202 ;;;; Destructuring-bind
203
204 (defmacro destructuring-bind (lambda-list arg-list &rest body)
205 "Bind the variables in LAMBDA-LIST to the contents of ARG-LIST."
206 (let* ((arg-list-name (gensym "ARG-LIST-")))
207 (multiple-value-bind
208 (body local-decls)
209 (parse-defmacro lambda-list arg-list-name body nil 'destructuring-bind
210 :annonymousp t :doc-string-allowed nil)
211 `(let ((,arg-list-name ,arg-list))
212 ,@local-decls
213 ,body))))
214
215
216 ;;;; Defun, Defvar, Defparameter, Defconstant:
217
218 ;;; Defun -- Public
219 ;;;
220 ;;; Very similar to Defmacro, but simpler. We don't have to parse the
221 ;;; lambda-list.
222 ;;;
223 (defmacro defun (&whole source name lambda-list &body (body decls doc))
224 (let ((def `(lambda ,lambda-list
225 ,@decls
226 (block ,(if (and (consp name) (eq (car name) 'setf))
227 (cadr name)
228 name)
229 ,@body))))
230 `(c::%defun ',name #',def ,doc ',source)))
231
232
233 ;;; %Defun, %%Defun -- Internal
234 ;;;
235 ;;; Similar to %Defmacro, ...
236 ;;;
237 (defun c::%%defun (name def doc &optional inline-expansion)
238 (setf (fdefinition name) def)
239 (when doc
240 (if (and (consp name) (eq (first name) 'setf))
241 (setf (documentation (second name) 'setf) doc)
242 (setf (documentation name 'function) doc)))
243 (c::define-function-name name)
244 (when (eq (info function where-from name) :assumed)
245 (setf (info function where-from name) :defined)
246 (when (info function assumed-type name)
247 (setf (info function assumed-type name) nil)))
248 (when (or inline-expansion
249 (info function inline-expansion name))
250 (setf (info function inline-expansion name) inline-expansion))
251 name)
252 ;;;
253 (defun c::%defun (name def doc source)
254 (declare (ignore source))
255 (assert (eval:interpreted-function-p def))
256 (setf (eval:interpreted-function-name def) name)
257 (c::%%defun name def doc))
258
259
260 ;;; DEFCONSTANT -- Public
261 ;;;
262 (defmacro defconstant (var val &optional doc)
263 "For defining global constants at top level. The DEFCONSTANT says that the
264 value is constant and may be compiled into code. If the variable already has
265 a value, and this is not equal to the init, an error is signalled. The third
266 argument is an optional documentation string for the variable."
267 `(c::%defconstant ',var ,val ',doc))
268
269 ;;; %Defconstant, %%Defconstant -- Internal
270 ;;;
271 ;;; Like the other %mumbles except that we currently actually do something
272 ;;; interesting at load time, namely checking if the constant is being
273 ;;; redefined.
274 ;;;
275 (defun c::%defconstant (name value doc)
276 (c::%%defconstant name value doc))
277 ;;;
278 (defun c::%%defconstant (name value doc)
279 (when doc
280 (setf (documentation name 'variable) doc))
281 (when (boundp name)
282 (unless (equalp (symbol-value name) value)
283 (cerror "Go ahead and change the value."
284 "Constant ~S being redefined." name)))
285 (setf (symbol-value name) value)
286 (setf (info variable kind name) :constant)
287 (clear-info variable constant-value name)
288 name)
289
290
291 (defmacro defvar (var &optional (val nil valp) (doc nil docp))
292 "For defining global variables at top level. Declares the variable
293 SPECIAL and, optionally, initializes it. If the variable already has a
294 value, the old value is not clobbered. The third argument is an optional
295 documentation string for the variable."
296 `(progn
297 (proclaim '(special ,var))
298 ,@(when valp
299 `((unless (boundp ',var)
300 (setq ,var ,val))))
301 ,@(when docp
302 `((setf (documentation ',var 'variable) ',doc)))
303 ',var))
304
305 (defmacro defparameter (var val &optional (doc nil docp))
306 "Defines a parameter that is not normally changed by the program,
307 but that may be changed without causing an error. Declares the
308 variable special and sets its value to VAL. The third argument is
309 an optional documentation string for the parameter."
310 `(progn
311 (proclaim '(special ,var))
312 (setq ,var ,val)
313 ,@(when docp
314 `((setf (documentation ',var 'variable) ',doc)))
315 ',var))
316
317
318 ;;;; ASSORTED CONTROL STRUCTURES
319
320
321 (defmacro when (test &body forms)
322 "First arg is a predicate. If it is non-null, the rest of the forms are
323 evaluated as a PROGN."
324 `(cond (,test nil ,@forms)))
325
326 (defmacro unless (test &rest forms)
327 "First arg is a predicate. If it is null, the rest of the forms are
328 evaluated as a PROGN."
329 `(cond ((not ,test) nil ,@forms)))
330
331
332 (defmacro return (&optional (value nil))
333 `(return-from nil ,value))
334
335 (defmacro prog (varlist &body (body decls))
336 `(block nil
337 (let ,varlist
338 ,@decls
339 (tagbody ,@body))))
340
341 (defmacro prog* (varlist &body (body decls))
342 `(block nil
343 (let* ,varlist
344 ,@decls
345 (tagbody ,@body))))
346
347
348 ;;; Prog1, Prog2 -- Public
349 ;;;
350 ;;; These just turn into a Let.
351 ;;;
352 (defmacro prog1 (result &rest body)
353 (let ((n-result (gensym)))
354 `(let ((,n-result ,result))
355 ,@body
356 ,n-result)))
357 ;;;
358 (defmacro prog2 (form1 result &rest body)
359 `(prog1 (progn ,form1 ,result) ,@body))
360
361
362 ;;; And, Or -- Public
363 ;;;
364 ;;; AND and OR are defined in terms of IF.
365 ;;;
366 (defmacro and (&rest forms)
367 (cond ((endp forms) t)
368 ((endp (rest forms)) (first forms))
369 (t
370 `(if ,(first forms)
371 (and ,@(rest forms))
372 nil))))
373 ;;;
374 (defmacro or (&rest forms)
375 (cond ((endp forms) nil)
376 ((endp (rest forms)) (first forms))
377 (t
378 (let ((n-result (gensym)))
379 `(let ((,n-result ,(first forms)))
380 (if ,n-result
381 ,n-result
382 (or ,@(rest forms))))))))
383
384
385 ;;; Cond -- Public
386 ;;;
387 ;;; COND also turns into IF.
388 ;;;
389 (defmacro cond (&rest clauses)
390 (if (endp clauses)
391 nil
392 (let ((clause (first clauses)))
393 (when (atom clause)
394 (error "Cond clause is not a list: ~S." clause))
395 (let ((test (first clause))
396 (forms (rest clause)))
397 (if (endp forms)
398 (let ((n-result (gensym)))
399 `(let ((,n-result ,test))
400 (if ,n-result
401 ,n-result
402 (cond ,@(rest clauses)))))
403 `(if ,test
404 (progn ,@forms)
405 (cond ,@(rest clauses))))))))
406
407
408 ;;;; Multiple value macros:
409
410 ;;; Multiple-Value-XXX -- Public
411 ;;;
412 ;;; All the multiple-value receiving forms are defined in terms of
413 ;;; Multiple-Value-Call.
414 ;;;
415 (defmacro multiple-value-setq (varlist value-form)
416 (unless (and (listp varlist) (every #'symbolp varlist))
417 (error "Varlist is not a list of symbols: ~S." varlist))
418 (let ((temps (mapcar #'(lambda (x) (declare (ignore x)) (gensym)) varlist)))
419 `(multiple-value-bind ,temps ,value-form
420 ,@(mapcar #'(lambda (var temp)
421 `(setq ,var ,temp))
422 varlist temps)
423 ,(car temps))))
424 ;;;
425 (defmacro multiple-value-bind (varlist value-form &body body)
426 (unless (and (listp varlist) (every #'symbolp varlist))
427 (error "Varlist is not a list of symbols: ~S." varlist))
428 (if (= (length varlist) 1)
429 `(let ((,(car varlist) ,value-form))
430 ,@body)
431 (let ((ignore (gensym)))
432 `(multiple-value-call #'(lambda (&optional ,@varlist &rest ,ignore)
433 (declare (ignore ,ignore))
434 ,@body)
435 ,value-form))))
436 ;;;
437 (defmacro multiple-value-list (value-form)
438 `(multiple-value-call #'list ,value-form))
439
440
441 (defmacro nth-value (n form)
442 "Evaluates FORM and returns the Nth value (zero based). This involves no
443 consing when N is a trivial constant integer."
444 (if (integerp n)
445 (let ((dummy-list nil)
446 (wendy (gensym)))
447 ;; We build DUMMY-LIST, a list of variables to bind to useless
448 ;; values, then we explicitly IGNORE those bindings and return
449 ;; WENDY, the only thing we're really interested in right now.
450 (dotimes (i n)
451 (push (gensym) dummy-list))
452 `(multiple-value-bind (,@dummy-list ,wendy)
453 ,form
454 (declare (ignore ,@dummy-list))
455 ,wendy))
456 `(once-only (,n)
457 (case (the fixnum ,n)
458 (0 (nth-value 0 ,form))
459 (1 (nth-value 1 ,form))
460 (2 (nth-value 2 ,form))
461 (T (nth (the fixnum ,n) (multiple-value-list ,form)))))))
462
463
464 ;;;; SETF and friends.
465
466 ;;; Note: The expansions for SETF and friends sometimes create needless
467 ;;; LET-bindings of argument values. The compiler will remove most of
468 ;;; these spurious bindings, so SETF doesn't worry too much about creating
469 ;;; them.
470
471 ;;; The inverse for a generalized-variable reference function is stored in
472 ;;; one of two ways:
473 ;;;
474 ;;; A SETF-INVERSE property corresponds to the short form of DEFSETF. It is
475 ;;; the name of a function takes the same args as the reference form, plus a
476 ;;; new-value arg at the end.
477 ;;;
478 ;;; A SETF-METHOD-EXPANDER property is created by the long form of DEFSETF or
479 ;;; by DEFINE-SETF-METHOD. It is a function that is called on the reference
480 ;;; form and that produces five values: a list of temporary variables, a list
481 ;;; of value forms, a list of the single store-value form, a storing function,
482 ;;; and an accessing function.
483
484 (defun get-setf-method-multiple-value (form &optional environment)
485 "Returns five values needed by the SETF machinery: a list of temporary
486 variables, a list of values with which to fill them, a list of temporaries
487 for the new values, the setting function, and the accessing function."
488 (let (temp)
489 (cond ((symbolp form)
490 (let ((new-var (gensym)))
491 (values nil nil (list new-var) `(setq ,form ,new-var) form)))
492 ;;
493 ;; Local functions inhibit global setf methods...
494 ((and environment
495 (c::leaf-p (cdr (assoc (car form)
496 (c::lexenv-functions environment)))))
497 (get-setf-method-inverse form `(funcall #'(setf ,(car form))) t))
498 ((setq temp (info setf inverse (car form)))
499 (get-setf-method-inverse form `(,temp) nil))
500 ((setq temp (info setf expander (car form)))
501 (funcall temp form environment))
502 ;;
503 ;; If a macro, expand one level and try again. If not, go for the
504 ;; SETF function.
505 (t
506 (multiple-value-bind (res win)
507 (macroexpand-1 form environment)
508 (if win
509 (get-setf-method res environment)
510 (get-setf-method-inverse form
511 `(funcall #'(setf ,(car form)))
512 t)))))))
513
514 (defun get-setf-method-inverse (form inverse setf-function)
515 (let ((new-var (gensym))
516 (vars nil)
517 (vals nil))
518 (dolist (x (cdr form))
519 (push (gensym) vars)
520 (push x vals))
521 (setq vals (nreverse vals))
522 (values vars vals (list new-var)
523 (if setf-function
524 `(,@inverse ,new-var ,@vars)
525 `(,@inverse ,@vars ,new-var))
526 `(,(car form) ,@vars))))
527
528
529 (defun get-setf-method (form &optional environment)
530 "Like Get-Setf-Method-Multiple-Value, but signal an error if there are
531 more than one new-value variables."
532 (multiple-value-bind
533 (temps value-forms store-vars store-form access-form)
534 (get-setf-method-multiple-value form environment)
535 (when (cdr store-vars)
536 (error "GET-SETF-METHOD used for a form with multiple store ~
537 variables:~% ~S" form))
538 (values temps value-forms store-vars store-form access-form)))
539
540
541 (defun defsetter (fn rest)
542 (let ((arglist (car rest))
543 (arglist-var (gensym "ARGS-"))
544 (new-var (car (cadr rest))))
545 (multiple-value-bind
546 (body local-decs doc)
547 (parse-defmacro arglist arglist-var (cddr rest) fn 'defsetf)
548 (values
549 `(lambda (,arglist-var ,new-var)
550 ,@local-decs
551 ,body)
552 doc))))
553
554
555 (defmacro defsetf (access-fn &rest rest)
556 "Associates a SETF update function or macro with the specified access
557 function or macro. The format is complex. See the manual for
558 details."
559 (cond ((not (listp (car rest)))
560 `(eval-when (load compile eval)
561 (%define-setf-macro ',access-fn nil ',(car rest)
562 ,(when (and (car rest) (stringp (cadr rest)))
563 `',(cadr rest)))))
564 ((and (cdr rest) (listp (cadr rest)))
565 (destructuring-bind
566 (lambda-list (&rest store-variables) &body body)
567 rest
568 (let ((arglist-var (gensym "ARGS-"))
569 (access-form-var (gensym "ACCESS-FORM-"))
570 (env-var (gensym "ENVIRONMENT-")))
571 (multiple-value-bind
572 (body local-decs doc)
573 (parse-defmacro `(,lambda-list ,@store-variables)
574 arglist-var body access-fn 'defsetf
575 :annonymousp t)
576 `(eval-when (load compile eval)
577 (%define-setf-macro
578 ',access-fn
579 #'(lambda (,access-form-var ,env-var)
580 (declare (ignore ,env-var))
581 (%defsetf ,access-form-var ,(length store-variables)
582 #'(lambda (,arglist-var)
583 ,@local-decs
584 (block ,access-fn
585 ,body))))
586 nil
587 ',doc))))))
588 (t
589 (error "Ill-formed DEFSETF for ~S." access-fn))))
590
591 (defun %defsetf (orig-access-form num-store-vars expander)
592 (collect ((subform-vars) (store-vars))
593 (let ((subforms (cdr orig-access-form)))
594 (dolist (subform subforms)
595 (declare (ignore subform))
596 (subform-vars (gensym)))
597 (dotimes (i num-store-vars)
598 (store-vars (gensym)))
599 (values (subform-vars)
600 subforms
601 (store-vars)
602 (funcall expander (cons (subform-vars) (store-vars)))
603 `(,(car orig-access-form) ,@(subform-vars))))))
604
605
606 ;;; SETF -- Public
607 ;;;
608 ;;; Except for atoms, we always call GET-SETF-METHOD, since it has some
609 ;;; non-trivial semantics. But when there is a setf inverse, and G-S-M uses
610 ;;; it, then we return a call to the inverse, rather than returning a hairy let
611 ;;; form. This is probably important mainly as a convenince in allowing the
612 ;;; use of setf inverses without the full interpreter.
613 ;;;
614 (defmacro setf (&rest args &environment env)
615 "Takes pairs of arguments like SETQ. The first is a place and the second
616 is the value that is supposed to go into that place. Returns the last
617 value. The place argument may be any of the access forms for which SETF
618 knows a corresponding setting form."
619 (let ((nargs (length args)))
620 (cond
621 ((= nargs 2)
622 (let ((place (first args))
623 (value-form (second args)))
624 (if (atom place)
625 `(setq ,place ,value-form)
626 (multiple-value-bind (dummies vals newval setter getter)
627 (get-setf-method-multiple-value place env)
628 (declare (ignore getter))
629 (let ((inverse (info setf inverse (car place))))
630 (if (and inverse (eq inverse (car setter)))
631 `(,inverse ,@(cdr place) ,value-form)
632 `(let* (,@(mapcar #'list dummies vals))
633 (multiple-value-bind ,newval ,value-form
634 ,setter))))))))
635 ((oddp nargs)
636 (error "Odd number of args to SETF."))
637 (t
638 (do ((a args (cddr a)) (l nil))
639 ((null a) `(progn ,@(nreverse l)))
640 (setq l (cons (list 'setf (car a) (cadr a)) l)))))))
641
642 (defmacro psetf (&rest args &environment env)
643 "This is to SETF as PSETQ is to SETQ. Args are alternating place
644 expressions and values to go into those places. All of the subforms and
645 values are determined, left to right, and only then are the locations
646 updated. Returns NIL."
647 (collect ((let*-bindings) (mv-bindings) (setters))
648 (do ((a args (cddr a)))
649 ((endp a))
650 (if (endp (cdr a))
651 (error "Odd number of args to PSETF."))
652 (multiple-value-bind
653 (dummies vals newval setter getter)
654 (get-setf-method-multiple-value (car a) env)
655 (declare (ignore getter))
656 (let*-bindings (mapcar #'list dummies vals))
657 (mv-bindings (list newval (cadr a)))
658 (setters setter)))
659 (labels ((thunk (let*-bindings mv-bindings)
660 (if let*-bindings
661 `(let* ,(car let*-bindings)
662 (multiple-value-bind ,@(car mv-bindings)
663 ,(thunk (cdr let*-bindings) (cdr mv-bindings))))
664 `(progn ,@(setters) nil))))
665 (thunk (let*-bindings) (mv-bindings)))))
666
667
668 (defmacro shiftf (&rest args &environment env)
669 "One or more SETF-style place expressions, followed by a single
670 value expression. Evaluates all of the expressions in turn, then
671 assigns the value of each expression to the place on its left,
672 returning the value of the leftmost."
673 (if (< (length args) 2)
674 (error "Too few argument forms to a SHIFTF."))
675 (collect ((let*-bindings) (forms))
676 (do ((first t nil)
677 (a args (cdr a))
678 (prev-store-vars)
679 (prev-setter))
680 ((endp (cdr a))
681 (forms `(multiple-value-bind ,prev-store-vars ,(car a)
682 ,prev-setter)))
683 (multiple-value-bind
684 (temps exprs store-vars setter getter)
685 (get-setf-method-multiple-value (car a) env)
686 (loop
687 for temp in temps
688 for expr in exprs
689 do (let*-bindings `(,temp ,expr)))
690 (forms (if first
691 getter
692 `(multiple-value-bind ,prev-store-vars ,getter
693 ,prev-setter)))
694 (setf prev-store-vars store-vars)
695 (setf prev-setter setter)))
696 `(let* ,(let*-bindings)
697 (multiple-value-prog1
698 ,@(forms)))))
699
700 (defmacro rotatef (&rest args &environment env)
701 "Takes any number of SETF-style place expressions. Evaluates all of the
702 expressions in turn, then assigns to each place the value of the form to
703 its right. The rightmost form gets the value of the leftmost.
704 Returns NIL."
705 (when args
706 (collect ((let*-bindings) (mv-bindings) (setters) (getters))
707 (dolist (arg args)
708 (multiple-value-bind
709 (temps subforms store-vars setter getter)
710 (get-setf-method-multiple-value arg env)
711 (loop
712 for temp in temps
713 for subform in subforms
714 do (let*-bindings `(,temp ,subform)))
715 (mv-bindings store-vars)
716 (setters setter)
717 (getters getter)))
718 (setters nil)
719 (getters (car (getters)))
720 (labels ((thunk (mv-bindings getters)
721 (if mv-bindings
722 `((multiple-value-bind
723 ,(car mv-bindings)
724 ,(car getters)
725 ,@(thunk (cdr mv-bindings) (cdr getters))))
726 (setters))))
727 `(let* ,(let*-bindings)
728 ,@(thunk (mv-bindings) (cdr (getters))))))))
729
730
731 (defmacro define-modify-macro (name lambda-list function &optional doc-string)
732 "Creates a new read-modify-write macro like PUSH or INCF."
733 (let ((other-args nil)
734 (rest-arg nil)
735 (env (gensym))
736 (reference (gensym)))
737
738 ;; Parse out the variable names and rest arg from the lambda list.
739 (do ((ll lambda-list (cdr ll))
740 (arg nil))
741 ((null ll))
742 (setq arg (car ll))
743 (cond ((eq arg '&optional))
744 ((eq arg '&rest)
745 (if (symbolp (cadr ll))
746 (setq rest-arg (cadr ll))
747 (error "Non-symbol &rest arg in definition of ~S." name))
748 (if (null (cddr ll))
749 (return nil)
750 (error "Illegal stuff after &rest arg in Define-Modify-Macro.")))
751 ((memq arg '(&key &allow-other-keys &aux))
752 (error "~S not allowed in Define-Modify-Macro lambda list." arg))
753 ((symbolp arg)
754 (push arg other-args))
755 ((and (listp arg) (symbolp (car arg)))
756 (push (car arg) other-args))
757 (t (error "Illegal stuff in lambda list of Define-Modify-Macro."))))
758 (setq other-args (nreverse other-args))
759 `(defmacro ,name (,reference ,@lambda-list &environment ,env)
760 ,doc-string
761 (multiple-value-bind (dummies vals newval setter getter)
762 (get-setf-method ,reference ,env)
763 (do ((d dummies (cdr d))
764 (v vals (cdr v))
765 (let-list nil (cons (list (car d) (car v)) let-list)))
766 ((null d)
767 (push
768 (list (car newval)
769 ,(if rest-arg
770 `(list* ',function getter ,@other-args ,rest-arg)
771 `(list ',function getter ,@other-args)))
772 let-list)
773 `(let* ,(nreverse let-list)
774 ,setter)))))))
775
776
777
778 (defmacro push (obj place &environment env)
779 "Takes an object and a location holding a list. Conses the object onto
780 the list, returning the modified list."
781 (if (symbolp place)
782 `(setq ,place (cons ,obj ,place))
783 (multiple-value-bind (dummies vals newval setter getter)
784 (get-setf-method place env)
785 (do* ((d dummies (cdr d))
786 (v vals (cdr v))
787 (let-list nil))
788 ((null d)
789 (push (list (car newval) `(cons ,obj ,getter))
790 let-list)
791 `(let* ,(nreverse let-list)
792 ,setter))
793 (push (list (car d) (car v)) let-list)))))
794
795
796 (defmacro pushnew (obj place &rest keys &environment env)
797 "Takes an object and a location holding a list. If the object is already
798 in the list, does nothing. Else, conses the object onto the list. Returns
799 NIL. If there is a :TEST keyword, this is used for the comparison."
800 (if (symbolp place)
801 `(setq ,place (adjoin ,obj ,place ,@keys))
802 (multiple-value-bind (dummies vals newval setter getter)
803 (get-setf-method place env)
804 (do* ((d dummies (cdr d))
805 (v vals (cdr v))
806 (let-list nil))
807 ((null d)
808 (push (list (car newval) `(adjoin ,obj ,getter ,@keys))
809 let-list)
810 `(let* ,(nreverse let-list)
811 ,setter))
812 (push (list (car d) (car v)) let-list)))))
813
814
815 (defmacro pop (place &environment env)
816 "The argument is a location holding a list. Pops one item off the front
817 of the list and returns it."
818 (if (symbolp place)
819 `(prog1 (car ,place) (setq ,place (cdr ,place)))
820 (multiple-value-bind (dummies vals newval setter getter)
821 (get-setf-method place env)
822 (do* ((d dummies (cdr d))
823 (v vals (cdr v))
824 (let-list nil))
825 ((null d)
826 (push (list (car newval) getter) let-list)
827 `(let* ,(nreverse let-list)
828 (prog1 (car ,(car newval))
829 (setq ,(car newval) (cdr ,(car newval)))
830 ,setter)))
831 (push (list (car d) (car v)) let-list)))))
832
833
834 (define-modify-macro incf (&optional (delta 1)) +
835 "The first argument is some location holding a number. This number is
836 incremented by the second argument, DELTA, which defaults to 1.")
837
838
839 (define-modify-macro decf (&optional (delta 1)) -
840 "The first argument is some location holding a number. This number is
841 decremented by the second argument, DELTA, which defaults to 1.")
842
843
844 (defmacro remf (place indicator &environment env)
845 "Place may be any place expression acceptable to SETF, and is expected
846 to hold a property list or (). This list is destructively altered to
847 remove the property specified by the indicator. Returns T if such a
848 property was present, NIL if not."
849 (multiple-value-bind (dummies vals newval setter getter)
850 (get-setf-method place env)
851 (do* ((d dummies (cdr d))
852 (v vals (cdr v))
853 (let-list nil)
854 (ind-temp (gensym))
855 (local1 (gensym))
856 (local2 (gensym)))
857 ((null d)
858 (push (list (car newval) getter) let-list)
859 (push (list ind-temp indicator) let-list)
860 `(let* ,(nreverse let-list)
861 (do ((,local1 ,(car newval) (cddr ,local1))
862 (,local2 nil ,local1))
863 ((atom ,local1) nil)
864 (cond ((atom (cdr ,local1))
865 (error "Odd-length property list in REMF."))
866 ((eq (car ,local1) ,ind-temp)
867 (cond (,local2
868 (rplacd (cdr ,local2) (cddr ,local1))
869 (return t))
870 (t (setq ,(car newval) (cddr ,(car newval)))
871 ,setter
872 (return t))))))))
873 (push (list (car d) (car v)) let-list))))
874
875
876 ;;; The built-in DEFSETFs.
877
878 (defsetf car %rplaca)
879 (defsetf cdr %rplacd)
880 (defsetf caar (x) (v) `(%rplaca (car ,x) ,v))
881 (defsetf cadr (x) (v) `(%rplaca (cdr ,x) ,v))
882 (defsetf cdar (x) (v) `(%rplacd (car ,x) ,v))
883 (defsetf cddr (x) (v) `(%rplacd (cdr ,x) ,v))
884 (defsetf caaar (x) (v) `(%rplaca (caar ,x) ,v))
885 (defsetf cadar (x) (v) `(%rplaca (cdar ,x) ,v))
886 (defsetf cdaar (x) (v) `(%rplacd (caar ,x) ,v))
887 (defsetf cddar (x) (v) `(%rplacd (cdar ,x) ,v))
888 (defsetf caadr (x) (v) `(%rplaca (cadr ,x) ,v))
889 (defsetf caddr (x) (v) `(%rplaca (cddr ,x) ,v))
890 (defsetf cdadr (x) (v) `(%rplacd (cadr ,x) ,v))
891 (defsetf cdddr (x) (v) `(%rplacd (cddr ,x) ,v))
892 (defsetf caaaar (x) (v) `(%rplaca (caaar ,x) ,v))
893 (defsetf cadaar (x) (v) `(%rplaca (cdaar ,x) ,v))
894 (defsetf cdaaar (x) (v) `(%rplacd (caaar ,x) ,v))
895 (defsetf cddaar (x) (v) `(%rplacd (cdaar ,x) ,v))
896 (defsetf caadar (x) (v) `(%rplaca (cadar ,x) ,v))
897 (defsetf caddar (x) (v) `(%rplaca (cddar ,x) ,v))
898 (defsetf cdadar (x) (v) `(%rplacd (cadar ,x) ,v))
899 (defsetf cdddar (x) (v) `(%rplacd (cddar ,x) ,v))
900 (defsetf caaadr (x) (v) `(%rplaca (caadr ,x) ,v))
901 (defsetf cadadr (x) (v) `(%rplaca (cdadr ,x) ,v))
902 (defsetf cdaadr (x) (v) `(%rplacd (caadr ,x) ,v))
903 (defsetf cddadr (x) (v) `(%rplacd (cdadr ,x) ,v))
904 (defsetf caaddr (x) (v) `(%rplaca (caddr ,x) ,v))
905 (defsetf cadddr (x) (v) `(%rplaca (cdddr ,x) ,v))
906 (defsetf cdaddr (x) (v) `(%rplacd (caddr ,x) ,v))
907 (defsetf cddddr (x) (v) `(%rplacd (cdddr ,x) ,v))
908
909 (defsetf first %rplaca)
910 (defsetf second (x) (v) `(%rplaca (cdr ,x) ,v))
911 (defsetf third (x) (v) `(%rplaca (cddr ,x) ,v))
912 (defsetf fourth (x) (v) `(%rplaca (cdddr ,x) ,v))
913 (defsetf fifth (x) (v) `(%rplaca (cddddr ,x) ,v))
914 (defsetf sixth (x) (v) `(%rplaca (cdr (cddddr ,x)) ,v))
915 (defsetf seventh (x) (v) `(%rplaca (cddr (cddddr ,x)) ,v))
916 (defsetf eighth (x) (v) `(%rplaca (cdddr (cddddr ,x)) ,v))
917 (defsetf ninth (x) (v) `(%rplaca (cddddr (cddddr ,x)) ,v))
918 (defsetf tenth (x) (v) `(%rplaca (cdr (cddddr (cddddr ,x))) ,v))
919 (defsetf rest %rplacd)
920
921 (defsetf elt %setelt)
922 (defsetf aref %aset)
923 (defsetf row-major-aref %set-row-major-aref)
924 (defsetf svref %svset)
925 (defsetf char %charset)
926 (defsetf bit %bitset)
927 (defsetf schar %scharset)
928 (defsetf sbit %sbitset)
929 (defsetf %array-dimension %set-array-dimension)
930 (defsetf %raw-bits %set-raw-bits)
931 (defsetf symbol-value set)
932 (defsetf symbol-function fset)
933 (defsetf symbol-plist %set-symbol-plist)
934 (defsetf documentation %set-documentation)
935 (defsetf nth %setnth)
936 (defsetf fill-pointer %set-fill-pointer)
937 (defsetf search-list %set-search-list)
938
939 (defsetf sap-ref-8 %set-sap-ref-8)
940 (defsetf signed-sap-ref-8 %set-signed-sap-ref-8)
941 (defsetf sap-ref-16 %set-sap-ref-16)
942 (defsetf signed-sap-ref-16 %set-signed-sap-ref-16)
943 (defsetf sap-ref-32 %set-sap-ref-32)
944 (defsetf signed-sap-ref-32 %set-signed-sap-ref-32)
945 (defsetf sap-ref-sap %set-sap-ref-sap)
946 (defsetf sap-ref-single %set-sap-ref-single)
947 (defsetf sap-ref-double %set-sap-ref-double)
948
949 (define-setf-method getf (place prop &optional default &environment env)
950 (multiple-value-bind (temps values stores set get)
951 (get-setf-method place env)
952 (let ((newval (gensym))
953 (ptemp (gensym))
954 (def-temp (gensym)))
955 (values `(,@temps ,(car stores) ,ptemp ,@(if default `(,def-temp)))
956 `(,@values ,get ,prop ,@(if default `(,default)))
957 `(,newval)
958 `(progn (setq ,(car stores)
959 (%putf ,(car stores) ,ptemp ,newval))
960 ,set
961 ,newval)
962 `(getf ,(car stores) ,ptemp ,@(if default `(,def-temp)))))))
963
964 (define-setf-method get (symbol prop &optional default)
965 "Get turns into %put. Don't put in the default unless it really is supplied
966 and non-nil, so that we can transform into the get instruction whenever
967 possible."
968 (let ((symbol-temp (gensym))
969 (prop-temp (gensym))
970 (def-temp (gensym))
971 (newval (gensym)))
972 (values `(,symbol-temp ,prop-temp ,@(if default `(,def-temp)))
973 `(,symbol ,prop ,@(if default `(,default)))
974 (list newval)
975 `(%put ,symbol-temp ,prop-temp ,newval)
976 `(get ,symbol-temp ,prop-temp ,@(if default `(,def-temp))))))
977
978 (define-setf-method gethash (key hashtable &optional default)
979 (let ((key-temp (gensym))
980 (hashtable-temp (gensym))
981 (default-temp (gensym))
982 (new-value-temp (gensym)))
983 (values
984 `(,key-temp ,hashtable-temp ,@(if default `(,default-temp)))
985 `(,key ,hashtable ,@(if default `(,default)))
986 `(,new-value-temp)
987 `(%puthash ,key-temp ,hashtable-temp ,new-value-temp)
988 `(gethash ,key-temp ,hashtable-temp ,@(if default `(,default-temp))))))
989
990 (defsetf subseq (sequence start &optional (end nil)) (v)
991 `(progn (replace ,sequence ,v :start1 ,start :end1 ,end)
992 ,v))
993
994
995 ;;; Evil hack invented by the gnomes of Vassar Street. The function arg must
996 ;;; be constant. Get a setf method for this function, pretending that the
997 ;;; final (list) arg to apply is just a normal arg. If the setting and access
998 ;;; forms produced in this way reference this arg at the end, then just splice
999 ;;; the APPLY back onto the front and the right thing happens.
1000 ;;;
1001 ;;; We special-case uses functions in the Lisp package so that APPLY AREF works
1002 ;;; even though %ASET takes the new-value last. (there is (SETF AREF) as well
1003 ;;; as a setf method, etc.)
1004 ;;;
1005 (define-setf-method apply (function &rest args &environment env)
1006 (unless (and (listp function)
1007 (= (list-length function) 2)
1008 (eq (first function) 'function)
1009 (symbolp (second function)))
1010 (error "Setf of Apply is only defined for function args like #'symbol."))
1011 (let ((function (second function)))
1012 (multiple-value-bind
1013 (dummies vals newval setter getter)
1014 (if (eq (symbol-package function) (symbol-package 'aref))
1015 (get-setf-method-inverse (cons function args) `((setf ,function)) t)
1016 (get-setf-method (cons function args) env))
1017 (unless (and (eq (car (last args)) (car (last vals)))
1018 (eq (car (last getter)) (car (last dummies)))
1019 (eq (car (last setter)) (car (last dummies))))
1020 (error "Apply of ~S not understood as a location for Setf." function))
1021 (values dummies vals newval
1022 `(apply (function ,(car setter)) ,@(cdr setter))
1023 `(apply (function ,(car getter)) ,@(cdr getter))))))
1024
1025
1026 ;;; Special-case a BYTE bytespec so that the compiler can recognize it.
1027 ;;;
1028 (define-setf-method ldb (bytespec place &environment env)
1029 "The first argument is a byte specifier. The second is any place form
1030 acceptable to SETF. Replaces the specified byte of the number in this
1031 place with bits from the low-order end of the new value."
1032 (multiple-value-bind (dummies vals newval setter getter)
1033 (get-setf-method place env)
1034 (if (and (consp bytespec) (eq (car bytespec) 'byte))
1035 (let ((n-size (gensym))
1036 (n-pos (gensym))
1037 (n-new (gensym)))
1038 (values (list* n-size n-pos dummies)
1039 (list* (second bytespec) (third bytespec) vals)
1040 (list n-new)
1041 `(let ((,(car newval) (dpb ,n-new (byte ,n-size ,n-pos)
1042 ,getter)))
1043 ,setter
1044 ,n-new)
1045 `(ldb (byte ,n-size ,n-pos) ,getter)))
1046 (let ((btemp (gensym))
1047 (gnuval (gensym)))
1048 (values (cons btemp dummies)
1049 (cons bytespec vals)
1050 (list gnuval)
1051 `(let ((,(car newval) (dpb ,gnuval ,btemp ,getter)))
1052 ,setter
1053 ,gnuval)
1054 `(ldb ,btemp ,getter))))))
1055
1056
1057 (define-setf-method mask-field (bytespec place &environment env)
1058 "The first argument is a byte specifier. The second is any place form
1059 acceptable to SETF. Replaces the specified byte of the number in this place
1060 with bits from the corresponding position in the new value."
1061 (multiple-value-bind (dummies vals newval setter getter)
1062 (get-setf-method place env)
1063 (let ((btemp (gensym))
1064 (gnuval (gensym)))
1065 (values (cons btemp dummies)
1066 (cons bytespec vals)
1067 (list gnuval)
1068 `(let ((,(car newval) (deposit-field ,gnuval ,btemp ,getter)))
1069 ,setter
1070 ,gnuval)
1071 `(mask-field ,btemp ,getter)))))
1072
1073
1074 (define-setf-method the (type place &environment env)
1075 (multiple-value-bind (dummies vals newval setter getter)
1076 (get-setf-method place env)
1077 (values dummies
1078 vals
1079 newval
1080 (subst `(the ,type ,(car newval)) (car newval) setter)
1081 `(the ,type ,getter))))
1082
1083
1084 ;;;; CASE, TYPECASE, & Friends.
1085
1086 (eval-when (compile load eval)
1087
1088 ;;; CASE-BODY returns code for all the standard "case" macros. Name is the
1089 ;;; macro name, and keyform is the thing to case on. Multi-p indicates whether
1090 ;;; a branch may fire off a list of keys; otherwise, a key that is a list is
1091 ;;; interpreted in some way as a single key. When multi-p, test is applied to
1092 ;;; the value of keyform and each key for a given branch; otherwise, test is
1093 ;;; applied to the value of keyform and the entire first element, instead of
1094 ;;; each part, of the case branch. When errorp, no t or otherwise branch is
1095 ;;; permitted, and an ERROR form is generated. When proceedp, it is an error
1096 ;;; to omit errorp, and the ERROR form generated is executed within a
1097 ;;; RESTART-CASE allowing keyform to be set and retested.
1098 ;;;
1099 (defun case-body (name keyform cases multi-p test errorp proceedp)
1100 (let ((keyform-value (gensym))
1101 (clauses ())
1102 (keys ()))
1103 (dolist (case cases)
1104 (cond ((atom case)
1105 (error "~S -- Bad clause in ~S." case name))
1106 ((memq (car case) '(t otherwise))
1107 (if errorp
1108 (error "No default clause allowed in ~S: ~S" name case)
1109 (push `(t nil ,@(rest case)) clauses)))
1110 ((and multi-p (listp (first case)))
1111 (setf keys (append (first case) keys))
1112 (push `((or ,@(mapcar #'(lambda (key)
1113 `(,test ,keyform-value ',key))
1114 (first case)))
1115 nil ,@(rest case))
1116 clauses))
1117 (t
1118 (push (first case) keys)
1119 (push `((,test ,keyform-value
1120 ',(first case)) nil ,@(rest case)) clauses))))
1121 (case-body-aux name keyform keyform-value clauses keys errorp proceedp
1122 `(,(if multi-p 'member 'or) ,@keys))))
1123
1124 ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled all the
1125 ;;; cases. Note: it is not necessary that the resulting code signal
1126 ;;; case-failure conditions, but that's what KMP's prototype code did. We call
1127 ;;; CASE-BODY-ERROR, because of how closures are compiled. RESTART-CASE has
1128 ;;; forms with closures that the compiler causes to be generated at the top of
1129 ;;; any function using the case macros, regardless of whether they are needed.
1130 ;;;
1131 (defun case-body-aux (name keyform keyform-value clauses keys
1132 errorp proceedp expected-type)
1133 (if proceedp
1134 (let ((block (gensym))
1135 (again (gensym)))
1136 `(let ((,keyform-value ,keyform))
1137 (block ,block
1138 (tagbody
1139 ,again
1140 (return-from
1141 ,block
1142 (cond ,@(nreverse clauses)
1143 (t
1144 (setf ,keyform-value
1145 (setf ,keyform
1146 (case-body-error
1147 ',name ',keyform ,keyform-value
1148 ',expected-type ',keys)))
1149 (go ,again))))))))
1150 `(let ((,keyform-value ,keyform))
1151 (cond
1152 ,@(nreverse clauses)
1153 ,@(if errorp
1154 `((t (error 'conditions::case-failure
1155 :name ',name
1156 :datum ,keyform-value
1157 :expected-type ',expected-type
1158 :possibilities ',keys))))))))
1159
1160 ); eval-when
1161
1162 (defun case-body-error (name keyform keyform-value expected-type keys)
1163 (restart-case
1164 (error 'conditions::case-failure
1165 :name name
1166 :datum keyform-value
1167 :expected-type expected-type
1168 :possibilities keys)
1169 (store-value (value)
1170 :report (lambda (stream)
1171 (format stream "Supply a new value for ~S." keyform))
1172 :interactive read-evaluated-form
1173 value)))
1174
1175
1176 (defmacro case (keyform &body cases)
1177 "CASE Keyform {({(Key*) | Key} Form*)}*
1178 Evaluates the Forms in the first clause with a Key EQL to the value of
1179 Keyform. If a singleton key is T then the clause is a default clause."
1180 (case-body 'case keyform cases t 'eql nil nil))
1181
1182 (defmacro ccase (keyform &body cases)
1183 "CCASE Keyform {({(Key*) | Key} Form*)}*
1184 Evaluates the Forms in the first clause with a Key EQL to the value of
1185 Keyform. If none of the keys matches then a correctable error is
1186 signalled."
1187 (case-body 'ccase keyform cases t 'eql t t))
1188
1189 (defmacro ecase (keyform &body cases)
1190 "ECASE Keyform {({(Key*) | Key} Form*)}*
1191 Evaluates the Forms in the first clause with a Key EQL to the value of
1192 Keyform. If none of the keys matches then an error is signalled."
1193 (case-body 'ecase keyform cases t 'eql t nil))
1194
1195 (defmacro typecase (keyform &body cases)
1196 "TYPECASE Keyform {(Type Form*)}*
1197 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
1198 is true."
1199 (case-body 'typecase keyform cases nil 'typep nil nil))
1200
1201 (defmacro ctypecase (keyform &body cases)
1202 "CTYPECASE Keyform {(Type Form*)}*
1203 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
1204 is true. If no form is satisfied then a correctable error is signalled."
1205 (case-body 'ctypecase keyform cases nil 'typep t t))
1206
1207 (defmacro etypecase (keyform &body cases)
1208 "ETYPECASE Keyform {(Type Form*)}*
1209 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
1210 is true. If no form is satisfied then an error is signalled."
1211 (case-body 'etypecase keyform cases nil 'typep t nil))
1212
1213
1214 ;;;; ASSERT and CHECK-TYPE.
1215
1216 ;;; ASSERT is written this way, to call ASSERT-ERROR, because of how closures
1217 ;;; are compiled. RESTART-CASE has forms with closures that the compiler
1218 ;;; causes to be generated at the top of any function using ASSERT, regardless
1219 ;;; of whether they are needed.
1220 ;;;
1221 (defmacro assert (test-form &optional places datum &rest arguments)
1222 "Signals an error if the value of test-form is nil. Continuing from this
1223 error using the CONTINUE restart will allow the user to alter the value of
1224 some locations known to SETF, starting over with test-form. Returns nil."
1225 `(loop
1226 (when ,test-form (return nil))
1227 (assert-error ',test-form ',places ,datum ,@arguments)
1228 ,@(mapcar #'(lambda (place)
1229 `(setf ,place (assert-prompt ',place ,place)))
1230 places)))
1231
1232 (defun assert-error (test-form places datum &rest arguments)
1233 (restart-case (if datum
1234 (apply #'error datum arguments)
1235 (simple-assertion-failure test-form))
1236 (continue ()
1237 :report (lambda (stream) (assert-report places stream))
1238 nil)))
1239
1240 (defun simple-assertion-failure (assertion)
1241 (error 'simple-type-error
1242 :datum assertion
1243 :expected-type nil ;this needs some work in next revision. -kmp
1244 :format-string "The assertion ~S failed."
1245 :format-arguments (list assertion)))
1246
1247 (defun assert-report (names stream)
1248 (format stream "Retry assertion")
1249 (if names
1250 (format stream " with new value~P for ~{~S~^, ~}."
1251 (length names) names)
1252 (format stream ".")))
1253
1254 (defun assert-prompt (name value)
1255 (cond ((y-or-n-p "The old value of ~S is ~S.~
1256 ~%Do you want to supply a new value? "
1257 name value)
1258 (format *query-io* "~&Type a form to be evaluated:~%")
1259 (flet ((read-it () (eval (read *query-io*))))
1260 (if (symbolp name) ;help user debug lexical variables
1261 (progv (list name) (list value) (read-it))
1262 (read-it))))
1263 (t value)))
1264
1265
1266 ;;; CHECK-TYPE is written this way, to call CHECK-TYPE-ERROR, because of how
1267 ;;; closures are compiled. RESTART-CASE has forms with closures that the
1268 ;;; compiler causes to be generated at the top of any function using
1269 ;;; CHECK-TYPE, regardless of whether they are needed. Because it would be
1270 ;;; nice if this were cheap to use, and some things can't afford this excessive
1271 ;;; consing (e.g., READ-CHAR), we bend backwards a little.
1272 ;;;
1273
1274 (defmacro check-type (place type &optional type-string)
1275 "Signals an error of type type-error if the contents of place are not of the
1276 specified type. If an error is signaled, this can only return if
1277 STORE-VALUE is invoked. It will store into place and start over."
1278 (let ((place-value (gensym)))
1279 `(loop
1280 (let ((,place-value ,place))
1281 (when (typep ,place-value ',type) (return nil))
1282 (setf ,place
1283 (check-type-error ',place ,place-value ',type ,type-string))))))
1284
1285 (defun check-type-error (place place-value type type-string)
1286 (restart-case (if type-string
1287 (error 'simple-type-error
1288 :datum place :expected-type type
1289 :format-string
1290 "The value of ~S is ~S, which is not ~A."
1291 :format-arguments
1292 (list place place-value type-string))
1293 (error 'simple-type-error
1294 :datum place :expected-type type
1295 :format-string
1296 "The value of ~S is ~S, which is not of type ~S."
1297 :format-arguments
1298 (list place place-value type)))
1299 (store-value (value)
1300 :report (lambda (stream)
1301 (format stream "Supply a new value of ~S."
1302 place))
1303 :interactive read-evaluated-form
1304 value)))
1305
1306 ;;; READ-EVALUATED-FORM is used as the interactive method for restart cases
1307 ;;; setup by the Common Lisp "casing" (e.g., CCASE and CTYPECASE) macros
1308 ;;; and by CHECK-TYPE.
1309 ;;;
1310 (defun read-evaluated-form ()
1311 (format *query-io* "~&Type a form to be evaluated:~%")
1312 (list (eval (read *query-io*))))
1313
1314
1315 ;;;; With-XXX
1316
1317 (defmacro with-open-file ((var &rest open-args) &body (forms decls))
1318 "Bindspec is of the form (Stream File-Name . Options). The file whose
1319 name is File-Name is opened using the Options and bound to the variable
1320 Stream. If the call to open is unsuccessful, the forms are not
1321 evaluated. The Forms are executed, and when they terminate, normally or
1322 otherwise, the file is closed."
1323 (let ((abortp (gensym)))
1324 `(let ((,var (open ,@open-args))
1325 (,abortp t))
1326 ,@decls
1327 (when ,var
1328 (unwind-protect
1329 (multiple-value-prog1
1330 (progn ,@forms)
1331 (setq ,abortp nil))
1332 (close ,var :abort ,abortp))))))
1333
1334
1335
1336 (defmacro with-open-stream ((var stream) &body (forms decls))
1337 "The form stream should evaluate to a stream. VAR is bound
1338 to the stream and the forms are evaluated as an implicit
1339 progn. The stream is closed upon exit."
1340 (let ((abortp (gensym)))
1341 `(let ((,var ,stream)
1342 (,abortp t))
1343 ,@decls
1344 (unwind-protect
1345 (multiple-value-prog1
1346 (progn ,@forms)
1347 (setq ,abortp nil))
1348 (when ,var
1349 (close ,var :abort ,abortp))))))
1350
1351
1352 (defmacro with-input-from-string ((var string &key index start end) &body (forms decls))
1353 "Binds the Var to an input stream that returns characters from String and
1354 executes the body. See manual for details."
1355 `(let ((,var
1356 ,(if end
1357 `(make-string-input-stream ,string ,(or start 0) ,end)
1358 `(make-string-input-stream ,string ,(or start 0)))))
1359 ,@decls
1360 (unwind-protect
1361 (progn ,@forms)
1362 (close ,var)
1363 ,@(if index `((setf ,index (string-input-stream-current ,var)))))))
1364
1365
1366 (defmacro with-output-to-string ((var &optional string) &body (forms decls))
1367 "If *string* is specified, it must be a string with a fill pointer;
1368 the output is incrementally appended to the string (as if by use of
1369 VECTOR-PUSH-EXTEND)."
1370 (if string
1371 `(let ((,var (make-fill-pointer-output-stream ,string)))
1372 ,@decls
1373 (unwind-protect
1374 (progn ,@forms)
1375 (close ,var)))
1376 `(let ((,var (make-string-output-stream)))
1377 ,@decls
1378 (unwind-protect
1379 (progn ,@forms)
1380 (close ,var))
1381 (get-output-stream-string ,var))))
1382
1383
1384 ;;;; Iteration macros:
1385
1386 (defmacro dotimes ((var count &optional (result nil)) &body body)
1387 (cond ((numberp count)
1388 `(do ((,var 0 (1+ ,var)))
1389 ((>= ,var ,count) ,result)
1390 (declare (type unsigned-byte ,var))
1391 ,@body))
1392 (t (let ((v1 (gensym)))
1393 `(do ((,var 0 (1+ ,var)) (,v1 ,count))
1394 ((>= ,var ,v1) ,result)
1395 (declare (type unsigned-byte ,var))
1396 ,@body)))))
1397
1398
1399 ;;; We repeatedly bind the var instead of setting it so that we never give the
1400 ;;; var a random value such as NIL (which might conflict with a declaration).
1401 ;;; ### Might not be legal...
1402 ;;;
1403 (defmacro dolist ((var list &optional (result nil)) &body body)
1404 (let ((n-list (gensym)))
1405 `(do ((,n-list ,list (cdr ,n-list)))
1406 ((endp ,n-list)
1407 (let ((,var nil))
1408 (declare (ignorable ,var))
1409 ,result))
1410 (let ((,var (car ,n-list)))
1411 ,@body))))
1412
1413
1414 (defmacro do (varlist endlist &body (body decls))
1415 "DO ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
1416 Iteration construct. Each Var is initialized in parallel to the value of the
1417 specified Init form. On subsequent iterations, the Vars are assigned the
1418 value of the Step form (if any) in paralell. The Test is evaluated before
1419 each evaluation of the body Forms. When the Test is true, the the Exit-Forms
1420 are evaluated as a PROGN, with the result being the value of the DO. A block
1421 named NIL is established around the entire expansion, allowing RETURN to be
1422 used as an laternate exit mechanism."
1423
1424 (do-do-body varlist endlist body decls 'let 'psetq 'do nil))
1425
1426
1427 (defmacro do* (varlist endlist &body (body decls))
1428 "DO* ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
1429 Iteration construct. Each Var is initialized sequentially (like LET*) to the
1430 value of the specified Init form. On subsequent iterations, the Vars are
1431 sequentially assigned the value of the Step form (if any). The Test is
1432 evaluated before each evaluation of the body Forms. When the Test is true,
1433 the the Exit-Forms are evaluated as a PROGN, with the result being the value
1434 of the DO. A block named NIL is established around the entire expansion,
1435 allowing RETURN to be used as an laternate exit mechanism."
1436 (do-do-body varlist endlist body decls 'let* 'setq 'do* nil))
1437
1438
1439 ;;;; Miscellaneous macros:
1440
1441 (defmacro locally (&rest forms)
1442 "A form providing a container for locally-scoped variables."
1443 `(let () ,@forms))
1444
1445 (defmacro psetq (&rest pairs)
1446 (do ((lets nil)
1447 (setqs nil)
1448 (pairs pairs (cddr pairs)))
1449 ((atom (cdr pairs))
1450 `(let ,(nreverse lets) (setq ,@(nreverse setqs))))
1451 (let ((gen (gensym)))
1452 (push `(,gen ,(cadr pairs)) lets)
1453 (push (car pairs) setqs)
1454 (push gen setqs))))
1455
1456
1457 ;;;; With-Compilation-Unit:
1458
1459 ;;; True if we are within a With-Compilation-Unit form, which normally causes
1460 ;;; nested uses to be NOOPS.
1461 ;;;
1462 (defvar *in-compilation-unit* nil)
1463
1464 ;;; Count of the number of compilation units dynamically enclosed by the
1465 ;;; current active WITH-COMPILATION-UNIT that were unwound out of.
1466 ;;;
1467 (defvar *aborted-compilation-units*)
1468
1469 (declaim (special c::*context-declarations*))
1470
1471
1472 ;;; EVALUATE-DECLARATION-CONTEXT -- Internal
1473 ;;;
1474 ;;; Recursively descend the context form, returning true if this subpart
1475 ;;; matches the specified context.
1476 ;;;
1477 (defun evaluate-declaration-context (context name parent)
1478 (let* ((base (if (and (consp name) (consp (cdr name)))
1479 (cadr name)
1480 name))
1481 (package (and (symbolp base) (symbol-package base))))
1482 (if (atom context)
1483 (multiple-value-bind (ignore how)
1484 (if package
1485 (find-symbol (symbol-name base) package)
1486 (values nil nil))
1487 (declare (ignore ignore))
1488 (case context
1489 (:internal (eq how :internal))
1490 (:external (eq how :external))
1491 (:uninterned (and (symbolp base) (not package)))
1492 (:anonymous (not name))
1493 (:macro (eq parent 'defmacro))
1494 (:function (member parent '(defun labels flet function)))
1495 (:global (member parent '(defun defmacro function)))
1496 (:local (member parent '(labels flet)))
1497 (t
1498 (error "Unknown declaration context: ~S." context))))
1499 (case (first context)
1500 (:or
1501 (loop for x in (rest context)
1502 thereis (evaluate-declaration-context x name parent)))
1503 (:and
1504 (loop for x in (rest context)
1505 always (evaluate-declaration-context x name parent)))
1506 (:not
1507 (evaluate-declaration-context (second context) name parent))
1508 (:member
1509 (member name (rest context) :test #'equal))
1510 (:match
1511 (let ((name (concatenate 'string "$" (string base) "$")))
1512 (loop for x in (rest context)
1513 thereis (search (string x) name))))
1514 (:package
1515 (and package
1516 (loop for x in (rest context)
1517 thereis (eq (find-package (string x)) package))))
1518 (t
1519 (error "Unknown declaration context: ~S." context))))))
1520
1521
1522 ;;; PROCESS-CONTEXT-DECLARATIONS -- Internal
1523 ;;;
1524 ;;; Given a list of context declaration specs, return a new value for
1525 ;;; C::*CONTEXT-DECLARATIONS*.
1526 ;;;
1527 (defun process-context-declarations (decls)
1528 (append
1529 (mapcar
1530 #'(lambda (decl)
1531 (unless (>= (length decl) 2)
1532 (error "Context declaration spec should have context and at ~
1533 least one DECLARE form:~% ~S" decl))
1534 #'(lambda (name parent)
1535 (when (evaluate-declaration-context (first decl) name parent)
1536 (rest decl))))
1537 decls)
1538 c::*context-declarations*))
1539
1540
1541 ;;; With-Compilation-Unit -- Public
1542 ;;;
1543 (defmacro with-compilation-unit (options &body body)
1544 "WITH-COMPILATION-UNIT ({Key Value}*) Form*
1545 This form affects compilations that take place within its dynamic extent. It
1546 is intended to be wrapped around the compilation of all files in the same
1547 system. These keywords are defined:
1548 :OVERRIDE Boolean-Form
1549 One of the effects of this form is to delay undefined warnings
1550 until the end of the form, instead of giving them at the end of each
1551 compilation. If OVERRIDE is NIL (the default), then the outermost
1552 WITH-COMPILATION-UNIT form grabs the undefined warnings. Specifying
1553 OVERRIDE true causes that form to grab any enclosed warnings, even if
1554 it is enclosed by another WITH-COMPILATION-UNIT.
1555 :OPTIMIZE Decl-Form
1556 Decl-Form should evaluate to an OPTIMIZE declaration specifier. This
1557 declaration changes the `global' policy for compilations within the
1558 body.
1559 :OPTIMIZE-INTERFACE Decl-Form
1560 Like OPTIMIZE, except that it specifies the value of the CMU extension
1561 OPTIMIZE-INTERFACE policy (which controls argument type and syntax
1562 checking.)
1563 :CONTEXT-DECLARATIONS List-of-Context-Decls-Form
1564 This is a CMU extension which allows compilation to be controlled
1565 by pattern matching on the context in which a definition appears. The
1566 argument should evaluate to a list of lists of the form:
1567 (Context-Spec Declare-Form+)
1568 In the indicated context, the specified declare forms are inserted at
1569 the head of each definition. The declare forms for all contexts that
1570 match are appended together, with earlier declarations getting
1571 predecence over later ones. A simple example:
1572 :context-declarations
1573 '((:external (declare (optimize (safety 2)))))
1574 This will cause all functions that are named by external symbols to be
1575 compiled with SAFETY 2. The full syntax of context specs is:
1576 :INTERNAL, :EXTERNAL
1577 True if the symbols is internal (external) in its home package.
1578 :UNINTERNED
1579 True if the symbol has no home package.
1580 :ANONYMOUS
1581 True if the function doesn't have any interesting name (not
1582 DEFMACRO, DEFUN, LABELS or FLET).
1583 :MACRO, :FUNCTION
1584 :MACRO is a global (DEFMACRO) macro. :FUNCTION is anything else.
1585 :LOCAL, :GLOBAL
1586 :LOCAL is a LABELS or FLET. :GLOBAL is anything else.
1587 (:OR Context-Spec*)
1588 True in any specified context.
1589 (:AND Context-Spec*)
1590 True only when all specs are true.
1591 (:NOT Context-Spec)
1592 True when the spec is false.
1593 (:MEMBER Name*)
1594 True when the name is one of these names (EQUAL test.)
1595 (:MATCH Pattern*)
1596 True when any of the patterns is a substring of the name. The name
1597 is wrapped with $'s, so $FOO matches names beginning with FOO,
1598 etc."
1599 (let ((override nil)
1600 (optimize nil)
1601 (optimize-interface nil)
1602 (context-declarations nil)
1603 (n-fun (gensym))
1604 (n-abort-p (gensym)))
1605 (when (oddp (length options))
1606 (error "Odd number of key/value pairs: ~S." options))
1607 (do ((opt options (cddr opt)))
1608 ((null opt))
1609 (case (first opt)
1610 (:override
1611 (setq override (second opt)))
1612 (:optimize
1613 (setq optimize (second opt)))
1614 (:optimize-interface
1615 (setq optimize-interface (second opt)))
1616 (:context-declarations
1617 (setq context-declarations (second opt)))
1618 (t
1619 (warn "Ignoring unknown option: ~S." (first opt)))))
1620
1621 `(flet ((,n-fun ()
1622 (let (,@(when optimize
1623 `((c::*default-cookie*
1624 (c::process-optimize-declaration
1625 ,optimize c::*default-cookie*))))
1626 ,@(when optimize-interface
1627 `((c::*default-interface-cookie*
1628 (c::process-optimize-declaration
1629 ,optimize-interface
1630 c::*default-interface-cookie*))))
1631 ,@(when context-declarations
1632 `((c::*context-declarations*
1633 (process-context-declarations
1634 ,context-declarations)))))
1635 ,@body)))
1636 (if (or ,override (not *in-compilation-unit*))
1637 (let ((c::*undefined-warnings* nil)
1638 (c::*compiler-error-count* 0)
1639 (c::*compiler-warning-count* 0)
1640 (c::*compiler-note-count* 0)
1641 (*in-compilation-unit* t)
1642 (*aborted-compilation-units* 0)
1643 (,n-abort-p t))
1644 (handler-bind ((c::parse-unknown-type
1645 #'(lambda (c)
1646 (c::note-undefined-reference
1647 (c::parse-unknown-type-specifier c)
1648 :type))))
1649 (unwind-protect
1650 (multiple-value-prog1
1651 (,n-fun)
1652 (setq ,n-abort-p nil))
1653 (c::print-summary ,n-abort-p *aborted-compilation-units*))))
1654 (let ((,n-abort-p t))
1655 (unwind-protect
1656 (multiple-value-prog1
1657 (,n-fun)
1658 (setq ,n-abort-p nil))
1659 (when ,n-abort-p
1660 (incf *aborted-compilation-units*))))))))

  ViewVC Help
Powered by ViewVC 1.1.5