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