0.8.0.6:
[sbcl.git] / src / code / early-type.lisp
1 ;;;; This software is part of the SBCL system. See the README file for
2 ;;;; more information.
3 ;;;;
4 ;;;; This software is derived from the CMU CL system, which was
5 ;;;; written at Carnegie Mellon University and released into the
6 ;;;; public domain. The software is in the public domain and is
7 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
8 ;;;; files for more information.
9
10 (in-package "SB!KERNEL")
11
12 (!begin-collecting-cold-init-forms)
13
14 ;;; Has the type system been properly initialized? (I.e. is it OK to
15 ;;; use it?)
16 (defvar *type-system-initialized* #+sb-xc-host nil) ; (set in cold load)
17 \f
18 ;;;; representations of types
19
20 ;;; A HAIRY-TYPE represents anything too weird to be described
21 ;;; reasonably or to be useful, such as NOT, SATISFIES, unknown types,
22 ;;; and unreasonably complicated types involving AND. We just remember
23 ;;; the original type spec.
24 (defstruct (hairy-type (:include ctype
25                                  (class-info (type-class-or-lose 'hairy))
26                                  (enumerable t)
27                                  (might-contain-other-types-p t))
28                        (:copier nil)
29                        #!+cmu (:pure nil))
30   ;; the Common Lisp type-specifier of the type we represent
31   (specifier nil :type t))
32
33 (!define-type-class hairy)
34
35 ;;; An UNKNOWN-TYPE is a type not known to the type system (not yet
36 ;;; defined). We make this distinction since we don't want to complain
37 ;;; about types that are hairy but defined.
38 (defstruct (unknown-type (:include hairy-type)
39                          (:copier nil)))
40
41 (defstruct (negation-type (:include ctype
42                                     (class-info (type-class-or-lose 'negation))
43                                     ;; FIXME: is this right?  It's
44                                     ;; what they had before, anyway
45                                     (enumerable t)
46                                     (might-contain-other-types-p t))
47                           (:copier nil)
48                           #!+cmu (:pure nil))
49   (type (missing-arg) :type ctype))
50
51 (!define-type-class negation)
52
53 ;;; ARGS-TYPE objects are used both to represent VALUES types and
54 ;;; to represent FUNCTION types.
55 (defstruct (args-type (:include ctype)
56                       (:constructor nil)
57                       (:copier nil))
58   ;; Lists of the type for each required and optional argument.
59   (required nil :type list)
60   (optional nil :type list)
61   ;; The type for the rest arg. NIL if there is no &REST arg.
62   (rest nil :type (or ctype null))
63   ;; true if &KEY arguments are specified
64   (keyp nil :type boolean)
65   ;; list of KEY-INFO structures describing the &KEY arguments
66   (keywords nil :type list)
67   ;; true if other &KEY arguments are allowed
68   (allowp nil :type boolean))
69
70 (defun canonicalize-args-type-args (required optional rest)
71   (when (eq rest *empty-type*)
72     ;; or vice-versa?
73     (setq rest nil))
74   (loop with last-not-rest = nil
75         for i from 0
76         for opt in optional
77         do (cond ((eq opt *empty-type*)
78                   (return (values required (subseq optional i) rest)))
79                  ((neq opt rest)
80                   (setq last-not-rest i)))
81         finally (return (values required
82                                 (if last-not-rest
83                                     (subseq optional 0 (1+ last-not-rest))
84                                     nil)
85                                 rest))))
86
87 (defun args-types (lambda-list-like-thing)
88   (multiple-value-bind
89         (required optional restp rest keyp keys allowp auxp aux
90                   morep more-context more-count llk-p)
91       (parse-lambda-list-like-thing lambda-list-like-thing)
92     (declare (ignore aux morep more-context more-count))
93     (when auxp
94       (error "&AUX in a FUNCTION or VALUES type: ~S." lambda-list-like-thing))
95     (let ((required (mapcar #'single-value-specifier-type required))
96           (optional (mapcar #'single-value-specifier-type optional))
97           (rest (when restp (single-value-specifier-type rest)))
98           (keywords
99            (collect ((key-info))
100              (dolist (key keys)
101                (unless (proper-list-of-length-p key 2)
102                  (error "Keyword type description is not a two-list: ~S." key))
103                (let ((kwd (first key)))
104                  (when (find kwd (key-info) :key #'key-info-name)
105                    (error "~@<repeated keyword ~S in lambda list: ~2I~_~S~:>"
106                           kwd lambda-list-like-thing))
107                  (key-info
108                   (make-key-info
109                    :name kwd
110                    :type (single-value-specifier-type (second key))))))
111              (key-info))))
112       (multiple-value-bind (required optional rest)
113           (canonicalize-args-type-args required optional rest)
114         (values required optional rest keyp keywords allowp llk-p)))))
115
116 (defstruct (values-type
117             (:include args-type
118                       (class-info (type-class-or-lose 'values)))
119             (:constructor %make-values-type)
120             (:copier nil)))
121
122 (defun-cached (make-values-type-cached
123                :hash-bits 8
124                :hash-function (lambda (req opt rest allowp)
125                                 (logand (logxor
126                                          (type-list-cache-hash req)
127                                          (type-list-cache-hash opt)
128                                          (if rest
129                                              (type-hash-value rest)
130                                              42)
131                                          (sxhash allowp))
132                                         #xFF)))
133     ((required equal-but-no-car-recursion)
134      (optional equal-but-no-car-recursion)
135      (rest eq)
136      (allowp eq))
137   (%make-values-type :required required
138                      :optional optional
139                      :rest rest
140                      :allowp allowp))
141
142 ;;; FIXME: ANSI VALUES has a short form (without lambda list
143 ;;; keywords), which should be translated into a long one.
144 (defun make-values-type (&key (args nil argsp)
145                          required optional rest allowp)
146   (if argsp
147       (if (eq args '*)
148           *wild-type*
149           (multiple-value-bind (required optional rest keyp keywords allowp
150                                 llk-p)
151               (args-types args)
152             (declare (ignore keywords))
153             (when keyp
154               (error "&KEY appeared in a VALUES type specifier ~S."
155                      `(values ,@args)))
156             (if llk-p
157                 (make-values-type :required required
158                                   :optional optional
159                                   :rest rest
160                                   :allowp allowp)
161                 (make-short-values-type required))))
162       (multiple-value-bind (required optional rest)
163           (canonicalize-args-type-args required optional rest)
164         (cond ((and (null required)
165                     (null optional)
166                     (eq rest *universal-type*))
167                *wild-type*)
168               ((memq *empty-type* required)
169                *empty-type*)
170               (t (make-values-type-cached required optional
171                                           rest allowp))))))
172
173 (!define-type-class values)
174
175 ;;; (SPECIFIER-TYPE 'FUNCTION) and its subtypes
176 (defstruct (fun-type (:include args-type
177                                (class-info (type-class-or-lose 'function)))
178                      (:constructor %make-fun-type))
179   ;; true if the arguments are unrestrictive, i.e. *
180   (wild-args nil :type boolean)
181   ;; type describing the return values. This is a values type
182   ;; when multiple values were specified for the return.
183   (returns (missing-arg) :type ctype))
184 (defun make-fun-type (&rest initargs
185                       &key (args nil argsp) returns &allow-other-keys)
186   (if argsp
187       (if (eq args '*)
188           (if (eq returns *wild-type*)
189               (specifier-type 'function)
190               (%make-fun-type :wild-args t :returns returns))
191           (multiple-value-bind (required optional rest keyp keywords allowp)
192               (args-types args)
193             (if (and (null required)
194                      (null optional)
195                      (eq rest *universal-type*)
196                      (not keyp))
197                 (if (eq returns *wild-type*)
198                     (specifier-type 'function)
199                     (%make-fun-type :wild-args t :returns returns))
200                 (%make-fun-type :required required
201                                 :optional optional
202                                 :rest rest
203                                 :keyp keyp
204                                 :keywords keywords
205                                 :allowp allowp
206                                 :returns returns))))
207       ;; FIXME: are we really sure that we won't make something that
208       ;; looks like a completely wild function here?
209       (apply #'%make-fun-type initargs)))
210
211 ;;; The CONSTANT-TYPE structure represents a use of the CONSTANT-ARG
212 ;;; "type specifier", which is only meaningful in function argument
213 ;;; type specifiers used within the compiler. (It represents something
214 ;;; that the compiler knows to be a constant.)
215 (defstruct (constant-type
216             (:include ctype
217                       (class-info (type-class-or-lose 'constant)))
218             (:copier nil))
219   ;; The type which the argument must be a constant instance of for this type
220   ;; specifier to win.
221   (type (missing-arg) :type ctype))
222
223 ;;; The NAMED-TYPE is used to represent *, T and NIL. These types must
224 ;;; be super- or sub-types of all types, not just classes and * and
225 ;;; NIL aren't classes anyway, so it wouldn't make much sense to make
226 ;;; them built-in classes.
227 (defstruct (named-type (:include ctype
228                                  (class-info (type-class-or-lose 'named)))
229                        (:copier nil))
230   (name nil :type symbol))
231
232 ;;; a list of all the float "formats" (i.e. internal representations;
233 ;;; nothing to do with #'FORMAT), in order of decreasing precision
234 (eval-when (:compile-toplevel :load-toplevel :execute)
235   (defparameter *float-formats*
236     '(long-float double-float single-float short-float)))
237
238 ;;; The type of a float format.
239 (deftype float-format () `(member ,@*float-formats*))
240
241 ;;; A NUMERIC-TYPE represents any numeric type, including things
242 ;;; such as FIXNUM.
243 (defstruct (numeric-type (:include ctype
244                                    (class-info (type-class-or-lose 'number)))
245                          (:constructor %make-numeric-type)
246                          (:copier nil))
247   ;; the kind of numeric type we have, or NIL if not specified (just
248   ;; NUMBER or COMPLEX)
249   ;;
250   ;; KLUDGE: A slot named CLASS for a non-CLASS value is bad.
251   ;; Especially when a CLASS value *is* stored in another slot (called
252   ;; CLASS-INFO:-). Perhaps this should be called CLASS-NAME? Also
253   ;; weird that comment above says "Numeric-Type is used to represent
254   ;; all numeric types" but this slot doesn't allow COMPLEX as an
255   ;; option.. how does this fall into "not specified" NIL case above?
256   ;; Perhaps someday we can switch to CLOS and make NUMERIC-TYPE
257   ;; be an abstract base class and INTEGER-TYPE, RATIONAL-TYPE, and
258   ;; whatnot be concrete subclasses..
259   (class nil :type (member integer rational float nil) :read-only t)
260   ;; "format" for a float type (i.e. type specifier for a CPU
261   ;; representation of floating point, e.g. 'SINGLE-FLOAT -- nothing
262   ;; to do with #'FORMAT), or NIL if not specified or not a float.
263   ;; Formats which don't exist in a given implementation don't appear
264   ;; here.
265   (format nil :type (or float-format null) :read-only t)
266   ;; Is this a complex numeric type?  Null if unknown (only in NUMBER).
267   ;;
268   ;; FIXME: I'm bewildered by FOO-P names for things not intended to
269   ;; interpreted as truth values. Perhaps rename this COMPLEXNESS?
270   (complexp :real :type (member :real :complex nil) :read-only t)
271   ;; The upper and lower bounds on the value, or NIL if there is no
272   ;; bound. If a list of a number, the bound is exclusive. Integer
273   ;; types never have exclusive bounds, i.e. they may have them on
274   ;; input, but they're canonicalized to inclusive bounds before we
275   ;; store them here.
276   (low nil :type (or number cons null) :read-only t)
277   (high nil :type (or number cons null) :read-only t))
278
279 ;;; Impose canonicalization rules for NUMERIC-TYPE. Note that in some
280 ;;; cases, despite the name, we return *EMPTY-TYPE* instead of a
281 ;;; NUMERIC-TYPE.
282 (defun make-numeric-type (&key class format (complexp :real) low high
283                                enumerable)
284   ;; if interval is empty
285   (if (and low
286            high
287            (if (or (consp low) (consp high)) ; if either bound is exclusive
288                (>= (type-bound-number low) (type-bound-number high))
289                (> low high)))
290       *empty-type*
291       (multiple-value-bind (canonical-low canonical-high)
292           (case class
293             (integer
294              ;; INTEGER types always have their LOW and HIGH bounds
295              ;; represented as inclusive, not exclusive values.
296              (values (if (consp low)
297                          (1+ (type-bound-number low))
298                          low)
299                      (if (consp high)
300                          (1- (type-bound-number high))
301                          high)))
302             (t 
303              ;; no canonicalization necessary
304              (values low high)))
305         (when (and (eq class 'rational)
306                    (integerp canonical-low)
307                    (integerp canonical-high)
308                    (= canonical-low canonical-high))
309           (setf class 'integer))
310         (%make-numeric-type :class class
311                             :format format
312                             :complexp complexp
313                             :low canonical-low
314                             :high canonical-high
315                             :enumerable enumerable))))
316
317 (defun modified-numeric-type (base
318                               &key
319                               (class      (numeric-type-class      base))
320                               (format     (numeric-type-format     base))
321                               (complexp   (numeric-type-complexp   base))
322                               (low        (numeric-type-low        base))
323                               (high       (numeric-type-high       base))
324                               (enumerable (numeric-type-enumerable base)))
325   (make-numeric-type :class class
326                      :format format
327                      :complexp complexp
328                      :low low
329                      :high high
330                      :enumerable enumerable))
331
332 ;;; An ARRAY-TYPE is used to represent any array type, including
333 ;;; things such as SIMPLE-STRING.
334 (defstruct (array-type (:include ctype
335                                  (class-info (type-class-or-lose 'array)))
336                        (:constructor %make-array-type)
337                        (:copier nil))
338   ;; the dimensions of the array, or * if unspecified. If a dimension
339   ;; is unspecified, it is *.
340   (dimensions '* :type (or list (member *)))
341   ;; Is this not a simple array type? (:MAYBE means that we don't know.)
342   (complexp :maybe :type (member t nil :maybe))
343   ;; the element type as originally specified
344   (element-type (missing-arg) :type ctype)
345   ;; the element type as it is specialized in this implementation
346   (specialized-element-type *wild-type* :type ctype))
347 (define-cached-synonym make-array-type)
348
349 ;;; A MEMBER-TYPE represent a use of the MEMBER type specifier. We
350 ;;; bother with this at this level because MEMBER types are fairly
351 ;;; important and union and intersection are well defined.
352 (defstruct (member-type (:include ctype
353                                   (class-info (type-class-or-lose 'member))
354                                   (enumerable t))
355                         (:copier nil)
356                         (:constructor %make-member-type (members))
357                         #-sb-xc-host (:pure nil))
358   ;; the things in the set, with no duplications
359   (members nil :type list))
360 (defun make-member-type (&key members)
361   (declare (type list members))
362   ;; make sure that we've removed duplicates
363   (aver (= (length members) (length (remove-duplicates members))))
364   ;; if we have a pair of zeros (e.g. 0.0d0 and -0.0d0), then we can
365   ;; canonicalize to (DOUBLE-FLOAT 0.0d0 0.0d0), because numeric
366   ;; ranges are compared by arithmetic operators (while MEMBERship is
367   ;; compared by EQL).  -- CSR, 2003-04-23
368   (let ((singlep (subsetp `(,(load-time-value (make-unportable-float :single-float-negative-zero)) 0.0f0) members))
369         (doublep (subsetp `(,(load-time-value (make-unportable-float :double-float-negative-zero)) 0.0d0) members))
370         #!+long-float
371         (longp (subsetp `(,(load-time-value (make-unportable-float :long-float-negative-zero)) 0.0l0) members)))
372     (if (or singlep doublep #!+long-float longp)
373         (let (union-types)
374           (when singlep
375             (push (ctype-of 0.0f0) union-types)
376             (setf members (set-difference members `(,(load-time-value (make-unportable-float :single-float-negative-zero)) 0.0f0))))
377           (when doublep
378             (push (ctype-of 0.0d0) union-types)
379             (setf members (set-difference members `(,(load-time-value (make-unportable-float :double-float-negative-zero)) 0.0d0))))
380           #!+long-float
381           (when longp
382             (push (ctype-of 0.0l0) union-types)
383             (setf members (set-difference members `(,(load-time-value (make-unportable-float :long-float-negative-zero)) 0.0l0))))
384           (aver (not (null union-types)))
385           (make-union-type t
386                            (if (null members)
387                                union-types
388                                (cons (%make-member-type members)
389                                      union-types))))
390         (%make-member-type members))))
391
392 ;;; A COMPOUND-TYPE is a type defined out of a set of types, the
393 ;;; common parent of UNION-TYPE and INTERSECTION-TYPE.
394 (defstruct (compound-type (:include ctype
395                                     (might-contain-other-types-p t))
396                           (:constructor nil)
397                           (:copier nil))
398   (types nil :type list :read-only t))
399
400 ;;; A UNION-TYPE represents a use of the OR type specifier which we
401 ;;; couldn't canonicalize to something simpler. Canonical form:
402 ;;;   1. All possible pairwise simplifications (using the UNION2 type
403 ;;;      methods) have been performed. Thus e.g. there is never more
404 ;;;      than one MEMBER-TYPE component. FIXME: As of sbcl-0.6.11.13,
405 ;;;      this hadn't been fully implemented yet.
406 ;;;   2. There are never any UNION-TYPE components.
407 (defstruct (union-type (:include compound-type
408                                  (class-info (type-class-or-lose 'union)))
409                        (:constructor %make-union-type (enumerable types))
410                        (:copier nil)))
411 (define-cached-synonym make-union-type)
412
413 ;;; An INTERSECTION-TYPE represents a use of the AND type specifier
414 ;;; which we couldn't canonicalize to something simpler. Canonical form:
415 ;;;   1. All possible pairwise simplifications (using the INTERSECTION2
416 ;;;      type methods) have been performed. Thus e.g. there is never more
417 ;;;      than one MEMBER-TYPE component.
418 ;;;   2. There are never any INTERSECTION-TYPE components: we've
419 ;;;      flattened everything into a single INTERSECTION-TYPE object.
420 ;;;   3. There are never any UNION-TYPE components. Either we should
421 ;;;      use the distributive rule to rearrange things so that
422 ;;;      unions contain intersections and not vice versa, or we
423 ;;;      should just punt to using a HAIRY-TYPE.
424 (defstruct (intersection-type (:include compound-type
425                                         (class-info (type-class-or-lose
426                                                      'intersection)))
427                               (:constructor %make-intersection-type
428                                             (enumerable types))
429                               (:copier nil)))
430
431 ;;; Return TYPE converted to canonical form for a situation where the
432 ;;; "type" '* (which SBCL still represents as a type even though ANSI
433 ;;; CL defines it as a related but different kind of placeholder) is
434 ;;; equivalent to type T.
435 (defun type-*-to-t (type)
436   (if (type= type *wild-type*)
437       *universal-type*
438       type))
439
440 ;;; A CONS-TYPE is used to represent a CONS type.
441 (defstruct (cons-type (:include ctype (class-info (type-class-or-lose 'cons)))
442                       (:constructor
443                        %make-cons-type (car-type
444                                         cdr-type))
445                       (:copier nil))
446   ;; the CAR and CDR element types (to support ANSI (CONS FOO BAR) types)
447   ;;
448   ;; FIXME: Most or all other type structure slots could also be :READ-ONLY.
449   (car-type (missing-arg) :type ctype :read-only t)
450   (cdr-type (missing-arg) :type ctype :read-only t))
451 (defun make-cons-type (car-type cdr-type)
452   (aver (not (or (eq car-type *wild-type*)
453                  (eq cdr-type *wild-type*))))
454   (if (or (eq car-type *empty-type*)
455           (eq cdr-type *empty-type*))
456       *empty-type*
457       (%make-cons-type car-type cdr-type)))
458 \f
459 ;;;; type utilities
460
461 ;;; Return the type structure corresponding to a type specifier. We
462 ;;; pick off structure types as a special case.
463 ;;;
464 ;;; Note: VALUES-SPECIFIER-TYPE-CACHE-CLEAR must be called whenever a
465 ;;; type is defined (or redefined).
466 (defun-cached (values-specifier-type
467                :hash-function (lambda (x)
468                                 (logand (sxhash x) #x3FF))
469                :hash-bits 10
470                :init-wrapper !cold-init-forms)
471               ((orig equal-but-no-car-recursion))
472   (let ((u (uncross orig)))
473     (or (info :type :builtin u)
474         (let ((spec (type-expand u)))
475           (cond
476            ((and (not (eq spec u))
477                  (info :type :builtin spec)))
478            ((eq (info :type :kind spec) :instance)
479             (find-classoid spec))
480            ((typep spec 'classoid)
481             ;; There doesn't seem to be any way to translate
482             ;; (TYPEP SPEC 'BUILT-IN-CLASS) into something which can be
483             ;; executed on the host Common Lisp at cross-compilation time.
484             #+sb-xc-host (error
485                           "stub: (TYPEP SPEC 'BUILT-IN-CLASS) on xc host")
486             (if (typep spec 'built-in-classoid)
487                 (or (built-in-classoid-translation spec) spec)
488                 spec))
489            (t
490             (let* (;; FIXME: This automatic promotion of FOO-style
491                    ;; specs to (FOO)-style specs violates the ANSI
492                    ;; standard. Unfortunately, we can't fix the
493                    ;; problem just by removing it, since then things
494                    ;; downstream should break. But at some point we
495                    ;; should fix this and the things downstream too.
496                    (lspec (if (atom spec) (list spec) spec))
497                    (fun (info :type :translator (car lspec))))
498               (cond (fun
499                      (funcall fun lspec))
500                     ((or (and (consp spec) (symbolp (car spec)))
501                          (symbolp spec))
502                      (when (and *type-system-initialized*
503                                 (not (eq (info :type :kind spec)
504                                          :forthcoming-defclass-type)))
505                        (signal 'parse-unknown-type :specifier spec))
506                      ;; (The RETURN-FROM here inhibits caching.)
507                      (return-from values-specifier-type
508                        (make-unknown-type :specifier spec)))
509                     (t
510                      (error "bad thing to be a type specifier: ~S"
511                             spec))))))))))
512
513 ;;; This is like VALUES-SPECIFIER-TYPE, except that we guarantee to
514 ;;; never return a VALUES type.
515 (defun specifier-type (x)
516   (let ((res (values-specifier-type x)))
517     (when (or (values-type-p res)
518               ;; bootstrap magic :-(
519               (and (named-type-p res)
520                    (eq (named-type-name res) '*)))
521       (error "VALUES type illegal in this context:~%  ~S" x))
522     res))
523
524 (defun single-value-specifier-type (x)
525   (if (eq x '*)
526       *universal-type*
527       (specifier-type x)))
528
529 ;;; Similar to MACROEXPAND, but expands DEFTYPEs. We don't bother
530 ;;; returning a second value.
531 (defun type-expand (form)
532   (let ((def (cond ((symbolp form)
533                     (info :type :expander form))
534                    ((and (consp form) (symbolp (car form)))
535                     (info :type :expander (car form)))
536                    (t nil))))
537     (if def
538         (type-expand (funcall def (if (consp form) form (list form))))
539         form)))
540
541 ;;; Note that the type NAME has been (re)defined, updating the
542 ;;; undefined warnings and VALUES-SPECIFIER-TYPE cache.
543 (defun %note-type-defined (name)
544   (declare (symbol name))
545   (note-name-defined name :type)
546   (when (boundp 'sb!kernel::*values-specifier-type-cache-vector*)
547     (values-specifier-type-cache-clear))
548   (values))
549
550 \f
551 (!defun-from-collected-cold-init-forms !early-type-cold-init)