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

Contents of /src/code/macros.lisp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.52 - (show annotations)
Sat Sep 13 20:28:10 1997 UTC (16 years, 7 months ago) by pw
Branch: MAIN
Changes since 1.51: +17 -15 lines
Minor change to inhibit compiler notes about dead code removal
when WITH-INPUT-FROM-STRING was called with an END argument.
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.52 1997/09/13 20:28:10 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 (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
1003 (define-setf-method getf (place prop &optional default &environment env)
1004 (multiple-value-bind (temps values stores set get)
1005 (get-setf-method place env)
1006 (let ((newval (gensym))
1007 (ptemp (gensym))
1008 (def-temp (if default (gensym))))
1009 (values `(,@temps ,ptemp ,@(if default `(,def-temp)))
1010 `(,@values ,prop ,@(if default `(,default)))
1011 `(,newval)
1012 `(let ((,(car stores) (%putf ,get ,ptemp ,newval)))
1013 ,set
1014 ,newval)
1015 `(getf ,get ,ptemp ,@(if default `(,def-temp)))))))
1016
1017 (define-setf-method get (symbol prop &optional default)
1018 (let ((symbol-temp (gensym))
1019 (prop-temp (gensym))
1020 (def-temp (gensym))
1021 (newval (gensym)))
1022 (values `(,symbol-temp ,prop-temp ,@(if default `(,def-temp)))
1023 `(,symbol ,prop ,@(if default `(,default)))
1024 (list newval)
1025 `(%put ,symbol-temp ,prop-temp ,newval)
1026 `(get ,symbol-temp ,prop-temp ,@(if default `(,def-temp))))))
1027
1028 (define-setf-method gethash (key hashtable &optional default)
1029 (let ((key-temp (gensym))
1030 (hashtable-temp (gensym))
1031 (default-temp (gensym))
1032 (new-value-temp (gensym)))
1033 (values
1034 `(,key-temp ,hashtable-temp ,@(if default `(,default-temp)))
1035 `(,key ,hashtable ,@(if default `(,default)))
1036 `(,new-value-temp)
1037 `(%puthash ,key-temp ,hashtable-temp ,new-value-temp)
1038 `(gethash ,key-temp ,hashtable-temp ,@(if default `(,default-temp))))))
1039
1040 (defsetf subseq (sequence start &optional (end nil)) (v)
1041 `(progn (replace ,sequence ,v :start1 ,start :end1 ,end)
1042 ,v))
1043
1044
1045 ;;; Evil hack invented by the gnomes of Vassar Street (though not as evil as
1046 ;;; it used to be.) The function arg must be constant, and is converted to an
1047 ;;; APPLY of ther SETF function, which ought to exist.
1048 ;;;
1049 (define-setf-method apply (function &rest args)
1050 (unless (and (listp function)
1051 (= (list-length function) 2)
1052 (eq (first function) 'function)
1053 (symbolp (second function)))
1054 (error "Setf of Apply is only defined for function args like #'symbol."))
1055 (let ((function (second function))
1056 (new-var (gensym))
1057 (vars nil))
1058 (dolist (x args)
1059 (declare (ignore x))
1060 (push (gensym) vars))
1061 (values vars args (list new-var)
1062 `(apply #'(setf ,function) ,new-var ,@vars)
1063 `(apply #',function ,@vars))))
1064
1065
1066 ;;; Special-case a BYTE bytespec so that the compiler can recognize it.
1067 ;;;
1068 (define-setf-method ldb (bytespec place &environment env)
1069 "The first argument is a byte specifier. The second is any place form
1070 acceptable to SETF. Replaces the specified byte of the number in this
1071 place with bits from the low-order end of the new value."
1072 (multiple-value-bind (dummies vals newval setter getter)
1073 (get-setf-method place env)
1074 (if (and (consp bytespec) (eq (car bytespec) 'byte))
1075 (let ((n-size (gensym))
1076 (n-pos (gensym))
1077 (n-new (gensym)))
1078 (values (list* n-size n-pos dummies)
1079 (list* (second bytespec) (third bytespec) vals)
1080 (list n-new)
1081 `(let ((,(car newval) (dpb ,n-new (byte ,n-size ,n-pos)
1082 ,getter)))
1083 ,setter
1084 ,n-new)
1085 `(ldb (byte ,n-size ,n-pos) ,getter)))
1086 (let ((btemp (gensym))
1087 (gnuval (gensym)))
1088 (values (cons btemp dummies)
1089 (cons bytespec vals)
1090 (list gnuval)
1091 `(let ((,(car newval) (dpb ,gnuval ,btemp ,getter)))
1092 ,setter
1093 ,gnuval)
1094 `(ldb ,btemp ,getter))))))
1095
1096
1097 (define-setf-method mask-field (bytespec place &environment env)
1098 "The first argument is a byte specifier. The second is any place form
1099 acceptable to SETF. Replaces the specified byte of the number in this place
1100 with bits from the corresponding position in the new value."
1101 (multiple-value-bind (dummies vals newval setter getter)
1102 (get-setf-method place env)
1103 (let ((btemp (gensym))
1104 (gnuval (gensym)))
1105 (values (cons btemp dummies)
1106 (cons bytespec vals)
1107 (list gnuval)
1108 `(let ((,(car newval) (deposit-field ,gnuval ,btemp ,getter)))
1109 ,setter
1110 ,gnuval)
1111 `(mask-field ,btemp ,getter)))))
1112
1113
1114 (define-setf-method the (type place &environment env)
1115 (multiple-value-bind (dummies vals newval setter getter)
1116 (get-setf-method place env)
1117 (values dummies
1118 vals
1119 newval
1120 (subst `(the ,type ,(car newval)) (car newval) setter)
1121 `(the ,type ,getter))))
1122
1123
1124 ;;;; CASE, TYPECASE, & Friends.
1125
1126 (eval-when (compile load eval)
1127
1128 ;;; CASE-BODY returns code for all the standard "case" macros. Name is the
1129 ;;; macro name, and keyform is the thing to case on. Multi-p indicates whether
1130 ;;; a branch may fire off a list of keys; otherwise, a key that is a list is
1131 ;;; interpreted in some way as a single key. When multi-p, test is applied to
1132 ;;; the value of keyform and each key for a given branch; otherwise, test is
1133 ;;; applied to the value of keyform and the entire first element, instead of
1134 ;;; each part, of the case branch. When errorp, no t or otherwise branch is
1135 ;;; permitted, and an ERROR form is generated. When proceedp, it is an error
1136 ;;; to omit errorp, and the ERROR form generated is executed within a
1137 ;;; RESTART-CASE allowing keyform to be set and retested.
1138 ;;;
1139 (defun case-body (name keyform cases multi-p test errorp proceedp)
1140 (let ((keyform-value (gensym))
1141 (clauses ())
1142 (keys ()))
1143 (dolist (case cases)
1144 (cond ((atom case)
1145 (error "~S -- Bad clause in ~S." case name))
1146 ((memq (car case) '(t otherwise))
1147 (if errorp
1148 (error "No default clause allowed in ~S: ~S" name case)
1149 (push `(t nil ,@(rest case)) clauses)))
1150 ((and multi-p (listp (first case)))
1151 (setf keys (append (first case) keys))
1152 (push `((or ,@(mapcar #'(lambda (key)
1153 `(,test ,keyform-value ',key))
1154 (first case)))
1155 nil ,@(rest case))
1156 clauses))
1157 (t
1158 (push (first case) keys)
1159 (push `((,test ,keyform-value
1160 ',(first case)) nil ,@(rest case)) clauses))))
1161 (case-body-aux name keyform keyform-value clauses keys errorp proceedp
1162 `(,(if multi-p 'member 'or) ,@keys))))
1163
1164 ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled all the
1165 ;;; cases. Note: it is not necessary that the resulting code signal
1166 ;;; case-failure conditions, but that's what KMP's prototype code did. We call
1167 ;;; CASE-BODY-ERROR, because of how closures are compiled. RESTART-CASE has
1168 ;;; forms with closures that the compiler causes to be generated at the top of
1169 ;;; any function using the case macros, regardless of whether they are needed.
1170 ;;;
1171 (defun case-body-aux (name keyform keyform-value clauses keys
1172 errorp proceedp expected-type)
1173 (if proceedp
1174 (let ((block (gensym))
1175 (again (gensym)))
1176 `(let ((,keyform-value ,keyform))
1177 (block ,block
1178 (tagbody
1179 ,again
1180 (return-from
1181 ,block
1182 (cond ,@(nreverse clauses)
1183 (t
1184 (setf ,keyform-value
1185 (setf ,keyform
1186 (case-body-error
1187 ',name ',keyform ,keyform-value
1188 ',expected-type ',keys)))
1189 (go ,again))))))))
1190 `(let ((,keyform-value ,keyform))
1191 ,keyform-value ; prevent warnings when key not used eg (case key (t))
1192 (cond
1193 ,@(nreverse clauses)
1194 ,@(if errorp
1195 `((t (error 'conditions::case-failure
1196 :name ',name
1197 :datum ,keyform-value
1198 :expected-type ',expected-type
1199 :possibilities ',keys))))))))
1200
1201 ); eval-when
1202
1203 (defun case-body-error (name keyform keyform-value expected-type keys)
1204 (restart-case
1205 (error 'conditions::case-failure
1206 :name name
1207 :datum keyform-value
1208 :expected-type expected-type
1209 :possibilities keys)
1210 (store-value (value)
1211 :report (lambda (stream)
1212 (format stream "Supply a new value for ~S." keyform))
1213 :interactive read-evaluated-form
1214 value)))
1215
1216
1217 (defmacro case (keyform &body cases)
1218 "CASE Keyform {({(Key*) | Key} Form*)}*
1219 Evaluates the Forms in the first clause with a Key EQL to the value of
1220 Keyform. If a singleton key is T then the clause is a default clause."
1221 (case-body 'case keyform cases t 'eql nil nil))
1222
1223 (defmacro ccase (keyform &body cases)
1224 "CCASE Keyform {({(Key*) | Key} Form*)}*
1225 Evaluates the Forms in the first clause with a Key EQL to the value of
1226 Keyform. If none of the keys matches then a correctable error is
1227 signalled."
1228 (case-body 'ccase keyform cases t 'eql t t))
1229
1230 (defmacro ecase (keyform &body cases)
1231 "ECASE Keyform {({(Key*) | Key} Form*)}*
1232 Evaluates the Forms in the first clause with a Key EQL to the value of
1233 Keyform. If none of the keys matches then an error is signalled."
1234 (case-body 'ecase keyform cases t 'eql t nil))
1235
1236 (defmacro typecase (keyform &body cases)
1237 "TYPECASE Keyform {(Type Form*)}*
1238 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
1239 is true."
1240 (case-body 'typecase keyform cases nil 'typep nil nil))
1241
1242 (defmacro ctypecase (keyform &body cases)
1243 "CTYPECASE Keyform {(Type Form*)}*
1244 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
1245 is true. If no form is satisfied then a correctable error is signalled."
1246 (case-body 'ctypecase keyform cases nil 'typep t t))
1247
1248 (defmacro etypecase (keyform &body cases)
1249 "ETYPECASE Keyform {(Type Form*)}*
1250 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
1251 is true. If no form is satisfied then an error is signalled."
1252 (case-body 'etypecase keyform cases nil 'typep t nil))
1253
1254
1255 ;;;; ASSERT and CHECK-TYPE.
1256
1257 ;;; ASSERT is written this way, to call ASSERT-ERROR, because of how closures
1258 ;;; are compiled. RESTART-CASE has forms with closures that the compiler
1259 ;;; causes to be generated at the top of any function using ASSERT, regardless
1260 ;;; of whether they are needed.
1261 ;;;
1262 (defmacro assert (test-form &optional places datum &rest arguments)
1263 "Signals an error if the value of test-form is nil. Continuing from this
1264 error using the CONTINUE restart will allow the user to alter the value of
1265 some locations known to SETF, starting over with test-form. Returns nil."
1266 `(loop
1267 (when ,test-form (return nil))
1268 (assert-error ',test-form ',places ,datum ,@arguments)
1269 ,@(mapcar #'(lambda (place)
1270 `(setf ,place (assert-prompt ',place ,place)))
1271 places)))
1272
1273 (defun assert-error (assertion places datum &rest arguments)
1274 (let ((cond (if datum
1275 (conditions::coerce-to-condition
1276 datum arguments
1277 'simple-error 'error)
1278 (make-condition 'simple-error
1279 :format-control "The assertion ~S failed."
1280 :format-arguments (list assertion)))))
1281 (restart-case (error cond)
1282 (continue ()
1283 :report (lambda (stream) (assert-report places stream))
1284 nil))))
1285
1286
1287 (defun assert-report (names stream)
1288 (format stream "Retry assertion")
1289 (if names
1290 (format stream " with new value~P for ~{~S~^, ~}."
1291 (length names) names)
1292 (format stream ".")))
1293
1294 (defun assert-prompt (name value)
1295 (cond ((y-or-n-p "The old value of ~S is ~S.~
1296 ~%Do you want to supply a new value? "
1297 name value)
1298 (format *query-io* "~&Type a form to be evaluated:~%")
1299 (flet ((read-it () (eval (read *query-io*))))
1300 (if (symbolp name) ;help user debug lexical variables
1301 (progv (list name) (list value) (read-it))
1302 (read-it))))
1303 (t value)))
1304
1305
1306 ;;; CHECK-TYPE is written this way, to call CHECK-TYPE-ERROR, because of how
1307 ;;; closures are compiled. RESTART-CASE has forms with closures that the
1308 ;;; compiler causes to be generated at the top of any function using
1309 ;;; CHECK-TYPE, regardless of whether they are needed. Because it would be
1310 ;;; nice if this were cheap to use, and some things can't afford this excessive
1311 ;;; consing (e.g., READ-CHAR), we bend backwards a little.
1312 ;;;
1313
1314 (defmacro check-type (place type &optional type-string)
1315 "Signals an error of type type-error if the contents of place are not of the
1316 specified type. If an error is signaled, this can only return if
1317 STORE-VALUE is invoked. It will store into place and start over."
1318 (let ((place-value (gensym)))
1319 `(loop
1320 (let ((,place-value ,place))
1321 (when (typep ,place-value ',type) (return nil))
1322 (setf ,place
1323 (check-type-error ',place ,place-value ',type ,type-string))))))
1324
1325 (defun check-type-error (place place-value type type-string)
1326 (let ((cond (if type-string
1327 (make-condition 'simple-type-error
1328 :datum place :expected-type type
1329 :format-control
1330 "The value of ~S is ~S, which is not ~A."
1331 :format-arguments
1332 (list place place-value type-string))
1333 (make-condition 'simple-type-error
1334 :datum place :expected-type type
1335 :format-control
1336 "The value of ~S is ~S, which is not of type ~S."
1337 :format-arguments
1338 (list place place-value type)))))
1339 (restart-case (error cond)
1340 (store-value (value)
1341 :report (lambda (stream)
1342 (format stream "Supply a new value of ~S."
1343 place))
1344 :interactive read-evaluated-form
1345 value))))
1346
1347 ;;; READ-EVALUATED-FORM is used as the interactive method for restart cases
1348 ;;; setup by the Common Lisp "casing" (e.g., CCASE and CTYPECASE) macros
1349 ;;; and by CHECK-TYPE.
1350 ;;;
1351 (defun read-evaluated-form ()
1352 (format *query-io* "~&Type a form to be evaluated:~%")
1353 (list (eval (read *query-io*))))
1354
1355
1356 ;;;; With-XXX
1357 (defmacro with-open-file ((var &rest open-args) &body (forms decls))
1358 "Bindspec is of the form (Stream File-Name . Options). The file whose
1359 name is File-Name is opened using the Options and bound to the variable
1360 Stream. If the call to open is unsuccessful, the forms are not
1361 evaluated. The Forms are executed, and when they
1362 terminate, normally or otherwise, the file is closed."
1363 (let ((abortp (gensym)))
1364 `(let ((,var (open ,@open-args))
1365 (,abortp t))
1366 ,@decls
1367 (unwind-protect
1368 (multiple-value-prog1
1369 (progn ,@forms)
1370 (setq ,abortp nil))
1371 (when ,var
1372 (close ,var :abort ,abortp))))))
1373
1374
1375 (defmacro with-open-stream ((var stream) &body (forms decls))
1376 "The form stream should evaluate to a stream. VAR is bound
1377 to the stream and the forms are evaluated as an implicit
1378 progn. The stream is closed upon exit."
1379 (let ((abortp (gensym)))
1380 `(let ((,var ,stream)
1381 (,abortp t))
1382 ,@decls
1383 (unwind-protect
1384 (multiple-value-prog1
1385 (progn ,@forms)
1386 (setq ,abortp nil))
1387 (when ,var
1388 (close ,var :abort ,abortp))))))
1389
1390
1391 (defmacro with-input-from-string ((var string &key index start end) &body (forms decls))
1392 "Binds the Var to an input stream that returns characters from String and
1393 executes the body. See manual for details."
1394 ;; The once-only inhibits compiler note for unreachable code when 'end' is true.
1395 (once-only ((string string))
1396 `(let ((,var
1397 ,(cond ((null end)
1398 `(make-string-input-stream ,string ,(or start 0)))
1399 ((symbolp end)
1400 `(if ,end
1401 (make-string-input-stream ,string ,(or start 0) ,end)
1402 (make-string-input-stream ,string ,(or start 0))))
1403 (t
1404 `(make-string-input-stream ,string ,(or start 0) ,end)))))
1405 ,@decls
1406 (unwind-protect
1407 (progn ,@forms)
1408 (close ,var)
1409 ,@(if index `((setf ,index (string-input-stream-current ,var))))))))
1410
1411
1412 (defmacro with-output-to-string ((var &optional string) &body (forms decls))
1413 "If *string* is specified, it must be a string with a fill pointer;
1414 the output is incrementally appended to the string (as if by use of
1415 VECTOR-PUSH-EXTEND)."
1416 (if string
1417 `(let ((,var (make-fill-pointer-output-stream ,string)))
1418 ,@decls
1419 (unwind-protect
1420 (progn ,@forms)
1421 (close ,var)))
1422 `(let ((,var (make-string-output-stream)))
1423 ,@decls
1424 (unwind-protect
1425 (progn ,@forms)
1426 (close ,var))
1427 (get-output-stream-string ,var))))
1428
1429
1430 ;;;; Iteration macros:
1431
1432 (defmacro dotimes ((var count &optional (result nil)) &body body)
1433 (cond ((numberp count)
1434 `(do ((,var 0 (1+ ,var)))
1435 ((>= ,var ,count) ,result)
1436 (declare (type unsigned-byte ,var))
1437 ,@body))
1438 (t (let ((v1 (gensym)))
1439 `(do ((,var 0 (1+ ,var)) (,v1 ,count))
1440 ((>= ,var ,v1) ,result)
1441 (declare (type unsigned-byte ,var))
1442 ,@body)))))
1443
1444
1445 ;;; We repeatedly bind the var instead of setting it so that we never give the
1446 ;;; var a random value such as NIL (which might conflict with a declaration).
1447 ;;; If there is a result form, we introduce a gratitous binding of the variable
1448 ;;; to NIL w/o the declarations, then evaluate the result form in that
1449 ;;; environment. We spuriously reference the gratuitous variable, since we
1450 ;;; don't want to use IGNORABLE on what might be a special var.
1451 ;;;
1452 (defmacro dolist ((var list &optional (result nil)) &body body)
1453 (let ((n-list (gensym)))
1454 `(do ((,n-list ,list (cdr ,n-list)))
1455 ((endp ,n-list)
1456 ,@(if result
1457 `((let ((,var nil))
1458 ,var
1459 ,result))
1460 '(nil)))
1461 (let ((,var (car ,n-list)))
1462 ,@body))))
1463
1464
1465 (defmacro do (varlist endlist &body (body decls))
1466 "DO ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
1467 Iteration construct. Each Var is initialized in parallel to the value of the
1468 specified Init form. On subsequent iterations, the Vars are assigned the
1469 value of the Step form (if any) in paralell. The Test is evaluated before
1470 each evaluation of the body Forms. When the Test is true, the the Exit-Forms
1471 are evaluated as a PROGN, with the result being the value of the DO. A block
1472 named NIL is established around the entire expansion, allowing RETURN to be
1473 used as an laternate exit mechanism."
1474
1475 (do-do-body varlist endlist body decls 'let 'psetq 'do nil))
1476
1477
1478 (defmacro do* (varlist endlist &body (body decls))
1479 "DO* ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
1480 Iteration construct. Each Var is initialized sequentially (like LET*) to the
1481 value of the specified Init form. On subsequent iterations, the Vars are
1482 sequentially assigned the value of the Step form (if any). The Test is
1483 evaluated before each evaluation of the body Forms. When the Test is true,
1484 the the Exit-Forms are evaluated as a PROGN, with the result being the value
1485 of the DO. A block named NIL is established around the entire expansion,
1486 allowing RETURN to be used as an laternate exit mechanism."
1487 (do-do-body varlist endlist body decls 'let* 'setq 'do* nil))
1488
1489
1490 ;;;; Miscellaneous macros:
1491
1492 (defmacro locally (&rest forms)
1493 "A form providing a container for locally-scoped variables."
1494 `(let () ,@forms))
1495
1496 (defmacro psetq (&rest pairs)
1497 (do ((lets nil)
1498 (setqs nil)
1499 (pairs pairs (cddr pairs)))
1500 ((atom (cdr pairs))
1501 `(let ,(nreverse lets) (setq ,@(nreverse setqs))))
1502 (let ((gen (gensym)))
1503 (push `(,gen ,(cadr pairs)) lets)
1504 (push (car pairs) setqs)
1505 (push gen setqs))))
1506
1507 ;;; LAMBDA -- from the ANSI spec.
1508 ;;;
1509 (defmacro lambda (&whole form &rest bvl-decls-and-body)
1510 (declare (ignore bvl-decls-and-body))
1511 `#',form)
1512
1513
1514
1515 ;;;; With-Compilation-Unit:
1516
1517 ;;; True if we are within a With-Compilation-Unit form, which normally causes
1518 ;;; nested uses to be NOOPS.
1519 ;;;
1520 (defvar *in-compilation-unit* nil)
1521
1522 ;;; Count of the number of compilation units dynamically enclosed by the
1523 ;;; current active WITH-COMPILATION-UNIT that were unwound out of.
1524 ;;;
1525 (defvar *aborted-compilation-units*)
1526
1527 (declaim (special c::*context-declarations*))
1528
1529
1530 ;;; EVALUATE-DECLARATION-CONTEXT -- Internal
1531 ;;;
1532 ;;; Recursively descend the context form, returning true if this subpart
1533 ;;; matches the specified context.
1534 ;;;
1535 (defun evaluate-declaration-context (context name parent)
1536 (let* ((base (if (and (consp name) (consp (cdr name)))
1537 (cadr name)
1538 name))
1539 (package (and (symbolp base) (symbol-package base))))
1540 (if (atom context)
1541 (multiple-value-bind (ignore how)
1542 (if package
1543 (find-symbol (symbol-name base) package)
1544 (values nil nil))
1545 (declare (ignore ignore))
1546 (case context
1547 (:internal (eq how :internal))
1548 (:external (eq how :external))
1549 (:uninterned (and (symbolp base) (not package)))
1550 (:anonymous (not name))
1551 (:macro (eq parent 'defmacro))
1552 (:function (member parent '(defun labels flet function)))
1553 (:global (member parent '(defun defmacro function)))
1554 (:local (member parent '(labels flet)))
1555 (t
1556 (error "Unknown declaration context: ~S." context))))
1557 (case (first context)
1558 (:or
1559 (loop for x in (rest context)
1560 thereis (evaluate-declaration-context x name parent)))
1561 (:and
1562 (loop for x in (rest context)
1563 always (evaluate-declaration-context x name parent)))
1564 (:not
1565 (evaluate-declaration-context (second context) name parent))
1566 (:member
1567 (member name (rest context) :test #'equal))
1568 (:match
1569 (let ((name (concatenate 'string "$" (string base) "$")))
1570 (loop for x in (rest context)
1571 thereis (search (string x) name))))
1572 (:package
1573 (and package
1574 (loop for x in (rest context)
1575 thereis (eq (find-package (string x)) package))))
1576 (t
1577 (error "Unknown declaration context: ~S." context))))))
1578
1579
1580 ;;; PROCESS-CONTEXT-DECLARATIONS -- Internal
1581 ;;;
1582 ;;; Given a list of context declaration specs, return a new value for
1583 ;;; C::*CONTEXT-DECLARATIONS*.
1584 ;;;
1585 (defun process-context-declarations (decls)
1586 (append
1587 (mapcar
1588 #'(lambda (decl)
1589 (unless (>= (length decl) 2)
1590 (error "Context declaration spec should have context and at ~
1591 least one DECLARE form:~% ~S" decl))
1592 #'(lambda (name parent)
1593 (when (evaluate-declaration-context (first decl) name parent)
1594 (rest decl))))
1595 decls)
1596 c::*context-declarations*))
1597
1598
1599 ;;; With-Compilation-Unit -- Public
1600 ;;;
1601 (defmacro with-compilation-unit (options &body body)
1602 "WITH-COMPILATION-UNIT ({Key Value}*) Form*
1603 This form affects compilations that take place within its dynamic extent. It
1604 is intended to be wrapped around the compilation of all files in the same
1605 system. These keywords are defined:
1606 :OVERRIDE Boolean-Form
1607 One of the effects of this form is to delay undefined warnings
1608 until the end of the form, instead of giving them at the end of each
1609 compilation. If OVERRIDE is NIL (the default), then the outermost
1610 WITH-COMPILATION-UNIT form grabs the undefined warnings. Specifying
1611 OVERRIDE true causes that form to grab any enclosed warnings, even if
1612 it is enclosed by another WITH-COMPILATION-UNIT.
1613 :OPTIMIZE Decl-Form
1614 Decl-Form should evaluate to an OPTIMIZE declaration specifier. This
1615 declaration changes the `global' policy for compilations within the
1616 body.
1617 :OPTIMIZE-INTERFACE Decl-Form
1618 Like OPTIMIZE, except that it specifies the value of the CMU extension
1619 OPTIMIZE-INTERFACE policy (which controls argument type and syntax
1620 checking.)
1621 :CONTEXT-DECLARATIONS List-of-Context-Decls-Form
1622 This is a CMU extension which allows compilation to be controlled
1623 by pattern matching on the context in which a definition appears. The
1624 argument should evaluate to a list of lists of the form:
1625 (Context-Spec Declare-Form+)
1626 In the indicated context, the specified declare forms are inserted at
1627 the head of each definition. The declare forms for all contexts that
1628 match are appended together, with earlier declarations getting
1629 predecence over later ones. A simple example:
1630 :context-declarations
1631 '((:external (declare (optimize (safety 2)))))
1632 This will cause all functions that are named by external symbols to be
1633 compiled with SAFETY 2. The full syntax of context specs is:
1634 :INTERNAL, :EXTERNAL
1635 True if the symbols is internal (external) in its home package.
1636 :UNINTERNED
1637 True if the symbol has no home package.
1638 :ANONYMOUS
1639 True if the function doesn't have any interesting name (not
1640 DEFMACRO, DEFUN, LABELS or FLET).
1641 :MACRO, :FUNCTION
1642 :MACRO is a global (DEFMACRO) macro. :FUNCTION is anything else.
1643 :LOCAL, :GLOBAL
1644 :LOCAL is a LABELS or FLET. :GLOBAL is anything else.
1645 (:OR Context-Spec*)
1646 True in any specified context.
1647 (:AND Context-Spec*)
1648 True only when all specs are true.
1649 (:NOT Context-Spec)
1650 True when the spec is false.
1651 (:MEMBER Name*)
1652 True when the name is one of these names (EQUAL test.)
1653 (:MATCH Pattern*)
1654 True when any of the patterns is a substring of the name. The name
1655 is wrapped with $'s, so $FOO matches names beginning with FOO,
1656 etc."
1657 (let ((override nil)
1658 (optimize nil)
1659 (optimize-interface nil)
1660 (context-declarations nil)
1661 (n-fun (gensym))
1662 (n-abort-p (gensym)))
1663 (when (oddp (length options))
1664 (error "Odd number of key/value pairs: ~S." options))
1665 (do ((opt options (cddr opt)))
1666 ((null opt))
1667 (case (first opt)
1668 (:override
1669 (setq override (second opt)))
1670 (:optimize
1671 (setq optimize (second opt)))
1672 (:optimize-interface
1673 (setq optimize-interface (second opt)))
1674 (:context-declarations
1675 (setq context-declarations (second opt)))
1676 (t
1677 (warn "Ignoring unknown option: ~S." (first opt)))))
1678
1679 `(flet ((,n-fun ()
1680 (let (,@(when optimize
1681 `((c::*default-cookie*
1682 (c::process-optimize-declaration
1683 ,optimize c::*default-cookie*))))
1684 ,@(when optimize-interface
1685 `((c::*default-interface-cookie*
1686 (c::process-optimize-declaration
1687 ,optimize-interface
1688 c::*default-interface-cookie*))))
1689 ,@(when context-declarations
1690 `((c::*context-declarations*
1691 (process-context-declarations
1692 ,context-declarations)))))
1693 ,@body)))
1694 (if (or ,override (not *in-compilation-unit*))
1695 (let ((c::*undefined-warnings* nil)
1696 (c::*compiler-error-count* 0)
1697 (c::*compiler-warning-count* 0)
1698 (c::*compiler-note-count* 0)
1699 (*in-compilation-unit* t)
1700 (*aborted-compilation-units* 0)
1701 (,n-abort-p t))
1702 (handler-bind ((c::parse-unknown-type
1703 #'(lambda (c)
1704 (c::note-undefined-reference
1705 (c::parse-unknown-type-specifier c)
1706 :type))))
1707 (unwind-protect
1708 (multiple-value-prog1
1709 (,n-fun)
1710 (setq ,n-abort-p nil))
1711 (c::print-summary ,n-abort-p *aborted-compilation-units*))))
1712 (let ((,n-abort-p t))
1713 (unwind-protect
1714 (multiple-value-prog1
1715 (,n-fun)
1716 (setq ,n-abort-p nil))
1717 (when ,n-abort-p
1718 (incf *aborted-compilation-units*))))))))

  ViewVC Help
Powered by ViewVC 1.1.5