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