5c64df2350c9691765c11ce46a535ed0ab51e31f
[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 ;;; CHECK-TYPE-ERROR isn't defined until a later file because it uses
58 ;;; the macro RESTART-CASE, which isn't defined until a later file.
59 (defmacro-mundanely check-type (place type &optional type-string)
60   #!+sb-doc
61   "Signal a restartable error of type TYPE-ERROR if the value of PLACE is
62   not of the specified type. If an error is signalled and the restart is
63   used to return, this can only return if the STORE-VALUE restart is
64   invoked. In that case it will store into PLACE and start over."
65   (let ((place-value (gensym)))
66     `(do ((,place-value ,place ,place))
67          ((typep ,place-value ',type))
68        (setf ,place
69              (check-type-error ',place ,place-value ',type ,type-string)))))
70 \f
71 ;;;; DEFINE-SYMBOL-MACRO
72
73 (defmacro-mundanely define-symbol-macro (name expansion)
74   `(eval-when (:compile-toplevel :load-toplevel :execute)
75     (sb!c::%define-symbol-macro ',name ',expansion)))
76
77 (defun sb!c::%define-symbol-macro (name expansion)
78   (unless (symbolp name)
79     (error 'simple-type-error :datum name :expected-type 'symbol
80            :format-control "Symbol macro name is not a symbol: ~S."
81            :format-arguments (list name)))
82   (ecase (info :variable :kind name)
83     ((:macro :global nil)
84      (setf (info :variable :kind name) :macro)
85      (setf (info :variable :macro-expansion name) expansion))
86     (:special
87      (error 'simple-program-error
88             :format-control "Symbol macro name already declared special: ~S."
89             :format-arguments (list name)))
90     (:constant
91      (error 'simple-program-error
92             :format-control "Symbol macro name already declared constant: ~S."
93             :format-arguments (list name))))
94   name)
95 \f
96 ;;;; DEFINE-COMPILER-MACRO
97
98 (defmacro-mundanely define-compiler-macro (name lambda-list &body body)
99   #!+sb-doc
100   "Define a compiler-macro for NAME."
101   (legal-fun-name-or-type-error name)
102   (when (consp name)
103     ;; It's fairly clear that the user intends the compiler macro to
104     ;; expand when he does (SETF (FOO ...) X). And that's even a
105     ;; useful and reasonable thing to want. Unfortunately,
106     ;; (SETF (FOO ...) X) macroexpands into (FUNCALL (SETF FOO) X ...),
107     ;; and it's not at all clear that it's valid to expand a FUNCALL form,
108     ;; and the ANSI standard doesn't seem to say anything else which
109     ;; would justify us expanding the compiler macro the way the user
110     ;; wants. So instead we rely on 3.2.2.1.3 "When Compiler Macros Are
111     ;; Used" which says they never have to be used, so by ignoring such
112     ;; macros we're erring on the safe side. But any user who does
113     ;; (DEFINE-COMPILER-MACRO (SETF FOO) ...) could easily be surprised
114     ;; by this way of complying with a rather screwy aspect of the ANSI
115     ;; spec, so at least we can warn him...
116     (sb!c::compiler-style-warn
117      "defining compiler macro of (SETF ...), which will not be expanded"))
118   (when (and (symbolp name) (special-operator-p name))
119     (error 'simple-program-error
120            :format-control "cannot define a compiler-macro for a special operator: ~S"
121            :format-arguments (list name)))
122   (with-unique-names (whole environment)
123     (multiple-value-bind (body local-decs doc)
124         (parse-defmacro lambda-list whole body name 'define-compiler-macro
125                         :environment environment)
126       (let ((def `(lambda (,whole ,environment)
127                     ,@local-decs
128                     ,body))
129             (debug-name (sb!c::debug-namify "DEFINE-COMPILER-MACRO " name)))
130         `(eval-when (:compile-toplevel :load-toplevel :execute)
131           (sb!c::%define-compiler-macro ',name
132                                         #',def
133                                         ',lambda-list
134                                         ,doc
135                                         ,debug-name))))))
136
137 ;;; FIXME: This will look remarkably similar to those who have already
138 ;;; seen the code for %DEFMACRO in src/code/defmacro.lisp.  Various
139 ;;; bits of logic should be shared (notably arglist setting).
140 (macrolet
141     ((def (times set-p)
142          `(eval-when (,@times)
143            (defun sb!c::%define-compiler-macro
144                (name definition lambda-list doc debug-name)
145              ,@(unless set-p
146                  '((declare (ignore lambda-list debug-name))))
147              ;; FIXME: warn about incompatible lambda list with
148              ;; respect to parent function?
149              (setf (sb!xc:compiler-macro-function name) definition)
150              ;; FIXME: Add support for (SETF FDOCUMENTATION) when
151              ;; object is a list and type is COMPILER-MACRO. (Until
152              ;; then, we have to discard any compiler macro
153              ;; documentation for (SETF FOO).)
154              (unless (listp name)
155                (setf (fdocumentation name 'compiler-macro) doc))
156              ,(when set-p
157                     `(case (widetag-of definition)
158                       (#.sb!vm:closure-header-widetag
159                        (setf (%simple-fun-arglist (%closure-fun definition))
160                              lambda-list
161                              (%simple-fun-name (%closure-fun definition))
162                              debug-name))
163                       (#.sb!vm:simple-fun-header-widetag
164                        (setf (%simple-fun-arglist definition) lambda-list
165                              (%simple-fun-name definition) debug-name))))
166              name))))
167   (progn
168     (def (:load-toplevel :execute) #-sb-xc-host t #+sb-xc-host nil)
169     #-sb-xc (def (:compile-toplevel) nil)))
170 \f
171 ;;;; CASE, TYPECASE, and friends
172
173 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
174
175 ;;; CASE-BODY returns code for all the standard "case" macros. NAME is
176 ;;; the macro name, and KEYFORM is the thing to case on. MULTI-P
177 ;;; indicates whether a branch may fire off a list of keys; otherwise,
178 ;;; a key that is a list is interpreted in some way as a single key.
179 ;;; When MULTI-P, TEST is applied to the value of KEYFORM and each key
180 ;;; for a given branch; otherwise, TEST is applied to the value of
181 ;;; KEYFORM and the entire first element, instead of each part, of the
182 ;;; case branch. When ERRORP, no T or OTHERWISE branch is permitted,
183 ;;; and an ERROR form is generated. When PROCEEDP, it is an error to
184 ;;; omit ERRORP, and the ERROR form generated is executed within a
185 ;;; RESTART-CASE allowing KEYFORM to be set and retested.
186 (defun case-body (name keyform cases multi-p test errorp proceedp needcasesp)
187   (unless (or cases (not needcasesp))
188     (warn "no clauses in ~S" name))
189   (let ((keyform-value (gensym))
190         (clauses ())
191         (keys ()))
192     (do* ((cases cases (cdr cases))
193           (case (car cases) (car cases)))
194          ((null cases) nil)
195       (unless (list-of-length-at-least-p case 1)
196         (error "~S -- bad clause in ~S" case name))
197       (destructuring-bind (keyoid &rest forms) case
198         (cond ((and (memq keyoid '(t otherwise))
199                     (null (cdr cases)))
200                (if errorp
201                    (progn
202                      (style-warn "~@<Treating bare ~A in ~A as introducing a ~
203                                   normal-clause, not an otherwise-clause~@:>"
204                                  keyoid name)
205                      (push keyoid keys)
206                      (push `((,test ,keyform-value ',keyoid) nil ,@forms)
207                            clauses))
208                    (push `(t nil ,@forms) clauses)))
209               ((and multi-p (listp keyoid))
210                (setf keys (append keyoid keys))
211                (push `((or ,@(mapcar (lambda (key)
212                                        `(,test ,keyform-value ',key))
213                                      keyoid))
214                        nil
215                        ,@forms)
216                      clauses))
217               (t
218                (push keyoid keys)
219                (push `((,test ,keyform-value ',keyoid)
220                        nil
221                        ,@forms)
222                      clauses)))))
223     (case-body-aux name keyform keyform-value clauses keys errorp proceedp
224                    `(,(if multi-p 'member 'or) ,@keys))))
225
226 ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled
227 ;;; all the cases. Note: it is not necessary that the resulting code
228 ;;; signal case-failure conditions, but that's what KMP's prototype
229 ;;; code did. We call CASE-BODY-ERROR, because of how closures are
230 ;;; compiled. RESTART-CASE has forms with closures that the compiler
231 ;;; causes to be generated at the top of any function using the case
232 ;;; macros, regardless of whether they are needed.
233 ;;;
234 ;;; The CASE-BODY-ERROR function is defined later, when the
235 ;;; RESTART-CASE macro has been defined.
236 (defun case-body-aux (name keyform keyform-value clauses keys
237                       errorp proceedp expected-type)
238   (if proceedp
239       (let ((block (gensym))
240             (again (gensym)))
241         `(let ((,keyform-value ,keyform))
242            (block ,block
243              (tagbody
244               ,again
245               (return-from
246                ,block
247                (cond ,@(nreverse clauses)
248                      (t
249                       (setf ,keyform-value
250                             (setf ,keyform
251                                   (case-body-error
252                                    ',name ',keyform ,keyform-value
253                                    ',expected-type ',keys)))
254                       (go ,again))))))))
255       `(let ((,keyform-value ,keyform))
256          (declare (ignorable ,keyform-value)) ; e.g. (CASE KEY (T))
257          (cond
258           ,@(nreverse clauses)
259           ,@(if errorp
260                 `((t (error 'case-failure
261                             :name ',name
262                             :datum ,keyform-value
263                             :expected-type ',expected-type
264                             :possibilities ',keys))))))))
265 ) ; EVAL-WHEN
266
267 (defmacro-mundanely case (keyform &body cases)
268   #!+sb-doc
269   "CASE Keyform {({(Key*) | Key} Form*)}*
270   Evaluates the Forms in the first clause with a Key EQL to the value of
271   Keyform. If a singleton key is T then the clause is a default clause."
272   (case-body 'case keyform cases t 'eql nil nil nil))
273
274 (defmacro-mundanely ccase (keyform &body cases)
275   #!+sb-doc
276   "CCASE Keyform {({(Key*) | Key} Form*)}*
277   Evaluates the Forms in the first clause with a Key EQL to the value of
278   Keyform. If none of the keys matches then a correctable error is
279   signalled."
280   (case-body 'ccase keyform cases t 'eql t t t))
281
282 (defmacro-mundanely ecase (keyform &body cases)
283   #!+sb-doc
284   "ECASE Keyform {({(Key*) | Key} Form*)}*
285   Evaluates the Forms in the first clause with a Key EQL to the value of
286   Keyform. If none of the keys matches then an error is signalled."
287   (case-body 'ecase keyform cases t 'eql t nil t))
288
289 (defmacro-mundanely typecase (keyform &body cases)
290   #!+sb-doc
291   "TYPECASE Keyform {(Type Form*)}*
292   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
293   is true."
294   (case-body 'typecase keyform cases nil 'typep nil nil nil))
295
296 (defmacro-mundanely ctypecase (keyform &body cases)
297   #!+sb-doc
298   "CTYPECASE Keyform {(Type Form*)}*
299   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
300   is true. If no form is satisfied then a correctable error is signalled."
301   (case-body 'ctypecase keyform cases nil 'typep t t t))
302
303 (defmacro-mundanely etypecase (keyform &body cases)
304   #!+sb-doc
305   "ETYPECASE Keyform {(Type Form*)}*
306   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
307   is true. If no form is satisfied then an error is signalled."
308   (case-body 'etypecase keyform cases nil 'typep t nil t))
309 \f
310 ;;;; WITH-FOO i/o-related macros
311
312 (defmacro-mundanely with-open-stream ((var stream) &body forms-decls)
313   (multiple-value-bind (forms decls)
314       (parse-body forms-decls :doc-string-allowed nil)
315     (let ((abortp (gensym)))
316       `(let ((,var ,stream)
317              (,abortp t))
318          ,@decls
319          (unwind-protect
320              (multiple-value-prog1
321               (progn ,@forms)
322               (setq ,abortp nil))
323            (when ,var
324              (close ,var :abort ,abortp)))))))
325
326 (defmacro-mundanely with-open-file ((stream filespec &rest options)
327                                     &body body)
328   `(with-open-stream (,stream (open ,filespec ,@options))
329      ,@body))
330
331 (defmacro-mundanely with-input-from-string ((var string &key index start end)
332                                             &body forms-decls)
333   (multiple-value-bind (forms decls)
334       (parse-body forms-decls :doc-string-allowed 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 
360     ((var &optional string &key (element-type ''character))
361      &body forms-decls)
362   (multiple-value-bind (forms decls)
363       (parse-body forms-decls :doc-string-allowed nil)
364     (if string
365       `(let ((,var (make-fill-pointer-output-stream ,string)))
366          ,@decls
367          (unwind-protect
368              (progn ,@forms)
369            (close ,var)))
370       `(let ((,var (make-string-output-stream :element-type ,element-type)))
371          ,@decls
372          (unwind-protect
373              (progn ,@forms)
374            (close ,var))
375          (get-output-stream-string ,var)))))
376 \f
377 ;;;; miscellaneous macros
378
379 (defmacro-mundanely nth-value (n form)
380   #!+sb-doc
381   "Evaluate FORM and return the Nth value (zero based). This involves no
382   consing when N is a trivial constant integer."
383   ;; FIXME: The above is true, if slightly misleading.  The
384   ;; MULTIPLE-VALUE-BIND idiom [ as opposed to MULTIPLE-VALUE-CALL
385   ;; (LAMBDA (&REST VALUES) (NTH N VALUES)) ] does indeed not cons at
386   ;; runtime.  However, for large N (say N = 200), COMPILE on such a
387   ;; form will take longer than can be described as adequate, as the
388   ;; optional dispatch mechanism for the M-V-B gets increasingly
389   ;; hairy.
390   (if (integerp n)
391       (let ((dummy-list nil)
392             (keeper (gensym "KEEPER-")))
393         ;; We build DUMMY-LIST, a list of variables to bind to useless
394         ;; values, then we explicitly IGNORE those bindings and return
395         ;; KEEPER, the only thing we're really interested in right now.
396         (dotimes (i n)
397           (push (gensym "IGNORE-") dummy-list))
398         `(multiple-value-bind (,@dummy-list ,keeper) ,form
399            (declare (ignore ,@dummy-list))
400            ,keeper))
401       (once-only ((n n))
402         `(case (the fixnum ,n)
403            (0 (nth-value 0 ,form))
404            (1 (nth-value 1 ,form))
405            (2 (nth-value 2 ,form))
406            (t (nth (the fixnum ,n) (multiple-value-list ,form)))))))
407
408 (defmacro-mundanely declaim (&rest specs)
409   #!+sb-doc
410   "DECLAIM Declaration*
411   Do a declaration or declarations for the global environment."
412   `(eval-when (:compile-toplevel :load-toplevel :execute)
413      ,@(mapcar (lambda (spec) `(sb!xc:proclaim ',spec))
414                specs)))
415
416 (defmacro-mundanely print-unreadable-object ((object stream &key type identity)
417                                              &body body)
418   "Output OBJECT to STREAM with \"#<\" prefix, \">\" suffix, optionally
419   with object-type prefix and object-identity suffix, and executing the
420   code in BODY to provide possible further output."
421   `(%print-unreadable-object ,object ,stream ,type ,identity
422                              ,(if body
423                                   `(lambda () ,@body)
424                                   nil)))
425
426 (defmacro-mundanely ignore-errors (&rest forms)
427   #!+sb-doc
428   "Execute FORMS handling ERROR conditions, returning the result of the last
429   form, or (VALUES NIL the-ERROR-that-was-caught) if an ERROR was handled."
430   `(handler-case (progn ,@forms)
431      (error (condition) (values nil condition))))