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