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