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