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

Contents of /src/code/macros.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.5