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