Eliminate style-warning about undefined type GLOBAL-VAR
[sbcl.git] / src / code / macros.lisp
blobef7b7a8b3409b09b6311ce701717b17647b15274
1 ;;;; lots of basic macros for the target SBCL
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.
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
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 &environment env)
29 #!+sb-doc
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
34 ARGUMENTS).
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
42 (FUNCTION ARG*)
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 ((new-test
49 (flet ((process-place (place)
50 (if (sb!xc:constantp place env)
51 place
52 (with-unique-names (temp)
53 (bindings `(,temp ,place))
54 (infos `(list ',place ,temp))
55 temp))))
56 (cond
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
60 ;; order issues.
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)
65 (sb!c::functional-p
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.
71 test-form)))))
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.
75 `(tagbody
76 :try
77 (let ,(bindings)
78 (when ,new-test
79 (go :done))
80 (assert-error ',test-form (list ,@(infos))
81 ',places ,datum ,@arguments))
82 ,@(mapcar (lambda (place)
83 `(setf ,place (assert-prompt ',place ,place)))
84 places)
85 (go :try)
86 :done))))
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? "
91 name 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))
96 (read-it))))
97 (t value)))
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
110 &environment env)
111 #!+sb-doc
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)
128 `(do ()
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))
134 (setf ,place
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)))
151 (case kind
152 ((:macro :unknown)
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
161 (case kind
162 (:alien "an alien variable")
163 (:constant "a constant")
164 (:special "a special variable")
165 (:global "a global variable")
166 (t kind)))))))
167 name)
169 ;;;; DEFINE-COMPILER-MACRO
171 (defmacro-mundanely define-compiler-macro (name lambda-list &body body)
172 #!+sb-doc
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 ;; DEBUG-NAME is called primarily for its side-effect of asserting
180 ;; that (COMPILER-MACRO-FUNCTION x) is not a legal function name.
181 (let ((def (make-macro-lambda (sb!c::debug-name 'compiler-macro name)
182 lambda-list body 'define-compiler-macro name
183 :accessor 'sb!c::compiler-macro-args)))
184 `(progn
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)))))
190 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
191 (defun sb!c::%define-compiler-macro (name definition)
192 (sb!c::warn-if-compiler-macro-dependency-problem name)
193 ;; FIXME: warn about incompatible lambda list with
194 ;; respect to parent function?
195 (setf (sb!xc:compiler-macro-function name) definition)
196 name))
198 ;;;; CASE, TYPECASE, and friends
200 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
202 ;;; Make this a full warning during SBCL build.
203 (define-condition duplicate-case-key-warning (#-sb-xc-host style-warning #+sb-xc-host warning)
204 ((key :initarg :key
205 :reader case-warning-key)
206 (case-kind :initarg :case-kind
207 :reader case-warning-case-kind)
208 (occurrences :initarg :occurrences
209 :type list
210 :reader duplicate-case-key-warning-occurrences))
211 (:report
212 (lambda (condition stream)
213 (format stream
214 "Duplicate key ~S in ~S form, ~
215 occurring in~{~#[~; and~]~{ the ~:R clause:~%~< ~S~:>~}~^,~}."
216 (case-warning-key condition)
217 (case-warning-case-kind condition)
218 (duplicate-case-key-warning-occurrences condition)))))
220 ;;; CASE-BODY returns code for all the standard "case" macros. NAME is
221 ;;; the macro name, and KEYFORM is the thing to case on. MULTI-P
222 ;;; indicates whether a branch may fire off a list of keys; otherwise,
223 ;;; a key that is a list is interpreted in some way as a single key.
224 ;;; When MULTI-P, TEST is applied to the value of KEYFORM and each key
225 ;;; for a given branch; otherwise, TEST is applied to the value of
226 ;;; KEYFORM and the entire first element, instead of each part, of the
227 ;;; case branch. When ERRORP, no OTHERWISE-CLAUSEs are recognized,
228 ;;; and an ERROR form is generated where control falls off the end
229 ;;; of the ordinary clauses. When PROCEEDP, it is an error to
230 ;;; omit ERRORP, and the ERROR form generated is executed within a
231 ;;; RESTART-CASE allowing KEYFORM to be set and retested.
232 (defun case-body (name keyform cases multi-p test errorp proceedp needcasesp)
233 (unless (or cases (not needcasesp))
234 (warn "no clauses in ~S" name))
235 (let ((keyform-value (gensym))
236 (clauses ())
237 (keys ())
238 (keys-seen (make-hash-table :test #'eql)))
239 (do* ((cases cases (cdr cases))
240 (case (car cases) (car cases))
241 (case-position 1 (1+ case-position)))
242 ((null cases) nil)
243 (flet ((check-clause (case-keys)
244 (loop for k in case-keys
245 for existing = (gethash k keys-seen)
246 do (when existing
247 (let ((sb!c::*current-path*
248 (when (boundp 'sb!c::*source-paths*)
249 (or (sb!c::get-source-path case)
250 (and (boundp 'sb!c::*current-path*)
251 sb!c::*current-path*)))))
252 (warn 'duplicate-case-key-warning
253 :key k
254 :case-kind name
255 :occurrences `(,existing (,case-position (,case)))))))
256 (let ((record (list case-position (list case))))
257 (dolist (k case-keys)
258 (setf (gethash k keys-seen) record)))))
259 (unless (list-of-length-at-least-p case 1)
260 (error "~S -- bad clause in ~S" case name))
261 (destructuring-bind (keyoid &rest forms) case
262 (cond (;; an OTHERWISE-CLAUSE
264 ;; By the way... The old code here tried gave
265 ;; STYLE-WARNINGs for normal-clauses which looked as
266 ;; though they might've been intended to be
267 ;; otherwise-clauses. As Tony Martinez reported on
268 ;; sbcl-devel 2004-11-09 there are sometimes good
269 ;; reasons to write clauses like that; and as I noticed
270 ;; when trying to understand the old code so I could
271 ;; understand his patch, trying to guess which clauses
272 ;; don't have good reasons is fundamentally kind of a
273 ;; mess. SBCL does issue style warnings rather
274 ;; enthusiastically, and I have often justified that by
275 ;; arguing that we're doing that to detect issues which
276 ;; are tedious for programmers to detect for by
277 ;; proofreading (like small typoes in long symbol
278 ;; names, or duplicate function definitions in large
279 ;; files). This doesn't seem to be an issue like that,
280 ;; and I can't think of a comparably good justification
281 ;; for giving STYLE-WARNINGs for legal code here, so
282 ;; now we just hope the programmer knows what he's
283 ;; doing. -- WHN 2004-11-20
284 (and (not errorp) ; possible only in CASE or TYPECASE,
285 ; not in [EC]CASE or [EC]TYPECASE
286 (memq keyoid '(t otherwise))
287 (null (cdr cases)))
288 (push `(t nil ,@forms) clauses))
289 ((and multi-p (listp keyoid))
290 (setf keys (nconc (reverse keyoid) keys))
291 (check-clause keyoid)
292 (push `((or ,@(mapcar (lambda (key)
293 `(,test ,keyform-value ',key))
294 keyoid))
296 ,@forms)
297 clauses))
299 (when (and (eq name 'case)
300 (cdr cases)
301 (memq keyoid '(t otherwise)))
302 (error 'simple-reference-error
303 :format-control
304 "~@<~IBad ~S clause:~:@_ ~S~:@_~S allowed as the key ~
305 designator only in the final otherwise-clause, not in a ~
306 normal-clause. Use (~S) instead, or move the clause the ~
307 correct position.~:@>"
308 :format-arguments (list 'case case keyoid keyoid)
309 :references `((:ansi-cl :macro case))))
310 (push keyoid keys)
311 (check-clause (list keyoid))
312 (push `((,test ,keyform-value ',keyoid)
314 ,@forms)
315 clauses))))))
316 (setq keys
317 (nreverse (mapcon (lambda (tail)
318 (unless (member (car tail) (cdr tail))
319 (list (car tail))))
320 keys)))
321 (case-body-aux name keyform keyform-value clauses keys errorp proceedp
322 `(,(if multi-p 'member 'or) ,@keys))))
324 ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled
325 ;;; all the cases. Note: it is not necessary that the resulting code
326 ;;; signal case-failure conditions, but that's what KMP's prototype
327 ;;; code did. We call CASE-BODY-ERROR, because of how closures are
328 ;;; compiled. RESTART-CASE has forms with closures that the compiler
329 ;;; causes to be generated at the top of any function using the case
330 ;;; macros, regardless of whether they are needed.
332 ;;; The CASE-BODY-ERROR function is defined later, when the
333 ;;; RESTART-CASE macro has been defined.
334 (defun case-body-aux (name keyform keyform-value clauses keys
335 errorp proceedp expected-type)
336 (if proceedp
337 (let ((block (gensym))
338 (again (gensym)))
339 `(let ((,keyform-value ,keyform))
340 (block ,block
341 (tagbody
342 ,again
343 (return-from
344 ,block
345 (cond ,@(nreverse clauses)
347 (setf ,keyform-value
348 (setf ,keyform
349 (case-body-error
350 ',name ',keyform ,keyform-value
351 ',expected-type ',keys)))
352 (go ,again))))))))
353 `(let ((,keyform-value ,keyform))
354 (declare (ignorable ,keyform-value)) ; e.g. (CASE KEY (T))
355 (cond
356 ,@(nreverse clauses)
357 ,@(if errorp
358 `((t (case-failure ',name ,keyform-value ',keys))))))))
359 ) ; EVAL-WHEN
361 (defmacro-mundanely case (keyform &body cases)
362 #!+sb-doc
363 "CASE Keyform {({(Key*) | Key} Form*)}*
364 Evaluates the Forms in the first clause with a Key EQL to the value of
365 Keyform. If a singleton key is T then the clause is a default clause."
366 (case-body 'case keyform cases t 'eql nil nil nil))
368 (defmacro-mundanely ccase (keyform &body cases)
369 #!+sb-doc
370 "CCASE Keyform {({(Key*) | Key} Form*)}*
371 Evaluates the Forms in the first clause with a Key EQL to the value of
372 Keyform. If none of the keys matches then a correctable error is
373 signalled."
374 (case-body 'ccase keyform cases t 'eql t t t))
376 (defmacro-mundanely ecase (keyform &body cases)
377 #!+sb-doc
378 "ECASE 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 an error is signalled."
381 (case-body 'ecase keyform cases t 'eql t nil t))
383 (defmacro-mundanely typecase (keyform &body cases)
384 #!+sb-doc
385 "TYPECASE Keyform {(Type Form*)}*
386 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
387 is true."
388 (case-body 'typecase keyform cases nil 'typep nil nil nil))
390 (defmacro-mundanely ctypecase (keyform &body cases)
391 #!+sb-doc
392 "CTYPECASE Keyform {(Type Form*)}*
393 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
394 is true. If no form is satisfied then a correctable error is signalled."
395 (case-body 'ctypecase keyform cases nil 'typep t t t))
397 (defmacro-mundanely etypecase (keyform &body cases)
398 #!+sb-doc
399 "ETYPECASE Keyform {(Type Form*)}*
400 Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
401 is true. If no form is satisfied then an error is signalled."
402 (case-body 'etypecase keyform cases nil 'typep t nil t))
404 ;;;; WITH-FOO i/o-related macros
406 (defmacro-mundanely with-open-stream ((var stream) &body forms-decls)
407 (multiple-value-bind (forms decls)
408 (parse-body forms-decls :doc-string-allowed nil)
409 (let ((abortp (gensym)))
410 `(let ((,var ,stream)
411 (,abortp t))
412 ,@decls
413 (unwind-protect
414 (multiple-value-prog1
415 (progn ,@forms)
416 (setq ,abortp nil))
417 (when ,var
418 (close ,var :abort ,abortp)))))))
420 (defmacro-mundanely with-open-file ((stream filespec &rest options)
421 &body body)
422 `(with-open-stream (,stream (open ,filespec ,@options))
423 ,@body))
425 (defmacro-mundanely with-input-from-string ((var string &key index start end)
426 &body forms-decls)
427 (multiple-value-bind (forms decls)
428 (parse-body forms-decls :doc-string-allowed nil)
429 `(let ((,var
430 ;; Should (WITH-INPUT-FROM-STRING (stream str :start nil :end 5))
431 ;; pass the explicit NIL, and thus get an error? It's logical
432 ;; because an explicit NIL does not mean "default" in any other
433 ;; string operation. So why does it here?
434 ,(if (null end)
435 `(make-string-input-stream ,string ,@(if start (list start)))
436 `(make-string-input-stream ,string ,(or start 0) ,end))))
437 ,@decls
438 (multiple-value-prog1
439 (unwind-protect
440 (progn ,@forms)
441 (close ,var))
442 ,@(when index
443 `((setf ,index (string-input-stream-current ,var))))))))
445 (defmacro-mundanely with-output-to-string
446 ((var &optional string &key (element-type ''character))
447 &body forms-decls)
448 (multiple-value-bind (forms decls)
449 (parse-body forms-decls :doc-string-allowed nil)
450 (if string
451 (let ((element-type-var (gensym)))
452 `(let ((,var (make-fill-pointer-output-stream ,string))
453 ;; ELEMENT-TYPE isn't currently used for anything
454 ;; (see FILL-POINTER-OUTPUT-STREAM FIXME in stream.lisp),
455 ;; but it still has to be evaluated for side-effects.
456 (,element-type-var ,element-type))
457 (declare (ignore ,element-type-var))
458 ,@decls
459 (unwind-protect
460 (progn ,@forms)
461 (close ,var))))
462 `(let ((,var (make-string-output-stream
463 ;; CHARACTER is the default element-type of
464 ;; string-ouput-stream, save a few bytes when passing it
465 ,@(and (not (equal element-type ''character))
466 `(:element-type ,element-type)))))
467 ,@decls
468 (unwind-protect
469 (progn ,@forms)
470 (close ,var))
471 (get-output-stream-string ,var)))))
473 ;;;; miscellaneous macros
475 (defmacro-mundanely nth-value (n form)
476 #!+sb-doc
477 "Evaluate FORM and return the Nth value (zero based)
478 without consing a temporary list of values."
479 ;; FIXME: The above is true, if slightly misleading. The
480 ;; MULTIPLE-VALUE-BIND idiom [ as opposed to MULTIPLE-VALUE-CALL
481 ;; (LAMBDA (&REST VALUES) (NTH N VALUES)) ] does indeed not cons at
482 ;; runtime. However, for large N (say N = 200), COMPILE on such a
483 ;; form will take longer than can be described as adequate, as the
484 ;; optional dispatch mechanism for the M-V-B gets increasingly
485 ;; hairy.
486 (if (integerp n)
487 (let ((dummy-list (make-gensym-list n))
488 (keeper (sb!xc:gensym "KEEPER")))
489 `(multiple-value-bind (,@dummy-list ,keeper) ,form
490 (declare (ignore ,@dummy-list))
491 ,keeper))
492 ;; &MORE conversion handily deals with non-constant N,
493 ;; avoiding the unstylish practice of inserting FORM into the
494 ;; expansion more than once to pick off a few small values.
495 `(multiple-value-call
496 (lambda (n &rest list) (nth (truly-the index n) list))
497 (the index ,n) ,form)))
499 (defmacro-mundanely declaim (&rest specs)
500 #!+sb-doc
501 "DECLAIM Declaration*
502 Do a declaration or declarations for the global environment."
503 `(eval-when (:compile-toplevel :load-toplevel :execute)
504 ,@(mapcar (lambda (spec)
505 `(sb!c::%proclaim ',spec (sb!c:source-location)))
506 specs)))
508 ;; Avoid unknown return values in emitted code for PRINT-UNREADABLE-OBJECT
509 (declaim (ftype (sfunction (t t t t &optional t) null)
510 %print-unreadable-object))
511 (defmacro-mundanely print-unreadable-object ((object stream &key type identity)
512 &body body)
513 #!+sb-doc
514 "Output OBJECT to STREAM with \"#<\" prefix, \">\" suffix, optionally
515 with object-type prefix and object-identity suffix, and executing the
516 code in BODY to provide possible further output."
517 ;; Note: possibly out-of-order keyword argument evaluation.
518 (if body
519 (let ((fun (make-symbol "THUNK")))
520 `(dx-flet ((,fun () ,@body))
521 (%print-unreadable-object ,object ,stream ,type ,identity #',fun)))
522 `(%print-unreadable-object ,object ,stream ,type ,identity)))
524 (defmacro-mundanely ignore-errors (&rest forms)
525 #!+sb-doc
526 "Execute FORMS handling ERROR conditions, returning the result of the last
527 form, or (VALUES NIL the-ERROR-that-was-caught) if an ERROR was handled."
528 `(handler-case (progn ,@forms)
529 (error (condition) (values nil condition))))
531 ;; A macroexpander helper. Not sure where else to put this.
532 (defun funarg-bind/call-forms (funarg arg-forms)
533 (if (typep funarg
534 '(or (cons (eql function) (cons (satisfies legal-fun-name-p) null))
535 (cons (eql quote) (cons symbol null))))
536 (values nil `(funcall ,funarg . ,arg-forms))
537 (let ((fn-sym (sb!xc:gensym))) ; for ONCE-ONLY-ish purposes
538 (values `((,fn-sym (%coerce-callable-to-fun ,funarg)))
539 `(sb!c::%funcall ,fn-sym . ,arg-forms)))))