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

Contents of /src/code/macros.lisp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.70 - (show annotations)
Wed Jun 13 14:43:51 2001 UTC (12 years, 10 months ago) by pw
Branch: MAIN
Changes since 1.69: +4 -2 lines
From Pekka P. Pirinen via c.l.l

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

  ViewVC Help
Powered by ViewVC 1.1.5