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

Contents of /src/code/macros.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.5