1 ;;;; various extensions (including SB-INT "internal extensions")
2 ;;;; available both in the cross-compilation host Lisp and in the
5 ;;;; This software is part of the SBCL system. See the README file for
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
14 (in-package "SB!IMPL")
16 ;;; something not EQ to anything we might legitimately READ
17 (defparameter *eof-object* (make-symbol "EOF-OBJECT"))
19 ;;; a type used for indexing into arrays, and for related quantities
20 ;;; like lengths of lists
22 ;;; It's intentionally limited to one less than the
23 ;;; ARRAY-DIMENSION-LIMIT for efficiency reasons, because in SBCL
24 ;;; ARRAY-DIMENSION-LIMIT is MOST-POSITIVE-FIXNUM, and staying below
25 ;;; that lets the system know it can increment a value of this type
26 ;;; without having to worry about using a bignum to represent the
29 ;;; (It should be safe to use ARRAY-DIMENSION-LIMIT as an exclusive
30 ;;; bound because ANSI specifies it as an exclusive bound.)
31 (def!type index () `(integer 0 (,sb!xc:array-dimension-limit)))
33 ;;; like INDEX, but augmented with -1 (useful when using the index
34 ;;; to count downwards to 0, e.g. LOOP FOR I FROM N DOWNTO 0, with
35 ;;; an implementation which terminates the loop by testing for the
36 ;;; index leaving the loop range)
37 (def!type index-or-minus-1 () `(integer -1 (,sb!xc:array-dimension-limit)))
39 ;;; A couple of VM-related types that are currently used only on the
40 ;;; alpha platform. -- CSR, 2002-06-24
41 (def!type unsigned-byte-with-a-bite-out (s bite)
42 (cond ((eq s '*) 'integer)
43 ((and (integerp s) (> s 1))
44 (let ((bound (ash 1 s)))
45 `(integer 0 ,(- bound bite 1))))
47 (error "Bad size specified for SIGNED-BYTE type specifier: ~S." s))))
49 (def!type load/store-index (scale lowtag min-offset
50 &optional (max-offset min-offset))
51 `(integer ,(- (truncate (+ (ash 1 16)
52 (* min-offset sb!vm:n-word-bytes)
55 ,(truncate (- (+ (1- (ash 1 16)) lowtag)
56 (* max-offset sb!vm:n-word-bytes))
59 ;;; the default value used for initializing character data. The ANSI
60 ;;; spec says this is arbitrary, so we use the value that falls
61 ;;; through when we just let the low-level consing code initialize
62 ;;; all newly-allocated memory to zero.
64 ;;; KLUDGE: It might be nice to use something which is a
65 ;;; STANDARD-CHAR, both to reduce user surprise a little and, probably
66 ;;; more significantly, to help SBCL's cross-compiler (which knows how
67 ;;; to dump STANDARD-CHARs). Unfortunately, the old CMU CL code is
68 ;;; shot through with implicit assumptions that it's #\NULL, and code
69 ;;; in several places (notably both DEFUN MAKE-ARRAY and DEFTRANSFORM
70 ;;; MAKE-ARRAY) would have to be rewritten. -- WHN 2001-10-04
71 (eval-when (:compile-toplevel :load-toplevel :execute)
72 ;; an expression we can use to construct a DEFAULT-INIT-CHAR value
73 ;; at load time (so that we don't need to teach the cross-compiler
74 ;; how to represent and dump non-STANDARD-CHARs like #\NULL)
75 (defparameter *default-init-char-form* '(code-char 0)))
77 ;;; CHAR-CODE values for ASCII characters which we care about but
78 ;;; which aren't defined in section "2.1.3 Standard Characters" of the
79 ;;; ANSI specification for Lisp
81 ;;; KLUDGE: These are typically used in the idiom (CODE-CHAR
82 ;;; FOO-CHAR-CODE). I suspect that the current implementation is
83 ;;; expanding this idiom into a full call to CODE-CHAR, which is an
84 ;;; annoying overhead. I should check whether this is happening, and
85 ;;; if so, perhaps implement a DEFTRANSFORM or something to stop it.
86 ;;; (or just find a nicer way of expressing characters portably?) --
88 (def!constant bell-char-code 7)
89 (def!constant backspace-char-code 8)
90 (def!constant tab-char-code 9)
91 (def!constant line-feed-char-code 10)
92 (def!constant form-feed-char-code 12)
93 (def!constant return-char-code 13)
94 (def!constant escape-char-code 27)
95 (def!constant rubout-char-code 127)
97 ;;;; type-ish predicates
99 ;;; a helper function for various macros which expect clauses of a
100 ;;; given length, etc.
101 (eval-when (:compile-toplevel :load-toplevel :execute)
102 ;; Return true if X is a proper list whose length is between MIN and
104 (defun proper-list-of-length-p (x min &optional (max min))
105 ;; FIXME: This implementation will hang on circular list
106 ;; structure. Since this is an error-checking utility, i.e. its
107 ;; job is to deal with screwed-up input, it'd be good style to fix
108 ;; it so that it can deal with circular list structure.
115 (proper-list-of-length-p (cdr x)
122 ;;; Is X a list containing a cycle?
123 (defun cyclic-list-p (x)
125 (labels ((safe-cddr (x) (if (listp (cdr x)) (cddr x))))
126 (do ((y x (safe-cddr y))
129 ((not (and (consp z) (consp y))) nil)
130 (when (and started-p (eq y z))
133 ;;; Is X a (possibly-improper) list of at least N elements?
134 (declaim (ftype (function (t index)) list-of-length-at-least-p))
135 (defun list-of-length-at-least-p (x n)
136 (or (zerop n) ; since anything can be considered an improper list of length 0
138 (list-of-length-at-least-p (cdr x) (1- n)))))
140 ;;; Is X is a positive prime integer?
141 (defun positive-primep (x)
142 ;; This happens to be called only from one place in sbcl-0.7.0, and
143 ;; only for fixnums, we can limit it to fixnums for efficiency. (And
144 ;; if we didn't limit it to fixnums, we should use a cleverer
145 ;; algorithm, since this one scales pretty badly for huge X.)
148 (and (>= x 2) (/= x 4))
150 (not (zerop (rem x 3)))
153 (inc 2 (logxor inc 6)) ;; 2,4,2,4...
155 ((or (= r 0) (> d q)) (/= r 0))
156 (declare (fixnum inc))
157 (multiple-value-setq (q r) (truncate x d))))))
159 ;;; Could this object contain other objects? (This is important to
160 ;;; the implementation of things like *PRINT-CIRCLE* and the dumper.)
161 (defun compound-object-p (x)
164 (typep x '(array t *))))
166 ;;;; the COLLECT macro
168 ;;;; comment from CMU CL: "the ultimate collection macro..."
170 ;;; helper functions for COLLECT, which become the expanders of the
171 ;;; MACROLET definitions created by COLLECT
173 ;;; COLLECT-NORMAL-EXPANDER handles normal collection macros.
175 ;;; COLLECT-LIST-EXPANDER handles the list collection case. N-TAIL
176 ;;; is the pointer to the current tail of the list, or NIL if the list
178 (eval-when (:compile-toplevel :load-toplevel :execute)
179 (defun collect-normal-expander (n-value fun forms)
181 ,@(mapcar (lambda (form) `(setq ,n-value (,fun ,form ,n-value))) forms)
183 (defun collect-list-expander (n-value n-tail forms)
184 (let ((n-res (gensym)))
186 ,@(mapcar (lambda (form)
187 `(let ((,n-res (cons ,form nil)))
189 (setf (cdr ,n-tail) ,n-res)
190 (setq ,n-tail ,n-res))
192 (setq ,n-tail ,n-res ,n-value ,n-res)))))
196 ;;; Collect some values somehow. Each of the collections specifies a
197 ;;; bunch of things which collected during the evaluation of the body
198 ;;; of the form. The name of the collection is used to define a local
199 ;;; macro, a la MACROLET. Within the body, this macro will evaluate
200 ;;; each of its arguments and collect the result, returning the
201 ;;; current value after the collection is done. The body is evaluated
202 ;;; as a PROGN; to get the final values when you are done, just call
203 ;;; the collection macro with no arguments.
205 ;;; INITIAL-VALUE is the value that the collection starts out with,
206 ;;; which defaults to NIL. FUNCTION is the function which does the
207 ;;; collection. It is a function which will accept two arguments: the
208 ;;; value to be collected and the current collection. The result of
209 ;;; the function is made the new value for the collection. As a
210 ;;; totally magical special-case, FUNCTION may be COLLECT, which tells
211 ;;; us to build a list in forward order; this is the default. If an
212 ;;; INITIAL-VALUE is supplied for COLLECT, the stuff will be RPLACD'd
213 ;;; onto the end. Note that FUNCTION may be anything that can appear
214 ;;; in the functional position, including macros and lambdas.
215 (defmacro collect (collections &body body)
218 (dolist (spec collections)
219 (unless (proper-list-of-length-p spec 1 3)
220 (error "malformed collection specifier: ~S" spec))
221 (let* ((name (first spec))
222 (default (second spec))
223 (kind (or (third spec) 'collect))
224 (n-value (gensym (concatenate 'string
227 (push `(,n-value ,default) binds)
228 (if (eq kind 'collect)
229 (let ((n-tail (gensym (concatenate 'string
233 (push `(,n-tail (last ,n-value)) binds)
235 (push `(,name (&rest args)
236 (collect-list-expander ',n-value ',n-tail args))
238 (push `(,name (&rest args)
239 (collect-normal-expander ',n-value ',kind args))
241 `(macrolet ,macros (let* ,(nreverse binds) ,@body))))
243 ;;;; some old-fashioned functions. (They're not just for old-fashioned
244 ;;;; code, they're also used as optimized forms of the corresponding
245 ;;;; general functions when the compiler can prove that they're
248 ;;; like (MEMBER ITEM LIST :TEST #'EQ)
249 (defun memq (item list)
251 "Return tail of LIST beginning with first element EQ to ITEM."
252 ;; KLUDGE: These could be and probably should be defined as
253 ;; (MEMBER ITEM LIST :TEST #'EQ)),
254 ;; but when I try to cross-compile that, I get an error from
255 ;; LTN-ANALYZE-KNOWN-CALL, "Recursive known function definition". The
256 ;; comments for that error say it "is probably a botched interpreter stub".
257 ;; Rather than try to figure that out, I just rewrote this function from
258 ;; scratch. -- WHN 19990512
259 (do ((i list (cdr i)))
261 (when (eq (car i) item)
264 ;;; like (ASSOC ITEM ALIST :TEST #'EQ):
265 ;;; Return the first pair of ALIST where ITEM is EQ to the key of
267 (defun assq (item alist)
268 ;; KLUDGE: CMU CL defined this with
269 ;; (DECLARE (INLINE ASSOC))
270 ;; (ASSOC ITEM ALIST :TEST #'EQ))
271 ;; which is pretty, but which would have required adding awkward
272 ;; build order constraints on SBCL (or figuring out some way to make
273 ;; inline definitions installable at build-the-cross-compiler time,
274 ;; which was too ambitious for now). Rather than mess with that, we
275 ;; just define ASSQ explicitly in terms of more primitive
278 (when (eq (car pair) item)
281 ;;; like (DELETE .. :TEST #'EQ):
282 ;;; Delete all LIST entries EQ to ITEM (destructively modifying
283 ;;; LIST), and return the modified LIST.
284 (defun delq (item list)
286 (do ((x list (cdr x))
289 (cond ((eq item (car x))
292 (rplacd splice (cdr x))))
293 (t (setq splice x)))))) ; Move splice along to include element.
296 ;;; like (POSITION .. :TEST #'EQ):
297 ;;; Return the position of the first element EQ to ITEM.
298 (defun posq (item list)
299 (do ((i list (cdr i))
302 (when (eq (car i) item)
305 (declaim (inline neq))
309 ;;; not really an old-fashioned function, but what the calling
310 ;;; convention should've been: like NTH, but with the same argument
311 ;;; order as in all the other dereferencing functions, with the
312 ;;; collection first and the index second
313 (declaim (inline nth-but-with-sane-arg-order))
314 (declaim (ftype (function (list index) t) nth-but-with-sane-arg-order))
315 (defun nth-but-with-sane-arg-order (list index)
318 ;;;; miscellaneous iteration extensions
320 ;;; "the ultimate iteration macro"
322 ;;; note for Schemers: This seems to be identical to Scheme's "named LET".
323 (defmacro named-let (name binds &body body)
326 (unless (proper-list-of-length-p x 2)
327 (error "malformed NAMED-LET variable spec: ~S" x)))
328 `(labels ((,name ,(mapcar #'first binds) ,@body))
329 (,name ,@(mapcar #'second binds))))
331 ;;; just like DOLIST, but with one-dimensional arrays
332 (defmacro dovector ((elt vector &optional result) &rest forms)
333 (let ((index (gensym))
336 `(let ((,vec ,vector))
337 (declare (type vector ,vec))
338 (do ((,index 0 (1+ ,index))
339 (,length (length ,vec)))
340 ((>= ,index ,length) ,result)
341 (let ((,elt (aref ,vec ,index)))
344 ;;; Iterate over the entries in a HASH-TABLE.
345 (defmacro dohash ((key-var value-var table &optional result) &body body)
346 (multiple-value-bind (forms decls) (parse-body body nil)
349 `(with-hash-table-iterator (,gen ,table)
351 (multiple-value-bind (,n-more ,key-var ,value-var) (,gen)
353 (unless ,n-more (return ,result))
356 ;;;; hash cache utility
358 (eval-when (:compile-toplevel :load-toplevel :execute)
359 (defvar *profile-hash-cache* nil))
361 ;;; a flag for whether it's too early in cold init to use caches so
362 ;;; that we have a better chance of recovering so that we have a
363 ;;; better chance of getting the system running so that we have a
364 ;;; better chance of diagnosing the problem which caused us to use the
367 (defvar *hash-caches-initialized-p*)
369 ;;; Define a hash cache that associates some number of argument values
370 ;;; with a result value. The TEST-FUNCTION paired with each ARG-NAME
371 ;;; is used to compare the value for that arg in a cache entry with a
372 ;;; supplied arg. The TEST-FUNCTION must not error when passed NIL as
373 ;;; its first arg, but need not return any particular value.
374 ;;; TEST-FUNCTION may be any thing that can be placed in CAR position.
376 ;;; NAME is used to define these functions:
377 ;;; <name>-CACHE-LOOKUP Arg*
378 ;;; See whether there is an entry for the specified ARGs in the
379 ;;; cache. If not present, the :DEFAULT keyword (default NIL)
380 ;;; determines the result(s).
381 ;;; <name>-CACHE-ENTER Arg* Value*
382 ;;; Encache the association of the specified args with VALUE.
383 ;;; <name>-CACHE-CLEAR
384 ;;; Reinitialize the cache, invalidating all entries and allowing
385 ;;; the arguments and result values to be GC'd.
387 ;;; These other keywords are defined:
389 ;;; The size of the cache as a power of 2.
390 ;;; :HASH-FUNCTION function
391 ;;; Some thing that can be placed in CAR position which will compute
392 ;;; a value between 0 and (1- (expt 2 <hash-bits>)).
394 ;;; the number of return values cached for each function call
395 ;;; :INIT-WRAPPER <name>
396 ;;; The code for initializing the cache is wrapped in a form with
397 ;;; the specified name. (:INIT-WRAPPER is set to COLD-INIT-FORMS
398 ;;; in type system definitions so that caches will be created
399 ;;; before top level forms run.)
400 (defmacro define-hash-cache (name args &key hash-function hash-bits default
401 (init-wrapper 'progn)
403 (let* ((var-name (symbolicate "*" name "-CACHE-VECTOR*"))
404 (nargs (length args))
405 (entry-size (+ nargs values))
406 (size (ash 1 hash-bits))
407 (total-size (* entry-size size))
408 (default-values (if (and (consp default) (eq (car default) 'values))
414 (unless (= (length default-values) values)
415 (error "The number of default values ~S differs from :VALUES ~W."
427 (values-indices `(+ ,n-index ,(+ nargs i)))
428 (values-names (gensym)))
431 (unless (= (length arg) 2)
432 (error "bad argument spec: ~S" arg))
433 (let ((arg-name (first arg))
436 (tests `(,test (svref ,n-cache (+ ,n-index ,n)) ,arg-name))
437 (sets `(setf (svref ,n-cache (+ ,n-index ,n)) ,arg-name)))
440 (when *profile-hash-cache*
441 (let ((n-probe (symbolicate "*" name "-CACHE-PROBES*"))
442 (n-miss (symbolicate "*" name "-CACHE-MISSES*")))
443 (inits `(setq ,n-probe 0))
444 (inits `(setq ,n-miss 0))
445 (forms `(defvar ,n-probe))
446 (forms `(defvar ,n-miss))
447 (forms `(declaim (fixnum ,n-miss ,n-probe)))))
449 (let ((fun-name (symbolicate name "-CACHE-LOOKUP")))
452 `(defun ,fun-name ,(arg-vars)
453 ,@(when *profile-hash-cache*
454 `((incf ,(symbolicate "*" name "-CACHE-PROBES*"))))
455 (let ((,n-index (* (,hash-function ,@(arg-vars)) ,entry-size))
456 (,n-cache ,var-name))
457 (declare (type fixnum ,n-index))
458 (cond ((and ,@(tests))
459 (values ,@(mapcar (lambda (x) `(svref ,n-cache ,x))
462 ,@(when *profile-hash-cache*
463 `((incf ,(symbolicate "*" name "-CACHE-MISSES*"))))
466 (let ((fun-name (symbolicate name "-CACHE-ENTER")))
469 `(defun ,fun-name (,@(arg-vars) ,@(values-names))
470 (let ((,n-index (* (,hash-function ,@(arg-vars)) ,entry-size))
471 (,n-cache ,var-name))
472 (declare (type fixnum ,n-index))
474 ,@(mapcar (lambda (i val)
475 `(setf (svref ,n-cache ,i) ,val))
480 (let ((fun-name (symbolicate name "-CACHE-CLEAR")))
483 (do ((,n-index ,(- total-size entry-size) (- ,n-index ,entry-size))
484 (,n-cache ,var-name))
486 (declare (type fixnum ,n-index))
487 ,@(collect ((arg-sets))
489 (arg-sets `(setf (svref ,n-cache (+ ,n-index ,i)) nil)))
491 ,@(mapcar (lambda (i val)
492 `(setf (svref ,n-cache ,i) ,val))
496 (forms `(,fun-name)))
498 (inits `(unless (boundp ',var-name)
499 (setq ,var-name (make-array ,total-size))))
500 #!+sb-show (inits `(setq *hash-caches-initialized-p* t))
504 (declaim (type (simple-vector ,total-size) ,var-name))
505 #!-sb-fluid (declaim (inline ,@(inlines)))
506 (,init-wrapper ,@(inits))
510 ;;; some syntactic sugar for defining a function whose values are
511 ;;; cached by DEFINE-HASH-CACHE
512 (defmacro defun-cached ((name &rest options &key (values 1) default
514 args &body body-decls-doc)
515 (let ((default-values (if (and (consp default) (eq (car default) 'values))
518 (arg-names (mapcar #'car args)))
519 (collect ((values-names))
521 (values-names (gensym)))
522 (multiple-value-bind (body decls doc) (parse-body body-decls-doc)
524 (define-hash-cache ,name ,args ,@options)
525 (defun ,name ,arg-names
529 ((not (boundp '*hash-caches-initialized-p*))
530 ;; This shouldn't happen, but it did happen to me
531 ;; when revising the type system, and it's a lot
532 ;; easier to figure out what what's going on with
533 ;; that kind of problem if the system can be kept
534 ;; alive until cold boot is complete. The recovery
535 ;; mechanism should definitely be conditional on
536 ;; some debugging feature (e.g. SB-SHOW) because
537 ;; it's big, duplicating all the BODY code. -- WHN
538 (/show0 ,name " too early in cold init, uncached")
539 (/show0 ,(first arg-names) "=..")
540 (/hexstr ,(first arg-names))
543 (multiple-value-bind ,(values-names)
544 (,(symbolicate name "-CACHE-LOOKUP") ,@arg-names)
545 (if (and ,@(mapcar (lambda (val def)
547 (values-names) default-values))
548 (multiple-value-bind ,(values-names)
550 (,(symbolicate name "-CACHE-ENTER") ,@arg-names
552 (values ,@(values-names)))
553 (values ,@(values-names))))))))))))
557 ;;; Note: Almost always you want to use FIND-UNDELETED-PACKAGE-OR-LOSE
558 ;;; instead of this function. (The distinction only actually matters when
559 ;;; PACKAGE-DESIGNATOR is actually a deleted package, and in that case
560 ;;; you generally do want to signal an error instead of proceeding.)
561 (defun %find-package-or-lose (package-designator)
562 (or (find-package package-designator)
563 (error 'sb!kernel:simple-package-error
564 :package package-designator
565 :format-control "The name ~S does not designate any package."
566 :format-arguments (list package-designator))))
568 ;;; ANSI specifies (in the section for FIND-PACKAGE) that the
569 ;;; consequences of most operations on deleted packages are
570 ;;; unspecified. We try to signal errors in such cases.
571 (defun find-undeleted-package-or-lose (package-designator)
572 (let ((maybe-result (%find-package-or-lose package-designator)))
573 (if (package-name maybe-result) ; if not deleted
575 (error 'sb!kernel:simple-package-error
576 :package maybe-result
577 :format-control "The package ~S has been deleted."
578 :format-arguments (list maybe-result)))))
580 ;;;; various operations on names
582 ;;; Is NAME a legal function name?
583 (defun legal-fun-name-p (name)
586 (eq (car name) 'setf)
588 (symbolp (cadr name))
589 (null (cddr name)))))
591 ;;; Given a function name, return the name for the BLOCK which
592 ;;; encloses its body (e.g. in DEFUN, DEFINE-COMPILER-MACRO, or FLET).
593 (declaim (ftype (function ((or symbol cons)) symbol) fun-name-block-name))
594 (defun fun-name-block-name (fun-name)
595 (cond ((symbolp fun-name)
597 ((and (consp fun-name)
598 (= (length fun-name) 2)
599 (eq (first fun-name) 'setf))
602 (error "not legal as a function name: ~S" fun-name))))
604 (defun looks-like-name-of-special-var-p (x)
606 (let ((name (symbol-name x)))
607 (and (> (length name) 2) ; to exclude '* and '**
608 (char= #\* (aref name 0))
609 (char= #\* (aref name (1- (length name))))))))
611 ;;; Some symbols are defined by ANSI to be self-evaluating. Return
612 ;;; non-NIL for such symbols (and make the non-NIL value a traditional
613 ;;; message, for use in contexts where the user asks us to change such
615 (defun symbol-self-evaluating-p (symbol)
616 (declare (type symbol symbol))
618 "Veritas aeterna. (can't change T)")
620 "Nihil ex nihil. (can't change NIL)")
622 "Keyword values can't be changed.")
626 ;;; This function is to be called just before a change which would
627 ;;; affect the symbol value. (We don't absolutely have to call this
628 ;;; function before such changes, since such changes are given as
629 ;;; undefined behavior. In particular, we don't if the runtime cost
630 ;;; would be annoying. But otherwise it's nice to do so.)
631 (defun about-to-modify-symbol-value (symbol)
632 (declare (type symbol symbol))
633 (let ((reason (symbol-self-evaluating-p symbol)))
636 ;; (Note: Just because a value is CONSTANTP is not a good enough
637 ;; reason to complain here, because we want DEFCONSTANT to be able
638 ;; to use this function, and it's legal to DEFCONSTANT a constant as
639 ;; long as the new value is EQL to the old value.)
643 ;;; If COLD-FSET occurs not at top level, just treat it as an ordinary
644 ;;; assignment instead of doing cold static linking. That way things like
645 ;;; (FLET ((FROB (X) ..))
646 ;;; (DEFUN FOO (X Y) (FROB X) ..)
647 ;;; (DEFUN BAR (Z) (AND (FROB X) ..)))
648 ;;; can still "work" for cold init: they don't do magical static
649 ;;; linking the way that true toplevel DEFUNs do, but at least they do
650 ;;; the linking eventually, so as long as #'FOO and #'BAR aren't
651 ;;; needed until "cold toplevel forms" have executed, it's OK.
652 (defmacro cold-fset (name lambda)
654 "~@<COLD-FSET ~S not cross-compiled at top level: demoting to ~
655 (SETF FDEFINITION)~:@>"
657 ;; We convert the LAMBDA expression to the corresponding NAMED-LAMBDA
658 ;; expression so that the compiler can use NAME in debug names etc.
659 (destructuring-bind (lambda-symbol &rest lambda-rest) lambda
660 (assert (eql lambda-symbol 'lambda)) ; else dunno how to do conversion
661 `(setf (fdefinition ',name)
662 (named-lambda ,name ,@lambda-rest))))
666 ;;;; "The macro ONCE-ONLY has been around for a long time on various
667 ;;;; systems [..] if you can understand how to write and when to use
668 ;;;; ONCE-ONLY, then you truly understand macro." -- Peter Norvig,
669 ;;;; _Paradigms of Artificial Intelligence Programming: Case Studies
670 ;;;; in Common Lisp_, p. 853
672 ;;; ONCE-ONLY is a utility useful in writing source transforms and
673 ;;; macros. It provides a concise way to wrap a LET around some code
674 ;;; to ensure that some forms are only evaluated once.
676 ;;; Create a LET* which evaluates each value expression, binding a
677 ;;; temporary variable to the result, and wrapping the LET* around the
678 ;;; result of the evaluation of BODY. Within the body, each VAR is
679 ;;; bound to the corresponding temporary variable.
680 (defmacro once-only (specs &body body)
681 (named-let frob ((specs specs)
685 (let ((spec (first specs)))
686 ;; FIXME: should just be DESTRUCTURING-BIND of SPEC
687 (unless (proper-list-of-length-p spec 2)
688 (error "malformed ONCE-ONLY binding spec: ~S" spec))
689 (let* ((name (first spec))
690 (exp-temp (gensym (symbol-name name))))
691 `(let ((,exp-temp ,(second spec))
692 (,name (gensym "ONCE-ONLY-")))
693 `(let ((,,name ,,exp-temp))
694 ,,(frob (rest specs) body))))))))
696 ;;;; various error-checking utilities
698 ;;; This function can be used as the default value for keyword
699 ;;; arguments that must be always be supplied. Since it is known by
700 ;;; the compiler to never return, it will avoid any compile-time type
701 ;;; warnings that would result from a default value inconsistent with
702 ;;; the declared type. When this function is called, it signals an
703 ;;; error indicating that a required &KEY argument was not supplied.
704 ;;; This function is also useful for DEFSTRUCT slot defaults
705 ;;; corresponding to required arguments.
706 (declaim (ftype (function () nil) missing-arg))
707 (defun missing-arg ()
709 (/show0 "entering MISSING-ARG")
710 (error "A required &KEY or &OPTIONAL argument was not supplied."))
712 ;;; like CL:ASSERT and CL:CHECK-TYPE, but lighter-weight
714 ;;; (As of sbcl-0.6.11.20, we were using some 400 calls to CL:ASSERT.
715 ;;; The CL:ASSERT restarts and whatnot expand into a significant
716 ;;; amount of code when you multiply them by 400, so replacing them
717 ;;; with this should reduce the size of the system by enough to be
718 ;;; worthwhile. ENFORCE-TYPE is much less common, but might still be
719 ;;; worthwhile, and since I don't really like CERROR stuff deep in the
720 ;;; guts of complex systems anyway, I replaced it too.)
721 (defmacro aver (expr)
723 (%failed-aver ,(format nil "~A" expr))))
725 (defun %failed-aver (expr-as-string)
726 (bug "~@<failed AVER: ~2I~_~S~:>" expr-as-string))
728 ;;; We need a definition of BUG here for the host compiler to be able
729 ;;; to deal with BUGs in sbcl. This should never affect an end-user,
730 ;;; who will pick up the definition that signals a CONDITION of
731 ;;; condition-class BUG; however, this is not defined on the host
732 ;;; lisp, but for the target. SBCL developers sometimes trigger BUGs
733 ;;; in their efforts, and it is useful to get the details of the BUG
734 ;;; rather than an undefined function error. - CSR, 2002-04-12
736 (defun bug (format-control &rest format-arguments)
738 :format-control "~@< ~? ~:@_~?~:>"
739 :format-arguments `(,format-control
741 "~@<If you see this and are an SBCL ~
742 developer, then it is probable that you have made a change to the ~
743 system that has broken the ability for SBCL to compile, usually by ~
744 removing an assumed invariant of the system, but sometimes by making ~
745 an averrance that is violated (check your code!). If you are a user, ~
746 please submit a bug report to the developers' mailing list, details of ~
747 which can be found at <http://sbcl.sourceforge.net/>.~:@>"
750 (defmacro enforce-type (value type)
751 (once-only ((value value))
752 `(unless (typep ,value ',type)
753 (%failed-enforce-type ,value ',type))))
755 (defun %failed-enforce-type (value type)
756 (error 'simple-type-error ; maybe should be TYPE-BUG, subclass of BUG?
759 :format-string "~@<~S ~_is not a ~_~S~:>"
760 :format-arguments (list value type)))
762 ;;; Return a list of N gensyms. (This is a common suboperation in
763 ;;; macros and other code-manipulating code.)
764 (declaim (ftype (function (index) list) make-gensym-list))
765 (defun make-gensym-list (n)
766 (loop repeat n collect (gensym)))
768 ;;; Return a function like FUN, but expecting its (two) arguments in
769 ;;; the opposite order that FUN does.
770 (declaim (inline swapped-args-fun))
771 (defun swapped-args-fun (fun)
772 (declare (type function fun))
776 ;;; Return the numeric value of a type bound, i.e. an interval bound
777 ;;; more or less in the format of bounds in ANSI's type specifiers,
778 ;;; where a bare numeric value is a closed bound and a list of a
779 ;;; single numeric value is an open bound.
781 ;;; The "more or less" bit is that the no-bound-at-all case is
782 ;;; represented by NIL (not by * as in ANSI type specifiers); and in
783 ;;; this case we return NIL.
784 (defun type-bound-number (x)
786 (destructuring-bind (result) x result)
789 ;;; some commonly-occuring CONSTANTLY forms
790 (macrolet ((def-constantly-fun (name constant-expr)
791 `(setf (symbol-function ',name)
792 (constantly ,constant-expr))))
793 (def-constantly-fun constantly-t t)
794 (def-constantly-fun constantly-nil nil)
795 (def-constantly-fun constantly-0 0))
797 ;;; If X is an atom, see whether it is present in *FEATURES*. Also
798 ;;; handle arbitrary combinations of atoms using NOT, AND, OR.
804 (error "too many subexpressions in feature expression: ~S" x)
805 (not (featurep (cadr x)))))
806 ((:and and) (every #'featurep (cdr x)))
807 ((:or or) (some #'featurep (cdr x)))
809 (error "unknown operator in feature expression: ~S." x)))
810 (not (null (memq x *features*)))))
812 ;;; Given a list of keyword substitutions `(,OLD ,NEW), and a
813 ;;; &KEY-argument-list-style list of alternating keywords and
814 ;;; arbitrary values, return a new &KEY-argument-list-style list with
815 ;;; all substitutions applied to it.
817 ;;; Note: If efficiency mattered, we could do less consing. (But if
818 ;;; efficiency mattered, why would we be using &KEY arguments at
819 ;;; all, much less renaming &KEY arguments?)
821 ;;; KLUDGE: It would probably be good to get rid of this. -- WHN 19991201
822 (defun rename-key-args (rename-list key-args)
823 (declare (type list rename-list key-args))
824 ;; Walk through RENAME-LIST modifying RESULT as per each element in
826 (do ((result (copy-list key-args))) ; may be modified below
827 ((null rename-list) result)
828 (destructuring-bind (old new) (pop rename-list)
829 ;; ANSI says &KEY arg names aren't necessarily KEYWORDs.
830 (declare (type symbol old new))
831 ;; Walk through RESULT renaming any OLD key argument to NEW.
832 (do ((in-result result (cddr in-result)))
834 (declare (type list in-result))
835 (when (eq (car in-result) old)
836 (setf (car in-result) new))))))
838 ;;; ANSI Common Lisp's READ-SEQUENCE function, unlike most of the
839 ;;; other ANSI input functions, is defined to communicate end of file
840 ;;; status with its return value, not by signalling. That is not the
841 ;;; behavior that we usually want. This function is a wrapper which
842 ;;; restores the behavior that we usually want, causing READ-SEQUENCE
843 ;;; to communicate end-of-file status by signalling.
844 (defun read-sequence-or-die (sequence stream &key start end)
845 ;; implementation using READ-SEQUENCE
846 #-no-ansi-read-sequence
847 (let ((read-end (read-sequence sequence
851 (unless (= read-end end)
852 (error 'end-of-file :stream stream))
854 ;; workaround for broken READ-SEQUENCE
855 #+no-ansi-read-sequence
857 (aver (<= start end))
858 (let ((etype (stream-element-type stream)))
859 (cond ((equal etype '(unsigned-byte 8))
860 (do ((i start (1+ i)))
863 (setf (aref sequence i)
864 (read-byte stream))))
865 (t (error "unsupported element type ~S" etype))))))
867 ;;;; utilities for two-VALUES predicates
869 ;;; sort of like ANY and EVERY, except:
870 ;;; * We handle two-VALUES predicate functions, as SUBTYPEP does.
871 ;;; (And if the result is uncertain, then we return (VALUES NIL NIL),
872 ;;; as SUBTYPEP does.)
873 ;;; * THING is just an atom, and we apply OP (an arity-2 function)
874 ;;; successively to THING and each element of LIST.
875 (defun any/type (op thing list)
876 (declare (type function op))
878 (dolist (i list (values nil certain?))
879 (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
881 (when sub-value (return (values t t)))
882 (setf certain? nil))))))
883 (defun every/type (op thing list)
884 (declare (type function op))
886 (dolist (i list (if certain? (values t t) (values nil nil)))
887 (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
889 (unless sub-value (return (values nil t)))
890 (setf certain? nil))))))
894 ;;; These functions are called by the expansion of the DEFPRINTER
895 ;;; macro to do the actual printing.
896 (declaim (ftype (function (symbol t stream) (values))
897 defprinter-prin1 defprinter-princ))
898 (defun defprinter-prin1 (name value stream)
899 (defprinter-prinx #'prin1 name value stream))
900 (defun defprinter-princ (name value stream)
901 (defprinter-prinx #'princ name value stream))
902 (defun defprinter-prinx (prinx name value stream)
903 (declare (type function prinx))
905 (pprint-newline :linear stream))
906 (format stream ":~A " name)
907 (funcall prinx value stream)
909 (defun defprinter-print-space (stream)
910 (write-char #\space stream))
912 ;;; Define some kind of reasonable PRINT-OBJECT method for a
913 ;;; STRUCTURE-OBJECT class.
915 ;;; NAME is the name of the structure class, and CONC-NAME is the same
918 ;;; The SLOT-DESCS describe how each slot should be printed. Each
919 ;;; SLOT-DESC can be a slot name, indicating that the slot should
920 ;;; simply be printed. A SLOT-DESC may also be a list of a slot name
921 ;;; and other stuff. The other stuff is composed of keywords followed
922 ;;; by expressions. The expressions are evaluated with the variable
923 ;;; which is the slot name bound to the value of the slot. These
924 ;;; keywords are defined:
926 ;;; :PRIN1 Print the value of the expression instead of the slot value.
927 ;;; :PRINC Like :PRIN1, only PRINC the value
928 ;;; :TEST Only print something if the test is true.
930 ;;; If no printing thing is specified then the slot value is printed
933 ;;; The structure being printed is bound to STRUCTURE and the stream
934 ;;; is bound to STREAM.
935 (defmacro defprinter ((name
937 (conc-name (concatenate 'simple-string
944 (reversed-prints nil)
945 (stream (gensym "STREAM")))
946 (flet ((sref (slot-name)
947 `(,(symbolicate conc-name slot-name) structure)))
948 (dolist (slot-desc slot-descs)
950 (setf maybe-print-space nil
952 (setf maybe-print-space `(defprinter-print-space ,stream)))
953 (cond ((atom slot-desc)
954 (push maybe-print-space reversed-prints)
955 (push `(defprinter-prin1 ',slot-desc ,(sref slot-desc) ,stream)
958 (let ((sname (first slot-desc))
961 (do ((option (rest slot-desc) (cddr option)))
963 (push `(let ((,sname ,(sref sname)))
968 ',sname ,sname ,stream)))))
972 (stuff `(defprinter-prin1
973 ',sname ,(second option) ,stream)))
975 (stuff `(defprinter-princ
976 ',sname ,(second option) ,stream)))
977 (:test (setq test (second option)))
979 (error "bad option: ~S" (first option)))))))))))
980 `(def!method print-object ((structure ,name) ,stream)
981 (pprint-logical-block (,stream nil)
982 (print-unreadable-object (structure
986 ,@(nreverse reversed-prints))))))
990 ;;; Given a pathname, return a corresponding physical pathname.
991 (defun physicalize-pathname (possibly-logical-pathname)
992 (if (typep possibly-logical-pathname 'logical-pathname)
993 (translate-logical-pathname possibly-logical-pathname)
994 possibly-logical-pathname))
996 (defun deprecation-warning (bad-name &optional good-name)
997 (warn "using deprecated ~S~@[, should use ~S instead~]"