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