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.
27 (defmacro-mundanely 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))
49 (flet ((process-place (place)
50 (if (sb!xc
:constantp place env
)
52 (with-unique-names (temp)
53 (bindings `(,temp
,place
))
54 (infos `(list ',place
,temp
))
57 ;; TEST-FORM looks like a function call. We do not
58 ;; attempt this if TEST-FORM is the application of a
59 ;; special operator because of argument evaluation
61 ((when (typep test-form
'(cons symbol list
))
62 (let* ((name (first test-form
))
64 (eq (info :function
:kind name
) :function
)))
67 (let ((f (cdr (assoc name
(sb!c
::lexenv-funs env
)))))
68 (if (not f
) global-fun-p
(sb!c
::functional-p f
))))
69 #!+(and sb-fasteval
(host-feature sb-xc
))
70 (sb!interpreter
:basic-env
72 (sb!interpreter
::find-lexical-fun env name
)))
73 (if (null kind
) global-fun-p
(eq kind
:function
))))
75 `(,name
,@(mapcar #'process-place
(rest test-form
)))))))
76 ;; For all other cases, just evaluate TEST-FORM and do
77 ;; not report any details if the assertion fails.
80 ;; If TEST-FORM, potentially using values from BINDINGS, does not
81 ;; hold, enter a loop which reports the assertion error,
82 ;; potentially changes PLACES, and retries TEST-FORM.
88 (assert-error ',test-form
(list ,@(infos))
89 ',places
,datum
,@arguments
))
90 ,@(mapcar (lambda (place)
91 `(setf ,place
(assert-prompt ',place
,place
)))
96 (defun assert-prompt (name value
)
97 (cond ((y-or-n-p "The old value of ~S is ~S.~
98 ~%Do you want to supply a new value? "
100 (format *query-io
* "~&Type a form to be evaluated:~%")
101 (flet ((read-it () (eval (read *query-io
*))))
102 (if (symbolp name
) ;help user debug lexical variables
103 (progv (list name
) (list value
) (read-it))
107 ;;; CHECK-TYPE is written this way, to call CHECK-TYPE-ERROR, because
108 ;;; of how closures are compiled. RESTART-CASE has forms with closures
109 ;;; that the compiler causes to be generated at the top of any
110 ;;; function using RESTART-CASE, regardless of whether they are
111 ;;; needed. Because it would be nice if CHECK-TYPE were cheap to use,
112 ;;; and some things (e.g., READ-CHAR) can't afford this excessive
113 ;;; consing, we bend backwards a little.
115 ;;; CHECK-TYPE-ERROR isn't defined until a later file because it uses
116 ;;; the macro RESTART-CASE, which isn't defined until a later file.
117 (defmacro-mundanely check-type
(place type
&optional type-string
120 "Signal a restartable error of type TYPE-ERROR if the value of PLACE
121 is not of the specified type. If an error is signalled and the restart
122 is used to return, this can only return if the STORE-VALUE restart is
123 invoked. In that case it will store into PLACE and start over."
124 ;; Detect a common user-error.
125 (when (and (consp type
) (eq 'quote
(car type
)))
126 (error 'simple-reference-error
127 :format-control
"Quoted type specifier in ~S: ~S"
128 :format-arguments
(list 'check-type type
)
129 :references
(list '(:ansi-cl
:macro check-type
))))
130 ;; KLUDGE: We use a simpler form of expansion if PLACE is just a
131 ;; variable to work around Python's blind spot in type derivation.
132 ;; For more complex places getting the type derived should not
133 ;; matter so much anyhow.
134 (let ((expanded (%macroexpand place env
)))
135 (if (symbolp expanded
)
137 ((typep ,place
',type
))
138 (setf ,place
(check-type-error ',place
,place
',type
,type-string
)))
139 (let ((value (gensym)))
140 `(do ((,value
,place
,place
))
141 ((typep ,value
',type
))
143 (check-type-error ',place
,value
',type
,type-string
)))))))
145 ;;;; DEFINE-SYMBOL-MACRO
147 (defmacro-mundanely define-symbol-macro
(name expansion
)
148 `(eval-when (:compile-toplevel
:load-toplevel
:execute
)
149 (sb!c
::%define-symbol-macro
',name
',expansion
(sb!c
:source-location
))))
151 (defun sb!c
::%define-symbol-macro
(name expansion source-location
)
152 (unless (symbolp name
)
153 (error 'simple-type-error
:datum name
:expected-type
'symbol
154 :format-control
"Symbol macro name is not a symbol: ~S."
155 :format-arguments
(list name
)))
156 (with-single-package-locked-error
157 (:symbol name
"defining ~A as a symbol-macro"))
158 (let ((kind (info :variable
:kind name
)))
161 (when source-location
162 (setf (info :source-location
:symbol-macro name
) source-location
))
163 (setf (info :variable
:kind name
) :macro
)
164 (setf (info :variable
:macro-expansion name
) expansion
))
166 (error 'simple-program-error
167 :format-control
"Symbol ~S is already defined as ~A."
168 :format-arguments
(list name
170 (:alien
"an alien variable")
171 (:constant
"a constant")
172 (:special
"a special variable")
173 (:global
"a global variable")
177 ;;;; DEFINE-COMPILER-MACRO
179 (defmacro-mundanely define-compiler-macro
(name lambda-list
&body body
)
181 "Define a compiler-macro for NAME."
182 (legal-fun-name-or-type-error name
)
183 (when (and (symbolp name
) (special-operator-p name
))
184 (error 'simple-program-error
185 :format-control
"cannot define a compiler-macro for a special operator: ~S"
186 :format-arguments
(list name
)))
187 ;; DEBUG-NAME is called primarily for its side-effect of asserting
188 ;; that (COMPILER-MACRO-FUNCTION x) is not a legal function name.
189 (let ((def (make-macro-lambda (sb!c
::debug-name
'compiler-macro name
)
190 lambda-list body
'define-compiler-macro name
191 :accessor
'sb
!c
::compiler-macro-args
)))
193 (eval-when (:compile-toplevel
)
194 (sb!c
::%compiler-defmacro
:compiler-macro-function
',name t
))
195 (eval-when (:compile-toplevel
:load-toplevel
:execute
)
196 (sb!c
::%define-compiler-macro
',name
,def
)))))
198 (eval-when (#-sb-xc
:compile-toplevel
:load-toplevel
:execute
)
199 (defun sb!c
::%define-compiler-macro
(name definition
)
200 (sb!c
::warn-if-compiler-macro-dependency-problem name
)
201 ;; FIXME: warn about incompatible lambda list with
202 ;; respect to parent function?
203 (setf (sb!xc
:compiler-macro-function name
) definition
)
206 ;;;; CASE, TYPECASE, and friends
208 (eval-when (#-sb-xc
:compile-toplevel
:load-toplevel
:execute
)
210 ;;; Make this a full warning during SBCL build.
211 (define-condition duplicate-case-key-warning
(#-sb-xc-host style-warning
#+sb-xc-host warning
)
213 :reader case-warning-key
)
214 (case-kind :initarg
:case-kind
215 :reader case-warning-case-kind
)
216 (occurrences :initarg
:occurrences
218 :reader duplicate-case-key-warning-occurrences
))
220 (lambda (condition stream
)
222 "Duplicate key ~S in ~S form, ~
223 occurring in~{~#[~; and~]~{ the ~:R clause:~%~< ~S~:>~}~^,~}."
224 (case-warning-key condition
)
225 (case-warning-case-kind condition
)
226 (duplicate-case-key-warning-occurrences condition
)))))
228 ;;; CASE-BODY returns code for all the standard "case" macros. NAME is
229 ;;; the macro name, and KEYFORM is the thing to case on. MULTI-P
230 ;;; indicates whether a branch may fire off a list of keys; otherwise,
231 ;;; a key that is a list is interpreted in some way as a single key.
232 ;;; When MULTI-P, TEST is applied to the value of KEYFORM and each key
233 ;;; for a given branch; otherwise, TEST is applied to the value of
234 ;;; KEYFORM and the entire first element, instead of each part, of the
235 ;;; case branch. When ERRORP, no OTHERWISE-CLAUSEs are recognized,
236 ;;; and an ERROR form is generated where control falls off the end
237 ;;; of the ordinary clauses. When PROCEEDP, it is an error to
238 ;;; omit ERRORP, and the ERROR form generated is executed within a
239 ;;; RESTART-CASE allowing KEYFORM to be set and retested.
240 (defun case-body (name keyform cases multi-p test errorp proceedp needcasesp
)
241 (unless (or cases
(not needcasesp
))
242 (warn "no clauses in ~S" name
))
243 (let ((keyform-value (gensym))
246 (keys-seen (make-hash-table :test
#'eql
)))
247 (do* ((cases cases
(cdr cases
))
248 (case (car cases
) (car cases
))
249 (case-position 1 (1+ case-position
)))
251 (flet ((check-clause (case-keys)
252 (loop for k in case-keys
253 for existing
= (gethash k keys-seen
)
255 (let ((sb!c
::*current-path
*
256 (when (boundp 'sb
!c
::*source-paths
*)
257 (or (sb!c
::get-source-path case
)
258 (and (boundp 'sb
!c
::*current-path
*)
259 sb
!c
::*current-path
*)))))
260 (warn 'duplicate-case-key-warning
263 :occurrences
`(,existing
(,case-position
(,case
)))))))
264 (let ((record (list case-position
(list case
))))
265 (dolist (k case-keys
)
266 (setf (gethash k keys-seen
) record
)))))
267 (unless (list-of-length-at-least-p case
1)
268 (error "~S -- bad clause in ~S" case name
))
269 (destructuring-bind (keyoid &rest forms
) case
270 (cond (;; an OTHERWISE-CLAUSE
272 ;; By the way... The old code here tried gave
273 ;; STYLE-WARNINGs for normal-clauses which looked as
274 ;; though they might've been intended to be
275 ;; otherwise-clauses. As Tony Martinez reported on
276 ;; sbcl-devel 2004-11-09 there are sometimes good
277 ;; reasons to write clauses like that; and as I noticed
278 ;; when trying to understand the old code so I could
279 ;; understand his patch, trying to guess which clauses
280 ;; don't have good reasons is fundamentally kind of a
281 ;; mess. SBCL does issue style warnings rather
282 ;; enthusiastically, and I have often justified that by
283 ;; arguing that we're doing that to detect issues which
284 ;; are tedious for programmers to detect for by
285 ;; proofreading (like small typoes in long symbol
286 ;; names, or duplicate function definitions in large
287 ;; files). This doesn't seem to be an issue like that,
288 ;; and I can't think of a comparably good justification
289 ;; for giving STYLE-WARNINGs for legal code here, so
290 ;; now we just hope the programmer knows what he's
291 ;; doing. -- WHN 2004-11-20
292 (and (not errorp
) ; possible only in CASE or TYPECASE,
293 ; not in [EC]CASE or [EC]TYPECASE
294 (memq keyoid
'(t otherwise
))
296 (push `(t nil
,@forms
) clauses
))
297 ((and multi-p
(listp keyoid
))
298 (setf keys
(nconc (reverse keyoid
) keys
))
299 (check-clause keyoid
)
300 (push `((or ,@(mapcar (lambda (key)
301 `(,test
,keyform-value
',key
))
307 (when (and (eq name
'case
)
309 (memq keyoid
'(t otherwise
)))
310 (error 'simple-reference-error
312 "~@<~IBad ~S clause:~:@_ ~S~:@_~S allowed as the key ~
313 designator only in the final otherwise-clause, not in a ~
314 normal-clause. Use (~S) instead, or move the clause the ~
315 correct position.~:@>"
316 :format-arguments
(list 'case case keyoid keyoid
)
317 :references
`((:ansi-cl
:macro case
))))
319 (check-clause (list keyoid
))
320 (push `((,test
,keyform-value
',keyoid
)
325 (nreverse (mapcon (lambda (tail)
326 (unless (member (car tail
) (cdr tail
))
329 (case-body-aux name keyform keyform-value clauses keys errorp proceedp
330 `(,(if multi-p
'member
'or
) ,@keys
))))
332 ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled
333 ;;; all the cases. Note: it is not necessary that the resulting code
334 ;;; signal case-failure conditions, but that's what KMP's prototype
335 ;;; code did. We call CASE-BODY-ERROR, because of how closures are
336 ;;; compiled. RESTART-CASE has forms with closures that the compiler
337 ;;; causes to be generated at the top of any function using the case
338 ;;; macros, regardless of whether they are needed.
340 ;;; The CASE-BODY-ERROR function is defined later, when the
341 ;;; RESTART-CASE macro has been defined.
342 (defun case-body-aux (name keyform keyform-value clauses keys
343 errorp proceedp expected-type
)
345 (let ((block (gensym))
347 `(let ((,keyform-value
,keyform
))
353 (cond ,@(nreverse clauses
)
358 ',name
',keyform
,keyform-value
359 ',expected-type
',keys
)))
361 `(let ((,keyform-value
,keyform
))
362 (declare (ignorable ,keyform-value
)) ; e.g. (CASE KEY (T))
366 `((t (case-failure ',name
,keyform-value
',keys
))))))))
369 (defmacro-mundanely 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 (defmacro-mundanely ccase
(keyform &body cases
)
378 "CCASE Keyform {({(Key*) | Key} Form*)}*
379 Evaluates the Forms in the first clause with a Key EQL to the value of
380 Keyform. If none of the keys matches then a correctable error is
382 (case-body 'ccase keyform cases t
'eql t t t
))
384 (defmacro-mundanely ecase
(keyform &body cases
)
386 "ECASE Keyform {({(Key*) | Key} Form*)}*
387 Evaluates the Forms in the first clause with a Key EQL to the value of
388 Keyform. If none of the keys matches then an error is signalled."
389 (case-body 'ecase keyform cases t
'eql t nil t
))
391 (defmacro-mundanely typecase
(keyform &body cases
)
393 "TYPECASE Keyform {(Type Form*)}*
394 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
396 (case-body 'typecase keyform cases nil
'typep nil nil nil
))
398 (defmacro-mundanely ctypecase
(keyform &body cases
)
400 "CTYPECASE Keyform {(Type Form*)}*
401 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
402 is true. If no form is satisfied then a correctable error is signalled."
403 (case-body 'ctypecase keyform cases nil
'typep t t t
))
405 (defmacro-mundanely etypecase
(keyform &body cases
)
407 "ETYPECASE Keyform {(Type Form*)}*
408 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
409 is true. If no form is satisfied then an error is signalled."
410 (case-body 'etypecase keyform cases nil
'typep t nil t
))
412 ;;;; WITH-FOO i/o-related macros
414 (defmacro-mundanely with-open-stream
((var stream
) &body forms-decls
)
415 (multiple-value-bind (forms decls
) (parse-body forms-decls nil
)
416 (let ((abortp (gensym)))
417 `(let ((,var
,stream
)
421 (multiple-value-prog1
425 (close ,var
:abort
,abortp
)))))))
427 (defmacro-mundanely with-open-file
((stream filespec
&rest options
)
429 `(with-open-stream (,stream
(open ,filespec
,@options
))
432 (defmacro-mundanely with-input-from-string
((var string
&key index start end
)
434 (multiple-value-bind (forms decls
) (parse-body forms-decls nil
)
436 ;; Should (WITH-INPUT-FROM-STRING (stream str :start nil :end 5))
437 ;; pass the explicit NIL, and thus get an error? It's logical
438 ;; because an explicit NIL does not mean "default" in any other
439 ;; string operation. So why does it here?
441 `(make-string-input-stream ,string
,@(if start
(list start
)))
442 `(make-string-input-stream ,string
,(or start
0) ,end
))))
444 (multiple-value-prog1
449 `((setf ,index
(string-input-stream-current ,var
))))))))
451 (defmacro-mundanely with-output-to-string
452 ((var &optional string
&key
(element-type ''character
))
454 (multiple-value-bind (forms decls
) (parse-body forms-decls nil
)
456 (let ((element-type-var (gensym)))
457 `(let ((,var
(make-fill-pointer-output-stream ,string
))
458 ;; ELEMENT-TYPE isn't currently used for anything
459 ;; (see FILL-POINTER-OUTPUT-STREAM FIXME in stream.lisp),
460 ;; but it still has to be evaluated for side-effects.
461 (,element-type-var
,element-type
))
462 (declare (ignore ,element-type-var
))
467 `(let ((,var
(make-string-output-stream
468 ;; CHARACTER is the default element-type of
469 ;; string-ouput-stream, save a few bytes when passing it
470 ,@(and (not (equal element-type
''character
))
471 `(:element-type
,element-type
)))))
476 (get-output-stream-string ,var
)))))
478 ;;;; miscellaneous macros
480 (defmacro-mundanely nth-value
(n form
&environment env
)
482 "Evaluate FORM and return the Nth value (zero based)
483 without consing a temporary list of values."
484 ;; FIXME: The above is true, if slightly misleading. The
485 ;; MULTIPLE-VALUE-BIND idiom [ as opposed to MULTIPLE-VALUE-CALL
486 ;; (LAMBDA (&REST VALUES) (NTH N VALUES)) ] does indeed not cons at
487 ;; runtime. However, for large N (say N = 200), COMPILE on such a
488 ;; form will take longer than can be described as adequate, as the
489 ;; optional dispatch mechanism for the M-V-B gets increasingly
491 (let ((val (and (sb!xc
:constantp n env
) (constant-form-value n env
))))
492 (if (and (integerp val
) (<= 0 val
10)) ; Arbitrary limit.
493 (let ((dummy-list (make-gensym-list val
))
494 (keeper (sb!xc
:gensym
"KEEPER")))
495 `(multiple-value-bind (,@dummy-list
,keeper
) ,form
496 (declare (ignore ,@dummy-list
))
498 ;; &MORE conversion handily deals with non-constant N,
499 ;; avoiding the unstylish practice of inserting FORM into the
500 ;; expansion more than once to pick off a few small values.
501 ;; This is not as good as above, because it uses TAIL-CALL-VARIABLE.
502 `(multiple-value-call
503 (lambda (n &rest list
) (nth (truly-the index n
) list
))
504 (the index
,n
) ,form
))))
506 (defmacro-mundanely declaim
(&rest specs
)
508 "DECLAIM Declaration*
509 Do a declaration or declarations for the global environment."
510 `(eval-when (:compile-toplevel
:load-toplevel
:execute
)
511 ,@(mapcar (lambda (spec)
512 `(sb!c
::%proclaim
',spec
(sb!c
:source-location
)))
515 ;; Avoid unknown return values in emitted code for PRINT-UNREADABLE-OBJECT
516 (declaim (ftype (sfunction (t t t t
&optional t
) null
)
517 %print-unreadable-object
))
518 (defmacro-mundanely print-unreadable-object
((object stream
&key type identity
)
521 "Output OBJECT to STREAM with \"#<\" prefix, \">\" suffix, optionally
522 with object-type prefix and object-identity suffix, and executing the
523 code in BODY to provide possible further output."
524 ;; Note: possibly out-of-order keyword argument evaluation.
525 (let ((call `(%print-unreadable-object
,object
,stream
,type
,identity
)))
527 (let ((fun (make-symbol "THUNK")))
528 `(dx-flet ((,fun
() ,@body
)) (,@call
#',fun
)))
531 (defmacro-mundanely ignore-errors
(&rest forms
)
533 "Execute FORMS handling ERROR conditions, returning the result of the last
534 form, or (VALUES NIL the-ERROR-that-was-caught) if an ERROR was handled."
535 `(handler-case (progn ,@forms
)
536 (error (condition) (values nil condition
))))
538 ;; A macroexpander helper. Not sure where else to put this.
539 (defun funarg-bind/call-forms
(funarg arg-forms
)
541 '(or (cons (eql function
) (cons (satisfies legal-fun-name-p
) null
))
542 (cons (eql quote
) (cons symbol null
))))
543 (values nil
`(funcall ,funarg .
,arg-forms
))
544 (let ((fn-sym (sb!xc
:gensym
))) ; for ONCE-ONLY-ish purposes
545 (values `((,fn-sym
(%coerce-callable-to-fun
,funarg
)))
546 `(sb!c
::%funcall
,fn-sym .
,arg-forms
)))))