0.6.11.26:
[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. DEFCONSTANT says that the value is
96   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 ;;; the guts of DEFCONSTANT
104 (defun sb!c::%defconstant (name value doc)
105   (unless (symbolp name)
106     (error "The constant name is not a symbol: ~S" name))
107   (about-to-modify name)
108   (let ((kind (info :variable :kind name)))
109     (case kind
110       (:constant
111        ;; Note: This behavior (discouraging any non-EQL modification)
112        ;; is unpopular, but it is specified by ANSI (i.e. ANSI says a
113        ;; non-EQL change has undefined consequences). If people really
114        ;; want bindings which are constant in some sense other than
115        ;; EQL, I suggest either just using DEFVAR (which is usually
116        ;; appropriate, despite the un-mnemonic name), or defining
117        ;; something like SB-INT:DEFCONSTANT-EQX (which is occasionally
118        ;; more appropriate). -- WHN 2000-11-03
119        (unless (eql value
120                     (info :variable :constant-value name))
121          (cerror "Go ahead and change the value."
122                  "The constant ~S is being redefined."
123                  name)))
124       (:global
125        ;; (This is OK -- undefined variables are of this kind. So we
126        ;; don't warn or error or anything, just fall through.)
127        )
128       (t (warn "redefining ~(~A~) ~S to be a constant" kind name))))
129   (when doc
130     (setf (fdocumentation name 'variable) doc))
131
132   ;; We want to set the cross-compilation host's symbol value, not just
133   ;; the cross-compiler's (INFO :VARIABLE :CONSTANT-VALUE NAME), so
134   ;; that code like
135   ;;   (defconstant max-entries 61)
136   ;;   (deftype entry-index () `(mod ,max-entries))
137   ;; will be cross-compiled correctly.
138   #-sb-xc-host (setf (symbol-value name) value)
139   #+sb-xc-host (progn
140                  (/show (symbol-package name))
141                  ;; Redefining our cross-compilation host's CL symbols
142                  ;; would be poor form.
143                  ;;
144                  ;; FIXME: Having to check this and then not treat it
145                  ;; as a fatal error seems like a symptom of things
146                  ;; being pretty broken. It's also a problem in and of
147                  ;; itself, since it makes it too easy for cases of
148                  ;; using the cross-compilation host Lisp's CL
149                  ;; constant values in the target Lisp to slip by. I
150                  ;; got backed into this because the cross-compiler
151                  ;; translates DEFCONSTANT SB!XC:FOO into DEFCONSTANT
152                  ;; CL:FOO. It would be good to unscrew the
153                  ;; cross-compilation package hacks so that that
154                  ;; translation doesn't happen. Perhaps:
155                  ;;   * Replace SB-XC with SB-CL. SB-CL exports all the 
156                  ;;     symbols which ANSI requires to be exported from CL.
157                  ;;   * Make a nickname SB!CL which behaves like SB!XC.
158                  ;;   * Go through the loaded-on-the-host code making
159                  ;;     every target definition be in SB-CL. E.g.
160                  ;;     DEFMACRO-MUNDANELY DEFCONSTANT becomes
161                  ;;     DEFMACRO-MUNDANELY SB!CL:DEFCONSTANT.
162                  ;;   * Make IN-TARGET-COMPILATION-MODE do 
163                  ;;     UNUSE-PACKAGE CL and USE-PACKAGE SB-CL in each
164                  ;;     of the target packages (then undo it on exit).
165                  ;;   * Make the cross-compiler's implementation of
166                  ;;     EVAL-WHEN (:COMPILE-TOPLEVEL) do UNCROSS.
167                  ;;     (This may not require any change.)
168                  ;;   * Hack GENESIS as necessary so that it outputs
169                  ;;     SB-CL stuff as COMMON-LISP stuff.
170                  ;;   * Now the code here can assert that the symbol
171                  ;;     being defined isn't in the cross-compilation
172                  ;;     host's CL package.
173                  (unless (eql (find-symbol (symbol-name name) :cl) name)
174                    ;; KLUDGE: In the cross-compiler, we use the
175                    ;; cross-compilation host's DEFCONSTANT macro
176                    ;; instead of just (SETF SYMBOL-VALUE), in order to
177                    ;; get whatever blessing the cross-compilation host
178                    ;; may expect for a global (SETF SYMBOL-VALUE).
179                    ;; (CMU CL, at least around 2.4.19, generated full
180                    ;; WARNINGs for code -- e.g. DEFTYPE expanders --
181                    ;; which referred to symbols which had been set by
182                    ;; (SETF SYMBOL-VALUE). I doubt such warnings are
183                    ;; ANSI-compliant, but I'm not sure, so I've
184                    ;; written this in a way that CMU CL will tolerate
185                    ;; and which ought to work elsewhere too.) -- WHN
186                    ;; 2001-03-24
187                    (eval `(defconstant ,name ',value))))
188
189   (setf (info :variable :kind name) :constant)
190   (setf (info :variable :constant-value name) value)
191   name)
192 \f
193 ;;;; DEFINE-COMPILER-MACRO
194
195 ;;; FIXME: The logic here for handling compiler macros named (SETF
196 ;;; FOO) was added after the fork from SBCL, is not well tested, and
197 ;;; may conflict with subtleties of the ANSI standard. E.g. section
198 ;;; "3.2.2.1 Compiler Macros" says that creating a lexical binding for
199 ;;; a function name shadows a compiler macro, and it's not clear that
200 ;;; that works with this version. It should be tested.
201 (defmacro-mundanely define-compiler-macro (name lambda-list &body body)
202   #!+sb-doc
203   "Define a compiler-macro for NAME."
204   (let ((whole (gensym "WHOLE-"))
205         (environment (gensym "ENV-")))
206     (multiple-value-bind (body local-decs doc)
207         (parse-defmacro lambda-list whole body name 'define-compiler-macro
208                         :environment environment)
209       (let ((def `(lambda (,whole ,environment)
210                     ,@local-decs
211                     (block ,(function-name-block-name name)
212                       ,body))))
213         `(sb!c::%define-compiler-macro ',name #',def ',lambda-list ,doc)))))
214 (defun sb!c::%define-compiler-macro (name definition lambda-list doc)
215   ;; FIXME: Why does this have to be an interpreted function? Shouldn't
216   ;; it get compiled?
217   (aver (sb!eval:interpreted-function-p definition))
218   (setf (sb!eval:interpreted-function-name definition)
219         (format nil "DEFINE-COMPILER-MACRO ~S" name))
220   (setf (sb!eval:interpreted-function-arglist definition) lambda-list)
221   (sb!c::%%define-compiler-macro name definition doc))
222 (defun sb!c::%%define-compiler-macro (name definition doc)
223   (setf (sb!xc:compiler-macro-function name) definition)
224   ;; FIXME: Add support for (SETF FDOCUMENTATION) when object is a list
225   ;; and type is COMPILER-MACRO. (Until then, we have to discard any
226   ;; compiler macro documentation for (SETF FOO).)
227   (unless (listp name)
228     (setf (fdocumentation name 'compiler-macro) doc))
229   name)
230 \f
231 ;;;; CASE, TYPECASE, and friends
232
233 (eval-when (:compile-toplevel :load-toplevel :execute)
234
235 ;;; CASE-BODY returns code for all the standard "case" macros. NAME is
236 ;;; the macro name, and KEYFORM is the thing to case on. MULTI-P
237 ;;; indicates whether a branch may fire off a list of keys; otherwise,
238 ;;; a key that is a list is interpreted in some way as a single key.
239 ;;; When MULTI-P, TEST is applied to the value of KEYFORM and each key
240 ;;; for a given branch; otherwise, TEST is applied to the value of
241 ;;; KEYFORM and the entire first element, instead of each part, of the
242 ;;; case branch. When ERRORP, no T or OTHERWISE branch is permitted,
243 ;;; and an ERROR form is generated. When PROCEEDP, it is an error to
244 ;;; omit ERRORP, and the ERROR form generated is executed within a
245 ;;; RESTART-CASE allowing KEYFORM to be set and retested.
246 (defun case-body (name keyform cases multi-p test errorp proceedp needcasesp)
247   (unless (or cases (not needcasesp))
248     (warn "no clauses in ~S" name))
249   (let ((keyform-value (gensym))
250         (clauses ())
251         (keys ()))
252     (dolist (case cases)
253       (unless (list-of-length-at-least-p case 1)
254         (error "~S -- bad clause in ~S" case name))
255       (destructuring-bind (keyoid &rest forms) case
256         (cond ((memq keyoid '(t otherwise))
257                (if errorp
258                    (error 'simple-program-error
259                           :format-control
260                           "No default clause is allowed in ~S: ~S"
261                           :format-arguments (list name case))
262                    (push `(t nil ,@forms) clauses)))
263               ((and multi-p (listp keyoid))
264                (setf keys (append keyoid keys))
265                (push `((or ,@(mapcar (lambda (key)
266                                        `(,test ,keyform-value ',key))
267                                      keyoid))
268                        nil
269                        ,@forms)
270                      clauses))
271               (t
272                (push keyoid keys)
273                (push `((,test ,keyform-value ',keyoid)
274                        nil
275                        ,@forms)
276                      clauses)))))
277     (case-body-aux name keyform keyform-value clauses keys errorp proceedp
278                    `(,(if multi-p 'member 'or) ,@keys))))
279
280 ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled
281 ;;; all the cases. Note: it is not necessary that the resulting code
282 ;;; signal case-failure conditions, but that's what KMP's prototype
283 ;;; code did. We call CASE-BODY-ERROR, because of how closures are
284 ;;; compiled. RESTART-CASE has forms with closures that the compiler
285 ;;; causes to be generated at the top of any function using the case
286 ;;; macros, regardless of whether they are needed.
287 ;;;
288 ;;; The CASE-BODY-ERROR function is defined later, when the
289 ;;; RESTART-CASE macro has been defined.
290 (defun case-body-aux (name keyform keyform-value clauses keys
291                       errorp proceedp expected-type)
292   (if proceedp
293       (let ((block (gensym))
294             (again (gensym)))
295         `(let ((,keyform-value ,keyform))
296            (block ,block
297              (tagbody
298               ,again
299               (return-from
300                ,block
301                (cond ,@(nreverse clauses)
302                      (t
303                       (setf ,keyform-value
304                             (setf ,keyform
305                                   (case-body-error
306                                    ',name ',keyform ,keyform-value
307                                    ',expected-type ',keys)))
308                       (go ,again))))))))
309       `(let ((,keyform-value ,keyform))
310          (declare (ignorable ,keyform-value)) ; e.g. (CASE KEY (T))
311          (cond
312           ,@(nreverse clauses)
313           ,@(if errorp
314                 `((t (error 'case-failure
315                             :name ',name
316                             :datum ,keyform-value
317                             :expected-type ',expected-type
318                             :possibilities ',keys))))))))
319 ) ; EVAL-WHEN
320
321 (defmacro-mundanely case (keyform &body cases)
322   #!+sb-doc
323   "CASE Keyform {({(Key*) | Key} Form*)}*
324   Evaluates the Forms in the first clause with a Key EQL to the value of
325   Keyform. If a singleton key is T then the clause is a default clause."
326   (case-body 'case keyform cases t 'eql nil nil nil))
327
328 (defmacro-mundanely ccase (keyform &body cases)
329   #!+sb-doc
330   "CCASE Keyform {({(Key*) | Key} Form*)}*
331   Evaluates the Forms in the first clause with a Key EQL to the value of
332   Keyform. If none of the keys matches then a correctable error is
333   signalled."
334   (case-body 'ccase keyform cases t 'eql t t t))
335
336 (defmacro-mundanely ecase (keyform &body cases)
337   #!+sb-doc
338   "ECASE Keyform {({(Key*) | Key} Form*)}*
339   Evaluates the Forms in the first clause with a Key EQL to the value of
340   Keyform. If none of the keys matches then an error is signalled."
341   (case-body 'ecase keyform cases t 'eql t nil t))
342
343 (defmacro-mundanely typecase (keyform &body cases)
344   #!+sb-doc
345   "TYPECASE Keyform {(Type Form*)}*
346   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
347   is true."
348   (case-body 'typecase keyform cases nil 'typep nil nil nil))
349
350 (defmacro-mundanely ctypecase (keyform &body cases)
351   #!+sb-doc
352   "CTYPECASE Keyform {(Type Form*)}*
353   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
354   is true. If no form is satisfied then a correctable error is signalled."
355   (case-body 'ctypecase keyform cases nil 'typep t t t))
356
357 (defmacro-mundanely etypecase (keyform &body cases)
358   #!+sb-doc
359   "ETYPECASE Keyform {(Type Form*)}*
360   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
361   is true. If no form is satisfied then an error is signalled."
362   (case-body 'etypecase keyform cases nil 'typep t nil t))
363 \f
364 ;;;; WITH-FOO i/o-related macros
365
366 (defmacro-mundanely with-open-stream ((var stream) &body forms-decls)
367   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
368     (let ((abortp (gensym)))
369       `(let ((,var ,stream)
370              (,abortp t))
371          ,@decls
372          (unwind-protect
373              (multiple-value-prog1
374               (progn ,@forms)
375               (setq ,abortp nil))
376            (when ,var
377              (close ,var :abort ,abortp)))))))
378
379 (defmacro-mundanely with-open-file ((stream filespec &rest options)
380                                     &body body)
381   `(with-open-stream (,stream (open ,filespec ,@options))
382      ,@body))
383
384 (defmacro-mundanely with-input-from-string ((var string &key index start end)
385                                             &body forms-decls)
386   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
387     ;; The ONCE-ONLY inhibits compiler note for unreachable code when
388     ;; END is true.
389     (once-only ((string string))
390       `(let ((,var
391               ,(cond ((null end)
392                       `(make-string-input-stream ,string ,(or start 0)))
393                      ((symbolp end)
394                       `(if ,end
395                            (make-string-input-stream ,string
396                                                      ,(or start 0)
397                                                      ,end)
398                            (make-string-input-stream ,string
399                                                      ,(or start 0))))
400                      (t
401                       `(make-string-input-stream ,string
402                                                  ,(or start 0)
403                                                  ,end)))))
404          ,@decls
405          (unwind-protect
406              (progn ,@forms)
407            (close ,var)
408            ,@(when index
409                `((setf ,index (string-input-stream-current ,var)))))))))
410
411 (defmacro-mundanely with-output-to-string ((var &optional string)
412                                            &body forms-decls)
413   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
414     (if string
415       `(let ((,var (make-fill-pointer-output-stream ,string)))
416          ,@decls
417          (unwind-protect
418              (progn ,@forms)
419            (close ,var)))
420       `(let ((,var (make-string-output-stream)))
421          ,@decls
422          (unwind-protect
423              (progn ,@forms)
424            (close ,var))
425          (get-output-stream-string ,var)))))
426 \f
427 ;;;; miscellaneous macros
428
429 (defmacro-mundanely nth-value (n form)
430   #!+sb-doc
431   "Evaluates FORM and returns the Nth value (zero based). This involves no
432   consing when N is a trivial constant integer."
433   (if (integerp n)
434       (let ((dummy-list nil)
435             (keeper (gensym "KEEPER-")))
436         ;; We build DUMMY-LIST, a list of variables to bind to useless
437         ;; values, then we explicitly IGNORE those bindings and return
438         ;; KEEPER, the only thing we're really interested in right now.
439         (dotimes (i n)
440           (push (gensym "IGNORE-") dummy-list))
441         `(multiple-value-bind (,@dummy-list ,keeper) ,form
442            (declare (ignore ,@dummy-list))
443            ,keeper))
444       (once-only ((n n))
445         `(case (the fixnum ,n)
446            (0 (nth-value 0 ,form))
447            (1 (nth-value 1 ,form))
448            (2 (nth-value 2 ,form))
449            (t (nth (the fixnum ,n) (multiple-value-list ,form)))))))
450
451 (defmacro-mundanely declaim (&rest specs)
452   #!+sb-doc
453   "DECLAIM Declaration*
454   Do a declaration or declarations for the global environment."
455   #-sb-xc-host
456   `(eval-when (:compile-toplevel :load-toplevel :execute)
457      ,@(mapcar #'(lambda (x)
458                    `(sb!xc:proclaim ',x))
459                specs))
460   ;; KLUDGE: The definition above doesn't work in the cross-compiler,
461   ;; because UNCROSS translates SB!XC:PROCLAIM into CL:PROCLAIM before
462   ;; the form gets executed. Instead, we have to explicitly do the
463   ;; proclamation at macroexpansion time. -- WHN ca. 19990810
464   ;;
465   ;; FIXME: Maybe we don't need this special treatment any more now
466   ;; that we're using DEFMACRO-MUNDANELY instead of DEFMACRO?
467   #+sb-xc-host (progn
468                  (mapcar #'sb!xc:proclaim specs)
469                  `(progn
470                     ,@(mapcar #'(lambda (x)
471                                   `(sb!xc:proclaim ',x))
472                               specs))))
473
474 (defmacro-mundanely print-unreadable-object ((object stream
475                                               &key type identity)
476                                              &body body)
477   `(%print-unreadable-object ,object ,stream ,type ,identity
478                              ,(if body
479                                   `#'(lambda () ,@body)
480                                   nil)))