0.6.7.22: removed CVS dollar-Header-dollar tags from sources
[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 ;;; FIXME: In reality, this restart cruft is needed hardly anywhere in
58 ;;; the system. Write NEED and NEED-TYPE to replace ASSERT and
59 ;;; CHECK-TYPE inside the system.
60 ;;;
61 ;;; CHECK-TYPE-ERROR isn't defined until a later file because it uses
62 ;;; the macro RESTART-CASE, which isn't defined until a later file.
63 (defmacro-mundanely check-type (place type &optional type-string)
64   #!+sb-doc
65   "Signals a restartable error of type TYPE-ERROR if the value of PLACE is
66   not of the specified type. If an error is signalled and the restart is
67   used to return, the
68   return if the
69    STORE-VALUE is invoked. It will store into PLACE and start over."
70   (let ((place-value (gensym)))
71     `(do ((,place-value ,place))
72          ((typep ,place-value ',type))
73        (setf ,place
74              (check-type-error ',place ,place-value ',type ,type-string)))))
75
76 #!+high-security-support
77 (defmacro-mundanely check-type-var (place type-var &optional type-string)
78   #!+sb-doc
79   "Signals an error of type type-error if the contents of place are not of the
80    specified type to which the type-var evaluates. If an error is signaled,
81    this can only return if STORE-VALUE is invoked. It will store into place
82    and start over."
83   (let ((place-value (gensym))
84         (type-value (gensym)))
85     `(do ((,place-value ,place)
86           (,type-value  ,type-var))
87          ((typep ,place-value ,type-value))
88        (setf ,place
89              (check-type-error ',place ,place-value ,type-value ,type-string)))))
90 \f
91 ;;;; DEFCONSTANT
92
93 (defmacro-mundanely defconstant (var val &optional doc)
94   #!+sb-doc
95   "For defining global constants at top level. The DEFCONSTANT says that the
96   value is constant and may be compiled into code. If the variable already has
97   a value, and this is not equal to the init, an error is signalled. The third
98   argument is an optional documentation string for the variable."
99   `(sb!c::%defconstant ',var ,val ',doc))
100
101 ;;; These are like the other %MUMBLEs except that we currently
102 ;;; actually do something interesting at load time, namely checking
103 ;;; whether the constant is being redefined.
104 (defun sb!c::%defconstant (name value doc)
105   (sb!c::%%defconstant name value doc))
106 #+sb-xc-host (sb!xc:proclaim '(ftype function sb!c::%%defconstant)) ; to avoid
107                                         ; undefined function warnings
108 (defun sb!c::%%defconstant (name value doc)
109   (when doc
110     (setf (fdocumentation name 'variable) doc))
111   (when (boundp name)
112     (unless (equalp (symbol-value name) value)
113       (cerror "Go ahead and change the value."
114               "The constant ~S is being redefined."
115               name)))
116   (setf (symbol-value name) value)
117   (setf (info :variable :kind name) :constant)
118   (clear-info :variable :constant-value name)
119   name)
120 \f
121 ;;;; DEFINE-COMPILER-MACRO
122
123 ;;; FIXME: The logic here for handling compiler macros named (SETF
124 ;;; FOO) was added after the fork from SBCL, is not well tested, and
125 ;;; may conflict with subtleties of the ANSI standard. E.g. section
126 ;;; "3.2.2.1 Compiler Macros" says that creating a lexical binding for
127 ;;; a function name shadows a compiler macro, and it's not clear that
128 ;;; that works with this version. It should be tested.
129 (defmacro-mundanely define-compiler-macro (name lambda-list &body body)
130   #!+sb-doc
131   "Define a compiler-macro for NAME."
132   (let ((whole (gensym "WHOLE-"))
133         (environment (gensym "ENV-")))
134     (multiple-value-bind (body local-decs doc)
135         (parse-defmacro lambda-list whole body name 'define-compiler-macro
136                         :environment environment)
137       (let ((def `(lambda (,whole ,environment)
138                     ,@local-decs
139                     (block ,(function-name-block-name name)
140                       ,body))))
141         `(sb!c::%define-compiler-macro ',name #',def ',lambda-list ,doc)))))
142 (defun sb!c::%define-compiler-macro (name definition lambda-list doc)
143   ;; FIXME: Why does this have to be an interpreted function? Shouldn't
144   ;; it get compiled?
145   (assert (sb!eval:interpreted-function-p definition))
146   (setf (sb!eval:interpreted-function-name definition)
147         (format nil "DEFINE-COMPILER-MACRO ~S" name))
148   (setf (sb!eval:interpreted-function-arglist definition) lambda-list)
149   (sb!c::%%define-compiler-macro name definition doc))
150 (defun sb!c::%%define-compiler-macro (name definition doc)
151   (setf (sb!xc:compiler-macro-function name) definition)
152   ;; FIXME: Add support for (SETF FDOCUMENTATION) when object is a list
153   ;; and type is COMPILER-MACRO. (Until then, we have to discard any
154   ;; compiler macro documentation for (SETF FOO).)
155   (unless (listp name)
156     (setf (fdocumentation name 'compiler-macro) doc))
157   name)
158 \f
159 ;;;; CASE, TYPECASE, and friends
160
161 (eval-when (:compile-toplevel :load-toplevel :execute)
162
163 ;;; CASE-BODY (interface)
164 ;;;
165 ;;; CASE-BODY returns code for all the standard "case" macros. Name is
166 ;;; the macro name, and keyform is the thing to case on. Multi-p
167 ;;; indicates whether a branch may fire off a list of keys; otherwise,
168 ;;; a key that is a list is interpreted in some way as a single key.
169 ;;; When multi-p, test is applied to the value of keyform and each key
170 ;;; for a given branch; otherwise, test is applied to the value of
171 ;;; keyform and the entire first element, instead of each part, of the
172 ;;; case branch. When errorp, no t or otherwise branch is permitted,
173 ;;; and an ERROR form is generated. When proceedp, it is an error to
174 ;;; omit errorp, and the ERROR form generated is executed within a
175 ;;; RESTART-CASE allowing keyform to be set and retested.
176 (defun case-body (name keyform cases multi-p test errorp proceedp needcasesp)
177   (unless (or cases (not needcasesp))
178     (warn "no clauses in ~S" name))
179   (let ((keyform-value (gensym))
180         (clauses ())
181         (keys ()))
182     (dolist (case cases)
183       (cond ((atom case)
184              (error "~S -- Bad clause in ~S." case name))
185             ((memq (car case) '(t otherwise))
186              (if errorp
187                  (error 'simple-program-error
188                         :format-control "No default clause is allowed in ~S: ~S"
189                         :format-arguments (list name case))
190                  (push `(t nil ,@(rest case)) clauses)))
191             ((and multi-p (listp (first case)))
192              (setf keys (append (first case) keys))
193              (push `((or ,@(mapcar #'(lambda (key)
194                                        `(,test ,keyform-value ',key))
195                                    (first case)))
196                      nil ,@(rest case))
197                    clauses))
198             (t
199              (push (first case) keys)
200              (push `((,test ,keyform-value
201                             ',(first case)) nil ,@(rest case)) clauses))))
202     (case-body-aux name keyform keyform-value clauses keys errorp proceedp
203                    `(,(if multi-p 'member 'or) ,@keys))))
204
205 ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled
206 ;;; all the cases. Note: it is not necessary that the resulting code
207 ;;; signal case-failure conditions, but that's what KMP's prototype
208 ;;; code did. We call CASE-BODY-ERROR, because of how closures are
209 ;;; compiled. RESTART-CASE has forms with closures that the compiler
210 ;;; causes to be generated at the top of any function using the case
211 ;;; macros, regardless of whether they are needed.
212 ;;;
213 ;;; The CASE-BODY-ERROR function is defined later, when the
214 ;;; RESTART-CASE macro has been defined.
215 (defun case-body-aux (name keyform keyform-value clauses keys
216                       errorp proceedp expected-type)
217   (if proceedp
218       (let ((block (gensym))
219             (again (gensym)))
220         `(let ((,keyform-value ,keyform))
221            (block ,block
222              (tagbody
223               ,again
224               (return-from
225                ,block
226                (cond ,@(nreverse clauses)
227                      (t
228                       (setf ,keyform-value
229                             (setf ,keyform
230                                   (case-body-error
231                                    ',name ',keyform ,keyform-value
232                                    ',expected-type ',keys)))
233                       (go ,again))))))))
234       `(let ((,keyform-value ,keyform))
235          (declare (ignorable ,keyform-value)) ; e.g. (CASE KEY (T))
236          (cond
237           ,@(nreverse clauses)
238           ,@(if errorp
239                 `((t (error 'sb!conditions::case-failure
240                             :name ',name
241                             :datum ,keyform-value
242                             :expected-type ',expected-type
243                             :possibilities ',keys))))))))
244 ) ; EVAL-WHEN
245
246 (defmacro-mundanely case (keyform &body cases)
247   #!+sb-doc
248   "CASE Keyform {({(Key*) | Key} Form*)}*
249   Evaluates the Forms in the first clause with a Key EQL to the value of
250   Keyform. If a singleton key is T then the clause is a default clause."
251   (case-body 'case keyform cases t 'eql nil nil nil))
252
253 (defmacro-mundanely ccase (keyform &body cases)
254   #!+sb-doc
255   "CCASE Keyform {({(Key*) | Key} Form*)}*
256   Evaluates the Forms in the first clause with a Key EQL to the value of
257   Keyform. If none of the keys matches then a correctable error is
258   signalled."
259   (case-body 'ccase keyform cases t 'eql t t t))
260
261 (defmacro-mundanely ecase (keyform &body cases)
262   #!+sb-doc
263   "ECASE Keyform {({(Key*) | Key} Form*)}*
264   Evaluates the Forms in the first clause with a Key EQL to the value of
265   Keyform. If none of the keys matches then an error is signalled."
266   (case-body 'ecase keyform cases t 'eql t nil t))
267
268 (defmacro-mundanely typecase (keyform &body cases)
269   #!+sb-doc
270   "TYPECASE Keyform {(Type Form*)}*
271   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
272   is true."
273   (case-body 'typecase keyform cases nil 'typep nil nil nil))
274
275 (defmacro-mundanely ctypecase (keyform &body cases)
276   #!+sb-doc
277   "CTYPECASE Keyform {(Type Form*)}*
278   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
279   is true. If no form is satisfied then a correctable error is signalled."
280   (case-body 'ctypecase keyform cases nil 'typep t t t))
281
282 (defmacro-mundanely etypecase (keyform &body cases)
283   #!+sb-doc
284   "ETYPECASE Keyform {(Type Form*)}*
285   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
286   is true. If no form is satisfied then an error is signalled."
287   (case-body 'etypecase keyform cases nil 'typep t nil t))
288 \f
289 ;;;; WITH-FOO i/o-related macros
290
291 (defmacro-mundanely with-open-stream ((var stream) &body forms-decls)
292   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
293     (let ((abortp (gensym)))
294       `(let ((,var ,stream)
295              (,abortp t))
296          ,@decls
297          (unwind-protect
298              (multiple-value-prog1
299               (progn ,@forms)
300               (setq ,abortp nil))
301            (when ,var
302              (close ,var :abort ,abortp)))))))
303
304 (defmacro-mundanely with-open-file ((stream filespec &rest options)
305                                     &body body)
306   `(with-open-stream (,stream (open ,filespec ,@options))
307      ,@body))
308
309 (defmacro-mundanely with-input-from-string ((var string &key index start end)
310                                             &body forms-decls)
311   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
312     ;; The ONCE-ONLY inhibits compiler note for unreachable code when
313     ;; END is true.
314     (once-only ((string string))
315       `(let ((,var
316               ,(cond ((null end)
317                       `(make-string-input-stream ,string ,(or start 0)))
318                      ((symbolp end)
319                       `(if ,end
320                            (make-string-input-stream ,string
321                                                      ,(or start 0)
322                                                      ,end)
323                            (make-string-input-stream ,string
324                                                      ,(or start 0))))
325                      (t
326                       `(make-string-input-stream ,string
327                                                  ,(or start 0)
328                                                  ,end)))))
329          ,@decls
330          (unwind-protect
331              (progn ,@forms)
332            (close ,var)
333            ,@(when index
334                `((setf ,index (string-input-stream-current ,var)))))))))
335
336 (defmacro-mundanely with-output-to-string ((var &optional string)
337                                            &body forms-decls)
338   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
339     (if string
340       `(let ((,var (make-fill-pointer-output-stream ,string)))
341          ,@decls
342          (unwind-protect
343              (progn ,@forms)
344            (close ,var)))
345       `(let ((,var (make-string-output-stream)))
346          ,@decls
347          (unwind-protect
348              (progn ,@forms)
349            (close ,var))
350          (get-output-stream-string ,var)))))
351 \f
352 ;;;; miscellaneous macros
353
354 (defmacro-mundanely nth-value (n form)
355   #!+sb-doc
356   "Evaluates FORM and returns the Nth value (zero based). This involves no
357   consing when N is a trivial constant integer."
358   (if (integerp n)
359       (let ((dummy-list nil)
360             (keeper (gensym "KEEPER-")))
361         ;; We build DUMMY-LIST, a list of variables to bind to useless
362         ;; values, then we explicitly IGNORE those bindings and return
363         ;; KEEPER, the only thing we're really interested in right now.
364         (dotimes (i n)
365           (push (gensym "IGNORE-") dummy-list))
366         `(multiple-value-bind (,@dummy-list ,keeper) ,form
367            (declare (ignore ,@dummy-list))
368            ,keeper))
369       (once-only ((n n))
370         `(case (the fixnum ,n)
371            (0 (nth-value 0 ,form))
372            (1 (nth-value 1 ,form))
373            (2 (nth-value 2 ,form))
374            (t (nth (the fixnum ,n) (multiple-value-list ,form)))))))
375
376 (defmacro-mundanely declaim (&rest specs)
377   #!+sb-doc
378   "DECLAIM Declaration*
379   Do a declaration or declarations for the global environment."
380   #-sb-xc-host
381   `(eval-when (:compile-toplevel :load-toplevel :execute)
382      ,@(mapcar #'(lambda (x)
383                    `(sb!xc:proclaim ',x))
384                specs))
385   ;; KLUDGE: The definition above doesn't work in the cross-compiler,
386   ;; because UNCROSS translates SB!XC:PROCLAIM into CL:PROCLAIM before
387   ;; the form gets executed. Instead, we have to explicitly do the
388   ;; proclamation at macroexpansion time. -- WHN ca. 19990810
389   ;;
390   ;; FIXME: Maybe we don't need this special treatment any more now
391   ;; that we're using DEFMACRO-MUNDANELY instead of DEFMACRO?
392   #+sb-xc-host (progn
393                  (mapcar #'sb!xc:proclaim specs)
394                  `(progn
395                     ,@(mapcar #'(lambda (x)
396                                   `(sb!xc:proclaim ',x))
397                               specs))))
398
399 (defmacro-mundanely print-unreadable-object ((object stream
400                                               &key type identity)
401                                              &body body)
402   `(%print-unreadable-object ,object ,stream ,type ,identity
403                              ,(if body
404                                   `#'(lambda () ,@body)
405                                   nil)))