935fe5b6cc05242c1fd4462ff2a4b90ed0021315
[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 (%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              ,(when set-p
156                     `(setf (%fun-doc definition) doc
157                            (%fun-lambda-list definition) lambda-list
158                            (%fun-name definition) debug-name))
159              name))))
160   (progn
161     (def (:load-toplevel :execute) #-sb-xc-host t #+sb-xc-host nil)
162     #-sb-xc (def (:compile-toplevel) nil)))
163 \f
164 ;;;; CASE, TYPECASE, and friends
165
166 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
167
168 ;;; Make this a full warning during SBCL build.
169 (define-condition duplicate-case-key-warning (#-sb-xc-host style-warning #+sb-xc-host warning)
170   ((key :initarg :key
171         :reader case-warning-key)
172    (case-kind :initarg :case-kind
173               :reader case-warning-case-kind)
174    (occurrences :initarg :occurrences
175                 :type list
176                 :reader duplicate-case-key-warning-occurrences))
177   (:report
178     (lambda (condition stream)
179       (format stream
180         "Duplicate key ~S in ~S form, ~
181          occurring in~{~#[~; and~]~{ the ~:R clause:~%~<  ~S~:>~}~^,~}."
182         (case-warning-key condition)
183         (case-warning-case-kind condition)
184         (duplicate-case-key-warning-occurrences condition)))))
185
186 ;;; CASE-BODY returns code for all the standard "case" macros. NAME is
187 ;;; the macro name, and KEYFORM is the thing to case on. MULTI-P
188 ;;; indicates whether a branch may fire off a list of keys; otherwise,
189 ;;; a key that is a list is interpreted in some way as a single key.
190 ;;; When MULTI-P, TEST is applied to the value of KEYFORM and each key
191 ;;; for a given branch; otherwise, TEST is applied to the value of
192 ;;; KEYFORM and the entire first element, instead of each part, of the
193 ;;; case branch. When ERRORP, no OTHERWISE-CLAUSEs are recognized,
194 ;;; and an ERROR form is generated where control falls off the end
195 ;;; of the ordinary clauses. When PROCEEDP, it is an error to
196 ;;; omit ERRORP, and the ERROR form generated is executed within a
197 ;;; RESTART-CASE allowing KEYFORM to be set and retested.
198 (defun case-body (name keyform cases multi-p test errorp proceedp needcasesp)
199   (unless (or cases (not needcasesp))
200     (warn "no clauses in ~S" name))
201   (let ((keyform-value (gensym))
202         (clauses ())
203         (keys ())
204         (keys-seen (make-hash-table :test #'eql)))
205     (do* ((cases cases (cdr cases))
206           (case (car cases) (car cases))
207           (case-position 1 (1+ case-position)))
208          ((null cases) nil)
209       (flet ((check-clause (case-keys)
210                (loop for k in case-keys
211                      for existing = (gethash k keys-seen)
212                      do (when existing
213                           (let ((sb!c::*current-path*
214                                  (when (boundp 'sb!c::*source-paths*)
215                                    (or (sb!c::get-source-path case)
216                                        sb!c::*current-path*))))
217                             (warn 'duplicate-case-key-warning
218                                   :key k
219                                   :case-kind name
220                                   :occurrences `(,existing (,case-position (,case)))))))
221                (let ((record (list case-position (list case))))
222                  (dolist (k case-keys)
223                    (setf (gethash k keys-seen) record)))))
224         (unless (list-of-length-at-least-p case 1)
225           (error "~S -- bad clause in ~S" case name))
226         (destructuring-bind (keyoid &rest forms) case
227           (cond (;; an OTHERWISE-CLAUSE
228                  ;;
229                  ;; By the way... The old code here tried gave
230                  ;; STYLE-WARNINGs for normal-clauses which looked as
231                  ;; though they might've been intended to be
232                  ;; otherwise-clauses. As Tony Martinez reported on
233                  ;; sbcl-devel 2004-11-09 there are sometimes good
234                  ;; reasons to write clauses like that; and as I noticed
235                  ;; when trying to understand the old code so I could
236                  ;; understand his patch, trying to guess which clauses
237                  ;; don't have good reasons is fundamentally kind of a
238                  ;; mess. SBCL does issue style warnings rather
239                  ;; enthusiastically, and I have often justified that by
240                  ;; arguing that we're doing that to detect issues which
241                  ;; are tedious for programmers to detect for by
242                  ;; proofreading (like small typoes in long symbol
243                  ;; names, or duplicate function definitions in large
244                  ;; files). This doesn't seem to be an issue like that,
245                  ;; and I can't think of a comparably good justification
246                  ;; for giving STYLE-WARNINGs for legal code here, so
247                  ;; now we just hope the programmer knows what he's
248                  ;; doing. -- WHN 2004-11-20
249                  (and (not errorp) ; possible only in CASE or TYPECASE,
250                                    ; not in [EC]CASE or [EC]TYPECASE
251                       (memq keyoid '(t otherwise))
252                       (null (cdr cases)))
253                  (push `(t nil ,@forms) clauses))
254                 ((and multi-p (listp keyoid))
255                  (setf keys (append keyoid keys))
256                  (check-clause keyoid)
257                  (push `((or ,@(mapcar (lambda (key)
258                                          `(,test ,keyform-value ',key))
259                                        keyoid))
260                          nil
261                          ,@forms)
262                        clauses))
263                 (t
264                  (when (and (eq name 'case)
265                             (cdr cases)
266                             (memq keyoid '(t otherwise)))
267                    (error 'simple-reference-error
268                           :format-control
269                           "~@<~IBad ~S clause:~:@_  ~S~:@_~S allowed as the key ~
270                            designator only in the final otherwise-clause, not in a ~
271                            normal-clause. Use (~S) instead, or move the clause the ~
272                            correct position.~:@>"
273                           :format-arguments (list 'case case keyoid keyoid)
274                           :references `((:ansi-cl :macro case))))
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 (case-failure ',name ,keyform-value ',keys))))))))
319 ) ; EVAL-WHEN
320
321 (defmacro-mundanely case (keyform &body cases)
322   #!+sb-doc
323   "CASE Keyform {({(Key*) | Key} Form*)}*
324   Evaluates the Forms in the first clause with a Key EQL to the value of
325   Keyform. If a singleton key is T then the clause is a default clause."
326   (case-body 'case keyform cases t 'eql nil nil nil))
327
328 (defmacro-mundanely ccase (keyform &body cases)
329   #!+sb-doc
330   "CCASE Keyform {({(Key*) | Key} Form*)}*
331   Evaluates the Forms in the first clause with a Key EQL to the value of
332   Keyform. If none of the keys matches then a correctable error is
333   signalled."
334   (case-body 'ccase keyform cases t 'eql t t t))
335
336 (defmacro-mundanely ecase (keyform &body cases)
337   #!+sb-doc
338   "ECASE Keyform {({(Key*) | Key} Form*)}*
339   Evaluates the Forms in the first clause with a Key EQL to the value of
340   Keyform. If none of the keys matches then an error is signalled."
341   (case-body 'ecase keyform cases t 'eql t nil t))
342
343 (defmacro-mundanely typecase (keyform &body cases)
344   #!+sb-doc
345   "TYPECASE Keyform {(Type Form*)}*
346   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
347   is true."
348   (case-body 'typecase keyform cases nil 'typep nil nil nil))
349
350 (defmacro-mundanely ctypecase (keyform &body cases)
351   #!+sb-doc
352   "CTYPECASE Keyform {(Type Form*)}*
353   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
354   is true. If no form is satisfied then a correctable error is signalled."
355   (case-body 'ctypecase keyform cases nil 'typep t t t))
356
357 (defmacro-mundanely etypecase (keyform &body cases)
358   #!+sb-doc
359   "ETYPECASE Keyform {(Type Form*)}*
360   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
361   is true. If no form is satisfied then an error is signalled."
362   (case-body 'etypecase keyform cases nil 'typep t nil t))
363 \f
364 ;;;; WITH-FOO i/o-related macros
365
366 (defmacro-mundanely with-open-stream ((var stream) &body forms-decls)
367   (multiple-value-bind (forms decls)
368       (parse-body forms-decls :doc-string-allowed nil)
369     (let ((abortp (gensym)))
370       `(let ((,var ,stream)
371              (,abortp t))
372          ,@decls
373          (unwind-protect
374              (multiple-value-prog1
375               (progn ,@forms)
376               (setq ,abortp nil))
377            (when ,var
378              (close ,var :abort ,abortp)))))))
379
380 (defmacro-mundanely with-open-file ((stream filespec &rest options)
381                                     &body body)
382   `(with-open-stream (,stream (open ,filespec ,@options))
383      ,@body))
384
385 (defmacro-mundanely with-input-from-string ((var string &key index start end)
386                                             &body forms-decls)
387   (multiple-value-bind (forms decls)
388       (parse-body forms-decls :doc-string-allowed nil)
389     ;; The ONCE-ONLY inhibits compiler note for unreachable code when
390     ;; END is true.
391     (once-only ((string string))
392       `(let ((,var
393               ,(cond ((null end)
394                       `(make-string-input-stream ,string ,(or start 0)))
395                      ((symbolp end)
396                       `(if ,end
397                            (make-string-input-stream ,string
398                                                      ,(or start 0)
399                                                      ,end)
400                            (make-string-input-stream ,string
401                                                      ,(or start 0))))
402                      (t
403                       `(make-string-input-stream ,string
404                                                  ,(or start 0)
405                                                  ,end)))))
406          ,@decls
407          (multiple-value-prog1
408              (unwind-protect
409                   (progn ,@forms)
410                (close ,var))
411            ,@(when index
412                `((setf ,index (string-input-stream-current ,var)))))))))
413
414 (defmacro-mundanely with-output-to-string
415     ((var &optional string &key (element-type ''character))
416      &body forms-decls)
417   (multiple-value-bind (forms decls)
418       (parse-body forms-decls :doc-string-allowed nil)
419     (if string
420         (let ((element-type-var (gensym)))
421           `(let ((,var (make-fill-pointer-output-stream ,string))
422                  ;; ELEMENT-TYPE isn't currently used for anything
423                  ;; (see FILL-POINTER-OUTPUT-STREAM FIXME in stream.lisp),
424                  ;; but it still has to be evaluated for side-effects.
425                  (,element-type-var ,element-type))
426             (declare (ignore ,element-type-var))
427             ,@decls
428             (unwind-protect
429                  (progn ,@forms)
430               (close ,var))))
431       `(let ((,var (make-string-output-stream :element-type ,element-type)))
432          ,@decls
433          (unwind-protect
434              (progn ,@forms)
435            (close ,var))
436          (get-output-stream-string ,var)))))
437 \f
438 ;;;; miscellaneous macros
439
440 (defmacro-mundanely nth-value (n form)
441   #!+sb-doc
442   "Evaluate FORM and return the Nth value (zero based). This involves no
443   consing when N is a trivial constant integer."
444   ;; FIXME: The above is true, if slightly misleading.  The
445   ;; MULTIPLE-VALUE-BIND idiom [ as opposed to MULTIPLE-VALUE-CALL
446   ;; (LAMBDA (&REST VALUES) (NTH N VALUES)) ] does indeed not cons at
447   ;; runtime.  However, for large N (say N = 200), COMPILE on such a
448   ;; form will take longer than can be described as adequate, as the
449   ;; optional dispatch mechanism for the M-V-B gets increasingly
450   ;; hairy.
451   (if (integerp n)
452       (let ((dummy-list (make-gensym-list n))
453             (keeper (sb!xc:gensym "KEEPER")))
454         `(multiple-value-bind (,@dummy-list ,keeper) ,form
455            (declare (ignore ,@dummy-list))
456            ,keeper))
457       (once-only ((n n))
458         `(case (the fixnum ,n)
459            (0 (nth-value 0 ,form))
460            (1 (nth-value 1 ,form))
461            (2 (nth-value 2 ,form))
462            (t (nth (the fixnum ,n) (multiple-value-list ,form)))))))
463
464 (defmacro-mundanely declaim (&rest specs)
465   #!+sb-doc
466   "DECLAIM Declaration*
467   Do a declaration or declarations for the global environment."
468   `(eval-when (:compile-toplevel :load-toplevel :execute)
469      ,@(mapcar (lambda (spec) `(sb!xc:proclaim ',spec))
470                specs)))
471
472 (defmacro-mundanely print-unreadable-object ((object stream &key type identity)
473                                              &body body)
474   "Output OBJECT to STREAM with \"#<\" prefix, \">\" suffix, optionally
475   with object-type prefix and object-identity suffix, and executing the
476   code in BODY to provide possible further output."
477   `(%print-unreadable-object ,object ,stream ,type ,identity
478                              ,(if body
479                                   `(lambda () ,@body)
480                                   nil)))
481
482 (defmacro-mundanely ignore-errors (&rest forms)
483   #!+sb-doc
484   "Execute FORMS handling ERROR conditions, returning the result of the last
485   form, or (VALUES NIL the-ERROR-that-was-caught) if an ERROR was handled."
486   `(handler-case (progn ,@forms)
487      (error (condition) (values nil condition))))