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

Contents of /src/code/macros.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.5