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