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