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