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

Contents of /src/code/macros.lisp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.50.2.6 - (show annotations)
Sun Jul 9 14:03:01 2000 UTC (13 years, 9 months ago) by dtc
Branch: RELENG_18
Changes since 1.50.2.5: +4 -3 lines
Reworking of the values-type system to overcome a number of inconsistencies
causing problems:

o Redefine coerce-to-values to convert a single value type into (values type),
  rather than the former definition (values type &rest t). A single value
  type such as fixnum is now equivalent to (values fixnum).

o Now when the compiler makes assertions for the first value of
  continuations that may be generating multiple values it asserts the
  type as (values type &rest t), or as (value &optional type &rest t) if
  it is not sure that the continuation does generate a value.

o Enhance the type check generation to better handle the now common
  values types with optional and rest arguments. Add the new function
  Values-types-asserted which converts asserted optional and rest
  arguments to required arguments that have been proven to be delivered,
  Thus an assertion such as (values &optional fixnum &rest t) will
  generate a fixnum type check if the proven type if (values t).

o The compiler is now far more likely to pickup attempts to use an
  assertion to select a subset of values. For example
  (the (values fixnum) (values x y)) will generated a compiler warning.

o Update single values type assertions where appropriate to clarify that
  the received values may be optional or that multiple values may be
  received. For example, a macro argument which had been asserted to be
  a list via (the list ,...) would now be asserted to be
  (the (values &optional list &rest t)) etc.

