51214a49c27aec6a6c0f5403b0c681746b4f922a
[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   (when (and (symbolp name) (special-operator-p name))
128     (error 'simple-program-error
129            :format-control "cannot define a compiler-macro for a special operator: ~S"
130            :format-arguments (list name)))
131   (let ((whole (gensym "WHOLE-"))
132         (environment (gensym "ENV-")))
133     (multiple-value-bind (body local-decs doc)
134         (parse-defmacro lambda-list whole body name 'define-compiler-macro
135                         :environment environment)
136       (let ((def `(lambda (,whole ,environment)
137                     ,@local-decs
138                     (block ,(fun-name-block-name name)
139                       ,body)))
140             (debug-name (debug-namify "DEFINE-COMPILER-MACRO ~S" name)))
141         `(eval-when (:compile-toplevel :load-toplevel :execute)
142           (sb!c::%define-compiler-macro ',name #',def ',lambda-list ,doc ,debug-name))))))
143
144 ;;; FIXME: This will look remarkably similar to those who have already
145 ;;; seen the code for %DEFMACRO in src/code/defmacro.lisp.  Various
146 ;;; bits of logic should be shared (notably arglist setting).
147 (macrolet
148     ((def (times set-p)
149          `(eval-when (,@times)
150            (defun sb!c::%define-compiler-macro
151                (name definition lambda-list doc debug-name)
152              ,@(unless set-p
153                  '((declare (ignore lambda-list debug-name))))
154              ;; FIXME: warn about incompatible lambda list with
155              ;; respect to parent function?
156              (setf (sb!xc:compiler-macro-function name) definition)
157              ;; FIXME: Add support for (SETF FDOCUMENTATION) when
158              ;; object is a list and type is COMPILER-MACRO. (Until
159              ;; then, we have to discard any compiler macro
160              ;; documentation for (SETF FOO).)
161              (unless (listp name)
162                (setf (fdocumentation name 'compiler-macro) doc))
163              ,(when set-p
164                     `(case (widetag-of definition)
165                       (#.sb!vm:closure-header-widetag
166                        (setf (%simple-fun-arglist (%closure-fun definition))
167                              lambda-list
168                              (%simple-fun-name (%closure-fun definition))
169                              debug-name))
170                       ((#.sb!vm:simple-fun-header-widetag
171                         #.sb!vm:closure-fun-header-widetag)
172                        (setf (%simple-fun-arglist definition) lambda-list
173                              (%simple-fun-name definition) debug-name))))
174              name))))
175   (progn
176     (def (:load-toplevel :execute) #-sb-xc-host t #+sb-xc-host nil)
177     (def (:compile-toplevel) nil)))
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     (do* ((cases cases (cdr cases))
201           (case (car cases) (car cases)))
202          ((null cases) nil)
203       (unless (list-of-length-at-least-p case 1)
204         (error "~S -- bad clause in ~S" case name))
205       (destructuring-bind (keyoid &rest forms) case
206         (cond ((and (memq keyoid '(t otherwise))
207                     (null (cdr cases)))
208                (if errorp
209                    (progn
210                      (style-warn "~@<Treating bare ~A in ~A as introducing a ~
211                                   normal-clause, not an otherwise-clause~@:>"
212                                  keyoid name)
213                      (push keyoid keys)
214                      (push `((,test ,keyform-value ',keyoid) nil ,@forms)
215                            clauses))
216                    (push `(t nil ,@forms) clauses)))
217               ((and multi-p (listp keyoid))
218                (setf keys (append keyoid keys))
219                (push `((or ,@(mapcar (lambda (key)
220                                        `(,test ,keyform-value ',key))
221                                      keyoid))
222                        nil
223                        ,@forms)
224                      clauses))
225               (t
226                (push keyoid keys)
227                (push `((,test ,keyform-value ',keyoid)
228                        nil
229                        ,@forms)
230                      clauses)))))
231     (case-body-aux name keyform keyform-value clauses keys errorp proceedp
232                    `(,(if multi-p 'member 'or) ,@keys))))
233
234 ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled
235 ;;; all the cases. Note: it is not necessary that the resulting code
236 ;;; signal case-failure conditions, but that's what KMP's prototype
237 ;;; code did. We call CASE-BODY-ERROR, because of how closures are
238 ;;; compiled. RESTART-CASE has forms with closures that the compiler
239 ;;; causes to be generated at the top of any function using the case
240 ;;; macros, regardless of whether they are needed.
241 ;;;
242 ;;; The CASE-BODY-ERROR function is defined later, when the
243 ;;; RESTART-CASE macro has been defined.
244 (defun case-body-aux (name keyform keyform-value clauses keys
245                       errorp proceedp expected-type)
246   (if proceedp
247       (let ((block (gensym))
248             (again (gensym)))
249         `(let ((,keyform-value ,keyform))
250            (block ,block
251              (tagbody
252               ,again
253               (return-from
254                ,block
255                (cond ,@(nreverse clauses)
256                      (t
257                       (setf ,keyform-value
258                             (setf ,keyform
259                                   (case-body-error
260                                    ',name ',keyform ,keyform-value
261                                    ',expected-type ',keys)))
262                       (go ,again))))))))
263       `(let ((,keyform-value ,keyform))
264          (declare (ignorable ,keyform-value)) ; e.g. (CASE KEY (T))
265          (cond
266           ,@(nreverse clauses)
267           ,@(if errorp
268                 `((t (error 'case-failure
269                             :name ',name
270                             :datum ,keyform-value
271                             :expected-type ',expected-type
272                             :possibilities ',keys))))))))
273 ) ; EVAL-WHEN
274
275 (defmacro-mundanely case (keyform &body cases)
276   #!+sb-doc
277   "CASE Keyform {({(Key*) | Key} Form*)}*
278   Evaluates the Forms in the first clause with a Key EQL to the value of
279   Keyform. If a singleton key is T then the clause is a default clause."
280   (case-body 'case keyform cases t 'eql nil nil nil))
281
282 (defmacro-mundanely ccase (keyform &body cases)
283   #!+sb-doc
284   "CCASE 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 a correctable error is
287   signalled."
288   (case-body 'ccase keyform cases t 'eql t t t))
289
290 (defmacro-mundanely ecase (keyform &body cases)
291   #!+sb-doc
292   "ECASE Keyform {({(Key*) | Key} Form*)}*
293   Evaluates the Forms in the first clause with a Key EQL to the value of
294   Keyform. If none of the keys matches then an error is signalled."
295   (case-body 'ecase keyform cases t 'eql t nil t))
296
297 (defmacro-mundanely typecase (keyform &body cases)
298   #!+sb-doc
299   "TYPECASE Keyform {(Type Form*)}*
300   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
301   is true."
302   (case-body 'typecase keyform cases nil 'typep nil nil nil))
303
304 (defmacro-mundanely ctypecase (keyform &body cases)
305   #!+sb-doc
306   "CTYPECASE Keyform {(Type Form*)}*
307   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
308   is true. If no form is satisfied then a correctable error is signalled."
309   (case-body 'ctypecase keyform cases nil 'typep t t t))
310
311 (defmacro-mundanely etypecase (keyform &body cases)
312   #!+sb-doc
313   "ETYPECASE Keyform {(Type Form*)}*
314   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
315   is true. If no form is satisfied then an error is signalled."
316   (case-body 'etypecase keyform cases nil 'typep t nil t))
317 \f
318 ;;;; WITH-FOO i/o-related macros
319
320 (defmacro-mundanely with-open-stream ((var stream) &body forms-decls)
321   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
322     (let ((abortp (gensym)))
323       `(let ((,var ,stream)
324              (,abortp t))
325          ,@decls
326          (unwind-protect
327              (multiple-value-prog1
328               (progn ,@forms)
329               (setq ,abortp nil))
330            (when ,var
331              (close ,var :abort ,abortp)))))))
332
333 (defmacro-mundanely with-open-file ((stream filespec &rest options)
334                                     &body body)
335   `(with-open-stream (,stream (open ,filespec ,@options))
336      ,@body))
337
338 (defmacro-mundanely with-input-from-string ((var string &key index start end)
339                                             &body forms-decls)
340   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
341     ;; The ONCE-ONLY inhibits compiler note for unreachable code when
342     ;; END is true.
343     (once-only ((string string))
344       `(let ((,var
345               ,(cond ((null end)
346                       `(make-string-input-stream ,string ,(or start 0)))
347                      ((symbolp end)
348                       `(if ,end
349                            (make-string-input-stream ,string
350                                                      ,(or start 0)
351                                                      ,end)
352                            (make-string-input-stream ,string
353                                                      ,(or start 0))))
354                      (t
355                       `(make-string-input-stream ,string
356                                                  ,(or start 0)
357                                                  ,end)))))
358          ,@decls
359          (unwind-protect
360              (progn ,@forms)
361            (close ,var)
362            ,@(when index
363                `((setf ,index (string-input-stream-current ,var)))))))))
364
365 (defmacro-mundanely with-output-to-string ((var &optional string)
366                                            &body forms-decls)
367   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
368     (if string
369       `(let ((,var (make-fill-pointer-output-stream ,string)))
370          ,@decls
371          (unwind-protect
372              (progn ,@forms)
373            (close ,var)))
374       `(let ((,var (make-string-output-stream)))
375          ,@decls
376          (unwind-protect
377              (progn ,@forms)
378            (close ,var))
379          (get-output-stream-string ,var)))))
380 \f
381 ;;;; miscellaneous macros
382
383 (defmacro-mundanely nth-value (n form)
384   #!+sb-doc
385   "Evaluate FORM and return the Nth value (zero based). This involves no
386   consing when N is a trivial constant integer."
387   ;; FIXME: The above is true, if slightly misleading.  The
388   ;; MULTIPLE-VALUE-BIND idiom [ as opposed to MULTIPLE-VALUE-CALL
389   ;; (LAMBDA (&REST VALUES) (NTH N VALUES)) ] does indeed not cons at
390   ;; runtime.  However, for large N (say N = 200), COMPILE on such a
391   ;; form will take longer than can be described as adequate, as the
392   ;; optional dispatch mechanism for the M-V-B gets increasingly
393   ;; hairy.
394   (if (integerp n)
395       (let ((dummy-list nil)
396             (keeper (gensym "KEEPER-")))
397         ;; We build DUMMY-LIST, a list of variables to bind to useless
398         ;; values, then we explicitly IGNORE those bindings and return
399         ;; KEEPER, the only thing we're really interested in right now.
400         (dotimes (i n)
401           (push (gensym "IGNORE-") dummy-list))
402         `(multiple-value-bind (,@dummy-list ,keeper) ,form
403            (declare (ignore ,@dummy-list))
404            ,keeper))
405       (once-only ((n n))
406         `(case (the fixnum ,n)
407            (0 (nth-value 0 ,form))
408            (1 (nth-value 1 ,form))
409            (2 (nth-value 2 ,form))
410            (t (nth (the fixnum ,n) (multiple-value-list ,form)))))))
411
412 (defmacro-mundanely declaim (&rest specs)
413   #!+sb-doc
414   "DECLAIM Declaration*
415   Do a declaration or declarations for the global environment."
416   `(eval-when (:compile-toplevel :load-toplevel :execute)
417      ,@(mapcar (lambda (spec) `(sb!xc:proclaim ',spec))
418                specs)))
419
420 (defmacro-mundanely print-unreadable-object ((object stream &key type identity)
421                                              &body body)
422   "Output OBJECT to STREAM with \"#<\" prefix, \">\" suffix, optionally
423   with object-type prefix and object-identity suffix, and executing the
424   code in BODY to provide possible further output."
425   `(%print-unreadable-object ,object ,stream ,type ,identity
426                              ,(if body
427                                   `(lambda () ,@body)
428                                   nil)))
429
430 (defmacro-mundanely ignore-errors (&rest forms)
431   #!+sb-doc
432   "Execute FORMS handling ERROR conditions, returning the result of the last
433   form, or (VALUES NIL the-ERROR-that-was-caught) if an ERROR was handled."
434   `(handler-case (progn ,@forms)
435      (error (condition) (values nil condition))))