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