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