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