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