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