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