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