0.7.9.19:
[sbcl.git] / src / code / late-type.lisp
1 ;;;; This file contains the definition of non-CLASS types (e.g.
2 ;;;; subtypes of interesting BUILT-IN-CLASSes) and the interfaces to
3 ;;;; the type system. Common Lisp type specifiers are parsed into a
4 ;;;; somewhat canonical internal type representation that supports
5 ;;;; type union, intersection, etc. (Except that ALIEN types have
6 ;;;; moved out..)
7
8 ;;;; This software is part of the SBCL system. See the README file for
9 ;;;; more information.
10 ;;;;
11 ;;;; This software is derived from the CMU CL system, which was
12 ;;;; written at Carnegie Mellon University and released into the
13 ;;;; public domain. The software is in the public domain and is
14 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
15 ;;;; files for more information.
16
17 (in-package "SB!KERNEL")
18
19 (/show0 "late-type.lisp 19")
20
21 (!begin-collecting-cold-init-forms)
22
23 ;;; ### Remaining incorrectnesses:
24 ;;;
25 ;;; TYPE-UNION (and the OR type) doesn't properly canonicalize an
26 ;;; exhaustive partition or coalesce contiguous ranges of numeric
27 ;;; types.
28 ;;;
29 ;;; There are all sorts of nasty problems with open bounds on FLOAT
30 ;;; types (and probably FLOAT types in general.)
31 ;;;
32 ;;; RATIO and BIGNUM are not recognized as numeric types.
33
34 ;;; FIXME: This really should go away. Alas, it doesn't seem to be so
35 ;;; simple to make it go away.. (See bug 123 in BUGS file.)
36 (defvar *use-implementation-types* t ; actually initialized in cold init
37   #!+sb-doc
38   "*USE-IMPLEMENTATION-TYPES* is a semi-public flag which determines how
39    restrictive we are in determining type membership. If two types are the
40    same in the implementation, then we will consider them them the same when
41    this switch is on. When it is off, we try to be as restrictive as the
42    language allows, allowing us to detect more errors. Currently, this only
43    affects array types.")
44 (!cold-init-forms (setq *use-implementation-types* t))
45
46 ;;; These functions are used as method for types which need a complex
47 ;;; subtypep method to handle some superclasses, but cover a subtree
48 ;;; of the type graph (i.e. there is no simple way for any other type
49 ;;; class to be a subtype.) There are always still complex ways,
50 ;;; namely UNION and MEMBER types, so we must give TYPE1's method a
51 ;;; chance to run, instead of immediately returning NIL, T.
52 (defun delegate-complex-subtypep-arg2 (type1 type2)
53   (let ((subtypep-arg1
54          (type-class-complex-subtypep-arg1
55           (type-class-info type1))))
56     (if subtypep-arg1
57         (funcall subtypep-arg1 type1 type2)
58         (values nil t))))
59 (defun delegate-complex-intersection2 (type1 type2)
60   (let ((method (type-class-complex-intersection2 (type-class-info type1))))
61     (if (and method (not (eq method #'delegate-complex-intersection2)))
62         (funcall method type2 type1)
63         (hierarchical-intersection2 type1 type2))))
64
65 ;;; This is used by !DEFINE-SUPERCLASSES to define the SUBTYPE-ARG1
66 ;;; method. INFO is a list of conses
67 ;;;   (SUPERCLASS-CLASS . {GUARD-TYPE-SPECIFIER | NIL}).
68 (defun !has-superclasses-complex-subtypep-arg1 (type1 type2 info)
69   ;; If TYPE2 might be concealing something related to our class
70   ;; hierarchy
71   (if (type-might-contain-other-types-p type2)
72       ;; too confusing, gotta punt
73       (values nil nil)
74       ;; ordinary case expected by old CMU CL code, where the taxonomy
75       ;; of TYPE2's representation accurately reflects the taxonomy of
76       ;; the underlying set
77       (values
78        ;; FIXME: This old CMU CL code probably deserves a comment
79        ;; explaining to us mere mortals how it works...
80        (and (sb!xc:typep type2 'sb!xc:class)
81             (dolist (x info nil)
82               (when (or (not (cdr x))
83                         (csubtypep type1 (specifier-type (cdr x))))
84                 (return
85                  (or (eq type2 (car x))
86                      (let ((inherits (layout-inherits (class-layout (car x)))))
87                        (dotimes (i (length inherits) nil)
88                          (when (eq type2 (layout-class (svref inherits i)))
89                            (return t)))))))))
90        t)))
91
92 ;;; This function takes a list of specs, each of the form
93 ;;;    (SUPERCLASS-NAME &OPTIONAL GUARD).
94 ;;; Consider one spec (with no guard): any instance of the named
95 ;;; TYPE-CLASS is also a subtype of the named superclass and of any of
96 ;;; its superclasses. If there are multiple specs, then some will have
97 ;;; guards. We choose the first spec whose guard is a supertype of
98 ;;; TYPE1 and use its superclass. In effect, a sequence of guards
99 ;;;    G0, G1, G2
100 ;;; is actually
101 ;;;    G0,(and G1 (not G0)), (and G2 (not (or G0 G1))).
102 ;;;
103 ;;; WHEN controls when the forms are executed.
104 (defmacro !define-superclasses (type-class-name specs when)
105   (let ((type-class (gensym "TYPE-CLASS-"))
106         (info (gensym "INFO")))
107     `(,when
108        (let ((,type-class (type-class-or-lose ',type-class-name))
109              (,info (mapcar (lambda (spec)
110                               (destructuring-bind
111                                   (super &optional guard)
112                                   spec
113                                 (cons (sb!xc:find-class super) guard)))
114                             ',specs)))
115          (setf (type-class-complex-subtypep-arg1 ,type-class)
116                (lambda (type1 type2)
117                  (!has-superclasses-complex-subtypep-arg1 type1 type2 ,info)))
118          (setf (type-class-complex-subtypep-arg2 ,type-class)
119                #'delegate-complex-subtypep-arg2)
120          (setf (type-class-complex-intersection2 ,type-class)
121                #'delegate-complex-intersection2)))))
122 \f
123 ;;;; FUNCTION and VALUES types
124 ;;;;
125 ;;;; Pretty much all of the general type operations are illegal on
126 ;;;; VALUES types, since we can't discriminate using them, do
127 ;;;; SUBTYPEP, etc. FUNCTION types are acceptable to the normal type
128 ;;;; operations, but are generally considered to be equivalent to
129 ;;;; FUNCTION. These really aren't true types in any type theoretic
130 ;;;; sense, but we still parse them into CTYPE structures for two
131 ;;;; reasons:
132
133 ;;;; -- Parsing and unparsing work the same way, and indeed we can't
134 ;;;;    tell whether a type is a function or values type without
135 ;;;;    parsing it.
136 ;;;; -- Many of the places that can be annotated with real types can
137 ;;;;    also be annotated with function or values types.
138
139 ;;; the description of a &KEY argument
140 (defstruct (key-info #-sb-xc-host (:pure t)
141                      (:copier nil))
142   ;; the key (not necessarily a keyword in ANSI Common Lisp)
143   (name (missing-arg) :type symbol)
144   ;; the type of the argument value
145   (type (missing-arg) :type ctype))
146
147 (!define-type-method (values :simple-subtypep :complex-subtypep-arg1)
148                      (type1 type2)
149   (declare (ignore type2))
150   ;; FIXME: should be TYPE-ERROR, here and in next method
151   (error "SUBTYPEP is illegal on this type:~%  ~S" (type-specifier type1)))
152
153 (!define-type-method (values :complex-subtypep-arg2)
154                      (type1 type2)
155   (declare (ignore type1))
156   (error "SUBTYPEP is illegal on this type:~%  ~S" (type-specifier type2)))
157
158 (!define-type-method (values :unparse) (type)
159   (cons 'values (unparse-args-types type)))
160
161 ;;; Return true if LIST1 and LIST2 have the same elements in the same
162 ;;; positions according to TYPE=. We return NIL, NIL if there is an
163 ;;; uncertain comparison.
164 (defun type=-list (list1 list2)
165   (declare (list list1 list2))
166   (do ((types1 list1 (cdr types1))
167        (types2 list2 (cdr types2)))
168       ((or (null types1) (null types2))
169        (if (or types1 types2)
170            (values nil t)
171            (values t t)))
172     (multiple-value-bind (val win)
173         (type= (first types1) (first types2))
174       (unless win
175         (return (values nil nil)))
176       (unless val
177         (return (values nil t))))))
178
179 (!define-type-method (values :simple-=) (type1 type2)
180   (let ((rest1 (args-type-rest type1))
181         (rest2 (args-type-rest type2)))
182     (cond ((or (args-type-keyp type1) (args-type-keyp type2)
183                (args-type-allowp type1) (args-type-allowp type2))
184            (values nil nil))
185           ((and rest1 rest2 (type/= rest1 rest2))
186            (type= rest1 rest2))
187           ((or rest1 rest2)
188            (values nil t))
189           (t
190            (multiple-value-bind (req-val req-win)
191                (type=-list (values-type-required type1)
192                            (values-type-required type2))
193              (multiple-value-bind (opt-val opt-win)
194                  (type=-list (values-type-optional type1)
195                              (values-type-optional type2))
196                (values (and req-val opt-val) (and req-win opt-win))))))))
197
198 (!define-type-class function)
199
200 ;;; a flag that we can bind to cause complex function types to be
201 ;;; unparsed as FUNCTION. This is useful when we want a type that we
202 ;;; can pass to TYPEP.
203 (defvar *unparse-fun-type-simplify*)
204 (!cold-init-forms (setq *unparse-fun-type-simplify* nil))
205
206 (!define-type-method (function :unparse) (type)
207   (if *unparse-fun-type-simplify*
208       'function
209       (list 'function
210             (if (fun-type-wild-args type)
211                 '*
212                 (unparse-args-types type))
213             (type-specifier
214              (fun-type-returns type)))))
215
216 (!define-type-method (function :simple-subtypep) (type1 type2)
217    (flet ((fun-type-simple-p (type)
218             (not (or (fun-type-rest type)
219                      (fun-type-keyp type))))
220           (every-csubtypep (types1 types2)
221             (loop
222                for a1 in types1
223                for a2 in types2
224                do (multiple-value-bind (res sure-p)
225                       (csubtypep a1 a2)
226                     (unless res (return (values res sure-p))))
227                finally (return (values t t)))))
228      (macrolet ((3and (x y)
229                   `(multiple-value-bind (val1 win1)
230                        ,x
231                      (if (and (not val1) win1)
232                          (values nil t)
233                          (multiple-value-bind (val2 win2)
234                              ,y
235                            (if (and val1 val2)
236                                (values t t)
237                                (values nil (or win1 win2))))))))
238        (3and (values-subtypep (fun-type-returns type1)
239                               (fun-type-returns type2))
240              (cond ((fun-type-wild-args type2)
241                     (values t t))
242                    ((fun-type-wild-args type1)
243                     (values nil t))
244                    ((not (or (fun-type-simple-p type1)
245                              (fun-type-simple-p type2)))
246                     (values nil nil))
247                    ((not (and (= (length (fun-type-required type1))
248                                  (length (fun-type-required type2)))
249                               (= (length (fun-type-optional type1))
250                                  (length (fun-type-optional type2)))))
251                     (values nil t))
252                    (t (3and (every-csubtypep (fun-type-required type1)
253                                              (fun-type-required type2))
254                             (every-csubtypep (fun-type-optional type1)
255                                              (fun-type-optional type2)))))))))
256
257 (!define-superclasses function ((function)) !cold-init-forms)
258
259 ;;; The union or intersection of two FUNCTION types is FUNCTION.
260 (!define-type-method (function :simple-union2) (type1 type2)
261   (declare (ignore type1 type2))
262   (specifier-type 'function))
263 (!define-type-method (function :simple-intersection2) (type1 type2)
264   (declare (ignore type1 type2))
265   (specifier-type 'function))
266
267 ;;; ### Not very real, but good enough for redefining transforms
268 ;;; according to type:
269 (!define-type-method (function :simple-=) (type1 type2)
270   (values (equalp type1 type2) t))
271
272 (!define-type-class constant :inherits values)
273
274 (!define-type-method (constant :unparse) (type)
275   `(constant-arg ,(type-specifier (constant-type-type type))))
276
277 (!define-type-method (constant :simple-=) (type1 type2)
278   (type= (constant-type-type type1) (constant-type-type type2)))
279
280 (!def-type-translator constant-arg (type)
281   (make-constant-type :type (specifier-type type)))
282
283 ;;; Given a LAMBDA-LIST-like values type specification and an ARGS-TYPE
284 ;;; structure, fill in the slots in the structure accordingly. This is
285 ;;; used for both FUNCTION and VALUES types.
286 (declaim (ftype (function (list args-type) (values)) parse-args-types))
287 (defun parse-args-types (lambda-list result)
288   (multiple-value-bind (required optional restp rest keyp keys allowp auxp aux)
289       (parse-lambda-list-like-thing lambda-list)
290     (declare (ignore aux)) ; since we require AUXP=NIL
291     (when auxp
292       (error "&AUX in a FUNCTION or VALUES type: ~S." lambda-list))
293     (setf (args-type-required result) (mapcar #'specifier-type required))
294     (setf (args-type-optional result) (mapcar #'specifier-type optional))
295     (setf (args-type-rest result) (if restp (specifier-type rest) nil))
296     (setf (args-type-keyp result) keyp)
297     (collect ((key-info))
298       (dolist (key keys)
299         (unless (proper-list-of-length-p key 2)
300           (error "Keyword type description is not a two-list: ~S." key))
301         (let ((kwd (first key)))
302           (when (find kwd (key-info) :key #'key-info-name)
303             (error "~@<repeated keyword ~S in lambda list: ~2I~_~S~:>"
304                    kwd lambda-list))
305           (key-info (make-key-info :name kwd
306                                    :type (specifier-type (second key))))))
307       (setf (args-type-keywords result) (key-info)))
308     (setf (args-type-allowp result) allowp)
309     (values)))
310
311 ;;; Return the lambda-list-like type specification corresponding
312 ;;; to an ARGS-TYPE.
313 (declaim (ftype (function (args-type) list) unparse-args-types))
314 (defun unparse-args-types (type)
315   (collect ((result))
316
317     (dolist (arg (args-type-required type))
318       (result (type-specifier arg)))
319
320     (when (args-type-optional type)
321       (result '&optional)
322       (dolist (arg (args-type-optional type))
323         (result (type-specifier arg))))
324
325     (when (args-type-rest type)
326       (result '&rest)
327       (result (type-specifier (args-type-rest type))))
328
329     (when (args-type-keyp type)
330       (result '&key)
331       (dolist (key (args-type-keywords type))
332         (result (list (key-info-name key)
333                       (type-specifier (key-info-type key))))))
334
335     (when (args-type-allowp type)
336       (result '&allow-other-keys))
337
338     (result)))
339
340 (!def-type-translator function (&optional (args '*) (result '*))
341   (let ((res (make-fun-type :returns (values-specifier-type result))))
342     (if (eq args '*)
343         (setf (fun-type-wild-args res) t)
344         (parse-args-types args res))
345     res))
346
347 (!def-type-translator values (&rest values)
348   (let ((res (make-values-type)))
349     (parse-args-types values res)
350     res))
351 \f
352 ;;;; VALUES types interfaces
353 ;;;;
354 ;;;; We provide a few special operations that can be meaningfully used
355 ;;;; on VALUES types (as well as on any other type).
356
357 ;;; Return the type of the first value indicated by TYPE. This is used
358 ;;; by people who don't want to have to deal with VALUES types.
359 #!-sb-fluid (declaim (freeze-type values-type))
360 ; (inline single-value-type))
361 (defun single-value-type (type)
362   (declare (type ctype type))
363   (cond ((values-type-p type)
364          (or (car (args-type-required type))
365              (if (args-type-optional type)
366                  (type-union (car (args-type-optional type))
367                              (specifier-type 'null)))
368              (args-type-rest type)
369              (specifier-type 'null)))
370         ((eq type *wild-type*)
371          *universal-type*)
372         (t
373          type)))
374
375 ;;; Return the minimum number of arguments that a function can be
376 ;;; called with, and the maximum number or NIL. If not a function
377 ;;; type, return NIL, NIL.
378 (defun fun-type-nargs (type)
379   (declare (type ctype type))
380   (if (fun-type-p type)
381       (let ((fixed (length (args-type-required type))))
382         (if (or (args-type-rest type)
383                 (args-type-keyp type)
384                 (args-type-allowp type))
385             (values fixed nil)
386             (values fixed (+ fixed (length (args-type-optional type))))))
387       (values nil nil)))
388
389 ;;; Determine whether TYPE corresponds to a definite number of values.
390 ;;; The first value is a list of the types for each value, and the
391 ;;; second value is the number of values. If the number of values is
392 ;;; not fixed, then return NIL and :UNKNOWN.
393 (defun values-types (type)
394   (declare (type ctype type))
395   (cond ((eq type *wild-type*)
396          (values nil :unknown))
397         ((not (values-type-p type))
398          (values (list type) 1))
399         ((or (args-type-optional type)
400              (args-type-rest type)
401              (args-type-keyp type)
402              (args-type-allowp type))
403          (values nil :unknown))
404         (t
405          (let ((req (args-type-required type)))
406            (values (mapcar #'single-value-type req) (length req))))))
407
408 ;;; Return two values:
409 ;;; 1. A list of all the positional (fixed and optional) types.
410 ;;; 2. The &REST type (if any). If keywords allowed, *UNIVERSAL-TYPE*.
411 ;;;    If no keywords or &REST, then the DEFAULT-TYPE.
412 (defun values-type-types (type &optional (default-type *empty-type*))
413   (declare (type values-type type))
414   (values (append (args-type-required type)
415                   (args-type-optional type))
416           (cond ((args-type-keyp type) *universal-type*)
417                 ((args-type-rest type))
418                 (t
419                  default-type))))
420
421 ;;; Return a list of OPERATION applied to the types in TYPES1 and
422 ;;; TYPES2, padding with REST2 as needed. TYPES1 must not be shorter
423 ;;; than TYPES2. The second value is T if OPERATION always returned a
424 ;;; true second value.
425 (defun fixed-values-op (types1 types2 rest2 operation)
426   (declare (list types1 types2) (type ctype rest2) (type function operation))
427   (let ((exact t))
428     (values (mapcar (lambda (t1 t2)
429                       (multiple-value-bind (res win)
430                           (funcall operation t1 t2)
431                         (unless win
432                           (setq exact nil))
433                         res))
434                     types1
435                     (append types2
436                             (make-list (- (length types1) (length types2))
437                                        :initial-element rest2)))
438             exact)))
439
440 ;;; If Type isn't a values type, then make it into one:
441 ;;;    <type>  ==>  (values type &rest t)
442 (defun coerce-to-values (type)
443   (declare (type ctype type))
444   (if (values-type-p type)
445       type
446       (make-values-type :required (list type) :rest *universal-type*)))
447
448 ;;; Do the specified OPERATION on TYPE1 and TYPE2, which may be any
449 ;;; type, including VALUES types. With VALUES types such as:
450 ;;;    (VALUES a0 a1)
451 ;;;    (VALUES b0 b1)
452 ;;; we compute the more useful result
453 ;;;    (VALUES (<operation> a0 b0) (<operation> a1 b1))
454 ;;; rather than the precise result
455 ;;;    (<operation> (values a0 a1) (values b0 b1))
456 ;;; This has the virtue of always keeping the VALUES type specifier
457 ;;; outermost, and retains all of the information that is really
458 ;;; useful for static type analysis. We want to know what is always
459 ;;; true of each value independently. It is worthless to know that if
460 ;;; the first value is B0 then the second will be B1.
461 ;;;
462 ;;; If the VALUES count signatures differ, then we produce a result with
463 ;;; the required VALUE count chosen by NREQ when applied to the number
464 ;;; of required values in TYPE1 and TYPE2. Any &KEY values become
465 ;;; &REST T (anyone who uses keyword values deserves to lose.)
466 ;;;
467 ;;; The second value is true if the result is definitely empty or if
468 ;;; OPERATION returned true as its second value each time we called
469 ;;; it. Since we approximate the intersection of VALUES types, the
470 ;;; second value being true doesn't mean the result is exact.
471 (defun args-type-op (type1 type2 operation nreq default-type)
472   (declare (type ctype type1 type2 default-type)
473            (type function operation nreq))
474   (if (or (values-type-p type1) (values-type-p type2))
475       (let ((type1 (coerce-to-values type1))
476             (type2 (coerce-to-values type2)))
477         (multiple-value-bind (types1 rest1)
478             (values-type-types type1 default-type)
479           (multiple-value-bind (types2 rest2)
480               (values-type-types type2 default-type)
481             (multiple-value-bind (rest rest-exact)
482                 (funcall operation rest1 rest2)
483               (multiple-value-bind (res res-exact)
484                   (if (< (length types1) (length types2))
485                       (fixed-values-op types2 types1 rest1 operation)
486                       (fixed-values-op types1 types2 rest2 operation))
487                 (let* ((req (funcall nreq
488                                      (length (args-type-required type1))
489                                      (length (args-type-required type2))))
490                        (required (subseq res 0 req))
491                        (opt (subseq res req))
492                        (opt-last (position rest opt :test-not #'type=
493                                            :from-end t)))
494                   (if (find *empty-type* required :test #'type=)
495                       (values *empty-type* t)
496                       (values (make-values-type
497                                :required required
498                                :optional (if opt-last
499                                              (subseq opt 0 (1+ opt-last))
500                                              ())
501                                :rest (if (eq rest default-type) nil rest))
502                               (and rest-exact res-exact)))))))))
503       (funcall operation type1 type2)))
504
505 ;;; Do a union or intersection operation on types that might be values
506 ;;; types. The result is optimized for utility rather than exactness,
507 ;;; but it is guaranteed that it will be no smaller (more restrictive)
508 ;;; than the precise result.
509 ;;;
510 ;;; The return convention seems to be analogous to
511 ;;; TYPES-EQUAL-OR-INTERSECT. -- WHN 19990910.
512 (defun-cached (values-type-union :hash-function type-cache-hash
513                                  :hash-bits 8
514                                  :default nil
515                                  :init-wrapper !cold-init-forms)
516               ((type1 eq) (type2 eq))
517   (declare (type ctype type1 type2))
518   (cond ((or (eq type1 *wild-type*) (eq type2 *wild-type*)) *wild-type*)
519         ((eq type1 *empty-type*) type2)
520         ((eq type2 *empty-type*) type1)
521         (t
522          (values (args-type-op type1 type2 #'type-union #'min *empty-type*)))))
523 (defun-cached (values-type-intersection :hash-function type-cache-hash
524                                         :hash-bits 8
525                                         :values 2
526                                         :default (values nil :empty)
527                                         :init-wrapper !cold-init-forms)
528               ((type1 eq) (type2 eq))
529   (declare (type ctype type1 type2))
530   (cond ((eq type1 *wild-type*) (values type2 t))
531         ((eq type2 *wild-type*) (values type1 t))
532         (t
533          (args-type-op type1 type2
534                        #'type-intersection
535                        #'max
536                        (specifier-type 'null)))))
537
538 ;;; This is like TYPES-EQUAL-OR-INTERSECT, except that it sort of
539 ;;; works on VALUES types. Note that due to the semantics of
540 ;;; VALUES-TYPE-INTERSECTION, this might return (VALUES T T) when
541 ;;; there isn't really any intersection.
542 (defun values-types-equal-or-intersect (type1 type2)
543   (cond ((or (eq type1 *empty-type*) (eq type2 *empty-type*))
544          (values t t))
545         ((or (values-type-p type1) (values-type-p type2))
546          (multiple-value-bind (res win) (values-type-intersection type1 type2)
547            (values (not (eq res *empty-type*))
548                    win)))
549         (t
550          (types-equal-or-intersect type1 type2))))
551
552 ;;; a SUBTYPEP-like operation that can be used on any types, including
553 ;;; VALUES types
554 (defun-cached (values-subtypep :hash-function type-cache-hash
555                                :hash-bits 8
556                                :values 2
557                                :default (values nil :empty)
558                                :init-wrapper !cold-init-forms)
559               ((type1 eq) (type2 eq))
560   (declare (type ctype type1 type2))
561   (cond ((eq type2 *wild-type*) (values t t))
562         ((eq type1 *wild-type*)
563          (values (eq type2 *universal-type*) t))
564         ((not (values-types-equal-or-intersect type1 type2))
565          (values nil t))
566         (t
567          (if (or (values-type-p type1) (values-type-p type2))
568              (let ((type1 (coerce-to-values type1))
569                    (type2 (coerce-to-values type2)))
570                (multiple-value-bind (types1 rest1) (values-type-types type1)
571                  (multiple-value-bind (types2 rest2) (values-type-types type2)
572                    (cond ((< (length (values-type-required type1))
573                              (length (values-type-required type2)))
574                           (values nil t))
575                          ((< (length types1) (length types2))
576                           (values nil nil))
577                          ((or (values-type-keyp type1)
578                               (values-type-keyp type2))
579                           (values nil nil))
580                          (t
581                           (do ((t1 types1 (rest t1))
582                                (t2 types2 (rest t2)))
583                               ((null t2)
584                                (csubtypep rest1 rest2))
585                             (multiple-value-bind (res win-p)
586                                 (csubtypep (first t1) (first t2))
587                               (unless win-p
588                                 (return (values nil nil)))
589                               (unless res
590                                 (return (values nil t))))))))))
591              (csubtypep type1 type2)))))
592 \f
593 ;;;; type method interfaces
594
595 ;;; like SUBTYPEP, only works on CTYPE structures
596 (defun-cached (csubtypep :hash-function type-cache-hash
597                          :hash-bits 8
598                          :values 2
599                          :default (values nil :empty)
600                          :init-wrapper !cold-init-forms)
601               ((type1 eq) (type2 eq))
602   (declare (type ctype type1 type2))
603   (cond ((or (eq type1 type2)
604              (eq type1 *empty-type*)
605              (eq type2 *wild-type*))
606          (values t t))
607         ((eq type1 *wild-type*)
608          (values nil t))
609         (t
610          (!invoke-type-method :simple-subtypep :complex-subtypep-arg2
611                               type1 type2
612                               :complex-arg1 :complex-subtypep-arg1))))
613
614 ;;; Just parse the type specifiers and call CSUBTYPE.
615 (defun sb!xc:subtypep (type1 type2)
616   #!+sb-doc
617   "Return two values indicating the relationship between type1 and type2.
618   If values are T and T, type1 definitely is a subtype of type2.
619   If values are NIL and T, type1 definitely is not a subtype of type2.
620   If values are NIL and NIL, it couldn't be determined."
621   (csubtypep (specifier-type type1) (specifier-type type2)))
622
623 ;;; If two types are definitely equivalent, return true. The second
624 ;;; value indicates whether the first value is definitely correct.
625 ;;; This should only fail in the presence of HAIRY types.
626 (defun-cached (type= :hash-function type-cache-hash
627                      :hash-bits 8
628                      :values 2
629                      :default (values nil :empty)
630                      :init-wrapper !cold-init-forms)
631               ((type1 eq) (type2 eq))
632   (declare (type ctype type1 type2))
633   (if (eq type1 type2)
634       (values t t)
635       (!invoke-type-method :simple-= :complex-= type1 type2)))
636
637 ;;; Not exactly the negation of TYPE=, since when the relationship is
638 ;;; uncertain, we still return NIL, NIL. This is useful in cases where
639 ;;; the conservative assumption is =.
640 (defun type/= (type1 type2)
641   (declare (type ctype type1 type2))
642   (multiple-value-bind (res win) (type= type1 type2)
643     (if win
644         (values (not res) t)
645         (values nil nil))))
646
647 ;;; the type method dispatch case of TYPE-UNION2
648 (defun %type-union2 (type1 type2)
649   ;; As in %TYPE-INTERSECTION2, it seems to be a good idea to give
650   ;; both argument orders a chance at COMPLEX-INTERSECTION2. Unlike
651   ;; %TYPE-INTERSECTION2, though, I don't have a specific case which
652   ;; demonstrates this is actually necessary. Also unlike
653   ;; %TYPE-INTERSECTION2, there seems to be no need to distinguish
654   ;; between not finding a method and having a method return NIL.
655   (flet ((1way (x y)
656            (!invoke-type-method :simple-union2 :complex-union2
657                                 x y
658                                 :default nil)))
659     (declare (inline 1way))
660     (or (1way type1 type2)
661         (1way type2 type1))))
662
663 ;;; Find a type which includes both types. Any inexactness is
664 ;;; represented by the fuzzy element types; we return a single value
665 ;;; that is precise to the best of our knowledge. This result is
666 ;;; simplified into the canonical form, thus is not a UNION-TYPE
667 ;;; unless we find no other way to represent the result.
668 (defun-cached (type-union2 :hash-function type-cache-hash
669                            :hash-bits 8
670                            :init-wrapper !cold-init-forms)
671               ((type1 eq) (type2 eq))
672   ;; KLUDGE: This was generated from TYPE-INTERSECTION2 by Ye Olde Cut And
673   ;; Paste technique of programming. If it stays around (as opposed to
674   ;; e.g. fading away in favor of some CLOS solution) the shared logic
675   ;; should probably become shared code. -- WHN 2001-03-16
676   (declare (type ctype type1 type2))
677   (cond ((eq type1 type2)
678          type1)
679         ((csubtypep type1 type2) type2)
680         ((csubtypep type2 type1) type1)
681         ((or (union-type-p type1)
682              (union-type-p type2))
683          ;; Unions of UNION-TYPE should have the UNION-TYPE-TYPES
684          ;; values broken out and united separately. The full TYPE-UNION
685          ;; function knows how to do this, so let it handle it.
686          (type-union type1 type2))
687         (t
688          ;; the ordinary case: we dispatch to type methods
689          (%type-union2 type1 type2))))
690
691 ;;; the type method dispatch case of TYPE-INTERSECTION2
692 (defun %type-intersection2 (type1 type2)
693   ;; We want to give both argument orders a chance at
694   ;; COMPLEX-INTERSECTION2. Without that, the old CMU CL type
695   ;; methods could give noncommutative results, e.g.
696   ;;   (TYPE-INTERSECTION2 *EMPTY-TYPE* SOME-HAIRY-TYPE)
697   ;;     => NIL, NIL
698   ;;   (TYPE-INTERSECTION2 SOME-HAIRY-TYPE *EMPTY-TYPE*)
699   ;;     => #<NAMED-TYPE NIL>, T
700   ;; We also need to distinguish between the case where we found a
701   ;; type method, and it returned NIL, and the case where we fell
702   ;; through without finding any type method. An example of the first
703   ;; case is the intersection of a HAIRY-TYPE with some ordinary type.
704   ;; An example of the second case is the intersection of two
705   ;; completely-unrelated types, e.g. CONS and NUMBER, or SYMBOL and
706   ;; ARRAY.
707   ;;
708   ;; (Why yes, CLOS probably *would* be nicer..)
709   (flet ((1way (x y)
710            (!invoke-type-method :simple-intersection2 :complex-intersection2
711                                 x y
712                                 :default :no-type-method-found)))
713     (declare (inline 1way))
714     (let ((xy (1way type1 type2)))
715       (or (and (not (eql xy :no-type-method-found)) xy)
716           (let ((yx (1way type2 type1)))
717             (or (and (not (eql yx :no-type-method-found)) yx)
718                 (cond ((and (eql xy :no-type-method-found)
719                             (eql yx :no-type-method-found))
720                        *empty-type*)
721                       (t
722                        (aver (and (not xy) (not yx))) ; else handled above
723                        nil))))))))
724
725 (defun-cached (type-intersection2 :hash-function type-cache-hash
726                                   :hash-bits 8
727                                   :values 1
728                                   :default nil
729                                   :init-wrapper !cold-init-forms)
730               ((type1 eq) (type2 eq))
731   (declare (type ctype type1 type2))
732   (cond ((eq type1 type2)
733          ;; FIXME: For some reason, this doesn't catch e.g. type1 =
734          ;; type2 = (SPECIFIER-TYPE
735          ;; 'SOME-UNKNOWN-TYPE). Investigate. - CSR, 2002-04-10
736          type1)
737         ((or (intersection-type-p type1)
738              (intersection-type-p type2))
739          ;; Intersections of INTERSECTION-TYPE should have the
740          ;; INTERSECTION-TYPE-TYPES values broken out and intersected
741          ;; separately. The full TYPE-INTERSECTION function knows how
742          ;; to do that, so let it handle it.
743          (type-intersection type1 type2))
744         (t
745          ;; the ordinary case: we dispatch to type methods
746          (%type-intersection2 type1 type2))))
747
748 ;;; Return as restrictive and simple a type as we can discover that is
749 ;;; no more restrictive than the intersection of TYPE1 and TYPE2. At
750 ;;; worst, we arbitrarily return one of the arguments as the first
751 ;;; value (trying not to return a hairy type).
752 (defun type-approx-intersection2 (type1 type2)
753   (cond ((type-intersection2 type1 type2))
754         ((hairy-type-p type1) type2)
755         (t type1)))
756
757 ;;; a test useful for checking whether a derived type matches a
758 ;;; declared type
759 ;;;
760 ;;; The first value is true unless the types don't intersect and
761 ;;; aren't equal. The second value is true if the first value is
762 ;;; definitely correct. NIL is considered to intersect with any type.
763 ;;; If T is a subtype of either type, then we also return T, T. This
764 ;;; way we recognize that hairy types might intersect with T.
765 (defun types-equal-or-intersect (type1 type2)
766   (declare (type ctype type1 type2))
767   (if (or (eq type1 *empty-type*) (eq type2 *empty-type*))
768       (values t t)
769       (let ((intersection2 (type-intersection2 type1 type2)))
770         (cond ((not intersection2)
771                (if (or (csubtypep *universal-type* type1)
772                        (csubtypep *universal-type* type2))
773                    (values t t)
774                    (values t nil)))
775               ((eq intersection2 *empty-type*) (values nil t))
776               (t (values t t))))))
777
778 ;;; Return a Common Lisp type specifier corresponding to the TYPE
779 ;;; object.
780 (defun type-specifier (type)
781   (declare (type ctype type))
782   (funcall (type-class-unparse (type-class-info type)) type))
783
784 ;;; (VALUES-SPECIFIER-TYPE and SPECIFIER-TYPE moved from here to
785 ;;; early-type.lisp by WHN ca. 19990201.)
786
787 ;;; Take a list of type specifiers, computing the translation of each
788 ;;; specifier and defining it as a builtin type.
789 (declaim (ftype (function (list) (values)) precompute-types))
790 (defun precompute-types (specs)
791   (dolist (spec specs)
792     (let ((res (specifier-type spec)))
793       (unless (unknown-type-p res)
794         (setf (info :type :builtin spec) res)
795         ;; KLUDGE: the three copies of this idiom in this file (and
796         ;; the one in class.lisp as at sbcl-0.7.4.1x) should be
797         ;; coalesced, or perhaps the error-detecting code that
798         ;; disallows redefinition of :PRIMITIVE types should be
799         ;; rewritten to use *TYPE-SYSTEM-FINALIZED* (rather than
800         ;; *TYPE-SYSTEM-INITIALIZED*). The effect of this is not to
801         ;; cause redefinition errors when precompute-types is called
802         ;; for a second time while building the target compiler using
803         ;; the cross-compiler. -- CSR, trying to explain why this
804         ;; isn't completely wrong, 2002-06-07
805         (setf (info :type :kind spec) #+sb-xc-host :defined #-sb-xc-host :primitive))))
806   (values))
807 \f
808 ;;;; general TYPE-UNION and TYPE-INTERSECTION operations
809 ;;;;
810 ;;;; These are fully general operations on CTYPEs: they'll always
811 ;;;; return a CTYPE representing the result.
812
813 ;;; shared logic for unions and intersections: Stuff TYPE into the
814 ;;; vector TYPES, finding pairs of types which can be simplified by
815 ;;; SIMPLIFY2 (TYPE-UNION2 or TYPE-INTERSECTION2) and replacing them
816 ;;; by their simplified forms.
817 (defun accumulate1-compound-type (type types %compound-type-p simplify2)
818   (declare (type ctype type))
819   (declare (type (vector ctype) types))
820   (declare (type function simplify2))
821   ;; Any input object satisfying %COMPOUND-TYPE-P should've been
822   ;; broken into components before it reached us.
823   (aver (not (funcall %compound-type-p type)))
824   (dotimes (i (length types) (vector-push-extend type types))
825     (let ((simplified2 (funcall simplify2 type (aref types i))))
826       (when simplified2
827         ;; Discard the old (AREF TYPES I).
828         (setf (aref types i) (vector-pop types))
829         ;; Merge the new SIMPLIFIED2 into TYPES, by tail recursing.
830         ;; (Note that the tail recursion is indirect: we go through
831         ;; ACCUMULATE, not ACCUMULATE1, so that if SIMPLIFIED2 is
832         ;; handled properly if it satisfies %COMPOUND-TYPE-P.)
833         (return (accumulate-compound-type simplified2
834                                           types
835                                           %compound-type-p
836                                           simplify2)))))
837   ;; Voila.
838   (values))
839
840 ;;; shared logic for unions and intersections: Use
841 ;;; ACCUMULATE1-COMPOUND-TYPE to merge TYPE into TYPES, either
842 ;;; all in one step or, if %COMPOUND-TYPE-P is satisfied,
843 ;;; component by component.
844 (defun accumulate-compound-type (type types %compound-type-p simplify2)
845   (declare (type function %compound-type-p simplify2))
846   (flet ((accumulate1 (x)
847            (accumulate1-compound-type x types %compound-type-p simplify2)))
848     (declare (inline accumulate1))
849     (if (funcall %compound-type-p type)
850         (map nil #'accumulate1 (compound-type-types type))
851         (accumulate1 type)))
852   (values))
853
854 ;;; shared logic for unions and intersections: Return a vector of
855 ;;; types representing the same types as INPUT-TYPES, but with 
856 ;;; COMPOUND-TYPEs satisfying %COMPOUND-TYPE-P broken up into their
857 ;;; component types, and with any SIMPLY2 simplifications applied.
858 (defun simplified-compound-types (input-types %compound-type-p simplify2)
859   (let ((simplified-types (make-array (length input-types)
860                                       :fill-pointer 0
861                                       :adjustable t
862                                       :element-type 'ctype
863                                       ;; (This INITIAL-ELEMENT shouldn't
864                                       ;; matter, but helps avoid type
865                                       ;; warnings at compile time.)
866                                       :initial-element *empty-type*)))
867     (dolist (input-type input-types)
868       (accumulate-compound-type input-type
869                                 simplified-types
870                                 %compound-type-p
871                                 simplify2))
872     simplified-types))
873
874 ;;; shared logic for unions and intersections: Make a COMPOUND-TYPE
875 ;;; object whose components are the types in TYPES, or skip to special
876 ;;; cases when TYPES is short.
877 (defun make-compound-type-or-something (constructor types enumerable identity)
878   (declare (type function constructor))
879   (declare (type (vector ctype) types))
880   (declare (type ctype identity))
881   (case (length types)
882     (0 identity)
883     (1 (aref types 0))
884     (t (funcall constructor
885                 enumerable
886                 ;; FIXME: This should be just (COERCE TYPES 'LIST), but as
887                 ;; of sbcl-0.6.11.17 the COERCE optimizer is really
888                 ;; brain-dead, so that would generate a full call to
889                 ;; SPECIFIER-TYPE at runtime, so we get into bootstrap
890                 ;; problems in cold init because 'LIST is a compound
891                 ;; type, so we need to MAKE-COMPOUND-TYPE-OR-SOMETHING
892                 ;; before we know what 'LIST is. Once the COERCE
893                 ;; optimizer is less brain-dead, we can make this
894                 ;; (COERCE TYPES 'LIST) again.
895                 #+sb-xc-host (coerce types 'list)
896                 #-sb-xc-host (coerce-to-list types)))))
897
898 (defun maybe-distribute-one-union (union-type types)
899   (let* ((intersection (apply #'type-intersection types))
900          (union (mapcar (lambda (x) (type-intersection x intersection))
901                         (union-type-types union-type))))
902     (if (notany (lambda (x) (or (hairy-type-p x)
903                                 (intersection-type-p x)))
904                 union)
905         union
906         nil)))
907
908 (defun type-intersection (&rest input-types)
909   (let ((simplified-types (simplified-compound-types input-types
910                                                      #'intersection-type-p
911                                                      #'type-intersection2)))
912     (declare (type (vector ctype) simplified-types))
913     ;; We want to have a canonical representation of types (or failing
914     ;; that, punt to HAIRY-TYPE). Canonical representation would have
915     ;; intersections inside unions but not vice versa, since you can
916     ;; always achieve that by the distributive rule. But we don't want
917     ;; to just apply the distributive rule, since it would be too easy
918     ;; to end up with unreasonably huge type expressions. So instead
919     ;; we try to generate a simple type by distributing the union; if
920     ;; the type can't be made simple, we punt to HAIRY-TYPE.
921     (if (and (> (length simplified-types) 1)
922              (some #'union-type-p simplified-types))
923         (let* ((first-union (find-if #'union-type-p simplified-types))
924                (other-types (coerce (remove first-union simplified-types) 'list))
925                (distributed (maybe-distribute-one-union first-union other-types)))
926           (if distributed
927               (apply #'type-union distributed)
928               (make-hairy-type
929                :specifier `(and ,@(map 'list #'type-specifier simplified-types)))))
930         (make-compound-type-or-something #'%make-intersection-type
931                                          simplified-types
932                                          (some #'type-enumerable
933                                                simplified-types)
934                                          *universal-type*))))
935
936 (defun type-union (&rest input-types)
937   (let ((simplified-types (simplified-compound-types input-types
938                                                      #'union-type-p
939                                                      #'type-union2)))
940     (make-compound-type-or-something #'%make-union-type
941                                      simplified-types
942                                      (every #'type-enumerable simplified-types)
943                                      *empty-type*)))
944 \f
945 ;;;; built-in types
946
947 (!define-type-class named)
948
949 (defvar *wild-type*)
950 (defvar *empty-type*)
951 (defvar *universal-type*)
952 (defvar *universal-fun-type*)
953 (!cold-init-forms
954  (macrolet ((frob (name var)
955               `(progn
956                  (setq ,var (make-named-type :name ',name))
957                  (setf (info :type :kind ',name) #+sb-xc-host :defined #-sb-xc-host :primitive)
958                  (setf (info :type :builtin ',name) ,var))))
959    ;; KLUDGE: In ANSI, * isn't really the name of a type, it's just a
960    ;; special symbol which can be stuck in some places where an
961    ;; ordinary type can go, e.g. (ARRAY * 1) instead of (ARRAY T 1).
962    ;; At some point, in order to become more standard, we should
963    ;; convert all the classic CMU CL legacy *s and *WILD-TYPE*s into
964    ;; Ts and *UNIVERSAL-TYPE*s.
965    (frob * *wild-type*)
966    (frob nil *empty-type*)
967    (frob t *universal-type*))
968  (setf *universal-fun-type*
969        (make-fun-type :wild-args t
970                       :returns *wild-type*)))
971
972 (!define-type-method (named :simple-=) (type1 type2)
973   ;; FIXME: BUG 85: This assertion failed when I added it in
974   ;; sbcl-0.6.11.13. It probably shouldn't fail; but for now it's
975   ;; just commented out.
976   ;;(aver (not (eq type1 *wild-type*))) ; * isn't really a type.
977   (values (eq type1 type2) t))
978
979 (!define-type-method (named :simple-subtypep) (type1 type2)
980   (aver (not (eq type1 *wild-type*))) ; * isn't really a type.
981   (values (or (eq type1 *empty-type*) (eq type2 *wild-type*)) t))
982
983 (!define-type-method (named :complex-subtypep-arg1) (type1 type2)
984   ;; This AVER causes problems if we write accurate methods for the
985   ;; union (and possibly intersection) types which then delegate to
986   ;; us; while a user shouldn't get here, because of the odd status of
987   ;; *wild-type* a type-intersection executed by the compiler can. -
988   ;; CSR, 2002-04-10
989   ;;
990   ;; (aver (not (eq type1 *wild-type*))) ; * isn't really a type.
991   (cond ((eq type1 *empty-type*)
992          t)
993         (;; When TYPE2 might be the universal type in disguise
994          (type-might-contain-other-types-p type2)
995          ;; Now that the UNION and HAIRY COMPLEX-SUBTYPEP-ARG2 methods
996          ;; can delegate to us (more or less as CALL-NEXT-METHOD) when
997          ;; they're uncertain, we can't just barf on COMPOUND-TYPE and
998          ;; HAIRY-TYPEs as we used to. Instead we deal with the
999          ;; problem (where at least part of the problem is cases like
1000          ;;   (SUBTYPEP T '(SATISFIES FOO))
1001          ;; or
1002          ;;   (SUBTYPEP T '(AND (SATISFIES FOO) (SATISFIES BAR)))
1003          ;; where the second type is a hairy type like SATISFIES, or
1004          ;; is a compound type which might contain a hairy type) by
1005          ;; returning uncertainty.
1006          (values nil nil))
1007         (t
1008          ;; By elimination, TYPE1 is the universal type.
1009          (aver (or (eq type1 *wild-type*) (eq type1 *universal-type*)))
1010          ;; This case would have been picked off by the SIMPLE-SUBTYPEP
1011          ;; method, and so shouldn't appear here.
1012          (aver (not (eq type2 *universal-type*)))
1013          ;; Since TYPE2 is not EQ *UNIVERSAL-TYPE* and is not the
1014          ;; universal type in disguise, TYPE2 is not a superset of TYPE1.
1015          (values nil t))))
1016
1017 (!define-type-method (named :complex-subtypep-arg2) (type1 type2)
1018   (aver (not (eq type2 *wild-type*))) ; * isn't really a type.
1019   (cond ((eq type2 *universal-type*)
1020          (values t t))
1021         ((hairy-type-p type1)
1022          (invoke-complex-subtypep-arg1-method type1 type2))
1023         (t
1024          ;; FIXME: This seems to rely on there only being 2 or 3
1025          ;; HAIRY-TYPE values, and the exclusion of various
1026          ;; possibilities above. It would be good to explain it and/or
1027          ;; rewrite it so that it's clearer.
1028          (values (not (eq type2 *empty-type*)) t))))
1029
1030 (!define-type-method (named :complex-intersection2) (type1 type2)
1031   ;; FIXME: This assertion failed when I added it in sbcl-0.6.11.13.
1032   ;; Perhaps when bug 85 is fixed it can be reenabled.
1033   ;;(aver (not (eq type2 *wild-type*))) ; * isn't really a type.
1034   (hierarchical-intersection2 type1 type2))
1035
1036 (!define-type-method (named :complex-union2) (type1 type2)
1037   ;; Perhaps when bug 85 is fixed this can be reenabled.
1038   ;;(aver (not (eq type2 *wild-type*))) ; * isn't really a type.
1039   (hierarchical-union2 type1 type2))
1040
1041 (!define-type-method (named :unparse) (x)
1042   (named-type-name x))
1043 \f
1044 ;;;; hairy and unknown types
1045
1046 (!define-type-method (hairy :unparse) (x)
1047   (hairy-type-specifier x))
1048     
1049 (!define-type-method (hairy :simple-subtypep) (type1 type2)
1050   (let ((hairy-spec1 (hairy-type-specifier type1))
1051         (hairy-spec2 (hairy-type-specifier type2)))
1052     (cond ((and (consp hairy-spec1) (eq (car hairy-spec1) 'not)
1053                 (consp hairy-spec2) (eq (car hairy-spec2) 'not))
1054            (csubtypep (specifier-type (cadr hairy-spec2))
1055                       (specifier-type (cadr hairy-spec1))))
1056           ((equal hairy-spec1 hairy-spec2)
1057            (values t t))
1058           (t
1059            (values nil nil)))))
1060
1061 (!define-type-method (hairy :complex-subtypep-arg2) (type1 type2)
1062   (let ((hairy-spec (hairy-type-specifier type2)))
1063     (cond ((and (consp hairy-spec) (eq (car hairy-spec) 'not))
1064            (let* ((complement-type2 (specifier-type (cadr hairy-spec)))
1065                   (intersection2 (type-intersection2 type1
1066                                                      complement-type2)))
1067              (if intersection2
1068                  (values (eq intersection2 *empty-type*) t)
1069                  (invoke-complex-subtypep-arg1-method type1 type2))))
1070           (t
1071            (invoke-complex-subtypep-arg1-method type1 type2)))))
1072
1073 (!define-type-method (hairy :complex-subtypep-arg1) (type1 type2)
1074   ;; "Incrementally extended heuristic algorithms tend inexorably toward the
1075   ;; incomprehensible." -- http://www.unlambda.com/~james/lambda/lambda.txt
1076   (let ((hairy-spec (hairy-type-specifier type1)))
1077      (cond ((and (consp hairy-spec) (eq (car hairy-spec) 'not))
1078             ;; You may not believe this. I couldn't either. But then I
1079             ;; sat down and drew lots of Venn diagrams. Comments
1080             ;; involving a and b refer to the call (subtypep '(not a)
1081             ;; 'b) -- CSR, 2002-02-27.
1082             (block nil
1083               ;; (Several logical truths in this block are true as
1084               ;; long as b/=T. As of sbcl-0.7.1.28, it seems
1085               ;; impossible to construct a case with b=T where we
1086               ;; actually reach this type method, but we'll test for
1087               ;; and exclude this case anyway, since future
1088               ;; maintenance might make it possible for it to end up
1089               ;; in this code.)
1090               (multiple-value-bind (equal certain)
1091                   (type= type2 (specifier-type t))
1092                 (unless certain
1093                   (return (values nil nil)))
1094                 (when equal
1095                   (return (values t t))))
1096               (let ((complement-type1 (specifier-type (cadr hairy-spec))))
1097                 ;; Do the special cases first, in order to give us a
1098                 ;; chance if subtype/supertype relationships are hairy.
1099                 (multiple-value-bind (equal certain) 
1100                     (type= complement-type1 type2)
1101                   ;; If a = b, ~a is not a subtype of b (unless b=T,
1102                   ;; which was excluded above).
1103                   (unless certain
1104                     (return (values nil nil)))
1105                   (when equal
1106                     (return (values nil t))))
1107                 ;; KLUDGE: ANSI requires that the SUBTYPEP result
1108                 ;; between any two built-in atomic type specifiers
1109                 ;; never be uncertain. This is hard to do cleanly for
1110                 ;; the built-in types whose definitions include
1111                 ;; (NOT FOO), i.e. CONS and RATIO. However, we can do
1112                 ;; it with this hack, which uses our global knowledge
1113                 ;; that our implementation of the type system uses
1114                 ;; disjoint implementation types to represent disjoint
1115                 ;; sets (except when types are contained in other types).
1116                 ;; (This is a KLUDGE because it's fragile. Various
1117                 ;; changes in internal representation in the type
1118                 ;; system could make it start confidently returning
1119                 ;; incorrect results.) -- WHN 2002-03-08
1120                 (unless (or (type-might-contain-other-types-p complement-type1)
1121                             (type-might-contain-other-types-p type2))
1122                   ;; Because of the way our types which don't contain
1123                   ;; other types are disjoint subsets of the space of
1124                   ;; possible values, (SUBTYPEP '(NOT AA) 'B)=NIL when
1125                   ;; AA and B are simple (and B is not T, as checked above).
1126                   (return (values nil t)))
1127                 ;; The old (TYPE= TYPE1 TYPE2) branch would never be
1128                 ;; taken, as TYPE1 and TYPE2 will only be equal if
1129                 ;; they're both NOT types, and then the
1130                 ;; :SIMPLE-SUBTYPEP method would be used instead.
1131                 ;; But a CSUBTYPEP relationship might still hold:
1132                 (multiple-value-bind (equal certain)
1133                     (csubtypep complement-type1 type2)
1134                   ;; If a is a subtype of b, ~a is not a subtype of b
1135                   ;; (unless b=T, which was excluded above).
1136                   (unless certain
1137                     (return (values nil nil)))
1138                   (when equal
1139                     (return (values nil t))))
1140                 (multiple-value-bind (equal certain)
1141                     (csubtypep type2 complement-type1)
1142                   ;; If b is a subtype of a, ~a is not a subtype of b.
1143                   ;; (FIXME: That's not true if a=T. Do we know at
1144                   ;; this point that a is not T?)
1145                   (unless certain
1146                     (return (values nil nil)))
1147                   (when equal
1148                     (return (values nil t))))
1149                 ;; old CSR comment ca. 0.7.2, now obsoleted by the
1150                 ;; SIMPLE-CTYPE? KLUDGE case above:
1151                 ;;   Other cases here would rely on being able to catch
1152                 ;;   all possible cases, which the fragility of this
1153                 ;;   type system doesn't inspire me; for instance, if a
1154                 ;;   is type= to ~b, then we want T, T; if this is not
1155                 ;;   the case and the types are disjoint (have an
1156                 ;;   intersection of *empty-type*) then we want NIL, T;
1157                 ;;   else if the union of a and b is the
1158                 ;;   *universal-type* then we want T, T. So currently we
1159                 ;;   still claim to be unsure about e.g. (subtypep '(not
1160                 ;;   fixnum) 'single-float).
1161                 )))
1162            (t
1163             (values nil nil)))))
1164
1165 (!define-type-method (hairy :complex-=) (type1 type2)
1166   (declare (ignore type1 type2))
1167   (values nil nil))
1168
1169 (!define-type-method (hairy :simple-intersection2 :complex-intersection2)
1170                      (type1 type2)
1171   (if (type= type1 type2)
1172       type1
1173       nil))
1174
1175 (!define-type-method (hairy :simple-=) (type1 type2)
1176   (if (equal (hairy-type-specifier type1)
1177              (hairy-type-specifier type2))
1178       (values t t)
1179       (values nil nil)))
1180
1181 (!def-type-translator not (&whole whole type)
1182   (declare (ignore type))
1183   ;; Check legality of arguments.
1184   (destructuring-bind (not typespec) whole
1185     (declare (ignore not))
1186     (let ((spec (type-specifier (specifier-type typespec)))) ; must be legal typespec
1187       (if (and (listp spec) (eq (car spec) 'not))
1188           ;; canonicalize (not (not foo))
1189           (specifier-type (cadr spec))
1190           (make-hairy-type :specifier whole)))))
1191
1192 (!def-type-translator satisfies (&whole whole fun)
1193   (declare (ignore fun))
1194   ;; Check legality of arguments.
1195   (destructuring-bind (satisfies predicate-name) whole
1196     (declare (ignore satisfies))
1197     (unless (symbolp predicate-name)
1198       (error 'simple-type-error
1199              :datum predicate-name
1200              :expected-type 'symbol
1201              :format-control "~S is not a symbol."
1202              :format-arguments (list predicate-name))))
1203   ;; Create object.
1204   (make-hairy-type :specifier whole))
1205 \f
1206 ;;;; numeric types
1207
1208 (!define-type-class number)
1209
1210 (!define-type-method (number :simple-=) (type1 type2)
1211   (values
1212    (and (eq (numeric-type-class type1) (numeric-type-class type2))
1213         (eq (numeric-type-format type1) (numeric-type-format type2))
1214         (eq (numeric-type-complexp type1) (numeric-type-complexp type2))
1215         (equal (numeric-type-low type1) (numeric-type-low type2))
1216         (equal (numeric-type-high type1) (numeric-type-high type2)))
1217    t))
1218
1219 (!define-type-method (number :unparse) (type)
1220   (let* ((complexp (numeric-type-complexp type))
1221          (low (numeric-type-low type))
1222          (high (numeric-type-high type))
1223          (base (case (numeric-type-class type)
1224                  (integer 'integer)
1225                  (rational 'rational)
1226                  (float (or (numeric-type-format type) 'float))
1227                  (t 'real))))
1228     (let ((base+bounds
1229            (cond ((and (eq base 'integer) high low)
1230                   (let ((high-count (logcount high))
1231                         (high-length (integer-length high)))
1232                     (cond ((= low 0)
1233                            (cond ((= high 0) '(integer 0 0))
1234                                  ((= high 1) 'bit)
1235                                  ((and (= high-count high-length)
1236                                        (plusp high-length))
1237                                   `(unsigned-byte ,high-length))
1238                                  (t
1239                                   `(mod ,(1+ high)))))
1240                           ((and (= low sb!xc:most-negative-fixnum)
1241                                 (= high sb!xc:most-positive-fixnum))
1242                            'fixnum)
1243                           ((and (= low (lognot high))
1244                                 (= high-count high-length)
1245                                 (> high-count 0))
1246                            `(signed-byte ,(1+ high-length)))
1247                           (t
1248                            `(integer ,low ,high)))))
1249                  (high `(,base ,(or low '*) ,high))
1250                  (low
1251                   (if (and (eq base 'integer) (= low 0))
1252                       'unsigned-byte
1253                       `(,base ,low)))
1254                  (t base))))
1255       (ecase complexp
1256         (:real
1257          base+bounds)
1258         (:complex
1259          (if (eq base+bounds 'real)
1260              'complex
1261              `(complex ,base+bounds)))
1262         ((nil)
1263          (aver (eq base+bounds 'real))
1264          'number)))))
1265
1266 ;;; Return true if X is "less than or equal" to Y, taking open bounds
1267 ;;; into consideration. CLOSED is the predicate used to test the bound
1268 ;;; on a closed interval (e.g. <=), and OPEN is the predicate used on
1269 ;;; open bounds (e.g. <). Y is considered to be the outside bound, in
1270 ;;; the sense that if it is infinite (NIL), then the test succeeds,
1271 ;;; whereas if X is infinite, then the test fails (unless Y is also
1272 ;;; infinite).
1273 ;;;
1274 ;;; This is for comparing bounds of the same kind, e.g. upper and
1275 ;;; upper. Use NUMERIC-BOUND-TEST* for different kinds of bounds.
1276 #!-negative-zero-is-not-zero
1277 (defmacro numeric-bound-test (x y closed open)
1278   `(cond ((not ,y) t)
1279          ((not ,x) nil)
1280          ((consp ,x)
1281           (if (consp ,y)
1282               (,closed (car ,x) (car ,y))
1283               (,closed (car ,x) ,y)))
1284          (t
1285           (if (consp ,y)
1286               (,open ,x (car ,y))
1287               (,closed ,x ,y)))))
1288
1289 #!+negative-zero-is-not-zero
1290 (defmacro numeric-bound-test-zero (op x y)
1291   `(if (and (zerop ,x) (zerop ,y) (floatp ,x) (floatp ,y))
1292        (,op (float-sign ,x) (float-sign ,y))
1293        (,op ,x ,y)))
1294
1295 #!+negative-zero-is-not-zero
1296 (defmacro numeric-bound-test (x y closed open)
1297   `(cond ((not ,y) t)
1298          ((not ,x) nil)
1299          ((consp ,x)
1300           (if (consp ,y)
1301               (numeric-bound-test-zero ,closed (car ,x) (car ,y))
1302               (numeric-bound-test-zero ,closed (car ,x) ,y)))
1303          (t
1304           (if (consp ,y)
1305               (numeric-bound-test-zero ,open ,x (car ,y))
1306               (numeric-bound-test-zero ,closed ,x ,y)))))
1307
1308 ;;; This is used to compare upper and lower bounds. This is different
1309 ;;; from the same-bound case:
1310 ;;; -- Since X = NIL is -infinity, whereas y = NIL is +infinity, we
1311 ;;;    return true if *either* arg is NIL.
1312 ;;; -- an open inner bound is "greater" and also squeezes the interval,
1313 ;;;    causing us to use the OPEN test for those cases as well.
1314 #!-negative-zero-is-not-zero
1315 (defmacro numeric-bound-test* (x y closed open)
1316   `(cond ((not ,y) t)
1317          ((not ,x) t)
1318          ((consp ,x)
1319           (if (consp ,y)
1320               (,open (car ,x) (car ,y))
1321               (,open (car ,x) ,y)))
1322          (t
1323           (if (consp ,y)
1324               (,open ,x (car ,y))
1325               (,closed ,x ,y)))))
1326
1327 #!+negative-zero-is-not-zero
1328 (defmacro numeric-bound-test* (x y closed open)
1329   `(cond ((not ,y) t)
1330          ((not ,x) t)
1331          ((consp ,x)
1332           (if (consp ,y)
1333               (numeric-bound-test-zero ,open (car ,x) (car ,y))
1334               (numeric-bound-test-zero ,open (car ,x) ,y)))
1335          (t
1336           (if (consp ,y)
1337               (numeric-bound-test-zero ,open ,x (car ,y))
1338               (numeric-bound-test-zero ,closed ,x ,y)))))
1339
1340 ;;; Return whichever of the numeric bounds X and Y is "maximal"
1341 ;;; according to the predicates CLOSED (e.g. >=) and OPEN (e.g. >).
1342 ;;; This is only meaningful for maximizing like bounds, i.e. upper and
1343 ;;; upper. If MAX-P is true, then we return NIL if X or Y is NIL,
1344 ;;; otherwise we return the other arg.
1345 (defmacro numeric-bound-max (x y closed open max-p)
1346   (once-only ((n-x x)
1347               (n-y y))
1348     `(cond ((not ,n-x) ,(if max-p nil n-y))
1349            ((not ,n-y) ,(if max-p nil n-x))
1350            ((consp ,n-x)
1351             (if (consp ,n-y)
1352                 (if (,closed (car ,n-x) (car ,n-y)) ,n-x ,n-y)
1353                 (if (,open (car ,n-x) ,n-y) ,n-x ,n-y)))
1354            (t
1355             (if (consp ,n-y)
1356                 (if (,open (car ,n-y) ,n-x) ,n-y ,n-x)
1357                 (if (,closed ,n-y ,n-x) ,n-y ,n-x))))))
1358
1359 (!define-type-method (number :simple-subtypep) (type1 type2)
1360   (let ((class1 (numeric-type-class type1))
1361         (class2 (numeric-type-class type2))
1362         (complexp2 (numeric-type-complexp type2))
1363         (format2 (numeric-type-format type2))
1364         (low1 (numeric-type-low type1))
1365         (high1 (numeric-type-high type1))
1366         (low2 (numeric-type-low type2))
1367         (high2 (numeric-type-high type2)))
1368     ;; If one is complex and the other isn't, they are disjoint.
1369     (cond ((not (or (eq (numeric-type-complexp type1) complexp2)
1370                     (null complexp2)))
1371            (values nil t))
1372           ;; If the classes are specified and different, the types are
1373           ;; disjoint unless type2 is rational and type1 is integer.
1374           ((not (or (eq class1 class2)
1375                     (null class2)
1376                     (and (eq class1 'integer)
1377                          (eq class2 'rational))))
1378            (values nil t))
1379           ;; If the float formats are specified and different, the types
1380           ;; are disjoint.
1381           ((not (or (eq (numeric-type-format type1) format2)
1382                     (null format2)))
1383            (values nil t))
1384           ;; Check the bounds.
1385           ((and (numeric-bound-test low1 low2 >= >)
1386                 (numeric-bound-test high1 high2 <= <))
1387            (values t t))
1388           (t
1389            (values nil t)))))
1390
1391 (!define-superclasses number ((number)) !cold-init-forms)
1392
1393 ;;; If the high bound of LOW is adjacent to the low bound of HIGH,
1394 ;;; then return true, otherwise NIL.
1395 (defun numeric-types-adjacent (low high)
1396   (let ((low-bound (numeric-type-high low))
1397         (high-bound (numeric-type-low high)))
1398     (cond ((not (and low-bound high-bound)) nil)
1399           ((and (consp low-bound) (consp high-bound)) nil)
1400           ((consp low-bound)
1401            #!-negative-zero-is-not-zero
1402            (let ((low-value (car low-bound)))
1403              (or (eql low-value high-bound)
1404                  (and (eql low-value -0f0) (eql high-bound 0f0))
1405                  (and (eql low-value 0f0) (eql high-bound -0f0))
1406                  (and (eql low-value -0d0) (eql high-bound 0d0))
1407                  (and (eql low-value 0d0) (eql high-bound -0d0))))
1408            #!+negative-zero-is-not-zero
1409            (eql (car low-bound) high-bound))
1410           ((consp high-bound)
1411            #!-negative-zero-is-not-zero
1412            (let ((high-value (car high-bound)))
1413              (or (eql high-value low-bound)
1414                  (and (eql high-value -0f0) (eql low-bound 0f0))
1415                  (and (eql high-value 0f0) (eql low-bound -0f0))
1416                  (and (eql high-value -0d0) (eql low-bound 0d0))
1417                  (and (eql high-value 0d0) (eql low-bound -0d0))))
1418            #!+negative-zero-is-not-zero
1419            (eql (car high-bound) low-bound))
1420           #!+negative-zero-is-not-zero
1421           ((or (and (eql low-bound -0f0) (eql high-bound 0f0))
1422                (and (eql low-bound -0d0) (eql high-bound 0d0))))
1423           ((and (eq (numeric-type-class low) 'integer)
1424                 (eq (numeric-type-class high) 'integer))
1425            (eql (1+ low-bound) high-bound))
1426           (t
1427            nil))))
1428
1429 ;;; Return a numeric type that is a supertype for both TYPE1 and TYPE2.
1430 ;;;
1431 ;;; ### Note: we give up early to keep from dropping lots of information on
1432 ;;; the floor by returning overly general types.
1433 (!define-type-method (number :simple-union2) (type1 type2)
1434   (declare (type numeric-type type1 type2))
1435   (cond ((csubtypep type1 type2) type2)
1436         ((csubtypep type2 type1) type1)
1437         (t
1438          (let ((class1 (numeric-type-class type1))
1439                (format1 (numeric-type-format type1))
1440                (complexp1 (numeric-type-complexp type1))
1441                (class2 (numeric-type-class type2))
1442                (format2 (numeric-type-format type2))
1443                (complexp2 (numeric-type-complexp type2)))
1444            (when (and (eq class1 class2)
1445                       (eq format1 format2)
1446                       (eq complexp1 complexp2)
1447                       (or (numeric-types-intersect type1 type2)
1448                           (numeric-types-adjacent type1 type2)
1449                           (numeric-types-adjacent type2 type1)))
1450              (make-numeric-type
1451               :class class1
1452               :format format1
1453               :complexp complexp1
1454               :low (numeric-bound-max (numeric-type-low type1)
1455                                       (numeric-type-low type2)
1456                                       <= < t)
1457               :high (numeric-bound-max (numeric-type-high type1)
1458                                        (numeric-type-high type2)
1459                                        >= > t)))))))
1460
1461 (!cold-init-forms
1462   (setf (info :type :kind 'number) #+sb-xc-host :defined #-sb-xc-host :primitive)
1463   (setf (info :type :builtin 'number)
1464         (make-numeric-type :complexp nil)))
1465
1466 (!def-type-translator complex (&optional (typespec '*))
1467   (if (eq typespec '*)
1468       (make-numeric-type :complexp :complex)
1469       (labels ((not-numeric ()
1470                  (error "The component type for COMPLEX is not numeric: ~S"
1471                         typespec))
1472                (not-real ()
1473                  (error "The component type for COMPLEX is not real: ~S"
1474                         typespec))
1475                (complex1 (component-type)
1476                  (unless (numeric-type-p component-type)
1477                    (not-numeric))
1478                  (when (eq (numeric-type-complexp component-type) :complex)
1479                    (not-real))
1480                  (modified-numeric-type component-type :complexp :complex))
1481                (complex-union (component)
1482                  (unless (numberp component)
1483                    (not-numeric))
1484                  ;; KLUDGE: This TYPECASE more or less does
1485                  ;; (UPGRADED-COMPLEX-PART-TYPE (TYPE-OF COMPONENT)),
1486                  ;; (plus a small hack to treat (EQL COMPONENT 0) specially)
1487                  ;; but uses logic cut and pasted from the DEFUN of
1488                  ;; UPGRADED-COMPLEX-PART-TYPE. That's fragile, because
1489                  ;; changing the definition of UPGRADED-COMPLEX-PART-TYPE
1490                  ;; would tend to break the code here. Unfortunately,
1491                  ;; though, reusing UPGRADED-COMPLEX-PART-TYPE here
1492                  ;; would cause another kind of fragility, because
1493                  ;; ANSI's definition of TYPE-OF is so weak that e.g.
1494                  ;; (UPGRADED-COMPLEX-PART-TYPE (TYPE-OF 1/2)) could
1495                  ;; end up being (UPGRADED-COMPLEX-PART-TYPE 'REAL)
1496                  ;; instead of (UPGRADED-COMPLEX-PART-TYPE 'RATIONAL).
1497                  ;; So using TYPE-OF would mean that ANSI-conforming
1498                  ;; maintenance changes in TYPE-OF could break the code here.
1499                  ;; It's not clear how best to fix this. -- WHN 2002-01-21,
1500                  ;; trying to summarize CSR's concerns in his patch
1501                  (typecase component
1502                    (complex (error "The component type for COMPLEX (EQL X) ~
1503                                     is complex: ~S"
1504                                    component))
1505                    ((eql 0) (specifier-type nil)) ; as required by ANSI
1506                    (single-float (specifier-type '(complex single-float)))
1507                    (double-float (specifier-type '(complex double-float)))
1508                    #!+long-float
1509                    (long-float (specifier-type '(complex long-float)))
1510                    (rational (specifier-type '(complex rational)))
1511                    (t (specifier-type '(complex real))))))
1512         (let ((ctype (specifier-type typespec)))
1513           (typecase ctype
1514             (numeric-type (complex1 ctype))
1515             (union-type (apply #'type-union
1516                                ;; FIXME: This code could suffer from
1517                                ;; (admittedly very obscure) cases of
1518                                ;; bug 145 e.g. when TYPE is
1519                                ;;   (OR (AND INTEGER (SATISFIES ODDP))
1520                                ;;       (AND FLOAT (SATISFIES FOO))
1521                                ;; and not even report the problem very well.
1522                                (mapcar #'complex1
1523                                        (union-type-types ctype))))
1524             ;; MEMBER-TYPE is almost the same as UNION-TYPE, but
1525             ;; there's a gotcha: (COMPLEX (EQL 0)) is, according to
1526             ;; ANSI, equal to type NIL, the empty set.
1527             (member-type (apply #'type-union
1528                                 (mapcar #'complex-union
1529                                         (member-type-members ctype))))
1530             (t
1531              (multiple-value-bind (subtypep certainly)
1532                  (csubtypep ctype (specifier-type 'real))
1533                (if (and (not subtypep) certainly)
1534                    (not-real)
1535                    ;; ANSI just says that TYPESPEC is any subtype of
1536                    ;; type REAL, not necessarily a NUMERIC-TYPE. In
1537                    ;; particular, at this point TYPESPEC could legally be
1538                    ;; an intersection type like (AND REAL (SATISFIES ODDP)),
1539                    ;; in which case we fall through the logic above and
1540                    ;; end up here, stumped.
1541                    (bug "~@<(known bug #145): The type ~S is too hairy to be 
1542                          used for a COMPLEX component.~:@>"
1543                         typespec)))))))))
1544
1545 ;;; If X is *, return NIL, otherwise return the bound, which must be a
1546 ;;; member of TYPE or a one-element list of a member of TYPE.
1547 #!-sb-fluid (declaim (inline canonicalized-bound))
1548 (defun canonicalized-bound (bound type)
1549   (cond ((eq bound '*) nil)
1550         ((or (sb!xc:typep bound type)
1551              (and (consp bound)
1552                   (sb!xc:typep (car bound) type)
1553                   (null (cdr bound))))
1554           bound)
1555         (t
1556          (error "Bound is not ~S, a ~S or a list of a ~S: ~S"
1557                 '*
1558                 type
1559                 type
1560                 bound))))
1561
1562 (!def-type-translator integer (&optional (low '*) (high '*))
1563   (let* ((l (canonicalized-bound low 'integer))
1564          (lb (if (consp l) (1+ (car l)) l))
1565          (h (canonicalized-bound high 'integer))
1566          (hb (if (consp h) (1- (car h)) h)))
1567     (if (and hb lb (< hb lb))
1568         ;; previously we threw an error here:
1569         ;; (error "Lower bound ~S is greater than upper bound ~S." l h))
1570         ;; but ANSI doesn't say anything about that, so:
1571         *empty-type*
1572       (make-numeric-type :class 'integer
1573                          :complexp :real
1574                          :enumerable (not (null (and l h)))
1575                          :low lb
1576                          :high hb))))
1577
1578 (defmacro !def-bounded-type (type class format)
1579   `(!def-type-translator ,type (&optional (low '*) (high '*))
1580      (let ((lb (canonicalized-bound low ',type))
1581            (hb (canonicalized-bound high ',type)))
1582        (if (not (numeric-bound-test* lb hb <= <))
1583            ;; as above, previously we did
1584            ;; (error "Lower bound ~S is not less than upper bound ~S." low high))
1585            ;; but it is correct to do
1586            *empty-type*
1587          (make-numeric-type :class ',class :format ',format :low lb :high hb)))))
1588
1589 (!def-bounded-type rational rational nil)
1590
1591 ;;; Unlike CMU CL, we represent the types FLOAT and REAL as
1592 ;;; UNION-TYPEs of more primitive types, in order to make
1593 ;;; type representation more unique, avoiding problems in the
1594 ;;; simplification of things like
1595 ;;;   (subtypep '(or (single-float -1.0 1.0) (single-float 0.1))
1596 ;;;             '(or (real -1 7) (single-float 0.1) (single-float -1.0 1.0)))
1597 ;;; When we allowed REAL to remain as a separate NUMERIC-TYPE,
1598 ;;; it was too easy for the first argument to be simplified to
1599 ;;; '(SINGLE-FLOAT -1.0), and for the second argument to be simplified
1600 ;;; to '(OR (REAL -1 7) (SINGLE-FLOAT 0.1)) and then for the
1601 ;;; SUBTYPEP to fail (returning NIL,T instead of T,T) because
1602 ;;; the first argument can't be seen to be a subtype of any of the
1603 ;;; terms in the second argument.
1604 ;;;
1605 ;;; The old CMU CL way was:
1606 ;;;   (!def-bounded-type float float nil)
1607 ;;;   (!def-bounded-type real nil nil)
1608 ;;;
1609 ;;; FIXME: If this new way works for a while with no weird new
1610 ;;; problems, we can go back and rip out support for separate FLOAT
1611 ;;; and REAL flavors of NUMERIC-TYPE. The new way was added in
1612 ;;; sbcl-0.6.11.22, 2001-03-21.
1613 ;;;
1614 ;;; FIXME: It's probably necessary to do something to fix the
1615 ;;; analogous problem with INTEGER and RATIONAL types. Perhaps
1616 ;;; bounded RATIONAL types should be represented as (OR RATIO INTEGER).
1617 (defun coerce-bound (bound type inner-coerce-bound-fun)
1618   (declare (type function inner-coerce-bound-fun))
1619   (cond ((eql bound '*)
1620          bound)
1621         ((consp bound)
1622          (destructuring-bind (inner-bound) bound
1623            (list (funcall inner-coerce-bound-fun inner-bound type))))
1624         (t
1625          (funcall inner-coerce-bound-fun bound type))))
1626 (defun inner-coerce-real-bound (bound type)
1627   (ecase type
1628     (rational (rationalize bound))
1629     (float (if (floatp bound)
1630                bound
1631                ;; Coerce to the widest float format available, to
1632                ;; avoid unnecessary loss of precision:
1633                (coerce bound 'long-float)))))
1634 (defun coerced-real-bound (bound type)
1635   (coerce-bound bound type #'inner-coerce-real-bound))
1636 (defun coerced-float-bound (bound type)
1637   (coerce-bound bound type #'coerce))
1638 (!def-type-translator real (&optional (low '*) (high '*))
1639   (specifier-type `(or (float ,(coerced-real-bound  low 'float)
1640                               ,(coerced-real-bound high 'float))
1641                        (rational ,(coerced-real-bound  low 'rational)
1642                                  ,(coerced-real-bound high 'rational)))))
1643 (!def-type-translator float (&optional (low '*) (high '*))
1644   (specifier-type 
1645    `(or (single-float ,(coerced-float-bound  low 'single-float)
1646                       ,(coerced-float-bound high 'single-float))
1647         (double-float ,(coerced-float-bound  low 'double-float)
1648                       ,(coerced-float-bound high 'double-float))
1649         #!+long-float ,(error "stub: no long float support yet"))))
1650
1651 (defmacro !define-float-format (f)
1652   `(!def-bounded-type ,f float ,f))
1653
1654 (!define-float-format short-float)
1655 (!define-float-format single-float)
1656 (!define-float-format double-float)
1657 (!define-float-format long-float)
1658
1659 (defun numeric-types-intersect (type1 type2)
1660   (declare (type numeric-type type1 type2))
1661   (let* ((class1 (numeric-type-class type1))
1662          (class2 (numeric-type-class type2))
1663          (complexp1 (numeric-type-complexp type1))
1664          (complexp2 (numeric-type-complexp type2))
1665          (format1 (numeric-type-format type1))
1666          (format2 (numeric-type-format type2))
1667          (low1 (numeric-type-low type1))
1668          (high1 (numeric-type-high type1))
1669          (low2 (numeric-type-low type2))
1670          (high2 (numeric-type-high type2)))
1671     ;; If one is complex and the other isn't, then they are disjoint.
1672     (cond ((not (or (eq complexp1 complexp2)
1673                     (null complexp1) (null complexp2)))
1674            nil)
1675           ;; If either type is a float, then the other must either be
1676           ;; specified to be a float or unspecified. Otherwise, they
1677           ;; are disjoint.
1678           ((and (eq class1 'float)
1679                 (not (member class2 '(float nil)))) nil)
1680           ((and (eq class2 'float)
1681                 (not (member class1 '(float nil)))) nil)
1682           ;; If the float formats are specified and different, the
1683           ;; types are disjoint.
1684           ((not (or (eq format1 format2) (null format1) (null format2)))
1685            nil)
1686           (t
1687            ;; Check the bounds. This is a bit odd because we must
1688            ;; always have the outer bound of the interval as the
1689            ;; second arg.
1690            (if (numeric-bound-test high1 high2 <= <)
1691                (or (and (numeric-bound-test low1 low2 >= >)
1692                         (numeric-bound-test* low1 high2 <= <))
1693                    (and (numeric-bound-test low2 low1 >= >)
1694                         (numeric-bound-test* low2 high1 <= <)))
1695                (or (and (numeric-bound-test* low2 high1 <= <)
1696                         (numeric-bound-test low2 low1 >= >))
1697                    (and (numeric-bound-test high2 high1 <= <)
1698                         (numeric-bound-test* high2 low1 >= >))))))))
1699
1700 ;;; Take the numeric bound X and convert it into something that can be
1701 ;;; used as a bound in a numeric type with the specified CLASS and
1702 ;;; FORMAT. If UP-P is true, then we round up as needed, otherwise we
1703 ;;; round down. UP-P true implies that X is a lower bound, i.e. (N) > N.
1704 ;;;
1705 ;;; This is used by NUMERIC-TYPE-INTERSECTION to mash the bound into
1706 ;;; the appropriate type number. X may only be a float when CLASS is
1707 ;;; FLOAT.
1708 ;;;
1709 ;;; ### Note: it is possible for the coercion to a float to overflow
1710 ;;; or underflow. This happens when the bound doesn't fit in the
1711 ;;; specified format. In this case, we should really return the
1712 ;;; appropriate {Most | Least}-{Positive | Negative}-XXX-Float float
1713 ;;; of desired format. But these conditions aren't currently signalled
1714 ;;; in any useful way.
1715 ;;;
1716 ;;; Also, when converting an open rational bound into a float we
1717 ;;; should probably convert it to a closed bound of the closest float
1718 ;;; in the specified format. KLUDGE: In general, open float bounds are
1719 ;;; screwed up. -- (comment from original CMU CL)
1720 (defun round-numeric-bound (x class format up-p)
1721   (if x
1722       (let ((cx (if (consp x) (car x) x)))
1723         (ecase class
1724           ((nil rational) x)
1725           (integer
1726            (if (and (consp x) (integerp cx))
1727                (if up-p (1+ cx) (1- cx))
1728                (if up-p (ceiling cx) (floor cx))))
1729           (float
1730            (let ((res (if format (coerce cx format) (float cx))))
1731              (if (consp x) (list res) res)))))
1732       nil))
1733
1734 ;;; Handle the case of type intersection on two numeric types. We use
1735 ;;; TYPES-EQUAL-OR-INTERSECT to throw out the case of types with no
1736 ;;; intersection. If an attribute in TYPE1 is unspecified, then we use
1737 ;;; TYPE2's attribute, which must be at least as restrictive. If the
1738 ;;; types intersect, then the only attributes that can be specified
1739 ;;; and different are the class and the bounds.
1740 ;;;
1741 ;;; When the class differs, we use the more restrictive class. The
1742 ;;; only interesting case is RATIONAL/INTEGER, since RATIONAL includes
1743 ;;; INTEGER.
1744 ;;;
1745 ;;; We make the result lower (upper) bound the maximum (minimum) of
1746 ;;; the argument lower (upper) bounds. We convert the bounds into the
1747 ;;; appropriate numeric type before maximizing. This avoids possible
1748 ;;; confusion due to mixed-type comparisons (but I think the result is
1749 ;;; the same).
1750 (!define-type-method (number :simple-intersection2) (type1 type2)
1751   (declare (type numeric-type type1 type2))
1752   (if (numeric-types-intersect type1 type2)
1753       (let* ((class1 (numeric-type-class type1))
1754              (class2 (numeric-type-class type2))
1755              (class (ecase class1
1756                       ((nil) class2)
1757                       ((integer float) class1)
1758                       (rational (if (eq class2 'integer)
1759                                        'integer
1760                                        'rational))))
1761              (format (or (numeric-type-format type1)
1762                          (numeric-type-format type2))))
1763         (make-numeric-type
1764          :class class
1765          :format format
1766          :complexp (or (numeric-type-complexp type1)
1767                        (numeric-type-complexp type2))
1768          :low (numeric-bound-max
1769                (round-numeric-bound (numeric-type-low type1)
1770                                     class format t)
1771                (round-numeric-bound (numeric-type-low type2)
1772                                     class format t)
1773                > >= nil)
1774          :high (numeric-bound-max
1775                 (round-numeric-bound (numeric-type-high type1)
1776                                      class format nil)
1777                 (round-numeric-bound (numeric-type-high type2)
1778                                      class format nil)
1779                 < <= nil)))
1780       *empty-type*))
1781
1782 ;;; Given two float formats, return the one with more precision. If
1783 ;;; either one is null, return NIL.
1784 (defun float-format-max (f1 f2)
1785   (when (and f1 f2)
1786     (dolist (f *float-formats* (error "bad float format: ~S" f1))
1787       (when (or (eq f f1) (eq f f2))
1788         (return f)))))
1789
1790 ;;; Return the result of an operation on TYPE1 and TYPE2 according to
1791 ;;; the rules of numeric contagion. This is always NUMBER, some float
1792 ;;; format (possibly complex) or RATIONAL. Due to rational
1793 ;;; canonicalization, there isn't much we can do here with integers or
1794 ;;; rational complex numbers.
1795 ;;;
1796 ;;; If either argument is not a NUMERIC-TYPE, then return NUMBER. This
1797 ;;; is useful mainly for allowing types that are technically numbers,
1798 ;;; but not a NUMERIC-TYPE.
1799 (defun numeric-contagion (type1 type2)
1800   (if (and (numeric-type-p type1) (numeric-type-p type2))
1801       (let ((class1 (numeric-type-class type1))
1802             (class2 (numeric-type-class type2))
1803             (format1 (numeric-type-format type1))
1804             (format2 (numeric-type-format type2))
1805             (complexp1 (numeric-type-complexp type1))
1806             (complexp2 (numeric-type-complexp type2)))
1807         (cond ((or (null complexp1)
1808                    (null complexp2))
1809                (specifier-type 'number))
1810               ((eq class1 'float)
1811                (make-numeric-type
1812                 :class 'float
1813                 :format (ecase class2
1814                           (float (float-format-max format1 format2))
1815                           ((integer rational) format1)
1816                           ((nil)
1817                            ;; A double-float with any real number is a
1818                            ;; double-float.
1819                            #!-long-float
1820                            (if (eq format1 'double-float)
1821                              'double-float
1822                              nil)
1823                            ;; A long-float with any real number is a
1824                            ;; long-float.
1825                            #!+long-float
1826                            (if (eq format1 'long-float)
1827                              'long-float
1828                              nil)))
1829                 :complexp (if (or (eq complexp1 :complex)
1830                                   (eq complexp2 :complex))
1831                               :complex
1832                               :real)))
1833               ((eq class2 'float) (numeric-contagion type2 type1))
1834               ((and (eq complexp1 :real) (eq complexp2 :real))
1835                (make-numeric-type
1836                 :class (and class1 class2 'rational)
1837                 :complexp :real))
1838               (t
1839                (specifier-type 'number))))
1840       (specifier-type 'number)))
1841 \f
1842 ;;;; array types
1843
1844 (!define-type-class array)
1845
1846 ;;; What this does depends on the setting of the
1847 ;;; *USE-IMPLEMENTATION-TYPES* switch. If true, return the specialized
1848 ;;; element type, otherwise return the original element type.
1849 (defun specialized-element-type-maybe (type)
1850   (declare (type array-type type))
1851   (if *use-implementation-types*
1852       (array-type-specialized-element-type type)
1853       (array-type-element-type type)))
1854
1855 (!define-type-method (array :simple-=) (type1 type2)
1856   (if (or (unknown-type-p (array-type-element-type type1))
1857           (unknown-type-p (array-type-element-type type2)))
1858       (multiple-value-bind (equalp certainp)
1859           (type= (array-type-element-type type1)
1860                  (array-type-element-type type2))
1861         ;; by its nature, the call to TYPE= should never return NIL,
1862         ;; T, as we don't know what the UNKNOWN-TYPE will grow up to
1863         ;; be.  -- CSR, 2002-08-19
1864         (aver (not (and (not equalp) certainp)))
1865         (values equalp certainp))
1866       (values (and (equal (array-type-dimensions type1)
1867                           (array-type-dimensions type2))
1868                    (eq (array-type-complexp type1)
1869                        (array-type-complexp type2))
1870                    (type= (specialized-element-type-maybe type1)
1871                           (specialized-element-type-maybe type2)))
1872               t)))
1873
1874 (!define-type-method (array :unparse) (type)
1875   (let ((dims (array-type-dimensions type))
1876         (eltype (type-specifier (array-type-element-type type)))
1877         (complexp (array-type-complexp type)))
1878     (cond ((eq dims '*)
1879            (if (eq eltype '*)
1880                (if complexp 'array 'simple-array)
1881                (if complexp `(array ,eltype) `(simple-array ,eltype))))
1882           ((= (length dims) 1)
1883            (if complexp
1884                (if (eq (car dims) '*)
1885                    (case eltype
1886                      (bit 'bit-vector)
1887                      (base-char 'base-string)
1888                      (character 'string)
1889                      (* 'vector)
1890                      (t `(vector ,eltype)))
1891                    (case eltype
1892                      (bit `(bit-vector ,(car dims)))
1893                      (base-char `(base-string ,(car dims)))
1894                      (character `(string ,(car dims)))
1895                      (t `(vector ,eltype ,(car dims)))))
1896                (if (eq (car dims) '*)
1897                    (case eltype
1898                      (bit 'simple-bit-vector)
1899                      (base-char 'simple-base-string)
1900                      (character 'simple-string)
1901                      ((t) 'simple-vector)
1902                      (t `(simple-array ,eltype (*))))
1903                    (case eltype
1904                      (bit `(simple-bit-vector ,(car dims)))
1905                      (base-char `(simple-base-string ,(car dims)))
1906                      (character `(simple-string ,(car dims)))
1907                      ((t) `(simple-vector ,(car dims)))
1908                      (t `(simple-array ,eltype ,dims))))))
1909           (t
1910            (if complexp
1911                `(array ,eltype ,dims)
1912                `(simple-array ,eltype ,dims))))))
1913
1914 (!define-type-method (array :simple-subtypep) (type1 type2)
1915   (let ((dims1 (array-type-dimensions type1))
1916         (dims2 (array-type-dimensions type2))
1917         (complexp2 (array-type-complexp type2)))
1918     (cond (;; not subtypep unless dimensions are compatible
1919            (not (or (eq dims2 '*)
1920                     (and (not (eq dims1 '*))
1921                          ;; (sbcl-0.6.4 has trouble figuring out that
1922                          ;; DIMS1 and DIMS2 must be lists at this
1923                          ;; point, and knowing that is important to
1924                          ;; compiling EVERY efficiently.)
1925                          (= (length (the list dims1))
1926                             (length (the list dims2)))
1927                          (every (lambda (x y)
1928                                   (or (eq y '*) (eql x y)))
1929                                 (the list dims1)
1930                                 (the list dims2)))))
1931            (values nil t))
1932           ;; not subtypep unless complexness is compatible
1933           ((not (or (eq complexp2 :maybe)
1934                     (eq (array-type-complexp type1) complexp2)))
1935            (values nil t))
1936           ;; Since we didn't fail any of the tests above, we win
1937           ;; if the TYPE2 element type is wild.
1938           ((eq (array-type-element-type type2) *wild-type*)
1939            (values t t))
1940           (;; Since we didn't match any of the special cases above, we
1941            ;; can't give a good answer unless both the element types
1942            ;; have been defined.
1943            (or (unknown-type-p (array-type-element-type type1))
1944                (unknown-type-p (array-type-element-type type2)))
1945            (values nil nil))
1946           (;; Otherwise, the subtype relationship holds iff the
1947            ;; types are equal, and they're equal iff the specialized
1948            ;; element types are identical.
1949            t
1950            (values (type= (specialized-element-type-maybe type1)
1951                           (specialized-element-type-maybe type2))
1952                    t)))))
1953
1954 (!define-superclasses array
1955   ((string string)
1956    (vector vector)
1957    (array))
1958   !cold-init-forms)
1959
1960 (defun array-types-intersect (type1 type2)
1961   (declare (type array-type type1 type2))
1962   (let ((dims1 (array-type-dimensions type1))
1963         (dims2 (array-type-dimensions type2))
1964         (complexp1 (array-type-complexp type1))
1965         (complexp2 (array-type-complexp type2)))
1966     ;; See whether dimensions are compatible.
1967     (cond ((not (or (eq dims1 '*) (eq dims2 '*)
1968                     (and (= (length dims1) (length dims2))
1969                          (every (lambda (x y)
1970                                   (or (eq x '*) (eq y '*) (= x y)))
1971                                 dims1 dims2))))
1972            (values nil t))
1973           ;; See whether complexpness is compatible.
1974           ((not (or (eq complexp1 :maybe)
1975                     (eq complexp2 :maybe)
1976                     (eq complexp1 complexp2)))
1977            (values nil t))
1978           ;; Old comment:
1979           ;;
1980           ;;   If either element type is wild, then they intersect.
1981           ;;   Otherwise, the types must be identical.
1982           ;;
1983           ;; FIXME: There seems to have been a fair amount of
1984           ;; confusion about the distinction between requested element
1985           ;; type and specialized element type; here is one of
1986           ;; them. If we request an array to hold objects of an
1987           ;; unknown type, we can do no better than represent that
1988           ;; type as an array specialized on wild-type.  We keep the
1989           ;; requested element-type in the -ELEMENT-TYPE slot, and
1990           ;; *WILD-TYPE* in the -SPECIALIZED-ELEMENT-TYPE.  So, here,
1991           ;; we must test for the SPECIALIZED slot being *WILD-TYPE*,
1992           ;; not just the ELEMENT-TYPE slot.  Maybe the return value
1993           ;; in that specific case should be T, NIL?  Or maybe this
1994           ;; function should really be called
1995           ;; ARRAY-TYPES-COULD-POSSIBLY-INTERSECT?  In any case, this
1996           ;; was responsible for bug #123, and this whole issue could
1997           ;; do with a rethink and/or a rewrite.  -- CSR, 2002-08-21
1998           ((or (eq (array-type-specialized-element-type type1) *wild-type*)
1999                (eq (array-type-specialized-element-type type2) *wild-type*)
2000                (type= (specialized-element-type-maybe type1)
2001                       (specialized-element-type-maybe type2)))
2002
2003            (values t t))
2004           (t
2005            (values nil t)))))
2006
2007 (!define-type-method (array :simple-intersection2) (type1 type2)
2008   (declare (type array-type type1 type2))
2009   (if (array-types-intersect type1 type2)
2010       (let ((dims1 (array-type-dimensions type1))
2011             (dims2 (array-type-dimensions type2))
2012             (complexp1 (array-type-complexp type1))
2013             (complexp2 (array-type-complexp type2))
2014             (eltype1 (array-type-element-type type1))
2015             (eltype2 (array-type-element-type type2)))
2016         (specialize-array-type
2017          (make-array-type
2018           :dimensions (cond ((eq dims1 '*) dims2)
2019                             ((eq dims2 '*) dims1)
2020                             (t
2021                              (mapcar (lambda (x y) (if (eq x '*) y x))
2022                                      dims1 dims2)))
2023           :complexp (if (eq complexp1 :maybe) complexp2 complexp1)
2024           :element-type (if (eq eltype1 *wild-type*) eltype2 eltype1))))
2025       *empty-type*))
2026
2027 ;;; Check a supplied dimension list to determine whether it is legal,
2028 ;;; and return it in canonical form (as either '* or a list).
2029 (defun canonical-array-dimensions (dims)
2030   (typecase dims
2031     ((member *) dims)
2032     (integer
2033      (when (minusp dims)
2034        (error "Arrays can't have a negative number of dimensions: ~S" dims))
2035      (when (>= dims sb!xc:array-rank-limit)
2036        (error "array type with too many dimensions: ~S" dims))
2037      (make-list dims :initial-element '*))
2038     (list
2039      (when (>= (length dims) sb!xc:array-rank-limit)
2040        (error "array type with too many dimensions: ~S" dims))
2041      (dolist (dim dims)
2042        (unless (eq dim '*)
2043          (unless (and (integerp dim)
2044                       (>= dim 0)
2045                       (< dim sb!xc:array-dimension-limit))
2046            (error "bad dimension in array type: ~S" dim))))
2047      dims)
2048     (t
2049      (error "Array dimensions is not a list, integer or *:~%  ~S" dims))))
2050 \f
2051 ;;;; MEMBER types
2052
2053 (!define-type-class member)
2054
2055 (!define-type-method (member :unparse) (type)
2056   (let ((members (member-type-members type)))
2057     (cond
2058       ((equal members '(nil)) 'null)
2059       ((type= type (specifier-type 'standard-char)) 'standard-char)
2060       (t `(member ,@members)))))
2061
2062 (!define-type-method (member :simple-subtypep) (type1 type2)
2063   (values (subsetp (member-type-members type1) (member-type-members type2))
2064           t))
2065
2066 (!define-type-method (member :complex-subtypep-arg1) (type1 type2)
2067   (every/type (swapped-args-fun #'ctypep)
2068               type2
2069               (member-type-members type1)))
2070
2071 ;;; We punt if the odd type is enumerable and intersects with the
2072 ;;; MEMBER type. If not enumerable, then it is definitely not a
2073 ;;; subtype of the MEMBER type.
2074 (!define-type-method (member :complex-subtypep-arg2) (type1 type2)
2075   (cond ((not (type-enumerable type1)) (values nil t))
2076         ((types-equal-or-intersect type1 type2)
2077          (invoke-complex-subtypep-arg1-method type1 type2))
2078         (t (values nil t))))
2079
2080 (!define-type-method (member :simple-intersection2) (type1 type2)
2081   (let ((mem1 (member-type-members type1))
2082         (mem2 (member-type-members type2)))
2083     (cond ((subsetp mem1 mem2) type1)
2084           ((subsetp mem2 mem1) type2)
2085           (t
2086            (let ((res (intersection mem1 mem2)))
2087              (if res
2088                  (make-member-type :members res)
2089                  *empty-type*))))))
2090
2091 (!define-type-method (member :complex-intersection2) (type1 type2)
2092   (block punt                
2093     (collect ((members))
2094       (let ((mem2 (member-type-members type2)))
2095         (dolist (member mem2)
2096           (multiple-value-bind (val win) (ctypep member type1)
2097             (unless win
2098               (return-from punt nil))
2099             (when val (members member))))
2100         (cond ((subsetp mem2 (members)) type2)
2101               ((null (members)) *empty-type*)
2102               (t
2103                (make-member-type :members (members))))))))
2104
2105 ;;; We don't need a :COMPLEX-UNION2, since the only interesting case is
2106 ;;; a union type, and the member/union interaction is handled by the
2107 ;;; union type method.
2108 (!define-type-method (member :simple-union2) (type1 type2)
2109   (let ((mem1 (member-type-members type1))
2110         (mem2 (member-type-members type2)))
2111     (cond ((subsetp mem1 mem2) type2)
2112           ((subsetp mem2 mem1) type1)
2113           (t
2114            (make-member-type :members (union mem1 mem2))))))
2115
2116 (!define-type-method (member :simple-=) (type1 type2)
2117   (let ((mem1 (member-type-members type1))
2118         (mem2 (member-type-members type2)))
2119     (values (and (subsetp mem1 mem2)
2120                  (subsetp mem2 mem1))
2121             t)))
2122
2123 (!define-type-method (member :complex-=) (type1 type2)
2124   (if (type-enumerable type1)
2125       (multiple-value-bind (val win) (csubtypep type2 type1)
2126         (if (or val (not win))
2127             (values nil nil)
2128             (values nil t)))
2129       (values nil t)))
2130
2131 (!def-type-translator member (&rest members)
2132   (if members
2133     (make-member-type :members (remove-duplicates members))
2134     *empty-type*))
2135 \f
2136 ;;;; intersection types
2137 ;;;;
2138 ;;;; Until version 0.6.10.6, SBCL followed the original CMU CL approach
2139 ;;;; of punting on all AND types, not just the unreasonably complicated
2140 ;;;; ones. The change was motivated by trying to get the KEYWORD type
2141 ;;;; to behave sensibly:
2142 ;;;;    ;; reasonable definition
2143 ;;;;    (DEFTYPE KEYWORD () '(AND SYMBOL (SATISFIES KEYWORDP)))
2144 ;;;;    ;; reasonable behavior
2145 ;;;;    (AVER (SUBTYPEP 'KEYWORD 'SYMBOL))
2146 ;;;; Without understanding a little about the semantics of AND, we'd
2147 ;;;; get (SUBTYPEP 'KEYWORD 'SYMBOL)=>NIL,NIL and, for entirely
2148 ;;;; parallel reasons, (SUBTYPEP 'RATIO 'NUMBER)=>NIL,NIL. That's
2149 ;;;; not so good..)
2150 ;;;;
2151 ;;;; We still follow the example of CMU CL to some extent, by punting
2152 ;;;; (to the opaque HAIRY-TYPE) on sufficiently complicated types
2153 ;;;; involving AND.
2154
2155 (!define-type-class intersection)
2156
2157 ;;; A few intersection types have special names. The others just get
2158 ;;; mechanically unparsed.
2159 (!define-type-method (intersection :unparse) (type)
2160   (declare (type ctype type))
2161   (or (find type '(ratio bignum keyword) :key #'specifier-type :test #'type=)
2162       `(and ,@(mapcar #'type-specifier (intersection-type-types type)))))
2163
2164 ;;; shared machinery for type equality: true if every type in the set
2165 ;;; TYPES1 matches a type in the set TYPES2 and vice versa
2166 (defun type=-set (types1 types2)
2167   (flet (;; true if every type in the set X matches a type in the set Y
2168          (type<=-set (x y)
2169            (declare (type list x y))
2170            (every (lambda (xelement)
2171                     (position xelement y :test #'type=))
2172                   x)))
2173     (values (and (type<=-set types1 types2)
2174                  (type<=-set types2 types1))
2175             t)))
2176
2177 ;;; Two intersection types are equal if their subtypes are equal sets.
2178 ;;;
2179 ;;; FIXME: Might it be better to use
2180 ;;;   (AND (SUBTYPEP X Y) (SUBTYPEP Y X))
2181 ;;; instead, since SUBTYPEP is the usual relationship that we care
2182 ;;; most about, so it would be good to leverage any ingenuity there
2183 ;;; in this more obscure method?
2184 (!define-type-method (intersection :simple-=) (type1 type2)
2185   (type=-set (intersection-type-types type1)
2186              (intersection-type-types type2)))
2187
2188 (defun %intersection-complex-subtypep-arg1 (type1 type2)
2189   (any/type (swapped-args-fun #'csubtypep)
2190             type2
2191             (intersection-type-types type1)))
2192
2193 (!define-type-method (intersection :simple-subtypep) (type1 type2)
2194   (every/type #'%intersection-complex-subtypep-arg1
2195               type1
2196               (intersection-type-types type2)))
2197
2198 (!define-type-method (intersection :complex-subtypep-arg1) (type1 type2)
2199   (%intersection-complex-subtypep-arg1 type1 type2))
2200
2201 (!define-type-method (intersection :complex-subtypep-arg2) (type1 type2)
2202   (every/type #'csubtypep type1 (intersection-type-types type2)))
2203
2204 (!def-type-translator and (&whole whole &rest type-specifiers)
2205   (apply #'type-intersection
2206          (mapcar #'specifier-type
2207                  type-specifiers)))
2208 \f
2209 ;;;; union types
2210
2211 (!define-type-class union)
2212
2213 ;;; The LIST, FLOAT and REAL types have special names.  Other union
2214 ;;; types just get mechanically unparsed.
2215 (!define-type-method (union :unparse) (type)
2216   (declare (type ctype type))
2217   (cond
2218     ((type= type (specifier-type 'list)) 'list)
2219     ((type= type (specifier-type 'float)) 'float)
2220     ((type= type (specifier-type 'real)) 'real)
2221     ((type= type (specifier-type 'sequence)) 'sequence)
2222     ((type= type (specifier-type 'string-stream)) 'string-stream)
2223     (t `(or ,@(mapcar #'type-specifier (union-type-types type))))))
2224
2225 ;;; Two union types are equal if they are each subtypes of each
2226 ;;; other. We need to be this clever because our complex subtypep
2227 ;;; methods are now more accurate; we don't get infinite recursion
2228 ;;; because the simple-subtypep method delegates to complex-subtypep
2229 ;;; of the individual types of type1. - CSR, 2002-04-09
2230 ;;;
2231 ;;; Previous comment, now obsolete, but worth keeping around because
2232 ;;; it is true, though too strong a condition:
2233 ;;;
2234 ;;; Two union types are equal if their subtypes are equal sets.
2235 (!define-type-method (union :simple-=) (type1 type2)
2236   (multiple-value-bind (subtype certain?)
2237       (csubtypep type1 type2)
2238     (if subtype
2239         (csubtypep type2 type1)
2240         ;; we might as well become as certain as possible.
2241         (if certain?
2242             (values nil t)
2243             (multiple-value-bind (subtype certain?)
2244                 (csubtypep type2 type1)
2245               (declare (ignore subtype))
2246               (values nil certain?))))))
2247
2248 (!define-type-method (union :complex-=) (type1 type2)
2249   (declare (ignore type1))
2250   (if (some #'hairy-type-p (union-type-types type2))
2251       (values nil nil)
2252       (values nil t)))
2253
2254 ;;; Similarly, a union type is a subtype of another if and only if
2255 ;;; every element of TYPE1 is a subtype of TYPE2.
2256 (defun union-simple-subtypep (type1 type2)
2257   (every/type (swapped-args-fun #'union-complex-subtypep-arg2)
2258               type2
2259               (union-type-types type1)))
2260
2261 (!define-type-method (union :simple-subtypep) (type1 type2)
2262   (union-simple-subtypep type1 type2))
2263   
2264 (defun union-complex-subtypep-arg1 (type1 type2)
2265   (every/type (swapped-args-fun #'csubtypep)
2266               type2
2267               (union-type-types type1)))
2268
2269 (!define-type-method (union :complex-subtypep-arg1) (type1 type2)
2270   (union-complex-subtypep-arg1 type1 type2))
2271
2272 (defun union-complex-subtypep-arg2 (type1 type2)
2273   (multiple-value-bind (sub-value sub-certain?)
2274       ;; was: (any/type #'csubtypep type1 (union-type-types type2)),
2275       ;; which turns out to be too restrictive, causing bug 91.
2276       ;;
2277       ;; the following reimplementation might look dodgy.  It is
2278       ;; dodgy. It depends on the union :complex-= method not doing
2279       ;; very much work -- certainly, not using subtypep. Reasoning:
2280       (progn
2281         ;; At this stage, we know that type2 is a union type and type1
2282         ;; isn't. We might as well check this, though:
2283         (aver (union-type-p type2))
2284         (aver (not (union-type-p type1)))
2285         ;;     A is a subset of (B1 u B2)
2286         ;; <=> A n (B1 u B2) = A
2287         ;; <=> (A n B1) u (A n B2) = A
2288         ;;
2289         ;; But, we have to be careful not to delegate this type= to
2290         ;; something that could invoke subtypep, which might get us
2291         ;; back here -> stack explosion. We therefore ensure that the
2292         ;; second type (which is the one that's dispatched on) is
2293         ;; either a union type (where we've ensured that the complex-=
2294         ;; method will not call subtypep) or something with no union
2295         ;; types involved, in which case we'll never come back here.
2296         ;;
2297         ;; If we don't do this, then e.g.
2298         ;; (SUBTYPEP '(MEMBER 3) '(OR (SATISFIES FOO) (SATISFIES BAR)))
2299         ;; would loop infinitely, as the member :complex-= method is
2300         ;; implemented in terms of subtypep.
2301         ;;
2302         ;; Ouch. - CSR, 2002-04-10
2303         (type= type1
2304                (apply #'type-union
2305                       (mapcar (lambda (x) (type-intersection type1 x))
2306                               (union-type-types type2)))))
2307     (if sub-certain?
2308         (values sub-value sub-certain?)
2309         ;; The ANY/TYPE expression above is a sufficient condition for
2310         ;; subsetness, but not a necessary one, so we might get a more
2311         ;; certain answer by this CALL-NEXT-METHOD-ish step when the
2312         ;; ANY/TYPE expression is uncertain.
2313         (invoke-complex-subtypep-arg1-method type1 type2))))
2314
2315 (!define-type-method (union :complex-subtypep-arg2) (type1 type2)
2316   (union-complex-subtypep-arg2 type1 type2))
2317
2318 (!define-type-method (union :simple-intersection2 :complex-intersection2)
2319                      (type1 type2)
2320   ;; The CSUBTYPEP clauses here let us simplify e.g.
2321   ;;   (TYPE-INTERSECTION2 (SPECIFIER-TYPE 'LIST)
2322   ;;                       (SPECIFIER-TYPE '(OR LIST VECTOR)))
2323   ;; (where LIST is (OR CONS NULL)).
2324   ;;
2325   ;; The tests are more or less (CSUBTYPEP TYPE1 TYPE2) and vice
2326   ;; versa, but it's important that we pre-expand them into
2327   ;; specialized operations on individual elements of
2328   ;; UNION-TYPE-TYPES, instead of using the ordinary call to
2329   ;; CSUBTYPEP, in order to avoid possibly invoking any methods which
2330   ;; might in turn invoke (TYPE-INTERSECTION2 TYPE1 TYPE2) and thus
2331   ;; cause infinite recursion.
2332   ;;
2333   ;; Within this method, type2 is guaranteed to be a union type:
2334   (aver (union-type-p type2))
2335   ;; Make sure to call only the applicable methods...
2336   (cond ((and (union-type-p type1)
2337               (union-simple-subtypep type1 type2)) type1)
2338         ((and (union-type-p type1)
2339               (union-simple-subtypep type2 type1)) type2)
2340         ((and (not (union-type-p type1))
2341               (union-complex-subtypep-arg2 type1 type2))
2342          type1)
2343         ((and (not (union-type-p type1))
2344               (union-complex-subtypep-arg1 type2 type1))
2345          type2)
2346         (t 
2347          ;; KLUDGE: This code accumulates a sequence of TYPE-UNION2
2348          ;; operations in a particular order, and gives up if any of
2349          ;; the sub-unions turn out not to be simple. In other cases
2350          ;; ca. sbcl-0.6.11.15, that approach to taking a union was a
2351          ;; bad idea, since it can overlook simplifications which
2352          ;; might occur if the terms were accumulated in a different
2353          ;; order. It's possible that that will be a problem here too.
2354          ;; However, I can't think of a good example to demonstrate
2355          ;; it, and without an example to demonstrate it I can't write
2356          ;; test cases, and without test cases I don't want to
2357          ;; complicate the code to address what's still a hypothetical
2358          ;; problem. So I punted. -- WHN 2001-03-20
2359          (let ((accumulator *empty-type*))
2360            (dolist (t2 (union-type-types type2) accumulator)
2361              (setf accumulator
2362                    (type-union2 accumulator
2363                                 (type-intersection type1 t2)))
2364              ;; When our result isn't simple any more (because
2365              ;; TYPE-UNION2 was unable to give us a simple result)
2366              (unless accumulator
2367                (return nil)))))))
2368
2369 (!def-type-translator or (&rest type-specifiers)
2370   (apply #'type-union
2371          (mapcar #'specifier-type
2372                  type-specifiers)))
2373 \f
2374 ;;;; CONS types
2375
2376 (!define-type-class cons)
2377
2378 (!def-type-translator cons (&optional (car-type-spec '*) (cdr-type-spec '*))
2379   (make-cons-type (specifier-type car-type-spec)
2380                   (specifier-type cdr-type-spec)))
2381  
2382 (!define-type-method (cons :unparse) (type)
2383   (let ((car-eltype (type-specifier (cons-type-car-type type)))
2384         (cdr-eltype (type-specifier (cons-type-cdr-type type))))
2385     (if (and (member car-eltype '(t *))
2386              (member cdr-eltype '(t *)))
2387         'cons
2388         `(cons ,car-eltype ,cdr-eltype))))
2389  
2390 (!define-type-method (cons :simple-=) (type1 type2)
2391   (declare (type cons-type type1 type2))
2392   (and (type= (cons-type-car-type type1) (cons-type-car-type type2))
2393        (type= (cons-type-cdr-type type1) (cons-type-cdr-type type2))))
2394  
2395 (!define-type-method (cons :simple-subtypep) (type1 type2)
2396   (declare (type cons-type type1 type2))
2397   (multiple-value-bind (val-car win-car)
2398       (csubtypep (cons-type-car-type type1) (cons-type-car-type type2))
2399     (multiple-value-bind (val-cdr win-cdr)
2400         (csubtypep (cons-type-cdr-type type1) (cons-type-cdr-type type2))
2401       (if (and val-car val-cdr)
2402           (values t (and win-car win-cdr))
2403           (values nil (or win-car win-cdr))))))
2404  
2405 ;;; Give up if a precise type is not possible, to avoid returning
2406 ;;; overly general types.
2407 (!define-type-method (cons :simple-union2) (type1 type2)
2408   (declare (type cons-type type1 type2))
2409   (let ((car-type1 (cons-type-car-type type1))
2410         (car-type2 (cons-type-car-type type2))
2411         (cdr-type1 (cons-type-cdr-type type1))
2412         (cdr-type2 (cons-type-cdr-type type2)))
2413     (cond ((type= car-type1 car-type2)
2414            (make-cons-type car-type1
2415                            (type-union cdr-type1 cdr-type2)))
2416           ((type= cdr-type1 cdr-type2)
2417            (make-cons-type (type-union cdr-type1 cdr-type2)
2418                            cdr-type1)))))
2419
2420 (!define-type-method (cons :simple-intersection2) (type1 type2)
2421   (declare (type cons-type type1 type2))
2422   (let (car-int2
2423         cdr-int2)
2424     (and (setf car-int2 (type-intersection2 (cons-type-car-type type1)
2425                                             (cons-type-car-type type2)))
2426          (setf cdr-int2 (type-intersection2 (cons-type-cdr-type type1)
2427                                             (cons-type-cdr-type type2)))
2428          (make-cons-type car-int2 cdr-int2))))
2429 \f
2430 ;;; Return the type that describes all objects that are in X but not
2431 ;;; in Y. If we can't determine this type, then return NIL.
2432 ;;;
2433 ;;; For now, we only are clever dealing with union and member types.
2434 ;;; If either type is not a union type, then we pretend that it is a
2435 ;;; union of just one type. What we do is remove from X all the types
2436 ;;; that are a subtype any type in Y. If any type in X intersects with
2437 ;;; a type in Y but is not a subtype, then we give up.
2438 ;;;
2439 ;;; We must also special-case any member type that appears in the
2440 ;;; union. We remove from X's members all objects that are TYPEP to Y.
2441 ;;; If Y has any members, we must be careful that none of those
2442 ;;; members are CTYPEP to any of Y's non-member types. We give up in
2443 ;;; this case, since to compute that difference we would have to break
2444 ;;; the type from X into some collection of types that represents the
2445 ;;; type without that particular element. This seems too hairy to be
2446 ;;; worthwhile, given its low utility.
2447 (defun type-difference (x y)
2448   (let ((x-types (if (union-type-p x) (union-type-types x) (list x)))
2449         (y-types (if (union-type-p y) (union-type-types y) (list y))))
2450     (collect ((res))
2451       (dolist (x-type x-types)
2452         (if (member-type-p x-type)
2453             (collect ((members))
2454               (dolist (mem (member-type-members x-type))
2455                 (multiple-value-bind (val win) (ctypep mem y)
2456                   (unless win (return-from type-difference nil))
2457                   (unless val
2458                     (members mem))))
2459               (when (members)
2460                 (res (make-member-type :members (members)))))
2461             (dolist (y-type y-types (res x-type))
2462               (multiple-value-bind (val win) (csubtypep x-type y-type)
2463                 (unless win (return-from type-difference nil))
2464                 (when val (return))
2465                 (when (types-equal-or-intersect x-type y-type)
2466                   (return-from type-difference nil))))))
2467       (let ((y-mem (find-if #'member-type-p y-types)))
2468         (when y-mem
2469           (let ((members (member-type-members y-mem)))
2470             (dolist (x-type x-types)
2471               (unless (member-type-p x-type)
2472                 (dolist (member members)
2473                   (multiple-value-bind (val win) (ctypep member x-type)
2474                     (when (or (not win) val)
2475                       (return-from type-difference nil)))))))))
2476       (apply #'type-union (res)))))
2477 \f
2478 (!def-type-translator array (&optional (element-type '*)
2479                                        (dimensions '*))
2480   (specialize-array-type
2481    (make-array-type :dimensions (canonical-array-dimensions dimensions)
2482                     :element-type (specifier-type element-type))))
2483
2484 (!def-type-translator simple-array (&optional (element-type '*)
2485                                               (dimensions '*))
2486   (specialize-array-type
2487    (make-array-type :dimensions (canonical-array-dimensions dimensions)
2488                     :element-type (specifier-type element-type)
2489                     :complexp nil)))
2490 \f
2491 ;;;; utilities shared between cross-compiler and target system
2492
2493 ;;; Does the type derived from compilation of an actual function
2494 ;;; definition satisfy declarations of a function's type?
2495 (defun defined-ftype-matches-declared-ftype-p (defined-ftype declared-ftype)
2496   (declare (type ctype defined-ftype declared-ftype))
2497   (flet ((is-built-in-class-function-p (ctype)
2498            (and (built-in-class-p ctype)
2499                 (eq (built-in-class-%name ctype) 'function))))
2500     (cond (;; DECLARED-FTYPE could certainly be #<BUILT-IN-CLASS FUNCTION>;
2501            ;; that's what happens when we (DECLAIM (FTYPE FUNCTION FOO)).
2502            (is-built-in-class-function-p declared-ftype)
2503            ;; In that case, any definition satisfies the declaration.
2504            t)
2505           (;; It's not clear whether or how DEFINED-FTYPE might be
2506            ;; #<BUILT-IN-CLASS FUNCTION>, but it's not obviously
2507            ;; invalid, so let's handle that case too, just in case.
2508            (is-built-in-class-function-p defined-ftype)
2509            ;; No matter what DECLARED-FTYPE might be, we can't prove
2510            ;; that an object of type FUNCTION doesn't satisfy it, so
2511            ;; we return success no matter what.
2512            t)
2513           (;; Otherwise both of them must be FUN-TYPE objects.
2514            t
2515            ;; FIXME: For now we only check compatibility of the return
2516            ;; type, not argument types, and we don't even check the
2517            ;; return type very precisely (as per bug 94a). It would be
2518            ;; good to do a better job. Perhaps to check the
2519            ;; compatibility of the arguments, we should (1) redo
2520            ;; VALUES-TYPES-EQUAL-OR-INTERSECT as
2521            ;; ARGS-TYPES-EQUAL-OR-INTERSECT, and then (2) apply it to
2522            ;; the ARGS-TYPE slices of the FUN-TYPEs. (ARGS-TYPE
2523            ;; is a base class both of VALUES-TYPE and of FUN-TYPE.)
2524            (values-types-equal-or-intersect
2525             (fun-type-returns defined-ftype)
2526             (fun-type-returns declared-ftype))))))
2527            
2528 ;;; This messy case of CTYPE for NUMBER is shared between the
2529 ;;; cross-compiler and the target system.
2530 (defun ctype-of-number (x)
2531   (let ((num (if (complexp x) (realpart x) x)))
2532     (multiple-value-bind (complexp low high)
2533         (if (complexp x)
2534             (let ((imag (imagpart x)))
2535               (values :complex (min num imag) (max num imag)))
2536             (values :real num num))
2537       (make-numeric-type :class (etypecase num
2538                                   (integer 'integer)
2539                                   (rational 'rational)
2540                                   (float 'float))
2541                          :format (and (floatp num) (float-format-name num))
2542                          :complexp complexp
2543                          :low low
2544                          :high high))))
2545 \f
2546 (locally
2547   ;; Why SAFETY 0? To suppress the is-it-the-right-structure-type
2548   ;; checking for declarations in structure accessors. Otherwise we
2549   ;; can get caught in a chicken-and-egg bootstrapping problem, whose
2550   ;; symptom on x86 OpenBSD sbcl-0.pre7.37.flaky5.22 is an illegal
2551   ;; instruction trap. I haven't tracked it down, but I'm guessing it
2552   ;; has to do with setting LAYOUTs when the LAYOUT hasn't been set
2553   ;; yet. -- WHN
2554   (declare (optimize (safety 0)))
2555   (!defun-from-collected-cold-init-forms !late-type-cold-init))
2556
2557 (/show0 "late-type.lisp end of file")