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