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