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

Contents of /src/code/macros.lisp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.55 - (show annotations)
Tue Jun 16 06:37:15 1998 UTC (15 years, 10 months ago) by dtc
Branch: MAIN
Changes since 1.54: +2 -2 lines
PSETQ should return nil. Fix from Peter VanEynde.
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.55 1998/06/16 06:37:15 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 ;;; 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 (defmacro shiftf (&whole form &rest args &environment env)
730 "One or more SETF-style place expressions, followed by a single
731 value expression. Evaluates all of the expressions in turn, then
732 assigns the value of each expression to the place on its left,
733 returning the value of the leftmost."
734 (when (< (length args) 2)
735 (error "~S called with too few arguments: ~S" 'shiftf form))
736 (let ((resultvar (gensym)))
737 (do ((arglist args (cdr arglist))
738 (bindlist nil)
739 (storelist nil)
740 (lastvar resultvar))
741 ((atom (cdr arglist))
742 (push `(,lastvar ,(first arglist)) bindlist)
743 `(LET* ,(nreverse bindlist) ,@(nreverse storelist) ,resultvar))
744 (multiple-value-bind (SM1 SM2 SM3 SM4 SM5)
745 (get-setf-method (first arglist) env)
746 (mapc #'(lambda (var val) (push `(,var ,val) bindlist)) SM1 SM2)
747 (push `(,lastvar ,SM5) bindlist)
748 (push SM4 storelist)
749 (setq lastvar (first SM3))))))
750
751 (defmacro rotatef (&rest args &environment env)
752 "Takes any number of SETF-style place expressions. Evaluates all of the
753 expressions in turn, then assigns to each place the value of the form to
754 its right. The rightmost form gets the value of the leftmost.
755 Returns NIL."
756 (when args
757 (collect ((let*-bindings) (mv-bindings) (setters) (getters))
758 (dolist (arg args)
759 (multiple-value-bind
760 (temps subforms store-vars setter getter)
761 (get-setf-expansion arg env)
762 (loop
763 for temp in temps
764 for subform in subforms
765 do (let*-bindings `(,temp ,subform)))
766 (mv-bindings store-vars)
767 (setters setter)
768 (getters getter)))
769 (setters nil)
770 (getters (car (getters)))
771 (labels ((thunk (mv-bindings getters)
772 (if mv-bindings
773 `((multiple-value-bind
774 ,(car mv-bindings)
775 ,(car getters)
776 ,@(thunk (cdr mv-bindings) (cdr getters))))
777 (setters))))
778 `(let* ,(let*-bindings)
779 ,@(thunk (mv-bindings) (cdr (getters))))))))
780
781
782 (defmacro define-modify-macro (name lambda-list function &optional doc-string)
783 "Creates a new read-modify-write macro like PUSH or INCF."
784 (let ((other-args nil)
785 (rest-arg nil)
786 (env (gensym))
787 (reference (gensym)))
788
789 ;; Parse out the variable names and rest arg from the lambda list.
790 (do ((ll lambda-list (cdr ll))
791 (arg nil))
792 ((null ll))
793 (setq arg (car ll))
794 (cond ((eq arg '&optional))
795 ((eq arg '&rest)
796 (if (symbolp (cadr ll))
797 (setq rest-arg (cadr ll))
798 (error "Non-symbol &rest arg in definition of ~S." name))
799 (if (null (cddr ll))
800 (return nil)
801 (error "Illegal stuff after &rest arg in Define-Modify-Macro.")))
802 ((memq arg '(&key &allow-other-keys &aux))
803 (error "~S not allowed in Define-Modify-Macro lambda list." arg))
804 ((symbolp arg)
805 (push arg other-args))
806 ((and (listp arg) (symbolp (car arg)))
807 (push (car arg) other-args))
808 (t (error "Illegal stuff in lambda list of Define-Modify-Macro."))))
809 (setq other-args (nreverse other-args))
810 `(defmacro ,name (,reference ,@lambda-list &environment ,env)
811 ,doc-string
812 (multiple-value-bind (dummies vals newval setter getter)
813 (get-setf-method ,reference ,env)
814 (do ((d dummies (cdr d))
815 (v vals (cdr v))
816 (let-list nil (cons (list (car d) (car v)) let-list)))
817 ((null d)
818 (push
819 (list (car newval)
820 ,(if rest-arg
821 `(list* ',function getter ,@other-args ,rest-arg)
822 `(list ',function getter ,@other-args)))
823 let-list)
824 `(let* ,(nreverse let-list)
825 ,setter)))))))
826
827
828
829 (defmacro push (obj place &environment env)
830 "Takes an object and a location holding a list. Conses the object onto
831 the list, returning the modified list."
832 (if (symbolp place)
833 `(setq ,place (cons ,obj ,place))
834 (multiple-value-bind (dummies vals newval setter getter)
835 (get-setf-method place env)
836 (do* ((d dummies (cdr d))
837 (v vals (cdr v))
838 (let-list nil))
839 ((null d)
840 (push (list (car newval) `(cons ,obj ,getter))
841 let-list)
842 `(let* ,(nreverse let-list)
843 ,setter))
844 (push (list (car d) (car v)) let-list)))))
845
846
847 (defmacro pushnew (obj place &rest keys &environment env)
848 "Takes an object and a location holding a list. If the object is already
849 in the list, does nothing. Else, conses the object onto the list. Returns
850 NIL. If there is a :TEST keyword, this is used for the comparison."
851 (if (symbolp place)
852 `(setq ,place (adjoin ,obj ,place ,@keys))
853 (multiple-value-bind (dummies vals newval setter getter)
854 (get-setf-method place env)
855 (do* ((d dummies (cdr d))
856 (v vals (cdr v))
857 (let-list nil))
858 ((null d)
859 (push (list (car newval) `(adjoin ,obj ,getter ,@keys))
860 let-list)
861 `(let* ,(nreverse let-list)
862 ,setter))
863 (push (list (car d) (car v)) let-list)))))
864
865
866 (defmacro pop (place &environment env)
867 "The argument is a location holding a list. Pops one item off the front
868 of the list and returns it."
869 (if (symbolp place)
870 `(prog1 (car ,place) (setq ,place (cdr ,place)))
871 (multiple-value-bind (dummies vals newval setter getter)
872 (get-setf-method place env)
873 (do* ((d dummies (cdr d))
874 (v vals (cdr v))
875 (let-list nil))
876 ((null d)
877 (push (list (car newval) getter) let-list)
878 `(let* ,(nreverse let-list)
879 (prog1 (car ,(car newval))
880 (setq ,(car newval) (cdr ,(car newval)))
881 ,setter)))
882 (push (list (car d) (car v)) let-list)))))
883
884
885 (define-modify-macro incf (&optional (delta 1)) +
886 "The first argument is some location holding a number. This number is
887 incremented by the second argument, DELTA, which defaults to 1.")
888
889
890 (define-modify-macro decf (&optional (delta 1)) -
891 "The first argument is some location holding a number. This number is
892 decremented by the second argument, DELTA, which defaults to 1.")
893
894
895 (defmacro remf (place indicator &environment env)
896 "Place may be any place expression acceptable to SETF, and is expected
897 to hold a property list or (). This list is destructively altered to
898 remove the property specified by the indicator. Returns T if such a
899 property was present, NIL if not."
900 (multiple-value-bind (dummies vals newval setter getter)
901 (get-setf-method place env)
902 (do* ((d dummies (cdr d))
903 (v vals (cdr v))
904 (let-list nil)
905 (ind-temp (gensym))
906 (local1 (gensym))
907 (local2 (gensym)))
908 ((null d)
909 (push (list (car newval) getter) let-list)
910 (push (list ind-temp indicator) let-list)
911 `(let* ,(nreverse let-list)
912 (do ((,local1 ,(car newval) (cddr ,local1))
913 (,local2 nil ,local1))
914 ((atom ,local1) nil)
915 (cond ((atom (cdr ,local1))
916 (error "Odd-length property list in REMF."))
917 ((eq (car ,local1) ,ind-temp)
918 (cond (,local2
919 (rplacd (cdr ,local2) (cddr ,local1))
920 (return t))
921 (t (setq ,(car newval) (cddr ,(car newval)))
922 ,setter
923 (return t))))))))
924 (push (list (car d) (car v)) let-list))))
925
926
927 ;;; The built-in DEFSETFs.
928
929 (defsetf car %rplaca)
930 (defsetf cdr %rplacd)
931 (defsetf caar (x) (v) `(%rplaca (car ,x) ,v))
932 (defsetf cadr (x) (v) `(%rplaca (cdr ,x) ,v))
933 (defsetf cdar (x) (v) `(%rplacd (car ,x) ,v))
934 (defsetf cddr (x) (v) `(%rplacd (cdr ,x) ,v))
935 (defsetf caaar (x) (v) `(%rplaca (caar ,x) ,v))
936 (defsetf cadar (x) (v) `(%rplaca (cdar ,x) ,v))
937 (defsetf cdaar (x) (v) `(%rplacd (caar ,x) ,v))
938 (defsetf cddar (x) (v) `(%rplacd (cdar ,x) ,v))
939 (defsetf caadr (x) (v) `(%rplaca (cadr ,x) ,v))
940 (defsetf caddr (x) (v) `(%rplaca (cddr ,x) ,v))
941 (defsetf cdadr (x) (v) `(%rplacd (cadr ,x) ,v))
942 (defsetf cdddr (x) (v) `(%rplacd (cddr ,x) ,v))
943 (defsetf caaaar (x) (v) `(%rplaca (caaar ,x) ,v))
944 (defsetf cadaar (x) (v) `(%rplaca (cdaar ,x) ,v))
945 (defsetf cdaaar (x) (v) `(%rplacd (caaar ,x) ,v))
946 (defsetf cddaar (x) (v) `(%rplacd (cdaar ,x) ,v))
947 (defsetf caadar (x) (v) `(%rplaca (cadar ,x) ,v))
948 (defsetf caddar (x) (v) `(%rplaca (cddar ,x) ,v))
949 (defsetf cdadar (x) (v) `(%rplacd (cadar ,x) ,v))
950 (defsetf cdddar (x) (v) `(%rplacd (cddar ,x) ,v))
951 (defsetf caaadr (x) (v) `(%rplaca (caadr ,x) ,v))
952 (defsetf cadadr (x) (v) `(%rplaca (cdadr ,x) ,v))
953 (defsetf cdaadr (x) (v) `(%rplacd (caadr ,x) ,v))
954 (defsetf cddadr (x) (v) `(%rplacd (cdadr ,x) ,v))
955 (defsetf caaddr (x) (v) `(%rplaca (caddr ,x) ,v))
956 (defsetf cadddr (x) (v) `(%rplaca (cdddr ,x) ,v))
957 (defsetf cdaddr (x) (v) `(%rplacd (caddr ,x) ,v))
958 (defsetf cddddr (x) (v) `(%rplacd (cdddr ,x) ,v))
959
960 (defsetf first %rplaca)
961 (defsetf second (x) (v) `(%rplaca (cdr ,x) ,v))
962 (defsetf third (x) (v) `(%rplaca (cddr ,x) ,v))
963 (defsetf fourth (x) (v) `(%rplaca (cdddr ,x) ,v))
964 (defsetf fifth (x) (v) `(%rplaca (cddddr ,x) ,v))
965 (defsetf sixth (x) (v) `(%rplaca (cdr (cddddr ,x)) ,v))
966 (defsetf seventh (x) (v) `(%rplaca (cddr (cddddr ,x)) ,v))
967 (defsetf eighth (x) (v) `(%rplaca (cdddr (cddddr ,x)) ,v))
968 (defsetf ninth (x) (v) `(%rplaca (cddddr (cddddr ,x)) ,v))
969 (defsetf tenth (x) (v) `(%rplaca (cdr (cddddr (cddddr ,x))) ,v))
970 (defsetf rest %rplacd)
971
972 (defsetf elt %setelt)
973 (defsetf aref %aset)
974 (defsetf row-major-aref %set-row-major-aref)
975 (defsetf svref %svset)
976 (defsetf char %charset)
977 (defsetf bit %bitset)
978 (defsetf schar %scharset)
979 (defsetf sbit %sbitset)
980 (defsetf %array-dimension %set-array-dimension)
981 (defsetf %raw-bits %set-raw-bits)
982 (defsetf symbol-value set)
983 (defsetf symbol-function fset)
984 (defsetf symbol-plist %set-symbol-plist)
985 (defsetf nth %setnth)
986 (defsetf fill-pointer %set-fill-pointer)
987 (defsetf search-list %set-search-list)
988
989 (defsetf sap-ref-8 %set-sap-ref-8)
990 (defsetf signed-sap-ref-8 %set-signed-sap-ref-8)
991 (defsetf sap-ref-16 %set-sap-ref-16)
992 (defsetf signed-sap-ref-16 %set-signed-sap-ref-16)
993 (defsetf sap-ref-32 %set-sap-ref-32)
994 (defsetf signed-sap-ref-32 %set-signed-sap-ref-32)
995 #+alpha
996 (defsetf sap-ref-64 %set-sap-ref-64)
997 #+alpha
998 (defsetf signed-sap-ref-64 %set-signed-sap-ref-64)
999 (defsetf sap-ref-sap %set-sap-ref-sap)
1000 (defsetf sap-ref-single %set-sap-ref-single)
1001 (defsetf sap-ref-double %set-sap-ref-double)
1002 #+long-float
1003 (defsetf sap-ref-long %set-sap-ref-long)
1004
1005 (define-setf-method getf (place prop &optional default &environment env)
1006 (multiple-value-bind (temps values stores set get)
1007 (get-setf-method place env)
1008 (let ((newval (gensym))
1009 (ptemp (gensym))
1010 (def-temp (if default (gensym))))
1011 (values `(,@temps ,ptemp ,@(if default `(,def-temp)))
1012 `(,@values ,prop ,@(if default `(,default)))
1013 `(,newval)
1014 `(let ((,(car stores) (%putf ,get ,ptemp ,newval)))
1015 ,set
1016 ,newval)
1017 `(getf ,get ,ptemp ,@(if default `(,def-temp)))))))
1018
1019 (define-setf-method get (symbol prop &optional default)
1020 (let ((symbol-temp (gensym))
1021 (prop-temp (gensym))
1022 (def-temp (gensym))
1023 (newval (gensym)))
1024 (values `(,symbol-temp ,prop-temp ,@(if default `(,def-temp)))
1025 `(,symbol ,prop ,@(if default `(,default)))
1026 (list newval)
1027 `(%put ,symbol-temp ,prop-temp ,newval)
1028 `(get ,symbol-temp ,prop-temp ,@(if default `(,def-temp))))))
1029
1030 (define-setf-method gethash (key hashtable &optional default)
1031 (let ((key-temp (gensym))
1032 (hashtable-temp (gensym))
1033 (default-temp (gensym))
1034 (new-value-temp (gensym)))
1035 (values
1036 `(,key-temp ,hashtable-temp ,@(if default `(,default-temp)))
1037 `(,key ,hashtable ,@(if default `(,default)))
1038 `(,new-value-temp)
1039 `(%puthash ,key-temp ,hashtable-temp ,new-value-temp)
1040 `(gethash ,key-temp ,hashtable-temp ,@(if default `(,default-temp))))))
1041
1042 (defsetf subseq (sequence start &optional (end nil)) (v)
1043 `(progn (replace ,sequence ,v :start1 ,start :end1 ,end)
1044 ,v))
1045
1046
1047 ;;; Evil hack invented by the gnomes of Vassar Street (though not as evil as
1048 ;;; it used to be.) The function arg must be constant, and is converted to an
1049 ;;; APPLY of ther SETF function, which ought to exist.
1050 ;;;
1051 (define-setf-method apply (function &rest args)
1052 (unless (and (listp function)
1053 (= (list-length function) 2)
1054 (eq (first function) 'function)
1055 (symbolp (second function)))
1056 (error "Setf of Apply is only defined for function args like #'symbol."))
1057 (let ((function (second function))
1058 (new-var (gensym))
1059 (vars nil))
1060 (dolist (x args)
1061 (declare (ignore x))
1062 (push (gensym) vars))
1063 (values vars args (list new-var)
1064 `(apply #'(setf ,function) ,new-var ,@vars)
1065 `(apply #',function ,@vars))))
1066
1067
1068 ;;; Special-case a BYTE bytespec so that the compiler can recognize it.
1069 ;;;
1070 (define-setf-method ldb (bytespec place &environment env)
1071 "The first argument is a byte specifier. The second is any place form
1072 acceptable to SETF. Replaces the specified byte of the number in this
1073 place with bits from the low-order end of the new value."
1074 (multiple-value-bind (dummies vals newval setter getter)
1075 (get-setf-method place env)
1076 (if (and (consp bytespec) (eq (car bytespec) 'byte))
1077 (let ((n-size (gensym))
1078 (n-pos (gensym))
1079 (n-new (gensym)))
1080 (values (list* n-size n-pos dummies)
1081 (list* (second bytespec) (third bytespec) vals)
1082 (list n-new)
1083 `(let ((,(car newval) (dpb ,n-new (byte ,n-size ,n-pos)
1084 ,getter)))
1085 ,setter
1086 ,n-new)
1087 `(ldb (byte ,n-size ,n-pos) ,getter)))
1088 (let ((btemp (gensym))
1089 (gnuval (gensym)))
1090 (values (cons btemp dummies)
1091 (cons bytespec vals)
1092 (list gnuval)
1093 `(let ((,(car newval) (dpb ,gnuval ,btemp ,getter)))
1094 ,setter
1095 ,gnuval)
1096 `(ldb ,btemp ,getter))))))
1097
1098
1099 (define-setf-method mask-field (bytespec place &environment env)
1100 "The first argument is a byte specifier. The second is any place form
1101 acceptable to SETF. Replaces the specified byte of the number in this place
1102 with bits from the corresponding position in the new value."
1103 (multiple-value-bind (dummies vals newval setter getter)
1104 (get-setf-method place env)
1105 (let ((btemp (gensym))
1106 (gnuval (gensym)))
1107 (values (cons btemp dummies)
1108 (cons bytespec vals)
1109 (list gnuval)
1110 `(let ((,(car newval) (deposit-field ,gnuval ,btemp ,getter)))
1111 ,setter
1112 ,gnuval)
1113 `(mask-field ,btemp ,getter)))))
1114
1115
1116 (define-setf-method the (type place &environment env)
1117 (multiple-value-bind (dummies vals newval setter getter)
1118 (get-setf-method place env)
1119 (values dummies
1120 vals
1121 newval
1122 (subst `(the ,type ,(car newval)) (car newval) setter)
1123 `(the ,type ,getter))))
1124
1125
1126 ;;;; CASE, TYPECASE, & Friends.
1127
1128 (eval-when (compile load eval)
1129
1130 ;;; CASE-BODY returns code for all the standard "case" macros. Name is the
1131 ;;; macro name, and keyform is the thing to case on. Multi-p indicates whether
1132 ;;; a branch may fire off a list of keys; otherwise, a key that is a list is
1133 ;;; interpreted in some way as a single key. When multi-p, test is applied to
1134 ;;; the value of keyform and each key for a given branch; otherwise, test is
1135 ;;; applied to the value of keyform and the entire first element, instead of
1136 ;;; each part, of the case branch. When errorp, no t or otherwise branch is
1137 ;;; permitted, and an ERROR form is generated. When proceedp, it is an error
1138 ;;; to omit errorp, and the ERROR form generated is executed within a
1139 ;;; RESTART-CASE allowing keyform to be set and retested.
1140 ;;;
1141 (defun case-body (name keyform cases multi-p test errorp proceedp)
1142 (let ((keyform-value (gensym))
1143 (clauses ())
1144 (keys ()))
1145 (dolist (case cases)
1146 (cond ((atom case)
1147 (error "~S -- Bad clause in ~S." case name))
1148 ((memq (car case) '(t otherwise))
1149 (if errorp
1150 (error "No default clause allowed in ~S: ~S" name case)
1151 (push `(t nil ,@(rest case)) clauses)))
1152 ((and multi-p (listp (first case)))
1153 (setf keys (append (first case) keys))
1154 (push `((or ,@(mapcar #'(lambda (key)
1155 `(,test ,keyform-value ',key))
1156 (first case)))
1157 nil ,@(rest case))
1158 clauses))
1159 (t
1160 (push (first case) keys)
1161 (push `((,test ,keyform-value
1162 ',(first case)) nil ,@(rest case)) clauses))))
1163 (case-body-aux name keyform keyform-value clauses keys errorp proceedp
1164 `(,(if multi-p 'member 'or) ,@keys))))
1165
1166 ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled all the
1167 ;;; cases. Note: it is not necessary that the resulting code signal
1168 ;;; case-failure conditions, but that's what KMP's prototype code did. We call
1169 ;;; CASE-BODY-ERROR, because of how closures are compiled. RESTART-CASE has
1170 ;;; forms with closures that the compiler causes to be generated at the top of
1171 ;;; any function using the case macros, regardless of whether they are needed.
1172 ;;;
1173 (defun case-body-aux (name keyform keyform-value clauses keys
1174 errorp proceedp expected-type)
1175 (if proceedp
1176 (let ((block (gensym))
1177 (again (gensym)))
1178 `(let ((,keyform-value ,keyform))
1179 (block ,block
1180 (tagbody
1181 ,again
1182 (return-from
1183 ,block
1184 (cond ,@(nreverse clauses)
1185 (t
1186 (setf ,keyform-value
1187 (setf ,keyform
1188 (case-body-error
1189 ',name ',keyform ,keyform-value
1190 ',expected-type ',keys)))
1191 (go ,again))))))))
1192 `(let ((,keyform-value ,keyform))
1193 ,keyform-value ; prevent warnings when key not used eg (case key (t))
1194 (cond
1195 ,@(nreverse clauses)
1196 ,@(if errorp
1197 `((t (error 'conditions::case-failure
1198 :name ',name
1199 :datum ,keyform-value
1200 :expected-type ',expected-type
1201 :possibilities ',keys))))))))
1202
1203 ); eval-when
1204
1205 (defun case-body-error (name keyform keyform-value expected-type keys)
1206 (restart-case
1207 (error 'conditions::case-failure
1208 :name name
1209 :datum keyform-value
1210 :expected-type expected-type
1211 :possibilities keys)
1212 (store-value (value)
1213 :report (lambda (stream)
1214 (format stream "Supply a new value for ~S." keyform))
1215 :interactive read-evaluated-form
1216 value)))
1217
1218
1219 (defmacro case (keyform &body cases)
1220 "CASE Keyform {({(Key*) | Key} Form*)}*
1221 Evaluates the Forms in the first clause with a Key EQL to the value of
1222 Keyform. If a singleton key is T then the clause is a default clause."
1223 (case-body 'case keyform cases t 'eql nil nil))
1224
1225 (defmacro ccase (keyform &body cases)
1226 "CCASE Keyform {({(Key*) | Key} Form*)}*
1227 Evaluates the Forms in the first clause with a Key EQL to the value of
1228 Keyform. If none of the keys matches then a correctable error is
1229 signalled."
1230 (case-body 'ccase keyform cases t 'eql t t))
1231
1232 (defmacro ecase (keyform &body cases)
1233 "ECASE Keyform {({(Key*) | Key} Form*)}*
1234 Evaluates the Forms in the first clause with a Key EQL to the value of
1235 Keyform. If none of the keys matches then an error is signalled."
1236 (case-body 'ecase keyform cases t 'eql t nil))
1237
1238 (defmacro typecase (keyform &body cases)
1239 "TYPECASE Keyform {(Type Form*)}*
1240 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
1241 is true."
1242 (case-body 'typecase keyform cases nil 'typep nil nil))
1243
1244 (defmacro ctypecase (keyform &body cases)
1245 "CTYPECASE Keyform {(Type Form*)}*
1246 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
1247 is true. If no form is satisfied then a correctable error is signalled."
1248 (case-body 'ctypecase keyform cases nil 'typep t t))
1249
1250 (defmacro etypecase (keyform &body cases)
1251 "ETYPECASE Keyform {(Type Form*)}*
1252 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
1253 is true. If no form is satisfied then an error is signalled."
1254 (case-body 'etypecase keyform cases nil 'typep t nil))
1255
1256
1257 ;;;; ASSERT and CHECK-TYPE.
1258
1259 ;;; ASSERT is written this way, to call ASSERT-ERROR, because of how closures
1260 ;;; are compiled. RESTART-CASE has forms with closures that the compiler
1261 ;;; causes to be generated at the top of any function using ASSERT, regardless
1262 ;;; of whether they are needed.
1263 ;;;
1264 (defmacro assert (test-form &optional places datum &rest arguments)
1265 "Signals an error if the value of test-form is nil. Continuing from this
1266 error using the CONTINUE restart will allow the user to alter the value of
1267 some locations known to SETF, starting over with test-form. Returns nil."
1268 `(loop
1269 (when ,test-form (return nil))
1270 (assert-error ',test-form ',places ,datum ,@arguments)
1271 ,@(mapcar #'(lambda (place)
1272 `(setf ,place (assert-prompt ',place ,place)))
1273 places)))
1274
1275 (defun assert-error (assertion places datum &rest arguments)
1276 (let ((cond (if datum
1277 (conditions::coerce-to-condition
1278 datum arguments
1279 'simple-error 'error)
1280 (make-condition 'simple-error
1281 :format-control "The assertion ~S failed."
1282 :format-arguments (list assertion)))))
1283 (restart-case (error cond)
1284 (continue ()
1285 :report (lambda (stream) (assert-report places stream))
1286 nil))))
1287
1288
1289 (defun assert-report (names stream)
1290 (format stream "Retry assertion")
1291 (if names
1292 (format stream " with new value~P for ~{~S~^, ~}."
1293 (length names) names)
1294 (format stream ".")))
1295
1296 (defun assert-prompt (name value)
1297 (cond ((y-or-n-p "The old value of ~S is ~S.~
1298 ~%Do you want to supply a new value? "
1299 name value)
1300 (format *query-io* "~&Type a form to be evaluated:~%")
1301 (flet ((read-it () (eval (read *query-io*))))
1302 (if (symbolp name) ;help user debug lexical variables
1303 (progv (list name) (list value) (read-it))
1304 (read-it))))
1305 (t value)))
1306
1307
1308 ;;; CHECK-TYPE is written this way, to call CHECK-TYPE-ERROR, because of how
1309 ;;; closures are compiled. RESTART-CASE has forms with closures that the
1310 ;;; compiler causes to be generated at the top of any function using
1311 ;;; CHECK-TYPE, regardless of whether they are needed. Because it would be
1312 ;;; nice if this were cheap to use, and some things can't afford this excessive
1313 ;;; consing (e.g., READ-CHAR), we bend backwards a little.
1314 ;;;
1315
1316 (defmacro check-type (place type &optional type-string)
1317 "Signals an error of type type-error if the contents of place are not of the
1318 specified type. If an error is signaled, this can only return if
1319 STORE-VALUE is invoked. It will store into place and start over."
1320 (let ((place-value (gensym)))
1321 `(loop
1322 (let ((,place-value ,place))
1323 (when (typep ,place-value ',type) (return nil))
1324 (setf ,place
1325 (check-type-error ',place ,place-value ',type ,type-string))))))
1326
1327 (defun check-type-error (place place-value type type-string)
1328 (let ((cond (if type-string
1329 (make-condition 'simple-type-error
1330 :datum place :expected-type type
1331 :format-control
1332 "The value of ~S is ~S, which is not ~A."
1333 :format-arguments
1334 (list place place-value type-string))
1335 (make-condition 'simple-type-error
1336 :datum place :expected-type type
1337 :format-control
1338 "The value of ~S is ~S, which is not of type ~S."
1339 :format-arguments
1340 (list place place-value type)))))
1341 (restart-case (error cond)
1342 (store-value (value)
1343 :report (lambda (stream)
1344 (format stream "Supply a new value of ~S."
1345 place))
1346 :interactive read-evaluated-form
1347 value))))
1348
1349 ;;; READ-EVALUATED-FORM is used as the interactive method for restart cases
1350 ;;; setup by the Common Lisp "casing" (e.g., CCASE and CTYPECASE) macros
1351 ;;; and by CHECK-TYPE.
1352 ;;;
1353 (defun read-evaluated-form ()
1354 (format *query-io* "~&Type a form to be evaluated:~%")
1355 (list (eval (read *query-io*))))
1356
1357
1358 ;;;; With-XXX
1359 (defmacro with-open-file ((var &rest open-args) &body (forms decls))
1360 "Bindspec is of the form (Stream File-Name . Options). The file whose
1361 name is File-Name is opened using the Options and bound to the variable
1362 Stream. If the call to open is unsuccessful, the forms are not
1363 evaluated. The Forms are executed, and when they
1364 terminate, normally or otherwise, the file is closed."
1365 (let ((abortp (gensym)))
1366 `(let ((,var (open ,@open-args))
1367 (,abortp t))
1368 ,@decls
1369 (unwind-protect
1370 (multiple-value-prog1
1371 (progn ,@forms)
1372 (setq ,abortp nil))
1373 (when ,var
1374 (close ,var :abort ,abortp))))))
1375
1376
1377 (defmacro with-open-stream ((var stream) &body (forms decls))
1378 "The form stream should evaluate to a stream. VAR is bound
1379 to the stream and the forms are evaluated as an implicit
1380 progn. The stream is closed upon exit."
1381 (let ((abortp (gensym)))
1382 `(let ((,var ,stream)
1383 (,abortp t))
1384 ,@decls
1385 (unwind-protect
1386 (multiple-value-prog1
1387 (progn ,@forms)
1388 (setq ,abortp nil))
1389 (when ,var
1390 (close ,var :abort ,abortp))))))
1391
1392
1393 (defmacro with-input-from-string ((var string &key index start end) &body (forms decls))
1394 "Binds the Var to an input stream that returns characters from String and
1395 executes the body. See manual for details."
1396 ;; The once-only inhibits compiler note for unreachable code when 'end' is true.
1397 (once-only ((string string))
1398 `(let ((,var
1399 ,(cond ((null end)
1400 `(make-string-input-stream ,string ,(or start 0)))
1401 ((symbolp end)
1402 `(if ,end
1403 (make-string-input-stream ,string ,(or start 0) ,end)
1404 (make-string-input-stream ,string ,(or start 0))))
1405 (t
1406 `(make-string-input-stream ,string ,(or start 0) ,end)))))
1407 ,@decls
1408 (unwind-protect
1409 (progn ,@forms)
1410 (close ,var)
1411 ,@(if index `((setf ,index (string-input-stream-current ,var))))))))
1412
1413
1414 (defmacro with-output-to-string ((var &optional string) &body (forms decls))
1415 "If *string* is specified, it must be a string with a fill pointer;
1416 the output is incrementally appended to the string (as if by use of
1417 VECTOR-PUSH-EXTEND)."
1418 (if string
1419 `(let ((,var (make-fill-pointer-output-stream ,string)))
1420 ,@decls
1421 (unwind-protect
1422 (progn ,@forms)
1423 (close ,var)))
1424 `(let ((,var (make-string-output-stream)))
1425 ,@decls
1426 (unwind-protect
1427 (progn ,@forms)
1428 (close ,var))
1429 (get-output-stream-string ,var))))
1430
1431
1432 ;;;; Iteration macros:
1433
1434 (defmacro dotimes ((var count &optional (result nil)) &body body)
1435 (cond ((numberp count)
1436 `(do ((,var 0 (1+ ,var)))
1437 ((>= ,var ,count) ,result)
1438 (declare (type unsigned-byte ,var))
1439 ,@body))
1440 (t (let ((v1 (gensym)))
1441 `(do ((,var 0 (1+ ,var)) (,v1 ,count))
1442 ((>= ,var ,v1) ,result)
1443 (declare (type unsigned-byte ,var))
1444 ,@body)))))
1445
1446
1447 ;;; We repeatedly bind the var instead of setting it so that we never give the
1448 ;;; var a random value such as NIL (which might conflict with a declaration).
1449 ;;; If there is a result form, we introduce a gratitous binding of the variable
1450 ;;; to NIL w/o the declarations, then evaluate the result form in that
1451 ;;; environment. We spuriously reference the gratuitous variable, since we
1452 ;;; don't want to use IGNORABLE on what might be a special var.
1453 ;;;
1454 (defmacro dolist ((var list &optional (result nil)) &body body)
1455 (let ((n-list (gensym)))
1456 `(do ((,n-list ,list (cdr ,n-list)))
1457 ((endp ,n-list)
1458 ,@(if result
1459 `((let ((,var nil))
1460 ,var
1461 ,result))
1462 '(nil)))
1463 (let ((,var (car ,n-list)))
1464 ,@body))))
1465
1466
1467 (defmacro do (varlist endlist &body (body decls))
1468 "DO ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
1469 Iteration construct. Each Var is initialized in parallel to the value of the
1470 specified Init form. On subsequent iterations, the Vars are assigned the
1471 value of the Step form (if any) in paralell. The Test is evaluated before
1472 each evaluation of the body Forms. When the Test is true, the Exit-Forms
1473 are evaluated as a PROGN, with the result being the value of the DO. A block
1474 named NIL is established around the entire expansion, allowing RETURN to be
1475 used as an laternate exit mechanism."
1476
1477 (do-do-body varlist endlist body decls 'let 'psetq 'do nil))
1478
1479
1480 (defmacro do* (varlist endlist &body (body decls))
1481 "DO* ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
1482 Iteration construct. Each Var is initialized sequentially (like LET*) to the
1483 value of the specified Init form. On subsequent iterations, the Vars are
1484 sequentially assigned the value of the Step form (if any). The Test is
1485 evaluated before each evaluation of the body Forms. When the Test is true,
1486 the Exit-Forms are evaluated as a PROGN, with the result being the value
1487 of the DO. A block named NIL is established around the entire expansion,
1488 allowing RETURN to be used as an laternate exit mechanism."
1489 (do-do-body varlist endlist body decls 'let* 'setq 'do* nil))
1490
1491
1492 ;;;; Miscellaneous macros:
1493
1494 (defmacro locally (&rest forms)
1495 "A form providing a container for locally-scoped variables."
1496 `(let () ,@forms))
1497
1498 (defmacro psetq (&rest pairs)
1499 (do ((lets nil)
1500 (setqs nil)
1501 (pairs pairs (cddr pairs)))
1502 ((atom (cdr pairs))
1503 `(let ,(nreverse lets) (setq ,@(nreverse setqs)) nil))
1504 (let ((gen (gensym)))
1505 (push `(,gen ,(cadr pairs)) lets)
1506 (push (car pairs) setqs)
1507 (push gen setqs))))
1508
1509 ;;; LAMBDA -- from the ANSI spec.
1510 ;;;
1511 (defmacro lambda (&whole form &rest bvl-decls-and-body)
1512 (declare (ignore bvl-decls-and-body))
1513 `#',form)
1514
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