0.pre7.14.flaky4:
[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-EQUAL-OR-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-EQUAL-OR-INTERSECT, except that it sort of
497 ;;; works on 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 (defun values-types-equal-or-intersect (type1 type2)
501   (cond ((or (eq type1 *empty-type*) (eq type2 *empty-type*))
502          (values t t))
503         ((or (values-type-p type1) (values-type-p type2))
504          (multiple-value-bind (res win) (values-type-intersection type1 type2)
505            (values (not (eq res *empty-type*))
506                    win)))
507         (t
508          (types-equal-or-intersect type1 type2))))
509
510 ;;; a SUBTYPEP-like operation that can be used on any types, including
511 ;;; VALUES types
512 (defun-cached (values-subtypep :hash-function type-cache-hash
513                                :hash-bits 8
514                                :values 2
515                                :default (values nil :empty)
516                                :init-wrapper !cold-init-forms)
517               ((type1 eq) (type2 eq))
518   (declare (type ctype type1 type2))
519   (cond ((eq type2 *wild-type*) (values t t))
520         ((eq type1 *wild-type*)
521          (values (eq type2 *universal-type*) t))
522         ((not (values-types-equal-or-intersect type1 type2))
523          (values nil t))
524         (t
525          (if (or (values-type-p type1) (values-type-p type2))
526              (let ((type1 (coerce-to-values type1))
527                    (type2 (coerce-to-values type2)))
528                (multiple-value-bind (types1 rest1) (values-type-types type1)
529                  (multiple-value-bind (types2 rest2) (values-type-types type2)
530                    (cond ((< (length (values-type-required type1))
531                              (length (values-type-required type2)))
532                           (values nil t))
533                          ((< (length types1) (length types2))
534                           (values nil nil))
535                          ((or (values-type-keyp type1)
536                               (values-type-keyp type2))
537                           (values nil nil))
538                          (t
539                           (do ((t1 types1 (rest t1))
540                                (t2 types2 (rest t2)))
541                               ((null t2)
542                                (csubtypep rest1 rest2))
543                             (multiple-value-bind (res win-p)
544                                 (csubtypep (first t1) (first t2))
545                               (unless win-p
546                                 (return (values nil nil)))
547                               (unless res
548                                 (return (values nil t))))))))))
549              (csubtypep type1 type2)))))
550 \f
551 ;;;; type method interfaces
552
553 ;;; like SUBTYPEP, only works on CTYPE structures
554 (defun-cached (csubtypep :hash-function type-cache-hash
555                          :hash-bits 8
556                          :values 2
557                          :default (values nil :empty)
558                          :init-wrapper !cold-init-forms)
559               ((type1 eq) (type2 eq))
560   (declare (type ctype type1 type2))
561   (cond ((or (eq type1 type2)
562              (eq type1 *empty-type*)
563              (eq type2 *wild-type*))
564          (values t t))
565         ((or (eq type1 *wild-type*)
566              (eq type2 *empty-type*))
567          (values nil t))
568         (t
569          (!invoke-type-method :simple-subtypep :complex-subtypep-arg2
570                               type1 type2
571                               :complex-arg1 :complex-subtypep-arg1))))
572
573 ;;; Just parse the type specifiers and call CSUBTYPE.
574 (defun sb!xc:subtypep (type1 type2)
575   #!+sb-doc
576   "Return two values indicating the relationship between type1 and type2.
577   If values are T and T, type1 definitely is a subtype of type2.
578   If values are NIL and T, type1 definitely is not a subtype of type2.
579   If values are NIL and NIL, it couldn't be determined."
580   (csubtypep (specifier-type type1) (specifier-type type2)))
581
582 ;;; If two types are definitely equivalent, return true. The second
583 ;;; value indicates whether the first value is definitely correct.
584 ;;; This should only fail in the presence of HAIRY types.
585 (defun-cached (type= :hash-function type-cache-hash
586                      :hash-bits 8
587                      :values 2
588                      :default (values nil :empty)
589                      :init-wrapper !cold-init-forms)
590               ((type1 eq) (type2 eq))
591   (declare (type ctype type1 type2))
592   (if (eq type1 type2)
593       (values t t)
594       (!invoke-type-method :simple-= :complex-= type1 type2)))
595
596 ;;; Not exactly the negation of TYPE=, since when the relationship is
597 ;;; uncertain, we still return NIL, NIL. This is useful in cases where
598 ;;; the conservative assumption is =.
599 (defun type/= (type1 type2)
600   (declare (type ctype type1 type2))
601   (multiple-value-bind (res win) (type= type1 type2)
602     (if win
603         (values (not res) t)
604         (values nil nil))))
605
606 ;;; the type method dispatch case of TYPE-UNION2
607 (defun %type-union2 (type1 type2)
608   ;; As in %TYPE-INTERSECTION2, it seems to be a good idea to give
609   ;; both argument orders a chance at COMPLEX-INTERSECTION2. Unlike
610   ;; %TYPE-INTERSECTION2, though, I don't have a specific case which
611   ;; demonstrates this is actually necessary. Also unlike
612   ;; %TYPE-INTERSECTION2, there seems to be no need to distinguish
613   ;; between not finding a method and having a method return NIL.
614   (flet ((1way (x y)
615            (!invoke-type-method :simple-union2 :complex-union2
616                                 x y
617                                 :default nil)))
618     (declare (inline 1way))
619     (or (1way type1 type2)
620         (1way type2 type1))))
621
622 ;;; Find a type which includes both types. Any inexactness is
623 ;;; represented by the fuzzy element types; we return a single value
624 ;;; that is precise to the best of our knowledge. This result is
625 ;;; simplified into the canonical form, thus is not a UNION-TYPE
626 ;;; unless we find no other way to represent the result.
627 (defun-cached (type-union2 :hash-function type-cache-hash
628                            :hash-bits 8
629                            :init-wrapper !cold-init-forms)
630               ((type1 eq) (type2 eq))
631   ;; KLUDGE: This was generated from TYPE-INTERSECTION2 by Ye Olde Cut And
632   ;; Paste technique of programming. If it stays around (as opposed to
633   ;; e.g. fading away in favor of some CLOS solution) the shared logic
634   ;; should probably become shared code. -- WHN 2001-03-16
635   (declare (type ctype type1 type2))
636   (cond ((eq type1 type2)
637          type1)
638         ((or (union-type-p type1)
639              (union-type-p type2))
640          ;; Unions of UNION-TYPE should have the UNION-TYPE-TYPES
641          ;; values broken out and united separately. The full TYPE-UNION
642          ;; function knows how to do this, so let it handle it.
643          (type-union type1 type2))
644         (t
645          ;; the ordinary case: we dispatch to type methods
646          (%type-union2 type1 type2))))
647
648 ;;; the type method dispatch case of TYPE-INTERSECTION2
649 (defun %type-intersection2 (type1 type2)
650   ;; We want to give both argument orders a chance at
651   ;; COMPLEX-INTERSECTION2. Without that, the old CMU CL type
652   ;; methods could give noncommutative results, e.g.
653   ;;   (TYPE-INTERSECTION2 *EMPTY-TYPE* SOME-HAIRY-TYPE)
654   ;;     => NIL, NIL
655   ;;   (TYPE-INTERSECTION2 SOME-HAIRY-TYPE *EMPTY-TYPE*)
656   ;;     => #<NAMED-TYPE NIL>, T
657   ;; We also need to distinguish between the case where we found a
658   ;; type method, and it returned NIL, and the case where we fell
659   ;; through without finding any type method. An example of the first
660   ;; case is the intersection of a HAIRY-TYPE with some ordinary type.
661   ;; An example of the second case is the intersection of two
662   ;; completely-unrelated types, e.g. CONS and NUMBER, or SYMBOL and
663   ;; ARRAY.
664   ;;
665   ;; (Why yes, CLOS probably *would* be nicer..)
666   (flet ((1way (x y)
667            (!invoke-type-method :simple-intersection2 :complex-intersection2
668                                 x y
669                                 :default :no-type-method-found)))
670     (declare (inline 1way))
671     (let ((xy (1way type1 type2)))
672       (or (and (not (eql xy :no-type-method-found)) xy)
673           (let ((yx (1way type2 type1)))
674             (or (and (not (eql yx :no-type-method-found)) yx)
675                 (cond ((and (eql xy :no-type-method-found)
676                             (eql yx :no-type-method-found))
677                        *empty-type*)
678                       (t
679                        (aver (and (not xy) (not yx))) ; else handled above
680                        nil))))))))
681
682 (defun-cached (type-intersection2 :hash-function type-cache-hash
683                                   :hash-bits 8
684                                   :values 1
685                                   :default nil
686                                   :init-wrapper !cold-init-forms)
687               ((type1 eq) (type2 eq))
688   (declare (type ctype type1 type2))
689   (cond ((eq type1 type2)
690          type1)
691         ((or (intersection-type-p type1)
692              (intersection-type-p type2))
693          ;; Intersections of INTERSECTION-TYPE should have the
694          ;; INTERSECTION-TYPE-TYPES values broken out and intersected
695          ;; separately. The full TYPE-INTERSECTION function knows how
696          ;; to do that, so let it handle it.
697          (type-intersection type1 type2))
698         (t
699          ;; the ordinary case: we dispatch to type methods
700          (%type-intersection2 type1 type2))))
701
702 ;;; Return as restrictive and simple a type as we can discover that is
703 ;;; no more restrictive than the intersection of TYPE1 and TYPE2. At
704 ;;; worst, we arbitrarily return one of the arguments as the first
705 ;;; value (trying not to return a hairy type).
706 (defun type-approx-intersection2 (type1 type2)
707   (cond ((type-intersection2 type1 type2))
708         ((hairy-type-p type1) type2)
709         (t type1)))
710
711 ;;; a test useful for checking whether a derived type matches a
712 ;;; declared type
713 ;;;
714 ;;; The first value is true unless the types don't intersect and
715 ;;; aren't equal. The second value is true if the first value is
716 ;;; definitely correct. NIL is considered to intersect with any type.
717 ;;; If T is a subtype of either type, then we also return T, T. This
718 ;;; way we recognize that hairy types might intersect with T.
719 (defun types-equal-or-intersect (type1 type2)
720   (declare (type ctype type1 type2))
721   (if (or (eq type1 *empty-type*) (eq type2 *empty-type*))
722       (values t t)
723       (let ((intersection2 (type-intersection2 type1 type2)))
724         (cond ((not intersection2)
725                (if (or (csubtypep *universal-type* type1)
726                        (csubtypep *universal-type* type2))
727                    (values t t)
728                    (values t nil)))
729               ((eq intersection2 *empty-type*) (values nil t))
730               (t (values t t))))))
731
732 ;;; Return a Common Lisp type specifier corresponding to the TYPE
733 ;;; object.
734 (defun type-specifier (type)
735   (declare (type ctype type))
736   (funcall (type-class-unparse (type-class-info type)) type))
737
738 ;;; (VALUES-SPECIFIER-TYPE and SPECIFIER-TYPE moved from here to
739 ;;; early-type.lisp by WHN ca. 19990201.)
740
741 ;;; Take a list of type specifiers, computing the translation of each
742 ;;; specifier and defining it as a builtin type.
743 (declaim (ftype (function (list) (values)) precompute-types))
744 (defun precompute-types (specs)
745   (dolist (spec specs)
746     (let ((res (specifier-type spec)))
747       (unless (unknown-type-p res)
748         (setf (info :type :builtin spec) res)
749         (setf (info :type :kind spec) :primitive))))
750   (values))
751 \f
752 ;;;; general TYPE-UNION and TYPE-INTERSECTION operations
753 ;;;;
754 ;;;; These are fully general operations on CTYPEs: they'll always
755 ;;;; return a CTYPE representing the result.
756
757 ;;; shared logic for unions and intersections: Stuff TYPE into the
758 ;;; vector TYPES, finding pairs of types which can be simplified by
759 ;;; SIMPLIFY2 (TYPE-UNION2 or TYPE-INTERSECTION2) and replacing them
760 ;;; by their simplified forms.
761 (defun accumulate1-compound-type (type types %compound-type-p simplify2)
762   (declare (type ctype type))
763   (declare (type (vector ctype) types))
764   (declare (type function simplify2))
765   ;; Any input object satisfying %COMPOUND-TYPE-P should've been
766   ;; broken into components before it reached us.
767   (aver (not (funcall %compound-type-p type)))
768   (dotimes (i (length types) (vector-push-extend type types))
769     (let ((simplified2 (funcall simplify2 type (aref types i))))
770       (when simplified2
771         ;; Discard the old (AREF TYPES I).
772         (setf (aref types i) (vector-pop types))
773         ;; Merge the new SIMPLIFIED2 into TYPES, by tail recursing.
774         ;; (Note that the tail recursion is indirect: we go through
775         ;; ACCUMULATE, not ACCUMULATE1, so that if SIMPLIFIED2 is
776         ;; handled properly if it satisfies %COMPOUND-TYPE-P.)
777         (return (accumulate-compound-type simplified2
778                                           types
779                                           %compound-type-p
780                                           simplify2)))))
781   ;; Voila.
782   (values))
783
784 ;;; shared logic for unions and intersections: Use
785 ;;; ACCUMULATE1-COMPOUND-TYPE to merge TYPE into TYPES, either
786 ;;; all in one step or, if %COMPOUND-TYPE-P is satisfied,
787 ;;; component by component.
788 (defun accumulate-compound-type (type types %compound-type-p simplify2)
789   (declare (type function %compound-type-p simplify2))
790   (flet ((accumulate1 (x)
791            (accumulate1-compound-type x types %compound-type-p simplify2)))
792     (declare (inline accumulate1))
793     (if (funcall %compound-type-p type)
794         (map nil #'accumulate1 (compound-type-types type))
795         (accumulate1 type)))
796   (values))
797
798 ;;; shared logic for unions and intersections: Return a vector of
799 ;;; types representing the same types as INPUT-TYPES, but with 
800 ;;; COMPOUND-TYPEs satisfying %COMPOUND-TYPE-P broken up into their
801 ;;; component types, and with any SIMPLY2 simplifications applied.
802 (defun simplified-compound-types (input-types %compound-type-p simplify2)
803   (let ((simplified-types (make-array (length input-types)
804                                       :fill-pointer 0
805                                       :element-type 'ctype
806                                       ;; (This INITIAL-ELEMENT shouldn't
807                                       ;; matter, but helps avoid type
808                                       ;; warnings at compile time.)
809                                       :initial-element *empty-type*)))
810     (dolist (input-type input-types)
811       (accumulate-compound-type input-type
812                                 simplified-types
813                                 %compound-type-p
814                                 simplify2))
815     simplified-types))
816
817 ;;; shared logic for unions and intersections: Make a COMPOUND-TYPE
818 ;;; object whose components are the types in TYPES, or skip to special
819 ;;; cases when TYPES is short.
820 (defun make-compound-type-or-something (constructor types enumerable identity)
821   (declare (type function constructor))
822   (declare (type (vector ctype) types))
823   (declare (type ctype identity))
824   (case (length types)
825     (0 identity)
826     (1 (aref types 0))
827     (t (funcall constructor
828                 enumerable
829                 ;; FIXME: This should be just (COERCE TYPES 'LIST), but as
830                 ;; of sbcl-0.6.11.17 the COERCE optimizer is really
831                 ;; brain-dead, so that would generate a full call to
832                 ;; SPECIFIER-TYPE at runtime, so we get into bootstrap
833                 ;; problems in cold init because 'LIST is a compound
834                 ;; type, so we need to MAKE-COMPOUND-TYPE-OR-SOMETHING
835                 ;; before we know what 'LIST is. Once the COERCE
836                 ;; optimizer is less brain-dead, we can make this
837                 ;; (COERCE TYPES 'LIST) again.
838                 #+sb-xc-host (coerce types 'list)
839                 #-sb-xc-host (coerce-to-list types)))))
840
841 (defun type-intersection (&rest input-types)
842   (let ((simplified-types (simplified-compound-types input-types
843                                                      #'intersection-type-p
844                                                      #'type-intersection2)))
845     (declare (type (vector ctype) simplified-types))
846     ;; We want to have a canonical representation of types (or failing
847     ;; that, punt to HAIRY-TYPE). Canonical representation would have
848     ;; intersections inside unions but not vice versa, since you can
849     ;; always achieve that by the distributive rule. But we don't want
850     ;; to just apply the distributive rule, since it would be too easy
851     ;; to end up with unreasonably huge type expressions. So instead
852     ;; we punt to HAIRY-TYPE when this comes up.
853     (if (and (> (length simplified-types) 1)
854              (some #'union-type-p simplified-types))
855         (make-hairy-type
856          :specifier `(and ,@(map 'list #'type-specifier simplified-types)))
857         (make-compound-type-or-something #'%make-intersection-type
858                                          simplified-types
859                                          (some #'type-enumerable
860                                                simplified-types)
861                                          *universal-type*))))
862
863 (defun type-union (&rest input-types)
864   (let ((simplified-types (simplified-compound-types input-types
865                                                      #'union-type-p
866                                                      #'type-union2)))
867     (make-compound-type-or-something #'%make-union-type
868                                      simplified-types
869                                      (every #'type-enumerable simplified-types)
870                                      *empty-type*)))
871 \f
872 ;;;; built-in types
873
874 (!define-type-class named)
875
876 (defvar *wild-type*)
877 (defvar *empty-type*)
878 (defvar *universal-type*)
879 (defvar *universal-function-type*)
880 (!cold-init-forms
881  (macrolet ((frob (name var)
882               `(progn
883                  (setq ,var (make-named-type :name ',name))
884                  (setf (info :type :kind ',name) :primitive)
885                  (setf (info :type :builtin ',name) ,var))))
886    ;; KLUDGE: In ANSI, * isn't really the name of a type, it's just a
887    ;; special symbol which can be stuck in some places where an
888    ;; ordinary type can go, e.g. (ARRAY * 1) instead of (ARRAY T 1).
889    ;; At some point, in order to become more standard, we should
890    ;; convert all the classic CMU CL legacy *s and *WILD-TYPE*s into
891    ;; Ts and *UNIVERSAL-TYPE*s.
892    (frob * *wild-type*)
893    (frob nil *empty-type*)
894    (frob t *universal-type*))
895  (setf *universal-function-type*
896        (make-function-type :wild-args t
897                            :returns *wild-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 (!define-type-class number)
1021
1022 (!define-type-method (number :simple-=) (type1 type2)
1023   (values
1024    (and (eq (numeric-type-class type1) (numeric-type-class type2))
1025         (eq (numeric-type-format type1) (numeric-type-format type2))
1026         (eq (numeric-type-complexp type1) (numeric-type-complexp type2))
1027         (equal (numeric-type-low type1) (numeric-type-low type2))
1028         (equal (numeric-type-high type1) (numeric-type-high type2)))
1029    t))
1030
1031 (!define-type-method (number :unparse) (type)
1032   (let* ((complexp (numeric-type-complexp type))
1033          (low (numeric-type-low type))
1034          (high (numeric-type-high type))
1035          (base (case (numeric-type-class type)
1036                  (integer 'integer)
1037                  (rational 'rational)
1038                  (float (or (numeric-type-format type) 'float))
1039                  (t 'real))))
1040     (let ((base+bounds
1041            (cond ((and (eq base 'integer) high low)
1042                   (let ((high-count (logcount high))
1043                         (high-length (integer-length high)))
1044                     (cond ((= low 0)
1045                            (cond ((= high 0) '(integer 0 0))
1046                                  ((= high 1) 'bit)
1047                                  ((and (= high-count high-length)
1048                                        (plusp high-length))
1049                                   `(unsigned-byte ,high-length))
1050                                  (t
1051                                   `(mod ,(1+ high)))))
1052                           ((and (= low sb!vm:*target-most-negative-fixnum*)
1053                                 (= high sb!vm:*target-most-positive-fixnum*))
1054                            'fixnum)
1055                           ((and (= low (lognot high))
1056                                 (= high-count high-length)
1057                                 (> high-count 0))
1058                            `(signed-byte ,(1+ high-length)))
1059                           (t
1060                            `(integer ,low ,high)))))
1061                  (high `(,base ,(or low '*) ,high))
1062                  (low
1063                   (if (and (eq base 'integer) (= low 0))
1064                       'unsigned-byte
1065                       `(,base ,low)))
1066                  (t base))))
1067       (ecase complexp
1068         (:real
1069          base+bounds)
1070         (:complex
1071          (if (eq base+bounds 'real)
1072              'complex
1073              `(complex ,base+bounds)))
1074         ((nil)
1075          (aver (eq base+bounds 'real))
1076          'number)))))
1077
1078 ;;; Return true if X is "less than or equal" to Y, taking open bounds
1079 ;;; into consideration. CLOSED is the predicate used to test the bound
1080 ;;; on a closed interval (e.g. <=), and OPEN is the predicate used on
1081 ;;; open bounds (e.g. <). Y is considered to be the outside bound, in
1082 ;;; the sense that if it is infinite (NIL), then the test succeeds,
1083 ;;; whereas if X is infinite, then the test fails (unless Y is also
1084 ;;; infinite).
1085 ;;;
1086 ;;; This is for comparing bounds of the same kind, e.g. upper and
1087 ;;; upper. Use NUMERIC-BOUND-TEST* for different kinds of bounds.
1088 #!-negative-zero-is-not-zero
1089 (defmacro numeric-bound-test (x y closed open)
1090   `(cond ((not ,y) t)
1091          ((not ,x) nil)
1092          ((consp ,x)
1093           (if (consp ,y)
1094               (,closed (car ,x) (car ,y))
1095               (,closed (car ,x) ,y)))
1096          (t
1097           (if (consp ,y)
1098               (,open ,x (car ,y))
1099               (,closed ,x ,y)))))
1100
1101 #!+negative-zero-is-not-zero
1102 (defmacro numeric-bound-test-zero (op x y)
1103   `(if (and (zerop ,x) (zerop ,y) (floatp ,x) (floatp ,y))
1104        (,op (float-sign ,x) (float-sign ,y))
1105        (,op ,x ,y)))
1106
1107 #!+negative-zero-is-not-zero
1108 (defmacro numeric-bound-test (x y closed open)
1109   `(cond ((not ,y) t)
1110          ((not ,x) nil)
1111          ((consp ,x)
1112           (if (consp ,y)
1113               (numeric-bound-test-zero ,closed (car ,x) (car ,y))
1114               (numeric-bound-test-zero ,closed (car ,x) ,y)))
1115          (t
1116           (if (consp ,y)
1117               (numeric-bound-test-zero ,open ,x (car ,y))
1118               (numeric-bound-test-zero ,closed ,x ,y)))))
1119
1120 ;;; This is used to compare upper and lower bounds. This is different
1121 ;;; from the same-bound case:
1122 ;;; -- Since X = NIL is -infinity, whereas y = NIL is +infinity, we
1123 ;;;    return true if *either* arg is NIL.
1124 ;;; -- an open inner bound is "greater" and also squeezes the interval,
1125 ;;;    causing us to use the OPEN test for those cases as well.
1126 #!-negative-zero-is-not-zero
1127 (defmacro numeric-bound-test* (x y closed open)
1128   `(cond ((not ,y) t)
1129          ((not ,x) t)
1130          ((consp ,x)
1131           (if (consp ,y)
1132               (,open (car ,x) (car ,y))
1133               (,open (car ,x) ,y)))
1134          (t
1135           (if (consp ,y)
1136               (,open ,x (car ,y))
1137               (,closed ,x ,y)))))
1138
1139 #!+negative-zero-is-not-zero
1140 (defmacro numeric-bound-test* (x y closed open)
1141   `(cond ((not ,y) t)
1142          ((not ,x) t)
1143          ((consp ,x)
1144           (if (consp ,y)
1145               (numeric-bound-test-zero ,open (car ,x) (car ,y))
1146               (numeric-bound-test-zero ,open (car ,x) ,y)))
1147          (t
1148           (if (consp ,y)
1149               (numeric-bound-test-zero ,open ,x (car ,y))
1150               (numeric-bound-test-zero ,closed ,x ,y)))))
1151
1152 ;;; Return whichever of the numeric bounds X and Y is "maximal"
1153 ;;; according to the predicates CLOSED (e.g. >=) and OPEN (e.g. >).
1154 ;;; This is only meaningful for maximizing like bounds, i.e. upper and
1155 ;;; upper. If MAX-P is true, then we return NIL if X or Y is NIL,
1156 ;;; otherwise we return the other arg.
1157 (defmacro numeric-bound-max (x y closed open max-p)
1158   (once-only ((n-x x)
1159               (n-y y))
1160     `(cond ((not ,n-x) ,(if max-p nil n-y))
1161            ((not ,n-y) ,(if max-p nil n-x))
1162            ((consp ,n-x)
1163             (if (consp ,n-y)
1164                 (if (,closed (car ,n-x) (car ,n-y)) ,n-x ,n-y)
1165                 (if (,open (car ,n-x) ,n-y) ,n-x ,n-y)))
1166            (t
1167             (if (consp ,n-y)
1168                 (if (,open (car ,n-y) ,n-x) ,n-y ,n-x)
1169                 (if (,closed ,n-y ,n-x) ,n-y ,n-x))))))
1170
1171 (!define-type-method (number :simple-subtypep) (type1 type2)
1172   (let ((class1 (numeric-type-class type1))
1173         (class2 (numeric-type-class type2))
1174         (complexp2 (numeric-type-complexp type2))
1175         (format2 (numeric-type-format type2))
1176         (low1 (numeric-type-low type1))
1177         (high1 (numeric-type-high type1))
1178         (low2 (numeric-type-low type2))
1179         (high2 (numeric-type-high type2)))
1180     ;; If one is complex and the other isn't, they are disjoint.
1181     (cond ((not (or (eq (numeric-type-complexp type1) complexp2)
1182                     (null complexp2)))
1183            (values nil t))
1184           ;; If the classes are specified and different, the types are
1185           ;; disjoint unless type2 is rational and type1 is integer.
1186           ((not (or (eq class1 class2)
1187                     (null class2)
1188                     (and (eq class1 'integer)
1189                          (eq class2 'rational))))
1190            (values nil t))
1191           ;; If the float formats are specified and different, the types
1192           ;; are disjoint.
1193           ((not (or (eq (numeric-type-format type1) format2)
1194                     (null format2)))
1195            (values nil t))
1196           ;; Check the bounds.
1197           ((and (numeric-bound-test low1 low2 >= >)
1198                 (numeric-bound-test high1 high2 <= <))
1199            (values t t))
1200           (t
1201            (values nil t)))))
1202
1203 (!define-superclasses number ((generic-number)) !cold-init-forms)
1204
1205 ;;; If the high bound of LOW is adjacent to the low bound of HIGH,
1206 ;;; then return true, otherwise NIL.
1207 (defun numeric-types-adjacent (low high)
1208   (let ((low-bound (numeric-type-high low))
1209         (high-bound (numeric-type-low high)))
1210     (cond ((not (and low-bound high-bound)) nil)
1211           ((and (consp low-bound) (consp high-bound)) nil)
1212           ((consp low-bound)
1213            #!-negative-zero-is-not-zero
1214            (let ((low-value (car low-bound)))
1215              (or (eql low-value high-bound)
1216                  (and (eql low-value -0f0) (eql high-bound 0f0))
1217                  (and (eql low-value 0f0) (eql high-bound -0f0))
1218                  (and (eql low-value -0d0) (eql high-bound 0d0))
1219                  (and (eql low-value 0d0) (eql high-bound -0d0))))
1220            #!+negative-zero-is-not-zero
1221            (eql (car low-bound) high-bound))
1222           ((consp high-bound)
1223            #!-negative-zero-is-not-zero
1224            (let ((high-value (car high-bound)))
1225              (or (eql high-value low-bound)
1226                  (and (eql high-value -0f0) (eql low-bound 0f0))
1227                  (and (eql high-value 0f0) (eql low-bound -0f0))
1228                  (and (eql high-value -0d0) (eql low-bound 0d0))
1229                  (and (eql high-value 0d0) (eql low-bound -0d0))))
1230            #!+negative-zero-is-not-zero
1231            (eql (car high-bound) low-bound))
1232           #!+negative-zero-is-not-zero
1233           ((or (and (eql low-bound -0f0) (eql high-bound 0f0))
1234                (and (eql low-bound -0d0) (eql high-bound 0d0))))
1235           ((and (eq (numeric-type-class low) 'integer)
1236                 (eq (numeric-type-class high) 'integer))
1237            (eql (1+ low-bound) high-bound))
1238           (t
1239            nil))))
1240
1241 ;;; Return a numeric type that is a supertype for both TYPE1 and TYPE2.
1242 ;;;
1243 ;;; ### Note: we give up early to keep from dropping lots of information on
1244 ;;; the floor by returning overly general types.
1245 (!define-type-method (number :simple-union2) (type1 type2)
1246   (declare (type numeric-type type1 type2))
1247   (cond ((csubtypep type1 type2) type2)
1248         ((csubtypep type2 type1) type1)
1249         (t
1250          (let ((class1 (numeric-type-class type1))
1251                (format1 (numeric-type-format type1))
1252                (complexp1 (numeric-type-complexp type1))
1253                (class2 (numeric-type-class type2))
1254                (format2 (numeric-type-format type2))
1255                (complexp2 (numeric-type-complexp type2)))
1256            (when (and (eq class1 class2)
1257                       (eq format1 format2)
1258                       (eq complexp1 complexp2)
1259                       (or (numeric-types-intersect type1 type2)
1260                           (numeric-types-adjacent type1 type2)
1261                           (numeric-types-adjacent type2 type1)))
1262              (make-numeric-type
1263               :class class1
1264               :format format1
1265               :complexp complexp1
1266               :low (numeric-bound-max (numeric-type-low type1)
1267                                       (numeric-type-low type2)
1268                                       <= < t)
1269               :high (numeric-bound-max (numeric-type-high type1)
1270                                        (numeric-type-high type2)
1271                                        >= > t)))))))
1272
1273 (!cold-init-forms
1274   (setf (info :type :kind 'number) :primitive)
1275   (setf (info :type :builtin 'number)
1276         (make-numeric-type :complexp nil)))
1277
1278 (!def-type-translator complex (&optional (typespec '*))
1279   (if (eq typespec '*)
1280       (make-numeric-type :complexp :complex)
1281       (labels ((not-numeric ()
1282                  ;; FIXME: should probably be TYPE-ERROR
1283                  (error "The component type for COMPLEX is not numeric: ~S"
1284                         typespec))
1285                (complex1 (component-type)
1286                  (unless (numeric-type-p component-type)
1287                    ;; FIXME: As per the FIXME below, ANSI says we're
1288                    ;; supposed to handle any subtype of REAL, not only
1289                    ;; those which can be represented as NUMERIC-TYPE.
1290                    (not-numeric))
1291                  (when (eq (numeric-type-complexp component-type) :complex)
1292                    (error "The component type for COMPLEX is complex: ~S"
1293                           typespec))
1294                  (modified-numeric-type component-type :complexp :complex)))
1295         (let ((type (specifier-type typespec)))
1296           (typecase type
1297             ;; This is all that CMU CL handled.
1298             (numeric-type (complex1 type))
1299             ;; We need to handle UNION-TYPEs in order to deal with
1300             ;; REAL and FLOAT being represented as UNION-TYPEs of more
1301             ;; primitive types.
1302             (union-type (apply #'type-union
1303                                (mapcar #'complex1
1304                                        (union-type-types type))))
1305             ;; FIXME: ANSI just says that TYPESPEC is a subtype of type
1306             ;; REAL, not necessarily a NUMERIC-TYPE. E.g. TYPESPEC could
1307             ;; legally be (AND REAL (SATISFIES ODDP))! But like the old
1308             ;; CMU CL code, we're still not nearly that general.
1309             (t (not-numeric)))))))
1310
1311 ;;; If X is *, return NIL, otherwise return the bound, which must be a
1312 ;;; member of TYPE or a one-element list of a member of TYPE.
1313 #!-sb-fluid (declaim (inline canonicalized-bound))
1314 (defun canonicalized-bound (bound type)
1315   (cond ((eq bound '*) nil)
1316         ((or (sb!xc:typep bound type)
1317              (and (consp bound)
1318                   (sb!xc:typep (car bound) type)
1319                   (null (cdr bound))))
1320           bound)
1321         (t
1322          (error "Bound is not ~S, a ~S or a list of a ~S: ~S"
1323                 '*
1324                 type
1325                 type
1326                 bound))))
1327
1328 (!def-type-translator integer (&optional (low '*) (high '*))
1329   (let* ((l (canonicalized-bound low 'integer))
1330          (lb (if (consp l) (1+ (car l)) l))
1331          (h (canonicalized-bound high 'integer))
1332          (hb (if (consp h) (1- (car h)) h)))
1333     (when (and hb lb (< hb lb))
1334       (error "Lower bound ~S is greater than upper bound ~S." l h))
1335     (make-numeric-type :class 'integer
1336                        :complexp :real
1337                        :enumerable (not (null (and l h)))
1338                        :low lb
1339                        :high hb)))
1340
1341 (defmacro !def-bounded-type (type class format)
1342   `(!def-type-translator ,type (&optional (low '*) (high '*))
1343      (let ((lb (canonicalized-bound low ',type))
1344            (hb (canonicalized-bound high ',type)))
1345        (unless (numeric-bound-test* lb hb <= <)
1346          (error "Lower bound ~S is not less than upper bound ~S." low high))
1347        (make-numeric-type :class ',class :format ',format :low lb :high hb))))
1348
1349 (!def-bounded-type rational rational nil)
1350
1351 ;;; Unlike CMU CL, we represent the types FLOAT and REAL as
1352 ;;; UNION-TYPEs of more primitive types, in order to make
1353 ;;; type representation more unique, avoiding problems in the
1354 ;;; simplification of things like
1355 ;;;   (subtypep '(or (single-float -1.0 1.0) (single-float 0.1))
1356 ;;;             '(or (real -1 7) (single-float 0.1) (single-float -1.0 1.0)))
1357 ;;; When we allowed REAL to remain as a separate NUMERIC-TYPE,
1358 ;;; it was too easy for the first argument to be simplified to
1359 ;;; '(SINGLE-FLOAT -1.0), and for the second argument to be simplified
1360 ;;; to '(OR (REAL -1 7) (SINGLE-FLOAT 0.1)) and then for the
1361 ;;; SUBTYPEP to fail (returning NIL,T instead of T,T) because
1362 ;;; the first argument can't be seen to be a subtype of any of the
1363 ;;; terms in the second argument.
1364 ;;;
1365 ;;; The old CMU CL way was:
1366 ;;;   (!def-bounded-type float float nil)
1367 ;;;   (!def-bounded-type real nil nil)
1368 ;;;
1369 ;;; FIXME: If this new way works for a while with no weird new
1370 ;;; problems, we can go back and rip out support for separate FLOAT
1371 ;;; and REAL flavors of NUMERIC-TYPE. The new way was added in
1372 ;;; sbcl-0.6.11.22, 2001-03-21.
1373 ;;;
1374 ;;; FIXME: It's probably necessary to do something to fix the
1375 ;;; analogous problem with INTEGER and RATIONAL types. Perhaps
1376 ;;; bounded RATIONAL types should be represented as (OR RATIO INTEGER).
1377 (defun coerce-bound (bound type inner-coerce-bound-fun)
1378   (declare (type function inner-coerce-bound-fun))
1379   (cond ((eql bound '*)
1380          bound)
1381         ((consp bound)
1382          (destructuring-bind (inner-bound) bound
1383            (list (funcall inner-coerce-bound-fun inner-bound type))))
1384         (t
1385          (funcall inner-coerce-bound-fun bound type))))
1386 (defun inner-coerce-real-bound (bound type)
1387   (ecase type
1388     (rational (rationalize bound))
1389     (float (if (floatp bound)
1390                bound
1391                ;; Coerce to the widest float format available, to
1392                ;; avoid unnecessary loss of precision:
1393                (coerce bound 'long-float)))))
1394 (defun coerced-real-bound (bound type)
1395   (coerce-bound bound type #'inner-coerce-real-bound))
1396 (defun coerced-float-bound (bound type)
1397   (coerce-bound bound type #'coerce))
1398 (!def-type-translator real (&optional (low '*) (high '*))
1399   (specifier-type `(or (float ,(coerced-real-bound  low 'float)
1400                               ,(coerced-real-bound high 'float))
1401                        (rational ,(coerced-real-bound  low 'rational)
1402                                  ,(coerced-real-bound high 'rational)))))
1403 (!def-type-translator float (&optional (low '*) (high '*))
1404   (specifier-type 
1405    `(or (single-float ,(coerced-float-bound  low 'single-float)
1406                       ,(coerced-float-bound high 'single-float))
1407         (double-float ,(coerced-float-bound  low 'double-float)
1408                       ,(coerced-float-bound high 'double-float))
1409         #!+long-float ,(error "stub: no long float support yet"))))
1410
1411 (defmacro !define-float-format (f)
1412   `(!def-bounded-type ,f float ,f))
1413
1414 (!define-float-format short-float)
1415 (!define-float-format single-float)
1416 (!define-float-format double-float)
1417 (!define-float-format long-float)
1418
1419 (defun numeric-types-intersect (type1 type2)
1420   (declare (type numeric-type type1 type2))
1421   (let* ((class1 (numeric-type-class type1))
1422          (class2 (numeric-type-class type2))
1423          (complexp1 (numeric-type-complexp type1))
1424          (complexp2 (numeric-type-complexp type2))
1425          (format1 (numeric-type-format type1))
1426          (format2 (numeric-type-format type2))
1427          (low1 (numeric-type-low type1))
1428          (high1 (numeric-type-high type1))
1429          (low2 (numeric-type-low type2))
1430          (high2 (numeric-type-high type2)))
1431     ;; If one is complex and the other isn't, then they are disjoint.
1432     (cond ((not (or (eq complexp1 complexp2)
1433                     (null complexp1) (null complexp2)))
1434            nil)
1435           ;; If either type is a float, then the other must either be
1436           ;; specified to be a float or unspecified. Otherwise, they
1437           ;; are disjoint.
1438           ((and (eq class1 'float)
1439                 (not (member class2 '(float nil)))) nil)
1440           ((and (eq class2 'float)
1441                 (not (member class1 '(float nil)))) nil)
1442           ;; If the float formats are specified and different, the
1443           ;; types are disjoint.
1444           ((not (or (eq format1 format2) (null format1) (null format2)))
1445            nil)
1446           (t
1447            ;; Check the bounds. This is a bit odd because we must
1448            ;; always have the outer bound of the interval as the
1449            ;; second arg.
1450            (if (numeric-bound-test high1 high2 <= <)
1451                (or (and (numeric-bound-test low1 low2 >= >)
1452                         (numeric-bound-test* low1 high2 <= <))
1453                    (and (numeric-bound-test low2 low1 >= >)
1454                         (numeric-bound-test* low2 high1 <= <)))
1455                (or (and (numeric-bound-test* low2 high1 <= <)
1456                         (numeric-bound-test low2 low1 >= >))
1457                    (and (numeric-bound-test high2 high1 <= <)
1458                         (numeric-bound-test* high2 low1 >= >))))))))
1459
1460 ;;; Take the numeric bound X and convert it into something that can be
1461 ;;; used as a bound in a numeric type with the specified CLASS and
1462 ;;; FORMAT. If UP-P is true, then we round up as needed, otherwise we
1463 ;;; round down. UP-P true implies that X is a lower bound, i.e. (N) > N.
1464 ;;;
1465 ;;; This is used by NUMERIC-TYPE-INTERSECTION to mash the bound into
1466 ;;; the appropriate type number. X may only be a float when CLASS is
1467 ;;; FLOAT.
1468 ;;;
1469 ;;; ### Note: it is possible for the coercion to a float to overflow
1470 ;;; or underflow. This happens when the bound doesn't fit in the
1471 ;;; specified format. In this case, we should really return the
1472 ;;; appropriate {Most | Least}-{Positive | Negative}-XXX-Float float
1473 ;;; of desired format. But these conditions aren't currently signalled
1474 ;;; in any useful way.
1475 ;;;
1476 ;;; Also, when converting an open rational bound into a float we
1477 ;;; should probably convert it to a closed bound of the closest float
1478 ;;; in the specified format. KLUDGE: In general, open float bounds are
1479 ;;; screwed up. -- (comment from original CMU CL)
1480 (defun round-numeric-bound (x class format up-p)
1481   (if x
1482       (let ((cx (if (consp x) (car x) x)))
1483         (ecase class
1484           ((nil rational) x)
1485           (integer
1486            (if (and (consp x) (integerp cx))
1487                (if up-p (1+ cx) (1- cx))
1488                (if up-p (ceiling cx) (floor cx))))
1489           (float
1490            (let ((res (if format (coerce cx format) (float cx))))
1491              (if (consp x) (list res) res)))))
1492       nil))
1493
1494 ;;; Handle the case of type intersection on two numeric types. We use
1495 ;;; TYPES-EQUAL-OR-INTERSECT to throw out the case of types with no
1496 ;;; intersection. If an attribute in TYPE1 is unspecified, then we use
1497 ;;; TYPE2's attribute, which must be at least as restrictive. If the
1498 ;;; types intersect, then the only attributes that can be specified
1499 ;;; and different are the class and the bounds.
1500 ;;;
1501 ;;; When the class differs, we use the more restrictive class. The
1502 ;;; only interesting case is RATIONAL/INTEGER, since RATIONAL includes
1503 ;;; INTEGER.
1504 ;;;
1505 ;;; We make the result lower (upper) bound the maximum (minimum) of
1506 ;;; the argument lower (upper) bounds. We convert the bounds into the
1507 ;;; appropriate numeric type before maximizing. This avoids possible
1508 ;;; confusion due to mixed-type comparisons (but I think the result is
1509 ;;; the same).
1510 (!define-type-method (number :simple-intersection2) (type1 type2)
1511   (declare (type numeric-type type1 type2))
1512   (if (numeric-types-intersect type1 type2)
1513       (let* ((class1 (numeric-type-class type1))
1514              (class2 (numeric-type-class type2))
1515              (class (ecase class1
1516                       ((nil) class2)
1517                       ((integer float) class1)
1518                       (rational (if (eq class2 'integer)
1519                                        'integer
1520                                        'rational))))
1521              (format (or (numeric-type-format type1)
1522                          (numeric-type-format type2))))
1523         (make-numeric-type
1524          :class class
1525          :format format
1526          :complexp (or (numeric-type-complexp type1)
1527                        (numeric-type-complexp type2))
1528          :low (numeric-bound-max
1529                (round-numeric-bound (numeric-type-low type1)
1530                                     class format t)
1531                (round-numeric-bound (numeric-type-low type2)
1532                                     class format t)
1533                > >= nil)
1534          :high (numeric-bound-max
1535                 (round-numeric-bound (numeric-type-high type1)
1536                                      class format nil)
1537                 (round-numeric-bound (numeric-type-high type2)
1538                                      class format nil)
1539                 < <= nil)))
1540       *empty-type*))
1541
1542 ;;; Given two float formats, return the one with more precision. If
1543 ;;; either one is null, return NIL.
1544 (defun float-format-max (f1 f2)
1545   (when (and f1 f2)
1546     (dolist (f *float-formats* (error "bad float format: ~S" f1))
1547       (when (or (eq f f1) (eq f f2))
1548         (return f)))))
1549
1550 ;;; Return the result of an operation on TYPE1 and TYPE2 according to
1551 ;;; the rules of numeric contagion. This is always NUMBER, some float
1552 ;;; format (possibly complex) or RATIONAL. Due to rational
1553 ;;; canonicalization, there isn't much we can do here with integers or
1554 ;;; rational complex numbers.
1555 ;;;
1556 ;;; If either argument is not a NUMERIC-TYPE, then return NUMBER. This
1557 ;;; is useful mainly for allowing types that are technically numbers,
1558 ;;; but not a NUMERIC-TYPE.
1559 (defun numeric-contagion (type1 type2)
1560   (if (and (numeric-type-p type1) (numeric-type-p type2))
1561       (let ((class1 (numeric-type-class type1))
1562             (class2 (numeric-type-class type2))
1563             (format1 (numeric-type-format type1))
1564             (format2 (numeric-type-format type2))
1565             (complexp1 (numeric-type-complexp type1))
1566             (complexp2 (numeric-type-complexp type2)))
1567         (cond ((or (null complexp1)
1568                    (null complexp2))
1569                (specifier-type 'number))
1570               ((eq class1 'float)
1571                (make-numeric-type
1572                 :class 'float
1573                 :format (ecase class2
1574                           (float (float-format-max format1 format2))
1575                           ((integer rational) format1)
1576                           ((nil)
1577                            ;; A double-float with any real number is a
1578                            ;; double-float.
1579                            #!-long-float
1580                            (if (eq format1 'double-float)
1581                              'double-float
1582                              nil)
1583                            ;; A long-float with any real number is a
1584                            ;; long-float.
1585                            #!+long-float
1586                            (if (eq format1 'long-float)
1587                              'long-float
1588                              nil)))
1589                 :complexp (if (or (eq complexp1 :complex)
1590                                   (eq complexp2 :complex))
1591                               :complex
1592                               :real)))
1593               ((eq class2 'float) (numeric-contagion type2 type1))
1594               ((and (eq complexp1 :real) (eq complexp2 :real))
1595                (make-numeric-type
1596                 :class (and class1 class2 'rational)
1597                 :complexp :real))
1598               (t
1599                (specifier-type 'number))))
1600       (specifier-type 'number)))
1601 \f
1602 ;;;; array types
1603
1604 (!define-type-class array)
1605
1606 ;;; What this does depends on the setting of the
1607 ;;; *USE-IMPLEMENTATION-TYPES* switch. If true, return the specialized
1608 ;;; element type, otherwise return the original element type.
1609 (defun specialized-element-type-maybe (type)
1610   (declare (type array-type type))
1611   (if *use-implementation-types*
1612       (array-type-specialized-element-type type)
1613       (array-type-element-type type)))
1614
1615 (!define-type-method (array :simple-=) (type1 type2)
1616   (values (and (equal (array-type-dimensions type1)
1617                       (array-type-dimensions type2))
1618                (eq (array-type-complexp type1)
1619                    (array-type-complexp type2))
1620                (type= (specialized-element-type-maybe type1)
1621                       (specialized-element-type-maybe type2)))
1622           t))
1623
1624 (!define-type-method (array :unparse) (type)
1625   (let ((dims (array-type-dimensions type))
1626         (eltype (type-specifier (array-type-element-type type)))
1627         (complexp (array-type-complexp type)))
1628     (cond ((eq dims '*)
1629            (if (eq eltype '*)
1630                (if complexp 'array 'simple-array)
1631                (if complexp `(array ,eltype) `(simple-array ,eltype))))
1632           ((= (length dims) 1)
1633            (if complexp
1634                (if (eq (car dims) '*)
1635                    (case eltype
1636                      (bit 'bit-vector)
1637                      (base-char 'base-string)
1638                      (character 'string)
1639                      (* 'vector)
1640                      (t `(vector ,eltype)))
1641                    (case eltype
1642                      (bit `(bit-vector ,(car dims)))
1643                      (base-char `(base-string ,(car dims)))
1644                      (character `(string ,(car dims)))
1645                      (t `(vector ,eltype ,(car dims)))))
1646                (if (eq (car dims) '*)
1647                    (case eltype
1648                      (bit 'simple-bit-vector)
1649                      (base-char 'simple-base-string)
1650                      (character 'simple-string)
1651                      ((t) 'simple-vector)
1652                      (t `(simple-array ,eltype (*))))
1653                    (case eltype
1654                      (bit `(simple-bit-vector ,(car dims)))
1655                      (base-char `(simple-base-string ,(car dims)))
1656                      (character `(simple-string ,(car dims)))
1657                      ((t) `(simple-vector ,(car dims)))
1658                      (t `(simple-array ,eltype ,dims))))))
1659           (t
1660            (if complexp
1661                `(array ,eltype ,dims)
1662                `(simple-array ,eltype ,dims))))))
1663
1664 (!define-type-method (array :simple-subtypep) (type1 type2)
1665   (let ((dims1 (array-type-dimensions type1))
1666         (dims2 (array-type-dimensions type2))
1667         (complexp2 (array-type-complexp type2)))
1668     (cond (;; not subtypep unless dimensions are compatible
1669            (not (or (eq dims2 '*)
1670                     (and (not (eq dims1 '*))
1671                          ;; (sbcl-0.6.4 has trouble figuring out that
1672                          ;; DIMS1 and DIMS2 must be lists at this
1673                          ;; point, and knowing that is important to
1674                          ;; compiling EVERY efficiently.)
1675                          (= (length (the list dims1))
1676                             (length (the list dims2)))
1677                          (every (lambda (x y)
1678                                   (or (eq y '*) (eql x y)))
1679                                 (the list dims1)
1680                                 (the list dims2)))))
1681            (values nil t))
1682           ;; not subtypep unless complexness is compatible
1683           ((not (or (eq complexp2 :maybe)
1684                     (eq (array-type-complexp type1) complexp2)))
1685            (values nil t))
1686           ;; Since we didn't fail any of the tests above, we win
1687           ;; if the TYPE2 element type is wild.
1688           ((eq (array-type-element-type type2) *wild-type*)
1689            (values t t))
1690           (;; Since we didn't match any of the special cases above, we
1691            ;; can't give a good answer unless both the element types
1692            ;; have been defined.
1693            (or (unknown-type-p (array-type-element-type type1))
1694                (unknown-type-p (array-type-element-type type2)))
1695            (values nil nil))
1696           (;; Otherwise, the subtype relationship holds iff the
1697            ;; types are equal, and they're equal iff the specialized
1698            ;; element types are identical.
1699            t
1700            (values (type= (specialized-element-type-maybe type1)
1701                           (specialized-element-type-maybe type2))
1702                    t)))))
1703
1704 (!define-superclasses array
1705   ((string string)
1706    (vector vector)
1707    (array))
1708   !cold-init-forms)
1709
1710 (defun array-types-intersect (type1 type2)
1711   (declare (type array-type type1 type2))
1712   (let ((dims1 (array-type-dimensions type1))
1713         (dims2 (array-type-dimensions type2))
1714         (complexp1 (array-type-complexp type1))
1715         (complexp2 (array-type-complexp type2)))
1716     ;; See whether dimensions are compatible.
1717     (cond ((not (or (eq dims1 '*) (eq dims2 '*)
1718                     (and (= (length dims1) (length dims2))
1719                          (every #'(lambda (x y)
1720                                     (or (eq x '*) (eq y '*) (= x y)))
1721                                 dims1 dims2))))
1722            (values nil t))
1723           ;; See whether complexpness is compatible.
1724           ((not (or (eq complexp1 :maybe)
1725                     (eq complexp2 :maybe)
1726                     (eq complexp1 complexp2)))
1727            (values nil t))
1728           ;; If either element type is wild, then they intersect.
1729           ;; Otherwise, the types must be identical.
1730           ((or (eq (array-type-element-type type1) *wild-type*)
1731                (eq (array-type-element-type type2) *wild-type*)
1732                (type= (specialized-element-type-maybe type1)
1733                       (specialized-element-type-maybe type2)))
1734
1735            (values t t))
1736           (t
1737            (values nil t)))))
1738
1739 (!define-type-method (array :simple-intersection2) (type1 type2)
1740   (declare (type array-type type1 type2))
1741   (if (array-types-intersect type1 type2)
1742       (let ((dims1 (array-type-dimensions type1))
1743             (dims2 (array-type-dimensions type2))
1744             (complexp1 (array-type-complexp type1))
1745             (complexp2 (array-type-complexp type2))
1746             (eltype1 (array-type-element-type type1))
1747             (eltype2 (array-type-element-type type2)))
1748         (specialize-array-type
1749          (make-array-type
1750           :dimensions (cond ((eq dims1 '*) dims2)
1751                             ((eq dims2 '*) dims1)
1752                             (t
1753                              (mapcar (lambda (x y) (if (eq x '*) y x))
1754                                      dims1 dims2)))
1755           :complexp (if (eq complexp1 :maybe) complexp2 complexp1)
1756           :element-type (if (eq eltype1 *wild-type*) eltype2 eltype1))))
1757       *empty-type*))
1758
1759 ;;; Check a supplied dimension list to determine whether it is legal,
1760 ;;; and return it in canonical form (as either '* or a list).
1761 (defun canonical-array-dimensions (dims)
1762   (typecase dims
1763     ((member *) dims)
1764     (integer
1765      (when (minusp dims)
1766        (error "Arrays can't have a negative number of dimensions: ~S" dims))
1767      (when (>= dims sb!xc:array-rank-limit)
1768        (error "array type with too many dimensions: ~S" dims))
1769      (make-list dims :initial-element '*))
1770     (list
1771      (when (>= (length dims) sb!xc:array-rank-limit)
1772        (error "array type with too many dimensions: ~S" dims))
1773      (dolist (dim dims)
1774        (unless (eq dim '*)
1775          (unless (and (integerp dim)
1776                       (>= dim 0)
1777                       (< dim sb!xc:array-dimension-limit))
1778            (error "bad dimension in array type: ~S" dim))))
1779      dims)
1780     (t
1781      (error "Array dimensions is not a list, integer or *:~%  ~S" dims))))
1782 \f
1783 ;;;; MEMBER types
1784
1785 (!define-type-class member)
1786
1787 (!define-type-method (member :unparse) (type)
1788   (let ((members (member-type-members type)))
1789     (if (equal members '(nil))
1790         'null
1791         `(member ,@members))))
1792
1793 (!define-type-method (member :simple-subtypep) (type1 type2)
1794   (values (subsetp (member-type-members type1) (member-type-members type2))
1795           t))
1796
1797 (!define-type-method (member :complex-subtypep-arg1) (type1 type2)
1798   (every/type (swapped-args-fun #'ctypep)
1799               type2
1800               (member-type-members type1)))
1801
1802 ;;; We punt if the odd type is enumerable and intersects with the
1803 ;;; MEMBER type. If not enumerable, then it is definitely not a
1804 ;;; subtype of the MEMBER type.
1805 (!define-type-method (member :complex-subtypep-arg2) (type1 type2)
1806   (cond ((not (type-enumerable type1)) (values nil t))
1807         ((types-equal-or-intersect type1 type2) (values nil nil))
1808         (t (values nil t))))
1809
1810 (!define-type-method (member :simple-intersection2) (type1 type2)
1811   (let ((mem1 (member-type-members type1))
1812         (mem2 (member-type-members type2)))
1813     (cond ((subsetp mem1 mem2) type1)
1814           ((subsetp mem2 mem1) type2)
1815           (t
1816            (let ((res (intersection mem1 mem2)))
1817              (if res
1818                  (make-member-type :members res)
1819                  *empty-type*))))))
1820
1821 (!define-type-method (member :complex-intersection2) (type1 type2)
1822   (block punt                
1823     (collect ((members))
1824       (let ((mem2 (member-type-members type2)))
1825         (dolist (member mem2)
1826           (multiple-value-bind (val win) (ctypep member type1)
1827             (unless win
1828               (return-from punt nil))
1829             (when val (members member))))
1830         (cond ((subsetp mem2 (members)) type2)
1831               ((null (members)) *empty-type*)
1832               (t
1833                (make-member-type :members (members))))))))
1834
1835 ;;; We don't need a :COMPLEX-UNION2, since the only interesting case is
1836 ;;; a union type, and the member/union interaction is handled by the
1837 ;;; union type method.
1838 (!define-type-method (member :simple-union2) (type1 type2)
1839   (let ((mem1 (member-type-members type1))
1840         (mem2 (member-type-members type2)))
1841     (cond ((subsetp mem1 mem2) type2)
1842           ((subsetp mem2 mem1) type1)
1843           (t
1844            (make-member-type :members (union mem1 mem2))))))
1845
1846 (!define-type-method (member :simple-=) (type1 type2)
1847   (let ((mem1 (member-type-members type1))
1848         (mem2 (member-type-members type2)))
1849     (values (and (subsetp mem1 mem2)
1850                  (subsetp mem2 mem1))
1851             t)))
1852
1853 (!define-type-method (member :complex-=) (type1 type2)
1854   (if (type-enumerable type1)
1855       (multiple-value-bind (val win) (csubtypep type2 type1)
1856         (if (or val (not win))
1857             (values nil nil)
1858             (values nil t)))
1859       (values nil t)))
1860
1861 (!def-type-translator member (&rest members)
1862   (if members
1863     (make-member-type :members (remove-duplicates members))
1864     *empty-type*))
1865 \f
1866 ;;;; intersection types
1867 ;;;;
1868 ;;;; Until version 0.6.10.6, SBCL followed the original CMU CL approach
1869 ;;;; of punting on all AND types, not just the unreasonably complicated
1870 ;;;; ones. The change was motivated by trying to get the KEYWORD type
1871 ;;;; to behave sensibly:
1872 ;;;;    ;; reasonable definition
1873 ;;;;    (DEFTYPE KEYWORD () '(AND SYMBOL (SATISFIES KEYWORDP)))
1874 ;;;;    ;; reasonable behavior
1875 ;;;;    (AVER (SUBTYPEP 'KEYWORD 'SYMBOL))
1876 ;;;; Without understanding a little about the semantics of AND, we'd
1877 ;;;; get (SUBTYPEP 'KEYWORD 'SYMBOL)=>NIL,NIL and, for entirely
1878 ;;;; parallel reasons, (SUBTYPEP 'RATIO 'NUMBER)=>NIL,NIL. That's
1879 ;;;; not so good..)
1880 ;;;;
1881 ;;;; We still follow the example of CMU CL to some extent, by punting
1882 ;;;; (to the opaque HAIRY-TYPE) on sufficiently complicated types
1883 ;;;; involving AND.
1884
1885 (!define-type-class intersection)
1886
1887 ;;; A few intersection types have special names. The others just get
1888 ;;; mechanically unparsed.
1889 (!define-type-method (intersection :unparse) (type)
1890   (declare (type ctype type))
1891   (or (find type '(ratio bignum keyword) :key #'specifier-type :test #'type=)
1892       `(and ,@(mapcar #'type-specifier (intersection-type-types type)))))
1893
1894 ;;; shared machinery for type equality: true if every type in the set
1895 ;;; TYPES1 matches a type in the set TYPES2 and vice versa
1896 (defun type=-set (types1 types2)
1897   (flet (;; true if every type in the set X matches a type in the set Y
1898          (type<=-set (x y)
1899            (declare (type list x y))
1900            (every (lambda (xelement)
1901                     (position xelement y :test #'type=))
1902                   x)))
1903     (values (and (type<=-set types1 types2)
1904                  (type<=-set types2 types1))
1905             t)))
1906
1907 ;;; Two intersection types are equal if their subtypes are equal sets.
1908 ;;;
1909 ;;; FIXME: Might it be better to use
1910 ;;;   (AND (SUBTYPEP X Y) (SUBTYPEP Y X))
1911 ;;; instead, since SUBTYPEP is the usual relationship that we care
1912 ;;; most about, so it would be good to leverage any ingenuity there
1913 ;;; in this more obscure method?
1914 (!define-type-method (intersection :simple-=) (type1 type2)
1915   (type=-set (intersection-type-types type1)
1916              (intersection-type-types type2)))
1917
1918 (flet ((intersection-complex-subtypep-arg1 (type1 type2)
1919          (any/type (swapped-args-fun #'csubtypep)
1920                    type2
1921                    (intersection-type-types type1))))
1922   (!define-type-method (intersection :simple-subtypep) (type1 type2)
1923     (every/type #'intersection-complex-subtypep-arg1
1924                 type1
1925                 (intersection-type-types type2)))
1926   (!define-type-method (intersection :complex-subtypep-arg1) (type1 type2)
1927     (intersection-complex-subtypep-arg1 type1 type2)))
1928
1929 (!define-type-method (intersection :complex-subtypep-arg2) (type1 type2)
1930   (every/type #'csubtypep type1 (intersection-type-types type2)))
1931
1932 (!def-type-translator and (&whole whole &rest type-specifiers)
1933   (apply #'type-intersection
1934          (mapcar #'specifier-type
1935                  type-specifiers)))
1936 \f
1937 ;;;; union types
1938
1939 (!define-type-class union)
1940
1941 ;;; The LIST type has a special name. Other union types just get
1942 ;;; mechanically unparsed.
1943 (!define-type-method (union :unparse) (type)
1944   (declare (type ctype type))
1945   (if (type= type (specifier-type 'list))
1946       'list
1947       `(or ,@(mapcar #'type-specifier (union-type-types type)))))
1948
1949 ;;; Two union types are equal if their subtypes are equal sets.
1950 (!define-type-method (union :simple-=) (type1 type2)
1951   (type=-set (union-type-types type1)
1952              (union-type-types type2)))
1953
1954 ;;; Similarly, a union type is a subtype of another if every element
1955 ;;; of TYPE1 is a subtype of some element of TYPE2.
1956 (!define-type-method (union :simple-subtypep) (type1 type2)
1957   (every/type (swapped-args-fun #'union-complex-subtypep-arg2)
1958               type2
1959               (union-type-types type1)))
1960
1961 (defun union-complex-subtypep-arg1 (type1 type2)
1962   (every/type (swapped-args-fun #'csubtypep)
1963               type2
1964               (union-type-types type1)))
1965 (!define-type-method (union :complex-subtypep-arg1) (type1 type2)
1966   (union-complex-subtypep-arg1 type1 type2))
1967
1968 (defun union-complex-subtypep-arg2 (type1 type2)
1969   (any/type #'csubtypep type1 (union-type-types type2)))
1970 (!define-type-method (union :complex-subtypep-arg2) (type1 type2)
1971   (union-complex-subtypep-arg2 type1 type2))
1972
1973 (!define-type-method (union :simple-intersection2 :complex-intersection2)
1974                      (type1 type2)
1975   ;; The CSUBTYPEP clauses here let us simplify e.g.
1976   ;;   (TYPE-INTERSECTION2 (SPECIFIER-TYPE 'LIST)
1977   ;;                       (SPECIFIER-TYPE '(OR LIST VECTOR)))
1978   ;; (where LIST is (OR CONS NULL)).
1979   ;;
1980   ;; The tests are more or less (CSUBTYPEP TYPE1 TYPE2) and vice
1981   ;; versa, but it's important that we pre-expand them into
1982   ;; specialized operations on individual elements of
1983   ;; UNION-TYPE-TYPES, instead of using the ordinary call to
1984   ;; CSUBTYPEP, in order to avoid possibly invoking any methods which
1985   ;; might in turn invoke (TYPE-INTERSECTION2 TYPE1 TYPE2) and thus
1986   ;; cause infinite recursion.
1987   (cond ((union-complex-subtypep-arg2 type1 type2)
1988          type1)
1989         ((union-complex-subtypep-arg1 type2 type1)
1990          type2)
1991         (t 
1992          ;; KLUDGE: This code accumulates a sequence of TYPE-UNION2
1993          ;; operations in a particular order, and gives up if any of
1994          ;; the sub-unions turn out not to be simple. In other cases
1995          ;; ca. sbcl-0.6.11.15, that approach to taking a union was a
1996          ;; bad idea, since it can overlook simplifications which
1997          ;; might occur if the terms were accumulated in a different
1998          ;; order. It's possible that that will be a problem here too.
1999          ;; However, I can't think of a good example to demonstrate
2000          ;; it, and without an example to demonstrate it I can't write
2001          ;; test cases, and without test cases I don't want to
2002          ;; complicate the code to address what's still a hypothetical
2003          ;; problem. So I punted. -- WHN 2001-03-20
2004          (let ((accumulator *empty-type*))
2005            (dolist (t2 (union-type-types type2) accumulator)
2006              (setf accumulator
2007                    (type-union2 accumulator
2008                                 (type-intersection type1 t2)))
2009              ;; When our result isn't simple any more (because
2010              ;; TYPE-UNION2 was unable to give us a simple result)
2011              (unless accumulator
2012                (return nil)))))))
2013
2014 (!def-type-translator or (&rest type-specifiers)
2015   (apply #'type-union
2016          (mapcar #'specifier-type
2017                  type-specifiers)))
2018 \f
2019 ;;;; CONS types
2020
2021 (!define-type-class cons)
2022
2023 (!def-type-translator cons (&optional (car-type-spec '*) (cdr-type-spec '*))
2024   (make-cons-type (specifier-type car-type-spec)
2025                   (specifier-type cdr-type-spec)))
2026  
2027 (!define-type-method (cons :unparse) (type)
2028   (let ((car-eltype (type-specifier (cons-type-car-type type)))
2029         (cdr-eltype (type-specifier (cons-type-cdr-type type))))
2030     (if (and (member car-eltype '(t *))
2031              (member cdr-eltype '(t *)))
2032         'cons
2033         `(cons ,car-eltype ,cdr-eltype))))
2034  
2035 (!define-type-method (cons :simple-=) (type1 type2)
2036   (declare (type cons-type type1 type2))
2037   (and (type= (cons-type-car-type type1) (cons-type-car-type type2))
2038        (type= (cons-type-cdr-type type1) (cons-type-cdr-type type2))))
2039  
2040 (!define-type-method (cons :simple-subtypep) (type1 type2)
2041   (declare (type cons-type type1 type2))
2042   (multiple-value-bind (val-car win-car)
2043       (csubtypep (cons-type-car-type type1) (cons-type-car-type type2))
2044     (multiple-value-bind (val-cdr win-cdr)
2045         (csubtypep (cons-type-cdr-type type1) (cons-type-cdr-type type2))
2046       (if (and val-car val-cdr)
2047           (values t (and win-car win-cdr))
2048           (values nil (or win-car win-cdr))))))
2049  
2050 ;;; Give up if a precise type is not possible, to avoid returning
2051 ;;; overly general types.
2052 (!define-type-method (cons :simple-union2) (type1 type2)
2053   (declare (type cons-type type1 type2))
2054   (let ((car-type1 (cons-type-car-type type1))
2055         (car-type2 (cons-type-car-type type2))
2056         (cdr-type1 (cons-type-cdr-type type1))
2057         (cdr-type2 (cons-type-cdr-type type2)))
2058     (cond ((type= car-type1 car-type2)
2059            (make-cons-type car-type1
2060                            (type-union cdr-type1 cdr-type2)))
2061           ((type= cdr-type1 cdr-type2)
2062            (make-cons-type (type-union cdr-type1 cdr-type2)
2063                            cdr-type1)))))
2064
2065 (!define-type-method (cons :simple-intersection2) (type1 type2)
2066   (declare (type cons-type type1 type2))
2067   (let (car-int2
2068         cdr-int2)
2069     (and (setf car-int2 (type-intersection2 (cons-type-car-type type1)
2070                                             (cons-type-car-type type2)))
2071          (setf cdr-int2 (type-intersection2 (cons-type-cdr-type type1)
2072                                             (cons-type-cdr-type type2)))
2073          (make-cons-type car-int2 cdr-int2))))
2074 \f
2075 ;;; Return the type that describes all objects that are in X but not
2076 ;;; in Y. If we can't determine this type, then return NIL.
2077 ;;;
2078 ;;; For now, we only are clever dealing with union and member types.
2079 ;;; If either type is not a union type, then we pretend that it is a
2080 ;;; union of just one type. What we do is remove from X all the types
2081 ;;; that are a subtype any type in Y. If any type in X intersects with
2082 ;;; a type in Y but is not a subtype, then we give up.
2083 ;;;
2084 ;;; We must also special-case any member type that appears in the
2085 ;;; union. We remove from X's members all objects that are TYPEP to Y.
2086 ;;; If Y has any members, we must be careful that none of those
2087 ;;; members are CTYPEP to any of Y's non-member types. We give up in
2088 ;;; this case, since to compute that difference we would have to break
2089 ;;; the type from X into some collection of types that represents the
2090 ;;; type without that particular element. This seems too hairy to be
2091 ;;; worthwhile, given its low utility.
2092 (defun type-difference (x y)
2093   (let ((x-types (if (union-type-p x) (union-type-types x) (list x)))
2094         (y-types (if (union-type-p y) (union-type-types y) (list y))))
2095     (collect ((res))
2096       (dolist (x-type x-types)
2097         (if (member-type-p x-type)
2098             (collect ((members))
2099               (dolist (mem (member-type-members x-type))
2100                 (multiple-value-bind (val win) (ctypep mem y)
2101                   (unless win (return-from type-difference nil))
2102                   (unless val
2103                     (members mem))))
2104               (when (members)
2105                 (res (make-member-type :members (members)))))
2106             (dolist (y-type y-types (res x-type))
2107               (multiple-value-bind (val win) (csubtypep x-type y-type)
2108                 (unless win (return-from type-difference nil))
2109                 (when val (return))
2110                 (when (types-equal-or-intersect x-type y-type)
2111                   (return-from type-difference nil))))))
2112       (let ((y-mem (find-if #'member-type-p y-types)))
2113         (when y-mem
2114           (let ((members (member-type-members y-mem)))
2115             (dolist (x-type x-types)
2116               (unless (member-type-p x-type)
2117                 (dolist (member members)
2118                   (multiple-value-bind (val win) (ctypep member x-type)
2119                     (when (or (not win) val)
2120                       (return-from type-difference nil)))))))))
2121       (apply #'type-union (res)))))
2122 \f
2123 (!def-type-translator array (&optional (element-type '*)
2124                                        (dimensions '*))
2125   (specialize-array-type
2126    (make-array-type :dimensions (canonical-array-dimensions dimensions)
2127                     :element-type (specifier-type element-type))))
2128
2129 (!def-type-translator simple-array (&optional (element-type '*)
2130                                               (dimensions '*))
2131   (specialize-array-type
2132    (make-array-type :dimensions (canonical-array-dimensions dimensions)
2133                     :element-type (specifier-type element-type)
2134                     :complexp nil)))
2135 \f
2136 ;;;; utilities shared between cross-compiler and target system
2137
2138 ;;; Does the type derived from compilation of an actual function
2139 ;;; definition satisfy declarations of a function's type?
2140 (defun defined-ftype-matches-declared-ftype-p (defined-ftype declared-ftype)
2141   (declare (type ctype defined-ftype declared-ftype))
2142   (flet ((is-built-in-class-function-p (ctype)
2143            (and (built-in-class-p ctype)
2144                 (eq (built-in-class-%name ctype) 'function))))
2145     (cond (;; DECLARED-FTYPE could certainly be #<BUILT-IN-CLASS FUNCTION>;
2146            ;; that's what happens when we (DECLAIM (FTYPE FUNCTION FOO)).
2147            (is-built-in-class-function-p declared-ftype)
2148            ;; In that case, any definition satisfies the declaration.
2149            t)
2150           (;; It's not clear whether or how DEFINED-FTYPE might be
2151            ;; #<BUILT-IN-CLASS FUNCTION>, but it's not obviously
2152            ;; invalid, so let's handle that case too, just in case.
2153            (is-built-in-class-function-p defined-ftype)
2154            ;; No matter what DECLARED-FTYPE might be, we can't prove
2155            ;; that an object of type FUNCTION doesn't satisfy it, so
2156            ;; we return success no matter what.
2157            t)
2158           (;; Otherwise both of them must be FUNCTION-TYPE objects.
2159            t
2160            ;; FIXME: For now we only check compatibility of the return
2161            ;; type, not argument types, and we don't even check the
2162            ;; return type very precisely (as per bug 94a). It would be
2163            ;; good to do a better job. Perhaps to check the
2164            ;; compatibility of the arguments, we should (1) redo
2165            ;; VALUES-TYPES-EQUAL-OR-INTERSECT as
2166            ;; ARGS-TYPES-EQUAL-OR-INTERSECT, and then (2) apply it to
2167            ;; the ARGS-TYPE slices of the FUNCTION-TYPEs. (ARGS-TYPE
2168            ;; is a base class both of VALUES-TYPE and of FUNCTION-TYPE.)
2169            (values-types-equal-or-intersect
2170             (function-type-returns defined-ftype)
2171             (function-type-returns declared-ftype))))))
2172            
2173 ;;; This messy case of CTYPE for NUMBER is shared between the
2174 ;;; cross-compiler and the target system.
2175 (defun ctype-of-number (x)
2176   (let ((num (if (complexp x) (realpart x) x)))
2177     (multiple-value-bind (complexp low high)
2178         (if (complexp x)
2179             (let ((imag (imagpart x)))
2180               (values :complex (min num imag) (max num imag)))
2181             (values :real num num))
2182       (make-numeric-type :class (etypecase num
2183                                   (integer 'integer)
2184                                   (rational 'rational)
2185                                   (float 'float))
2186                          :format (and (floatp num) (float-format-name num))
2187                          :complexp complexp
2188                          :low low
2189                          :high high))))
2190 \f
2191 (!defun-from-collected-cold-init-forms !late-type-cold-init)
2192
2193 (/show0 "late-type.lisp end of file")