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