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