362bce1a3afe6b60fdd4c2c7e98f41440bc0d0a8
[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
206 ;;; MNA: typecase-implicit-declarations patch
207
208 ;;; TYPECASE-BODY (interface)
209 ;;;
210 ;;; TYPECASE-BODY returns code for all the standard "typecase" macros.
211 ;;; Name is the macro name, and keyform is the thing to case on.
212 ;;; test is applied to the value of keyform and the entire first element,
213 ;;; instead of each part, of the case branch.
214 ;;; When errorp, no t or otherwise branch is permitted,
215 ;;; and an ERROR form is generated. When proceedp, it is an error to
216 ;;; omit errorp, and the ERROR form generated is executed within a
217 ;;; RESTART-CASE allowing keyform to be set and retested.
218 (defun typecase-body (name keyform cases test errorp proceedp needcasesp)
219   (unless (or cases (not needcasesp))
220     (warn "no clauses in ~S" name))
221   (let* ((keyform-symbol-p (symbolp keyform))
222          (keyform-value (unless keyform-symbol-p                         
223                           (gensym)))
224          (clauses ())
225          (keys ()))
226     (dolist (case cases)
227       (cond ((atom case)
228              (error "~S -- Bad clause in ~S." case name))
229             ((memq (car case) '(t otherwise))
230              (if errorp
231                  (error 'simple-program-error
232                         :format-control "No default clause is allowed in ~S: ~S"
233                         :format-arguments (list name case))
234                (push `(t nil ,@(rest case)) clauses)))
235             (t
236               (push (first case) keys)
237               (push (if keyform-symbol-p
238                       `((,test ,keyform ',(first case)) nil
239                         (locally
240                           ;; this will cause a compiler-warning ... disabled
241                           ;; for now.
242                           ;; (declare (type ,(first case) ,keyform))
243                           ,@(rest case)))
244                       `((,test ,keyform-value ',(first case)) nil
245                         ,@(rest case)))
246                     clauses))))
247     (if keyform-symbol-p
248       (typecase-symbol-body-aux name keyform clauses keys errorp proceedp
249                                 (cons 'or keys))
250       (case-body-aux name keyform keyform-value clauses keys errorp proceedp
251                      (cons 'or keys)))))
252
253 ;;; TYPECASE-SYMBOL-BODY-AUX provides the expansion once CASE-BODY has groveled
254 ;;; all the cases, iff keyform is a symbol.
255 (defun typecase-symbol-body-aux (name keyform clauses keys
256                                       errorp proceedp expected-type)
257   (if proceedp
258       (let ((block (gensym))
259             (again (gensym)))
260         `(block ,block
261           (tagbody
262             ,again
263             (return-from
264               ,block
265               (cond ,@(nreverse clauses)
266                     (t
267                       (setf ,keyform
268                               (case-body-error
269                                ',name ',keyform ,keyform
270                                ',expected-type ',keys)))
271                     (go ,again))))))
272     `(progn
273       (cond
274         ,@(nreverse clauses)
275         ,@(if errorp
276               `((t (error 'sb!conditions::case-failure
277                     :name ',name
278                     :datum ,keyform
279                     :expected-type ',expected-type
280                     :possibilities ',keys))))))))
281
282 ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled
283 ;;; all the cases. Note: it is not necessary that the resulting code
284 ;;; signal case-failure conditions, but that's what KMP's prototype
285 ;;; code did. We call CASE-BODY-ERROR, because of how closures are
286 ;;; compiled. RESTART-CASE has forms with closures that the compiler
287 ;;; causes to be generated at the top of any function using the case
288 ;;; macros, regardless of whether they are needed.
289 ;;;
290 ;;; The CASE-BODY-ERROR function is defined later, when the
291 ;;; RESTART-CASE macro has been defined.
292 (defun case-body-aux (name keyform keyform-value clauses keys
293                       errorp proceedp expected-type)
294   (if proceedp
295       (let ((block (gensym))
296             (again (gensym)))
297         `(let ((,keyform-value ,keyform))
298            (block ,block
299              (tagbody
300               ,again
301               (return-from
302                ,block
303                (cond ,@(nreverse clauses)
304                      (t
305                       (setf ,keyform-value
306                             (setf ,keyform
307                                   (case-body-error
308                                    ',name ',keyform ,keyform-value
309                                    ',expected-type ',keys)))
310                       (go ,again))))))))
311       `(let ((,keyform-value ,keyform))
312          (declare (ignorable ,keyform-value)) ; e.g. (CASE KEY (T))
313          (cond
314           ,@(nreverse clauses)
315           ,@(if errorp
316                 `((t (error 'sb!conditions::case-failure
317                             :name ',name
318                             :datum ,keyform-value
319                             :expected-type ',expected-type
320                             :possibilities ',keys))))))))
321 ) ; EVAL-WHEN
322
323 (defmacro-mundanely case (keyform &body cases)
324   #!+sb-doc
325   "CASE Keyform {({(Key*) | Key} Form*)}*
326   Evaluates the Forms in the first clause with a Key EQL to the value of
327   Keyform. If a singleton key is T then the clause is a default clause."
328   (case-body 'case keyform cases t 'eql nil nil nil))
329
330 (defmacro-mundanely ccase (keyform &body cases)
331   #!+sb-doc
332   "CCASE Keyform {({(Key*) | Key} Form*)}*
333   Evaluates the Forms in the first clause with a Key EQL to the value of
334   Keyform. If none of the keys matches then a correctable error is
335   signalled."
336   (case-body 'ccase keyform cases t 'eql t t t))
337
338 (defmacro-mundanely ecase (keyform &body cases)
339   #!+sb-doc
340   "ECASE Keyform {({(Key*) | Key} Form*)}*
341   Evaluates the Forms in the first clause with a Key EQL to the value of
342   Keyform. If none of the keys matches then an error is signalled."
343   (case-body 'ecase keyform cases t 'eql t nil t))
344
345 (defmacro-mundanely typecase (keyform &body cases)
346   #!+sb-doc
347   "TYPECASE Keyform {(Type Form*)}*
348   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
349   is true."
350   (typecase-body 'typecase keyform cases 'typep nil nil nil))
351
352 (defmacro-mundanely ctypecase (keyform &body cases)
353   #!+sb-doc
354   "CTYPECASE Keyform {(Type Form*)}*
355   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
356   is true. If no form is satisfied then a correctable error is signalled."
357   (typecase-body 'ctypecase keyform cases 'typep t t t))
358
359 (defmacro-mundanely etypecase (keyform &body cases)
360   #!+sb-doc
361   "ETYPECASE Keyform {(Type Form*)}*
362   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
363   is true. If no form is satisfied then an error is signalled."
364   (typecase-body 'etypecase keyform cases 'typep t nil t))
365 \f
366 ;;;; WITH-FOO i/o-related macros
367
368 (defmacro-mundanely with-open-stream ((var stream) &body forms-decls)
369   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
370     (let ((abortp (gensym)))
371       `(let ((,var ,stream)
372              (,abortp t))
373          ,@decls
374          (unwind-protect
375              (multiple-value-prog1
376               (progn ,@forms)
377               (setq ,abortp nil))
378            (when ,var
379              (close ,var :abort ,abortp)))))))
380
381 (defmacro-mundanely with-open-file ((stream filespec &rest options)
382                                     &body body)
383   `(with-open-stream (,stream (open ,filespec ,@options))
384      ,@body))
385
386 (defmacro-mundanely with-input-from-string ((var string &key index start end)
387                                             &body forms-decls)
388   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
389     ;; The ONCE-ONLY inhibits compiler note for unreachable code when
390     ;; END is true.
391     (once-only ((string string))
392       `(let ((,var
393               ,(cond ((null end)
394                       `(make-string-input-stream ,string ,(or start 0)))
395                      ((symbolp end)
396                       `(if ,end
397                            (make-string-input-stream ,string
398                                                      ,(or start 0)
399                                                      ,end)
400                            (make-string-input-stream ,string
401                                                      ,(or start 0))))
402                      (t
403                       `(make-string-input-stream ,string
404                                                  ,(or start 0)
405                                                  ,end)))))
406          ,@decls
407          (unwind-protect
408              (progn ,@forms)
409            (close ,var)
410            ,@(when index
411                `((setf ,index (string-input-stream-current ,var)))))))))
412
413 (defmacro-mundanely with-output-to-string ((var &optional string)
414                                            &body forms-decls)
415   (multiple-value-bind (forms decls) (parse-body forms-decls nil)
416     (if string
417       `(let ((,var (make-fill-pointer-output-stream ,string)))
418          ,@decls
419          (unwind-protect
420              (progn ,@forms)
421            (close ,var)))
422       `(let ((,var (make-string-output-stream)))
423          ,@decls
424          (unwind-protect
425              (progn ,@forms)
426            (close ,var))
427          (get-output-stream-string ,var)))))
428 \f
429 ;;;; miscellaneous macros
430
431 (defmacro-mundanely nth-value (n form)
432   #!+sb-doc
433   "Evaluates FORM and returns the Nth value (zero based). This involves no
434   consing when N is a trivial constant integer."
435   (if (integerp n)
436       (let ((dummy-list nil)
437             (keeper (gensym "KEEPER-")))
438         ;; We build DUMMY-LIST, a list of variables to bind to useless
439         ;; values, then we explicitly IGNORE those bindings and return
440         ;; KEEPER, the only thing we're really interested in right now.
441         (dotimes (i n)
442           (push (gensym "IGNORE-") dummy-list))
443         `(multiple-value-bind (,@dummy-list ,keeper) ,form
444            (declare (ignore ,@dummy-list))
445            ,keeper))
446       (once-only ((n n))
447         `(case (the fixnum ,n)
448            (0 (nth-value 0 ,form))
449            (1 (nth-value 1 ,form))
450            (2 (nth-value 2 ,form))
451            (t (nth (the fixnum ,n) (multiple-value-list ,form)))))))
452
453 (defmacro-mundanely declaim (&rest specs)
454   #!+sb-doc
455   "DECLAIM Declaration*
456   Do a declaration or declarations for the global environment."
457   #-sb-xc-host
458   `(eval-when (:compile-toplevel :load-toplevel :execute)
459      ,@(mapcar #'(lambda (x)
460                    `(sb!xc:proclaim ',x))
461                specs))
462   ;; KLUDGE: The definition above doesn't work in the cross-compiler,
463   ;; because UNCROSS translates SB!XC:PROCLAIM into CL:PROCLAIM before
464   ;; the form gets executed. Instead, we have to explicitly do the
465   ;; proclamation at macroexpansion time. -- WHN ca. 19990810
466   ;;
467   ;; FIXME: Maybe we don't need this special treatment any more now
468   ;; that we're using DEFMACRO-MUNDANELY instead of DEFMACRO?
469   #+sb-xc-host (progn
470                  (mapcar #'sb!xc:proclaim specs)
471                  `(progn
472                     ,@(mapcar #'(lambda (x)
473                                   `(sb!xc:proclaim ',x))
474                               specs))))
475
476 (defmacro-mundanely print-unreadable-object ((object stream
477                                               &key type identity)
478                                              &body body)
479   `(%print-unreadable-object ,object ,stream ,type ,identity
480                              ,(if body
481                                   `#'(lambda () ,@body)
482                                   nil)))