o Have the IR1 translator for THE convert single value types into
  (values &optional type &rest t) so that code such as
  (the fixnum (values x y)) will still work acceptably. This does not
  restrict the possible type assertions as the values types may be used
  and are not modified.
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.50.2.6 2000/07/09 14:03:01 dtc Exp $")
9 ;;;
10 ;;; **********************************************************************
11 ;;;
12 ;;; This file contains the macros that are part of the standard
13 ;;; Spice Lisp environment.
14 ;;;
15 ;;; Written by Scott Fahlman and Rob MacLachlan.
16 ;;; Modified by Bill Chiles to adhere to the wall.
17 ;;;
18 (in-package "LISP")
19 (export '(defvar defparameter defconstant when unless setf
20 defsetf psetf shiftf rotatef push pushnew pop
21 incf decf remf case typecase with-open-file
22 with-open-stream with-input-from-string with-output-to-string
23 locally etypecase ctypecase ecase ccase
24 get-setf-expansion define-setf-expander
25 define-modify-macro destructuring-bind nth-value
26 otherwise ; Sacred to CASE and related macros.
27 define-compiler-macro
28 ;; CLtL1 versions:
29 define-setf-method get-setf-method get-setf-method-multiple-value))
30
31 (in-package "EXTENSIONS")
32 (export '(do-anonymous collect iterate))
33
34 (in-package "LISP")
35
36
37 ;;; Parse-Body -- Public
38 ;;;
39 ;;; Parse out declarations and doc strings, *not* expanding macros.
40 ;;; Eventually the environment arg should be flushed, since macros can't expand
41 ;;; into declarations anymore.
42 ;;;
43 (defun parse-body (body environment &optional (doc-string-allowed t))
44 "This function is to parse the declarations and doc-string out of the body of
45 a defun-like form. Body is the list of stuff which is to be parsed.
46 Environment is ignored. If Doc-String-Allowed is true, then a doc string
47 will be parsed out of the body and returned. If it is false then a string
48 will terminate the search for declarations. Three values are returned: the
49 tail of Body after the declarations and doc strings, a list of declare forms,
50 and the doc-string, or NIL if none."
51 (declare (ignore environment))
52 (let ((decls ())
53 (doc nil))
54 (do ((tail body (cdr tail)))
55 ((endp tail)
56 (values tail (nreverse decls) doc))
57 (let ((form (car tail)))
58 (cond ((and (stringp form) (cdr tail))
59 (if doc-string-allowed
60 (setq doc form)
61 (return (values tail (nreverse decls) doc))))
62 ((not (and (consp form) (symbolp (car form))))
63 (return (values tail (nreverse decls) doc)))
64 ((eq (car form) 'declare)
65 (push form decls))
66 (t
67 (return (values tail (nreverse decls) doc))))))))
68
69
70 ;;;; DEFMACRO:
71
72 ;;; Defmacro -- Public
73 ;;;
74 ;;; Parse the definition and make an expander function. The actual
75 ;;; definition is done by %defmacro which we expand into.
76 ;;;
77 (defmacro defmacro (name lambda-list &body body)
78 (let ((whole (gensym "WHOLE-"))
79 (environment (gensym "ENV-")))
80 (multiple-value-bind
81 (body local-decs doc)
82 (parse-defmacro lambda-list whole body name 'defmacro
83 :environment environment)
84 (let ((def `(lambda (,whole ,environment)
85 ,@local-decs
86 (block ,name
87 ,body))))
88 `(c::%defmacro ',name #',def ',lambda-list ,doc)))))
89
90
91 ;;; %Defmacro, %%Defmacro -- Internal
92 ;;;
93 ;;; Defmacro expands into %Defmacro which is a function that is treated
94 ;;; magically the compiler. After the compiler has gotten the information it
95 ;;; wants out of macro definition, it compiles a call to %%Defmacro which
96 ;;; happens at load time. We have a %Defmacro function which just calls
97 ;;; %%Defmacro in order to keep the interpreter happy.
98 ;;;
99 ;;; Eventually %%Defmacro should deal with clearing old compiler information
100 ;;; for the functional value.
101 ;;;
102 (defun c::%defmacro (name definition lambda-list doc)
103 (assert (eval:interpreted-function-p definition))
104 (setf (eval:interpreted-function-name definition)
105 (format nil "DEFMACRO ~S" name))
106 (setf (eval:interpreted-function-arglist definition) lambda-list)
107 (c::%%defmacro name definition doc))
108 ;;;
109 (defun c::%%defmacro (name definition doc)
110 (clear-info function where-from name)
111 (setf (macro-function name) definition)
112 (setf (documentation name 'function) doc)
113 name)
114
115
116
117 ;;;; DEFINE-COMPILER-MACRO
118
119 (defmacro define-compiler-macro (name lambda-list &body body)
120 "Define a compiler-macro for NAME."
121 (let ((whole (gensym "WHOLE-"))
122 (environment (gensym "ENV-")))
123 (multiple-value-bind
124 (body local-decs doc)
125 (parse-defmacro lambda-list whole body name 'define-compiler-macro
126 :environment environment)
127 (let ((def `(lambda (,whole ,environment)
128 ,@local-decs
129 (block ,name
130 ,body))))
131 `(c::%define-compiler-macro ',name #',def ',lambda-list ,doc)))))
132
133 (defun c::%define-compiler-macro (name definition lambda-list doc)
134 (assert (eval:interpreted-function-p definition))
135 (setf (eval:interpreted-function-name definition)
136 (let ((*print-case* :upcase))
137 (format nil "DEFINE-COMPILER-MACRO ~S" name)))
138 (setf (eval:interpreted-function-arglist definition) lambda-list)
139 (c::%%define-compiler-macro name definition doc))
140 ;;;
141 (defun c::%%define-compiler-macro (name definition doc)
142 (setf (compiler-macro-function name) definition)
143 (setf (documentation name 'compiler-macro) doc)
144 name)
145
146
147
148 ;;; DEFTYPE is a lot like DEFMACRO.
149
150 (defmacro deftype (name arglist &body body)
151 "Syntax like DEFMACRO, but defines a new type."
152 (unless (symbolp name)
153 (error "~S -- Type name not a symbol." name))
154
155 (let ((whole (gensym "WHOLE-")))
156 (multiple-value-bind (body local-decs doc)
157 (parse-defmacro arglist whole body name 'deftype
158 :default-default ''*)
159 `(eval-when (compile load eval)
160 (%deftype ',name
161 #'(lambda (,whole)
162 ,@local-decs
163 (block ,name ,body))
164 ,@(when doc `(,doc)))))))
165 ;;;
166 (defun %deftype (name expander &optional doc)
167 (ecase (info type kind name)
168 (:primitive
169 (when *type-system-initialized*
170 (error "Illegal to redefine standard type: ~S." name)))
171 (:instance
172 (warn "Redefining class ~S to be a DEFTYPE." name)
173 (undefine-structure (layout-info (class-layout (find-class name))))
174 (setf (class-cell-class (find-class-cell name)) nil)
175 (setf (info type compiler-layout name) nil)
176 (setf (info type kind name) :defined))
177 (:defined)
178 ((nil)
179 (setf (info type kind name) :defined)))
180
181 (setf (info type expander name) expander)
182 (when doc
183 (setf (documentation name 'type) doc))
184 ;; ### Bootstrap hack -- we need to define types before %note-type-defined
185 ;; is defined.
186 (when (fboundp 'c::%note-type-defined)
187 (c::%note-type-defined name))
188 name)
189
190
191 ;;; And so is DEFINE-SETF-EXPANDER.
192
193 (defparameter defsetf-error-string "Setf expander for ~S cannot be called with ~S args.")
194
195 (defmacro define-setf-expander (access-fn lambda-list &body body)
196 "Syntax like DEFMACRO, but creates a Setf-Method generator. The body
197 must be a form that returns the five magical values."
198 (unless (symbolp access-fn)
199 (error "~S -- Access-function name not a symbol in DEFINE-SETF-EXPANDER."
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-expander
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 (values fixnum &rest t) ,n)
501 (0 (nth-value 0 ,form))
502 (1 (nth-value 1 ,form))
503 (2 (nth-value 2 ,form))
504 (T (nth (the (values fixnum &rest t) ,n)
505 (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 is created by the long form of DEFSETF or
523 ;;; by DEFINE-SETF-EXPANDER. 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-expansion (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-expansion expansion environment)
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 (expand-or-get-setf-inverse form environment))
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 (t
556 (expand-or-get-setf-inverse form environment)))))
557
558 (defun get-setf-method-multiple-value (form &optional env)
559 "Obsolete: use GET-SETF-EXPANSION."
560 (get-setf-expansion form env))
561
562 ;;;
563 ;;; If a macro, expand one level and try again. If not, go for the
564 ;;; SETF function.
565 (defun expand-or-get-setf-inverse (form environment)
566 (multiple-value-bind
567 (expansion expanded)
568 (macroexpand-1 form environment)
569 (if expanded
570 (get-setf-expansion expansion environment)
571 (get-setf-method-inverse form `(funcall #'(setf ,(car form)))
572 t))))
573
574
575 (defun get-setf-method-inverse (form inverse setf-function)
576 (let ((new-var (gensym))
577 (vars nil)
578 (vals nil))
579 (dolist (x (cdr form))
580 (push (gensym) vars)
581 (push x vals))
582 (setq vals (nreverse vals))
583 (values vars vals (list new-var)
584 (if setf-function
585 `(,@inverse ,new-var ,@vars)
586 `(,@inverse ,@vars ,new-var))
587 `(,(car form) ,@vars))))
588
589
590 (defun get-setf-method (form &optional environment)
591 "Obsolete: use GET-SETF-EXPANSION and handle multiple store values."
592 (multiple-value-bind
593 (temps value-forms store-vars store-form access-form)
594 (get-setf-expansion form environment)
595 (when (cdr store-vars)
596 (error "GET-SETF-METHOD used for a form with multiple store ~
597 variables:~% ~S" form))
598 (values temps value-forms store-vars store-form access-form)))
599
600
601 (defun defsetter (fn rest)
602 (let ((arglist (car rest))
603 (arglist-var (gensym "ARGS-"))
604 (new-var (car (cadr rest))))
605 (multiple-value-bind
606 (body local-decs doc)
607 (parse-defmacro arglist arglist-var (cddr rest) fn 'defsetf)
608 (values
609 `(lambda (,arglist-var ,new-var)
610 ,@local-decs
611 ,body)
612 doc))))
613
614
615 (defmacro defsetf (access-fn &rest rest)
616 "Associates a SETF update function or macro with the specified access
617 function or macro. The format is complex. See the manual for
618 details."
619 (cond ((not (listp (car rest)))
620 `(eval-when (load compile eval)
621 (%define-setf-macro ',access-fn nil ',(car rest)
622 ,(when (and (car rest) (stringp (cadr rest)))
623 `',(cadr rest)))))
624 ((and (cdr rest) (listp (cadr rest)))
625 (destructuring-bind
626 (lambda-list (&rest store-variables) &body body)
627 rest
628 (let ((arglist-var (gensym "ARGS-"))
629 (access-form-var (gensym "ACCESS-FORM-"))
630 (env-var (gensym "ENVIRONMENT-")))
631 (multiple-value-bind
632 (body local-decs doc)
633 (parse-defmacro `(,lambda-list ,@store-variables)
634 arglist-var body access-fn 'defsetf
635 :annonymousp t)
636 `(eval-when (load compile eval)
637 (%define-setf-macro
638 ',access-fn
639 #'(lambda (,access-form-var ,env-var)
640 (declare (ignore ,env-var))
641 (%defsetf ,access-form-var ,(length store-variables)
642 #'(lambda (,arglist-var)
643 ,@local-decs
644 (block ,access-fn
645 ,body))))
646 nil
647 ',doc))))))
648 (t
649 (error "Ill-formed DEFSETF for ~S." access-fn))))
650
651 (defun %defsetf (orig-access-form num-store-vars expander)
652 (collect ((subforms) (subform-vars) (subform-exprs) (store-vars))
653 (dolist (subform (cdr orig-access-form))
654 (if (constantp subform)
655 (subforms subform)
656 (let ((var (gensym)))
657 (subforms var)
658 (subform-vars var)
659 (subform-exprs subform))))
660 (dotimes (i num-store-vars)
661 (store-vars (gensym)))
662 (values (subform-vars)
663 (subform-exprs)
664 (store-vars)
665 (funcall expander (cons (subforms) (store-vars)))
666 `(,(car orig-access-form) ,@(subforms)))))
667
668
669 ;;; SETF -- Public
670 ;;;
671 ;;; Except for atoms, we always call GET-SETF-METHOD, since it has some
672 ;;; non-trivial semantics. But when there is a setf inverse, and G-S-M uses
673 ;;; it, then we return a call to the inverse, rather than returning a hairy let
674 ;;; form. This is probably important mainly as a convenince in allowing the
675 ;;; use of setf inverses without the full interpreter.
676 ;;;
677 (defmacro setf (&rest args &environment env)
678 "Takes pairs of arguments like SETQ. The first is a place and the second
679 is the value that is supposed to go into that place. Returns the last
680 value. The place argument may be any of the access forms for which SETF
681 knows a corresponding setting form."
682 (let ((nargs (length args)))
683 (cond
684 ((= nargs 2)
685 (let ((place (first args))
686 (value-form (second args)))
687 (if (atom place)
688 `(setq ,place ,value-form)
689 (multiple-value-bind (dummies vals newval setter getter)
690 (get-setf-expansion place env)
691 (declare (ignore getter))
692 (let ((inverse (info setf inverse (car place))))
693 (if (and inverse (eq inverse (car setter)))
694 `(,inverse ,@(cdr place) ,value-form)
695 `(let* (,@(mapcar #'list dummies vals))
696 (multiple-value-bind ,newval ,value-form
697 ,setter))))))))
698 ((oddp nargs)
699 (error "Odd number of args to SETF."))
700 (t
701 (do ((a args (cddr a)) (l nil))
702 ((null a) `(progn ,@(nreverse l)))
703 (setq l (cons (list 'setf (car a) (cadr a)) l)))))))
704
705 (defmacro psetf (&rest args &environment env)
706 "This is to SETF as PSETQ is to SETQ. Args are alternating place
707 expressions and values to go into those places. All of the subforms and
708 values are determined, left to right, and only then are the locations
709 updated. Returns NIL."
710 (collect ((let*-bindings) (mv-bindings) (setters))
711 (do ((a args (cddr a)))
712 ((endp a))
713 (if (endp (cdr a))
714 (error "Odd number of args to PSETF."))
715 (multiple-value-bind
716 (dummies vals newval setter getter)
717 (get-setf-expansion (car a) env)
718 (declare (ignore getter))
719 (let*-bindings (mapcar #'list dummies vals))
720 (mv-bindings (list newval (cadr a)))
721 (setters setter)))
722 (labels ((thunk (let*-bindings mv-bindings)
723 (if let*-bindings
724 `(let* ,(car let*-bindings)
725 (multiple-value-bind ,@(car mv-bindings)
726 ,(thunk (cdr let*-bindings) (cdr mv-bindings))))
727 `(progn ,@(setters) nil))))
728 (thunk (let*-bindings) (mv-bindings)))))
729
730 (defmacro shiftf (&whole form &rest args &environment env)
731 "One or more SETF-style place expressions, followed by a single
732 value expression. Evaluates all of the expressions in turn, then
733 assigns the value of each expression to the place on its left,
734 returning the value of the leftmost."
735 (when (< (length args) 2)
736 (error "~S called with too few arguments: ~S" 'shiftf form))
737 (let ((resultvar (gensym)))
738 (do ((arglist args (cdr arglist))
739 (bindlist nil)
740 (storelist nil)
741 (lastvar resultvar))
742 ((atom (cdr arglist))
743 (push `(,lastvar ,(first arglist)) bindlist)
744 `(LET* ,(nreverse bindlist) ,@(nreverse storelist) ,resultvar))
745 (multiple-value-bind (SM1 SM2 SM3 SM4 SM5)
746 (get-setf-method (first arglist) env)
747 (mapc #'(lambda (var val) (push `(,var ,val) bindlist)) SM1 SM2)
748 (push `(,lastvar ,SM5) bindlist)
749 (push SM4 storelist)
750 (setq lastvar (first SM3))))))
751
752 (defmacro rotatef (&rest args &environment env)
753 "Takes any number of SETF-style place expressions. Evaluates all of the
754 expressions in turn, then assigns to each place the value of the form to
755 its right. The rightmost form gets the value of the leftmost.
756 Returns NIL."
757 (when args
758 (collect ((let*-bindings) (mv-bindings) (setters) (getters))
759 (dolist (arg args)
760 (multiple-value-bind
761 (temps subforms store-vars setter getter)
762 (get-setf-expansion arg env)
763 (loop
764 for temp in temps
765 for subform in subforms
766 do (let*-bindings `(,temp ,subform)))
767 (mv-bindings store-vars)
768 (setters setter)
769 (getters getter)))
770 (setters nil)
771 (getters (car (getters)))
772 (labels ((thunk (mv-bindings getters)
773 (if mv-bindings
774 `((multiple-value-bind
775 ,(car mv-bindings)
776 ,(car getters)
777 ,@(thunk (cdr mv-bindings) (cdr getters))))
778 (setters))))
779 `(let* ,(let*-bindings)
780 ,@(thunk (mv-bindings) (cdr (getters))))))))
781
782
783 (defmacro define-modify-macro (name lambda-list function &optional doc-string)
784 "Creates a new read-modify-write macro like PUSH or INCF."
785 (let ((other-args nil)
786 (rest-arg nil)
787 (env (gensym))
788 (reference (gensym)))
789
790 ;; Parse out the variable names and rest arg from the lambda list.
791 (do ((ll lambda-list (cdr ll))
792 (arg nil))
793 ((null ll))
794 (setq arg (car ll))
795 (cond ((eq arg '&optional))
796 ((eq arg '&rest)
797 (if (symbolp (cadr ll))
798 (setq rest-arg (cadr ll))
799 (error "Non-symbol &rest arg in definition of ~S." name))
800 (if (null (cddr ll))
801 (return nil)
802 (error "Illegal stuff after &rest arg in Define-Modify-Macro.")))
803 ((memq arg '(&key &allow-other-keys &aux))
804 (error "~S not allowed in Define-Modify-Macro lambda list." arg))
805 ((symbolp arg)
806 (push arg other-args))
807 ((and (listp arg) (symbolp (car arg)))
808 (push (car arg) other-args))
809 (t (error "Illegal stuff in lambda list of Define-Modify-Macro."))))
810 (setq other-args (nreverse other-args))
811 `(defmacro ,name (,reference ,@lambda-list &environment ,env)
812 ,doc-string
813 (multiple-value-bind (dummies vals newval setter getter)
814 (get-setf-method ,reference ,env)
815 (do ((d dummies (cdr d))
816 (v vals (cdr v))
817 (let-list nil (cons (list (car d) (car v)) let-list)))
818 ((null d)
819 (push
820 (list (car newval)
821 ,(if rest-arg
822 `(list* ',function getter ,@other-args ,rest-arg)
823 `(list ',function getter ,@other-args)))
824 let-list)
825 `(let* ,(nreverse let-list)
826 ,setter)))))))
827
828 (defmacro push (obj place &environment env)
829 "Takes an object and a location holding a list. Conses the object onto
830 the list, returning the modified list. OBJ is evaluated before PLACE."
831 (if (symbolp place)
832 `(setq ,place (cons ,obj ,place))
833 (multiple-value-bind (dummies vals newval setter getter)
834 (get-setf-method place env)
835 (let ((g (gensym)))
836 `(let* ((,g ,obj)
837 ,@(mapcar #'list dummies vals)
838 (,(car newval) (cons ,g ,getter)))
839 ,setter)))))
840
841 (defmacro pushnew (obj place &rest keys &environment env)
842 "Takes an object and a location holding a list. If the object is already
843 in the list, does nothing. Else, conses the object onto the list. Returns
844 NIL. If there is a :TEST keyword, this is used for the comparison."
845 (if (symbolp place)
846 `(setq ,place (adjoin ,obj ,place ,@keys))
847 (multiple-value-bind (dummies vals newval setter getter)
848 (get-setf-method place env)
849 (do* ((d dummies (cdr d))
850 (v vals (cdr v))
851 (let-list nil))
852 ((null d)
853 (push (list (car newval) `(adjoin ,obj ,getter ,@keys))
854 let-list)
855 `(let* ,(nreverse let-list)
856 ,setter))
857 (push (list (car d) (car v)) let-list)))))
858
859
860 (defmacro pop (place &environment env)
861 "The argument is a location holding a list. Pops one item off the front
862 of the list and returns it."
863 (if (symbolp place)
864 `(prog1 (car ,place) (setq ,place (cdr ,place)))
865 (multiple-value-bind (dummies vals newval setter getter)
866 (get-setf-method place env)
867 (do* ((d dummies (cdr d))
868 (v vals (cdr v))
869 (let-list nil))
870 ((null d)
871 (push (list (car newval) getter) let-list)
872 `(let* ,(nreverse let-list)
873 (prog1 (car ,(car newval))
874 (setq ,(car newval) (cdr ,(car newval)))
875 ,setter)))
876 (push (list (car d) (car v)) let-list)))))
877
878
879 (define-modify-macro incf (&optional (delta 1)) +
880 "The first argument is some location holding a number. This number is
881 incremented by the second argument, DELTA, which defaults to 1.")
882
883
884 (define-modify-macro decf (&optional (delta 1)) -
885 "The first argument is some location holding a number. This number is
886 decremented by the second argument, DELTA, which defaults to 1.")
887
888
889 (defmacro remf (place indicator &environment env)
890 "Place may be any place expression acceptable to SETF, and is expected
891 to hold a property list or (). This list is destructively altered to
892 remove the property specified by the indicator. Returns T if such a
893 property was present, NIL if not."
894 (multiple-value-bind (dummies vals newval setter getter)
895 (get-setf-method place env)
896 (do* ((d dummies (cdr d))
897 (v vals (cdr v))
898 (let-list nil)
899 (ind-temp (gensym))
900 (local1 (gensym))
901 (local2 (gensym)))
902 ((null d)
903 (push (list (car newval) getter) let-list)
904 (push (list ind-temp indicator) let-list)
905 `(let* ,(nreverse let-list)
906 (do ((,local1 ,(car newval) (cddr ,local1))
907 (,local2 nil ,local1))
908 ((atom ,local1) nil)
909 (cond ((atom (cdr ,local1))
910 (error "Odd-length property list in REMF."))
911 ((eq (car ,local1) ,ind-temp)
912 (cond (,local2
913 (rplacd (cdr ,local2) (cddr ,local1))
914 (return t))
915 (t (setq ,(car newval) (cddr ,(car newval)))
916 ,setter
917 (return t))))))))
918 (push (list (car d) (car v)) let-list))))
919
920
921 ;;; The built-in DEFSETFs.
922
923 (defsetf car %rplaca)
924 (defsetf cdr %rplacd)
925 (defsetf caar (x) (v) `(%rplaca (car ,x) ,v))
926 (defsetf cadr (x) (v) `(%rplaca (cdr ,x) ,v))
927 (defsetf cdar (x) (v) `(%rplacd (car ,x) ,v))
928 (defsetf cddr (x) (v) `(%rplacd (cdr ,x) ,v))
929 (defsetf caaar (x) (v) `(%rplaca (caar ,x) ,v))
930 (defsetf cadar (x) (v) `(%rplaca (cdar ,x) ,v))
931 (defsetf cdaar (x) (v) `(%rplacd (caar ,x) ,v))
932 (defsetf cddar (x) (v) `(%rplacd (cdar ,x) ,v))
933 (defsetf caadr (x) (v) `(%rplaca (cadr ,x) ,v))
934 (defsetf caddr (x) (v) `(%rplaca (cddr ,x) ,v))
935 (defsetf cdadr (x) (v) `(%rplacd (cadr ,x) ,v))
936 (defsetf cdddr (x) (v) `(%rplacd (cddr ,x) ,v))
937 (defsetf caaaar (x) (v) `(%rplaca (caaar ,x) ,v))
938 (defsetf cadaar (x) (v) `(%rplaca (cdaar ,x) ,v))
939 (defsetf cdaaar (x) (v) `(%rplacd (caaar ,x) ,v))
940 (defsetf cddaar (x) (v) `(%rplacd (cdaar ,x) ,v))
941 (defsetf caadar (x) (v) `(%rplaca (cadar ,x) ,v))
942 (defsetf caddar (x) (v) `(%rplaca (cddar ,x) ,v))
943 (defsetf cdadar (x) (v) `(%rplacd (cadar ,x) ,v))
944 (defsetf cdddar (x) (v) `(%rplacd (cddar ,x) ,v))
945 (defsetf caaadr (x) (v) `(%rplaca (caadr ,x) ,v))
946 (defsetf cadadr (x) (v) `(%rplaca (cdadr ,x) ,v))
947 (defsetf cdaadr (x) (v) `(%rplacd (caadr ,x) ,v))
948 (defsetf cddadr (x) (v) `(%rplacd (cdadr ,x) ,v))
949 (defsetf caaddr (x) (v) `(%rplaca (caddr ,x) ,v))
950 (defsetf cadddr (x) (v) `(%rplaca (cdddr ,x) ,v))
951 (defsetf cdaddr (x) (v) `(%rplacd (caddr ,x) ,v))
952 (defsetf cddddr (x) (v) `(%rplacd (cdddr ,x) ,v))
953
954 (defsetf first %rplaca)
955 (defsetf second (x) (v) `(%rplaca (cdr ,x) ,v))
956 (defsetf third (x) (v) `(%rplaca (cddr ,x) ,v))
957 (defsetf fourth (x) (v) `(%rplaca (cdddr ,x) ,v))
958 (defsetf fifth (x) (v) `(%rplaca (cddddr ,x) ,v))
959 (defsetf sixth (x) (v) `(%rplaca (cdr (cddddr ,x)) ,v))
960 (defsetf seventh (x) (v) `(%rplaca (cddr (cddddr ,x)) ,v))
961 (defsetf eighth (x) (v) `(%rplaca (cdddr (cddddr ,x)) ,v))
962 (defsetf ninth (x) (v) `(%rplaca (cddddr (cddddr ,x)) ,v))
963 (defsetf tenth (x) (v) `(%rplaca (cdr (cddddr (cddddr ,x))) ,v))
964 (defsetf rest %rplacd)
965
966 (defsetf elt %setelt)
967 (defsetf aref %aset)
968 (defsetf row-major-aref %set-row-major-aref)
969 (defsetf svref %svset)
970 (defsetf char %charset)
971 (defsetf bit %bitset)
972 (defsetf schar %scharset)
973 (defsetf sbit %sbitset)
974 (defsetf %array-dimension %set-array-dimension)
975 (defsetf %raw-bits %set-raw-bits)
976 (defsetf symbol-value set)
977 (defsetf symbol-function fset)
978 (defsetf symbol-plist %set-symbol-plist)
979 (defsetf nth %setnth)
980 (defsetf fill-pointer %set-fill-pointer)
981 (defsetf search-list %set-search-list)
982
983 (defsetf sap-ref-8 %set-sap-ref-8)
984 (defsetf signed-sap-ref-8 %set-signed-sap-ref-8)
985 (defsetf sap-ref-16 %set-sap-ref-16)
986 (defsetf signed-sap-ref-16 %set-signed-sap-ref-16)
987 (defsetf sap-ref-32 %set-sap-ref-32)
988 (defsetf signed-sap-ref-32 %set-signed-sap-ref-32)
989 (defsetf sap-ref-64 %set-sap-ref-64)
990 (defsetf signed-sap-ref-64 %set-signed-sap-ref-64)
991 (defsetf sap-ref-sap %set-sap-ref-sap)
992 (defsetf sap-ref-single %set-sap-ref-single)
993 (defsetf sap-ref-double %set-sap-ref-double)
994 #+long-float
995 (defsetf sap-ref-long %set-sap-ref-long)
996
997 (define-setf-expander getf (place prop &optional default &environment env)
998 (multiple-value-bind (temps values stores set get)
999 (get-setf-method place env)
1000 (let ((newval (gensym))
1001 (ptemp (gensym))
1002 (def-temp (if default (gensym))))
1003 (values `(,@temps ,ptemp ,@(if default `(,def-temp)))
1004 `(,@values ,prop ,@(if default `(,default)))
1005 `(,newval)
1006 `(let ((,(car stores) (%putf ,get ,ptemp ,newval)))
1007 ,set
1008 ,newval)
1009 `(getf ,get ,ptemp ,@(if default `(,def-temp)))))))
1010
1011 (define-setf-expander get (symbol prop &optional default)
1012 (let ((symbol-temp (gensym))
1013 (prop-temp (gensym))
1014 (def-temp (gensym))
1015 (newval (gensym)))
1016 (values `(,symbol-temp ,prop-temp ,@(if default `(,def-temp)))
1017 `(,symbol ,prop ,@(if default `(,default)))
1018 (list newval)
1019 `(%put ,symbol-temp ,prop-temp ,newval)
1020 `(get ,symbol-temp ,prop-temp ,@(if default `(,def-temp))))))
1021
1022 (define-setf-expander gethash (key hashtable &optional default)
1023 (let ((key-temp (gensym))
1024 (hashtable-temp (gensym))
1025 (default-temp (gensym))
1026 (new-value-temp (gensym)))
1027 (values
1028 `(,key-temp ,hashtable-temp ,@(if default `(,default-temp)))
1029 `(,key ,hashtable ,@(if default `(,default)))
1030 `(,new-value-temp)
1031 `(%puthash ,key-temp ,hashtable-temp ,new-value-temp)
1032 `(gethash ,key-temp ,hashtable-temp ,@(if default `(,default-temp))))))
1033
1034 (defsetf subseq (sequence start &optional (end nil)) (v)
1035 `(progn (replace ,sequence ,v :start1 ,start :end1 ,end)
1036 ,v))
1037
1038
1039 ;;; Evil hack invented by the gnomes of Vassar Street (though not as evil as
1040 ;;; it used to be.) The function arg must be constant, and is converted to an
1041 ;;; APPLY of ther SETF function, which ought to exist.
1042 ;;;
1043 (define-setf-expander apply (function &rest args)
1044 (unless (and (listp function)
1045 (= (list-length function) 2)
1046 (eq (first function) 'function)
1047 (symbolp (second function)))
1048 (error "Setf of Apply is only defined for function args like #'symbol."))
1049 (let ((function (second function))
1050 (new-var (gensym))
1051 (vars nil))
1052 (dolist (x args)
1053 (declare (ignore x))
1054 (push (gensym) vars))
1055 (values vars args (list new-var)
1056 `(apply #'(setf ,function) ,new-var ,@vars)
1057 `(apply #',function ,@vars))))
1058
1059
1060 ;;; Special-case a BYTE bytespec so that the compiler can recognize it.
1061 ;;;
1062 (define-setf-expander ldb (bytespec place &environment env)
1063 "The first argument is a byte specifier. The second is any place form
1064 acceptable to SETF. Replaces the specified byte of the number in this
1065 place with bits from the low-order end of the new value."
1066 (multiple-value-bind (dummies vals newval setter getter)
1067 (get-setf-method place env)
1068 (if (and (consp bytespec) (eq (car bytespec) 'byte))
1069 (let ((n-size (gensym))
1070 (n-pos (gensym))
1071 (n-new (gensym)))
1072 (values (list* n-size n-pos dummies)
1073 (list* (second bytespec) (third bytespec) vals)
1074 (list n-new)
1075 `(let ((,(car newval) (dpb ,n-new (byte ,n-size ,n-pos)
1076 ,getter)))
1077 ,setter
1078 ,n-new)
1079 `(ldb (byte ,n-size ,n-pos) ,getter)))
1080 (let ((btemp (gensym))
1081 (gnuval (gensym)))
1082 (values (cons btemp dummies)
1083 (cons bytespec vals)
1084 (list gnuval)
1085 `(let ((,(car newval) (dpb ,gnuval ,btemp ,getter)))
1086 ,setter
1087 ,gnuval)
1088 `(ldb ,btemp ,getter))))))
1089
1090
1091 (define-setf-expander mask-field (bytespec place &environment env)
1092 "The first argument is a byte specifier. The second is any place form
1093 acceptable to SETF. Replaces the specified byte of the number in this place
1094 with bits from the corresponding position in the new value."
1095 (multiple-value-bind (dummies vals newval setter getter)
1096 (get-setf-method place env)
1097 (let ((btemp (gensym))
1098 (gnuval (gensym)))
1099 (values (cons btemp dummies)
1100 (cons bytespec vals)
1101 (list gnuval)
1102 `(let ((,(car newval) (deposit-field ,gnuval ,btemp ,getter)))
1103 ,setter
1104 ,gnuval)
1105 `(mask-field ,btemp ,getter)))))
1106
1107
1108 (define-setf-expander the (type place &environment env)
1109 (multiple-value-bind (dummies vals newval setter getter)
1110 (get-setf-method place env)
1111 (values dummies
1112 vals
1113 newval
1114 (subst `(the ,type ,(car newval)) (car newval) setter)
1115 `(the ,type ,getter))))
1116
1117 (define-setf-expander values (&rest places &environment env)
1118 (collect ((setters) (getters))
1119 (let ((all-dummies '())
1120 (all-vals '())
1121 (newvals '()))
1122 (dolist (place places)
1123 (multiple-value-bind (dummies vals newval setter getter)
1124 (get-setf-expansion place env)
1125 (setf all-dummies (append all-dummies dummies))
1126 (setf all-vals (append all-vals vals))
1127 (setf newvals (append newvals newval))
1128 (setters setter)
1129 (getters getter)))
1130 (values all-dummies all-vals newvals
1131 `(values ,@(setters)) `(values ,@(getters))))))
1132
1133
1134 ;;;; CASE, TYPECASE, & Friends.
1135
1136 (eval-when (compile load eval)
1137
1138 ;;; CASE-BODY returns code for all the standard "case" macros. Name is the
1139 ;;; macro name, and keyform is the thing to case on. Multi-p indicates whether
1140 ;;; a branch may fire off a list of keys; otherwise, a key that is a list is
1141 ;;; interpreted in some way as a single key. When multi-p, test is applied to
1142 ;;; the value of keyform and each key for a given branch; otherwise, test is
1143 ;;; applied to the value of keyform and the entire first element, instead of
1144 ;;; each part, of the case branch. When errorp, no t or otherwise branch is
1145 ;;; permitted, and an ERROR form is generated. When proceedp, it is an error
1146 ;;; to omit errorp, and the ERROR form generated is executed within a
1147 ;;; RESTART-CASE allowing keyform to be set and retested.
1148 ;;;
1149 (defun case-body (name keyform cases multi-p test errorp proceedp)
1150 (let ((keyform-value (gensym))
1151 (clauses ())
1152 (keys ()))
1153 (dolist (case cases)
1154 (cond ((atom case)
1155 (error "~S -- Bad clause in ~S." case name))
1156 ((memq (car case) '(t otherwise))
1157 (if errorp
1158 (error "No default clause allowed in ~S: ~S" name case)
1159 (push `(t nil ,@(rest case)) clauses)))
1160 ((and multi-p (listp (first case)))
1161 (setf keys (append (first case) keys))
1162 (push `((or ,@(mapcar #'(lambda (key)
1163 `(,test ,keyform-value ',key))
1164 (first case)))
1165 nil ,@(rest case))
1166 clauses))
1167 (t
1168 (push (first case) keys)
1169 (push `((,test ,keyform-value
1170 ',(first case)) nil ,@(rest case)) clauses))))
1171 (case-body-aux name keyform keyform-value clauses keys errorp proceedp
1172 `(,(if multi-p 'member 'or) ,@keys))))
1173
1174 ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled all the
1175 ;;; cases. Note: it is not necessary that the resulting code signal
1176 ;;; case-failure conditions, but that's what KMP's prototype code did. We call
1177 ;;; CASE-BODY-ERROR, because of how closures are compiled. RESTART-CASE has
1178 ;;; forms with closures that the compiler causes to be generated at the top of
1179 ;;; any function using the case macros, regardless of whether they are needed.
1180 ;;;
1181 (defun case-body-aux (name keyform keyform-value clauses keys
1182 errorp proceedp expected-type)
1183 (if proceedp
1184 (let ((block (gensym))
1185 (again (gensym)))
1186 `(let ((,keyform-value ,keyform))
1187 (block ,block
1188 (tagbody
1189 ,again
1190 (return-from
1191 ,block
1192 (cond ,@(nreverse clauses)
1193 (t
1194 (setf ,keyform-value
1195 (setf ,keyform
1196 (case-body-error
1197 ',name ',keyform ,keyform-value
1198 ',expected-type ',keys)))
1199 (go ,again))))))))
1200 `(let ((,keyform-value ,keyform))
1201 ,keyform-value ; prevent warnings when key not used eg (case key (t))
1202 (cond
1203 ,@(nreverse clauses)
1204 ,@(if errorp
1205 `((t (error 'conditions::case-failure
1206 :name ',name
1207 :datum ,keyform-value
1208 :expected-type ',expected-type
1209 :possibilities ',keys))))))))
1210
1211 ); eval-when
1212
1213 (defun case-body-error (name keyform keyform-value expected-type keys)
1214 (restart-case
1215 (error 'conditions::case-failure
1216 :name name
1217 :datum keyform-value
1218 :expected-type expected-type
1219 :possibilities keys)
1220 (store-value (value)
1221 :report (lambda (stream)
1222 (format stream "Supply a new value for ~S." keyform))
1223 :interactive read-evaluated-form
1224 value)))
1225
1226
1227 (defmacro case (keyform &body cases)
1228 "CASE Keyform {({(Key*) | Key} Form*)}*
1229 Evaluates the Forms in the first clause with a Key EQL to the value of
1230 Keyform. If a singleton key is T then the clause is a default clause."
1231 (case-body 'case keyform cases t 'eql nil nil))
1232
1233 (defmacro ccase (keyform &body cases)
1234 "CCASE Keyform {({(Key*) | Key} Form*)}*
1235 Evaluates the Forms in the first clause with a Key EQL to the value of
1236 Keyform. If none of the keys matches then a correctable error is
1237 signalled."
1238 (case-body 'ccase keyform cases t 'eql t t))
1239
1240 (defmacro ecase (keyform &body cases)
1241 "ECASE Keyform {({(Key*) | Key} Form*)}*
1242 Evaluates the Forms in the first clause with a Key EQL to the value of
1243 Keyform. If none of the keys matches then an error is signalled."
1244 (case-body 'ecase keyform cases t 'eql t nil))
1245
1246 (defmacro typecase (keyform &body cases)
1247 "TYPECASE Keyform {(Type Form*)}*
1248 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
1249 is true."
1250 (case-body 'typecase keyform cases nil 'typep nil nil))
1251
1252 (defmacro ctypecase (keyform &body cases)
1253 "CTYPECASE Keyform {(Type Form*)}*
1254 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
1255 is true. If no form is satisfied then a correctable error is signalled."
1256 (case-body 'ctypecase keyform cases nil 'typep t t))
1257
1258 (defmacro etypecase (keyform &body cases)
1259 "ETYPECASE Keyform {(Type Form*)}*
1260 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
1261 is true. If no form is satisfied then an error is signalled."
1262 (case-body 'etypecase keyform cases nil 'typep t nil))
1263
1264
1265 ;;;; ASSERT and CHECK-TYPE.
1266
1267 ;;; ASSERT is written this way, to call ASSERT-ERROR, because of how closures
1268 ;;; are compiled. RESTART-CASE has forms with closures that the compiler
1269 ;;; causes to be generated at the top of any function using ASSERT, regardless
1270 ;;; of whether they are needed.
1271 ;;;
1272 (defmacro assert (test-form &optional places datum &rest arguments)
1273 "Signals an error if the value of test-form is nil. Continuing from this
1274 error using the CONTINUE restart will allow the user to alter the value of
1275 some locations known to SETF, starting over with test-form. Returns nil."
1276 `(loop
1277 (when ,test-form (return nil))
1278 (assert-error ',test-form ',places ,datum ,@arguments)
1279 ,@(mapcar #'(lambda (place)
1280 `(setf ,place (assert-prompt ',place ,place)))
1281 places)))
1282
1283 (defun assert-error (assertion places datum &rest arguments)
1284 (let ((cond (if datum
1285 (conditions::coerce-to-condition
1286 datum arguments
1287 'simple-error 'error)
1288 (make-condition 'simple-error
1289 :format-control "The assertion ~S failed."
1290 :format-arguments (list assertion)))))
1291 (restart-case (error cond)
1292 (continue ()
1293 :report (lambda (stream) (assert-report places stream))
1294 nil))))
1295
1296
1297 (defun assert-report (names stream)
1298 (format stream "Retry assertion")
1299 (if names
1300 (format stream " with new value~P for ~{~S~^, ~}."
1301 (length names) names)
1302 (format stream ".")))
1303
1304 (defun assert-prompt (name value)
1305 (cond ((y-or-n-p "The old value of ~S is ~S.~
1306 ~%Do you want to supply a new value? "
1307 name value)
1308 (format *query-io* "~&Type a form to be evaluated:~%")
1309 (flet ((read-it () (eval (read *query-io*))))
1310 (if (symbolp name) ;help user debug lexical variables
1311 (progv (list name) (list value) (read-it))
1312 (read-it))))
1313 (t value)))
1314
1315
1316 ;;; CHECK-TYPE is written this way, to call CHECK-TYPE-ERROR, because of how
1317 ;;; closures are compiled. RESTART-CASE has forms with closures that the
1318 ;;; compiler causes to be generated at the top of any function using
1319 ;;; CHECK-TYPE, regardless of whether they are needed. Because it would be
1320 ;;; nice if this were cheap to use, and some things can't afford this excessive
1321 ;;; consing (e.g., READ-CHAR), we bend backwards a little.
1322 ;;;
1323
1324 (defmacro check-type (place type &optional type-string)
1325 "Signals an error of type type-error if the contents of place are not of the
1326 specified type. If an error is signaled, this can only return if
1327 STORE-VALUE is invoked. It will store into place and start over."
1328 (let ((place-value (gensym)))
1329 `(loop
1330 (let ((,place-value ,place))
1331 (when (typep ,place-value ',type) (return nil))
1332 (setf ,place
1333 (check-type-error ',place ,place-value ',type ,type-string))))))
1334
1335 (defun check-type-error (place place-value type type-string)
1336 (let ((cond (if type-string
1337 (make-condition 'simple-type-error
1338 :datum place :expected-type type
1339 :format-control
1340 "The value of ~S is ~S, which is not ~A."
1341 :format-arguments
1342 (list place place-value type-string))
1343 (make-condition 'simple-type-error
1344 :datum place :expected-type type
1345 :format-control
1346 "The value of ~S is ~S, which is not of type ~S."
1347 :format-arguments
1348 (list place place-value type)))))
1349 (restart-case (error cond)
1350 (store-value (value)
1351 :report (lambda (stream)
1352 (format stream "Supply a new value of ~S."
1353 place))
1354 :interactive read-evaluated-form
1355 value))))
1356
1357 ;;; READ-EVALUATED-FORM is used as the interactive method for restart cases
1358 ;;; setup by the Common Lisp "casing" (e.g., CCASE and CTYPECASE) macros
1359 ;;; and by CHECK-TYPE.
1360 ;;;
1361 (defun read-evaluated-form ()
1362 (format *query-io* "~&Type a form to be evaluated:~%")
1363 (list (eval (read *query-io*))))
1364
1365
1366 ;;;; With-XXX
1367 (defmacro with-open-file ((var &rest open-args) &body (forms decls))
1368 "Bindspec is of the form (Stream File-Name . Options). The file whose
1369 name is File-Name is opened using the Options and bound to the variable
1370 Stream. If the call to open is unsuccessful, the forms are not
1371 evaluated. The Forms are executed, and when they
1372 terminate, normally or otherwise, the file is closed."
1373 (let ((abortp (gensym)))
1374 `(let ((,var (open ,@open-args))
1375 (,abortp t))
1376 ,@decls
1377 (unwind-protect
1378 (multiple-value-prog1
1379 (progn ,@forms)
1380 (setq ,abortp nil))
1381 (when ,var
1382 (close ,var :abort ,abortp))))))
1383
1384
1385 (defmacro with-open-stream ((var stream) &body (forms decls))
1386 "The form stream should evaluate to a stream. VAR is bound
1387 to the stream and the forms are evaluated as an implicit
1388 progn. The stream is closed upon exit."
1389 (let ((abortp (gensym)))
1390 `(let ((,var ,stream)
1391 (,abortp t))
1392 ,@decls
1393 (unwind-protect
1394 (multiple-value-prog1
1395 (progn ,@forms)
1396 (setq ,abortp nil))
1397 (when ,var
1398 (close ,var :abort ,abortp))))))
1399
1400
1401 (defmacro with-input-from-string ((var string &key index start end) &body (forms decls))
1402 "Binds the Var to an input stream that returns characters from String and
1403 executes the body. See manual for details."
1404 ;; The once-only inhibits compiler note for unreachable code when 'end' is true.
1405 (once-only ((string string))
1406 `(let ((,var
1407 ,(cond ((null end)
1408 `(make-string-input-stream ,string ,(or start 0)))
1409 ((symbolp end)
1410 `(if ,end
1411 (make-string-input-stream ,string ,(or start 0) ,end)
1412 (make-string-input-stream ,string ,(or start 0))))
1413 (t
1414 `(make-string-input-stream ,string ,(or start 0) ,end)))))
1415 ,@decls
1416 (unwind-protect
1417 (progn ,@forms)
1418 (close ,var)
1419 ,@(if index `((setf ,index (string-input-stream-current ,var))))))))
1420
1421
1422 (defmacro with-output-to-string ((var &optional string) &body (forms decls))
1423 "If *string* is specified, it must be a string with a fill pointer;
1424 the output is incrementally appended to the string (as if by use of
1425 VECTOR-PUSH-EXTEND)."
1426 (if string
1427 `(let ((,var (make-fill-pointer-output-stream ,string)))
1428 ,@decls
1429 (unwind-protect
1430 (progn ,@forms)
1431 (close ,var)))
1432 `(let ((,var (make-string-output-stream)))
1433 ,@decls
1434 (unwind-protect
1435 (progn ,@forms)
1436 (close ,var))
1437 (get-output-stream-string ,var))))
1438
1439
1440 ;;;; Iteration macros:
1441
1442 (defmacro dotimes ((var count &optional (result nil)) &body body)
1443 (cond ((numberp count)
1444 `(do ((,var 0 (1+ ,var)))
1445 ((>= ,var ,count) ,result)
1446 (declare (type unsigned-byte ,var))
1447 ,@body))
1448 (t (let ((v1 (gensym)))
1449 `(do ((,var 0 (1+ ,var)) (,v1 ,count))
1450 ((>= ,var ,v1) ,result)
1451 (declare (type unsigned-byte ,var))
1452 ,@body)))))
1453
1454
1455 ;;; We repeatedly bind the var instead of setting it so that we never give the
1456 ;;; var a random value such as NIL (which might conflict with a declaration).
1457 ;;; If there is a result form, we introduce a gratitous binding of the variable
1458 ;;; to NIL w/o the declarations, then evaluate the result form in that
1459 ;;; environment. We spuriously reference the gratuitous variable, since we
1460 ;;; don't want to use IGNORABLE on what might be a special var.
1461 ;;;
1462 (defmacro dolist ((var list &optional (result nil)) &body body)
1463 (let ((n-list (gensym)))
1464 `(do ((,n-list ,list (cdr ,n-list)))
1465 ((endp ,n-list)
1466 ,@(if result
1467 `((let ((,var nil))
1468 ,var
1469 ,result))
1470 '(nil)))
1471 (let ((,var (car ,n-list)))
1472 ,@body))))
1473
1474
1475 (defmacro do (varlist endlist &body (body decls))
1476 "DO ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
1477 Iteration construct. Each Var is initialized in parallel to the value of the
1478 specified Init form. On subsequent iterations, the Vars are assigned the
1479 value of the Step form (if any) in paralell. The Test is evaluated before
1480 each evaluation of the body Forms. When the Test is true, the Exit-Forms
1481 are evaluated as a PROGN, with the result being the value of the DO. A block
1482 named NIL is established around the entire expansion, allowing RETURN to be
1483 used as an laternate exit mechanism."
1484
1485 (do-do-body varlist endlist body decls 'let 'psetq 'do nil))
1486
1487
1488 (defmacro do* (varlist endlist &body (body decls))
1489 "DO* ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
1490 Iteration construct. Each Var is initialized sequentially (like LET*) to the
1491 value of the specified Init form. On subsequent iterations, the Vars are
1492 sequentially assigned the value of the Step form (if any). The Test is
1493 evaluated before each evaluation of the body Forms. When the Test is true,
1494 the Exit-Forms are evaluated as a PROGN, with the result being the value
1495 of the DO. A block named NIL is established around the entire expansion,
1496 allowing RETURN to be used as an laternate exit mechanism."
1497 (do-do-body varlist endlist body decls 'let* 'setq 'do* nil))
1498
1499
1500 ;;;; Miscellaneous macros:
1501
1502 (defmacro locally (&rest forms)
1503 "A form providing a container for locally-scoped variables."
1504 `(let () ,@forms))
1505
1506 (defmacro psetq (&rest pairs)
1507 (do ((lets nil)
1508 (setqs nil)
1509 (pairs pairs (cddr pairs)))
1510 ((atom (cdr pairs))
1511 `(let ,(nreverse lets) (setq ,@(nreverse setqs)) nil))
1512 (let ((gen (gensym)))
1513 (push `(,gen ,(cadr pairs)) lets)
1514 (push (car pairs) setqs)
1515 (push gen setqs))))
1516
1517 ;;; LAMBDA -- from the ANSI spec.
1518 ;;;
1519 (defmacro lambda (&whole form &rest bvl-decls-and-body)
1520 (declare (ignore bvl-decls-and-body))
1521 `#',form)
1522
1523
1524
1525 ;;;; With-Compilation-Unit:
1526
1527 ;;; True if we are within a With-Compilation-Unit form, which normally causes
1528 ;;; nested uses to be NOOPS.
1529 ;;;
1530 (defvar *in-compilation-unit* nil)
1531
1532 ;;; Count of the number of compilation units dynamically enclosed by the
1533 ;;; current active WITH-COMPILATION-UNIT that were unwound out of.
1534 ;;;
1535 (defvar *aborted-compilation-units*)
1536
1537 (declaim (special c::*context-declarations*))
1538
1539
1540 ;;; EVALUATE-DECLARATION-CONTEXT -- Internal
1541 ;;;
1542 ;;; Recursively descend the context form, returning true if this subpart
1543 ;;; matches the specified context.
1544 ;;;
1545 (defun evaluate-declaration-context (context name parent)
1546 (let* ((base (if (and (consp name) (consp (cdr name)))
1547 (cadr name)
1548 name))
1549 (package (and (symbolp base) (symbol-package base))))
1550 (if (atom context)
1551 (multiple-value-bind (ignore how)
1552 (if package
1553 (find-symbol (symbol-name base) package)
1554 (values nil nil))
1555 (declare (ignore ignore))
1556 (case context
1557 (:internal (eq how :internal))
1558 (:external (eq how :external))
1559 (:uninterned (and (symbolp base) (not package)))
1560 (:anonymous (not name))
1561 (:macro (eq parent 'defmacro))
1562 (:function (member parent '(defun labels flet function)))
1563 (:global (member parent '(defun defmacro function)))
1564 (:local (member parent '(labels flet)))
1565 (t
1566 (error "Unknown declaration context: ~S." context))))
1567 (case (first context)
1568 (:or
1569 (loop for x in (rest context)
1570 thereis (evaluate-declaration-context x name parent)))
1571 (:and
1572 (loop for x in (rest context)
1573 always (evaluate-declaration-context x name parent)))
1574 (:not
1575 (evaluate-declaration-context (second context) name parent))
1576 (:member
1577 (member name (rest context) :test #'equal))
1578 (:match
1579 (let ((name (concatenate 'string "$" (string base) "$")))
1580 (loop for x in (rest context)
1581 thereis (search (string x) name))))
1582 (:package
1583 (and package
1584 (loop for x in (rest context)
1585 thereis (eq (find-package (string x)) package))))
1586 (t
1587 (error "Unknown declaration context: ~S." context))))))
1588
1589
1590 ;;; PROCESS-CONTEXT-DECLARATIONS -- Internal
1591 ;;;
1592 ;;; Given a list of context declaration specs, return a new value for
1593 ;;; C::*CONTEXT-DECLARATIONS*.
1594 ;;;
1595 (defun process-context-declarations (decls)
1596 (append
1597 (mapcar
1598 #'(lambda (decl)
1599 (unless (>= (length decl) 2)
1600 (error "Context declaration spec should have context and at ~
1601 least one DECLARE form:~% ~S" decl))
1602 #'(lambda (name parent)
1603 (when (evaluate-declaration-context (first decl) name parent)
1604 (rest decl))))
1605 decls)
1606 c::*context-declarations*))
1607
1608
1609 ;;; With-Compilation-Unit -- Public
1610 ;;;
1611 (defmacro with-compilation-unit (options &body body)
1612 "WITH-COMPILATION-UNIT ({Key Value}*) Form*
1613 This form affects compilations that take place within its dynamic extent. It
1614 is intended to be wrapped around the compilation of all files in the same
1615 system. These keywords are defined:
1616 :OVERRIDE Boolean-Form
1617 One of the effects of this form is to delay undefined warnings
1618 until the end of the form, instead of giving them at the end of each
1619 compilation. If OVERRIDE is NIL (the default), then the outermost
1620 WITH-COMPILATION-UNIT form grabs the undefined warnings. Specifying
1621 OVERRIDE true causes that form to grab any enclosed warnings, even if
1622 it is enclosed by another WITH-COMPILATION-UNIT.
1623 :OPTIMIZE Decl-Form
1624 Decl-Form should evaluate to an OPTIMIZE declaration specifier. This
1625 declaration changes the `global' policy for compilations within the
1626 body.
1627 :OPTIMIZE-INTERFACE Decl-Form
1628 Like OPTIMIZE, except that it specifies the value of the CMU extension
1629 OPTIMIZE-INTERFACE policy (which controls argument type and syntax
1630 checking.)
1631 :CONTEXT-DECLARATIONS List-of-Context-Decls-Form
1632 This is a CMU extension which allows compilation to be controlled
1633 by pattern matching on the context in which a definition appears. The
1634 argument should evaluate to a list of lists of the form:
1635 (Context-Spec Declare-Form+)
1636 In the indicated context, the specified declare forms are inserted at
1637 the head of each definition. The declare forms for all contexts that
1638 match are appended together, with earlier declarations getting
1639 predecence over later ones. A simple example:
1640 :context-declarations
1641 '((:external (declare (optimize (safety 2)))))
1642 This will cause all functions that are named by external symbols to be
1643 compiled with SAFETY 2. The full syntax of context specs is:
1644 :INTERNAL, :EXTERNAL
1645 True if the symbols is internal (external) in its home package.
1646 :UNINTERNED
1647 True if the symbol has no home package.
1648 :ANONYMOUS
1649 True if the function doesn't have any interesting name (not
1650 DEFMACRO, DEFUN, LABELS or FLET).
1651 :MACRO, :FUNCTION
1652 :MACRO is a global (DEFMACRO) macro. :FUNCTION is anything else.
1653 :LOCAL, :GLOBAL
1654 :LOCAL is a LABELS or FLET. :GLOBAL is anything else.
1655 (:OR Context-Spec*)
1656 True in any specified context.
1657 (:AND Context-Spec*)
1658 True only when all specs are true.
1659 (:NOT Context-Spec)
1660 True when the spec is false.
1661 (:MEMBER Name*)
1662 True when the name is one of these names (EQUAL test.)
1663 (:MATCH Pattern*)
1664 True when any of the patterns is a substring of the name. The name
1665 is wrapped with $'s, so $FOO matches names beginning with FOO,
1666 etc."
1667 (let ((override nil)
1668 (optimize nil)
1669 (optimize-interface nil)
1670 (context-declarations nil)
1671 (n-fun (gensym))
1672 (n-abort-p (gensym)))
1673 (when (oddp (length options))
1674 (error "Odd number of key/value pairs: ~S." options))
1675 (do ((opt options (cddr opt)))
1676 ((null opt))
1677 (case (first opt)
1678 (:override
1679 (setq override (second opt)))
1680 (:optimize
1681 (setq optimize (second opt)))
1682 (:optimize-interface
1683 (setq optimize-interface (second opt)))
1684 (:context-declarations
1685 (setq context-declarations (second opt)))
1686 (t
1687 (warn "Ignoring unknown option: ~S." (first opt)))))
1688
1689 `(flet ((,n-fun ()
1690 (let (,@(when optimize
1691 `((c::*default-cookie*
1692 (c::process-optimize-declaration
1693 ,optimize c::*default-cookie*))))
1694 ,@(when optimize-interface
1695 `((c::*default-interface-cookie*
1696 (c::process-optimize-declaration
1697 ,optimize-interface
1698 c::*default-interface-cookie*))))
1699 ,@(when context-declarations
1700 `((c::*context-declarations*
1701 (process-context-declarations
1702 ,context-declarations)))))
1703 ,@body)))
1704 (if (or ,override (not *in-compilation-unit*))
1705 (let ((c::*undefined-warnings* nil)
1706 (c::*compiler-error-count* 0)
1707 (c::*compiler-warning-count* 0)
1708 (c::*compiler-note-count* 0)
1709 (*in-compilation-unit* t)
1710 (*aborted-compilation-units* 0)
1711 (,n-abort-p t))
1712 (handler-bind ((c::parse-unknown-type
1713 #'(lambda (c)
1714 (c::note-undefined-reference
1715 (c::parse-unknown-type-specifier c)
1716 :type))))
1717 (unwind-protect
1718 (multiple-value-prog1
1719 (,n-fun)
1720 (setq ,n-abort-p nil))
1721 (c::print-summary ,n-abort-p *aborted-compilation-units*))))
1722 (let ((,n-abort-p t))
1723 (unwind-protect
1724 (multiple-value-prog1
1725 (,n-fun)
1726 (setq ,n-abort-p nil))
1727 (when ,n-abort-p
1728 (incf *aborted-compilation-units*))))))))

  ViewVC Help
Powered by ViewVC 1.1.5