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