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