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