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

Contents of /src/code/macros.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.5