0.8.1.21:
[sbcl.git] / src / code / early-extensions.lisp
1 ;;;; various extensions (including SB-INT "internal extensions")
2 ;;;; available both in the cross-compilation host Lisp and in the
3 ;;;; target SBCL
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
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.
13
14 (in-package "SB!IMPL")
15
16 ;;; something not EQ to anything we might legitimately READ
17 (defparameter *eof-object* (make-symbol "EOF-OBJECT"))
18
19 ;;; a type used for indexing into arrays, and for related quantities
20 ;;; like lengths of lists
21 ;;;
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
27 ;;; result.
28 ;;;
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)))
32
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)))
38
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 0))
44          (let ((bound (ash 1 s)))
45            `(integer 0 ,(- bound bite 1))))
46         (t
47          (error "Bad size specified for UNSIGNED-BYTE type specifier: ~S." s))))
48
49 ;;; Motivated by the mips port. -- CSR, 2002-08-22
50 (def!type signed-byte-with-a-bite-out (s bite)
51   (cond ((eq s '*) 'integer)
52         ((and (integerp s) (> s 1))
53          (let ((bound (ash 1 (1- s))))
54            `(integer ,(- bound) ,(- bound bite 1))))
55         (t
56          (error "Bad size specified for SIGNED-BYTE type specifier: ~S." s))))
57
58 (def!type load/store-index (scale lowtag min-offset
59                                  &optional (max-offset min-offset))
60   `(integer ,(- (truncate (+ (ash 1 16)
61                              (* min-offset sb!vm:n-word-bytes)
62                              (- lowtag))
63                           scale))
64             ,(truncate (- (+ (1- (ash 1 16)) lowtag)
65                           (* max-offset sb!vm:n-word-bytes))
66                        scale)))
67
68 ;;; Similar to FUNCTION, but the result type is "exactly" specified:
69 ;;; if it is an object type, then the function returns exactly one
70 ;;; value, if it is a short form of VALUES, then this short form
71 ;;; specifies the exact number of values.
72 (def!type sfunction (args &optional result)
73   (let ((result (cond ((eq result '*) '*)
74                       ((or (atom result)
75                            (not (eq (car result) 'values)))
76                        `(values ,result &optional))
77                       ((intersection (cdr result) lambda-list-keywords)
78                        result)
79                       (t `(values ,@(cdr result) &optional)))))
80     `(function ,args ,result)))
81
82 ;;; the default value used for initializing character data. The ANSI
83 ;;; spec says this is arbitrary, so we use the value that falls
84 ;;; through when we just let the low-level consing code initialize
85 ;;; all newly-allocated memory to zero.
86 ;;;
87 ;;; KLUDGE: It might be nice to use something which is a
88 ;;; STANDARD-CHAR, both to reduce user surprise a little and, probably
89 ;;; more significantly, to help SBCL's cross-compiler (which knows how
90 ;;; to dump STANDARD-CHARs). Unfortunately, the old CMU CL code is
91 ;;; shot through with implicit assumptions that it's #\NULL, and code
92 ;;; in several places (notably both DEFUN MAKE-ARRAY and DEFTRANSFORM
93 ;;; MAKE-ARRAY) would have to be rewritten. -- WHN 2001-10-04
94 (eval-when (:compile-toplevel :load-toplevel :execute)
95   ;; an expression we can use to construct a DEFAULT-INIT-CHAR value
96   ;; at load time (so that we don't need to teach the cross-compiler
97   ;; how to represent and dump non-STANDARD-CHARs like #\NULL)
98   (defparameter *default-init-char-form* '(code-char 0)))
99
100 ;;; CHAR-CODE values for ASCII characters which we care about but
101 ;;; which aren't defined in section "2.1.3 Standard Characters" of the
102 ;;; ANSI specification for Lisp
103 ;;;
104 ;;; KLUDGE: These are typically used in the idiom (CODE-CHAR
105 ;;; FOO-CHAR-CODE). I suspect that the current implementation is
106 ;;; expanding this idiom into a full call to CODE-CHAR, which is an
107 ;;; annoying overhead. I should check whether this is happening, and
108 ;;; if so, perhaps implement a DEFTRANSFORM or something to stop it.
109 ;;; (or just find a nicer way of expressing characters portably?) --
110 ;;; WHN 19990713
111 (def!constant bell-char-code 7)
112 (def!constant backspace-char-code 8)
113 (def!constant tab-char-code 9)
114 (def!constant line-feed-char-code 10)
115 (def!constant form-feed-char-code 12)
116 (def!constant return-char-code 13)
117 (def!constant escape-char-code 27)
118 (def!constant rubout-char-code 127)
119 \f
120 ;;;; type-ish predicates
121
122 ;;; Is X a list containing a cycle?
123 (defun cyclic-list-p (x)
124   (and (listp x)
125        (labels ((safe-cddr (x) (if (listp (cdr x)) (cddr x)))) 
126          (do ((y x (safe-cddr y))
127               (started-p nil t)
128               (z x (cdr z)))
129              ((not (and (consp z) (consp y))) nil)
130            (when (and started-p (eq y z))
131              (return t))))))
132
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
137       (and (consp x)
138            (list-of-length-at-least-p (cdr x) (1- n)))))
139
140 (declaim (inline singleton-p))
141 (defun singleton-p (list)
142   (and (consp list)
143        (null (rest list))))
144
145 ;;; Is X is a positive prime integer? 
146 (defun positive-primep (x)
147   ;; This happens to be called only from one place in sbcl-0.7.0, and
148   ;; only for fixnums, we can limit it to fixnums for efficiency. (And
149   ;; if we didn't limit it to fixnums, we should use a cleverer
150   ;; algorithm, since this one scales pretty badly for huge X.)
151   (declare (fixnum x))
152   (if (<= x 5)
153       (and (>= x 2) (/= x 4))
154       (and (not (evenp x))
155            (not (zerop (rem x 3)))
156            (do ((q 6)
157                 (r 1)
158                 (inc 2 (logxor inc 6)) ;; 2,4,2,4...
159                 (d 5 (+ d inc)))
160                ((or (= r 0) (> d q)) (/= r 0))
161              (declare (fixnum inc))
162              (multiple-value-setq (q r) (truncate x d))))))
163
164 ;;; Could this object contain other objects? (This is important to
165 ;;; the implementation of things like *PRINT-CIRCLE* and the dumper.)
166 (defun compound-object-p (x)
167   (or (consp x)
168       (typep x 'instance)
169       (typep x '(array t *))))
170 \f
171 ;;;; the COLLECT macro
172 ;;;;
173 ;;;; comment from CMU CL: "the ultimate collection macro..."
174
175 ;;; helper functions for COLLECT, which become the expanders of the
176 ;;; MACROLET definitions created by COLLECT
177 ;;;
178 ;;; COLLECT-NORMAL-EXPANDER handles normal collection macros.
179 ;;;
180 ;;; COLLECT-LIST-EXPANDER handles the list collection case. N-TAIL
181 ;;; is the pointer to the current tail of the list, or NIL if the list
182 ;;; is empty.
183 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
184   (defun collect-normal-expander (n-value fun forms)
185     `(progn
186        ,@(mapcar (lambda (form) `(setq ,n-value (,fun ,form ,n-value))) forms)
187        ,n-value))
188   (defun collect-list-expander (n-value n-tail forms)
189     (let ((n-res (gensym)))
190       `(progn
191          ,@(mapcar (lambda (form)
192                      `(let ((,n-res (cons ,form nil)))
193                         (cond (,n-tail
194                                (setf (cdr ,n-tail) ,n-res)
195                                (setq ,n-tail ,n-res))
196                               (t
197                                (setq ,n-tail ,n-res  ,n-value ,n-res)))))
198                    forms)
199          ,n-value))))
200
201 ;;; Collect some values somehow. Each of the collections specifies a
202 ;;; bunch of things which collected during the evaluation of the body
203 ;;; of the form. The name of the collection is used to define a local
204 ;;; macro, a la MACROLET. Within the body, this macro will evaluate
205 ;;; each of its arguments and collect the result, returning the
206 ;;; current value after the collection is done. The body is evaluated
207 ;;; as a PROGN; to get the final values when you are done, just call
208 ;;; the collection macro with no arguments.
209 ;;;
210 ;;; INITIAL-VALUE is the value that the collection starts out with,
211 ;;; which defaults to NIL. FUNCTION is the function which does the
212 ;;; collection. It is a function which will accept two arguments: the
213 ;;; value to be collected and the current collection. The result of
214 ;;; the function is made the new value for the collection. As a
215 ;;; totally magical special-case, FUNCTION may be COLLECT, which tells
216 ;;; us to build a list in forward order; this is the default. If an
217 ;;; INITIAL-VALUE is supplied for COLLECT, the stuff will be RPLACD'd
218 ;;; onto the end. Note that FUNCTION may be anything that can appear
219 ;;; in the functional position, including macros and lambdas.
220 (defmacro collect (collections &body body)
221   (let ((macros ())
222         (binds ()))
223     (dolist (spec collections)
224       (unless (proper-list-of-length-p spec 1 3)
225         (error "malformed collection specifier: ~S" spec))
226       (let* ((name (first spec))
227              (default (second spec))
228              (kind (or (third spec) 'collect))
229              (n-value (gensym (concatenate 'string
230                                            (symbol-name name)
231                                            "-N-VALUE-"))))
232         (push `(,n-value ,default) binds)
233         (if (eq kind 'collect)
234           (let ((n-tail (gensym (concatenate 'string
235                                              (symbol-name name)
236                                              "-N-TAIL-"))))
237             (if default
238               (push `(,n-tail (last ,n-value)) binds)
239               (push n-tail binds))
240             (push `(,name (&rest args)
241                      (collect-list-expander ',n-value ',n-tail args))
242                   macros))
243           (push `(,name (&rest args)
244                    (collect-normal-expander ',n-value ',kind args))
245                 macros))))
246     `(macrolet ,macros (let* ,(nreverse binds) ,@body))))
247 \f
248 ;;;; some old-fashioned functions. (They're not just for old-fashioned
249 ;;;; code, they're also used as optimized forms of the corresponding
250 ;;;; general functions when the compiler can prove that they're
251 ;;;; equivalent.)
252
253 ;;; like (MEMBER ITEM LIST :TEST #'EQ)
254 (defun memq (item list)
255   #!+sb-doc
256   "Return tail of LIST beginning with first element EQ to ITEM."
257   ;; KLUDGE: These could be and probably should be defined as
258   ;;   (MEMBER ITEM LIST :TEST #'EQ)),
259   ;; but when I try to cross-compile that, I get an error from
260   ;; LTN-ANALYZE-KNOWN-CALL, "Recursive known function definition". The
261   ;; comments for that error say it "is probably a botched interpreter stub".
262   ;; Rather than try to figure that out, I just rewrote this function from
263   ;; scratch. -- WHN 19990512
264   (do ((i list (cdr i)))
265       ((null i))
266     (when (eq (car i) item)
267       (return i))))
268
269 ;;; like (ASSOC ITEM ALIST :TEST #'EQ):
270 ;;;   Return the first pair of ALIST where ITEM is EQ to the key of
271 ;;;   the pair.
272 (defun assq (item alist)
273   ;; KLUDGE: CMU CL defined this with
274   ;;   (DECLARE (INLINE ASSOC))
275   ;;   (ASSOC ITEM ALIST :TEST #'EQ))
276   ;; which is pretty, but which would have required adding awkward
277   ;; build order constraints on SBCL (or figuring out some way to make
278   ;; inline definitions installable at build-the-cross-compiler time,
279   ;; which was too ambitious for now). Rather than mess with that, we
280   ;; just define ASSQ explicitly in terms of more primitive
281   ;; operations:
282   (dolist (pair alist)
283     (when (eq (car pair) item)
284       (return pair))))
285
286 ;;; like (DELETE .. :TEST #'EQ):
287 ;;;   Delete all LIST entries EQ to ITEM (destructively modifying
288 ;;;   LIST), and return the modified LIST.
289 (defun delq (item list)
290   (let ((list list))
291     (do ((x list (cdr x))
292          (splice '()))
293         ((endp x) list)
294       (cond ((eq item (car x))
295              (if (null splice)
296                (setq list (cdr x))
297                (rplacd splice (cdr x))))
298             (t (setq splice x)))))) ; Move splice along to include element.
299
300
301 ;;; like (POSITION .. :TEST #'EQ):
302 ;;;   Return the position of the first element EQ to ITEM.
303 (defun posq (item list)
304   (do ((i list (cdr i))
305        (j 0 (1+ j)))
306       ((null i))
307     (when (eq (car i) item)
308       (return j))))
309
310 (declaim (inline neq))
311 (defun neq (x y)
312   (not (eq x y)))
313
314 ;;; not really an old-fashioned function, but what the calling
315 ;;; convention should've been: like NTH, but with the same argument
316 ;;; order as in all the other dereferencing functions, with the
317 ;;; collection first and the index second
318 (declaim (inline nth-but-with-sane-arg-order))
319 (declaim (ftype (function (list index) t) nth-but-with-sane-arg-order))
320 (defun nth-but-with-sane-arg-order (list index)
321   (nth index list))
322
323 (defun adjust-list (list length initial-element)
324   (let ((old-length (length list)))
325     (cond ((< old-length length)
326            (append list (make-list (- length old-length)
327                                    :initial-element initial-element)))
328           ((> old-length length)
329            (subseq list 0 length))
330           (t list))))
331 \f
332 ;;;; miscellaneous iteration extensions
333
334 ;;; "the ultimate iteration macro"
335 ;;;
336 ;;; note for Schemers: This seems to be identical to Scheme's "named LET".
337 (defmacro named-let (name binds &body body)
338   #!+sb-doc
339   (dolist (x binds)
340     (unless (proper-list-of-length-p x 2)
341       (error "malformed NAMED-LET variable spec: ~S" x)))
342   `(labels ((,name ,(mapcar #'first binds) ,@body))
343      (,name ,@(mapcar #'second binds))))
344
345 ;;; just like DOLIST, but with one-dimensional arrays
346 (defmacro dovector ((elt vector &optional result) &rest forms)
347   (let ((index (gensym))
348         (length (gensym))
349         (vec (gensym)))
350     `(let ((,vec ,vector))
351        (declare (type vector ,vec))
352        (do ((,index 0 (1+ ,index))
353             (,length (length ,vec)))
354            ((>= ,index ,length) ,result)
355          (let ((,elt (aref ,vec ,index)))
356            ,@forms)))))
357
358 ;;; Iterate over the entries in a HASH-TABLE.
359 (defmacro dohash ((key-var value-var table &optional result) &body body)
360   (multiple-value-bind (forms decls) (parse-body body nil)
361     (let ((gen (gensym))
362           (n-more (gensym)))
363       `(with-hash-table-iterator (,gen ,table)
364          (loop
365           (multiple-value-bind (,n-more ,key-var ,value-var) (,gen)
366             ,@decls
367             (unless ,n-more (return ,result))
368             ,@forms))))))
369 \f
370 ;;;; hash cache utility
371
372 (eval-when (:compile-toplevel :load-toplevel :execute)
373   (defvar *profile-hash-cache* nil))
374
375 ;;; a flag for whether it's too early in cold init to use caches so
376 ;;; that we have a better chance of recovering so that we have a
377 ;;; better chance of getting the system running so that we have a
378 ;;; better chance of diagnosing the problem which caused us to use the
379 ;;; caches too early
380 #!+sb-show
381 (defvar *hash-caches-initialized-p*)
382
383 ;;; Define a hash cache that associates some number of argument values
384 ;;; with a result value. The TEST-FUNCTION paired with each ARG-NAME
385 ;;; is used to compare the value for that arg in a cache entry with a
386 ;;; supplied arg. The TEST-FUNCTION must not error when passed NIL as
387 ;;; its first arg, but need not return any particular value.
388 ;;; TEST-FUNCTION may be any thing that can be placed in CAR position.
389 ;;;
390 ;;; NAME is used to define these functions:
391 ;;; <name>-CACHE-LOOKUP Arg*
392 ;;;   See whether there is an entry for the specified ARGs in the
393 ;;;   cache. If not present, the :DEFAULT keyword (default NIL)
394 ;;;   determines the result(s).
395 ;;; <name>-CACHE-ENTER Arg* Value*
396 ;;;   Encache the association of the specified args with VALUE.
397 ;;; <name>-CACHE-CLEAR
398 ;;;   Reinitialize the cache, invalidating all entries and allowing
399 ;;;   the arguments and result values to be GC'd.
400 ;;;
401 ;;; These other keywords are defined:
402 ;;; :HASH-BITS <n>
403 ;;;   The size of the cache as a power of 2.
404 ;;; :HASH-FUNCTION function
405 ;;;   Some thing that can be placed in CAR position which will compute
406 ;;;   a value between 0 and (1- (expt 2 <hash-bits>)).
407 ;;; :VALUES <n>
408 ;;;   the number of return values cached for each function call
409 ;;; :INIT-WRAPPER <name>
410 ;;;   The code for initializing the cache is wrapped in a form with
411 ;;;   the specified name. (:INIT-WRAPPER is set to COLD-INIT-FORMS
412 ;;;   in type system definitions so that caches will be created
413 ;;;   before top level forms run.)
414 (defmacro define-hash-cache (name args &key hash-function hash-bits default
415                                   (init-wrapper 'progn)
416                                   (values 1))
417   (let* ((var-name (symbolicate "*" name "-CACHE-VECTOR*"))
418          (nargs (length args))
419          (entry-size (+ nargs values))
420          (size (ash 1 hash-bits))
421          (total-size (* entry-size size))
422          (default-values (if (and (consp default) (eq (car default) 'values))
423                              (cdr default)
424                              (list default)))
425          (n-index (gensym))
426          (n-cache (gensym)))
427
428     (unless (= (length default-values) values)
429       (error "The number of default values ~S differs from :VALUES ~W."
430              default values))
431
432     (collect ((inlines)
433               (forms)
434               (inits)
435               (tests)
436               (sets)
437               (arg-vars)
438               (values-indices)
439               (values-names))
440       (dotimes (i values)
441         (values-indices `(+ ,n-index ,(+ nargs i)))
442         (values-names (gensym)))
443       (let ((n 0))
444         (dolist (arg args)
445           (unless (= (length arg) 2)
446             (error "bad argument spec: ~S" arg))
447           (let ((arg-name (first arg))
448                 (test (second arg)))
449             (arg-vars arg-name)
450             (tests `(,test (svref ,n-cache (+ ,n-index ,n)) ,arg-name))
451             (sets `(setf (svref ,n-cache (+ ,n-index ,n)) ,arg-name)))
452           (incf n)))
453
454       (when *profile-hash-cache*
455         (let ((n-probe (symbolicate "*" name "-CACHE-PROBES*"))
456               (n-miss (symbolicate "*" name "-CACHE-MISSES*")))
457           (inits `(setq ,n-probe 0))
458           (inits `(setq ,n-miss 0))
459           (forms `(defvar ,n-probe))
460           (forms `(defvar ,n-miss))
461           (forms `(declaim (fixnum ,n-miss ,n-probe)))))
462
463       (let ((fun-name (symbolicate name "-CACHE-LOOKUP")))
464         (inlines fun-name)
465         (forms
466          `(defun ,fun-name ,(arg-vars)
467             ,@(when *profile-hash-cache*
468                 `((incf ,(symbolicate  "*" name "-CACHE-PROBES*"))))
469             (let ((,n-index (* (,hash-function ,@(arg-vars)) ,entry-size))
470                   (,n-cache ,var-name))
471               (declare (type fixnum ,n-index))
472               (cond ((and ,@(tests))
473                      (values ,@(mapcar (lambda (x) `(svref ,n-cache ,x))
474                                        (values-indices))))
475                     (t
476                      ,@(when *profile-hash-cache*
477                          `((incf ,(symbolicate  "*" name "-CACHE-MISSES*"))))
478                      ,default))))))
479
480       (let ((fun-name (symbolicate name "-CACHE-ENTER")))
481         (inlines fun-name)
482         (forms
483          `(defun ,fun-name (,@(arg-vars) ,@(values-names))
484             (let ((,n-index (* (,hash-function ,@(arg-vars)) ,entry-size))
485                   (,n-cache ,var-name))
486               (declare (type fixnum ,n-index))
487               ,@(sets)
488               ,@(mapcar (lambda (i val)
489                           `(setf (svref ,n-cache ,i) ,val))
490                         (values-indices)
491                         (values-names))
492               (values)))))
493
494       (let ((fun-name (symbolicate name "-CACHE-CLEAR")))
495         (forms
496          `(defun ,fun-name ()
497             (do ((,n-index ,(- total-size entry-size) (- ,n-index ,entry-size))
498                  (,n-cache ,var-name))
499                 ((minusp ,n-index))
500               (declare (type fixnum ,n-index))
501               ,@(collect ((arg-sets))
502                   (dotimes (i nargs)
503                     (arg-sets `(setf (svref ,n-cache (+ ,n-index ,i)) nil)))
504                   (arg-sets))
505               ,@(mapcar (lambda (i val)
506                           `(setf (svref ,n-cache ,i) ,val))
507                         (values-indices)
508                         default-values))
509             (values)))
510         (forms `(,fun-name)))
511
512       (inits `(unless (boundp ',var-name)
513                 (setq ,var-name (make-array ,total-size))))
514       #!+sb-show (inits `(setq *hash-caches-initialized-p* t))
515
516       `(progn
517          (defvar ,var-name)
518          (declaim (type (simple-vector ,total-size) ,var-name))
519          #!-sb-fluid (declaim (inline ,@(inlines)))
520          (,init-wrapper ,@(inits))
521          ,@(forms)
522          ',name))))
523
524 ;;; some syntactic sugar for defining a function whose values are
525 ;;; cached by DEFINE-HASH-CACHE
526 (defmacro defun-cached ((name &rest options &key (values 1) default
527                               &allow-other-keys)
528                         args &body body-decls-doc)
529   (let ((default-values (if (and (consp default) (eq (car default) 'values))
530                             (cdr default)
531                             (list default)))
532         (arg-names (mapcar #'car args)))
533     (collect ((values-names))
534       (dotimes (i values)
535         (values-names (gensym)))
536       (multiple-value-bind (body decls doc) (parse-body body-decls-doc)
537         `(progn
538            (define-hash-cache ,name ,args ,@options)
539            (defun ,name ,arg-names
540              ,@decls
541              ,doc
542              (cond #!+sb-show
543                    ((not (boundp '*hash-caches-initialized-p*))
544                     ;; This shouldn't happen, but it did happen to me
545                     ;; when revising the type system, and it's a lot
546                     ;; easier to figure out what what's going on with
547                     ;; that kind of problem if the system can be kept
548                     ;; alive until cold boot is complete. The recovery
549                     ;; mechanism should definitely be conditional on
550                     ;; some debugging feature (e.g. SB-SHOW) because
551                     ;; it's big, duplicating all the BODY code. -- WHN
552                     (/show0 ,name " too early in cold init, uncached")
553                     (/show0 ,(first arg-names) "=..")
554                     (/hexstr ,(first arg-names))
555                     ,@body)
556                    (t
557                     (multiple-value-bind ,(values-names)
558                         (,(symbolicate name "-CACHE-LOOKUP") ,@arg-names)
559                       (if (and ,@(mapcar (lambda (val def)
560                                            `(eq ,val ,def))
561                                          (values-names) default-values))
562                           (multiple-value-bind ,(values-names)
563                               (progn ,@body)
564                             (,(symbolicate name "-CACHE-ENTER") ,@arg-names
565                              ,@(values-names))
566                             (values ,@(values-names)))
567                           (values ,@(values-names))))))))))))
568
569 (defmacro define-cached-synonym
570     (name &optional (original (symbolicate "%" name)))
571   (let ((cached-name (symbolicate "%%" name "-cached")))
572     `(progn
573        (defun-cached (,cached-name :hash-bits 8
574                                    :hash-function (lambda (x)
575                                                     (logand (sxhash x) #xff)))
576            ((args equal))
577          (apply #',original args))
578        (defun ,name (&rest args)
579          (,cached-name args)))))
580
581 ;;; FIXME: maybe not the best place
582 ;;;
583 ;;; FIXME: think of a better name -- not only does this not have the
584 ;;; CAR recursion of EQUAL, it also doesn't have the special treatment
585 ;;; of pathnames, bit-vectors and strings.
586 ;;;
587 ;;; KLUDGE: This means that we will no longer cache specifiers of the
588 ;;; form '(INTEGER (0) 4).  This is probably not a disaster.
589 ;;;
590 ;;; A helper function for the type system, which is the main user of
591 ;;; these caches: we must be more conservative than EQUAL for some of
592 ;;; our equality tests, because MEMBER and friends refer to EQLity.
593 ;;; So:
594 (defun equal-but-no-car-recursion (x y)
595   (cond
596     ((eql x y) t)
597     ((consp x)
598      (and (consp y)
599           (eql (car x) (car y))
600           (equal-but-no-car-recursion (cdr x) (cdr y))))
601     (t nil)))
602 \f
603 ;;;; package idioms
604
605 ;;; Note: Almost always you want to use FIND-UNDELETED-PACKAGE-OR-LOSE
606 ;;; instead of this function. (The distinction only actually matters when
607 ;;; PACKAGE-DESIGNATOR is actually a deleted package, and in that case
608 ;;; you generally do want to signal an error instead of proceeding.)
609 (defun %find-package-or-lose (package-designator)
610   (or (find-package package-designator)
611       (error 'sb!kernel:simple-package-error
612              :package package-designator
613              :format-control "The name ~S does not designate any package."
614              :format-arguments (list package-designator))))
615
616 ;;; ANSI specifies (in the section for FIND-PACKAGE) that the
617 ;;; consequences of most operations on deleted packages are
618 ;;; unspecified. We try to signal errors in such cases.
619 (defun find-undeleted-package-or-lose (package-designator)
620   (let ((maybe-result (%find-package-or-lose package-designator)))
621     (if (package-name maybe-result)     ; if not deleted
622         maybe-result
623         (error 'sb!kernel:simple-package-error
624                :package maybe-result
625                :format-control "The package ~S has been deleted."
626                :format-arguments (list maybe-result)))))
627 \f
628 ;;;; various operations on names
629
630 ;;; Is NAME a legal function name?
631 (defun legal-fun-name-p (name)
632   (values (valid-function-name-p name)))
633
634 ;;; Signal an error unless NAME is a legal function name.
635 (defun legal-fun-name-or-type-error (name)
636   (unless (legal-fun-name-p name)
637     (error 'simple-type-error
638            :datum name
639            :expected-type '(or symbol list)
640            :format-control "invalid function name: ~S"
641            :format-arguments (list name))))
642
643 ;;; Given a function name, return the symbol embedded in it.
644 ;;;
645 ;;; The ordinary use for this operator (and the motivation for the
646 ;;; name of this operator) is to convert from a function name to the
647 ;;; name of the BLOCK which encloses its body.
648 ;;;
649 ;;; Occasionally the operator is useful elsewhere, where the operator
650 ;;; name is less mnemonic. (Maybe it should be changed?)
651 (declaim (ftype (function ((or symbol cons)) symbol) fun-name-block-name))
652 (defun fun-name-block-name (fun-name)
653   (cond ((symbolp fun-name)
654          fun-name)
655         ((consp fun-name)
656          (multiple-value-bind (legalp block-name)
657              (valid-function-name-p fun-name)
658            (if legalp
659                block-name
660                (error "not legal as a function name: ~S" fun-name))))
661         (t
662          (error "not legal as a function name: ~S" fun-name))))
663
664 (defun looks-like-name-of-special-var-p (x)
665   (and (symbolp x)
666        (let ((name (symbol-name x)))
667          (and (> (length name) 2) ; to exclude '* and '**
668               (char= #\* (aref name 0))
669               (char= #\* (aref name (1- (length name))))))))
670
671 ;;; Some symbols are defined by ANSI to be self-evaluating. Return
672 ;;; non-NIL for such symbols (and make the non-NIL value a traditional
673 ;;; message, for use in contexts where the user asks us to change such
674 ;;; a symbol).
675 (defun symbol-self-evaluating-p (symbol)
676   (declare (type symbol symbol))
677   (cond ((eq symbol t)
678          "Veritas aeterna. (can't change T)")
679         ((eq symbol nil)
680          "Nihil ex nihil. (can't change NIL)")
681         ((keywordp symbol)
682          "Keyword values can't be changed.")
683         (t
684          nil)))
685
686 ;;; This function is to be called just before a change which would
687 ;;; affect the symbol value. (We don't absolutely have to call this
688 ;;; function before such changes, since such changes are given as
689 ;;; undefined behavior. In particular, we don't if the runtime cost
690 ;;; would be annoying. But otherwise it's nice to do so.)
691 (defun about-to-modify-symbol-value (symbol)
692   (declare (type symbol symbol))
693   (let ((reason (symbol-self-evaluating-p symbol)))
694     (when reason
695       (error reason)))
696   ;; (Note: Just because a value is CONSTANTP is not a good enough
697   ;; reason to complain here, because we want DEFCONSTANT to be able
698   ;; to use this function, and it's legal to DEFCONSTANT a constant as
699   ;; long as the new value is EQL to the old value.)
700   (values))
701
702
703 ;;; If COLD-FSET occurs not at top level, just treat it as an ordinary
704 ;;; assignment instead of doing cold static linking. That way things like
705 ;;;   (FLET ((FROB (X) ..))
706 ;;;     (DEFUN FOO (X Y) (FROB X) ..)
707 ;;;     (DEFUN BAR (Z) (AND (FROB X) ..)))
708 ;;; can still "work" for cold init: they don't do magical static
709 ;;; linking the way that true toplevel DEFUNs do, but at least they do
710 ;;; the linking eventually, so as long as #'FOO and #'BAR aren't
711 ;;; needed until "cold toplevel forms" have executed, it's OK.
712 (defmacro cold-fset (name lambda)
713   (style-warn 
714    "~@<COLD-FSET ~S not cross-compiled at top level: demoting to ~
715 (SETF FDEFINITION)~:@>"
716    name)
717   ;; We convert the LAMBDA expression to the corresponding NAMED-LAMBDA
718   ;; expression so that the compiler can use NAME in debug names etc. 
719   (destructuring-bind (lambda-symbol &rest lambda-rest) lambda
720     (assert (eql lambda-symbol 'lambda)) ; else dunno how to do conversion
721     `(setf (fdefinition ',name)
722            (named-lambda ,name ,@lambda-rest))))
723 \f
724 ;;;; ONCE-ONLY
725 ;;;;
726 ;;;; "The macro ONCE-ONLY has been around for a long time on various
727 ;;;; systems [..] if you can understand how to write and when to use
728 ;;;; ONCE-ONLY, then you truly understand macro." -- Peter Norvig,
729 ;;;; _Paradigms of Artificial Intelligence Programming: Case Studies
730 ;;;; in Common Lisp_, p. 853
731
732 ;;; ONCE-ONLY is a utility useful in writing source transforms and
733 ;;; macros. It provides a concise way to wrap a LET around some code
734 ;;; to ensure that some forms are only evaluated once.
735 ;;;
736 ;;; Create a LET* which evaluates each value expression, binding a
737 ;;; temporary variable to the result, and wrapping the LET* around the
738 ;;; result of the evaluation of BODY. Within the body, each VAR is
739 ;;; bound to the corresponding temporary variable.
740 (defmacro once-only (specs &body body)
741   (named-let frob ((specs specs)
742                    (body body))
743     (if (null specs)
744         `(progn ,@body)
745         (let ((spec (first specs)))
746           ;; FIXME: should just be DESTRUCTURING-BIND of SPEC
747           (unless (proper-list-of-length-p spec 2)
748             (error "malformed ONCE-ONLY binding spec: ~S" spec))
749           (let* ((name (first spec))
750                  (exp-temp (gensym (symbol-name name))))
751             `(let ((,exp-temp ,(second spec))
752                    (,name (gensym "ONCE-ONLY-")))
753                `(let ((,,name ,,exp-temp))
754                   ,,(frob (rest specs) body))))))))
755 \f
756 ;;;; various error-checking utilities
757
758 ;;; This function can be used as the default value for keyword
759 ;;; arguments that must be always be supplied. Since it is known by
760 ;;; the compiler to never return, it will avoid any compile-time type
761 ;;; warnings that would result from a default value inconsistent with
762 ;;; the declared type. When this function is called, it signals an
763 ;;; error indicating that a required &KEY argument was not supplied.
764 ;;; This function is also useful for DEFSTRUCT slot defaults
765 ;;; corresponding to required arguments.
766 (declaim (ftype (function () nil) missing-arg))
767 (defun missing-arg ()
768   #!+sb-doc
769   (/show0 "entering MISSING-ARG")
770   (error "A required &KEY or &OPTIONAL argument was not supplied."))
771
772 ;;; like CL:ASSERT and CL:CHECK-TYPE, but lighter-weight
773 ;;;
774 ;;; (As of sbcl-0.6.11.20, we were using some 400 calls to CL:ASSERT.
775 ;;; The CL:ASSERT restarts and whatnot expand into a significant
776 ;;; amount of code when you multiply them by 400, so replacing them
777 ;;; with this should reduce the size of the system by enough to be
778 ;;; worthwhile. ENFORCE-TYPE is much less common, but might still be
779 ;;; worthwhile, and since I don't really like CERROR stuff deep in the
780 ;;; guts of complex systems anyway, I replaced it too.)
781 (defmacro aver (expr)
782   `(unless ,expr
783      (%failed-aver ,(format nil "~A" expr))))
784
785 (defun %failed-aver (expr-as-string)
786   (bug "~@<failed AVER: ~2I~_~S~:>" expr-as-string))
787
788 ;;; We need a definition of BUG here for the host compiler to be able
789 ;;; to deal with BUGs in sbcl. This should never affect an end-user,
790 ;;; who will pick up the definition that signals a CONDITION of
791 ;;; condition-class BUG; however, this is not defined on the host
792 ;;; lisp, but for the target. SBCL developers sometimes trigger BUGs
793 ;;; in their efforts, and it is useful to get the details of the BUG
794 ;;; rather than an undefined function error. - CSR, 2002-04-12
795 #+sb-xc-host
796 (defun bug (format-control &rest format-arguments)
797   (error 'simple-error
798          :format-control "~@<  ~? ~:@_~?~:>"
799          :format-arguments `(,format-control
800                              ,format-arguments
801                              "~@<If you see this and are an SBCL ~
802 developer, then it is probable that you have made a change to the ~
803 system that has broken the ability for SBCL to compile, usually by ~
804 removing an assumed invariant of the system, but sometimes by making ~
805 an averrance that is violated (check your code!). If you are a user, ~
806 please submit a bug report to the developers' mailing list, details of ~
807 which can be found at <http://sbcl.sourceforge.net/>.~:@>"
808                              ())))
809
810 (defmacro enforce-type (value type)
811   (once-only ((value value))
812     `(unless (typep ,value ',type)
813        (%failed-enforce-type ,value ',type))))
814
815 (defun %failed-enforce-type (value type)
816   (error 'simple-type-error ; maybe should be TYPE-BUG, subclass of BUG?
817          :value value
818          :expected-type type
819          :format-control "~@<~S ~_is not a ~_~S~:>"
820          :format-arguments (list value type)))
821 \f
822 ;;; Return a function like FUN, but expecting its (two) arguments in
823 ;;; the opposite order that FUN does.
824 (declaim (inline swapped-args-fun))
825 (defun swapped-args-fun (fun)
826   (declare (type function fun))
827   (lambda (x y)
828     (funcall fun y x)))
829
830 ;;; Return the numeric value of a type bound, i.e. an interval bound
831 ;;; more or less in the format of bounds in ANSI's type specifiers,
832 ;;; where a bare numeric value is a closed bound and a list of a
833 ;;; single numeric value is an open bound.
834 ;;;
835 ;;; The "more or less" bit is that the no-bound-at-all case is
836 ;;; represented by NIL (not by * as in ANSI type specifiers); and in
837 ;;; this case we return NIL.
838 (defun type-bound-number (x)
839   (if (consp x)
840       (destructuring-bind (result) x result)
841       x))
842
843 ;;; some commonly-occuring CONSTANTLY forms
844 (macrolet ((def-constantly-fun (name constant-expr)
845              `(setf (symbol-function ',name)
846                     (constantly ,constant-expr))))
847   (def-constantly-fun constantly-t t)
848   (def-constantly-fun constantly-nil nil)
849   (def-constantly-fun constantly-0 0))
850
851 ;;; If X is an atom, see whether it is present in *FEATURES*. Also
852 ;;; handle arbitrary combinations of atoms using NOT, AND, OR.
853 (defun featurep (x)
854   (if (consp x)
855     (case (car x)
856       ((:not not)
857        (if (cddr x)
858          (error "too many subexpressions in feature expression: ~S" x)
859          (not (featurep (cadr x)))))
860       ((:and and) (every #'featurep (cdr x)))
861       ((:or or) (some #'featurep (cdr x)))
862       (t
863        (error "unknown operator in feature expression: ~S." x)))
864     (not (null (memq x *features*)))))
865
866 ;;; Given a list of keyword substitutions `(,OLD ,NEW), and a
867 ;;; &KEY-argument-list-style list of alternating keywords and
868 ;;; arbitrary values, return a new &KEY-argument-list-style list with
869 ;;; all substitutions applied to it.
870 ;;;
871 ;;; Note: If efficiency mattered, we could do less consing. (But if
872 ;;; efficiency mattered, why would we be using &KEY arguments at
873 ;;; all, much less renaming &KEY arguments?)
874 ;;;
875 ;;; KLUDGE: It would probably be good to get rid of this. -- WHN 19991201
876 (defun rename-key-args (rename-list key-args)
877   (declare (type list rename-list key-args))
878   ;; Walk through RENAME-LIST modifying RESULT as per each element in
879   ;; RENAME-LIST.
880   (do ((result (copy-list key-args))) ; may be modified below
881       ((null rename-list) result)
882     (destructuring-bind (old new) (pop rename-list)
883       ;; ANSI says &KEY arg names aren't necessarily KEYWORDs.
884       (declare (type symbol old new))
885       ;; Walk through RESULT renaming any OLD key argument to NEW.
886       (do ((in-result result (cddr in-result)))
887           ((null in-result))
888         (declare (type list in-result))
889         (when (eq (car in-result) old)
890           (setf (car in-result) new))))))
891
892 ;;; ANSI Common Lisp's READ-SEQUENCE function, unlike most of the
893 ;;; other ANSI input functions, is defined to communicate end of file
894 ;;; status with its return value, not by signalling. That is not the
895 ;;; behavior that we usually want. This function is a wrapper which
896 ;;; restores the behavior that we usually want, causing READ-SEQUENCE
897 ;;; to communicate end-of-file status by signalling.
898 (defun read-sequence-or-die (sequence stream &key start end)
899   ;; implementation using READ-SEQUENCE
900   #-no-ansi-read-sequence
901   (let ((read-end (read-sequence sequence
902                                  stream
903                                  :start start
904                                  :end end)))
905     (unless (= read-end end)
906       (error 'end-of-file :stream stream))
907     (values))
908   ;; workaround for broken READ-SEQUENCE
909   #+no-ansi-read-sequence
910   (progn
911     (aver (<= start end))
912     (let ((etype (stream-element-type stream)))
913     (cond ((equal etype '(unsigned-byte 8))
914            (do ((i start (1+ i)))
915                ((>= i end)
916                 (values))
917              (setf (aref sequence i)
918                    (read-byte stream))))
919           (t (error "unsupported element type ~S" etype))))))
920 \f
921 ;;;; utilities for two-VALUES predicates
922
923 (defmacro not/type (x)
924   (let ((val (gensym "VAL"))
925         (win (gensym "WIN")))
926     `(multiple-value-bind (,val ,win)
927          ,x
928        (if ,win
929            (values (not ,val) t)
930            (values nil nil)))))
931
932 (defmacro and/type (x y)
933   `(multiple-value-bind (val1 win1) ,x
934      (if (and (not val1) win1)
935          (values nil t)
936          (multiple-value-bind (val2 win2) ,y
937            (if (and val1 val2)
938                (values t t)
939                (values nil (and win2 (not val2))))))))
940
941 ;;; sort of like ANY and EVERY, except:
942 ;;;   * We handle two-VALUES predicate functions, as SUBTYPEP does.
943 ;;;     (And if the result is uncertain, then we return (VALUES NIL NIL),
944 ;;;     as SUBTYPEP does.)
945 ;;;   * THING is just an atom, and we apply OP (an arity-2 function)
946 ;;;     successively to THING and each element of LIST.
947 (defun any/type (op thing list)
948   (declare (type function op))
949   (let ((certain? t))
950     (dolist (i list (values nil certain?))
951       (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
952         (if sub-certain?
953             (when sub-value (return (values t t)))
954             (setf certain? nil))))))
955 (defun every/type (op thing list)
956   (declare (type function op))
957   (let ((certain? t))
958     (dolist (i list (if certain? (values t t) (values nil nil)))
959       (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
960         (if sub-certain?
961             (unless sub-value (return (values nil t)))
962             (setf certain? nil))))))
963 \f
964 ;;;; DEFPRINTER
965
966 ;;; These functions are called by the expansion of the DEFPRINTER
967 ;;; macro to do the actual printing.
968 (declaim (ftype (function (symbol t stream) (values))
969                 defprinter-prin1 defprinter-princ))
970 (defun defprinter-prin1 (name value stream)
971   (defprinter-prinx #'prin1 name value stream))
972 (defun defprinter-princ (name value stream)
973   (defprinter-prinx #'princ name value stream))
974 (defun defprinter-prinx (prinx name value stream)
975   (declare (type function prinx))
976   (when *print-pretty*
977     (pprint-newline :linear stream))
978   (format stream ":~A " name)
979   (funcall prinx value stream)
980   (values))
981 (defun defprinter-print-space (stream)
982   (write-char #\space stream))
983
984 ;;; Define some kind of reasonable PRINT-OBJECT method for a
985 ;;; STRUCTURE-OBJECT class.
986 ;;;
987 ;;; NAME is the name of the structure class, and CONC-NAME is the same
988 ;;; as in DEFSTRUCT.
989 ;;;
990 ;;; The SLOT-DESCS describe how each slot should be printed. Each
991 ;;; SLOT-DESC can be a slot name, indicating that the slot should
992 ;;; simply be printed. A SLOT-DESC may also be a list of a slot name
993 ;;; and other stuff. The other stuff is composed of keywords followed
994 ;;; by expressions. The expressions are evaluated with the variable
995 ;;; which is the slot name bound to the value of the slot. These
996 ;;; keywords are defined:
997 ;;;
998 ;;; :PRIN1    Print the value of the expression instead of the slot value.
999 ;;; :PRINC    Like :PRIN1, only PRINC the value
1000 ;;; :TEST     Only print something if the test is true.
1001 ;;;
1002 ;;; If no printing thing is specified then the slot value is printed
1003 ;;; as if by PRIN1.
1004 ;;;
1005 ;;; The structure being printed is bound to STRUCTURE and the stream
1006 ;;; is bound to STREAM.
1007 (defmacro defprinter ((name
1008                        &key
1009                        (conc-name (concatenate 'simple-string
1010                                                (symbol-name name)
1011                                                "-"))
1012                        identity)
1013                       &rest slot-descs)
1014   (let ((first? t)
1015         maybe-print-space
1016         (reversed-prints nil)
1017         (stream (gensym "STREAM")))
1018     (flet ((sref (slot-name)
1019              `(,(symbolicate conc-name slot-name) structure)))
1020       (dolist (slot-desc slot-descs)
1021         (if first?
1022             (setf maybe-print-space nil
1023                   first? nil)
1024             (setf maybe-print-space `(defprinter-print-space ,stream)))
1025         (cond ((atom slot-desc)
1026                (push maybe-print-space reversed-prints)
1027                (push `(defprinter-prin1 ',slot-desc ,(sref slot-desc) ,stream)
1028                      reversed-prints))
1029               (t
1030                (let ((sname (first slot-desc))
1031                      (test t))
1032                  (collect ((stuff))
1033                    (do ((option (rest slot-desc) (cddr option)))
1034                        ((null option)
1035                         (push `(let ((,sname ,(sref sname)))
1036                                  (when ,test
1037                                    ,maybe-print-space
1038                                    ,@(or (stuff)
1039                                          `((defprinter-prin1
1040                                              ',sname ,sname ,stream)))))
1041                               reversed-prints))
1042                      (case (first option)
1043                        (:prin1
1044                         (stuff `(defprinter-prin1
1045                                   ',sname ,(second option) ,stream)))
1046                        (:princ
1047                         (stuff `(defprinter-princ
1048                                   ',sname ,(second option) ,stream)))
1049                        (:test (setq test (second option)))
1050                        (t
1051                         (error "bad option: ~S" (first option)))))))))))
1052     `(def!method print-object ((structure ,name) ,stream)
1053        (pprint-logical-block (,stream nil)
1054          (print-unreadable-object (structure
1055                                    ,stream
1056                                    :type t
1057                                    :identity ,identity)
1058            ,@(nreverse reversed-prints))))))
1059 \f
1060 ;;;; etc.
1061
1062 ;;; Given a pathname, return a corresponding physical pathname.
1063 (defun physicalize-pathname (possibly-logical-pathname)
1064   (if (typep possibly-logical-pathname 'logical-pathname)
1065       (translate-logical-pathname possibly-logical-pathname)
1066       possibly-logical-pathname))
1067
1068 (defun deprecation-warning (bad-name &optional good-name)
1069   (warn "using deprecated ~S~@[, should use ~S instead~]"
1070         bad-name
1071         good-name))
1072
1073 ;;; Anaphoric macros
1074 (defmacro awhen (test &body body)
1075   `(let ((it ,test))
1076      (when it ,@body)))
1077
1078 (defmacro acond (&rest clauses)
1079   (if (null clauses)
1080       `()
1081       (destructuring-bind ((test &body body) &rest rest) clauses
1082         (once-only ((test test))
1083           `(if ,test
1084                (let ((it ,test)) (declare (ignorable it)),@body)
1085                (acond ,@rest))))))
1086
1087 \f
1088 ;;; Delayed evaluation
1089 (defmacro delay (form)
1090   `(cons nil (lambda () ,form)))
1091
1092 (defun force (promise)
1093   (cond ((not (consp promise)) promise)
1094         ((car promise) (cdr promise))
1095         (t (setf (car promise) t
1096                  (cdr promise) (funcall (cdr promise))))))
1097
1098 (defun promise-ready-p (promise)
1099   (or (not (consp promise))
1100       (car promise)))