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