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