c36c1acf9faeba49ddb3dc7760e4498c86d8f164
[sbcl.git] / src / code / early-extensions.lisp
1 ;;;; This file contains definitions and declarations for the
2 ;;;; EXTENSIONS package which must be available at early cross-compile
3 ;;;; time, and perhaps also some things which might as well be built
4 ;;;; at cross-compile time even if they're not strictly needed, since
5 ;;;; that's harmless. Things which can't be built at cross-compile
6 ;;;; time (e.g. because they need machinery which only exists inside
7 ;;;; CMU CL's implementation of the LISP package) do not belong in
8 ;;;; this file.
9
10 ;;;; This software is part of the SBCL system. See the README file for
11 ;;;; more information.
12 ;;;;
13 ;;;; This software is derived from the CMU CL system, which was
14 ;;;; written at Carnegie Mellon University and released into the
15 ;;;; public domain. The software is in the public domain and is
16 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
17 ;;;; files for more information.
18
19 (in-package "SB!IMPL")
20
21 ;;; something not EQ to anything we might legitimately READ
22 (defparameter *eof-object* (make-symbol "EOF-OBJECT"))
23
24 ;;; a type used for indexing into arrays, and for related quantities
25 ;;; like lengths of lists
26 ;;;
27 ;;; It's intentionally limited to one less than the
28 ;;; ARRAY-DIMENSION-LIMIT for efficiency reasons, because in SBCL
29 ;;; ARRAY-DIMENSION-LIMIT is MOST-POSITIVE-FIXNUM, and staying below
30 ;;; that lets the system know it can increment a value of this type
31 ;;; without having to worry about using a bignum to represent the
32 ;;; result.
33 ;;;
34 ;;; (It should be safe to use ARRAY-DIMENSION-LIMIT as an exclusive
35 ;;; bound because ANSI specifies it as an exclusive bound.)
36 (def!type index () `(integer 0 (,sb!xc:array-dimension-limit)))
37
38 ;;; the default value used for initializing character data. The ANSI
39 ;;; spec says this is arbitrary. CMU CL used #\NULL, which we avoid
40 ;;; because it's not in the ANSI table of portable characters.
41 (defconstant default-init-char #\space)
42
43 ;;; CHAR-CODE values for ASCII characters which we care about but
44 ;;; which aren't defined in section "2.1.3 Standard Characters" of the
45 ;;; ANSI specification for Lisp
46 ;;;
47 ;;; KLUDGE: These are typically used in the idiom (CODE-CHAR
48 ;;; FOO-CHAR-CODE). I suspect that the current implementation is
49 ;;; expanding this idiom into a full call to CODE-CHAR, which is an
50 ;;; annoying overhead. I should check whether this is happening, and
51 ;;; if so, perhaps implement a DEFTRANSFORM or something to stop it.
52 ;;; (or just find a nicer way of expressing characters portably?) --
53 ;;; WHN 19990713
54 (defconstant bell-char-code 7)
55 (defconstant tab-char-code 9)
56 (defconstant form-feed-char-code 12)
57 (defconstant return-char-code 13)
58 (defconstant escape-char-code 27)
59 (defconstant rubout-char-code 127)
60 \f
61 ;;;; miscellaneous iteration extensions
62
63 (defmacro dovector ((elt vector &optional result) &rest forms)
64   #!+sb-doc
65   "just like DOLIST, but with one-dimensional arrays"
66   (let ((index (gensym))
67         (length (gensym))
68         (vec (gensym)))
69     `(let ((,vec ,vector))
70        (declare (type vector ,vec))
71        (do ((,index 0 (1+ ,index))
72             (,length (length ,vec)))
73            ((>= ,index ,length) ,result)
74          (let ((,elt (aref ,vec ,index)))
75            ,@forms)))))
76
77 (defmacro dohash ((key-var value-var table &optional result) &body body)
78   #!+sb-doc
79   "DOHASH (Key-Var Value-Var Table [Result]) Declaration* Form*
80    Iterate over the entries in a hash-table."
81   (multiple-value-bind (forms decls) (parse-body body nil)
82     (let ((gen (gensym))
83           (n-more (gensym)))
84       `(with-hash-table-iterator (,gen ,table)
85          (loop
86           (multiple-value-bind (,n-more ,key-var ,value-var) (,gen)
87             ,@decls
88             (unless ,n-more (return ,result))
89             ,@forms))))))
90 \f
91 ;;;; hash cache utility
92
93 (eval-when (:compile-toplevel :load-toplevel :execute)
94   (defvar *profile-hash-cache* nil))
95
96 ;;; a flag for whether it's too early in cold init to use caches so
97 ;;; that we have a better chance of recovering so that we have a
98 ;;; better chance of getting the system running so that we have a
99 ;;; better chance of diagnosing the problem which caused us to use the
100 ;;; caches too early
101 #!+sb-show
102 (defvar *hash-caches-initialized-p*)
103
104 ;;; :INIT-WRAPPER is set to COLD-INIT-FORMS in type system definitions
105 ;;; so that caches will be created before top-level forms run.
106 (defmacro define-hash-cache (name args &key hash-function hash-bits default
107                                   (init-wrapper 'progn)
108                                   (values 1))
109   #!+sb-doc
110   "DEFINE-HASH-CACHE Name ({(Arg-Name Test-Function)}*) {Key Value}*
111   Define a hash cache that associates some number of argument values to a
112   result value. The Test-Function paired with each Arg-Name is used to compare
113   the value for that arg in a cache entry with a supplied arg. The
114   Test-Function must not error when passed NIL as its first arg, but need not
115   return any particular value. Test-Function may be any thing that can be
116   placed in CAR position.
117
118   Name is used to define these functions:
119
120   <name>-CACHE-LOOKUP Arg*
121       See whether there is an entry for the specified Args in the cache. If
122       not present, the :DEFAULT keyword (default NIL) determines the result(s).
123
124   <name>-CACHE-ENTER Arg* Value*
125       Encache the association of the specified args with Value.
126
127   <name>-CACHE-CLEAR
128       Reinitialize the cache, invalidating all entries and allowing the
129       arguments and result values to be GC'd.
130
131   These other keywords are defined:
132
133   :HASH-BITS <n>
134       The size of the cache as a power of 2.
135
136   :HASH-FUNCTION function
137       Some thing that can be placed in CAR position which will compute a value
138       between 0 and (1- (expt 2 <hash-bits>)).
139
140   :VALUES <n>
141       The number of values cached.
142
143   :INIT-WRAPPER <name>
144       The code for initializing the cache is wrapped in a form with the
145       specified name. Default PROGN."
146
147   (let* ((var-name (symbolicate "*" name "-CACHE-VECTOR*"))
148          (nargs (length args))
149          (entry-size (+ nargs values))
150          (size (ash 1 hash-bits))
151          (total-size (* entry-size size))
152          (default-values (if (and (consp default) (eq (car default) 'values))
153                              (cdr default)
154                              (list default)))
155          (n-index (gensym))
156          (n-cache (gensym)))
157
158     (unless (= (length default-values) values)
159       (error "The number of default values ~S differs from :VALUES ~D."
160              default values))
161
162     (collect ((inlines)
163               (forms)
164               (inits)
165               (tests)
166               (sets)
167               (arg-vars)
168               (values-indices)
169               (values-names))
170       (dotimes (i values)
171         (values-indices `(+ ,n-index ,(+ nargs i)))
172         (values-names (gensym)))
173       (let ((n 0))
174         (dolist (arg args)
175           (unless (= (length arg) 2)
176             (error "bad argument spec: ~S" arg))
177           (let ((arg-name (first arg))
178                 (test (second arg)))
179             (arg-vars arg-name)
180             (tests `(,test (svref ,n-cache (+ ,n-index ,n)) ,arg-name))
181             (sets `(setf (svref ,n-cache (+ ,n-index ,n)) ,arg-name)))
182           (incf n)))
183
184       (when *profile-hash-cache*
185         (let ((n-probe (symbolicate "*" name "-CACHE-PROBES*"))
186               (n-miss (symbolicate "*" name "-CACHE-MISSES*")))
187           (inits `(setq ,n-probe 0))
188           (inits `(setq ,n-miss 0))
189           (forms `(defvar ,n-probe))
190           (forms `(defvar ,n-miss))
191           (forms `(declaim (fixnum ,n-miss ,n-probe)))))
192
193       (let ((fun-name (symbolicate name "-CACHE-LOOKUP")))
194         (inlines fun-name)
195         (forms
196          `(defun ,fun-name ,(arg-vars)
197             ,@(when *profile-hash-cache*
198                 `((incf ,(symbolicate  "*" name "-CACHE-PROBES*"))))
199             (let ((,n-index (* (,hash-function ,@(arg-vars)) ,entry-size))
200                   (,n-cache ,var-name))
201               (declare (type fixnum ,n-index))
202               (cond ((and ,@(tests))
203                      (values ,@(mapcar (lambda (x) `(svref ,n-cache ,x))
204                                        (values-indices))))
205                     (t
206                      ,@(when *profile-hash-cache*
207                          `((incf ,(symbolicate  "*" name "-CACHE-MISSES*"))))
208                      ,default))))))
209
210       (let ((fun-name (symbolicate name "-CACHE-ENTER")))
211         (inlines fun-name)
212         (forms
213          `(defun ,fun-name (,@(arg-vars) ,@(values-names))
214             (let ((,n-index (* (,hash-function ,@(arg-vars)) ,entry-size))
215                   (,n-cache ,var-name))
216               (declare (type fixnum ,n-index))
217               ,@(sets)
218               ,@(mapcar #'(lambda (i val)
219                             `(setf (svref ,n-cache ,i) ,val))
220                         (values-indices)
221                         (values-names))
222               (values)))))
223
224       (let ((fun-name (symbolicate name "-CACHE-CLEAR")))
225         (forms
226          `(defun ,fun-name ()
227             (do ((,n-index ,(- total-size entry-size) (- ,n-index ,entry-size))
228                  (,n-cache ,var-name))
229                 ((minusp ,n-index))
230               (declare (type fixnum ,n-index))
231               ,@(collect ((arg-sets))
232                   (dotimes (i nargs)
233                     (arg-sets `(setf (svref ,n-cache (+ ,n-index ,i)) nil)))
234                   (arg-sets))
235               ,@(mapcar #'(lambda (i val)
236                             `(setf (svref ,n-cache ,i) ,val))
237                         (values-indices)
238                         default-values))
239             (values)))
240         (forms `(,fun-name)))
241
242       (inits `(unless (boundp ',var-name)
243                 (setq ,var-name (make-array ,total-size))))
244       #!+sb-show (inits `(setq *hash-caches-initialized-p* t))
245
246       `(progn
247          (defvar ,var-name)
248          (declaim (type (simple-vector ,total-size) ,var-name))
249          #!-sb-fluid (declaim (inline ,@(inlines)))
250          (,init-wrapper ,@(inits))
251          ,@(forms)
252          ',name))))
253
254 (defmacro defun-cached ((name &rest options &key (values 1) default
255                               &allow-other-keys)
256                         args &body body-decls-doc)
257   #!+sb-doc
258   "DEFUN-CACHED (Name {Key Value}*) ({(Arg-Name Test-Function)}*) Form*
259   Some syntactic sugar for defining a function whose values are cached by
260   DEFINE-HASH-CACHE."
261   (let ((default-values (if (and (consp default) (eq (car default) 'values))
262                             (cdr default)
263                             (list default)))
264         (arg-names (mapcar #'car args)))
265     (collect ((values-names))
266       (dotimes (i values)
267         (values-names (gensym)))
268       (multiple-value-bind (body decls doc) (parse-body body-decls-doc)
269         `(progn
270            (define-hash-cache ,name ,args ,@options)
271            (defun ,name ,arg-names
272              ,@decls
273              ,doc
274              (cond #!+sb-show
275                    ((not (boundp '*hash-caches-initialized-p*))
276                     ;; This shouldn't happen, but it did happen to me
277                     ;; when revising the type system, and it's a lot
278                     ;; easier to figure out what what's going on with
279                     ;; that kind of problem if the system can be kept
280                     ;; alive until cold boot is complete. The recovery
281                     ;; mechanism should definitely be conditional on
282                     ;; some debugging feature (e.g. SB-SHOW) because
283                     ;; it's big, duplicating all the BODY code. -- WHN
284                     (/show0 ,name " too early in cold init, uncached")
285                     (/show0 ,(first arg-names) "=..")
286                     (/hexstr ,(first arg-names))
287                     ,@body)
288                    (t
289                     (multiple-value-bind ,(values-names)
290                         (,(symbolicate name "-CACHE-LOOKUP") ,@arg-names)
291                       (if (and ,@(mapcar (lambda (val def)
292                                            `(eq ,val ,def))
293                                          (values-names) default-values))
294                           (multiple-value-bind ,(values-names)
295                               (progn ,@body)
296                             (,(symbolicate name "-CACHE-ENTER") ,@arg-names
297                              ,@(values-names))
298                             (values ,@(values-names)))
299                           (values ,@(values-names))))))))))))
300 \f
301 ;;;; package idioms
302
303 ;;; Note: Almost always you want to use FIND-UNDELETED-PACKAGE-OR-LOSE
304 ;;; instead of this function. (The distinction only actually matters when
305 ;;; PACKAGE-DESIGNATOR is actually a deleted package, and in that case
306 ;;; you generally do want to signal an error instead of proceeding.)
307 (defun %find-package-or-lose (package-designator)
308   (or (find-package package-designator)
309       (error 'sb!kernel:simple-package-error
310              :package package-designator
311              :format-control "The name ~S does not designate any package."
312              :format-arguments (list package-designator))))
313
314 ;;; ANSI specifies (in the section for FIND-PACKAGE) that the
315 ;;; consequences of most operations on deleted packages are
316 ;;; unspecified. We try to signal errors in such cases.
317 (defun find-undeleted-package-or-lose (package-designator)
318   (let ((maybe-result (%find-package-or-lose package-designator)))
319     (if (package-name maybe-result)     ; if not deleted
320         maybe-result
321         (error 'sb!kernel:simple-package-error
322                :package maybe-result
323                :format-control "The package ~S has been deleted."
324                :format-arguments (list maybe-result)))))
325 \f
326 ;;;; miscellany
327
328 ;;; Is NAME a legal function name?
329 (defun legal-function-name-p (name)
330   (or (symbolp name)
331       (and (consp name)
332            (eq (car name) 'setf)
333            (consp (cdr name))
334            (symbolp (cadr name))
335            (null (cddr name)))))
336
337 ;;; Given a function name, return the name for the BLOCK which
338 ;;; encloses its body (e.g. in DEFUN, DEFINE-COMPILER-MACRO, or FLET).
339 (declaim (ftype (function ((or symbol cons)) symbol) function-name-block-name))
340 (defun function-name-block-name (function-name)
341   (cond ((symbolp function-name)
342          function-name)
343         ((and (consp function-name)
344               (= (length function-name) 2)
345               (eq (first function-name) 'setf))
346          (second function-name))
347         (t
348          (error "not legal as a function name: ~S" function-name))))
349
350 ;;; Is X a (possibly-improper) list of at least N elements?
351 (declaim (ftype (function (t index)) list-of-length-at-least-p))
352 (defun list-of-length-at-least-p (x n)
353   (or (zerop n) ; since anything can be considered an improper list of length 0
354       (and (consp x)
355            (list-of-length-at-least-p (cdr x) (1- n)))))
356
357 ;;; Return a list of N gensyms. (This is a common suboperation in
358 ;;; macros and other code-manipulating code.)
359 (declaim (ftype (function (index) list) make-gensym-list))
360 (defun make-gensym-list (n)
361   (loop repeat n collect (gensym)))
362
363 ;;; ANSI guarantees that some symbols are self-evaluating. This
364 ;;; function is to be called just before a change which would affect
365 ;;; that. (We don't absolutely have to call this function before such
366 ;;; changes, since such changes are given as undefined behavior. In
367 ;;; particular, we don't if the runtime cost would be annoying. But
368 ;;; otherwise it's nice to do so.)
369 (defun about-to-modify (symbol)
370   (declare (type symbol symbol))
371   (cond ((eq symbol t)
372          (error "Veritas aeterna. (can't change T)"))
373         ((eq symbol nil)
374          (error "Nihil ex nihil. (can't change NIL)"))
375         ((keywordp symbol)
376          (error "Keyword values can't be changed."))
377         ;; (Just because a value is CONSTANTP is not a good enough
378         ;; reason to complain here, because we want DEFCONSTANT to
379         ;; be able to use this function, and it's legal to DEFCONSTANT
380         ;; a constant as long as the new value is EQL to the old
381         ;; value.)
382         ))
383
384 ;;; Return a function like FUN, but expecting its (two) arguments in
385 ;;; the opposite order that FUN does.
386 (declaim (inline swapped-args-fun))
387 (defun swapped-args-fun (fun)
388   (declare (type function fun))
389   (lambda (x y)
390     (funcall fun y x)))
391 \f
392 ;;;; DEFPRINTER
393
394 ;;; These functions are called by the expansion of the DEFPRINTER
395 ;;; macro to do the actual printing.
396 (declaim (ftype (function (symbol t stream &optional t) (values))
397                 defprinter-prin1 defprinter-princ))
398 (defun defprinter-prin1 (name value stream &optional indent)
399   (declare (ignore indent))
400   (defprinter-prinx #'prin1 name value stream))
401 (defun defprinter-princ (name value stream &optional indent)
402   (declare (ignore indent))
403   (defprinter-prinx #'princ name value stream))
404 (defun defprinter-prinx (prinx name value stream)
405   (declare (type function prinx))
406   (when *print-pretty*
407     (pprint-newline :linear stream))
408   (format stream ":~A " name)
409   (funcall prinx value stream)
410   (values))
411 (defun defprinter-print-space (stream)
412   (write-char #\space stream))
413
414 ;;; Define some kind of reasonable PRINT-OBJECT method for a
415 ;;; STRUCTURE-OBJECT class.
416 ;;;
417 ;;; NAME is the name of the structure class, and CONC-NAME is the same
418 ;;; as in DEFSTRUCT.
419 ;;;
420 ;;; The SLOT-DESCS describe how each slot should be printed. Each
421 ;;; SLOT-DESC can be a slot name, indicating that the slot should
422 ;;; simply be printed. A SLOT-DESC may also be a list of a slot name
423 ;;; and other stuff. The other stuff is composed of keywords followed
424 ;;; by expressions. The expressions are evaluated with the variable
425 ;;; which is the slot name bound to the value of the slot. These
426 ;;; keywords are defined:
427 ;;;
428 ;;; :PRIN1    Print the value of the expression instead of the slot value.
429 ;;; :PRINC    Like :PRIN1, only princ the value
430 ;;; :TEST     Only print something if the test is true.
431 ;;;
432 ;;; If no printing thing is specified then the slot value is printed
433 ;;; as if by PRIN1.
434 ;;;
435 ;;; The structure being printed is bound to STRUCTURE and the stream
436 ;;; is bound to STREAM.
437 (defmacro defprinter ((name &key (conc-name (concatenate 'simple-string
438                                                          (symbol-name name)
439                                                          "-")))
440                       &rest slot-descs)
441   (let ((first? t)
442         maybe-print-space
443         (reversed-prints nil)
444         (stream (gensym "STREAM")))
445     (flet ((sref (slot-name)
446              `(,(symbolicate conc-name slot-name) structure)))
447       (dolist (slot-desc slot-descs)
448         (if first?
449             (setf maybe-print-space nil
450                   first? nil)
451             (setf maybe-print-space `(defprinter-print-space ,stream)))
452         (cond ((atom slot-desc)
453                (push maybe-print-space reversed-prints)
454                (push `(defprinter-prin1 ',slot-desc ,(sref slot-desc) ,stream)
455                      reversed-prints))
456               (t
457                (let ((sname (first slot-desc))
458                      (test t))
459                  (collect ((stuff))
460                    (do ((option (rest slot-desc) (cddr option)))
461                        ((null option)
462                         (push `(let ((,sname ,(sref sname)))
463                                  (when ,test
464                                    ,maybe-print-space
465                                    ,@(or (stuff)
466                                          `((defprinter-prin1
467                                              ',sname ,sname ,stream)))))
468                               reversed-prints))
469                      (case (first option)
470                        (:prin1
471                         (stuff `(defprinter-prin1
472                                   ',sname ,(second option) ,stream)))
473                        (:princ
474                         (stuff `(defprinter-princ
475                                   ',sname ,(second option) ,stream)))
476                        (:test (setq test (second option)))
477                        (t
478                         (error "bad option: ~S" (first option)))))))))))
479     `(def!method print-object ((structure ,name) ,stream)
480        ;; FIXME: should probably be byte-compiled
481        (pprint-logical-block (,stream nil)
482          (print-unreadable-object (structure ,stream :type t)
483            (when *print-pretty*
484              (pprint-indent :block 2 ,stream))
485            ,@(nreverse reversed-prints))))))
486 \f
487 #|
488 ;;; REMOVEME when done testing byte cross-compiler
489 (defun byte-compiled-foo (x y)
490   (declare (optimize (speed 0) (debug 1)))
491   (if x
492       x
493       (cons y y)))
494 |#