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