0.7.1.3:
[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 ~W."
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 instead of doing cold static linking. 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   ;; We convert the LAMBDA expression to the corresponding NAMED-LAMBDA
649   ;; expression so that the compiler can use NAME in debug names etc. 
650   (destructuring-bind (lambda-symbol &rest lambda-rest) lambda
651     (assert (eql lambda-symbol 'lambda)) ; else dunno how to do conversion
652     `(setf (fdefinition ',name)
653            (named-lambda ,name ,@lambda-rest))))
654 \f
655 ;;;; ONCE-ONLY
656 ;;;;
657 ;;;; "The macro ONCE-ONLY has been around for a long time on various
658 ;;;; systems [..] if you can understand how to write and when to use
659 ;;;; ONCE-ONLY, then you truly understand macro." -- Peter Norvig,
660 ;;;; _Paradigms of Artificial Intelligence Programming: Case Studies
661 ;;;; in Common Lisp_, p. 853
662
663 ;;; ONCE-ONLY is a utility useful in writing source transforms and
664 ;;; macros. It provides a concise way to wrap a LET around some code
665 ;;; to ensure that some forms are only evaluated once.
666 ;;;
667 ;;; Create a LET* which evaluates each value expression, binding a
668 ;;; temporary variable to the result, and wrapping the LET* around the
669 ;;; result of the evaluation of BODY. Within the body, each VAR is
670 ;;; bound to the corresponding temporary variable.
671 (defmacro once-only (specs &body body)
672   (named-let frob ((specs specs)
673                    (body body))
674     (if (null specs)
675         `(progn ,@body)
676         (let ((spec (first specs)))
677           ;; FIXME: should just be DESTRUCTURING-BIND of SPEC
678           (unless (proper-list-of-length-p spec 2)
679             (error "malformed ONCE-ONLY binding spec: ~S" spec))
680           (let* ((name (first spec))
681                  (exp-temp (gensym (symbol-name name))))
682             `(let ((,exp-temp ,(second spec))
683                    (,name (gensym "ONCE-ONLY-")))
684                `(let ((,,name ,,exp-temp))
685                   ,,(frob (rest specs) body))))))))
686 \f
687 ;;;; various error-checking utilities
688
689 ;;; This function can be used as the default value for keyword
690 ;;; arguments that must be always be supplied. Since it is known by
691 ;;; the compiler to never return, it will avoid any compile-time type
692 ;;; warnings that would result from a default value inconsistent with
693 ;;; the declared type. When this function is called, it signals an
694 ;;; error indicating that a required &KEY argument was not supplied.
695 ;;; This function is also useful for DEFSTRUCT slot defaults
696 ;;; corresponding to required arguments.
697 (declaim (ftype (function () nil) missing-arg))
698 (defun missing-arg ()
699   #!+sb-doc
700   (/show0 "entering MISSING-ARG")
701   (error "A required &KEY or &OPTIONAL argument was not supplied."))
702
703 ;;; like CL:ASSERT and CL:CHECK-TYPE, but lighter-weight
704 ;;;
705 ;;; (As of sbcl-0.6.11.20, we were using some 400 calls to CL:ASSERT.
706 ;;; The CL:ASSERT restarts and whatnot expand into a significant
707 ;;; amount of code when you multiply them by 400, so replacing them
708 ;;; with this should reduce the size of the system by enough to be
709 ;;; worthwhile. ENFORCE-TYPE is much less common, but might still be
710 ;;; worthwhile, and since I don't really like CERROR stuff deep in the
711 ;;; guts of complex systems anyway, I replaced it too.)
712 (defmacro aver (expr)
713   `(unless ,expr
714      (%failed-aver ,(format nil "~A" expr))))
715 (defun %failed-aver (expr-as-string)
716   (bug "~@<failed AVER: ~2I~_~S~:>" expr-as-string))
717 (defmacro enforce-type (value type)
718   (once-only ((value value))
719     `(unless (typep ,value ',type)
720        (%failed-enforce-type ,value ',type))))
721 (defun %failed-enforce-type (value type)
722   (error 'simple-type-error ; maybe should be TYPE-BUG, subclass of BUG?
723          :value value
724          :expected-type type
725          :format-string "~@<~S ~_is not a ~_~S~:>"
726          :format-arguments (list value type)))
727 \f
728 ;;; Return a list of N gensyms. (This is a common suboperation in
729 ;;; macros and other code-manipulating code.)
730 (declaim (ftype (function (index) list) make-gensym-list))
731 (defun make-gensym-list (n)
732   (loop repeat n collect (gensym)))
733
734 ;;; Return a function like FUN, but expecting its (two) arguments in
735 ;;; the opposite order that FUN does.
736 (declaim (inline swapped-args-fun))
737 (defun swapped-args-fun (fun)
738   (declare (type function fun))
739   (lambda (x y)
740     (funcall fun y x)))
741
742 ;;; Return the numeric value of a type bound, i.e. an interval bound
743 ;;; more or less in the format of bounds in ANSI's type specifiers,
744 ;;; where a bare numeric value is a closed bound and a list of a
745 ;;; single numeric value is an open bound.
746 ;;;
747 ;;; The "more or less" bit is that the no-bound-at-all case is
748 ;;; represented by NIL (not by * as in ANSI type specifiers); and in
749 ;;; this case we return NIL.
750 (defun type-bound-number (x)
751   (if (consp x)
752       (destructuring-bind (result) x result)
753       x))
754
755 ;;; some commonly-occuring CONSTANTLY forms
756 (macrolet ((def-constantly-fun (name constant-expr)
757              `(setf (symbol-function ',name)
758                     (constantly ,constant-expr))))
759   (def-constantly-fun constantly-t t)
760   (def-constantly-fun constantly-nil nil)
761   (def-constantly-fun constantly-0 0))
762
763 ;;; If X is an atom, see whether it is present in *FEATURES*. Also
764 ;;; handle arbitrary combinations of atoms using NOT, AND, OR.
765 (defun featurep (x)
766   (if (consp x)
767     (case (car x)
768       ((:not not)
769        (if (cddr x)
770          (error "too many subexpressions in feature expression: ~S" x)
771          (not (featurep (cadr x)))))
772       ((:and and) (every #'featurep (cdr x)))
773       ((:or or) (some #'featurep (cdr x)))
774       (t
775        (error "unknown operator in feature expression: ~S." x)))
776     (not (null (memq x *features*)))))
777
778 ;;; Given a list of keyword substitutions `(,OLD ,NEW), and a
779 ;;; &KEY-argument-list-style list of alternating keywords and
780 ;;; arbitrary values, return a new &KEY-argument-list-style list with
781 ;;; all substitutions applied to it.
782 ;;;
783 ;;; Note: If efficiency mattered, we could do less consing. (But if
784 ;;; efficiency mattered, why would we be using &KEY arguments at
785 ;;; all, much less renaming &KEY arguments?)
786 ;;;
787 ;;; KLUDGE: It would probably be good to get rid of this. -- WHN 19991201
788 (defun rename-key-args (rename-list key-args)
789   (declare (type list rename-list key-args))
790   ;; Walk through RENAME-LIST modifying RESULT as per each element in
791   ;; RENAME-LIST.
792   (do ((result (copy-list key-args))) ; may be modified below
793       ((null rename-list) result)
794     (destructuring-bind (old new) (pop rename-list)
795       ;; ANSI says &KEY arg names aren't necessarily KEYWORDs.
796       (declare (type symbol old new))
797       ;; Walk through RESULT renaming any OLD key argument to NEW.
798       (do ((in-result result (cddr in-result)))
799           ((null in-result))
800         (declare (type list in-result))
801         (when (eq (car in-result) old)
802           (setf (car in-result) new))))))
803
804 ;;; ANSI Common Lisp's READ-SEQUENCE function, unlike most of the
805 ;;; other ANSI input functions, is defined to communicate end of file
806 ;;; status with its return value, not by signalling. That is not the
807 ;;; behavior that we usually want. This function is a wrapper which
808 ;;; restores the behavior that we usually want, causing READ-SEQUENCE
809 ;;; to communicate end-of-file status by signalling.
810 (defun read-sequence-or-die (sequence stream &key start end)
811   ;; implementation using READ-SEQUENCE
812   #-no-ansi-read-sequence
813   (let ((read-end (read-sequence sequence
814                                  stream
815                                  :start start
816                                  :end end)))
817     (unless (= read-end end)
818       (error 'end-of-file :stream stream))
819     (values))
820   ;; workaround for broken READ-SEQUENCE
821   #+no-ansi-read-sequence
822   (progn
823     (aver (<= start end))
824     (let ((etype (stream-element-type stream)))
825     (cond ((equal etype '(unsigned-byte 8))
826            (do ((i start (1+ i)))
827                ((>= i end)
828                 (values))
829              (setf (aref sequence i)
830                    (read-byte stream))))
831           (t (error "unsupported element type ~S" etype))))))
832 \f
833 ;;;; utilities for two-VALUES predicates
834
835 ;;; sort of like ANY and EVERY, except:
836 ;;;   * We handle two-VALUES predicate functions, as SUBTYPEP does.
837 ;;;     (And if the result is uncertain, then we return (VALUES NIL NIL),
838 ;;;     as SUBTYPEP does.)
839 ;;;   * THING is just an atom, and we apply OP (an arity-2 function)
840 ;;;     successively to THING and each element of LIST.
841 (defun any/type (op thing list)
842   (declare (type function op))
843   (let ((certain? t))
844     (dolist (i list (values nil certain?))
845       (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
846         (if sub-certain?
847             (when sub-value (return (values t t)))
848             (setf certain? nil))))))
849 (defun every/type (op thing list)
850   (declare (type function op))
851   (let ((certain? t))
852     (dolist (i list (if certain? (values t t) (values nil nil)))
853       (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
854         (if sub-certain?
855             (unless sub-value (return (values nil t)))
856             (setf certain? nil))))))
857 \f
858 ;;;; DEFPRINTER
859
860 ;;; These functions are called by the expansion of the DEFPRINTER
861 ;;; macro to do the actual printing.
862 (declaim (ftype (function (symbol t stream) (values))
863                 defprinter-prin1 defprinter-princ))
864 (defun defprinter-prin1 (name value stream)
865   (defprinter-prinx #'prin1 name value stream))
866 (defun defprinter-princ (name value stream)
867   (defprinter-prinx #'princ name value stream))
868 (defun defprinter-prinx (prinx name value stream)
869   (declare (type function prinx))
870   (when *print-pretty*
871     (pprint-newline :linear stream))
872   (format stream ":~A " name)
873   (funcall prinx value stream)
874   (values))
875 (defun defprinter-print-space (stream)
876   (write-char #\space stream))
877
878 ;;; Define some kind of reasonable PRINT-OBJECT method for a
879 ;;; STRUCTURE-OBJECT class.
880 ;;;
881 ;;; NAME is the name of the structure class, and CONC-NAME is the same
882 ;;; as in DEFSTRUCT.
883 ;;;
884 ;;; The SLOT-DESCS describe how each slot should be printed. Each
885 ;;; SLOT-DESC can be a slot name, indicating that the slot should
886 ;;; simply be printed. A SLOT-DESC may also be a list of a slot name
887 ;;; and other stuff. The other stuff is composed of keywords followed
888 ;;; by expressions. The expressions are evaluated with the variable
889 ;;; which is the slot name bound to the value of the slot. These
890 ;;; keywords are defined:
891 ;;;
892 ;;; :PRIN1    Print the value of the expression instead of the slot value.
893 ;;; :PRINC    Like :PRIN1, only PRINC the value
894 ;;; :TEST     Only print something if the test is true.
895 ;;;
896 ;;; If no printing thing is specified then the slot value is printed
897 ;;; as if by PRIN1.
898 ;;;
899 ;;; The structure being printed is bound to STRUCTURE and the stream
900 ;;; is bound to STREAM.
901 (defmacro defprinter ((name
902                        &key
903                        (conc-name (concatenate 'simple-string
904                                                (symbol-name name)
905                                                "-"))
906                        identity)
907                       &rest slot-descs)
908   (let ((first? t)
909         maybe-print-space
910         (reversed-prints nil)
911         (stream (gensym "STREAM")))
912     (flet ((sref (slot-name)
913              `(,(symbolicate conc-name slot-name) structure)))
914       (dolist (slot-desc slot-descs)
915         (if first?
916             (setf maybe-print-space nil
917                   first? nil)
918             (setf maybe-print-space `(defprinter-print-space ,stream)))
919         (cond ((atom slot-desc)
920                (push maybe-print-space reversed-prints)
921                (push `(defprinter-prin1 ',slot-desc ,(sref slot-desc) ,stream)
922                      reversed-prints))
923               (t
924                (let ((sname (first slot-desc))
925                      (test t))
926                  (collect ((stuff))
927                    (do ((option (rest slot-desc) (cddr option)))
928                        ((null option)
929                         (push `(let ((,sname ,(sref sname)))
930                                  (when ,test
931                                    ,maybe-print-space
932                                    ,@(or (stuff)
933                                          `((defprinter-prin1
934                                              ',sname ,sname ,stream)))))
935                               reversed-prints))
936                      (case (first option)
937                        (:prin1
938                         (stuff `(defprinter-prin1
939                                   ',sname ,(second option) ,stream)))
940                        (:princ
941                         (stuff `(defprinter-princ
942                                   ',sname ,(second option) ,stream)))
943                        (:test (setq test (second option)))
944                        (t
945                         (error "bad option: ~S" (first option)))))))))))
946     `(def!method print-object ((structure ,name) ,stream)
947        (pprint-logical-block (,stream nil)
948          (print-unreadable-object (structure
949                                    ,stream
950                                    :type t
951                                    :identity ,identity)
952            ,@(nreverse reversed-prints))))))
953 \f
954 ;;;; etc.
955
956 ;;; Given a pathname, return a corresponding physical pathname.
957 (defun physicalize-pathname (possibly-logical-pathname)
958   (if (typep possibly-logical-pathname 'logical-pathname)
959       (translate-logical-pathname possibly-logical-pathname)
960       possibly-logical-pathname))
961
962 (defun deprecation-warning (bad-name &optional good-name)
963   (warn "using deprecated ~S~@[, should use ~S instead~]"
964         bad-name
965         good-name))