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
)))
63 (when (or (eq (info :function
:kind name
) :function
)
64 (and (typep env
'sb
!kernel
:lexenv
)
66 (cdr (assoc name
(sb!c
::lexenv-funs env
))))))
67 `(,name
,@(mapcar #'process-place
(rest test-form
)))))))
68 ;; For all other cases, just evaluate TEST-FORM and do
69 ;; not report any details if the assertion fails.
72 ;; If TEST-FORM, potentially using values from BINDINGS, does not
73 ;; hold, enter a loop which reports the assertion error,
74 ;; potentially changes PLACES, and retries TEST-FORM.
80 (assert-error ',test-form
(list ,@(infos))
81 ',places
,datum
,@arguments
))
82 ,@(mapcar (lambda (place)
83 `(setf ,place
(assert-prompt ',place
,place
)))
88 (defun assert-prompt (name value
)
89 (cond ((y-or-n-p "The old value of ~S is ~S.~
90 ~%Do you want to supply a new value? "
92 (format *query-io
* "~&Type a form to be evaluated:~%")
93 (flet ((read-it () (eval (read *query-io
*))))
94 (if (symbolp name
) ;help user debug lexical variables
95 (progv (list name
) (list value
) (read-it))
99 ;;; CHECK-TYPE is written this way, to call CHECK-TYPE-ERROR, because
100 ;;; of how closures are compiled. RESTART-CASE has forms with closures
101 ;;; that the compiler causes to be generated at the top of any
102 ;;; function using RESTART-CASE, regardless of whether they are
103 ;;; needed. Because it would be nice if CHECK-TYPE were cheap to use,
104 ;;; and some things (e.g., READ-CHAR) can't afford this excessive
105 ;;; consing, we bend backwards a little.
107 ;;; CHECK-TYPE-ERROR isn't defined until a later file because it uses
108 ;;; the macro RESTART-CASE, which isn't defined until a later file.
109 (defmacro-mundanely check-type
(place type
&optional type-string
112 "Signal a restartable error of type TYPE-ERROR if the value of PLACE
113 is not of the specified type. If an error is signalled and the restart
114 is used to return, this can only return if the STORE-VALUE restart is
115 invoked. In that case it will store into PLACE and start over."
116 ;; Detect a common user-error.
117 (when (and (consp type
) (eq 'quote
(car type
)))
118 (error 'simple-reference-error
119 :format-control
"Quoted type specifier in ~S: ~S"
120 :format-arguments
(list 'check-type type
)
121 :references
(list '(:ansi-cl
:macro check-type
))))
122 ;; KLUDGE: We use a simpler form of expansion if PLACE is just a
123 ;; variable to work around Python's blind spot in type derivation.
124 ;; For more complex places getting the type derived should not
125 ;; matter so much anyhow.
126 (let ((expanded (%macroexpand place env
)))
127 (if (symbolp expanded
)
129 ((typep ,place
',type
))
130 (setf ,place
(check-type-error ',place
,place
',type
,type-string
)))
131 (let ((value (gensym)))
132 `(do ((,value
,place
,place
))
133 ((typep ,value
',type
))
135 (check-type-error ',place
,value
',type
,type-string
)))))))
137 ;;;; DEFINE-SYMBOL-MACRO
139 (defmacro-mundanely define-symbol-macro
(name expansion
)
140 `(eval-when (:compile-toplevel
:load-toplevel
:execute
)
141 (sb!c
::%define-symbol-macro
',name
',expansion
(sb!c
:source-location
))))
143 (defun sb!c
::%define-symbol-macro
(name expansion source-location
)
144 (unless (symbolp name
)
145 (error 'simple-type-error
:datum name
:expected-type
'symbol
146 :format-control
"Symbol macro name is not a symbol: ~S."
147 :format-arguments
(list name
)))
148 (with-single-package-locked-error
149 (:symbol name
"defining ~A as a symbol-macro"))
150 (let ((kind (info :variable
:kind name
)))
153 (sb!c
:with-source-location
(source-location)
154 (setf (info :source-location
:symbol-macro name
) source-location
))
155 (setf (info :variable
:kind name
) :macro
)
156 (setf (info :variable
:macro-expansion name
) expansion
))
158 (error 'simple-program-error
159 :format-control
"Symbol ~S is already defined as ~A."
160 :format-arguments
(list name
162 (:alien
"an alien variable")
163 (:constant
"a constant")
164 (:special
"a special variable")
165 (:global
"a global variable")
169 ;;;; DEFINE-COMPILER-MACRO
171 (defmacro-mundanely define-compiler-macro
(name lambda-list
&body body
)
173 "Define a compiler-macro for NAME."
174 (legal-fun-name-or-type-error name
)
175 (when (and (symbolp name
) (special-operator-p name
))
176 (error 'simple-program-error
177 :format-control
"cannot define a compiler-macro for a special operator: ~S"
178 :format-arguments
(list name
)))
179 (multiple-value-bind (def lambda-list
)
180 ;; DEBUG-NAME is called primarily for its side-effect of asserting
181 ;; that (COMPILER-MACRO-FUNCTION x) is not a legal function name.
182 (make-macro-lambda (sb!c
::debug-name
'compiler-macro name
)
183 lambda-list body
'define-compiler-macro name
)
185 (eval-when (:compile-toplevel
)
186 (sb!c
::%compiler-defmacro
:compiler-macro-function
',name t
))
187 (eval-when (:compile-toplevel
:load-toplevel
:execute
)
188 (sb!c
::%define-compiler-macro
',name
,def
',lambda-list
)))))
190 ;;; FIXME: This will look remarkably similar to those who have already
191 ;;; seen the code for %DEFMACRO in src/code/defmacro.lisp. Various
192 ;;; bits of logic should be shared (notably arglist setting).
195 `(eval-when (,@times
)
196 (defun sb!c
::%define-compiler-macro
(name definition lambda-list
)
198 '((declare (ignore lambda-list
))))
199 (sb!c
::warn-if-compiler-macro-dependency-problem name
)
200 ;; FIXME: warn about incompatible lambda list with
201 ;; respect to parent function?
202 (setf (sb!xc
:compiler-macro-function name
) definition
)
204 `(setf (%fun-lambda-list definition
) lambda-list
))
207 (def (:load-toplevel
:execute
) #-sb-xc-host t
#+sb-xc-host nil
)
208 #-sb-xc
(def (:compile-toplevel
) nil
)))
210 ;;;; CASE, TYPECASE, and friends
212 (eval-when (#-sb-xc
:compile-toplevel
:load-toplevel
:execute
)
214 ;;; Make this a full warning during SBCL build.
215 (define-condition duplicate-case-key-warning
(#-sb-xc-host style-warning
#+sb-xc-host warning
)
217 :reader case-warning-key
)
218 (case-kind :initarg
:case-kind
219 :reader case-warning-case-kind
)
220 (occurrences :initarg
:occurrences
222 :reader duplicate-case-key-warning-occurrences
))
224 (lambda (condition stream
)
226 "Duplicate key ~S in ~S form, ~
227 occurring in~{~#[~; and~]~{ the ~:R clause:~%~< ~S~:>~}~^,~}."
228 (case-warning-key condition
)
229 (case-warning-case-kind condition
)
230 (duplicate-case-key-warning-occurrences condition
)))))
232 ;;; CASE-BODY returns code for all the standard "case" macros. NAME is
233 ;;; the macro name, and KEYFORM is the thing to case on. MULTI-P
234 ;;; indicates whether a branch may fire off a list of keys; otherwise,
235 ;;; a key that is a list is interpreted in some way as a single key.
236 ;;; When MULTI-P, TEST is applied to the value of KEYFORM and each key
237 ;;; for a given branch; otherwise, TEST is applied to the value of
238 ;;; KEYFORM and the entire first element, instead of each part, of the
239 ;;; case branch. When ERRORP, no OTHERWISE-CLAUSEs are recognized,
240 ;;; and an ERROR form is generated where control falls off the end
241 ;;; of the ordinary clauses. When PROCEEDP, it is an error to
242 ;;; omit ERRORP, and the ERROR form generated is executed within a
243 ;;; RESTART-CASE allowing KEYFORM to be set and retested.
244 (defun case-body (name keyform cases multi-p test errorp proceedp needcasesp
)
245 (unless (or cases
(not needcasesp
))
246 (warn "no clauses in ~S" name
))
247 (let ((keyform-value (gensym))
250 (keys-seen (make-hash-table :test
#'eql
)))
251 (do* ((cases cases
(cdr cases
))
252 (case (car cases
) (car cases
))
253 (case-position 1 (1+ case-position
)))
255 (flet ((check-clause (case-keys)
256 (loop for k in case-keys
257 for existing
= (gethash k keys-seen
)
259 (let ((sb!c
::*current-path
*
260 (when (boundp 'sb
!c
::*source-paths
*)
261 (or (sb!c
::get-source-path case
)
262 sb
!c
::*current-path
*))))
263 (warn 'duplicate-case-key-warning
266 :occurrences
`(,existing
(,case-position
(,case
)))))))
267 (let ((record (list case-position
(list case
))))
268 (dolist (k case-keys
)
269 (setf (gethash k keys-seen
) record
)))))
270 (unless (list-of-length-at-least-p case
1)
271 (error "~S -- bad clause in ~S" case name
))
272 (destructuring-bind (keyoid &rest forms
) case
273 (cond (;; an OTHERWISE-CLAUSE
275 ;; By the way... The old code here tried gave
276 ;; STYLE-WARNINGs for normal-clauses which looked as
277 ;; though they might've been intended to be
278 ;; otherwise-clauses. As Tony Martinez reported on
279 ;; sbcl-devel 2004-11-09 there are sometimes good
280 ;; reasons to write clauses like that; and as I noticed
281 ;; when trying to understand the old code so I could
282 ;; understand his patch, trying to guess which clauses
283 ;; don't have good reasons is fundamentally kind of a
284 ;; mess. SBCL does issue style warnings rather
285 ;; enthusiastically, and I have often justified that by
286 ;; arguing that we're doing that to detect issues which
287 ;; are tedious for programmers to detect for by
288 ;; proofreading (like small typoes in long symbol
289 ;; names, or duplicate function definitions in large
290 ;; files). This doesn't seem to be an issue like that,
291 ;; and I can't think of a comparably good justification
292 ;; for giving STYLE-WARNINGs for legal code here, so
293 ;; now we just hope the programmer knows what he's
294 ;; doing. -- WHN 2004-11-20
295 (and (not errorp
) ; possible only in CASE or TYPECASE,
296 ; not in [EC]CASE or [EC]TYPECASE
297 (memq keyoid
'(t otherwise
))
299 (push `(t nil
,@forms
) clauses
))
300 ((and multi-p
(listp keyoid
))
301 (setf keys
(nconc (reverse keyoid
) keys
))
302 (check-clause keyoid
)
303 (push `((or ,@(mapcar (lambda (key)
304 `(,test
,keyform-value
',key
))
310 (when (and (eq name
'case
)
312 (memq keyoid
'(t otherwise
)))
313 (error 'simple-reference-error
315 "~@<~IBad ~S clause:~:@_ ~S~:@_~S allowed as the key ~
316 designator only in the final otherwise-clause, not in a ~
317 normal-clause. Use (~S) instead, or move the clause the ~
318 correct position.~:@>"
319 :format-arguments
(list 'case case keyoid keyoid
)
320 :references
`((:ansi-cl
:macro case
))))
322 (check-clause (list keyoid
))
323 (push `((,test
,keyform-value
',keyoid
)
328 (nreverse (mapcon (lambda (tail)
329 (unless (member (car tail
) (cdr tail
))
332 (case-body-aux name keyform keyform-value clauses keys errorp proceedp
333 `(,(if multi-p
'member
'or
) ,@keys
))))
335 ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled
336 ;;; all the cases. Note: it is not necessary that the resulting code
337 ;;; signal case-failure conditions, but that's what KMP's prototype
338 ;;; code did. We call CASE-BODY-ERROR, because of how closures are
339 ;;; compiled. RESTART-CASE has forms with closures that the compiler
340 ;;; causes to be generated at the top of any function using the case
341 ;;; macros, regardless of whether they are needed.
343 ;;; The CASE-BODY-ERROR function is defined later, when the
344 ;;; RESTART-CASE macro has been defined.
345 (defun case-body-aux (name keyform keyform-value clauses keys
346 errorp proceedp expected-type
)
348 (let ((block (gensym))
350 `(let ((,keyform-value
,keyform
))
356 (cond ,@(nreverse clauses
)
361 ',name
',keyform
,keyform-value
362 ',expected-type
',keys
)))
364 `(let ((,keyform-value
,keyform
))
365 (declare (ignorable ,keyform-value
)) ; e.g. (CASE KEY (T))
369 `((t (case-failure ',name
,keyform-value
',keys
))))))))
372 (defmacro-mundanely case
(keyform &body cases
)
374 "CASE Keyform {({(Key*) | Key} Form*)}*
375 Evaluates the Forms in the first clause with a Key EQL to the value of
376 Keyform. If a singleton key is T then the clause is a default clause."
377 (case-body 'case keyform cases t
'eql nil nil nil
))
379 (defmacro-mundanely ccase
(keyform &body cases
)
381 "CCASE Keyform {({(Key*) | Key} Form*)}*
382 Evaluates the Forms in the first clause with a Key EQL to the value of
383 Keyform. If none of the keys matches then a correctable error is
385 (case-body 'ccase keyform cases t
'eql t t t
))
387 (defmacro-mundanely ecase
(keyform &body cases
)
389 "ECASE Keyform {({(Key*) | Key} Form*)}*
390 Evaluates the Forms in the first clause with a Key EQL to the value of
391 Keyform. If none of the keys matches then an error is signalled."
392 (case-body 'ecase keyform cases t
'eql t nil t
))
394 (defmacro-mundanely typecase
(keyform &body cases
)
396 "TYPECASE Keyform {(Type Form*)}*
397 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
399 (case-body 'typecase keyform cases nil
'typep nil nil nil
))
401 (defmacro-mundanely ctypecase
(keyform &body cases
)
403 "CTYPECASE Keyform {(Type Form*)}*
404 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
405 is true. If no form is satisfied then a correctable error is signalled."
406 (case-body 'ctypecase keyform cases nil
'typep t t t
))
408 (defmacro-mundanely etypecase
(keyform &body cases
)
410 "ETYPECASE Keyform {(Type Form*)}*
411 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
412 is true. If no form is satisfied then an error is signalled."
413 (case-body 'etypecase keyform cases nil
'typep t nil t
))
415 ;;;; WITH-FOO i/o-related macros
417 (defmacro-mundanely with-open-stream
((var stream
) &body forms-decls
)
418 (multiple-value-bind (forms decls
)
419 (parse-body forms-decls
:doc-string-allowed nil
)
420 (let ((abortp (gensym)))
421 `(let ((,var
,stream
)
425 (multiple-value-prog1
429 (close ,var
:abort
,abortp
)))))))
431 (defmacro-mundanely with-open-file
((stream filespec
&rest options
)
433 `(with-open-stream (,stream
(open ,filespec
,@options
))
436 (defmacro-mundanely with-input-from-string
((var string
&key index start end
)
438 (multiple-value-bind (forms decls
)
439 (parse-body forms-decls
:doc-string-allowed 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 (defmacro-mundanely with-output-to-string
457 ((var &optional string
&key
(element-type ''character
))
459 (multiple-value-bind (forms decls
)
460 (parse-body forms-decls
:doc-string-allowed nil
)
462 (let ((element-type-var (gensym)))
463 `(let ((,var
(make-fill-pointer-output-stream ,string
))
464 ;; ELEMENT-TYPE isn't currently used for anything
465 ;; (see FILL-POINTER-OUTPUT-STREAM FIXME in stream.lisp),
466 ;; but it still has to be evaluated for side-effects.
467 (,element-type-var
,element-type
))
468 (declare (ignore ,element-type-var
))
473 `(let ((,var
(make-string-output-stream
474 ;; CHARACTER is the default element-type of
475 ;; string-ouput-stream, save a few bytes when passing it
476 ,@(and (not (equal element-type
''character
))
477 `(:element-type
,element-type
)))))
482 (get-output-stream-string ,var
)))))
484 ;;;; miscellaneous macros
486 (defmacro-mundanely nth-value
(n form
)
488 "Evaluate FORM and return the Nth value (zero based)
489 without consing a temporary list of values."
490 ;; FIXME: The above is true, if slightly misleading. The
491 ;; MULTIPLE-VALUE-BIND idiom [ as opposed to MULTIPLE-VALUE-CALL
492 ;; (LAMBDA (&REST VALUES) (NTH N VALUES)) ] does indeed not cons at
493 ;; runtime. However, for large N (say N = 200), COMPILE on such a
494 ;; form will take longer than can be described as adequate, as the
495 ;; optional dispatch mechanism for the M-V-B gets increasingly
498 (let ((dummy-list (make-gensym-list n
))
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 `(multiple-value-call
507 (lambda (n &rest list
) (nth (truly-the index n
) list
))
508 (the index
,n
) ,form
)))
510 (defmacro-mundanely declaim
(&rest specs
)
512 "DECLAIM Declaration*
513 Do a declaration or declarations for the global environment."
514 `(eval-when (:compile-toplevel
:load-toplevel
:execute
)
515 ,@(mapcar (lambda (spec)
516 `(sb!c
::%proclaim
',spec
(sb!c
:source-location
)))
519 ;; Avoid unknown return values in emitted code for PRINT-UNREADABLE-OBJECT
520 (declaim (ftype (sfunction (t t t t
&optional t
) null
)
521 %print-unreadable-object
))
522 (defmacro-mundanely print-unreadable-object
((object stream
&key type identity
)
525 "Output OBJECT to STREAM with \"#<\" prefix, \">\" suffix, optionally
526 with object-type prefix and object-identity suffix, and executing the
527 code in BODY to provide possible further output."
528 ;; Note: possibly out-of-order keyword argument evaluation.
530 (let ((fun (make-symbol "THUNK")))
531 `(dx-flet ((,fun
() ,@body
))
532 (%print-unreadable-object
,object
,stream
,type
,identity
#',fun
)))
533 `(%print-unreadable-object
,object
,stream
,type
,identity
)))
535 (defmacro-mundanely ignore-errors
(&rest forms
)
537 "Execute FORMS handling ERROR conditions, returning the result of the last
538 form, or (VALUES NIL the-ERROR-that-was-caught) if an ERROR was handled."
539 `(handler-case (progn ,@forms
)
540 (error (condition) (values nil condition
))))
542 ;; A macroexpander helper. Not sure where else to put this.
543 (defun funarg-bind/call-forms
(funarg arg-forms
)
545 '(or (cons (eql function
) (cons (satisfies legal-fun-name-p
) null
))
546 (cons (eql quote
) (cons symbol null
))))
547 (values nil
`(funcall ,funarg .
,arg-forms
))
548 (let ((fn-sym (sb!xc
:gensym
))) ; for ONCE-ONLY-ish purposes
549 (values `((,fn-sym
(%coerce-callable-to-fun
,funarg
)))
550 `(sb!c
::%funcall
,fn-sym .
,arg-forms
)))))