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