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