1 ;;;; lots of basic macros for the target SBCL
3 ;;;; This software is part of the SBCL system. See the README file for
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.
12 (in-package "SB!IMPL")
14 ;;;; ASSERT and CHECK-TYPE
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
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.
28 (sb!xc
:defmacro assert
(test-form &optional places datum
&rest arguments
31 "Signals an error if the value of TEST-FORM is NIL. Returns NIL.
33 Optional DATUM and ARGUMENTS can be used to change the signaled
34 error condition and are interpreted as in (APPLY #'ERROR DATUM
37 Continuing from the signaled error using the CONTINUE restart will
38 allow the user to alter the values of the SETFable locations
39 specified in PLACES and then start over with TEST-FORM.
41 If TEST-FORM is of the form
45 where FUNCTION is a function (but not a special operator like
46 CL:OR, CL:AND, etc.) the results of evaluating the ARGs will be
47 included in the error report if the assertion fails."
48 (collect ((bindings) (infos))
49 (let* ((func (if (listp test-form
) (car test-form
)))
51 (if (and (typep func
'(and symbol
(not null
)))
52 (not (sb!xc
:macro-function func env
))
53 (not (sb!xc
:special-operator-p func
))
54 (proper-list-p (cdr test-form
)))
55 ;; TEST-FORM is a function call. We do not attempt this
56 ;; if TEST-FORM is a macro invocation or special form.
57 `(,func
,@(mapcar (lambda (place)
58 (if (sb!xc
:constantp place env
)
60 (with-unique-names (temp)
61 (bindings `(,temp
,place
))
62 (infos `(list ',place
,temp
))
65 ;; For all other cases, just evaluate TEST-FORM
66 ;; and don't report any details if the assertion fails.
70 ;; If TEST-FORM, potentially using values from BINDINGS, does not
71 ;; hold, enter a loop which reports the assertion error,
72 ;; potentially changes PLACES, and retries TEST-FORM.
78 (assert-error ',test-form
(list ,@(infos))
79 ',places
,datum
,@arguments
))
80 ,@(mapcar (lambda (place)
81 `(setf ,place
(assert-prompt ',place
,place
)))
86 (defun assert-prompt (name value
)
87 (cond ((y-or-n-p "The old value of ~S is ~S.~
88 ~%Do you want to supply a new value? "
90 (format *query-io
* "~&Type a form to be evaluated:~%")
91 (flet ((read-it () (eval (read *query-io
*))))
92 (if (symbolp name
) ;help user debug lexical variables
93 (progv (list name
) (list value
) (read-it))
97 ;;; CHECK-TYPE is written this way, to call CHECK-TYPE-ERROR, because
98 ;;; of how closures are compiled. RESTART-CASE has forms with closures
99 ;;; that the compiler causes to be generated at the top of any
100 ;;; function using RESTART-CASE, regardless of whether they are
101 ;;; needed. Because it would be nice if CHECK-TYPE were cheap to use,
102 ;;; and some things (e.g., READ-CHAR) can't afford this excessive
103 ;;; consing, we bend backwards a little.
105 ;;; CHECK-TYPE-ERROR isn't defined until a later file because it uses
106 ;;; the macro RESTART-CASE, which isn't defined until a later file.
107 (sb!xc
:defmacro check-type
(place type
&optional type-string
110 "Signal a restartable error of type TYPE-ERROR if the value of PLACE
111 is not of the specified type. If an error is signalled and the restart
112 is used to return, this can only return if the STORE-VALUE restart is
113 invoked. In that case it will store into PLACE and start over."
114 ;; Detect a common user-error.
115 (when (and (consp type
) (eq 'quote
(car type
)))
116 (error 'simple-reference-error
117 :format-control
"Quoted type specifier in ~S: ~S"
118 :format-arguments
(list 'check-type type
)
119 :references
(list '(:ansi-cl
:macro check-type
))))
120 ;; KLUDGE: We use a simpler form of expansion if PLACE is just a
121 ;; variable to work around Python's blind spot in type derivation.
122 ;; For more complex places getting the type derived should not
123 ;; matter so much anyhow.
124 (let ((expanded (%macroexpand place env
)))
125 (if (symbolp expanded
)
127 ((typep ,place
',type
))
128 (setf ,place
(check-type-error ',place
,place
',type
,type-string
)))
129 (let ((value (gensym)))
130 `(do ((,value
,place
,place
))
131 ((typep ,value
',type
))
133 (check-type-error ',place
,value
',type
,type-string
)))))))
135 ;;;; DEFINE-SYMBOL-MACRO
137 (sb!xc
:defmacro define-symbol-macro
(name expansion
)
138 `(eval-when (:compile-toplevel
:load-toplevel
:execute
)
139 (sb!c
::%define-symbol-macro
',name
',expansion
(sb!c
:source-location
))))
141 (defun sb!c
::%define-symbol-macro
(name expansion source-location
)
142 (unless (symbolp name
)
143 (error 'simple-type-error
:datum name
:expected-type
'symbol
144 :format-control
"Symbol macro name is not a symbol: ~S."
145 :format-arguments
(list name
)))
146 (with-single-package-locked-error
147 (:symbol name
"defining ~A as a symbol-macro"))
148 (let ((kind (info :variable
:kind name
)))
151 (when source-location
152 (setf (info :source-location
:symbol-macro name
) source-location
))
153 (setf (info :variable
:kind name
) :macro
)
154 (setf (info :variable
:macro-expansion name
) expansion
))
156 (error 'simple-program-error
157 :format-control
"Symbol ~S is already defined as ~A."
158 :format-arguments
(list name
160 (:alien
"an alien variable")
161 (:constant
"a constant")
162 (:special
"a special variable")
163 (:global
"a global variable")
167 ;;;; DEFINE-COMPILER-MACRO
169 (sb!xc
:defmacro define-compiler-macro
(name lambda-list
&body body
)
171 "Define a compiler-macro for NAME."
172 (legal-fun-name-or-type-error name
)
173 (when (and (symbolp name
) (special-operator-p name
))
174 (error 'simple-program-error
175 :format-control
"cannot define a compiler-macro for a special operator: ~S"
176 :format-arguments
(list name
)))
177 ;; DEBUG-NAME is called primarily for its side-effect of asserting
178 ;; that (COMPILER-MACRO-FUNCTION x) is not a legal function name.
179 (let ((def (make-macro-lambda (sb!c
::debug-name
'compiler-macro name
)
180 lambda-list body
'define-compiler-macro name
181 :accessor
'sb
!c
::compiler-macro-args
)))
183 (eval-when (:compile-toplevel
)
184 (sb!c
::%compiler-defmacro
:compiler-macro-function
',name t
))
185 (eval-when (:compile-toplevel
:load-toplevel
:execute
)
186 (sb!c
::%define-compiler-macro
',name
,def
)))))
188 (eval-when (#-sb-xc
:compile-toplevel
:load-toplevel
:execute
)
189 (defun sb!c
::%define-compiler-macro
(name definition
)
190 (sb!c
::warn-if-compiler-macro-dependency-problem name
)
191 ;; FIXME: warn about incompatible lambda list with
192 ;; respect to parent function?
193 (setf (sb!xc
:compiler-macro-function name
) definition
)
196 ;;;; CASE, TYPECASE, and friends
198 (eval-when (#-sb-xc
:compile-toplevel
:load-toplevel
:execute
)
200 ;;; Make this a full warning during SBCL build.
201 (define-condition duplicate-case-key-warning
(#-sb-xc-host style-warning
#+sb-xc-host warning
)
203 :reader case-warning-key
)
204 (case-kind :initarg
:case-kind
205 :reader case-warning-case-kind
)
206 (occurrences :initarg
:occurrences
208 :reader duplicate-case-key-warning-occurrences
))
210 (lambda (condition stream
)
212 "Duplicate key ~S in ~S form, ~
213 occurring in~{~#[~; and~]~{ the ~:R clause:~%~< ~S~:>~}~^,~}."
214 (case-warning-key condition
)
215 (case-warning-case-kind condition
)
216 (duplicate-case-key-warning-occurrences condition
)))))
218 ;;; CASE-BODY returns code for all the standard "case" macros. NAME is
219 ;;; the macro name, and KEYFORM is the thing to case on. MULTI-P
220 ;;; indicates whether a branch may fire off a list of keys; otherwise,
221 ;;; a key that is a list is interpreted in some way as a single key.
222 ;;; When MULTI-P, TEST is applied to the value of KEYFORM and each key
223 ;;; for a given branch; otherwise, TEST is applied to the value of
224 ;;; KEYFORM and the entire first element, instead of each part, of the
225 ;;; case branch. When ERRORP, no OTHERWISE-CLAUSEs are recognized,
226 ;;; and an ERROR form is generated where control falls off the end
227 ;;; of the ordinary clauses. When PROCEEDP, it is an error to
228 ;;; omit ERRORP, and the ERROR form generated is executed within a
229 ;;; RESTART-CASE allowing KEYFORM to be set and retested.
230 (defun case-body (name keyform cases multi-p test errorp proceedp needcasesp
)
231 (unless (or cases
(not needcasesp
))
232 (warn "no clauses in ~S" name
))
233 (let ((keyform-value (gensym))
236 (keys-seen (make-hash-table :test
#'eql
)))
237 (do* ((cases cases
(cdr cases
))
238 (case (car cases
) (car cases
))
239 (case-position 1 (1+ case-position
)))
241 (flet ((check-clause (case-keys)
242 (loop for k in case-keys
243 for existing
= (gethash k keys-seen
)
245 (let ((sb!c
::*current-path
*
246 (when (boundp 'sb
!c
::*source-paths
*)
247 (or (sb!c
::get-source-path case
)
248 (and (boundp 'sb
!c
::*current-path
*)
249 sb
!c
::*current-path
*)))))
250 (warn 'duplicate-case-key-warning
253 :occurrences
`(,existing
(,case-position
(,case
)))))))
254 (let ((record (list case-position
(list case
))))
255 (dolist (k case-keys
)
256 (setf (gethash k keys-seen
) record
)))))
257 (unless (list-of-length-at-least-p case
1)
258 (error "~S -- bad clause in ~S" case name
))
259 (destructuring-bind (keyoid &rest forms
) case
260 (cond (;; an OTHERWISE-CLAUSE
262 ;; By the way... The old code here tried gave
263 ;; STYLE-WARNINGs for normal-clauses which looked as
264 ;; though they might've been intended to be
265 ;; otherwise-clauses. As Tony Martinez reported on
266 ;; sbcl-devel 2004-11-09 there are sometimes good
267 ;; reasons to write clauses like that; and as I noticed
268 ;; when trying to understand the old code so I could
269 ;; understand his patch, trying to guess which clauses
270 ;; don't have good reasons is fundamentally kind of a
271 ;; mess. SBCL does issue style warnings rather
272 ;; enthusiastically, and I have often justified that by
273 ;; arguing that we're doing that to detect issues which
274 ;; are tedious for programmers to detect for by
275 ;; proofreading (like small typoes in long symbol
276 ;; names, or duplicate function definitions in large
277 ;; files). This doesn't seem to be an issue like that,
278 ;; and I can't think of a comparably good justification
279 ;; for giving STYLE-WARNINGs for legal code here, so
280 ;; now we just hope the programmer knows what he's
281 ;; doing. -- WHN 2004-11-20
282 (and (not errorp
) ; possible only in CASE or TYPECASE,
283 ; not in [EC]CASE or [EC]TYPECASE
284 (memq keyoid
'(t otherwise
))
286 (push `(t nil
,@forms
) clauses
))
287 ((and multi-p
(listp keyoid
))
288 (setf keys
(nconc (reverse keyoid
) keys
))
289 (check-clause keyoid
)
290 (push `((or ,@(mapcar (lambda (key)
291 `(,test
,keyform-value
',key
))
297 (when (and (eq name
'case
)
299 (memq keyoid
'(t otherwise
)))
300 (error 'simple-reference-error
302 "~@<~IBad ~S clause:~:@_ ~S~:@_~S allowed as the key ~
303 designator only in the final otherwise-clause, not in a ~
304 normal-clause. Use (~S) instead, or move the clause the ~
305 correct position.~:@>"
306 :format-arguments
(list 'case case keyoid keyoid
)
307 :references
`((:ansi-cl
:macro case
))))
309 (check-clause (list keyoid
))
310 (push `((,test
,keyform-value
',keyoid
)
315 (nreverse (mapcon (lambda (tail)
316 (unless (member (car tail
) (cdr tail
))
319 (case-body-aux name keyform keyform-value clauses keys errorp proceedp
320 `(,(if multi-p
'member
'or
) ,@keys
))))
322 ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled
323 ;;; all the cases. Note: it is not necessary that the resulting code
324 ;;; signal case-failure conditions, but that's what KMP's prototype
325 ;;; code did. We call CASE-BODY-ERROR, because of how closures are
326 ;;; compiled. RESTART-CASE has forms with closures that the compiler
327 ;;; causes to be generated at the top of any function using the case
328 ;;; macros, regardless of whether they are needed.
330 ;;; The CASE-BODY-ERROR function is defined later, when the
331 ;;; RESTART-CASE macro has been defined.
332 (defun case-body-aux (name keyform keyform-value clauses keys
333 errorp proceedp expected-type
)
335 (let ((block (gensym))
337 `(let ((,keyform-value
,keyform
))
343 (cond ,@(nreverse clauses
)
348 ',name
',keyform
,keyform-value
349 ',expected-type
',keys
)))
351 `(let ((,keyform-value
,keyform
))
352 (declare (ignorable ,keyform-value
)) ; e.g. (CASE KEY (T))
356 `((t (case-failure ',name
,keyform-value
',keys
))))))))
359 (sb!xc
:defmacro case
(keyform &body cases
)
361 "CASE Keyform {({(Key*) | Key} Form*)}*
362 Evaluates the Forms in the first clause with a Key EQL to the value of
363 Keyform. If a singleton key is T then the clause is a default clause."
364 (case-body 'case keyform cases t
'eql nil nil nil
))
366 (sb!xc
:defmacro ccase
(keyform &body cases
)
368 "CCASE Keyform {({(Key*) | Key} Form*)}*
369 Evaluates the Forms in the first clause with a Key EQL to the value of
370 Keyform. If none of the keys matches then a correctable error is
372 (case-body 'ccase keyform cases t
'eql t t t
))
374 (sb!xc
:defmacro ecase
(keyform &body cases
)
376 "ECASE Keyform {({(Key*) | Key} Form*)}*
377 Evaluates the Forms in the first clause with a Key EQL to the value of
378 Keyform. If none of the keys matches then an error is signalled."
379 (case-body 'ecase keyform cases t
'eql t nil t
))
381 (sb!xc
:defmacro typecase
(keyform &body cases
)
383 "TYPECASE Keyform {(Type Form*)}*
384 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
386 (case-body 'typecase keyform cases nil
'typep nil nil nil
))
388 (sb!xc
:defmacro ctypecase
(keyform &body cases
)
390 "CTYPECASE Keyform {(Type Form*)}*
391 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
392 is true. If no form is satisfied then a correctable error is signalled."
393 (case-body 'ctypecase keyform cases nil
'typep t t t
))
395 (sb!xc
:defmacro etypecase
(keyform &body cases
)
397 "ETYPECASE Keyform {(Type Form*)}*
398 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
399 is true. If no form is satisfied then an error is signalled."
400 (case-body 'etypecase keyform cases nil
'typep t nil t
))
402 ;;; Compile a version of BODY for all TYPES, and dispatch to the
403 ;;; correct one based on the value of VAR. This was originally used
404 ;;; only for strings, hence the name. Renaming it to something more
405 ;;; generic might not be a bad idea.
406 (sb!xc
:defmacro string-dispatch
((&rest types
) var
&body body
)
407 (let ((fun (sb!xc
:gensym
"STRING-DISPATCH-FUN")))
410 (declare (inline ,fun
))
412 ,@(loop for type in types
413 ;; TRULY-THE allows transforms to take advantage of the type
414 ;; information without need for constraint propagation.
415 collect
`(,type
(,fun
(truly-the ,type
,var
))))))))
417 ;;;; WITH-FOO i/o-related macros
419 (sb!xc
:defmacro with-open-stream
((var stream
) &body forms-decls
)
420 (multiple-value-bind (forms decls
) (parse-body forms-decls nil
)
421 (let ((abortp (gensym)))
422 `(let ((,var
,stream
)
426 (multiple-value-prog1
430 (close ,var
:abort
,abortp
)))))))
432 (sb!xc
:defmacro with-open-file
((stream filespec
&rest options
)
434 `(with-open-stream (,stream
(open ,filespec
,@options
))
437 (sb!xc
:defmacro with-input-from-string
((var string
&key index start end
)
439 (multiple-value-bind (forms decls
) (parse-body forms-decls nil
)
441 ;; Should (WITH-INPUT-FROM-STRING (stream str :start nil :end 5))
442 ;; pass the explicit NIL, and thus get an error? It's logical
443 ;; because an explicit NIL does not mean "default" in any other
444 ;; string operation. So why does it here?
446 `(make-string-input-stream ,string
,@(if start
(list start
)))
447 `(make-string-input-stream ,string
,(or start
0) ,end
))))
449 (multiple-value-prog1
454 `((setf ,index
(string-input-stream-current ,var
))))))))
456 (sb!xc
:defmacro with-output-to-string
457 ((var &optional string
&key
(element-type ''character
))
459 (multiple-value-bind (forms decls
) (parse-body forms-decls nil
)
461 (let ((element-type-var (gensym)))
462 `(let ((,var
(make-fill-pointer-output-stream ,string
))
463 ;; ELEMENT-TYPE isn't currently used for anything
464 ;; (see FILL-POINTER-OUTPUT-STREAM FIXME in stream.lisp),
465 ;; but it still has to be evaluated for side-effects.
466 (,element-type-var
,element-type
))
467 (declare (ignore ,element-type-var
))
472 `(let ((,var
(make-string-output-stream
473 ;; CHARACTER is the default element-type of
474 ;; string-ouput-stream, save a few bytes when passing it
475 ,@(and (not (equal element-type
''character
))
476 `(:element-type
,element-type
)))))
481 (get-output-stream-string ,var
)))))
483 ;;;; miscellaneous macros
485 (sb!xc
:defmacro nth-value
(n form
&environment env
)
487 "Evaluate FORM and return the Nth value (zero based)
488 without consing a temporary list of values."
489 ;; FIXME: The above is true, if slightly misleading. The
490 ;; MULTIPLE-VALUE-BIND idiom [ as opposed to MULTIPLE-VALUE-CALL
491 ;; (LAMBDA (&REST VALUES) (NTH N VALUES)) ] does indeed not cons at
492 ;; runtime. However, for large N (say N = 200), COMPILE on such a
493 ;; form will take longer than can be described as adequate, as the
494 ;; optional dispatch mechanism for the M-V-B gets increasingly
496 (let ((val (and (sb!xc
:constantp n env
) (constant-form-value n env
))))
497 (if (and (integerp val
) (<= 0 val
10)) ; Arbitrary limit.
498 (let ((dummy-list (make-gensym-list val
))
499 (keeper (sb!xc
:gensym
"KEEPER")))
500 `(multiple-value-bind (,@dummy-list
,keeper
) ,form
501 (declare (ignore ,@dummy-list
))
503 ;; &MORE conversion handily deals with non-constant N,
504 ;; avoiding the unstylish practice of inserting FORM into the
505 ;; expansion more than once to pick off a few small values.
506 ;; This is not as good as above, because it uses TAIL-CALL-VARIABLE.
507 `(multiple-value-call
508 (lambda (n &rest list
) (nth (truly-the index n
) list
))
509 (the index
,n
) ,form
))))
511 (sb!xc
:defmacro declaim
(&rest specs
)
513 "DECLAIM Declaration*
514 Do a declaration or declarations for the global environment."
515 `(eval-when (:compile-toplevel
:load-toplevel
:execute
)
516 ,@(mapcar (lambda (spec)
517 `(sb!c
::%proclaim
',spec
(sb!c
:source-location
)))
520 ;; Avoid unknown return values in emitted code for PRINT-UNREADABLE-OBJECT
521 (declaim (ftype (sfunction (t t t t
&optional t
) null
)
522 %print-unreadable-object
))
523 (sb!xc
:defmacro print-unreadable-object
((object stream
&key type identity
)
526 "Output OBJECT to STREAM with \"#<\" prefix, \">\" suffix, optionally
527 with object-type prefix and object-identity suffix, and executing the
528 code in BODY to provide possible further output."
529 ;; Note: possibly out-of-order keyword argument evaluation.
530 (let ((call `(%print-unreadable-object
,object
,stream
,type
,identity
)))
532 (let ((fun (make-symbol "THUNK")))
533 `(dx-flet ((,fun
() ,@body
)) (,@call
#',fun
)))
536 (sb!xc
:defmacro ignore-errors
(&rest forms
)
538 "Execute FORMS handling ERROR conditions, returning the result of the last
539 form, or (VALUES NIL the-ERROR-that-was-caught) if an ERROR was handled."
540 `(handler-case (progn ,@forms
)
541 (error (condition) (values nil condition
))))
543 ;; A macroexpander helper. Not sure where else to put this.
544 (defun funarg-bind/call-forms
(funarg arg-forms
)
546 '(or (cons (eql function
) (cons (satisfies legal-fun-name-p
) null
))
547 (cons (eql quote
) (cons symbol null
))
548 (cons (eql lambda
))))
549 (values nil
`(funcall ,funarg .
,arg-forms
))
550 (let ((fn-sym (sb!xc
:gensym
))) ; for ONCE-ONLY-ish purposes
551 (values `((,fn-sym
(%coerce-callable-to-fun
,funarg
)))
552 `(sb!c
::%funcall
,fn-sym .
,arg-forms
)))))