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