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