0.6.8.9:
[sbcl.git] / src / code / macros.lisp
1 ;;;; lots of basic macros for the target SBCL
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!IMPL")
13 \f
14 ;;;; ASSERT and CHECK-TYPE
15
16 ;;; ASSERT is written this way, to call ASSERT-ERROR, because of how
17 ;;; closures are compiled. RESTART-CASE has forms with closures that
18 ;;; the compiler causes to be generated at the top of any function
19 ;;; using RESTART-CASE, regardless of whether they are needed. Thus if
20 ;;; we just wrapped a RESTART-CASE around the call to ERROR, we'd have
21 ;;; to do a significant amount of work at runtime allocating and
22 ;;; deallocating the closures regardless of whether they were ever
23 ;;; needed.
24 ;;;
25 ;;; ASSERT-ERROR isn't defined until a later file because it uses the
26 ;;; macro RESTART-CASE, which isn't defined until a later file.
27 (defmacro-mundanely assert (test-form &optional places datum &rest arguments)
28   #!+sb-doc
29   "Signals an error if the value of test-form is nil. Continuing from this
30    error using the CONTINUE restart will allow the user to alter the value of
31    some locations known to SETF, starting over with test-form. Returns nil."
32   `(do () (,test-form)
33      (assert-error ',test-form ',places ,datum ,@arguments)
34      ,@(mapcar #'(lambda (place)
35                    `(setf ,place (assert-prompt ',place ,place)))
36                places)))
37
38 (defun assert-prompt (name value)
39   (cond ((y-or-n-p "The old value of ~S is ~S.~
40                   ~%Do you want to supply a new value? "
41                    name value)
42          (format *query-io* "~&Type a form to be evaluated:~%")
43          (flet ((read-it () (eval (read *query-io*))))
44            (if (symbolp name) ;help user debug lexical variables
45                (progv (list name) (list value) (read-it))
46                (read-it))))
47         (t value)))
48
49 ;;; CHECK-TYPE is written this way, to call CHECK-TYPE-ERROR, because
50 ;;; of how closures are compiled. RESTART-CASE has forms with closures
51 ;;; that the compiler causes to be generated at the top of any
52 ;;; function using RESTART-CASE, regardless of whether they are
53 ;;; needed. Because it would be nice if CHECK-TYPE were cheap to use,
54 ;;; and some things (e.g., READ-CHAR) can't afford this excessive
55 ;;; consing, we bend backwards a little.
56 ;;;
57 ;;; FIXME: In reality, this restart cruft is needed hardly anywhere in
58 ;;; the system. Write NEED and NEED-TYPE to replace ASSERT and
59 ;;; CHECK-TYPE inside the system.
60 ;;;
61 ;;; CHECK-TYPE-ERROR isn't defined until a later file because it uses
62 ;;; the macro RESTART-CASE, which isn't defined until a later file.
63 (defmacro-mundanely check-type (place type &optional type-string)
64   #!+sb-doc
65   "Signals a restartable error of type TYPE-ERROR if the value of PLACE is
66   not of the specified type. If an error is signalled and the restart is
67   used to return, the
68   return if the
69    STORE-VALUE is invoked. It will store into PLACE and start over."
70   (let ((place-value (gensym)))
71     `(do ((,place-value ,place))
72          ((typep ,place-value ',type))
73        (setf ,place
74              (check-type-error ',place ,place-value ',type ,type-string)))))
75
76 #!+high-security-support
77 (defmacro-mundanely check-type-var (place type-var &optional type-string)
78   #!+sb-doc
79   "Signals an error of type TYPE-ERROR if the contents of PLACE are not of the
80    specified type to which the TYPE-VAR evaluates. If an error is signaled,
81    this can only return if STORE-VALUE is invoked. It will store into PLACE
82    and start over."
83   (let ((place-value (gensym))
84         (type-value (gensym)))
85     `(do ((,place-value ,place)
86           (,type-value  ,type-var))
87          ((typep ,place-value ,type-value))
88        (setf ,place
89              (check-type-error ',place ,place-value ,type-value ,type-string)))))
90 \f
91 ;;;; DEFCONSTANT
92
93 (defmacro-mundanely defconstant (name value &optional documentation)
94   #!+sb-doc
95   "For defining global constants. The DEFCONSTANT says that the value
96   is constant and may be compiled into code. If the variable already has
97   a value, and this is not EQL to the init, the code is not portable
98   (undefined behavior). The third argument is an optional documentation
99   string for the variable."
100   `(eval-when (:compile-toplevel :load-toplevel :execute)
101      (sb!c::%defconstant ',name ,value ',documentation)))
102
103 ;;; (to avoid "undefined function" warnings when cross-compiling)
104 (sb!xc:proclaim '(ftype function sb!c::%defconstant))
105
106 ;;; the guts of DEFCONSTANT
107 (defun sb!c::%defconstant (name value doc)
108   (/show "doing %DEFCONSTANT" name value doc)
109   (unless (symbolp name)
110     (error "constant name not a symbol: ~S" name))
111   (about-to-modify name)
112   (let ((kind (info :variable :kind name)))
113     (case kind
114       (:constant
115        ;; Note 1: This behavior (discouraging any non-EQL
116        ;; modification) is unpopular, but it is specified by ANSI
117        ;; (i.e. ANSI says a non-EQL change has undefined
118        ;; consequences). If people really want bindings which are
119        ;; constant in some sense other than EQL, I suggest either just
120        ;; using DEFVAR (which is usually appropriate, despite the
121        ;; un-mnemonic name), or defining something like
122        ;; SB-INT:DEFCONSTANT-EQX (which is occasionally more
123        ;; appropriate). -- WHN 2000-11-03
124        (unless (eql value
125                     (info :variable :constant-value name))
126          (cerror "Go ahead and change the value."
127                  "The constant ~S is being redefined."
128                  name)))
129       (:global
130        ;; (This is OK -- undefined variables are of this kind. So we
131        ;; don't warn or error or anything, just fall through.)
132        )
133       (t (warn "redefining ~(~A~) ~S to be a constant" kind name))))
134   (when doc
135     (setf (fdocumentation name 'variable) doc))
136   (setf (symbol-value name) value)
137   (setf (info :variable :kind name) :constant)
138   (setf (info :variable :constant-value name) value)
139   name)
140 \f
141 ;;;; DEFINE-COMPILER-MACRO
142
143 ;;; FIXME: The logic here for handling compiler macros named (SETF
144 ;;; FOO) was added after the fork from SBCL, is not well tested, and
145 ;;; may conflict with subtleties of the ANSI standard. E.g. section
146 ;;; "3.2.2.1 Compiler Macros" says that creating a lexical binding for
147 ;;; a function name shadows a compiler macro, and it's not clear that
148 ;;; that works with this version. It should be tested.
149 (defmacro-mundanely define-compiler-macro (name lambda-list &body body)
150   #!+sb-doc
151   "Define a compiler-macro for NAME."
152   (let ((whole (gensym "WHOLE-"))
153         (environment (gensym "ENV-")))
154     (multiple-value-bind (body local-decs doc)
155         (parse-defmacro lambda-list whole body name 'define-compiler-macro
156                         :environment environment)
157       (let ((def `(lambda (,whole ,environment)
158                     ,@local-decs
159                     (block ,(function-name-block-name name)
160                       ,body))))
161         `(sb!c::%define-compiler-macro ',name #',def ',lambda-list ,doc)))))
162 (defun sb!c::%define-compiler-macro (name definition lambda-list doc)
163   ;; FIXME: Why does this have to be an interpreted function? Shouldn't
164   ;; it get compiled?
165   (assert (sb!eval:interpreted-function-p definition))
166   (setf (sb!eval:interpreted-function-name definition)
167         (format nil "DEFINE-COMPILER-MACRO ~S" name))
168   (setf (sb!eval:interpreted-function-arglist definition) lambda-list)
169   (sb!c::%%define-compiler-macro name definition doc))
170 (defun sb!c::%%define-compiler-macro (name definition doc)
171   (setf (sb!xc:compiler-macro-function name) definition)
172   ;; FIXME: Add support for (SETF FDOCUMENTATION) when object is a list
173   ;; and type is COMPILER-MACRO. (Until then, we have to discard any
174   ;; compiler macro documentation for (SETF FOO).)
175   (unless (listp name)
176     (setf (fdocumentation name 'compiler-macro) doc))
177   name)
178 \f
179 ;;;; CASE, TYPECASE, and friends
180
181 (eval-when (:compile-toplevel :load-toplevel :execute)
182
183 ;;; CASE-BODY (interface)
184 ;;;
185 ;;; CASE-BODY returns code for all the standard "case" macros. Name is
186 ;;; the macro name, and keyform is the thing to case on. Multi-p
187 ;;; indicates whether a branch may fire off a list of keys; otherwise,
188 ;;; a key that is a list is interpreted in some way as a single key.
189 ;;; When multi-p, test is applied to the value of keyform and each key
190 ;;; for a given branch; otherwise, test is applied to the value of
191 ;;; keyform and the entire first element, instead of each part, of the
192 ;;; case branch. When errorp, no t or otherwise branch is permitted,
193 ;;; and an ERROR form is generated. When proceedp, it is an error to
194 ;;; omit errorp, and the ERROR form generated is executed within a
195 ;;; RESTART-CASE allowing keyform to be set and retested.
196 (defun case-body (name keyform cases multi-p test errorp proceedp needcasesp)
197   (unless (or cases (not needcasesp))
198     (warn "no clauses in ~S" name))
199   (let ((keyform-value (gensym))
200         (clauses ())
201         (keys ()))
202     (dolist (case cases)
203       (cond ((atom case)
204              (error "~S -- Bad clause in ~S." case name))
205             ((memq (car case) '(t otherwise))
206              (if errorp
207                  (error 'simple-program-error
208                         :format-control "No default clause is allowed in ~S: ~S"
209                         :format-arguments (list name case))
210                  (push `(t nil ,@(rest case)) clauses)))
211             ((and multi-p (listp (first case)))
212              (setf keys (append (first case) keys))
213              (push `((or ,@(mapcar #'(lambda (key)
214                                        `(,test ,keyform-value ',key))
215                                    (first case)))
216                      nil ,@(rest case))
217                    clauses))
218             (t
219              (push (first case) keys)
220              (push `((,test ,keyform-value
221                             ',(first case)) nil ,@(rest case)) clauses))))
222     (case-body-aux name keyform keyform-value clauses keys errorp proceedp
223                    `(,(if multi-p 'member 'or) ,@keys))))
224
225
226 ;;; MNA: typecase-implicit-declarations patch
227
228 ;;; TYPECASE-BODY (interface)
229 ;;;
230 ;;; TYPECASE-BODY returns code for all the standard "typecase" macros.
231 ;;; Name is the macro name, and keyform is the thing to case on.
232 ;;; test is applied to the value of keyform and the entire first element,
233 ;;; instead of each part, of the case branch.
234 ;;; When errorp, no t or otherwise branch is permitted,
235 ;;; and an ERROR form is generated. When proceedp, it is an error to
236 ;;; omit errorp, and the ERROR form generated is executed within a
237 ;;; RESTART-CASE allowing keyform to be set and retested.
238 (defun typecase-body (name keyform cases test errorp proceedp needcasesp)
239   (unless (or cases (not needcasesp))
240     (warn "no clauses in ~S" name))
241   (let* ((keyform-symbol-p (symbolp keyform))
242          (keyform-value (unless keyform-symbol-p                         
243                           (gensym)))
244          (clauses ())
245          (keys ()))
246     (dolist (case cases)
247       (cond ((atom case)
248              (error "~S -- Bad clause in ~S." case name))
249             ((memq (car case) '(t otherwise))
250              (if errorp
251                  (error 'simple-program-error
252                         :format-control "No default clause is allowed in ~S: ~S"
253                         :format-arguments (list name case))
254                (push `(t nil ,@(rest case)) clauses)))
255             (t
256               (push (first case) keys)
257               (push (if keyform-symbol-p
258                       `((,test ,keyform ',(first case)) nil
259                         (locally
260                           ;; this will cause a compiler-warning ... disabled
261                           ;; for now.
262                           ;; (declare (type ,(first case) ,keyform))
263                           ,@(rest case)))
264                       `((,test ,keyform-value ',(first case)) nil
265                         ,@(rest case)))
266                     clauses))))
267     (if keyform-symbol-p
268       (typecase-symbol-body-aux name keyform clauses keys errorp proceedp
269                                 (cons 'or keys))
270       (case-body-aux name keyform keyform-value clauses keys errorp proceedp
271                      (cons 'or keys)))))
272
273 ;;; TYPECASE-SYMBOL-BODY-AUX provides the expansion once CASE-BODY has groveled
274 ;;; all the cases, iff keyform is a symbol.
275 (defun typecase-symbol-body-aux (name keyform clauses keys
276                                       errorp proceedp expected-type)
277   (if proceedp
278       (let ((block (gensym))
279             (again (gensym)))
280         `(block ,block
281           (tagbody
282             ,again
283             (return-from
284               ,block
285               (cond ,@(nreverse clauses)
286                     (t
287                       (setf ,keyform
288                               (case-body-error
289                                ',name ',keyform ,keyform
290                                ',expected-type ',keys)))
291                     (go ,again))))))
292     `(progn
293       (cond
294         ,@(nreverse clauses)
295         ,@(if errorp
296               `((t (error 'sb!conditions::case-failure
297                     :name ',name
298                     :datum ,keyform
299                     :expected-type ',expected-type
300                     :possibilities ',keys))))))))
301
302 ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled
303 ;;; all the cases. Note: it is not necessary that the resulting code
304 ;;; signal case-failure conditions, but that's what KMP's prototype
305 ;;; code did. We call CASE-BODY-ERROR, because of how closures are
306 ;;; compiled. RESTART-CASE has forms with closures that the compiler
307 ;;; causes to be generated at the top of any function using the case
308 ;;; macros, regardless of whether they are needed.
309 ;;;
310 ;;; The CASE-BODY-ERROR function is defined later, when the
311 ;;; RESTART-CASE macro has been defined.
312 (defun case-body-aux (name keyform keyform-value clauses keys
313                       errorp proceedp expected-type)
314   (if proceedp
315       (let ((block (gensym))
316             (again (gensym)))
317         `(let ((,keyform-value ,keyform))
318            (block ,block
319              (tagbody
320               ,again
321               (return-from
322                ,block
323                (cond ,@(nreverse clauses)
324                      (t
325                       (setf ,keyform-value
326                             (setf ,keyform
327                                   (case-body-error
328                                    ',name ',keyform ,keyform-value
329                                    ',expected-type ',keys)))
330                       (go ,again))))))))
331       `(let ((,keyform-value ,keyform))
332          (declare (ignorable ,keyform-value)) ; e.g. (CASE KEY (T))
333          (cond
334           ,@(nreverse clauses)
335           ,@(if errorp
336                 `((t (error 'sb!conditions::case-failure
337                             :name ',name
338                             :datum ,keyform-value
339                             :expected-type ',expected-type
340                             :possibilities ',keys))))))))
341 ) ; EVAL-WHEN
342
343 (defmacro-mundanely case (keyform &body cases)
344   #!+sb-doc
345   "CASE Keyform {({(Key*) | Key} Form*)}*
346   Evaluates the Forms in the first clause with a Key EQL to the value of
347   Keyform. If a singleton key is T then the clause is a default clause."
348   (case-body 'case keyform cases t 'eql nil nil nil))
349
350 (defmacro-mundanely ccase (keyform &body cases)
351   #!+sb-doc
352   "CCASE Keyform {({(Key*) | Key} Form*)}*
353   Evaluates the Forms in the first clause with a Key EQL to the value of
354   Keyform. If none of the keys matches then a correctable error is
355   signalled."
356   (case-body 'ccase keyform cases t 'eql t t t))
357
358 (defmacro-mundanely ecase (keyform &body cases)
359   #!+sb-doc
360   "ECASE Keyform {({(Key*) | Key} Form*)}*
361   Evaluates the Forms in the first clause with a Key EQL to the value of
362   Keyform. If none of the keys matches then an error is signalled."
363   (case-body 'ecase keyform cases t 'eql t nil t))
364
365 (defmacro-mundanely typecase (keyform &body cases)
366   #!+sb-doc
367   "TYPECASE Keyform {(Type Form*)}*
368   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
369   is true."
370   (typecase-body 'typecase keyform cases 'typep nil nil nil))
371
372 (defmacro-mundanely ctypecase (keyform &body cases)
373   #!+sb-doc
374   "CTYPECASE Keyform {(Type Form*)}*
375   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
376   is true. If no form is satisfied then a correctable error is signalled."
377   (typecase-body 'ctypecase keyform cases 'typep t t t))
378
379 (defmacro-mundanely etypecase (keyform &body cases)
380   #!+sb-doc
381   "ETYPECASE Keyform {(Type Form*)}*
382   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
383   is true. If no form is satisfied then an error is signalled."
384   (typecase-body 'etypecase keyform cases 'typep t nil t))
385 \f
386 ;;;; WITH-FOO i/o-related macros
387
388 (defmacro-mundanely with-open-stream ((var stream) &body forms-decls)
389   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
390     (let ((abortp (gensym)))
391       `(let ((,var ,stream)
392              (,abortp t))
393          ,@decls
394          (unwind-protect
395              (multiple-value-prog1
396               (progn ,@forms)
397               (setq ,abortp nil))
398            (when ,var
399              (close ,var :abort ,abortp)))))))
400
401 (defmacro-mundanely with-open-file ((stream filespec &rest options)
402                                     &body body)
403   `(with-open-stream (,stream (open ,filespec ,@options))
404      ,@body))
405
406 (defmacro-mundanely with-input-from-string ((var string &key index start end)
407                                             &body forms-decls)
408   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
409     ;; The ONCE-ONLY inhibits compiler note for unreachable code when
410     ;; END is true.
411     (once-only ((string string))
412       `(let ((,var
413               ,(cond ((null end)
414                       `(make-string-input-stream ,string ,(or start 0)))
415                      ((symbolp end)
416                       `(if ,end
417                            (make-string-input-stream ,string
418                                                      ,(or start 0)
419                                                      ,end)
420                            (make-string-input-stream ,string
421                                                      ,(or start 0))))
422                      (t
423                       `(make-string-input-stream ,string
424                                                  ,(or start 0)
425                                                  ,end)))))
426          ,@decls
427          (unwind-protect
428              (progn ,@forms)
429            (close ,var)
430            ,@(when index
431                `((setf ,index (string-input-stream-current ,var)))))))))
432
433 (defmacro-mundanely with-output-to-string ((var &optional string)
434                                            &body forms-decls)
435   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
436     (if string
437       `(let ((,var (make-fill-pointer-output-stream ,string)))
438          ,@decls
439          (unwind-protect
440              (progn ,@forms)
441            (close ,var)))
442       `(let ((,var (make-string-output-stream)))
443          ,@decls
444          (unwind-protect
445              (progn ,@forms)
446            (close ,var))
447          (get-output-stream-string ,var)))))
448 \f
449 ;;;; miscellaneous macros
450
451 (defmacro-mundanely nth-value (n form)
452   #!+sb-doc
453   "Evaluates FORM and returns the Nth value (zero based). This involves no
454   consing when N is a trivial constant integer."
455   (if (integerp n)
456       (let ((dummy-list nil)
457             (keeper (gensym "KEEPER-")))
458         ;; We build DUMMY-LIST, a list of variables to bind to useless
459         ;; values, then we explicitly IGNORE those bindings and return
460         ;; KEEPER, the only thing we're really interested in right now.
461         (dotimes (i n)
462           (push (gensym "IGNORE-") dummy-list))
463         `(multiple-value-bind (,@dummy-list ,keeper) ,form
464            (declare (ignore ,@dummy-list))
465            ,keeper))
466       (once-only ((n n))
467         `(case (the fixnum ,n)
468            (0 (nth-value 0 ,form))
469            (1 (nth-value 1 ,form))
470            (2 (nth-value 2 ,form))
471            (t (nth (the fixnum ,n) (multiple-value-list ,form)))))))
472
473 (defmacro-mundanely declaim (&rest specs)
474   #!+sb-doc
475   "DECLAIM Declaration*
476   Do a declaration or declarations for the global environment."
477   #-sb-xc-host
478   `(eval-when (:compile-toplevel :load-toplevel :execute)
479      ,@(mapcar #'(lambda (x)
480                    `(sb!xc:proclaim ',x))
481                specs))
482   ;; KLUDGE: The definition above doesn't work in the cross-compiler,
483   ;; because UNCROSS translates SB!XC:PROCLAIM into CL:PROCLAIM before
484   ;; the form gets executed. Instead, we have to explicitly do the
485   ;; proclamation at macroexpansion time. -- WHN ca. 19990810
486   ;;
487   ;; FIXME: Maybe we don't need this special treatment any more now
488   ;; that we're using DEFMACRO-MUNDANELY instead of DEFMACRO?
489   #+sb-xc-host (progn
490                  (mapcar #'sb!xc:proclaim specs)
491                  `(progn
492                     ,@(mapcar #'(lambda (x)
493                                   `(sb!xc:proclaim ',x))
494                               specs))))
495
496 (defmacro-mundanely print-unreadable-object ((object stream
497                                               &key type identity)
498                                              &body body)
499   `(%print-unreadable-object ,object ,stream ,type ,identity
500                              ,(if body
501                                   `#'(lambda () ,@body)
502                                   nil)))