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