0.8.12.7: Merge package locks, AKA "what can go wrong with a 3783 line patch?"
[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-namify "DEFINE-COMPILER-MACRO " 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 T or OTHERWISE branch is permitted,
185 ;;; and an ERROR form is generated. When PROCEEDP, it is an error to
186 ;;; omit ERRORP, and the ERROR form generated is executed within a
187 ;;; RESTART-CASE allowing KEYFORM to be set and retested.
188 (defun case-body (name keyform cases multi-p test errorp proceedp needcasesp)
189   (unless (or cases (not needcasesp))
190     (warn "no clauses in ~S" name))
191   (let ((keyform-value (gensym))
192         (clauses ())
193         (keys ()))
194     (do* ((cases cases (cdr cases))
195           (case (car cases) (car cases)))
196          ((null cases) nil)
197       (unless (list-of-length-at-least-p case 1)
198         (error "~S -- bad clause in ~S" case name))
199       (destructuring-bind (keyoid &rest forms) case
200         (cond ((and (memq keyoid '(t otherwise))
201                     (null (cdr cases)))
202                (if errorp
203                    (progn
204                      (style-warn "~@<Treating bare ~A in ~A as introducing a ~
205                                   normal-clause, not an otherwise-clause~@:>"
206                                  keyoid name)
207                      (push keyoid keys)
208                      (push `((,test ,keyform-value ',keyoid) nil ,@forms)
209                            clauses))
210                    (push `(t nil ,@forms) clauses)))
211               ((and multi-p (listp keyoid))
212                (setf keys (append keyoid keys))
213                (push `((or ,@(mapcar (lambda (key)
214                                        `(,test ,keyform-value ',key))
215                                      keyoid))
216                        nil
217                        ,@forms)
218                      clauses))
219               (t
220                (push keyoid keys)
221                (push `((,test ,keyform-value ',keyoid)
222                        nil
223                        ,@forms)
224                      clauses)))))
225     (case-body-aux name keyform keyform-value clauses keys errorp proceedp
226                    `(,(if multi-p 'member 'or) ,@keys))))
227
228 ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled
229 ;;; all the cases. Note: it is not necessary that the resulting code
230 ;;; signal case-failure conditions, but that's what KMP's prototype
231 ;;; code did. We call CASE-BODY-ERROR, because of how closures are
232 ;;; compiled. RESTART-CASE has forms with closures that the compiler
233 ;;; causes to be generated at the top of any function using the case
234 ;;; macros, regardless of whether they are needed.
235 ;;;
236 ;;; The CASE-BODY-ERROR function is defined later, when the
237 ;;; RESTART-CASE macro has been defined.
238 (defun case-body-aux (name keyform keyform-value clauses keys
239                       errorp proceedp expected-type)
240   (if proceedp
241       (let ((block (gensym))
242             (again (gensym)))
243         `(let ((,keyform-value ,keyform))
244            (block ,block
245              (tagbody
246               ,again
247               (return-from
248                ,block
249                (cond ,@(nreverse clauses)
250                      (t
251                       (setf ,keyform-value
252                             (setf ,keyform
253                                   (case-body-error
254                                    ',name ',keyform ,keyform-value
255                                    ',expected-type ',keys)))
256                       (go ,again))))))))
257       `(let ((,keyform-value ,keyform))
258          (declare (ignorable ,keyform-value)) ; e.g. (CASE KEY (T))
259          (cond
260           ,@(nreverse clauses)
261           ,@(if errorp
262                 `((t (error 'case-failure
263                             :name ',name
264                             :datum ,keyform-value
265                             :expected-type ',expected-type
266                             :possibilities ',keys))))))))
267 ) ; EVAL-WHEN
268
269 (defmacro-mundanely case (keyform &body cases)
270   #!+sb-doc
271   "CASE Keyform {({(Key*) | Key} Form*)}*
272   Evaluates the Forms in the first clause with a Key EQL to the value of
273   Keyform. If a singleton key is T then the clause is a default clause."
274   (case-body 'case keyform cases t 'eql nil nil nil))
275
276 (defmacro-mundanely ccase (keyform &body cases)
277   #!+sb-doc
278   "CCASE Keyform {({(Key*) | Key} Form*)}*
279   Evaluates the Forms in the first clause with a Key EQL to the value of
280   Keyform. If none of the keys matches then a correctable error is
281   signalled."
282   (case-body 'ccase keyform cases t 'eql t t t))
283
284 (defmacro-mundanely ecase (keyform &body cases)
285   #!+sb-doc
286   "ECASE Keyform {({(Key*) | Key} Form*)}*
287   Evaluates the Forms in the first clause with a Key EQL to the value of
288   Keyform. If none of the keys matches then an error is signalled."
289   (case-body 'ecase keyform cases t 'eql t nil t))
290
291 (defmacro-mundanely typecase (keyform &body cases)
292   #!+sb-doc
293   "TYPECASE Keyform {(Type Form*)}*
294   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
295   is true."
296   (case-body 'typecase keyform cases nil 'typep nil nil nil))
297
298 (defmacro-mundanely ctypecase (keyform &body cases)
299   #!+sb-doc
300   "CTYPECASE Keyform {(Type Form*)}*
301   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
302   is true. If no form is satisfied then a correctable error is signalled."
303   (case-body 'ctypecase keyform cases nil 'typep t t t))
304
305 (defmacro-mundanely etypecase (keyform &body cases)
306   #!+sb-doc
307   "ETYPECASE Keyform {(Type Form*)}*
308   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
309   is true. If no form is satisfied then an error is signalled."
310   (case-body 'etypecase keyform cases nil 'typep t nil t))
311 \f
312 ;;;; WITH-FOO i/o-related macros
313
314 (defmacro-mundanely with-open-stream ((var stream) &body forms-decls)
315   (multiple-value-bind (forms decls)
316       (parse-body forms-decls :doc-string-allowed nil)
317     (let ((abortp (gensym)))
318       `(let ((,var ,stream)
319              (,abortp t))
320          ,@decls
321          (unwind-protect
322              (multiple-value-prog1
323               (progn ,@forms)
324               (setq ,abortp nil))
325            (when ,var
326              (close ,var :abort ,abortp)))))))
327
328 (defmacro-mundanely with-open-file ((stream filespec &rest options)
329                                     &body body)
330   `(with-open-stream (,stream (open ,filespec ,@options))
331      ,@body))
332
333 (defmacro-mundanely with-input-from-string ((var string &key index start end)
334                                             &body forms-decls)
335   (multiple-value-bind (forms decls)
336       (parse-body forms-decls :doc-string-allowed nil)
337     ;; The ONCE-ONLY inhibits compiler note for unreachable code when
338     ;; END is true.
339     (once-only ((string string))
340       `(let ((,var
341               ,(cond ((null end)
342                       `(make-string-input-stream ,string ,(or start 0)))
343                      ((symbolp end)
344                       `(if ,end
345                            (make-string-input-stream ,string
346                                                      ,(or start 0)
347                                                      ,end)
348                            (make-string-input-stream ,string
349                                                      ,(or start 0))))
350                      (t
351                       `(make-string-input-stream ,string
352                                                  ,(or start 0)
353                                                  ,end)))))
354          ,@decls
355          (unwind-protect
356              (progn ,@forms)
357            (close ,var)
358            ,@(when index
359                `((setf ,index (string-input-stream-current ,var)))))))))
360
361 (defmacro-mundanely with-output-to-string 
362     ((var &optional string &key (element-type ''character))
363      &body forms-decls)
364   (multiple-value-bind (forms decls)
365       (parse-body forms-decls :doc-string-allowed nil)
366     (if string
367       `(let ((,var (make-fill-pointer-output-stream ,string)))
368          ,@decls
369          (unwind-protect
370              (progn ,@forms)
371            (close ,var)))
372       `(let ((,var (make-string-output-stream :element-type ,element-type)))
373          ,@decls
374          (unwind-protect
375              (progn ,@forms)
376            (close ,var))
377          (get-output-stream-string ,var)))))
378 \f
379 ;;;; miscellaneous macros
380
381 (defmacro-mundanely nth-value (n form)
382   #!+sb-doc
383   "Evaluate FORM and return the Nth value (zero based). This involves no
384   consing when N is a trivial constant integer."
385   ;; FIXME: The above is true, if slightly misleading.  The
386   ;; MULTIPLE-VALUE-BIND idiom [ as opposed to MULTIPLE-VALUE-CALL
387   ;; (LAMBDA (&REST VALUES) (NTH N VALUES)) ] does indeed not cons at
388   ;; runtime.  However, for large N (say N = 200), COMPILE on such a
389   ;; form will take longer than can be described as adequate, as the
390   ;; optional dispatch mechanism for the M-V-B gets increasingly
391   ;; hairy.
392   (if (integerp n)
393       (let ((dummy-list nil)
394             (keeper (gensym "KEEPER-")))
395         ;; We build DUMMY-LIST, a list of variables to bind to useless
396         ;; values, then we explicitly IGNORE those bindings and return
397         ;; KEEPER, the only thing we're really interested in right now.
398         (dotimes (i n)
399           (push (gensym "IGNORE-") dummy-list))
400         `(multiple-value-bind (,@dummy-list ,keeper) ,form
401            (declare (ignore ,@dummy-list))
402            ,keeper))
403       (once-only ((n n))
404         `(case (the fixnum ,n)
405            (0 (nth-value 0 ,form))
406            (1 (nth-value 1 ,form))
407            (2 (nth-value 2 ,form))
408            (t (nth (the fixnum ,n) (multiple-value-list ,form)))))))
409
410 (defmacro-mundanely declaim (&rest specs)
411   #!+sb-doc
412   "DECLAIM Declaration*
413   Do a declaration or declarations for the global environment."
414   `(eval-when (:compile-toplevel :load-toplevel :execute)
415      ,@(mapcar (lambda (spec) `(sb!xc:proclaim ',spec))
416                specs)))
417
418 (defmacro-mundanely print-unreadable-object ((object stream &key type identity)
419                                              &body body)
420   "Output OBJECT to STREAM with \"#<\" prefix, \">\" suffix, optionally
421   with object-type prefix and object-identity suffix, and executing the
422   code in BODY to provide possible further output."
423   `(%print-unreadable-object ,object ,stream ,type ,identity
424                              ,(if body
425                                   `(lambda () ,@body)
426                                   nil)))
427
428 (defmacro-mundanely ignore-errors (&rest forms)
429   #!+sb-doc
430   "Execute FORMS handling ERROR conditions, returning the result of the last
431   form, or (VALUES NIL the-ERROR-that-was-caught) if an ERROR was handled."
432   `(handler-case (progn ,@forms)
433      (error (condition) (values nil condition))))