home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / pcl / src-16f.lha / compiler / type.lisp < prev    next >
Encoding:
Text File  |  1992-05-19  |  89.8 KB  |  2,843 lines

  1. ;;; -*- Package: KERNEL; Log: C.Log -*-
  2. ;;;
  3. ;;; **********************************************************************
  4. ;;; This code was written as part of the CMU Common Lisp project at
  5. ;;; Carnegie Mellon University, and has been placed in the public domain.
  6. ;;; If you want to use this code or any part of CMU Common Lisp, please contact
  7. ;;; Scott Fahlman or slisp-group@cs.cmu.edu.
  8. ;;;
  9. (ext:file-comment
  10.   "$Header: type.lisp,v 1.41 92/04/17 00:10:26 wlott Exp $")
  11. ;;;
  12. ;;; **********************************************************************
  13. ;;;
  14. ;;;    This file contains definitions and utilities for the manipulation of
  15. ;;; Common Lisp types.  The main purpose of this code is to manage a
  16. ;;; representation for types which is more useful than Common Lisp type
  17. ;;; specifiers.
  18. ;;;
  19. ;;; Written by Rob MacLachlan
  20. ;;;
  21. (in-package "KERNEL")
  22. (use-package "ALIEN-INTERNALS")
  23.  
  24. (export '(function-type-nargs code-component code-component-p lra lra-p))
  25. (export '(make-alien-type-type alien-type-type
  26.       alien-type-type-p alien-type-type-alien-type))
  27. (import 'c-call:void)
  28. (export 'void)
  29.  
  30. (in-package "EXTENSIONS")
  31. (export 'constant-argument)
  32.  
  33. (in-package "KERNEL")
  34.  
  35.  
  36. ;;; ### Remaining incorrectnesses:
  37. ;;;
  38. ;;; Type-Union (and the OR type) doesn't properly canonicalize an exhaustive
  39. ;;; partition or coalesce contiguous ranges of numeric types.
  40. ;;;
  41. ;;; There are all sorts of nasty problems with open bounds on float types (and
  42. ;;; probably float types in general.)
  43. ;;;
  44. ;;; ratio and bignum are not recognized as numeric types.
  45.  
  46.  
  47. ;;; *Use-Implementation-Types* is a semi-public flag which determines how
  48. ;;; restrictive we are in determining type membership.  If two types are the
  49. ;;; same in the implementation, then we will consider them them the same when
  50. ;;; this switch is on.  When it is off, we try to be as restrictive as the
  51. ;;; language allows, allowing us to detect more errors.  Currently, this only
  52. ;;; affects array types.  Types such as the float types which may be made
  53. ;;; synonyms would be a good target also.
  54. ;;;
  55. (defvar *use-implementation-types*)
  56. (proclaim '(type boolean *use-implementation-types*))
  57.  
  58. ;;; These are the Common Lisp defined type specifier symbols.  These are the
  59. ;;; things which can be used as declarations without requiring the use of TYPE.
  60. (defconstant type-specifier-symbols
  61.   '(array atom bignum bit bit-vector character common compiled-function
  62.     complex cons double-float extended-char fixnum float function
  63.     hash-table integer keyword list long-float nil null number package
  64.     pathname random-state ratio rational real readtable sequence
  65.     short-float simple-array simple-bit-vector simple-string simple-vector
  66.     single-float standard-char stream string base-char symbol t vector))
  67.  
  68.  
  69. ;;; Def-Type-Translator  --  Internal
  70. ;;;
  71. ;;;    Define the translation from a type-specifier to a type structure for
  72. ;;; some particular type.  Syntax is identical to DEFTYPE.
  73. ;;;
  74. (defmacro def-type-translator (name arglist &body body)
  75.   (check-type name symbol)
  76.   (let ((whole (gensym)))
  77.     (multiple-value-bind
  78.     (body local-decs)
  79.     (lisp::parse-defmacro arglist whole body name 'def-type-translator
  80.                   :default-default ''*)
  81.       `(progn
  82.      (cold-load-init
  83.       (setf (info type translator ',name)
  84.         #'(lambda (,whole) ,@local-decs (block ,name ,body))))
  85.      ',name))))
  86.  
  87.  
  88. ;;; Defvars for these come later, after we have enough stuff defined.
  89. (proclaim '(special *wild-type* *universal-type* *empty-type*))
  90.  
  91.  
  92. ;;; This condition is signalled whenever we make a UNKNOWN-TYPE so that
  93. ;;; compiler warnings can be emitted as appropriate.
  94. ;;;
  95. (eval-when (compile load eval)
  96.   (define-condition parse-unknown-type (condition)
  97.     (specifier)))
  98.  
  99.  
  100. ;;;; Cold load hack magic.
  101.  
  102. (eval-when (compile eval)
  103.  
  104. (defparameter cold-type-init-forms nil
  105.   "Forms that must happen before top level forms are run.")
  106.  
  107. (defparameter cold-type-init-defuns nil
  108.   "Function names that enclose the above.")
  109.  
  110. (defmacro cold-load-init (&rest forms)
  111.   (if (and (consp forms) (consp (car forms)) (eq (caar forms) 'eval-when))
  112.       (let ((when (cadar forms))
  113.         (eval-when-forms (cddar forms)))
  114.     (unless (= (length forms) 1)
  115.       (warn "Can't cold-load-init other forms along with an eval-when."))
  116.     (when (member 'load when)
  117.       (setf cold-type-init-forms
  118.         (nconc cold-type-init-forms (copy-list eval-when-forms))))
  119.     `(eval-when ,(remove 'load when)
  120.        ,@eval-when-forms))
  121.       (progn
  122.     (setf cold-type-init-forms
  123.           (nconc cold-type-init-forms (copy-list forms)))
  124.     nil)))
  125.  
  126. (defmacro emit-cold-load-defuns ()
  127.   (let ((index 0))
  128.     (collect ((defuns))
  129.       (loop
  130.     (unless cold-type-init-forms (return))
  131.     (let ((num-forms (min 10 (length cold-type-init-forms)))
  132.           (name (intern (format nil "TYPE-INIT-~D" (incf index)))))
  133.       (defuns `(defun ,name ()
  134.              ,@(subseq cold-type-init-forms 0 num-forms)))
  135.       (setf cold-type-init-forms (nthcdr num-forms cold-type-init-forms))
  136.       (push (list name) cold-type-init-defuns)))
  137.       (setf cold-type-init-defuns (nreverse cold-type-init-defuns))
  138.       `(progn
  139.      ,@(defuns)))))
  140.  
  141. (defmacro do-cold-load-init-forms ()
  142.   `(progn
  143.      ,@cold-type-init-defuns))
  144.  
  145. ); eval-when
  146.  
  147. #+nil ;; Use this definition if you are trying to use this interactivly.
  148. (defmacro cold-load-init (&rest forms)
  149.   `(progn ,@forms))
  150.  
  151.  
  152.  
  153. ;;;; Type classes:
  154. ;;;
  155. ;;;    The TYPE-CLASS structure represents the "kind" of a type.  It mainly
  156. ;;; contains functions which are methods on that kind of type, but is also use
  157. ;;; in EQ comparisons to determined if two types have the "same kind".
  158.  
  159. (defvar *type-classes*)
  160.  
  161. ;;; TYPE-CLASS-OR-LOSE  --  Internal
  162. ;;;
  163. (defun type-class-or-lose (name)
  164.   (or (gethash name *type-classes*)
  165.       (error "~S is not a defined type class." name)))
  166.  
  167. ;;; MUST-SUPPLY-THIS  --  Internal
  168. ;;;
  169. (defun must-supply-this (&rest foo)
  170.   (error "Missing type method for ~S" foo))
  171.  
  172.  
  173. (defstruct (type-class
  174.         (:print-function
  175.          (lambda (s stream d)
  176.            (declare (ignore d))
  177.            (format stream "#<TYPE-CLASS ~S>" (type-class-name s)))))
  178.                  
  179.   ;;
  180.   ;; Name of this type class, used to resolve references at load time.
  181.   (name nil :type symbol)
  182.   ;;
  183.   ;; Dyadic type methods.  If the classes of the two types are EQ, then we call
  184.   ;; the SIMPLE-xxx method.  If the classes are not EQ, and either type's class
  185.   ;; has a COMPLEX-xxx method, then we call it.
  186.   ;;
  187.   ;; Although it is undefined which method will get precedence when both types
  188.   ;; have a complex method, the complex method can assume that the second arg
  189.   ;; always is in its class, and the first always is not.  The arguments to
  190.   ;; commutative operations will be swapped if the first argument has a complex
  191.   ;; method.
  192.   ;;
  193.   ;; Since SUBTYPEP is not commutative, we have two complex methods.  the ARG1
  194.   ;; method is only called when the first argument is in its class, and the
  195.   ;; ARG2 method is only called when called when the second type is.  If either
  196.   ;; is specified, both must be.
  197.   (simple-subtypep #'must-supply-this :type function)
  198.   (complex-subtypep-arg1 nil :type (or function null))
  199.   (complex-subtypep-arg2 nil :type (or function null))
  200.   ;;
  201.   ;; If SIMPLE-UNION is unspecified, then the union is computed to be the
  202.   ;; supertype (if a subtype relationship exists), or a two type union.
  203.   ;; SIMPLE-UNION should return NIL when the result would be the two type
  204.   ;; union.
  205.   (simple-union nil :type (or function null))
  206.   (complex-union nil :type (or function null))
  207.   ;;
  208.   ;; The default intersection methods assume that there is an intersection iff
  209.   ;; a subtype relationship exists.
  210.   (simple-intersection #'vanilla-intersection :type function)
  211.   (complex-intersection nil :type (or function null))
  212.   ;;
  213.   (simple-= #'must-supply-this :type function)
  214.   (complex-= nil :type (or function null))
  215.   ;;
  216.   ;; Function which returns a Common Lisp type specifier representing this
  217.   ;; type.
  218.   (unparse #'must-supply-this :type function)
  219.   
  220.   #|
  221.   Not used, and not really right.  Probably we want a TYPE= alist for the
  222.   unary operations, since there are lots of interesting unary predicates that
  223.   aren't equivalent to an entire class
  224.   ;;
  225.   ;; Names of functions used for testing the type of objects in this type
  226.   ;; class.  UNARY-PREDICATE takes just the object, whereas PREDICATE gets
  227.   ;; passed both the object and the CTYPE.  Normally one or the other will be
  228.   ;; supplied for any type that can be passed to TYPEP; there is no point in
  229.   ;; supplying both.
  230.   (unary-typep nil :type (or symbol null))
  231.   (typep nil :type (or symbol null))
  232.   ;;
  233.   ;; Like TYPEP, UNARY-TYPEP except these functions coerce objects to this
  234.   ;; type.
  235.   (unary-coerce nil :type (or symbol null))
  236.   (coerce :type (or symbol null))
  237.   |#
  238.   )
  239.  
  240.  
  241. (eval-when (compile load eval)
  242.  
  243. (defconstant type-class-function-slots
  244.   '((:simple-subtypep . type-class-simple-subtypep)
  245.     (:complex-subtypep-arg1 . type-class-complex-subtypep-arg1)
  246.     (:complex-subtypep-arg2 . type-class-complex-subtypep-arg2)
  247.     (:simple-union . type-class-simple-union)
  248.     (:complex-union . type-class-complex-union)
  249.     (:simple-intersection . type-class-simple-intersection)
  250.     (:complex-intersection . type-class-complex-intersection)
  251.     (:simple-= . type-class-simple-=)
  252.     (:complex-= . type-class-complex-=)
  253.     (:unparse . type-class-unparse)))
  254.  
  255. (defconstant type-class-symbol-slots
  256.   '((:unary-typep . type-class-unary-typep)
  257.     (:typep . type-class-typep)
  258.     (:unary-coerce . type-class-unary-coerce)
  259.     (:coerce . type-class-coerce)))
  260.   
  261.  
  262. ;;; CLASS-FUNCTION-SLOT-OR-LOSE  --  Internal
  263. ;;;
  264. (defun class-function-slot-or-lose (name)
  265.   (or (cdr (assoc name type-class-function-slots))
  266.       (error "~S is not a defined type class method." name)))
  267.  
  268. ); Eval-When (Compile Load Eval)
  269.  
  270.  
  271. ;;; DEFINE-TYPE-METHOD  --  Internal
  272. ;;;
  273. (defmacro define-type-method ((class method &rest more-methods)
  274.                   lambda-list &body body)
  275.   "DEFINE-TYPE-METHOD (Class-Name Method-Name+) Lambda-List Form*"
  276.   (let ((name (symbolicate CLASS "-" method "-TYPE-METHOD")))
  277.     `(progn
  278.        (defun ,name ,lambda-list ,@body)
  279.        (cold-load-init
  280.     ,@(mapcar #'(lambda (method)
  281.               `(setf (,(class-function-slot-or-lose method)
  282.                   (type-class-or-lose ',class))
  283.                  #',name))
  284.           (cons method more-methods)))
  285.        (undefined-value))))
  286.  
  287.  
  288. ;;; DEFINE-TYPE-CLASS  --  Internal
  289. ;;;
  290. (defmacro define-type-class (name &optional inherits)
  291.   "DEFINE-TYPE-CLASS Name [Inherits]"
  292.   `(cold-load-init
  293.     ,(once-only ((n-class (if inherits
  294.                   `(copy-type-class (type-class-or-lose ',inherits))
  295.                   '(make-type-class))))
  296.        `(progn
  297.       (setf (type-class-name ,n-class) ',name)
  298.       (setf (gethash ',name *type-classes*) ,n-class)
  299.       (undefined-value)))))
  300.  
  301.  
  302. ;;; INVOKE-TYPE-METHOD  --  Internal
  303. ;;;
  304. ;;;    Invoke a type method on TYPE1 and TYPE2.  If the two types have the same
  305. ;;; class, invoke the simple method.  Otherwise, invoke any complex method.  If
  306. ;;; there isn't a distinct complex-arg1 method, then swap the arguments when
  307. ;;; calling type1's method.  If no applicable method, return DEFAULT.
  308. ;;;
  309. (defmacro invoke-type-method (simple complex-arg2 type1 type2 &key
  310.                      (default '(values nil t))
  311.                      complex-arg1)
  312.   (let ((simple (class-function-slot-or-lose simple))
  313.     (cslot1 (class-function-slot-or-lose (or complex-arg1 complex-arg2)))
  314.     (cslot2 (class-function-slot-or-lose complex-arg2)))
  315.     (once-only ((n-type1 type1)
  316.         (n-type2 type2))
  317.       (once-only ((class1 `(type-class-info ,n-type1))
  318.           (class2 `(type-class-info ,n-type2)))
  319.     `(if (eq ,class1 ,class2)
  320.          (funcall (,simple ,class1) ,n-type1 ,n-type2)
  321.          ,(once-only ((complex1 `(,cslot1 ,class1))
  322.               (complex2 `(,cslot2 ,class2)))
  323.         `(cond (,complex2 (funcall ,complex2 ,n-type1 ,n-type2))
  324.                (,complex1
  325.             ,(if complex-arg1
  326.                  `(funcall ,complex1 ,n-type1 ,n-type2)
  327.                  `(funcall ,complex1 ,n-type2 ,n-type1)))
  328.                (t ,default))))))))
  329.  
  330.  
  331. ;;; The XXX-Type structures include the CTYPE structure for some slots that
  332. ;;; apply to all types.
  333. ;;;
  334. (defstruct (ctype (:conc-name type-))
  335.   ;;
  336.   ;; The class of this type.
  337.   (class-info (required-argument) :type type-class)
  338.   ;;
  339.   ;; True if this type has a fixed number of members, and as such could
  340.   ;; possibly be completely specified in a MEMBER type.  This is used by the
  341.   ;; MEMBER type methods.
  342.   (enumerable nil :type (member t nil) :read-only t))
  343.  
  344. ;;; %Print-Type  --  Internal
  345. ;;;
  346. ;;;    The print-function for all type structures.
  347. ;;;
  348. (defun %print-type (s stream d)
  349.   (declare (ignore d))
  350.   (format stream "#<~A ~S>" (type-of s) (type-specifier s)))
  351.  
  352.  
  353. ;;;; Utilities:
  354.  
  355. ;;; ANY-TYPE-OP, EVERY-TYPE-OP  --  Internal
  356. ;;;
  357. ;;;    Like ANY and EVERY, except that we handle two-arg uncertain predicates.
  358. ;;; If the result is uncertain, then we return Default from the block PUNT.
  359. ;;; If LIST-FIRST is true, then the list element is the first arg, otherwise
  360. ;;; the second.
  361. ;;;
  362. (defmacro any-type-op (op thing list &key (default '(values nil nil))
  363.               list-first)
  364.   (let ((n-this (gensym))
  365.     (n-thing (gensym))
  366.     (n-val (gensym))
  367.     (n-win (gensym))
  368.     (n-uncertain (gensym)))
  369.     `(let ((,n-thing ,thing)
  370.        (,n-uncertain nil))
  371.        (dolist (,n-this ,list
  372.             (if ,n-uncertain
  373.                 (return-from PUNT ,default)
  374.                 nil))
  375.      (multiple-value-bind (,n-val ,n-win)
  376.                   ,(if list-first
  377.                    `(,op ,n-this ,n-thing)
  378.                    `(,op ,n-thing ,n-this))
  379.        (unless ,n-win (setq ,n-uncertain t))
  380.        (when ,n-val (return t)))))))
  381. ;;;
  382. (defmacro every-type-op (op thing list &key (default '(values nil nil))
  383.                 list-first)
  384.   (let ((n-this (gensym))
  385.     (n-thing (gensym))
  386.     (n-val (gensym))
  387.     (n-win (gensym)))
  388.     `(let ((,n-thing ,thing))
  389.        (dolist (,n-this ,list t)
  390.      (multiple-value-bind (,n-val ,n-win)
  391.                   ,(if list-first
  392.                    `(,op ,n-this ,n-thing)
  393.                    `(,op ,n-thing ,n-this))
  394.        (unless ,n-win (return-from PUNT ,default))
  395.        (unless ,n-val (return nil)))))))
  396.  
  397.  
  398.   
  399. ;;; VANILLA-INTERSECTION  --  Internal
  400. ;;;
  401. ;;;    Compute the intersection for types that intersect only when one is a
  402. ;;; subtype of the other.
  403. ;;;
  404. (defun vanilla-intersection (type1 type2)
  405.   (multiple-value-bind (stp1 win1)
  406.                (csubtypep type1 type2)
  407.     (multiple-value-bind (stp2 win2)
  408.              (csubtypep type2 type1)
  409.       (cond (stp1 (values type1 t))
  410.         (stp2 (values type2 t))
  411.         ((and win1 win2) (values *empty-type* t))
  412.         (t
  413.          (values type1 nil))))))
  414.  
  415.  
  416. ;;; Def-Builtin-Type  --  Internal
  417. ;;;
  418. ;;;    Take a name and a type and define it as a builtin type.
  419. ;;;
  420. (defmacro def-builtin-type (symbol type)
  421.   `(cold-load-init
  422.     (%def-builtin-type ,symbol ,type)))
  423. ;;;
  424. (proclaim '(function %def-builtin-type (symbol ctype) void))
  425. (defun %def-builtin-type (name type)
  426.   (check-type name symbol)
  427.   (check-type type ctype)
  428.   (setf (info type builtin name) type))
  429.  
  430.  
  431. ;;; Precompute-Types  --  Internal
  432. ;;;
  433. ;;;    Take a list of type specifiers, compute the translation and define it as
  434. ;;; a builtin type.
  435. ;;;
  436. (proclaim '(function precompute-types (list) void)) 
  437. (defun precompute-types (specs)
  438.   (dolist (spec specs)
  439.     (let ((res (specifier-type spec)))
  440.       (unless (unknown-type-p res)
  441.     (setf (info type builtin spec) res)))))
  442.  
  443.  
  444. ;;; TYPE-CACHE-HASH  --  Internal
  445. ;;;
  446. ;;;    EQ hash two things (types) down to 8 bits.
  447. ;;;
  448. (defmacro type-cache-hash (type1 type2)
  449.   `(the fixnum
  450.     (logand (the fixnum
  451.              (logxor (the fixnum
  452.                   (ash (cache-hash-eq ,type1) -3))
  453.                  (the fixnum (cache-hash-eq ,type2))))
  454.         #xFF)))
  455.  
  456.  
  457. ;;;; Function and Values types.
  458. ;;;
  459. ;;;    Pretty much all of the general type operations are illegal on VALUES
  460. ;;; types, since we can't discriminate using them, do SUBTYPEP, etc.  FUNCTION
  461. ;;; types are acceptable to the normal type operations, but are generally
  462. ;;; considered to be equivalent to FUNCTION.  These really aren't true types in
  463. ;;; any type theoretic sense, but we still parse them into CTYPE structures for
  464. ;;; two reasons:
  465. ;;; -- Parsing and unparsing work the same way, and indeed we can't tell
  466. ;;;    whether a type is a function or values type without parsing it.
  467. ;;; -- Many of the places that can be annotated with real types can also be
  468. ;;;    annotated function or values types.
  469.  
  470.  
  471. ;;; The Args-Type structure is used both to represent Values types and
  472. ;;; and Function types.
  473. ;;;
  474. (defstruct (args-type (:include ctype)
  475.               (:print-function %print-type))
  476.   ;;
  477.   ;; Lists of the type for each required and optional argument.
  478.   (required nil :type list)
  479.   (optional nil :type list)
  480.   ;;
  481.   ;; The type for the rest arg.  NIL if there is no rest arg.
  482.   (rest nil :type (or ctype null))
  483.   ;;
  484.   ;; True if keyword arguments are specified.
  485.   (keyp nil :type boolean)
  486.   ;;
  487.   ;; List of key-info structures describing the keyword arguments.
  488.   (keywords nil :type list)
  489.   ;;
  490.   ;; True if other keywords are allowed.
  491.   (allowp nil :type boolean))
  492.  
  493. (defstruct key-info
  494.   ;;
  495.   ;; The keyword.
  496.   (name (required-argument) :type keyword)
  497.   ;;
  498.   ;; Type of this argument.
  499.   (type (required-argument) :type ctype))
  500.  
  501.  
  502. (define-type-class values)
  503.  
  504. (define-type-method (values :simple-subtypep :complex-subtypep-arg1)
  505.             (type1 type2)
  506.   (declare (ignore type2))
  507.   (error "Subtypep is illegal on this type:~%  ~S" (type-specifier type1)))
  508.  
  509. (define-type-method (values :complex-subtypep-arg2)
  510.             (type1 type2)
  511.   (declare (ignore type1))
  512.   (error "Subtypep is illegal on this type:~%  ~S" (type-specifier type2)))
  513.  
  514. (defstruct (values-type
  515.         (:include args-type
  516.               (:class-info (type-class-or-lose 'values)))
  517.         (:print-function %print-type)))
  518.  
  519. (define-type-method (values :unparse) (type)
  520.   (cons 'values (unparse-args-types type)))
  521.  
  522.  
  523. ;;; TYPE=-LIST  --  Internal
  524. ;;;
  525. ;;;    Return true if List1 and List2 have the same elements in the same
  526. ;;; positions according to TYPE=.  We return NIL, NIL if there is an uncertain
  527. ;;; comparison. 
  528. ;;;
  529. (defun type=-list (list1 list2)
  530.   (declare (list list1 list2))
  531.   (do ((types1 list1 (cdr types1))
  532.        (types2 list2 (cdr types2)))
  533.       ((or (null types1) (null types2))
  534.        (if (or types1 types2)
  535.        (values nil t)
  536.        (values t t)))
  537.     (multiple-value-bind (val win)
  538.              (type= (first types1) (first types2))
  539.       (unless win
  540.     (return (values nil nil)))
  541.       (unless val
  542.     (return (values nil t))))))
  543.  
  544.  
  545. (define-type-method (values :simple-=) (type1 type2)
  546.   (let ((rest1 (args-type-rest type1))
  547.     (rest2 (args-type-rest type2)))
  548.     (cond ((or (args-type-keyp type1) (args-type-keyp type2)
  549.            (args-type-allowp type1) (args-type-allowp type2))
  550.        (values nil nil))
  551.       ((and rest1 rest2 (type/= rest1 rest2))
  552.        (type= rest1 rest2))
  553.       ((or rest1 rest2)
  554.        (values nil t))
  555.       (t
  556.        (multiple-value-bind (req-val req-win)
  557.                 (type=-list (values-type-required type1)
  558.                         (values-type-required type2))
  559.          (multiple-value-bind (opt-val opt-win)
  560.                   (type=-list (values-type-optional type1)
  561.                           (values-type-optional type2))
  562.            (values (and req-val opt-val) (and req-win opt-win))))))))
  563.  
  564.  
  565. (define-type-class function)
  566.  
  567. (defstruct (function-type
  568.         (:include args-type
  569.               (class-info (type-class-or-lose 'function)))
  570.         (:print-function %print-type))
  571.   ;;
  572.   ;; True if the arguments are unrestrictive, i.e. *.
  573.   (wild-args nil :type boolean)
  574.   ;;
  575.   ;; Type describing the return values.  This is a values type
  576.   ;; when multiple values were specified for the return.
  577.   (returns (required-argument) :type ctype))
  578.  
  579.  
  580. ;;; A flag that we can bind to cause complex function types to be unparsed as
  581. ;;; FUNCTION.  Useful when we want a type that we can pass to TYPEP.
  582. ;;;
  583. (defvar *unparse-function-type-simplify*)
  584.  
  585. (define-type-method (function :unparse) (type)
  586.   (if *unparse-function-type-simplify*
  587.       'function
  588.       (list 'function
  589.         (if (function-type-wild-args type)
  590.         '*
  591.         (unparse-args-types type))
  592.         (type-specifier
  593.          (function-type-returns type)))))
  594.  
  595.  
  596. ;;; Since all function types are equivalent to FUNCTION, they are all subtypes
  597. ;;; of each other.
  598. ;;;
  599. (define-type-method (function :simple-subtypep) (type1 type2)
  600.   (declare (ignore type1 type2))
  601.   (values t t))
  602.  
  603.  
  604. ;;; The union or intersection of two FUNCTION types is FUNCTION.
  605. ;;;
  606. (define-type-method (function :simple-union) (type1 type2)
  607.   (declare (ignore type1 type2))
  608.   (specifier-type 'function))
  609. ;;;
  610. (define-type-method (function :simple-intersection) (type1 type2)
  611.   (declare (ignore type1 type2))
  612.   (values (specifier-type 'function) t))
  613.  
  614.  
  615. ;;; ### Not very real, but good enough for redefining transforms according to
  616. ;;; type:
  617. ;;;
  618. (define-type-method (function :simple-=) (type1 type2)
  619.   (values (equalp type1 type2) t))
  620.  
  621.  
  622. (define-type-class constant values)
  623.  
  624. ;;; The CONSTANT-TYPE structure represents a use of the CONSTANT-ARGUMENT "type
  625. ;;; specifier", which is only meaningful in function argument type specifiers
  626. ;;; used within the compiler.
  627. ;;;
  628. (defstruct (constant-type (:include ctype
  629.                     (class-info (type-class-or-lose 'constant)))
  630.               (:print-function %print-type))
  631.   ;;
  632.   ;; The type which the argument must be a constant instance of for this type
  633.   ;; specifier to win.
  634.   (type (required-argument) :type ctype))
  635.  
  636. (define-type-method (constant :unparse) (type)
  637.   `(constant-argument ,(type-specifier (constant-type-type type))))
  638.  
  639. (define-type-method (constant :simple-=) (type1 type2)
  640.   (type= (constant-type-type type1) (constant-type-type type2)))
  641.  
  642. (def-type-translator constant-argument (type)
  643.   (make-constant-type :type (specifier-type type)))
  644.  
  645.  
  646. ;;; Parse-Args-Types  --  Internal
  647. ;;;
  648. ;;;    Given a lambda-list like values type specification and a Args-Type
  649. ;;; structure, fill in the slots in the structure accordingly.  This is used
  650. ;;; for both FUNCTION and VALUES types.
  651. ;;;
  652. (proclaim '(function parse-args-types (list args-type) void))
  653. (defun parse-args-types (lambda-list result)
  654.   (multiple-value-bind (required optional restp rest keyp keys allowp aux)
  655.                (parse-lambda-list lambda-list)
  656.     (when aux
  657.       (error "&Aux in a FUNCTION or VALUES type: ~S." lambda-list))
  658.     (setf (args-type-required result) (mapcar #'specifier-type required))
  659.     (setf (args-type-optional result) (mapcar #'specifier-type optional))
  660.     (setf (args-type-rest result) (if restp (specifier-type rest) nil))
  661.     (setf (args-type-keyp result) keyp)
  662.     (collect ((key-info))
  663.       (dolist (key keys)
  664.     (when (or (atom key) (/= (length key) 2))
  665.       (error "Keyword type description is not a two-list: ~S." key))
  666.     (let* ((name (first key))
  667.            (kwd (if (keywordp name) name
  668.             (intern (symbol-name name) "KEYWORD"))))
  669.       (when (find kwd (key-info) :key #'key-info-name)
  670.         (error "Repeated keyword ~S in lambda list: ~S." kwd lambda-list))
  671.       (key-info (make-key-info :name kwd
  672.                    :type (specifier-type (second key))))))
  673.       (setf (args-type-keywords result) (key-info)))
  674.     (setf (args-type-allowp result) allowp)))
  675.  
  676.  
  677. ;;; Unparse-Args-Types  --  Internal
  678. ;;;
  679. ;;;    Return the lambda-list like type specification corresponding
  680. ;;; to a Args-Type.
  681. ;;;
  682. (proclaim '(function unparse-args-types (args-type) list))
  683. (defun unparse-args-types (type)
  684.   (collect ((result))
  685.  
  686.     (dolist (arg (args-type-required type))
  687.       (result (type-specifier arg)))
  688.  
  689.     (when (args-type-optional type)
  690.       (result '&optional)
  691.       (dolist (arg (args-type-optional type))
  692.     (result (type-specifier arg))))
  693.  
  694.     (when (args-type-rest type)
  695.       (result '&rest)
  696.       (result (type-specifier (args-type-rest type))))
  697.  
  698.     (when (args-type-keyp type)
  699.       (result '&key)
  700.       (dolist (key (args-type-keywords type))
  701.     (result (list (key-info-name key)
  702.               (type-specifier (key-info-type key))))))
  703.  
  704.     (when (args-type-allowp type)
  705.       (result '&allow-other-keys))
  706.  
  707.     (result)))
  708.  
  709.  
  710. (def-type-translator function (&optional args result)
  711.   (let ((res (make-function-type
  712.           :returns (values-specifier-type result))))
  713.     (if (eq args '*)
  714.     (setf (function-type-wild-args res) t)
  715.     (parse-args-types args res))
  716.     res))
  717.  
  718.  
  719. (def-type-translator values (&rest values)
  720.   (let ((res (make-values-type)))
  721.     (parse-args-types values res)
  722.     res))
  723.  
  724.  
  725. ;;;; Values types interfaces:
  726. ;;;
  727. ;;;    We provide a few special operations that can be meaningfully used on
  728. ;;; values types (as well as on any other type.)
  729. ;;;
  730.  
  731. ;;; Single-Value-Type  --  Interface
  732. ;;;
  733. ;;;    Return the type of the first value indicated by Type.  This is used by
  734. ;;; people who don't want to have to deal with values types.
  735. ;;;
  736. (defun single-value-type (type)
  737.   (declare (type ctype type))
  738.   (cond ((values-type-p type)
  739.      (cond ((args-type-required type)
  740.         (first (args-type-required type)))
  741.            ((args-type-optional type)
  742.         (first (args-type-optional type)))
  743.            ((args-type-rest type))
  744.            (t
  745.         *universal-type*)))
  746.     ((eq type *wild-type*)
  747.      *universal-type*)
  748.     (t
  749.      type)))
  750.  
  751.  
  752. ;;; FUNCTION-TYPE-NARGS  --  Interface
  753. ;;;
  754. ;;;    Return the minmum number of arguments that a function can be called
  755. ;;; with, and the maximum number or NIL.  If not a function type, return
  756. ;;; NIL, NIL.
  757. ;;;
  758. (defun function-type-nargs (type)
  759.   (declare (type ctype type))
  760.   (if (function-type-p type)
  761.       (let ((fixed (length (args-type-required type))))
  762.     (if (or (args-type-rest type)
  763.         (args-type-keyp type)
  764.         (args-type-allowp type))
  765.         (values fixed nil)
  766.         (values fixed (+ fixed (length (args-type-optional type))))))
  767.       (values nil nil)))
  768.  
  769.  
  770. ;;; Values-Types  --  Interface
  771. ;;;
  772. ;;;    Determine if Type corresponds to a definite number of values.  The first
  773. ;;; value is a list of the types for each value, and the second value is the
  774. ;;; number of values.  If the number of values is not fixed, then return NIL
  775. ;;; and :Unknown.
  776. ;;;
  777. (defun values-types (type)
  778.   (declare (type ctype type))
  779.   (cond ((eq type *wild-type*)
  780.      (values nil :unknown))
  781.     ((not (values-type-p type))
  782.      (values (list type) 1))
  783.     ((or (args-type-optional type)
  784.          (args-type-rest type)
  785.          (args-type-keyp type)
  786.          (args-type-allowp type))
  787.      (values nil :unknown))
  788.     (t
  789.      (let ((req (args-type-required type)))
  790.        (values (mapcar #'single-value-type req) (length req))))))
  791.  
  792.  
  793. ;;; Values-Type-Types  --  Internal
  794. ;;;
  795. ;;;    Return two values:
  796. ;;; 1] A list of all the positional (fixed and optional) types.
  797. ;;; 2] The rest type (if any).  If keywords allowed, *universal-type*.  If no
  798. ;;;    keywords or rest, *empty-type*.
  799. ;;;
  800. (defun values-type-types (type)
  801.   (declare (type values-type type))
  802.   (values (append (args-type-required type)
  803.           (args-type-optional type))
  804.       (cond ((args-type-keyp type) *universal-type*)
  805.         ((args-type-rest type))
  806.         (t
  807.          *empty-type*))))
  808.  
  809.  
  810. ;;; Fixed-Values-Op  --  Internal
  811. ;;;
  812. ;;;    Return a list of Operation applied to the types in Types1 and Types2,
  813. ;;; padding with Rest2 as needed.  Types1 must not be shorter than Types2.  The
  814. ;;; second value is T if Operation always returned a true second value.
  815. ;;;
  816. (defun fixed-values-op (types1 types2 rest2 operation)
  817.   (declare (list types1 types2) (type ctype rest2) (type function operation))
  818.   (let ((exact t))
  819.     (values (mapcar #'(lambda (t1 t2)
  820.             (multiple-value-bind (res win)
  821.                          (funcall operation t1 t2)
  822.               (unless win (setq exact nil))
  823.               res))
  824.             types1
  825.             (append types2
  826.                 (make-list (- (length types1) (length types2))
  827.                        :initial-element rest2)))
  828.         exact)))
  829.  
  830.  
  831. ;;; Coerce-To-Values  --  Internal
  832. ;;;
  833. ;;; If Type isn't a values type, then make it into one:
  834. ;;;    <type>  ==>  (values type &rest t)
  835. ;;;
  836. (defun coerce-to-values (type)
  837.   (declare (type ctype type))
  838.   (if (values-type-p type)
  839.       type
  840.       (make-values-type :required (list type) :rest *universal-type*)))
  841.  
  842.  
  843. ;;; Args-Type-Op  --  Internal
  844. ;;;
  845. ;;;    Do the specified Operation on Type1 and Type2, which may be any type,
  846. ;;; including Values types.  With values types such as:
  847. ;;;    (values a0 a1)
  848. ;;;    (values b0 b1)
  849. ;;;
  850. ;;; We compute the more useful result:
  851. ;;;    (values (<operation> a0 b0) (<operation> a1 b1))
  852. ;;;
  853. ;;; Rather than the precise result:
  854. ;;;    (<operation> (values a0 a1) (values b0 b1))
  855. ;;;
  856. ;;; This has the virtue of always keeping the values type specifier outermost,
  857. ;;; and retains all of the information that is really useful for static type
  858. ;;; analysis.  We want to know what is always true of each value independently.
  859. ;;; It is worthless to know that IF the first value is B0 then the second will
  860. ;;; be B1.
  861. ;;;
  862. ;;; If the values count signatures differ, then we produce result with the
  863. ;;; required value count chosen by Nreq when applied to the number of required
  864. ;;; values in type1 and type2.  Any &key values become &rest T (anyone who uses
  865. ;;; keyword values deserves to lose.)
  866. ;;;
  867. ;;; The second value is true if the result is definitely empty or if Operation
  868. ;;; returned true as its second value each time we called it.  Since we
  869. ;;; approximate the intersection of values types, the second value being true
  870. ;;; doesn't mean the result is exact.
  871. ;;;
  872. (defun args-type-op (type1 type2 operation nreq)
  873.   (declare (type ctype type1 type2) (type function operation nreq))
  874.   (if (or (values-type-p type1) (values-type-p type2))
  875.       (let ((type1 (coerce-to-values type1))
  876.         (type2 (coerce-to-values type2)))
  877.     (multiple-value-bind (types1 rest1)
  878.                  (values-type-types type1)
  879.       (multiple-value-bind (types2 rest2)
  880.                    (values-type-types type2)
  881.         (multiple-value-bind (rest rest-exact)
  882.                  (funcall operation rest1 rest2)
  883.           (multiple-value-bind
  884.           (res res-exact)
  885.           (if (< (length types1) (length types2))
  886.               (fixed-values-op types2 types1 rest1 operation)
  887.               (fixed-values-op types1 types2 rest2 operation))
  888.         (let* ((req (funcall nreq
  889.                      (length (args-type-required type1))
  890.                      (length (args-type-required type2))))
  891.                (required (subseq res 0 req))
  892.                (opt (subseq res req))
  893.                (opt-last (position rest opt :test-not #'type=
  894.                        :from-end t)))
  895.           (if (find *empty-type* required :test #'type=)
  896.               (values *empty-type* t)
  897.               (values (make-values-type
  898.                    :required required
  899.                    :optional (if opt-last
  900.                          (subseq opt 0 (1+ opt-last))
  901.                          ())
  902.                    :rest (if (eq rest *empty-type*) nil rest))
  903.                   (and rest-exact res-exact)))))))))
  904.       (funcall operation type1 type2)))
  905.  
  906.  
  907. ;;; Values-Type-Union, Values-Type-Intersection  --  Interface
  908. ;;;
  909. ;;;    Do a union or intersection operation on types that might be values
  910. ;;; types.  The result is optimized for utility rather than exactness, but it
  911. ;;; is guaranteed that it will be no smaller (more restrictive) than the
  912. ;;; precise result.
  913. ;;;
  914. (defun-cached (values-type-union :hash-function type-cache-hash
  915.                  :hash-bits 8
  916.                  :default nil)
  917.           ((type1 eq) (type2 eq))
  918.   (declare (type ctype type1 type2))
  919.   (cond ((or (eq type1 *wild-type*) (eq type2 *wild-type*)) *wild-type*)
  920.     ((eq type1 *empty-type*) type2)
  921.     ((eq type2 *empty-type*) type1)
  922.     (t
  923.      (values (args-type-op type1 type2 #'type-union #'min)))))
  924. ;;;
  925. (defun-cached (values-type-intersection :hash-function type-cache-hash
  926.                     :hash-bits 8
  927.                     :values 2
  928.                     :default (values nil :empty))
  929.           ((type1 eq) (type2 eq))
  930.   (declare (type ctype type1 type2))
  931.   (cond ((eq type1 *wild-type*) (values type2 t))
  932.     ((eq type2 *wild-type*) (values type1 t))
  933.     (t
  934.      (args-type-op type1 type2 #'type-intersection #'max))))
  935.  
  936.  
  937. ;;; Values-Types-Intersect  --  Interface
  938. ;;;
  939. ;;;    Like Types-Intersect, except that it sort of works on values types.
  940. ;;; Note that due to the semantics of Values-Type-Intersection, this might
  941. ;;; return {T, T} when there isn't really any intersection (?).
  942. ;;;
  943. (defun values-types-intersect (type1 type2)
  944.   (cond ((or (eq type1 *empty-type*) (eq type2 *empty-type*))
  945.      (values t t))
  946.     ((or (values-type-p type1) (values-type-p type2))
  947.      (multiple-value-bind (res win)
  948.                   (values-type-intersection type1 type2)
  949.        (values (not (eq res *empty-type*))
  950.            win)))
  951.     (t
  952.      (types-intersect type1 type2))))
  953.  
  954.  
  955. ;;; Values-Subtypep  --  Interface
  956. ;;;
  957. ;;;    A subtypep-like operation that can be used on any types, including
  958. ;;; values types.
  959. ;;;
  960. (defun-cached (values-subtypep :hash-function type-cache-hash
  961.                    :hash-bits 8
  962.                    :values 2
  963.                    :default (values nil :empty))
  964.           ((type1 eq) (type2 eq))
  965.   (declare (type ctype type1 type2))
  966.   (cond ((eq type2 *wild-type*) (values t t))
  967.     ((eq type1 *wild-type*)
  968.      (values (eq type2 *universal-type*) t))
  969.     ((not (values-types-intersect type1 type2))
  970.      (values nil t))
  971.     (t
  972.      (if (or (values-type-p type1) (values-type-p type2))
  973.          (let ((type1 (coerce-to-values type1))
  974.            (type2 (coerce-to-values type2)))
  975.            (multiple-value-bind (types1 rest1)
  976.                     (values-type-types type1)
  977.          (multiple-value-bind (types2 rest2)
  978.                       (values-type-types type2)
  979.            (cond ((< (length (values-type-required type1))
  980.                  (length (values-type-required type2)))
  981.               (values nil t))
  982.              ((< (length types1) (length types2))
  983.               (values nil nil))
  984.              ((or (values-type-keyp type1)
  985.                   (values-type-keyp type2))
  986.               (values nil nil))
  987.              (t
  988.               (do ((t1 types1 (rest t1))
  989.                    (t2 types2 (rest t2)))
  990.                   ((null t2)
  991.                    (csubtypep rest1 rest2))
  992.                 (multiple-value-bind
  993.                 (res win-p)
  994.                 (csubtypep (first t1) (first t2))
  995.                   (unless win-p
  996.                 (return (values nil nil)))
  997.                   (unless res
  998.                 (return (values nil t))))))))))
  999.          (csubtypep type1 type2)))))
  1000.                                
  1001.  
  1002. ;;;; Type method interfaces:
  1003.  
  1004. ;;; Csubtypep  --  Interface
  1005. ;;;
  1006. ;;;    Like subtypep, only works on Type structures.
  1007. ;;;
  1008. (defun-cached (csubtypep :hash-function type-cache-hash
  1009.              :hash-bits 8
  1010.              :values 2
  1011.              :default (values nil :empty))
  1012.           ((type1 eq) (type2 eq))
  1013.   (declare (type ctype type1 type2))
  1014.   (cond ((or (eq type1 type2)
  1015.          (eq type1 *empty-type*)
  1016.          (eq type2 *wild-type*))
  1017.      (values t t))
  1018.     ((or (eq type1 *wild-type*)
  1019.          (eq type2 *empty-type*))
  1020.      (values nil t))
  1021.     (t
  1022.      (invoke-type-method :simple-subtypep :complex-subtypep-arg2
  1023.                  type1 type2
  1024.                  :complex-arg1 :complex-subtypep-arg1))))
  1025.  
  1026.  
  1027. ;;; Type=  --  Interface
  1028. ;;;
  1029. ;;;    If two types are definitely equivalent, return true.  The second value
  1030. ;;; indicates whether the first value is definitely correct.  This should only
  1031. ;;; fail in the presence of Hairy types.
  1032. ;;;
  1033. (defun-cached (type= :hash-function type-cache-hash
  1034.              :hash-bits 8
  1035.              :values 2
  1036.              :default (values nil :empty))
  1037.           ((type1 eq) (type2 eq))
  1038.   (declare (type ctype type1 type2))
  1039.   (if (eq type1 type2)
  1040.       (values t t)
  1041.       (invoke-type-method :simple-= :complex-= type1 type2)))
  1042.  
  1043.  
  1044. ;;; TYPE/=  --  Interface
  1045. ;;;
  1046. ;;;    Not exactly the negation of TYPE=, since when the relationship is
  1047. ;;; uncertain, we still return NIL, NIL.  This is useful in cases where the
  1048. ;;; conservative assumption is =.
  1049. ;;;
  1050. (defun type/= (type1 type2)
  1051.   (declare (type ctype type1 type2))
  1052.   (multiple-value-bind (res win)
  1053.                (type= type1 type2)
  1054.     (if win
  1055.     (values (not res) t)
  1056.     (values nil nil))))
  1057.  
  1058.  
  1059. ;;; Type-Union  --  Interface
  1060. ;;;
  1061. ;;;    Find a type which includes both types.  Any inexactness is represented
  1062. ;;; by the fuzzy element types; we return a single value that is precise to the
  1063. ;;; best of our knowledge.  This result is simplified into the canonical form,
  1064. ;;; thus is not a UNION type unless there is no other way to represent the
  1065. ;;; result.
  1066. ;;;
  1067. ;;;    We can't use INVOKE-TYPE-METHOD because the :SIMPLE-UNION method may be
  1068. ;;; missing (meaning use subtype relations.)
  1069. ;;; 
  1070. (defun-cached (type-union :hash-function type-cache-hash
  1071.               :hash-bits 8)
  1072.           ((type1 eq) (type2 eq))
  1073.   (declare (type ctype type1 type2))
  1074.   (if (eq type1 type2)
  1075.       type1
  1076.       (let ((class1 (type-class-info type1))
  1077.         (class2 (type-class-info type2)))
  1078.     (if (eq class1 class2)
  1079.         (let ((method (type-class-simple-union class1)))
  1080.           (cond (method
  1081.              (let ((union (funcall method type1 type2)))
  1082.                (or union
  1083.                (make-union-type (list type1 type2)))))
  1084.             ((csubtypep type1 type2) type2)
  1085.             ((csubtypep type2 type1) type1)
  1086.             (t
  1087.              (make-union-type (list type1 type2)))))
  1088.         (let ((complex1 (type-class-complex-union class1))
  1089.           (complex2 (type-class-complex-union class2)))
  1090.           (cond (complex2 (funcall complex2 type1 type2))
  1091.             (complex1 (funcall complex1 type2 type1))
  1092.             (t
  1093.              (make-union-type (list type1 type2)))))))))
  1094.  
  1095.  
  1096. ;;; Type-Intersection  --  Interface
  1097. ;;;
  1098. ;;;    Return as restrictive a type as we can discover that is no more
  1099. ;;; restrictive than the intersection of Type1 and Type2.  The second value is
  1100. ;;; true if the result is exact.  At worst, we randomly return one of the
  1101. ;;; arguments as the first value (trying not to return a hairy type).
  1102. ;;;
  1103. (defun-cached (type-intersection :hash-function type-cache-hash
  1104.                  :hash-bits 8
  1105.                  :values 2
  1106.                  :default (values nil :empty))
  1107.           ((type1 eq) (type2 eq))
  1108.   (declare (type ctype type1 type2))
  1109.   (if (eq type1 type2)
  1110.       (values type1 t)
  1111.       (invoke-type-method :simple-intersection :complex-intersection
  1112.               type1 type2
  1113.               :default (values *empty-type* t))))
  1114.  
  1115.  
  1116. ;;; Types-Intersect  --  Interface
  1117. ;;;
  1118. ;;;    The first value is true unless the types don't intersect.  The second
  1119. ;;; value is true if the first value is definitely correct.  NIL is considered
  1120. ;;; to intersect with any type.  If T is a subtype of either type, then we also
  1121. ;;; return T, T.  This way we consider hairy types to intersect with T.
  1122. ;;;
  1123. (defun types-intersect (type1 type2)
  1124.   (declare (type ctype type1 type2))
  1125.   (if (or (eq type1 *empty-type*) (eq type2 *empty-type*))
  1126.       (values t t)
  1127.       (multiple-value-bind (val winp)
  1128.                (type-intersection type1 type2)
  1129.     (cond ((not winp)
  1130.            (if (or (csubtypep *universal-type* type1)
  1131.                (csubtypep *universal-type* type2))
  1132.            (values t t)
  1133.            (values t nil)))
  1134.           ((eq val *empty-type*) (values nil t))
  1135.           (t (values t t))))))
  1136.  
  1137.  
  1138. ;;; Type-Specifier  --  Interface
  1139. ;;;
  1140. ;;;    Return a Common Lisp type specifier corresponding to this type.
  1141. ;;;
  1142. (defun type-specifier (type)
  1143.   (declare (type ctype type))
  1144.   (funcall (type-class-unparse (type-class-info type)) type))
  1145.  
  1146.  
  1147. ;;; VALUES-SPECIFIER-TYPE  --  Interface
  1148. ;;;
  1149. ;;;    Return the type structure corresponding to a type specifier.  We pick
  1150. ;;; off Structure types as a special case.
  1151. ;;;
  1152. ;;; Note: SPECIFIER-TYPE-CACHE-CLEAR must be called whenever a type is defined
  1153. ;;; (or redefined).
  1154. ;;;
  1155. (defun-cached (values-specifier-type
  1156.            :hash-function (lambda (x)
  1157.                 (the fixnum
  1158.                      (logand (the fixnum (cache-hash-eq x))
  1159.                          #x3FF)))
  1160.            :hash-bits 10)
  1161.           ((spec eq))
  1162.   (or (info type builtin spec)
  1163.       (let ((expand (type-expand spec)))
  1164.     (if (eq expand spec)
  1165.         (let* ((lspec (if (atom spec) (list spec) spec))
  1166.            (fun (info type translator (car lspec))))
  1167.           (cond
  1168.            (fun (funcall fun lspec))
  1169.            ((and (symbolp spec)
  1170.              (eq (info type kind spec) :structure))
  1171.         (make-structure-type :name spec))
  1172.            ((or (and (consp spec) (symbolp (car spec)))
  1173.             (symbolp spec))
  1174.         (signal 'parse-unknown-type :specifier spec)
  1175.         ;;
  1176.         ;; Inhibit caching...
  1177.         (return-from values-specifier-type
  1178.                  (make-unknown-type :specifier spec)))
  1179.            (t
  1180.         (error "Bad thing to be a type specifier: ~S."
  1181.                spec))))
  1182.         (values-specifier-type expand)))))
  1183.  
  1184.  
  1185. ;;; SPECIFIER-TYPE  --  Interface
  1186. ;;;
  1187. ;;;    Like VALUES-SPECIFIER-TYPE, except that we guarantee to never return a
  1188. ;;; VALUES type.
  1189. ;;; 
  1190. (defun specifier-type (x)
  1191.   (let ((res (values-specifier-type x)))
  1192.     (when (values-type-p res)
  1193.       (error "VALUES type illegal in this context:~%  ~S" x))
  1194.     res))
  1195.  
  1196.  
  1197. ;;; Type-Expand  --  Interface
  1198. ;;;
  1199. ;;;    Similar to Macroexpand, but expands deftypes.  We don't bother returning
  1200. ;;; a second value.
  1201. ;;;
  1202. (defun type-expand (form)
  1203.   (let ((def (cond ((symbolp form)
  1204.             (info type expander form))
  1205.            ((and (consp form) (symbolp (car form)))
  1206.             (info type expander (car form)))
  1207.            (t nil))))
  1208.     (if def
  1209.     (type-expand (funcall def (if (consp form) form (list form))))
  1210.     form)))
  1211.  
  1212.  
  1213.  
  1214. ;;;; Builtin types.
  1215.  
  1216. ;;; The Named-Type is used to represent types which have no additional
  1217. ;;; information and don't have a more specific representation. 
  1218. (defstruct (named-type (:include ctype
  1219.                  (class-info (type-class-or-lose 'named)))
  1220.                (:print-function %print-type))
  1221.   ;;
  1222.   ;; The symbol name for this type.
  1223.   (name (required-argument) :type symbol)
  1224.   ;;
  1225.   ;; The names of (named) supertypes of this type.  Includes Name.
  1226.   (supertypes nil :type list)
  1227.   ;;
  1228.   ;; The names the type classes which are subtypes of this type.
  1229.   (subclasses nil :type list))
  1230.  
  1231. ;;; The Named class handles types whose only supertypes are other named types.
  1232. ;;;
  1233. (define-type-class named)
  1234.  
  1235. (define-type-method (named :unparse) (type)
  1236.   (named-type-name type))
  1237.  
  1238. ;;; We should never be called when the two types are equal, since the EQ check
  1239. ;;; in TYPE= should detect that.
  1240. ;;;
  1241. (define-type-method (named :simple-=) (type1 type2)
  1242.   (assert (not (eq (named-type-name type1) (named-type-name type2))))
  1243.   (values nil t))
  1244.  
  1245. (define-type-method (named :simple-subtypep) (type1 type2)
  1246.   (if (member (named-type-name type2)
  1247.           (named-type-supertypes type1))
  1248.       (values t t)
  1249.       (values nil t)))
  1250.  
  1251. (define-type-method (named :complex-subtypep-arg1) (type1 type2)
  1252.   (let ((meth (type-class-complex-subtypep-arg2 (type-class-info type2))))
  1253.     (cond ((eq type1 *empty-type*) (values t t))
  1254.       (meth (funcall meth type1 type2))
  1255.       (t
  1256.        (values nil t)))))
  1257.  
  1258. (define-type-method (named :complex-subtypep-arg2) (type1 type2)
  1259.   (let ((meth (type-class-complex-subtypep-arg1 (type-class-info type1))))
  1260.     (cond ((member (type-class-name (type-class-info type1))
  1261.            (named-type-subclasses type2))
  1262.        (values t t))
  1263.       (meth (funcall meth type1 type2))
  1264.       (t
  1265.        (values nil t)))))
  1266.  
  1267. (define-type-method (named :complex-intersection) (type1 type2)
  1268.   (let ((meth (type-class-complex-intersection (type-class-info type1))))
  1269.     (if meth
  1270.     (funcall meth type2 type1)
  1271.     (vanilla-intersection type1 type2))))
  1272.  
  1273. (define-type-method (named :complex-union) (type1 type2)
  1274.   (let* ((class1 (type-class-info type1))
  1275.      (union (type-class-complex-union class1)))
  1276.     (cond ((eq type2 *empty-type*) type1)
  1277.       ((csubtypep type1 type2) type2)
  1278.       (union (funcall union type2 type1))
  1279.       (t
  1280.        (make-union-type (list type1 type2))))))
  1281.  
  1282. (def-builtin-type '*
  1283.   (make-named-type :name '*
  1284.            :supertypes '(*)
  1285.            :subclasses '(hairy number array member function
  1286.                        structure alien)))
  1287. ;;;
  1288. (cold-load-init
  1289.  (defparameter *wild-type* (specifier-type '*)))
  1290.  
  1291.  
  1292. (def-builtin-type 't
  1293.   (make-named-type :name 't
  1294.            :supertypes '(t *)
  1295.            :subclasses '(number array member function
  1296.                     structure alien)))
  1297. ;;;
  1298. (cold-load-init
  1299.  (defparameter *universal-type* (specifier-type 't)))
  1300.  
  1301.  
  1302. ;;; SUBTYPEP-ARG1 special-cases NIL to make this work.
  1303. ;;;
  1304. (def-builtin-type 'nil
  1305.   (make-named-type :name 'nil
  1306.            :supertypes '(* t character base-char standard-char
  1307.                  extended-char function cons symbol keyword
  1308.                  system-area-pointer weak-pointer
  1309.                  scavenger-hook structure code-component
  1310.                  lra fdefn nil)))
  1311. ;;;
  1312. (cold-load-init
  1313.  (defparameter *empty-type* (specifier-type 'nil)))
  1314.  
  1315.  
  1316. (def-builtin-type 'character
  1317.   (make-named-type :name 'character
  1318.            :supertypes '(character t)
  1319.            :enumerable t))
  1320.  
  1321. (def-builtin-type 'base-char
  1322.   (make-named-type :name 'base-char
  1323.            :supertypes '(base-char character t)
  1324.            :enumerable t))
  1325.  
  1326. (def-builtin-type 'extended-char
  1327.   (make-named-type :name 'extended-char
  1328.            :supertypes '(extended-char character t)
  1329.            :enumerable t))
  1330.  
  1331. (def-builtin-type 'standard-char
  1332.   (make-named-type :name 'standard-char
  1333.            :supertypes '(standard-char base-char character t)
  1334.            :enumerable t))
  1335.  
  1336. (def-builtin-type 'function
  1337.   (make-named-type :name 'function
  1338.            :supertypes '(function t)
  1339.            :subclasses '(function)))
  1340.  
  1341. (deftype compiled-function () 'function)
  1342.  
  1343. (def-builtin-type 'cons
  1344.   (make-named-type :name 'cons
  1345.            :supertypes '(cons t)))
  1346.  
  1347. (def-builtin-type 'symbol
  1348.   (make-named-type :name 'symbol
  1349.            :supertypes '(symbol t)))
  1350.  
  1351. (def-builtin-type 'keyword
  1352.   (make-named-type :name 'keyword
  1353.            :supertypes '(keyword symbol t)))
  1354.  
  1355. (def-builtin-type 'system-area-pointer
  1356.   (make-named-type :name 'system-area-pointer
  1357.            :supertypes '(system-area-pointer t)))
  1358.  
  1359. (def-builtin-type 'weak-pointer
  1360.   (make-named-type :name 'weak-pointer
  1361.            :supertypes '(weak-pointer t)))
  1362.  
  1363. (def-builtin-type 'scavenger-hook
  1364.   (make-named-type :name 'scavenger-hook
  1365.            :supertypes '(scavenger-hook t)))
  1366.  
  1367. (def-builtin-type 'code-component
  1368.   (make-named-type :name 'code-component
  1369.            :supertypes '(code-component t)))
  1370.  
  1371. (def-builtin-type 'lra
  1372.   (make-named-type :name 'lra
  1373.            :supertypes '(lra t)))
  1374.  
  1375. (def-builtin-type 'fdefn
  1376.   (make-named-type :name 'fdefn
  1377.            :supertypes '(fdefn t)))
  1378.  
  1379. ;;; STRUCTURE is a named type instead of a structure type, since it isn't
  1380. ;;; really a sturcture.
  1381. ;;;
  1382. (def-builtin-type 'structure
  1383.   (make-named-type :name 'structure
  1384.            :supertypes '(structure t)
  1385.            :subclasses '(structure alien)))
  1386.  
  1387.  
  1388. ;;;; Hairy and unknown types:
  1389.  
  1390. ;;; The Hairy-Type represents anything too wierd to be described reasonably or
  1391. ;;; to be useful, such as AND, NOT and SATISFIES and unknown types.  We just
  1392. ;;; remember the original type spec.
  1393. ;;;
  1394. (defstruct (hairy-type (:include ctype
  1395.                  (:class-info (type-class-or-lose 'hairy))
  1396.                  (:enumerable t))
  1397.                (:print-function %print-type))
  1398.   ;;
  1399.   ;; The Common Lisp type-specifier.
  1400.   (specifier nil :type t))
  1401.  
  1402. (define-type-class hairy)
  1403.  
  1404. (define-type-method (hairy :unparse) (x) (hairy-type-specifier x))
  1405.  
  1406. (define-type-method (hairy :complex-subtypep-arg1 :complex-subtypep-arg2
  1407.                :complex-=)
  1408.             (type1 type2)
  1409.   (declare (ignore type1 type2))
  1410.   (values nil nil))
  1411.  
  1412. (define-type-method (hairy :simple-intersection :complex-intersection)
  1413.             (type1 type2)
  1414.   (declare (ignore type2))
  1415.   (values type1 nil))
  1416.  
  1417. (define-type-method (hairy :complex-union) (type1 type2)
  1418.   (make-union-type (list type1 type2)))
  1419.  
  1420. (define-type-method (hairy :simple-= :simple-subtypep) (type1 type2)
  1421.   (if (equal (hairy-type-specifier type1)
  1422.          (hairy-type-specifier type2))
  1423.       (values t t)
  1424.       (values nil nil)))
  1425.  
  1426. (def-type-translator not (&whole x type)
  1427.   (declare (ignore type))
  1428.   (make-hairy-type :specifier x))
  1429.  
  1430. (def-type-translator satisfies (&whole x fun)
  1431.   (declare (ignore fun))
  1432.   (make-hairy-type :specifier x))
  1433.  
  1434.  
  1435. ;;; An UNKNOWN-TYPE is a type not known to the type system (not yet defined).
  1436. ;;; We make this distinction since we don't want to complain about types that
  1437. ;;; are hairy but defined.
  1438. ;;;
  1439. (defstruct (unknown-type (:include hairy-type)))
  1440.  
  1441.  
  1442. ;;;; Numeric types.
  1443.  
  1444. ;;; A list of all the float formats, in order of decreasing precision.
  1445. ;;;
  1446. (eval-when (compile load eval)
  1447.   (defconstant float-formats
  1448.     '(long-float double-float single-float short-float)))
  1449.  
  1450. ;;; The type of a float format.
  1451. ;;;
  1452. (deftype float-format () `(member ,@float-formats))
  1453.  
  1454.  
  1455. ;;; The Numeric-Type is used to represent all numeric types, including things
  1456. ;;; such as FIXNUM.
  1457. (defstruct (numeric-type (:include ctype
  1458.                    (:class-info (type-class-or-lose 'number)))
  1459.              (:print-function %print-type))
  1460.   ;;
  1461.   ;; The kind of numeric type we have.  NIL if not specified (just NUMBER or
  1462.   ;; COMPLEX).
  1463.   (class nil :type (member integer rational float nil))
  1464.   ;;
  1465.   ;; Format for a float type.  NIL if not specified or not a float.  Formats
  1466.   ;; which don't exist in a given implementation don't appear here.
  1467.   (format nil :type (or float-format null))
  1468.   ;;
  1469.   ;; Is this a complex numeric type?  Null if unknown (only in NUMBER.)
  1470.   (complexp :real :type (member :real :complex nil))
  1471.   ;;
  1472.   ;; The upper and lower bounds on the value.  If null, there is no bound.  If
  1473.   ;; a list of a number, the bound is exclusive.  Integer types never have
  1474.   ;; exclusive bounds.
  1475.   (low nil :type (or number cons null))
  1476.   (high nil :type (or number cons null)))
  1477.  
  1478.  
  1479. (define-type-class number)
  1480.  
  1481. (define-type-method (number :simple-=) (type1 type2)
  1482.   (values
  1483.    (and (eq (numeric-type-class type1) (numeric-type-class type2))
  1484.     (eq (numeric-type-format type1) (numeric-type-format type2))
  1485.     (eq (numeric-type-complexp type1) (numeric-type-complexp type2))
  1486.     (equal (numeric-type-low type1) (numeric-type-low type2))
  1487.     (equal (numeric-type-high type1) (numeric-type-high type2)))
  1488.    t))
  1489.  
  1490. (define-type-method (number :unparse) (type)
  1491.   (let* ((complexp (numeric-type-complexp type))
  1492.      (low (numeric-type-low type))
  1493.      (high (numeric-type-high type))
  1494.      (base (case (numeric-type-class type)
  1495.          (integer 'integer)
  1496.          (rational 'rational)
  1497.          (float (or (numeric-type-format type) 'float))
  1498.          (t 'real))))
  1499.     (let ((base+bounds
  1500.        (cond ((and (eq base 'integer) high low)
  1501.           (let ((high-count (logcount high))
  1502.             (high-length (integer-length high)))
  1503.             (cond ((= low 0)
  1504.                (cond ((= high 0) '(integer 0 0))
  1505.                  ((= high 1) 'bit)
  1506.                  ((and (= high-count high-length)
  1507.                        (plusp high-length))
  1508.                   `(unsigned-byte ,high-length))
  1509.                  (t
  1510.                   `(mod ,(1+ high)))))
  1511.               ((and (= low vm:target-most-negative-fixnum)
  1512.                 (= high vm:target-most-positive-fixnum))
  1513.                'fixnum)
  1514.               ((and (= low (lognot high))
  1515.                 (= high-count high-length)
  1516.                 (> high-count 0))
  1517.                `(signed-byte ,(1+ high-length)))
  1518.               (t
  1519.                `(integer ,low ,high)))))
  1520.          (high `(,base ,(or low '*) ,high))
  1521.          (low
  1522.           (if (and (eq base 'integer) (= low 0))
  1523.               'unsigned-byte
  1524.               `(,base ,low)))
  1525.          (t base))))
  1526.       (ecase complexp
  1527.     (:real
  1528.      base+bounds)
  1529.     (:complex
  1530.      (if (eq base+bounds 'real)
  1531.          'complex
  1532.          `(complex ,base+bounds)))
  1533.     ((nil)
  1534.      (assert (eq base+bounds 'real))
  1535.      'number)))))
  1536.  
  1537. ;;; Numeric-Bound-Test  --  Internal
  1538. ;;;
  1539. ;;;    Return true if X is "less than or equal" to Y, taking open bounds into
  1540. ;;; consideration.  Closed is the predicate used to test the bound on a closed
  1541. ;;; interval (e.g. <=), and Open is the predicate used on open bounds (e.g. <).
  1542. ;;; Y is considered to be the outside bound, in the sense that if it is
  1543. ;;; infinite (NIL), then the test suceeds, whereas if X is infinite, then the
  1544. ;;; test fails (unless Y is also infinite).
  1545. ;;;
  1546. ;;;    This is for comparing bounds of the same kind, e.g. upper and upper.
  1547. ;;; Use Numeric-Bound-Test* for different kinds of bounds.
  1548. ;;;
  1549. (defmacro numeric-bound-test (x y closed open)
  1550.   `(cond ((not ,y) t)
  1551.      ((not ,x) nil)
  1552.      ((consp ,x)
  1553.       (if (consp ,y)
  1554.           (,closed (car ,x) (car ,y))
  1555.           (,closed (car ,x) ,y)))
  1556.      (t
  1557.       (if (consp ,y)
  1558.           (,open ,x (car ,y))
  1559.           (,closed ,x ,y)))))
  1560.  
  1561.  
  1562. ;;; Numeric-Bound-Test*  --  Internal
  1563. ;;;
  1564. ;;;    Used to compare upper and lower bounds.  This is different from the
  1565. ;;; same-bound case:
  1566. ;;; -- Since X = NIL is -infinity, whereas y = NIL is +infinity, we return true
  1567. ;;;    if *either* arg is NIL.
  1568. ;;; -- an open inner bound is "greater" and also squeezes the interval, causing
  1569. ;;;    us to use the Open test for those cases as well.
  1570. ;;;
  1571. (defmacro numeric-bound-test* (x y closed open)
  1572.   `(cond ((not ,y) t)
  1573.      ((not ,x) t)
  1574.      ((consp ,x)
  1575.       (if (consp ,y)
  1576.           (,open (car ,x) (car ,y))
  1577.           (,open (car ,x) ,y)))
  1578.      (t
  1579.       (if (consp ,y)
  1580.           (,open ,x (car ,y))
  1581.           (,closed ,x ,y)))))
  1582.  
  1583.  
  1584. ;;; Numeric-Bound-Max  --  Internal
  1585. ;;;
  1586. ;;;    Return whichever of the numeric bounds X and Y is "maximal" according to
  1587. ;;; the predicates Closed (e.g. >=) and Open (e.g. >).  This is only meaningful
  1588. ;;; for maximizing like bounds, i.e. upper and upper.  If Max-P is true, then
  1589. ;;; we return NIL if X or Y is NIL, otherwise we return the other arg.
  1590. ;;;
  1591. (defmacro numeric-bound-max (x y closed open max-p)
  1592.   (once-only ((n-x x)
  1593.           (n-y y))
  1594.     `(cond ((not ,n-x) ,(if max-p nil n-y))
  1595.        ((not ,n-y) ,(if max-p nil n-x))
  1596.        ((consp ,n-x)
  1597.         (if (consp ,n-y)
  1598.         (if (,closed (car ,n-x) (car ,n-y)) ,n-x ,n-y)
  1599.         (if (,open (car ,n-x) ,n-y) ,n-x ,n-y)))
  1600.        (t
  1601.         (if (consp ,n-y)
  1602.         (if (,open (car ,n-y) ,n-x) ,n-y ,n-x)
  1603.         (if (,closed ,n-y ,n-x) ,n-y ,n-x))))))
  1604.  
  1605.  
  1606. (define-type-method (number :simple-subtypep) (type1 type2)
  1607.   (let ((class1 (numeric-type-class type1))
  1608.     (class2 (numeric-type-class type2))
  1609.     (complexp2 (numeric-type-complexp type2))
  1610.     (format2 (numeric-type-format type2))
  1611.     (low1 (numeric-type-low type1))
  1612.     (high1 (numeric-type-high type1))
  1613.     (low2 (numeric-type-low type2))
  1614.     (high2 (numeric-type-high type2)))
  1615.     ;;
  1616.     ;; If one is complex and the other isn't, they are disjoint.
  1617.     (cond ((not (or (eq (numeric-type-complexp type1) complexp2)
  1618.             (null complexp2)))
  1619.        (values nil t))
  1620.       ;;
  1621.       ;; If the classes are specified and different, the types are
  1622.       ;; disjoint unless type2 is rational and type1 is integer.
  1623.       ((not (or (eq class1 class2) (null class2)
  1624.             (and (eq class1 'integer) (eq class2 'rational))))
  1625.        (values nil t))
  1626.       ;;
  1627.       ;; If the float formats are specified and different, the types
  1628.       ;; are disjoint.
  1629.       ((not (or (eq (numeric-type-format type1) format2)
  1630.             (null format2)))
  1631.        (values nil t))
  1632.       ;;
  1633.       ;; Check the bounds.
  1634.       ((and (numeric-bound-test low1 low2 >= >)
  1635.         (numeric-bound-test high1 high2 <= <))
  1636.        (values t t))
  1637.       (t
  1638.        (values nil t)))))
  1639.  
  1640.  
  1641. ;;; NUMERIC-TYPES-ADJACENT  --  Internal
  1642. ;;;
  1643. ;;;    If the high bound of Low is adjacent to the low bound of High, then
  1644. ;;; return T, otherwise NIL.
  1645. ;;;
  1646. (defun numeric-types-adjacent (low high)
  1647.   (let ((low-bound (numeric-type-high low))
  1648.     (high-bound (numeric-type-low high)))
  1649.     (cond ((not (and low-bound high-bound)) nil)
  1650.       ((consp low-bound)
  1651.        (eql (car low-bound) high-bound))
  1652.       ((consp high-bound)
  1653.        (eql (car high-bound) low-bound))
  1654.       ((and (eq (numeric-type-class low) 'integer)
  1655.         (eq (numeric-type-class high) 'integer))
  1656.        (eql (1+ low-bound) high-bound))
  1657.       (t
  1658.        nil))))
  1659.  
  1660.  
  1661. ;;; NUMBER :SIMPLE-UNION method  -- Internal
  1662. ;;;
  1663. ;;; Return the a numeric type that is a supertype for both type1 and type2.
  1664. ;;; 
  1665. ;;; ### Note: we give up early, so keep from dropping lots of information on
  1666. ;;; the floor by returning overly general types.
  1667. ;;;
  1668. (define-type-method (number :simple-union) (type1 type2)
  1669.   (declare (type numeric-type type1 type2))
  1670.   (cond ((csubtypep type1 type2) type2)
  1671.     ((csubtypep type2 type1) type1)
  1672.     (t
  1673.      (let ((class1 (numeric-type-class type1))
  1674.            (format1 (numeric-type-format type1))
  1675.            (complexp1 (numeric-type-complexp type1))
  1676.            (class2 (numeric-type-class type2))
  1677.            (format2 (numeric-type-format type2))
  1678.            (complexp2 (numeric-type-complexp type2)))
  1679.        (when (and (eq class1 class2)
  1680.               (eq format1 format2)
  1681.               (eq complexp1 complexp2)
  1682.               (or (numeric-types-intersect type1 type2)
  1683.               (numeric-types-adjacent type1 type2)
  1684.               (numeric-types-adjacent type2 type1)))
  1685.          (make-numeric-type
  1686.           :class class1
  1687.           :format format1
  1688.           :complexp complexp1
  1689.           :low (numeric-bound-max (numeric-type-low type1)
  1690.                       (numeric-type-low type2)
  1691.                       < <= t)
  1692.           :high (numeric-bound-max (numeric-type-high type1)
  1693.                        (numeric-type-high type2)
  1694.                        > >= t)))))))
  1695.  
  1696.  
  1697. (def-builtin-type 'number
  1698.   (make-numeric-type :complexp nil))
  1699.  
  1700.  
  1701. (deftype bit () '(integer 0 1))
  1702. (deftype fixnum ()
  1703.   '(integer #.vm:target-most-negative-fixnum
  1704.         #.vm:target-most-positive-fixnum))
  1705. (deftype bignum () '(and integer (not fixnum)))
  1706.  
  1707. (def-type-translator complex (&optional spec)
  1708.   (if (eq spec '*)
  1709.       (make-numeric-type :complexp :complex)
  1710.       (let ((type (specifier-type spec)))
  1711.     (unless (numeric-type-p type)
  1712.       (error "Component type for Complex is not numeric: ~S." spec))
  1713.     (when (eq (numeric-type-complexp type) :complex)
  1714.       (error "Component type for Complex is complex: ~S." spec))
  1715.  
  1716.     (let ((res (copy-numeric-type type)))
  1717.       (setf (numeric-type-complexp res) :complex)
  1718.       res))))
  1719.  
  1720.  
  1721. ;;; Check-Bound  --  Internal
  1722. ;;;
  1723. ;;;    Check that X is a well-formed numeric bound of the specified Type.
  1724. ;;; If X is *, return NIL, otherwise return the bound.
  1725. ;;;
  1726. (defmacro check-bound (x type)
  1727.   `(cond ((eq ,x '*) nil)
  1728.      ((or (typep ,x ',type)
  1729.           (and (consp ,x) (typep (car ,x) ',type) (null (cdr ,x))))
  1730.       ,x)
  1731.      (t
  1732.       (error "Bound is not *, a ~A or a list of a ~A: ~S" ',type ',type ,x))))
  1733.  
  1734. (def-type-translator integer (&optional low high)
  1735.   (let* ((l (check-bound low integer))
  1736.      (lb (if (consp l) (1+ (car l)) l))
  1737.      (h (check-bound high integer))
  1738.      (hb (if (consp h) (1- (car h)) h)))
  1739.     (when (and hb lb (< hb lb))
  1740.       (error "Lower bound ~S is greater than upper bound ~S." l h))
  1741.     (make-numeric-type :class 'integer  :complexp :real
  1742.                :enumerable (not (null (and l h)))
  1743.                :low lb
  1744.                :high hb)))
  1745.  
  1746. (deftype mod (n)
  1747.   (unless (and (integerp n) (> n 0))
  1748.     (error "Bad N specified for MOD type specifier: ~S." n))
  1749.   `(integer 0 ,(1- n)))
  1750.  
  1751. (deftype signed-byte (&optional s)
  1752.   (cond ((eq s '*) 'integer)
  1753.     ((and (integerp s) (> s 1))
  1754.      (let ((bound (ash 1 (1- s))))
  1755.        `(integer ,(- bound) ,(1- bound))))
  1756.     (t
  1757.      (error "Bad size specified for SIGNED-BYTE type specifier: ~S." s))))
  1758.  
  1759. (deftype unsigned-byte (&optional s)
  1760.   (cond ((eq s '*) '(integer 0))
  1761.     ((and (integerp s) (> s 0))
  1762.      `(integer 0 ,(1- (ash 1 s))))
  1763.     (t
  1764.      (error "Bad size specified for UNSIGNED-BYTE type specifier: ~S." s))))
  1765.  
  1766.  
  1767. (defmacro def-bounded-type (type class format)
  1768.   `(def-type-translator ,type (&optional low high)
  1769.      (let ((lb (check-bound low ,type))
  1770.        (hb (check-bound high ,type)))
  1771.        (unless (numeric-bound-test* lb hb <= <)
  1772.      (error "Lower bound ~S is not less than upper bound ~S." low high))
  1773.        (make-numeric-type :class ',class :format ',format :low lb :high hb))))
  1774.  
  1775. (def-bounded-type rational rational nil)
  1776. (def-bounded-type float float nil)
  1777. (def-bounded-type real nil nil)
  1778.  
  1779. (defmacro define-float-format (f)
  1780.   `(def-bounded-type ,f float ,f))
  1781.  
  1782. (define-float-format short-float)
  1783. (define-float-format single-float)
  1784. (define-float-format double-float)
  1785. (define-float-format long-float)
  1786.  
  1787. (deftype ratio () '(and rational (not integer)))
  1788.  
  1789.  
  1790. (defun numeric-types-intersect (type1 type2)
  1791.   (declare (type numeric-type type1 type2))
  1792.   (let* ((class1 (numeric-type-class type1))
  1793.      (class2 (numeric-type-class type2))
  1794.      (complexp1 (numeric-type-complexp type1))
  1795.      (complexp2 (numeric-type-complexp type2))
  1796.      (format1 (numeric-type-format type1))
  1797.      (format2 (numeric-type-format type2))
  1798.      (low1 (numeric-type-low type1))
  1799.      (high1 (numeric-type-high type1))
  1800.      (low2 (numeric-type-low type2))
  1801.      (high2 (numeric-type-high type2)))
  1802.     ;;
  1803.     ;; If one is complex and the other isn't, then they are disjoint.
  1804.     (cond ((not (or (eq complexp1 complexp2)
  1805.             (null complexp1) (null complexp2)))
  1806.        nil)
  1807.       ;;
  1808.       ;; If either type is a float, then the other must either be specified
  1809.       ;; to be a float or unspecified.  Otherwise, they are disjoint.
  1810.       ((and (eq class1 'float) (not (member class2 '(float nil)))) nil)
  1811.       ((and (eq class2 'float) (not (member class1 '(float nil)))) nil)
  1812.       ;;
  1813.       ;; If the float formats are specified and different, the types
  1814.       ;; are disjoint.
  1815.       ((not (or (eq format1 format2) (null format1) (null format2)))
  1816.        nil)
  1817.       (t
  1818.        ;;
  1819.        ;; Check the bounds.  This is a bit odd because we must always have
  1820.        ;; the outer bound of the interval as the second arg.
  1821.        (if (numeric-bound-test high1 high2 <= <)
  1822.            (or (and (numeric-bound-test low1 low2 >= >)
  1823.             (numeric-bound-test* low1 high2 <= <))
  1824.            (and (numeric-bound-test low2 low1 >= >)
  1825.             (numeric-bound-test* low2 high1 <= <)))
  1826.            (or (and (numeric-bound-test* low2 high1 <= <)
  1827.             (numeric-bound-test low2 low1 >= >))
  1828.            (and (numeric-bound-test high2 high1 <= <)
  1829.             (numeric-bound-test* high2 low1 >= >))))))))
  1830.  
  1831.  
  1832. ;;; Round-Numeric-Bound  --  Internal
  1833. ;;;
  1834. ;;;    Take the numeric bound X and convert it into something that can be used
  1835. ;;; as a bound in a numeric type with the specified Class and Format.  If up-p
  1836. ;;; is true, then we round up as needed, otherwise we round down.  Up-p true
  1837. ;;; implies that X is a lower bound, i.e. (N) > N.
  1838. ;;;
  1839. ;;; This is used by Numeric-Type-Intersection to mash the bound into the
  1840. ;;; appropriate type number.  X may only be a float when Class is Float.
  1841. ;;;
  1842. ;;; ### Note: it is possible for the coercion to a float to overflow or
  1843. ;;; underflow.  This happens when the bound doesn't fit in the specified
  1844. ;;; format.  In this case, we should really return the appropriate
  1845. ;;; {Most | Least}-{Positive | Negative}-XXX-Float float of desired format.
  1846. ;;; But these conditions aren't currently signalled in any useful way.
  1847. ;;;
  1848. ;;; Also, when converting an open rational bound into a float we should
  1849. ;;; probably convert it to a closed bound of the closest float in the specified
  1850. ;;; format.  In general, open float bounds are fucked.
  1851. ;;;
  1852. (defun round-numeric-bound (x class format up-p)
  1853.   (if x
  1854.       (let ((cx (if (consp x) (car x) x)))
  1855.     (ecase class
  1856.       ((nil rational) x)
  1857.       (integer
  1858.        (if (and (consp x) (integerp cx))
  1859.            (if up-p (1+ cx) (1- cx))
  1860.            (if up-p (ceiling cx) (floor cx))))
  1861.       (float
  1862.        (let ((res (if format (coerce cx format) (float cx))))
  1863.          (if (consp x) (list res) res)))))
  1864.       nil))
  1865.  
  1866.  
  1867. ;;; Number :Simple-Intersection type method  --  Internal
  1868. ;;;
  1869. ;;;    Handle the case of Type-Intersection on two numeric types.  We use
  1870. ;;; Types-Intersect to throw out the case of types with no intersection.  If an
  1871. ;;; attribute in Type1 is unspecified, then we use Type2's attribute, which
  1872. ;;; must be at least as restrictive.  If the types intersect, then the only
  1873. ;;; attributes that can be specified and different are the class and the
  1874. ;;; bounds.
  1875. ;;;
  1876. ;;;    When the class differs, we use the more restrictive class.  The only
  1877. ;;; interesting case is rational/integer, since rational includes integer.
  1878. ;;;
  1879. ;;;    We make the result lower (upper) bound the maximum (minimum) of the
  1880. ;;; argument lower (upper) bounds.  We convert the bounds into the
  1881. ;;; appropriate numeric type before maximizing.  This avoids possible confusion
  1882. ;;; due to mixed-type comparisons (but I think the result is the same).
  1883. ;;;
  1884. (define-type-method (number :simple-intersection) (type1 type2)
  1885.   (declare (type numeric-type type1 type2))
  1886.   (if (numeric-types-intersect type1 type2)
  1887.       (let* ((class1 (numeric-type-class type1))
  1888.          (class2 (numeric-type-class type2))
  1889.          (class (ecase class1
  1890.               ((nil) class2)
  1891.               ((integer float) class1)
  1892.               (rational (if (eq class2 'integer) 'integer 'rational))))
  1893.          (format (or (numeric-type-format type1)
  1894.              (numeric-type-format type2))))
  1895.     (values
  1896.      (make-numeric-type
  1897.       :class class
  1898.       :format format
  1899.       :complexp (or (numeric-type-complexp type1)
  1900.             (numeric-type-complexp type2))
  1901.       :low (numeric-bound-max
  1902.         (round-numeric-bound (numeric-type-low type1)
  1903.                      class format t)
  1904.         (round-numeric-bound (numeric-type-low type2)
  1905.                      class format t)
  1906.         >= > nil)
  1907.       :high (numeric-bound-max
  1908.          (round-numeric-bound (numeric-type-high type1)
  1909.                       class format nil)
  1910.          (round-numeric-bound (numeric-type-high type2)
  1911.                       class format nil)
  1912.          <= < nil))
  1913.      t))
  1914.       (values *empty-type* t)))
  1915.  
  1916.  
  1917. ;;; Float-Format-Max  --  Interface
  1918. ;;;
  1919. ;;;    Given two float formats, return the one with more precision.  If either
  1920. ;;; one is null, return NIL.
  1921. ;;;
  1922. (defun float-format-max (f1 f2)
  1923.   (when (and f1 f2)
  1924.     (dolist (f float-formats (error "Bad float format: ~S." f1))
  1925.       (when (or (eq f f1) (eq f f2))
  1926.     (return f)))))
  1927.  
  1928.  
  1929. ;;; Numeric-Contagion  --  Interface
  1930. ;;;
  1931. ;;;    Return the result of an operation on Type1 and Type2 according to the
  1932. ;;; rules of numeric contagion.  This is always NUMBER, some float format
  1933. ;;; (possibly complex) or RATIONAL.  Due to rational canonicalization, there
  1934. ;;; isn't much we can do here with integers or rational complex numbers.
  1935. ;;;
  1936. ;;;    If either argument is not a Numeric-Type, then return NUMBER.  This is
  1937. ;;; useful mainly for allowing types that are technically numbers, but not a
  1938. ;;; Numeric-Type. 
  1939. ;;;
  1940. (defun numeric-contagion (type1 type2)
  1941.   (if (and (numeric-type-p type1) (numeric-type-p type2))
  1942.       (let ((class1 (numeric-type-class type1))
  1943.         (class2 (numeric-type-class type2))
  1944.         (format1 (numeric-type-format type1))
  1945.         (format2 (numeric-type-format type2))
  1946.         (complexp1 (numeric-type-complexp type1))
  1947.         (complexp2 (numeric-type-complexp type2)))
  1948.     (cond ((or (null complexp1)
  1949.            (null complexp2))
  1950.            (specifier-type 'number))
  1951.           ((eq class1 'float)
  1952.            (make-numeric-type
  1953.         :class 'float
  1954.         :format (if (eq class2 'float)
  1955.                 (float-format-max format1 format2)
  1956.                 format1)
  1957.         :complexp (if (or (eq complexp1 :complex)
  1958.                   (eq complexp2 :complex))
  1959.                   :complex
  1960.                   :real)))
  1961.           ((eq class2 'float) (numeric-contagion type2 type1))
  1962.           ((and (eq complexp1 :real) (eq complexp2 :real))
  1963.            (make-numeric-type
  1964.         :class (and class1 class2 'rational)
  1965.         :complexp :real))
  1966.           (t
  1967.            (specifier-type 'number))))
  1968.       (specifier-type 'number)))
  1969.  
  1970.  
  1971. ;;;; Array types:
  1972.  
  1973. ;;; The Array-Type is used to represent all array types, including things such
  1974. ;;; as SIMPLE-STRING.
  1975. ;;;
  1976. (defstruct (array-type (:include ctype
  1977.                  (:class-info (type-class-or-lose 'array)))
  1978.                (:print-function %print-type))
  1979.   ;;
  1980.   ;; The dimensions of the array.  * if unspecified.  If a dimension is
  1981.   ;; unspecified, it is *.
  1982.   (dimensions '* :type (or list (member *)))
  1983.   ;;
  1984.   ;; Is this not a simple array type?
  1985.   (complexp '* :type (member t nil *))
  1986.   ;;
  1987.   ;; The element type as originally specified.
  1988.   (element-type (required-argument) :type ctype)
  1989.   ;;
  1990.   ;; The element type as it is specialized in this implementation.
  1991.   (specialized-element-type *wild-type* :type ctype))
  1992.  
  1993. (define-type-class array)
  1994.  
  1995.  
  1996. ;;; Specialized-Element-Type-Maybe  --  Internal
  1997. ;;;
  1998. ;;;      What this does depends on the setting of the
  1999. ;;; *use-implementation-types* switch.  If true, return the specialized element
  2000. ;;; type, otherwise return the original element type.
  2001. ;;;
  2002. (defun specialized-element-type-maybe (type)
  2003.   (declare (type array-type type))
  2004.   (if *use-implementation-types*
  2005.       (array-type-specialized-element-type type)
  2006.       (array-type-element-type type)))
  2007.  
  2008.  
  2009. (define-type-method (array :simple-=) (type1 type2)
  2010.   (values (and (equal (array-type-dimensions type1)
  2011.               (array-type-dimensions type2))
  2012.            (eq (array-type-complexp type1)
  2013.            (array-type-complexp type2))
  2014.            (type= (specialized-element-type-maybe type1)
  2015.               (specialized-element-type-maybe type2)))
  2016.       t))
  2017.  
  2018.  
  2019. (define-type-method (array :unparse) (type)
  2020.   (let ((dims (array-type-dimensions type))
  2021.     (eltype (type-specifier (array-type-element-type type)))
  2022.     (complexp (array-type-complexp type)))
  2023.     (cond ((eq dims '*)
  2024.        (if (eq eltype '*)
  2025.            (if complexp 'array 'simple-array)
  2026.            (if complexp `(array ,eltype) `(simple-array ,eltype))))
  2027.       ((= (length dims) 1) 
  2028.        (if complexp
  2029.            (if (eq (car dims) '*)
  2030.            (case eltype
  2031.              (bit 'bit-vector)
  2032.              (base-char 'base-string)
  2033.              (* 'vector)
  2034.              (t `(vector ,eltype)))
  2035.            (case eltype
  2036.              (bit `(bit-vector ,(car dims)))
  2037.              (base-char `(base-string ,(car dims)))
  2038.              (t `(vector ,eltype ,(car dims)))))
  2039.            (if (eq (car dims) '*)
  2040.            (case eltype
  2041.              (bit 'simple-bit-vector)
  2042.              (base-char 'simple-base-string)
  2043.              ((t) 'simple-vector)
  2044.              (t `(simple-array ,eltype (*))))
  2045.            (case eltype
  2046.              (bit `(simple-bit-vector ,(car dims)))
  2047.              (base-char `(simple-base-string ,(car dims)))
  2048.              ((t) `(simple-vector ,(car dims)))
  2049.              (t `(simple-array ,eltype ,dims))))))
  2050.       (t
  2051.        (if complexp
  2052.            `(array ,eltype ,dims)
  2053.            `(simple-array ,eltype ,dims))))))
  2054.  
  2055.  
  2056. (define-type-method (array :simple-subtypep) (type1 type2)
  2057.   (let ((dims1 (array-type-dimensions type1))
  2058.     (dims2 (array-type-dimensions type2))
  2059.     (complexp2 (array-type-complexp type2)))
  2060.     ;;
  2061.     ;; See if dimensions are compatible.
  2062.     (cond ((not (or (eq dims2 '*)
  2063.             (and (not (eq dims1 '*))
  2064.              (= (length dims1) (length dims2))
  2065.              (every #'(lambda (x y)
  2066.                     (or (eq y '*) (eql x y)))
  2067.                 dims1 dims2))))
  2068.        (values nil t))
  2069.       ;;
  2070.       ;; See if complexp is compatible.
  2071.       ((not (or (eq complexp2 '*)
  2072.             (eq (array-type-complexp type1) complexp2)))
  2073.        (values nil t))
  2074.       ;;
  2075.       ;; If the type2 eltype is wild, we win.  Otherwise, the types must be
  2076.       ;; identical.
  2077.       ((or (eq (array-type-element-type type2) *wild-type*)
  2078.            (type= (specialized-element-type-maybe type1)
  2079.               (specialized-element-type-maybe type2)))
  2080.        (values t t))
  2081.       (t
  2082.        (values nil t)))))
  2083.  
  2084.  
  2085. (defun array-types-intersect (type1 type2)
  2086.   (declare (type array-type type1 type2))
  2087.   (let ((dims1 (array-type-dimensions type1))
  2088.     (dims2 (array-type-dimensions type2))
  2089.     (complexp1 (array-type-complexp type1))
  2090.     (complexp2 (array-type-complexp type2)))
  2091.     ;;
  2092.     ;; See if dimensions are compatible.
  2093.     (cond ((not (or (eq dims1 '*) (eq dims2 '*)
  2094.             (and (= (length dims1) (length dims2))
  2095.              (every #'(lambda (x y)
  2096.                     (or (eq x '*) (eq y '*) (= x y)))
  2097.                 dims1 dims2))))
  2098.        (values nil t))
  2099.       ;;
  2100.       ;; See if complexp is compatible.
  2101.       ((not (or (eq complexp1 '*) (eq complexp2 '*)
  2102.             (eq complexp1 complexp2)))
  2103.        (values nil t))
  2104.       ;;
  2105.       ;; If either element type is wild, then they intersect.  Otherwise,
  2106.       ;; the types must be identical.
  2107.       ((or (eq (array-type-element-type type1) *wild-type*)
  2108.            (eq (array-type-element-type type2) *wild-type*)
  2109.            (type= (specialized-element-type-maybe type1)
  2110.               (specialized-element-type-maybe type2)))
  2111.  
  2112.        (values t t))
  2113.       (t
  2114.        (values nil t)))))
  2115.  
  2116.  
  2117. (define-type-method (array :simple-intersection) (type1 type2)
  2118.   (declare (type array-type type1 type2))
  2119.   (if (array-types-intersect type1 type2)
  2120.       (let ((dims1 (array-type-dimensions type1))
  2121.         (dims2 (array-type-dimensions type2))
  2122.         (complexp1 (array-type-complexp type1))
  2123.         (complexp2 (array-type-complexp type2))
  2124.         (eltype1 (array-type-element-type type1))
  2125.         (eltype2 (array-type-element-type type2)))
  2126.     (values
  2127.      (specialize-array-type
  2128.       (make-array-type
  2129.        :dimensions (cond ((eq dims1 '*) dims2)
  2130.                  ((eq dims2 '*) dims1)
  2131.                  (t
  2132.                   (mapcar #'(lambda (x y) (if (eq x '*) y x))
  2133.                       dims1 dims2)))
  2134.        :complexp (if (eq complexp1 '*) complexp2 complexp1)
  2135.        :element-type (if (eq eltype1 *wild-type*) eltype2 eltype1)))
  2136.      t))
  2137.       (values *empty-type* t)))
  2138.   
  2139.  
  2140. ;;; Check-Array-Dimensions  --  Internal
  2141. ;;;
  2142. ;;;    Check a supplied dimension list to determine if it is legal.
  2143. ;;;
  2144. (defun check-array-dimensions (dims)
  2145.   (typecase dims
  2146.     ((member *) dims)
  2147.     (integer
  2148.      (when (minusp dims)
  2149.        (error "Arrays can't have a negative number of dimensions: ~D." dims))
  2150.      (when (>= dims array-rank-limit)
  2151.        (error "Array type has too many dimensions: ~S." dims))
  2152.      (make-list dims :initial-element '*))
  2153.     (list
  2154.      (when (>= (length dims) array-rank-limit)
  2155.        (error "Array type has too many dimensions: ~S." dims))
  2156.      (dolist (dim dims)
  2157.        (unless (eq dim '*)
  2158.      (unless (and (integerp dim)
  2159.               (>= dim 0) (< dim array-dimension-limit))
  2160.        (error "Bad dimension in array type: ~S." dim))))
  2161.      dims)
  2162.     (t
  2163.      (error "Array dimensions is not a list, integer or *:~%  ~S"
  2164.         dims))))
  2165.            
  2166. (def-type-translator array (&optional element-type dimensions)
  2167.   (specialize-array-type
  2168.    (make-array-type :dimensions (check-array-dimensions dimensions)
  2169.             :element-type (specifier-type element-type))))
  2170.  
  2171. (def-type-translator simple-array (&optional element-type dimensions)
  2172.   (specialize-array-type
  2173.    (make-array-type :dimensions (check-array-dimensions dimensions)
  2174.             :element-type (specifier-type element-type)
  2175.             :complexp nil)))
  2176.  
  2177. (deftype vector (&optional element-type size)
  2178.   `(array ,element-type (,size)))
  2179.  
  2180. (deftype simple-vector (&optional size)
  2181.   `(simple-array t (,size)))
  2182.  
  2183. (deftype base-string (&optional size)
  2184.   `(array base-char (,size)))
  2185. (deftype simple-base-string (&optional size)
  2186.   `(simple-array base-char (,size)))
  2187. (deftype string (&optional size)
  2188.   `(or (array character (,size))
  2189.        (base-string ,size)))
  2190. (deftype simple-string (&optional size)
  2191.   `(or (simple-array character (,size))
  2192.        (simple-base-string ,size)))
  2193.  
  2194. (deftype bit-vector (&optional size)
  2195.   `(array bit (,size)))
  2196.  
  2197. (deftype simple-bit-vector (&optional size)
  2198.   `(simple-array bit (,size)))
  2199.  
  2200.  
  2201. ;;;; Member types.
  2202.  
  2203. ;;; The Member-Type represents uses of the MEMBER type specifier.  We bother
  2204. ;;; with this at this level because MEMBER types are fairly important and union
  2205. ;;; and intersection are well defined.
  2206.  
  2207. (defstruct (member-type (:include ctype
  2208.                   (:class-info (type-class-or-lose 'member))
  2209.                   (:enumerable t))
  2210.             (:print-function %print-type))
  2211.   ;;
  2212.   ;; The things in the set, with no duplications.
  2213.   (members nil :type list))
  2214.  
  2215.  
  2216. (define-type-class member)
  2217.  
  2218. (define-type-method (member :unparse) (type)
  2219.   (let ((members (member-type-members type)))
  2220.     (if (equal members '(nil))
  2221.     'null
  2222.     `(member ,@members))))
  2223.  
  2224. (define-type-method (member :simple-subtypep) (type1 type2)
  2225.   (values (subsetp (member-type-members type1) (member-type-members type2))
  2226.       t))
  2227.  
  2228.  
  2229. (define-type-method (member :complex-subtypep-arg1) (type1 type2)
  2230.   (block PUNT
  2231.     (values (every-type-op ctypep type2 (member-type-members type1)
  2232.                :list-first t)
  2233.         t)))
  2234.  
  2235. ;;; We punt if the odd type is enumerable and intersects with the member type.
  2236. ;;; If not enumerable, then it is definitely not a subtype of the member type.
  2237. ;;;
  2238. (define-type-method (member :complex-subtypep-arg2) (type1 type2)
  2239.   (cond ((not (type-enumerable type1)) (values nil t))
  2240.     ((types-intersect type1 type2) (values nil nil))
  2241.     (t
  2242.      (values nil t))))
  2243.  
  2244. (define-type-method (member :simple-intersection) (type1 type2)
  2245.   (let ((mem1 (member-type-members type1))
  2246.     (mem2 (member-type-members type2)))
  2247.     (values (cond ((subsetp mem1 mem2) type1)
  2248.           ((subsetp mem2 mem1) type2)
  2249.           (t
  2250.            (let ((res (intersection mem1 mem2)))
  2251.              (if res
  2252.              (make-member-type :members res)
  2253.              *empty-type*))))
  2254.         t)))
  2255.  
  2256. (define-type-method (member :complex-intersection) (type1 type2)
  2257.   (block PUNT
  2258.     (collect ((members))
  2259.       (let ((mem2 (member-type-members type2)))
  2260.     (dolist (member mem2)
  2261.       (multiple-value-bind (val win)
  2262.                    (ctypep member type1)
  2263.         (unless win
  2264.           (return-from PUNT (values type2 nil)))
  2265.         (when val (members member))))
  2266.  
  2267.     (values (cond ((subsetp mem2 (members)) type2)
  2268.               ((null (members)) *empty-type*)
  2269.               (t
  2270.                (make-member-type :members (members))))
  2271.         t)))))
  2272.  
  2273.  
  2274. ;;; We don't need a :COMPLEX-UNION, since the only interesting case is a union
  2275. ;;; type, and the member/union interaction is handled by the union type
  2276. ;;; method.
  2277. (define-type-method (member :simple-union) (type1 type2)
  2278.   (let ((mem1 (member-type-members type1))
  2279.     (mem2 (member-type-members type2)))
  2280.     (cond ((subsetp mem1 mem2) type2)
  2281.       ((subsetp mem2 mem1) type1)
  2282.       (t
  2283.        (make-member-type :members (union mem1 mem2))))))
  2284.  
  2285.  
  2286. (define-type-method (member :simple-=) (type1 type2)
  2287.   (let ((mem1 (member-type-members type1))
  2288.     (mem2 (member-type-members type2)))
  2289.     (values (and (subsetp mem1 mem2) (subsetp mem2 mem1))
  2290.         t)))
  2291.  
  2292. (define-type-method (member :complex-=) (type1 type2)
  2293.   (if (type-enumerable type1)
  2294.       (multiple-value-bind (val win)
  2295.                (csubtypep type2 type1)
  2296.     (if (or val (not win))
  2297.         (values nil nil)
  2298.         (values nil t)))
  2299.       (values nil t)))
  2300.  
  2301.  
  2302. (def-type-translator member (&rest members)
  2303.   (let ((mem (remove-duplicates members)))
  2304.     (if mem
  2305.     (make-member-type :members mem)
  2306.     *empty-type*)))
  2307.  
  2308.  
  2309. ;;;; Structure types.
  2310.  
  2311. ;;; The Structure type is used to represent the type of things known to be
  2312. ;;; structures.
  2313. ;;;
  2314. (defstruct (structure-type
  2315.         (:include ctype
  2316.               (:class-info (type-class-or-lose 'structure)))
  2317.         (:print-function %print-type))
  2318.   ;;
  2319.   ;; Name of the structure type.
  2320.   name)
  2321.  
  2322. (define-type-class structure)
  2323.  
  2324. ;;; The (info type structure-info ...) may be NIL if the type has been
  2325. ;;; undefined since the specifier was parsed.
  2326. ;;;
  2327. (define-type-method (structure :simple-subtypep) (type1 type2)
  2328.   (let ((name2 (structure-type-name type2)))
  2329.     (if (eq (structure-type-name type1) name2)
  2330.     (values t t)
  2331.     (let ((info1 (info type structure-info (structure-type-name type1))))
  2332.       (if info1
  2333.           (if (member name2 (c::dd-includes info1))
  2334.           (values t t)
  2335.           (values nil t))
  2336.           (values nil nil))))))
  2337.  
  2338. (define-type-method (structure :complex-subtypep-arg2) (type1 type2)
  2339.   (declare (type structure-type type2))
  2340.   (values (or (eq type1 *wild-type*)
  2341.           (and (eq (type-class-name (type-class-info type1)) 'alien)
  2342.            (eq (structure-type-name type2) 'alien-value)))
  2343.       t))
  2344.  
  2345. (define-type-method (structure :unparse) (type)
  2346.   (structure-type-name type))
  2347.  
  2348. (define-type-method (structure :simple-=) (type1 type2)
  2349.   (values (eq (structure-type-name type1) (structure-type-name type2))
  2350.       t))
  2351.  
  2352.  
  2353. ;;;; Union types:
  2354.  
  2355. ;;; The Union-Type represents uses of the OR type specifier which can't be
  2356. ;;; canonicalized to something simpler.  Canonical form:
  2357. ;;;
  2358. ;;; 1] There is never more than one Member-Type component.
  2359. ;;; 2] There are never any Union-Type components.
  2360. ;;;
  2361. (defstruct (union-type (:include ctype
  2362.                  (:class-info (type-class-or-lose 'union)))
  2363.                (:constructor %make-union-type (enumerable types))
  2364.                (:print-function %print-type))
  2365.   ;;
  2366.   ;; The types in the union.
  2367.   (types nil :type list))
  2368.  
  2369.  
  2370. ;;; MAKE-UNION-TYPE  --  Internal
  2371. ;;;
  2372. ;;;    Make a union type from the specifier types, setting ENUMERABLE in the
  2373. ;;; result if all are enumerable.
  2374. ;;;
  2375. (defun make-union-type (types)
  2376.   (declare (list types))
  2377.   (%make-union-type (every #'type-enumerable types) types))
  2378.  
  2379.  
  2380. (define-type-class union)
  2381.  
  2382.  
  2383. ;;;    If List, then return that, otherwise the OR of the component types.
  2384. ;;;
  2385. (define-type-method (union :unparse) (type)
  2386.   (declare (type ctype type))
  2387.   (if (type= type (specifier-type 'list))
  2388.       'list
  2389.       `(or ,@(mapcar #'type-specifier (union-type-types type)))))
  2390.  
  2391.  
  2392.  
  2393. ;;; Two union types are equal if every type in one is equal to some type in the
  2394. ;;; other.
  2395. ;;;
  2396. (define-type-method (union :simple-=) (type1 type2)
  2397.   (block PUNT
  2398.     (let ((types1 (union-type-types type1))
  2399.       (types2 (union-type-types type2)))
  2400.       (values (and (dolist (type1 types1 t)
  2401.              (unless (any-type-op type= type1 types2)
  2402.                (return nil)))
  2403.            (dolist (type2 types2 t)
  2404.              (unless (any-type-op type= type2 types1)
  2405.                (return nil))))
  2406.           t))))
  2407.  
  2408.  
  2409. ;;; Similarly, a union type is a subtype of another if every element of Type1
  2410. ;;; is a subtype of some element of Type2.
  2411. ;;;
  2412. (define-type-method (union :simple-subtypep) (type1 type2)
  2413.   (block PUNT
  2414.     (let ((types2 (union-type-types type2)))
  2415.       (values (dolist (type1 (union-type-types type1) t)
  2416.         (unless (any-type-op csubtypep type1 types2)
  2417.           (return nil)))
  2418.           t))))
  2419.  
  2420.  
  2421. (define-type-method (union :complex-subtypep-arg1) (type1 type2)
  2422.   (block PUNT
  2423.     (values (every-type-op csubtypep type2 (union-type-types type1)
  2424.                :list-first t)
  2425.         t)))
  2426.  
  2427. (define-type-method (union :complex-subtypep-arg2) (type1 type2)
  2428.   (block PUNT
  2429.     (values (any-type-op csubtypep type1 (union-type-types type2)) t)))
  2430.  
  2431.  
  2432. (define-type-method (union :complex-union) (type1 type2)
  2433.   (let* ((class1 (type-class-info type1))
  2434.      (union-meth-1 (type-class-simple-union class1)))
  2435.     (collect ((res))
  2436.       (let ((this-type type1))
  2437.     (dolist (type (union-type-types type2)
  2438.               (if (res)
  2439.               (make-union-type (cons this-type (res)))
  2440.               this-type))
  2441.       (cond ((and union-meth-1
  2442.               (eq (type-class-info type) class1))
  2443.          (let ((union (funcall union-meth-1 this-type type)))
  2444.            (if union
  2445.                (setq this-type union)
  2446.                (res type))))
  2447.         ((csubtypep type this-type))
  2448.         ((csubtypep type1 type) (return type2))
  2449.         (t
  2450.          (res type))))))))
  2451.  
  2452. ;;; For the union of union types, we let the :COMPLEX-UNION method do the work.
  2453. ;;;
  2454. (define-type-method (union :simple-union) (type1 type2)
  2455.   (let ((res type1))
  2456.     (dolist (t2 (union-type-types type2) res)
  2457.       (setq res (type-union res t2)))))
  2458.  
  2459.  
  2460. (define-type-method (union :simple-intersection :complex-intersection)
  2461.             (type1 type2)
  2462.   (let ((res *empty-type*)
  2463.     (win t))
  2464.     (dolist (type (union-type-types type2) (values res win))
  2465.       (multiple-value-bind (int w)
  2466.                (type-intersection type1 type)
  2467.     (setq res (type-union res int))
  2468.     (unless w (setq win nil))))))
  2469.  
  2470.  
  2471. (def-type-translator or (&rest types)
  2472.   (reduce #'type-union
  2473.       (mapcar #'specifier-type types)
  2474.       :initial-value *empty-type*))
  2475.  
  2476.  
  2477. ;;;    We don't actually have intersection types, since the result of
  2478. ;;; reasonable type intersections is always describable as a union of simple
  2479. ;;; types.  If something is too hairy to fit this mold, then we make a hairy
  2480. ;;; type.
  2481. (def-type-translator and (&whole spec &rest types)
  2482.   (let ((res *wild-type*))
  2483.     (dolist (type types res)
  2484.       (let ((ctype (specifier-type type)))
  2485.     (multiple-value-bind (int win)
  2486.                  (type-intersection res ctype)
  2487.       (unless win
  2488.         (return (make-hairy-type :specifier spec)))
  2489.       (setq res int))))))
  2490.  
  2491.  
  2492. ;;;; Alien-type types
  2493.  
  2494. (defstruct (alien-type-type
  2495.         (:include ctype
  2496.               (:class-info (type-class-or-lose 'alien)))
  2497.         (:print-function %print-type)
  2498.         (:constructor %make-alien-type-type (alien-type)))
  2499.   (alien-type nil :type alien-type))
  2500.  
  2501. (define-type-class alien)
  2502.  
  2503. (define-type-method (alien :unparse) (type)
  2504.   `(alien ,(unparse-alien-type (alien-type-type-alien-type type))))
  2505.  
  2506. (define-type-method (alien :simple-subtypep) (type1 type2)
  2507.   (values (alien-subtype-p (alien-type-type-alien-type type1)
  2508.                (alien-type-type-alien-type type2))
  2509.       t))
  2510.  
  2511. (define-type-method (alien :simple-=) (type1 type2)
  2512.   (let ((alien-type-1 (alien-type-type-alien-type type1))
  2513.     (alien-type-2 (alien-type-type-alien-type type2)))
  2514.     (values (or (eq alien-type-1 alien-type-2)
  2515.         (alien-type-= alien-type-1 alien-type-2))
  2516.         t)))
  2517.  
  2518. (define-type-method (alien :complex-intersection) (type1 type2)
  2519.   (vanilla-intersection type1 type2))
  2520.  
  2521. (def-type-translator alien (&optional (alien-type nil))
  2522.   (typecase alien-type
  2523.     (null
  2524.      (make-alien-type-type))
  2525.     (alien-type
  2526.      (make-alien-type-type alien-type))
  2527.     (t
  2528.      (make-alien-type-type (parse-alien-type alien-type)))))
  2529.  
  2530. (defun make-alien-type-type (&optional alien-type)
  2531.   (if alien-type
  2532.       (let ((lisp-rep-type (compute-lisp-rep-type alien-type)))
  2533.     (if lisp-rep-type
  2534.         (specifier-type lisp-rep-type)
  2535.         (%make-alien-type-type alien-type)))
  2536.       *universal-type*))
  2537.  
  2538.  
  2539. ;;; TYPE-DIFFERENCE  --  Interface
  2540. ;;;
  2541. ;;;    Return the type that describes all objects that are in X but not in Y.
  2542. ;;; If we can't determine this type, then return NIL.
  2543. ;;;
  2544. ;;;    For now, we only are clever dealing with union and member types.  If
  2545. ;;; either type is not a union type, then we pretend that it is a union of just
  2546. ;;; one type.  What we do is remove from X all the types that are a subtype any
  2547. ;;; type in Y.  If any type in X intersects with a type in Y but is not a
  2548. ;;; subtype, then we give up.
  2549. ;;;
  2550. ;;;    We must also special-case any member type that appears in the union.  We
  2551. ;;; remove from X's members all objects that are TYPEP to Y.  If Y has any
  2552. ;;; members, we must be careful that none of those members are CTYPEP to any
  2553. ;;; of Y's non-member types.  We give up in this case, since to compute that
  2554. ;;; difference we would have to break the type from X into some collection of
  2555. ;;; types that represents the type without that particular element.  This seems
  2556. ;;; too hairy to be worthwhile, given its low utility.
  2557. ;;;
  2558. (defun type-difference (x y)
  2559.   (let ((x-types (if (union-type-p x) (union-type-types x) (list x)))
  2560.     (y-types (if (union-type-p y) (union-type-types y) (list y))))
  2561.     (collect ((res))
  2562.       (dolist (x-type x-types)
  2563.     (if (member-type-p x-type)
  2564.         (collect ((members))
  2565.           (dolist (mem (member-type-members x-type))
  2566.         (multiple-value-bind (val win)
  2567.                      (ctypep mem y)
  2568.           (unless win (return-from type-difference nil))
  2569.           (unless val
  2570.             (members mem))))
  2571.           (when (members)
  2572.         (res (make-member-type :members (members)))))
  2573.         (dolist (y-type y-types (res x-type))
  2574.           (multiple-value-bind (val win)
  2575.                    (csubtypep x-type y-type)
  2576.         (unless win (return-from type-difference nil))
  2577.         (when val (return))
  2578.         (when (types-intersect x-type y-type)
  2579.           (return-from type-difference nil))))))
  2580.  
  2581.       (let ((y-mem (find-if #'member-type-p y-types)))
  2582.     (when y-mem
  2583.       (let ((members (member-type-members y-mem)))
  2584.         (dolist (x-type x-types)
  2585.           (unless (member-type-p x-type)
  2586.         (dolist (member members)
  2587.           (multiple-value-bind (val win)
  2588.                        (ctypep member x-type)
  2589.             (when (or (not win) val)
  2590.               (return-from type-difference nil)))))))))
  2591.  
  2592.       (cond ((null (res)) *empty-type*)
  2593.         ((null (rest (res))) (first (res)))
  2594.         (t
  2595.          (make-union-type (res)))))))
  2596.  
  2597.  
  2598. ;;;; Miscellaneous interfaces:
  2599.  
  2600. ;;; CTypep  --  Internal
  2601. ;;;
  2602. ;;;    If Type is a type that we can do a compile-time test on, then return the
  2603. ;;; whether the object is of that type as the first value and second value
  2604. ;;; true.  Otherwise return NIL, NIL.
  2605. ;;;
  2606. ;;; We give up on unknown types, pick off FUNCTION and UNION types.  For
  2607. ;;; structure types, we require that the type be defined in both the current
  2608. ;;; and compiler environments, and that the INCLUDES be the same.
  2609. ;;;
  2610. (defun ctypep (obj type)
  2611.   (declare (type ctype type))
  2612.   (etypecase type
  2613.     ((or numeric-type named-type member-type array-type)
  2614.      (values (typep obj (type-specifier type)) t))
  2615.     (structure-type
  2616.      (if (structurep obj)
  2617.      (let* ((name (structure-type-name type))
  2618.         (info (info type structure-info name))
  2619.         (defined-info (info type defined-structure-info name)))
  2620.        (if (and info defined-info
  2621.             (equal (c::dd-includes info)
  2622.                (c::dd-includes defined-info)))
  2623.            (values (typep obj name) t)
  2624.            (values nil nil)))
  2625.      (values nil t)))
  2626.     (union-type
  2627.      (dolist (mem (union-type-types type) (values nil t))
  2628.        (multiple-value-bind (val win)
  2629.                 (ctypep obj mem)
  2630.      (unless win (return (values nil nil)))
  2631.      (when val (return (values t t))))))
  2632.     (function-type
  2633.      (values (functionp obj) t))
  2634.     (unknown-type
  2635.      (values nil nil))
  2636.     (alien-type-type
  2637.      (values (alien-typep obj (alien-type-type-alien-type type)) t))
  2638.     (hairy-type
  2639.      ;; Now the tricky stuff.
  2640.      (let* ((hairy-spec (hairy-type-specifier type))
  2641.         (symbol (if (consp hairy-spec) (car hairy-spec) hairy-spec)))
  2642.        (ecase symbol
  2643.      (and
  2644.       (if (atom hairy-spec)
  2645.           (values t t)
  2646.           (dolist (spec (cdr hairy-spec) (values t t))
  2647.         (multiple-value-bind (res win)
  2648.                      (ctypep obj (specifier-type spec))
  2649.           (unless win (return (values nil nil)))
  2650.           (unless res (return (values nil t)))))))
  2651.      (not
  2652.       (multiple-value-bind
  2653.           (res win)
  2654.           (ctypep obj (specifier-type (cadr hairy-spec)))
  2655.         (if win
  2656.         (values (not res) t)
  2657.         (values nil nil))))
  2658.      (satisfies
  2659.       (let ((fun (second hairy-spec)))
  2660.         (cond ((and (consp fun) (eq (car fun) 'lambda))
  2661.            (values (not (null (funcall (coerce fun 'function) obj)))
  2662.                t))
  2663.           ((and (symbolp fun) (fboundp fun))
  2664.            (values (not (null (funcall fun obj))) t))
  2665.           (t
  2666.            (values nil nil))))))))))
  2667.  
  2668.  
  2669. ;;; Ctype-Of  --  Interface
  2670. ;;;
  2671. ;;;    Like Type-Of, only returns a Type structure instead of a type
  2672. ;;; specifier.  We try to return the type most useful for type checking, rather
  2673. ;;; than trying to come up with the one that the user might find most
  2674. ;;; informative.
  2675. ;;;
  2676. (proclaim '(function ctype-of (t) ctype))
  2677. (defun-cached (ctype-of
  2678.            :hash-function (lambda (x)
  2679.                 (the fixnum
  2680.                      (logand (the fixnum (cache-hash-eq x))
  2681.                          #x1FF)))
  2682.            :hash-bits 9)
  2683.           ((x eq))
  2684.   (typecase x
  2685.     (character
  2686.      (specifier-type
  2687.       (if (standard-char-p x)
  2688.       'standard-char
  2689.       'base-char)))
  2690.     (compiled-function (specifier-type 'compiled-function))
  2691.     (cons (specifier-type 'cons))
  2692.     (symbol
  2693.      (make-member-type :members (list x)))
  2694.     (number
  2695.      (let* ((num (if (complexp x) (realpart x) x))
  2696.         (res (make-numeric-type
  2697.           :class (etypecase num
  2698.                (integer 'integer)
  2699.                (rational 'rational)
  2700.                (float 'float))
  2701.           :format (if (floatp num)
  2702.                   (float-format-name num)
  2703.                   nil))))
  2704.        (cond ((complexp x)
  2705.           (setf (numeric-type-complexp res) :complex)
  2706.           (let ((imag (imagpart x)))
  2707.         (setf (numeric-type-low res) (min num imag))
  2708.         (setf (numeric-type-high res) (max num imag))))
  2709.          (t
  2710.           (setf (numeric-type-low res) num)
  2711.           (setf (numeric-type-high res) num)))
  2712.        res))
  2713.     (structure
  2714.      ;;
  2715.      ;; In bootstrapping, there can be an instance of a structure type that
  2716.      ;; isn't defined in the current environment.
  2717.      (let ((type (type-of x)))
  2718.        (if (info type structure-info type)
  2719.        (make-structure-type :name type)
  2720.        *universal-type*)))
  2721.     (array
  2722.      (let ((etype (specifier-type (array-element-type x))))
  2723.        (make-array-type :dimensions (array-dimensions x)
  2724.             :complexp (not (typep x 'simple-array))
  2725.             :element-type etype
  2726.             :specialized-element-type etype)))
  2727.     (t
  2728.      *universal-type*)))
  2729.  
  2730. ;;; Clear this cache on GC so that we don't hold onto too much garbage.
  2731. ;;;
  2732. (pushnew 'ctype-of-cache-clear *before-gc-hooks*)
  2733.  
  2734.  
  2735. ;;;; Standard Deftypes.
  2736.  
  2737. (deftype atom () '(not cons))
  2738. (deftype list () '(or cons null))
  2739. (deftype null () '(member nil))
  2740. (deftype sequence () '(or vector list))
  2741.  
  2742.  
  2743. ;;;; Compatibility Deftypes.
  2744.  
  2745. ;;; (Array Number) should probably really be (Array Common), but we can't hack 
  2746. ;;; circular type definitions.  This is probably O.K. since numeric arrays
  2747. ;;; are the only kind of Common array which is likely to exist. 
  2748. (deftype common ()
  2749.   '(or cons symbol (array t) (array number) string number standard-char structure))
  2750.  
  2751. (deftype string-char ()
  2752.   'base-char)
  2753.  
  2754.  
  2755. ;;;; Some types that we use in defining the standard functions:
  2756. ;;; 
  2757.  
  2758. ;;;
  2759. ;;; A type specifier.
  2760. (deftype type-specifier () '(or list symbol))
  2761. ;;;
  2762. ;;; An index into an array.   Also used for sequence index. 
  2763. (deftype index () `(integer 0 (,array-dimension-limit)))
  2764. ;;;
  2765. ;;; Array rank, total size...
  2766. (deftype array-rank () `(integer 0 (,array-rank-limit)))
  2767. (deftype array-total-size () `(integer 0 (,array-total-size-limit)))
  2768. ;;;
  2769. ;;; Some thing legal in an evaluated context.
  2770. (deftype form () t)
  2771. ;;;
  2772. ;;; Maclisp compatibility...
  2773. (deftype stringlike () '(or string symbol))
  2774. (deftype stringable () '(or string symbol character))
  2775. ;;;
  2776. ;;; Save a little typing...
  2777. (deftype truth () '(member t))
  2778. ;;;
  2779. ;;; A thing legal in places where we want the name of a file.
  2780. (deftype filename () '(or string pathname))
  2781. ;;;
  2782. ;;; A legal arg to pathname functions.
  2783. (deftype pathnamelike () '(or string pathname stream))
  2784. ;;;
  2785. ;;; A thing returned by the irrational functions.  We assume that they never
  2786. ;;; compute a rational result.
  2787. (deftype irrational () '(or float (complex float)))
  2788. ;;;
  2789. ;;; Character components:
  2790. (deftype char-code () `(integer 0 (,char-code-limit)))
  2791. ;;;
  2792. ;;; A consed sequence result.  If a vector, is a simple array.
  2793. (deftype consed-sequence () '(or list (simple-array * (*))))
  2794. ;;;
  2795. ;;; The :end arg to a sequence...
  2796. (deftype sequence-end () '(or null index))
  2797. ;;;
  2798. ;;; A valid argument to a stream function...
  2799. (deftype streamlike () '(or stream (member nil t)))
  2800. ;;;
  2801. ;;; A thing that can be passed to funcall & friends.
  2802. (deftype callable () '(or function symbol))
  2803.  
  2804. ;;; Until we decide if and how to wedge this into the type system, make it
  2805. ;;; equivalent to t.
  2806. ;;;
  2807. (deftype void () t)
  2808.  
  2809.  
  2810. ;;; ### Hack.  We need this for at lease a few more iterations.
  2811. (deftype base-character () 'base-char)
  2812.  
  2813.  
  2814.  
  2815. ;;;; Cold loading initializations.
  2816.  
  2817. (emit-cold-load-defuns)
  2818.  
  2819. (defun type-init ()
  2820.   (setf *use-implementation-types* t)
  2821.   (setf *type-classes* (make-hash-table :test #'equal))
  2822.   (setf *unparse-function-type-simplify* nil)
  2823.   (setf *values-type-union-cache-vector*
  2824.     (make-array (* (ash 1 8) (+ 2 1))))
  2825.   (setf *values-type-intersection-cache-vector*
  2826.     (make-array (* (ash 1 8) (+ 2 2))))
  2827.   (setf *values-subtypep-cache-vector*
  2828.     (make-array (* (ash 1 8) (+ 2 2))))
  2829.   (setf *csubtypep-cache-vector*
  2830.     (make-array (* (ash 1 8) (+ 2 2))))
  2831.   (setf *type=-cache-vector*
  2832.     (make-array (* (ash 1 8) (+ 2 2))))
  2833.   (setf *type-union-cache-vector*
  2834.     (make-array (* (ash 1 8) (+ 2 1))))
  2835.   (setf *type-intersection-cache-vector*
  2836.     (make-array (* (ash 1 8) (+ 2 2))))
  2837.   (setf *values-specifier-type-cache-vector*
  2838.     (make-array (* (ash 1 10) (+ 1 1))))
  2839.   (setf *ctype-of-cache-vector*
  2840.     (make-array (* (ash 1 9) (+ 1 1))))
  2841.   (do-cold-load-init-forms)
  2842.   nil)
  2843.