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