0.7.12.31:
[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            (or (eq (car name) 'setf)
630                (eq (car name) 'sb!pcl::class-predicate))
631            (consp (cdr name))
632            (symbolp (cadr name))
633            (null (cddr name)))))
634
635 ;;; Signal an error unless NAME is a legal function name.
636 (defun legal-fun-name-or-type-error (name)
637   (unless (legal-fun-name-p name)
638     (error 'simple-type-error
639            :datum name
640            :expected-type '(or symbol list)
641            :format-control "invalid function name: ~S"
642            :format-arguments (list name))))
643
644 ;;; Given a function name, return the symbol embedded in it.
645 ;;;
646 ;;; The ordinary use for this operator (and the motivation for the
647 ;;; name of this operator) is to convert from a function name to the
648 ;;; name of the BLOCK which encloses its body.
649 ;;;
650 ;;; Occasionally the operator is useful elsewhere, where the operator
651 ;;; name is less mnemonic. (Maybe it should be changed?)
652 (declaim (ftype (function ((or symbol cons)) symbol) fun-name-block-name))
653 (defun fun-name-block-name (fun-name)
654   (cond ((symbolp fun-name)
655          fun-name)
656         ((and (consp fun-name)
657               (legal-fun-name-p fun-name))
658          (second fun-name))
659         (t
660          (error "not legal as a function name: ~S" fun-name))))
661
662 (defun looks-like-name-of-special-var-p (x)
663   (and (symbolp x)
664        (let ((name (symbol-name x)))
665          (and (> (length name) 2) ; to exclude '* and '**
666               (char= #\* (aref name 0))
667               (char= #\* (aref name (1- (length name))))))))
668
669 ;;; Some symbols are defined by ANSI to be self-evaluating. Return
670 ;;; non-NIL for such symbols (and make the non-NIL value a traditional
671 ;;; message, for use in contexts where the user asks us to change such
672 ;;; a symbol).
673 (defun symbol-self-evaluating-p (symbol)
674   (declare (type symbol symbol))
675   (cond ((eq symbol t)
676          "Veritas aeterna. (can't change T)")
677         ((eq symbol nil)
678          "Nihil ex nihil. (can't change NIL)")
679         ((keywordp symbol)
680          "Keyword values can't be changed.")
681         (t
682          nil)))
683
684 ;;; This function is to be called just before a change which would
685 ;;; affect the symbol value. (We don't absolutely have to call this
686 ;;; function before such changes, since such changes are given as
687 ;;; undefined behavior. In particular, we don't if the runtime cost
688 ;;; would be annoying. But otherwise it's nice to do so.)
689 (defun about-to-modify-symbol-value (symbol)
690   (declare (type symbol symbol))
691   (let ((reason (symbol-self-evaluating-p symbol)))
692     (when reason
693       (error reason)))
694   ;; (Note: Just because a value is CONSTANTP is not a good enough
695   ;; reason to complain here, because we want DEFCONSTANT to be able
696   ;; to use this function, and it's legal to DEFCONSTANT a constant as
697   ;; long as the new value is EQL to the old value.)
698   (values))
699
700
701 ;;; If COLD-FSET occurs not at top level, just treat it as an ordinary
702 ;;; assignment instead of doing cold static linking. That way things like
703 ;;;   (FLET ((FROB (X) ..))
704 ;;;     (DEFUN FOO (X Y) (FROB X) ..)
705 ;;;     (DEFUN BAR (Z) (AND (FROB X) ..)))
706 ;;; can still "work" for cold init: they don't do magical static
707 ;;; linking the way that true toplevel DEFUNs do, but at least they do
708 ;;; the linking eventually, so as long as #'FOO and #'BAR aren't
709 ;;; needed until "cold toplevel forms" have executed, it's OK.
710 (defmacro cold-fset (name lambda)
711   (style-warn 
712    "~@<COLD-FSET ~S not cross-compiled at top level: demoting to ~
713 (SETF FDEFINITION)~:@>"
714    name)
715   ;; We convert the LAMBDA expression to the corresponding NAMED-LAMBDA
716   ;; expression so that the compiler can use NAME in debug names etc. 
717   (destructuring-bind (lambda-symbol &rest lambda-rest) lambda
718     (assert (eql lambda-symbol 'lambda)) ; else dunno how to do conversion
719     `(setf (fdefinition ',name)
720            (named-lambda ,name ,@lambda-rest))))
721 \f
722 ;;;; ONCE-ONLY
723 ;;;;
724 ;;;; "The macro ONCE-ONLY has been around for a long time on various
725 ;;;; systems [..] if you can understand how to write and when to use
726 ;;;; ONCE-ONLY, then you truly understand macro." -- Peter Norvig,
727 ;;;; _Paradigms of Artificial Intelligence Programming: Case Studies
728 ;;;; in Common Lisp_, p. 853
729
730 ;;; ONCE-ONLY is a utility useful in writing source transforms and
731 ;;; macros. It provides a concise way to wrap a LET around some code
732 ;;; to ensure that some forms are only evaluated once.
733 ;;;
734 ;;; Create a LET* which evaluates each value expression, binding a
735 ;;; temporary variable to the result, and wrapping the LET* around the
736 ;;; result of the evaluation of BODY. Within the body, each VAR is
737 ;;; bound to the corresponding temporary variable.
738 (defmacro once-only (specs &body body)
739   (named-let frob ((specs specs)
740                    (body body))
741     (if (null specs)
742         `(progn ,@body)
743         (let ((spec (first specs)))
744           ;; FIXME: should just be DESTRUCTURING-BIND of SPEC
745           (unless (proper-list-of-length-p spec 2)
746             (error "malformed ONCE-ONLY binding spec: ~S" spec))
747           (let* ((name (first spec))
748                  (exp-temp (gensym (symbol-name name))))
749             `(let ((,exp-temp ,(second spec))
750                    (,name (gensym "ONCE-ONLY-")))
751                `(let ((,,name ,,exp-temp))
752                   ,,(frob (rest specs) body))))))))
753 \f
754 ;;;; various error-checking utilities
755
756 ;;; This function can be used as the default value for keyword
757 ;;; arguments that must be always be supplied. Since it is known by
758 ;;; the compiler to never return, it will avoid any compile-time type
759 ;;; warnings that would result from a default value inconsistent with
760 ;;; the declared type. When this function is called, it signals an
761 ;;; error indicating that a required &KEY argument was not supplied.
762 ;;; This function is also useful for DEFSTRUCT slot defaults
763 ;;; corresponding to required arguments.
764 (declaim (ftype (function () nil) missing-arg))
765 (defun missing-arg ()
766   #!+sb-doc
767   (/show0 "entering MISSING-ARG")
768   (error "A required &KEY or &OPTIONAL argument was not supplied."))
769
770 ;;; like CL:ASSERT and CL:CHECK-TYPE, but lighter-weight
771 ;;;
772 ;;; (As of sbcl-0.6.11.20, we were using some 400 calls to CL:ASSERT.
773 ;;; The CL:ASSERT restarts and whatnot expand into a significant
774 ;;; amount of code when you multiply them by 400, so replacing them
775 ;;; with this should reduce the size of the system by enough to be
776 ;;; worthwhile. ENFORCE-TYPE is much less common, but might still be
777 ;;; worthwhile, and since I don't really like CERROR stuff deep in the
778 ;;; guts of complex systems anyway, I replaced it too.)
779 (defmacro aver (expr)
780   `(unless ,expr
781      (%failed-aver ,(format nil "~A" expr))))
782
783 (defun %failed-aver (expr-as-string)
784   (bug "~@<failed AVER: ~2I~_~S~:>" expr-as-string))
785
786 ;;; We need a definition of BUG here for the host compiler to be able
787 ;;; to deal with BUGs in sbcl. This should never affect an end-user,
788 ;;; who will pick up the definition that signals a CONDITION of
789 ;;; condition-class BUG; however, this is not defined on the host
790 ;;; lisp, but for the target. SBCL developers sometimes trigger BUGs
791 ;;; in their efforts, and it is useful to get the details of the BUG
792 ;;; rather than an undefined function error. - CSR, 2002-04-12
793 #+sb-xc-host
794 (defun bug (format-control &rest format-arguments)
795   (error 'simple-error
796          :format-control "~@<  ~? ~:@_~?~:>"
797          :format-arguments `(,format-control
798                              ,format-arguments
799                              "~@<If you see this and are an SBCL ~
800 developer, then it is probable that you have made a change to the ~
801 system that has broken the ability for SBCL to compile, usually by ~
802 removing an assumed invariant of the system, but sometimes by making ~
803 an averrance that is violated (check your code!). If you are a user, ~
804 please submit a bug report to the developers' mailing list, details of ~
805 which can be found at <http://sbcl.sourceforge.net/>.~:@>"
806                              ())))
807
808 (defmacro enforce-type (value type)
809   (once-only ((value value))
810     `(unless (typep ,value ',type)
811        (%failed-enforce-type ,value ',type))))
812
813 (defun %failed-enforce-type (value type)
814   (error 'simple-type-error ; maybe should be TYPE-BUG, subclass of BUG?
815          :value value
816          :expected-type type
817          :format-string "~@<~S ~_is not a ~_~S~:>"
818          :format-arguments (list value type)))
819 \f
820 ;;; Return a list of N gensyms. (This is a common suboperation in
821 ;;; macros and other code-manipulating code.)
822 (declaim (ftype (function (index) list) make-gensym-list))
823 (defun make-gensym-list (n)
824   (loop repeat n collect (gensym)))
825
826 ;;; Return a function like FUN, but expecting its (two) arguments in
827 ;;; the opposite order that FUN does.
828 (declaim (inline swapped-args-fun))
829 (defun swapped-args-fun (fun)
830   (declare (type function fun))
831   (lambda (x y)
832     (funcall fun y x)))
833
834 ;;; Return the numeric value of a type bound, i.e. an interval bound
835 ;;; more or less in the format of bounds in ANSI's type specifiers,
836 ;;; where a bare numeric value is a closed bound and a list of a
837 ;;; single numeric value is an open bound.
838 ;;;
839 ;;; The "more or less" bit is that the no-bound-at-all case is
840 ;;; represented by NIL (not by * as in ANSI type specifiers); and in
841 ;;; this case we return NIL.
842 (defun type-bound-number (x)
843   (if (consp x)
844       (destructuring-bind (result) x result)
845       x))
846
847 ;;; some commonly-occuring CONSTANTLY forms
848 (macrolet ((def-constantly-fun (name constant-expr)
849              `(setf (symbol-function ',name)
850                     (constantly ,constant-expr))))
851   (def-constantly-fun constantly-t t)
852   (def-constantly-fun constantly-nil nil)
853   (def-constantly-fun constantly-0 0))
854
855 ;;; If X is an atom, see whether it is present in *FEATURES*. Also
856 ;;; handle arbitrary combinations of atoms using NOT, AND, OR.
857 (defun featurep (x)
858   (if (consp x)
859     (case (car x)
860       ((:not not)
861        (if (cddr x)
862          (error "too many subexpressions in feature expression: ~S" x)
863          (not (featurep (cadr x)))))
864       ((:and and) (every #'featurep (cdr x)))
865       ((:or or) (some #'featurep (cdr x)))
866       (t
867        (error "unknown operator in feature expression: ~S." x)))
868     (not (null (memq x *features*)))))
869
870 ;;; Given a list of keyword substitutions `(,OLD ,NEW), and a
871 ;;; &KEY-argument-list-style list of alternating keywords and
872 ;;; arbitrary values, return a new &KEY-argument-list-style list with
873 ;;; all substitutions applied to it.
874 ;;;
875 ;;; Note: If efficiency mattered, we could do less consing. (But if
876 ;;; efficiency mattered, why would we be using &KEY arguments at
877 ;;; all, much less renaming &KEY arguments?)
878 ;;;
879 ;;; KLUDGE: It would probably be good to get rid of this. -- WHN 19991201
880 (defun rename-key-args (rename-list key-args)
881   (declare (type list rename-list key-args))
882   ;; Walk through RENAME-LIST modifying RESULT as per each element in
883   ;; RENAME-LIST.
884   (do ((result (copy-list key-args))) ; may be modified below
885       ((null rename-list) result)
886     (destructuring-bind (old new) (pop rename-list)
887       ;; ANSI says &KEY arg names aren't necessarily KEYWORDs.
888       (declare (type symbol old new))
889       ;; Walk through RESULT renaming any OLD key argument to NEW.
890       (do ((in-result result (cddr in-result)))
891           ((null in-result))
892         (declare (type list in-result))
893         (when (eq (car in-result) old)
894           (setf (car in-result) new))))))
895
896 ;;; ANSI Common Lisp's READ-SEQUENCE function, unlike most of the
897 ;;; other ANSI input functions, is defined to communicate end of file
898 ;;; status with its return value, not by signalling. That is not the
899 ;;; behavior that we usually want. This function is a wrapper which
900 ;;; restores the behavior that we usually want, causing READ-SEQUENCE
901 ;;; to communicate end-of-file status by signalling.
902 (defun read-sequence-or-die (sequence stream &key start end)
903   ;; implementation using READ-SEQUENCE
904   #-no-ansi-read-sequence
905   (let ((read-end (read-sequence sequence
906                                  stream
907                                  :start start
908                                  :end end)))
909     (unless (= read-end end)
910       (error 'end-of-file :stream stream))
911     (values))
912   ;; workaround for broken READ-SEQUENCE
913   #+no-ansi-read-sequence
914   (progn
915     (aver (<= start end))
916     (let ((etype (stream-element-type stream)))
917     (cond ((equal etype '(unsigned-byte 8))
918            (do ((i start (1+ i)))
919                ((>= i end)
920                 (values))
921              (setf (aref sequence i)
922                    (read-byte stream))))
923           (t (error "unsupported element type ~S" etype))))))
924 \f
925 ;;;; utilities for two-VALUES predicates
926
927 ;;; sort of like ANY and EVERY, except:
928 ;;;   * We handle two-VALUES predicate functions, as SUBTYPEP does.
929 ;;;     (And if the result is uncertain, then we return (VALUES NIL NIL),
930 ;;;     as SUBTYPEP does.)
931 ;;;   * THING is just an atom, and we apply OP (an arity-2 function)
932 ;;;     successively to THING and each element of LIST.
933 (defun any/type (op thing list)
934   (declare (type function op))
935   (let ((certain? t))
936     (dolist (i list (values nil certain?))
937       (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
938         (if sub-certain?
939             (when sub-value (return (values t t)))
940             (setf certain? nil))))))
941 (defun every/type (op thing list)
942   (declare (type function op))
943   (let ((certain? t))
944     (dolist (i list (if certain? (values t t) (values nil nil)))
945       (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
946         (if sub-certain?
947             (unless sub-value (return (values nil t)))
948             (setf certain? nil))))))
949 \f
950 ;;;; DEFPRINTER
951
952 ;;; These functions are called by the expansion of the DEFPRINTER
953 ;;; macro to do the actual printing.
954 (declaim (ftype (function (symbol t stream) (values))
955                 defprinter-prin1 defprinter-princ))
956 (defun defprinter-prin1 (name value stream)
957   (defprinter-prinx #'prin1 name value stream))
958 (defun defprinter-princ (name value stream)
959   (defprinter-prinx #'princ name value stream))
960 (defun defprinter-prinx (prinx name value stream)
961   (declare (type function prinx))
962   (when *print-pretty*
963     (pprint-newline :linear stream))
964   (format stream ":~A " name)
965   (funcall prinx value stream)
966   (values))
967 (defun defprinter-print-space (stream)
968   (write-char #\space stream))
969
970 ;;; Define some kind of reasonable PRINT-OBJECT method for a
971 ;;; STRUCTURE-OBJECT class.
972 ;;;
973 ;;; NAME is the name of the structure class, and CONC-NAME is the same
974 ;;; as in DEFSTRUCT.
975 ;;;
976 ;;; The SLOT-DESCS describe how each slot should be printed. Each
977 ;;; SLOT-DESC can be a slot name, indicating that the slot should
978 ;;; simply be printed. A SLOT-DESC may also be a list of a slot name
979 ;;; and other stuff. The other stuff is composed of keywords followed
980 ;;; by expressions. The expressions are evaluated with the variable
981 ;;; which is the slot name bound to the value of the slot. These
982 ;;; keywords are defined:
983 ;;;
984 ;;; :PRIN1    Print the value of the expression instead of the slot value.
985 ;;; :PRINC    Like :PRIN1, only PRINC the value
986 ;;; :TEST     Only print something if the test is true.
987 ;;;
988 ;;; If no printing thing is specified then the slot value is printed
989 ;;; as if by PRIN1.
990 ;;;
991 ;;; The structure being printed is bound to STRUCTURE and the stream
992 ;;; is bound to STREAM.
993 (defmacro defprinter ((name
994                        &key
995                        (conc-name (concatenate 'simple-string
996                                                (symbol-name name)
997                                                "-"))
998                        identity)
999                       &rest slot-descs)
1000   (let ((first? t)
1001         maybe-print-space
1002         (reversed-prints nil)
1003         (stream (gensym "STREAM")))
1004     (flet ((sref (slot-name)
1005              `(,(symbolicate conc-name slot-name) structure)))
1006       (dolist (slot-desc slot-descs)
1007         (if first?
1008             (setf maybe-print-space nil
1009                   first? nil)
1010             (setf maybe-print-space `(defprinter-print-space ,stream)))
1011         (cond ((atom slot-desc)
1012                (push maybe-print-space reversed-prints)
1013                (push `(defprinter-prin1 ',slot-desc ,(sref slot-desc) ,stream)
1014                      reversed-prints))
1015               (t
1016                (let ((sname (first slot-desc))
1017                      (test t))
1018                  (collect ((stuff))
1019                    (do ((option (rest slot-desc) (cddr option)))
1020                        ((null option)
1021                         (push `(let ((,sname ,(sref sname)))
1022                                  (when ,test
1023                                    ,maybe-print-space
1024                                    ,@(or (stuff)
1025                                          `((defprinter-prin1
1026                                              ',sname ,sname ,stream)))))
1027                               reversed-prints))
1028                      (case (first option)
1029                        (:prin1
1030                         (stuff `(defprinter-prin1
1031                                   ',sname ,(second option) ,stream)))
1032                        (:princ
1033                         (stuff `(defprinter-princ
1034                                   ',sname ,(second option) ,stream)))
1035                        (:test (setq test (second option)))
1036                        (t
1037                         (error "bad option: ~S" (first option)))))))))))
1038     `(def!method print-object ((structure ,name) ,stream)
1039        (pprint-logical-block (,stream nil)
1040          (print-unreadable-object (structure
1041                                    ,stream
1042                                    :type t
1043                                    :identity ,identity)
1044            ,@(nreverse reversed-prints))))))
1045 \f
1046 ;;;; etc.
1047
1048 ;;; Given a pathname, return a corresponding physical pathname.
1049 (defun physicalize-pathname (possibly-logical-pathname)
1050   (if (typep possibly-logical-pathname 'logical-pathname)
1051       (translate-logical-pathname possibly-logical-pathname)
1052       possibly-logical-pathname))
1053
1054 (defun deprecation-warning (bad-name &optional good-name)
1055   (warn "using deprecated ~S~@[, should use ~S instead~]"
1056         bad-name
1057         good-name))
1058
1059 ;;; Anaphoric macros
1060 (defmacro awhen (test &body body)
1061   `(let ((it ,test))
1062      (when it ,@body)))
1063
1064 (defmacro acond (&rest clauses)
1065   (if (null clauses)
1066       `()
1067       (destructuring-bind ((test &body body) &rest rest) clauses
1068         (once-only ((test test))
1069           `(if ,test
1070                (let ((it ,test)) (declare (ignorable it)),@body)
1071                (acond ,@rest))))))