242bf92d82d6358241c0f2627a2d7e5cb19e413d
[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 returns code for all the standard "case" macros. NAME is
184 ;;; the macro name, and KEYFORM is the thing to case on. MULTI-P
185 ;;; indicates whether a branch may fire off a list of keys; otherwise,
186 ;;; a key that is a list is interpreted in some way as a single key.
187 ;;; When MULTI-P, TEST is applied to the value of KEYFORM and each key
188 ;;; for a given branch; otherwise, TEST is applied to the value of
189 ;;; KEYFORM and the entire first element, instead of each part, of the
190 ;;; case branch. When ERRORP, no T or OTHERWISE branch is permitted,
191 ;;; and an ERROR form is generated. When PROCEEDP, it is an error to
192 ;;; omit ERRORP, and the ERROR form generated is executed within a
193 ;;; RESTART-CASE allowing KEYFORM to be set and retested.
194 (defun case-body (name keyform cases multi-p test errorp proceedp needcasesp)
195   (unless (or cases (not needcasesp))
196     (warn "no clauses in ~S" name))
197   (let ((keyform-value (gensym))
198         (clauses ())
199         (keys ()))
200     (dolist (case cases)
201       (unless (list-of-length-at-least-p case 1)
202         (error "~S -- bad clause in ~S" case name))
203       (destructuring-bind (keyoid &rest forms) case
204         (cond ((memq keyoid '(t otherwise))
205                (if errorp
206                    (error 'simple-program-error
207                           :format-control
208                           "No default clause is allowed in ~S: ~S"
209                           :format-arguments (list name case))
210                    (push `(t nil ,@forms) clauses)))
211               ((and multi-p (listp keyoid))
212                (setf keys (append keyoid keys))
213                (push `((or ,@(mapcar (lambda (key)
214                                        `(,test ,keyform-value ',key))
215                                      keyoid))
216                        nil
217                        ,@forms)
218                      clauses))
219               (t
220                (push keyoid keys)
221                (push `((,test ,keyform-value ',keyoid)
222                        nil
223                        ,@forms)
224                      clauses)))))
225     (case-body-aux name keyform keyform-value clauses keys errorp proceedp
226                    `(,(if multi-p 'member 'or) ,@keys))))
227
228 ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled
229 ;;; all the cases. Note: it is not necessary that the resulting code
230 ;;; signal case-failure conditions, but that's what KMP's prototype
231 ;;; code did. We call CASE-BODY-ERROR, because of how closures are
232 ;;; compiled. RESTART-CASE has forms with closures that the compiler
233 ;;; causes to be generated at the top of any function using the case
234 ;;; macros, regardless of whether they are needed.
235 ;;;
236 ;;; The CASE-BODY-ERROR function is defined later, when the
237 ;;; RESTART-CASE macro has been defined.
238 (defun case-body-aux (name keyform keyform-value clauses keys
239                       errorp proceedp expected-type)
240   (if proceedp
241       (let ((block (gensym))
242             (again (gensym)))
243         `(let ((,keyform-value ,keyform))
244            (block ,block
245              (tagbody
246               ,again
247               (return-from
248                ,block
249                (cond ,@(nreverse clauses)
250                      (t
251                       (setf ,keyform-value
252                             (setf ,keyform
253                                   (case-body-error
254                                    ',name ',keyform ,keyform-value
255                                    ',expected-type ',keys)))
256                       (go ,again))))))))
257       `(let ((,keyform-value ,keyform))
258          (declare (ignorable ,keyform-value)) ; e.g. (CASE KEY (T))
259          (cond
260           ,@(nreverse clauses)
261           ,@(if errorp
262                 `((t (error 'case-failure
263                             :name ',name
264                             :datum ,keyform-value
265                             :expected-type ',expected-type
266                             :possibilities ',keys))))))))
267 ) ; EVAL-WHEN
268
269 (defmacro-mundanely case (keyform &body cases)
270   #!+sb-doc
271   "CASE Keyform {({(Key*) | Key} Form*)}*
272   Evaluates the Forms in the first clause with a Key EQL to the value of
273   Keyform. If a singleton key is T then the clause is a default clause."
274   (case-body 'case keyform cases t 'eql nil nil nil))
275
276 (defmacro-mundanely ccase (keyform &body cases)
277   #!+sb-doc
278   "CCASE Keyform {({(Key*) | Key} Form*)}*
279   Evaluates the Forms in the first clause with a Key EQL to the value of
280   Keyform. If none of the keys matches then a correctable error is
281   signalled."
282   (case-body 'ccase keyform cases t 'eql t t t))
283
284 (defmacro-mundanely ecase (keyform &body cases)
285   #!+sb-doc
286   "ECASE Keyform {({(Key*) | Key} Form*)}*
287   Evaluates the Forms in the first clause with a Key EQL to the value of
288   Keyform. If none of the keys matches then an error is signalled."
289   (case-body 'ecase keyform cases t 'eql t nil t))
290
291 (defmacro-mundanely typecase (keyform &body cases)
292   #!+sb-doc
293   "TYPECASE Keyform {(Type Form*)}*
294   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
295   is true."
296   (case-body 'typecase keyform cases nil 'typep nil nil nil))
297
298 (defmacro-mundanely ctypecase (keyform &body cases)
299   #!+sb-doc
300   "CTYPECASE Keyform {(Type Form*)}*
301   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
302   is true. If no form is satisfied then a correctable error is signalled."
303   (case-body 'ctypecase keyform cases nil 'typep t t t))
304
305 (defmacro-mundanely etypecase (keyform &body cases)
306   #!+sb-doc
307   "ETYPECASE Keyform {(Type Form*)}*
308   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
309   is true. If no form is satisfied then an error is signalled."
310   (case-body 'etypecase keyform cases nil 'typep t nil t))
311 \f
312 ;;;; WITH-FOO i/o-related macros
313
314 (defmacro-mundanely with-open-stream ((var stream) &body forms-decls)
315   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
316     (let ((abortp (gensym)))
317       `(let ((,var ,stream)
318              (,abortp t))
319          ,@decls
320          (unwind-protect
321              (multiple-value-prog1
322               (progn ,@forms)
323               (setq ,abortp nil))
324            (when ,var
325              (close ,var :abort ,abortp)))))))
326
327 (defmacro-mundanely with-open-file ((stream filespec &rest options)
328                                     &body body)
329   `(with-open-stream (,stream (open ,filespec ,@options))
330      ,@body))
331
332 (defmacro-mundanely with-input-from-string ((var string &key index start end)
333                                             &body forms-decls)
334   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
335     ;; The ONCE-ONLY inhibits compiler note for unreachable code when
336     ;; END is true.
337     (once-only ((string string))
338       `(let ((,var
339               ,(cond ((null end)
340                       `(make-string-input-stream ,string ,(or start 0)))
341                      ((symbolp end)
342                       `(if ,end
343                            (make-string-input-stream ,string
344                                                      ,(or start 0)
345                                                      ,end)
346                            (make-string-input-stream ,string
347                                                      ,(or start 0))))
348                      (t
349                       `(make-string-input-stream ,string
350                                                  ,(or start 0)
351                                                  ,end)))))
352          ,@decls
353          (unwind-protect
354              (progn ,@forms)
355            (close ,var)
356            ,@(when index
357                `((setf ,index (string-input-stream-current ,var)))))))))
358
359 (defmacro-mundanely with-output-to-string ((var &optional string)
360                                            &body forms-decls)
361   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
362     (if string
363       `(let ((,var (make-fill-pointer-output-stream ,string)))
364          ,@decls
365          (unwind-protect
366              (progn ,@forms)
367            (close ,var)))
368       `(let ((,var (make-string-output-stream)))
369          ,@decls
370          (unwind-protect
371              (progn ,@forms)
372            (close ,var))
373          (get-output-stream-string ,var)))))
374 \f
375 ;;;; miscellaneous macros
376
377 (defmacro-mundanely nth-value (n form)
378   #!+sb-doc
379   "Evaluates FORM and returns the Nth value (zero based). This involves no
380   consing when N is a trivial constant integer."
381   (if (integerp n)
382       (let ((dummy-list nil)
383             (keeper (gensym "KEEPER-")))
384         ;; We build DUMMY-LIST, a list of variables to bind to useless
385         ;; values, then we explicitly IGNORE those bindings and return
386         ;; KEEPER, the only thing we're really interested in right now.
387         (dotimes (i n)
388           (push (gensym "IGNORE-") dummy-list))
389         `(multiple-value-bind (,@dummy-list ,keeper) ,form
390            (declare (ignore ,@dummy-list))
391            ,keeper))
392       (once-only ((n n))
393         `(case (the fixnum ,n)
394            (0 (nth-value 0 ,form))
395            (1 (nth-value 1 ,form))
396            (2 (nth-value 2 ,form))
397            (t (nth (the fixnum ,n) (multiple-value-list ,form)))))))
398
399 (defmacro-mundanely declaim (&rest specs)
400   #!+sb-doc
401   "DECLAIM Declaration*
402   Do a declaration or declarations for the global environment."
403   #-sb-xc-host
404   `(eval-when (:compile-toplevel :load-toplevel :execute)
405      ,@(mapcar #'(lambda (x)
406                    `(sb!xc:proclaim ',x))
407                specs))
408   ;; KLUDGE: The definition above doesn't work in the cross-compiler,
409   ;; because UNCROSS translates SB!XC:PROCLAIM into CL:PROCLAIM before
410   ;; the form gets executed. Instead, we have to explicitly do the
411   ;; proclamation at macroexpansion time. -- WHN ca. 19990810
412   ;;
413   ;; FIXME: Maybe we don't need this special treatment any more now
414   ;; that we're using DEFMACRO-MUNDANELY instead of DEFMACRO?
415   #+sb-xc-host (progn
416                  (mapcar #'sb!xc:proclaim specs)
417                  `(progn
418                     ,@(mapcar #'(lambda (x)
419                                   `(sb!xc:proclaim ',x))
420                               specs))))
421
422 (defmacro-mundanely print-unreadable-object ((object stream
423                                               &key type identity)
424                                              &body body)
425   `(%print-unreadable-object ,object ,stream ,type ,identity
426                              ,(if body
427                                   `#'(lambda () ,@body)
428                                   nil)))