armload of DEFINE-HASH-CACHE changes
[sbcl.git] / src / code / early-type.lisp
1 ;;;; This software is part of the SBCL system. See the README file for
2 ;;;; more information.
3 ;;;;
4 ;;;; This software is derived from the CMU CL system, which was
5 ;;;; written at Carnegie Mellon University and released into the
6 ;;;; public domain. The software is in the public domain and is
7 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
8 ;;;; files for more information.
9
10 (in-package "SB!KERNEL")
11
12 (!begin-collecting-cold-init-forms)
13
14 ;;;; representations of types
15
16 ;;; A HAIRY-TYPE represents anything too weird to be described
17 ;;; reasonably or to be useful, such as NOT, SATISFIES, unknown types,
18 ;;; and unreasonably complicated types involving AND. We just remember
19 ;;; the original type spec.
20 (defstruct (hairy-type (:include ctype
21                                  (class-info (type-class-or-lose 'hairy))
22                                  (enumerable t)
23                                  (might-contain-other-types-p t))
24                        (:copier nil)
25                        #!+cmu (:pure nil))
26   ;; the Common Lisp type-specifier of the type we represent
27   (specifier nil :type t))
28
29 (!define-type-class hairy)
30
31 ;;; An UNKNOWN-TYPE is a type not known to the type system (not yet
32 ;;; defined). We make this distinction since we don't want to complain
33 ;;; about types that are hairy but defined.
34 (defstruct (unknown-type (:include hairy-type)
35                          (:copier nil)))
36
37 (defun maybe-reparse-specifier (type)
38   (when (unknown-type-p type)
39     (let* ((spec (unknown-type-specifier type))
40            (name (if (consp spec)
41                      (car spec)
42                      spec)))
43       (when (info :type :kind name)
44         (let ((new-type (specifier-type spec)))
45           (unless (unknown-type-p new-type)
46             new-type))))))
47
48 ;;; Evil macro.
49 (defmacro maybe-reparse-specifier! (type)
50   (assert (symbolp type))
51   (with-unique-names (new-type)
52     `(let ((,new-type (maybe-reparse-specifier ,type)))
53        (when ,new-type
54          (setf ,type ,new-type)
55          t))))
56
57 (defstruct (negation-type (:include ctype
58                                     (class-info (type-class-or-lose 'negation))
59                                     ;; FIXME: is this right?  It's
60                                     ;; what they had before, anyway
61                                     (enumerable t)
62                                     (might-contain-other-types-p t))
63                           (:copier nil)
64                           #!+cmu (:pure nil))
65   (type (missing-arg) :type ctype))
66
67 (!define-type-class negation)
68
69 ;;; ARGS-TYPE objects are used both to represent VALUES types and
70 ;;; to represent FUNCTION types.
71 (defstruct (args-type (:include ctype)
72                       (:constructor nil)
73                       (:copier nil))
74   ;; Lists of the type for each required and optional argument.
75   (required nil :type list)
76   (optional nil :type list)
77   ;; The type for the rest arg. NIL if there is no &REST arg.
78   (rest nil :type (or ctype null))
79   ;; true if &KEY arguments are specified
80   (keyp nil :type boolean)
81   ;; list of KEY-INFO structures describing the &KEY arguments
82   (keywords nil :type list)
83   ;; true if other &KEY arguments are allowed
84   (allowp nil :type boolean))
85
86 (defun canonicalize-args-type-args (required optional rest &optional keyp)
87   (when (eq rest *empty-type*)
88     ;; or vice-versa?
89     (setq rest nil))
90   (loop with last-not-rest = nil
91         for i from 0
92         for opt in optional
93         do (cond ((eq opt *empty-type*)
94                   (return (values required (subseq optional i) rest)))
95                  ((and (not keyp) (neq opt rest))
96                   (setq last-not-rest i)))
97         finally (return (values required
98                                 (cond (keyp
99                                        optional)
100                                       (last-not-rest
101                                        (subseq optional 0 (1+ last-not-rest))))
102                                 rest))))
103
104 (defun parse-args-types (lambda-list-like-thing)
105   (multiple-value-bind
106         (required optional restp rest keyp keys allowp auxp aux
107                   morep more-context more-count llk-p)
108       (parse-lambda-list-like-thing lambda-list-like-thing :silent t)
109     (declare (ignore aux morep more-context more-count))
110     (when auxp
111       (error "&AUX in a FUNCTION or VALUES type: ~S." lambda-list-like-thing))
112     (let ((required (mapcar #'single-value-specifier-type required))
113           (optional (mapcar #'single-value-specifier-type optional))
114           (rest (when restp (single-value-specifier-type rest)))
115           (keywords
116            (collect ((key-info))
117              (dolist (key keys)
118                (unless (proper-list-of-length-p key 2)
119                  (error "Keyword type description is not a two-list: ~S." key))
120                (let ((kwd (first key)))
121                  (when (find kwd (key-info) :key #'key-info-name)
122                    (error "~@<repeated keyword ~S in lambda list: ~2I~_~S~:>"
123                           kwd lambda-list-like-thing))
124                  (key-info
125                   (make-key-info
126                    :name kwd
127                    :type (single-value-specifier-type (second key))))))
128              (key-info))))
129       (multiple-value-bind (required optional rest)
130           (canonicalize-args-type-args required optional rest keyp)
131         (values required optional rest keyp keywords allowp llk-p)))))
132
133 (defstruct (values-type
134             (:include args-type
135                       (class-info (type-class-or-lose 'values)))
136             (:constructor %make-values-type)
137             (:copier nil)))
138
139 (defun-cached (make-values-type-cached
140                :hash-bits 8
141                :hash-function (lambda (req opt rest allowp)
142                                 (logand (logxor
143                                          (type-list-cache-hash req)
144                                          (type-list-cache-hash opt)
145                                          (if rest
146                                              (type-hash-value rest)
147                                              42)
148                                          (sxhash allowp))
149                                         #xFF)))
150     ((required equal-but-no-car-recursion)
151      (optional equal-but-no-car-recursion)
152      (rest eq)
153      (allowp eq))
154   (%make-values-type :required required
155                      :optional optional
156                      :rest rest
157                      :allowp allowp))
158
159 (defun make-values-type (&key required optional rest allowp)
160   (multiple-value-bind (required optional rest)
161       (canonicalize-args-type-args required optional rest)
162     (cond ((and (null required)
163                 (null optional)
164                 (eq rest *universal-type*))
165            *wild-type*)
166           ((memq *empty-type* required)
167            *empty-type*)
168           (t (make-values-type-cached required optional
169                                       rest allowp)))))
170
171 (!define-type-class values)
172
173 ;;; (SPECIFIER-TYPE 'FUNCTION) and its subtypes
174 (defstruct (fun-type (:include args-type
175                                (class-info (type-class-or-lose 'function)))
176                      (:constructor
177                       make-fun-type (&key required optional rest
178                                           keyp keywords allowp
179                                           wild-args
180                                           returns
181                                      &aux (rest (if (eq rest *empty-type*)
182                                                     nil
183                                                     rest)))))
184   ;; true if the arguments are unrestrictive, i.e. *
185   (wild-args nil :type boolean)
186   ;; type describing the return values. This is a values type
187   ;; when multiple values were specified for the return.
188   (returns (missing-arg) :type ctype))
189
190 ;;; The CONSTANT-TYPE structure represents a use of the CONSTANT-ARG
191 ;;; "type specifier", which is only meaningful in function argument
192 ;;; type specifiers used within the compiler. (It represents something
193 ;;; that the compiler knows to be a constant.)
194 (defstruct (constant-type
195             (:include ctype
196                       (class-info (type-class-or-lose 'constant)))
197             (:copier nil))
198   ;; The type which the argument must be a constant instance of for this type
199   ;; specifier to win.
200   (type (missing-arg) :type ctype))
201
202 ;;; The NAMED-TYPE is used to represent *, T and NIL, the standard
203 ;;; special cases, as well as other special cases needed to
204 ;;; interpolate between regions of the type hierarchy, such as
205 ;;; INSTANCE (which corresponds to all those classes with slots which
206 ;;; are not funcallable), FUNCALLABLE-INSTANCE (those classes with
207 ;;; slots which are funcallable) and EXTENDED-SEQUUENCE (non-LIST
208 ;;; non-VECTOR classes which are also sequences).  These special cases
209 ;;; are the ones that aren't really discussed by Baker in his
210 ;;; "Decision Procedure for SUBTYPEP" paper.
211 (defstruct (named-type (:include ctype
212                                  (class-info (type-class-or-lose 'named)))
213                        (:copier nil))
214   (name nil :type symbol))
215
216 ;;; a list of all the float "formats" (i.e. internal representations;
217 ;;; nothing to do with #'FORMAT), in order of decreasing precision
218 (eval-when (:compile-toplevel :load-toplevel :execute)
219   (defparameter *float-formats*
220     '(long-float double-float single-float short-float)))
221
222 ;;; The type of a float format.
223 (deftype float-format () `(member ,@*float-formats*))
224
225 ;;; A NUMERIC-TYPE represents any numeric type, including things
226 ;;; such as FIXNUM.
227 (defstruct (numeric-type (:include ctype
228                                    (class-info (type-class-or-lose 'number)))
229                          (:constructor %make-numeric-type)
230                          (:copier nil))
231   ;; the kind of numeric type we have, or NIL if not specified (just
232   ;; NUMBER or COMPLEX)
233   ;;
234   ;; KLUDGE: A slot named CLASS for a non-CLASS value is bad.
235   ;; Especially when a CLASS value *is* stored in another slot (called
236   ;; CLASS-INFO:-). Perhaps this should be called CLASS-NAME? Also
237   ;; weird that comment above says "Numeric-Type is used to represent
238   ;; all numeric types" but this slot doesn't allow COMPLEX as an
239   ;; option.. how does this fall into "not specified" NIL case above?
240   ;; Perhaps someday we can switch to CLOS and make NUMERIC-TYPE
241   ;; be an abstract base class and INTEGER-TYPE, RATIONAL-TYPE, and
242   ;; whatnot be concrete subclasses..
243   (class nil :type (member integer rational float nil) :read-only t)
244   ;; "format" for a float type (i.e. type specifier for a CPU
245   ;; representation of floating point, e.g. 'SINGLE-FLOAT -- nothing
246   ;; to do with #'FORMAT), or NIL if not specified or not a float.
247   ;; Formats which don't exist in a given implementation don't appear
248   ;; here.
249   (format nil :type (or float-format null) :read-only t)
250   ;; Is this a complex numeric type?  Null if unknown (only in NUMBER).
251   ;;
252   ;; FIXME: I'm bewildered by FOO-P names for things not intended to
253   ;; interpreted as truth values. Perhaps rename this COMPLEXNESS?
254   (complexp :real :type (member :real :complex nil) :read-only t)
255   ;; The upper and lower bounds on the value, or NIL if there is no
256   ;; bound. If a list of a number, the bound is exclusive. Integer
257   ;; types never have exclusive bounds, i.e. they may have them on
258   ;; input, but they're canonicalized to inclusive bounds before we
259   ;; store them here.
260   (low nil :type (or number cons null) :read-only t)
261   (high nil :type (or number cons null) :read-only t))
262
263 ;;; Impose canonicalization rules for NUMERIC-TYPE. Note that in some
264 ;;; cases, despite the name, we return *EMPTY-TYPE* instead of a
265 ;;; NUMERIC-TYPE.
266 (defun make-numeric-type (&key class format (complexp :real) low high
267                                enumerable)
268   ;; if interval is empty
269   (if (and low
270            high
271            (if (or (consp low) (consp high)) ; if either bound is exclusive
272                (>= (type-bound-number low) (type-bound-number high))
273                (> low high)))
274       *empty-type*
275       (multiple-value-bind (canonical-low canonical-high)
276           (case class
277             (integer
278              ;; INTEGER types always have their LOW and HIGH bounds
279              ;; represented as inclusive, not exclusive values.
280              (values (if (consp low)
281                          (1+ (type-bound-number low))
282                          low)
283                      (if (consp high)
284                          (1- (type-bound-number high))
285                          high)))
286             (t
287              ;; no canonicalization necessary
288              (values low high)))
289         (when (and (eq class 'rational)
290                    (integerp canonical-low)
291                    (integerp canonical-high)
292                    (= canonical-low canonical-high))
293           (setf class 'integer))
294         (%make-numeric-type :class class
295                             :format format
296                             :complexp complexp
297                             :low canonical-low
298                             :high canonical-high
299                             :enumerable enumerable))))
300
301 (defun modified-numeric-type (base
302                               &key
303                               (class      (numeric-type-class      base))
304                               (format     (numeric-type-format     base))
305                               (complexp   (numeric-type-complexp   base))
306                               (low        (numeric-type-low        base))
307                               (high       (numeric-type-high       base))
308                               (enumerable (numeric-type-enumerable base)))
309   (make-numeric-type :class class
310                      :format format
311                      :complexp complexp
312                      :low low
313                      :high high
314                      :enumerable enumerable))
315
316 (defstruct (character-set-type
317             (:include ctype
318                       (class-info (type-class-or-lose 'character-set)))
319             (:constructor %make-character-set-type)
320             (:copier nil))
321   (pairs (missing-arg) :type list :read-only t))
322 (defun make-character-set-type (&key pairs)
323   ; (aver (equal (mapcar #'car pairs)
324   ;              (sort (mapcar #'car pairs) #'<)))
325   ;; aver that the cars of the list elements are sorted into increasing order
326   (aver (or (null pairs)
327             (do ((p pairs (cdr p)))
328                 ((null (cdr p)) t)
329               (when (> (caar p) (caadr p)) (return nil)))))
330   (let ((pairs (let (result)
331                 (do ((pairs pairs (cdr pairs)))
332                     ((null pairs) (nreverse result))
333                   (destructuring-bind (low . high) (car pairs)
334                     (loop for (low1 . high1) in (cdr pairs)
335                           if (<= low1 (1+ high))
336                           do (progn (setf high (max high high1))
337                                     (setf pairs (cdr pairs)))
338                           else do (return nil))
339                     (cond
340                       ((>= low sb!xc:char-code-limit))
341                       ((< high 0))
342                       (t (push (cons (max 0 low)
343                                      (min high (1- sb!xc:char-code-limit)))
344                                result))))))))
345     (if (null pairs)
346        *empty-type*
347        (%make-character-set-type :pairs pairs))))
348
349 ;;; An ARRAY-TYPE is used to represent any array type, including
350 ;;; things such as SIMPLE-BASE-STRING.
351 (defstruct (array-type (:include ctype
352                                  (class-info (type-class-or-lose 'array)))
353                        (:constructor %make-array-type)
354                        (:copier nil))
355   ;; the dimensions of the array, or * if unspecified. If a dimension
356   ;; is unspecified, it is *.
357   (dimensions '* :type (or list (member *)))
358   ;; Is this not a simple array type? (:MAYBE means that we don't know.)
359   (complexp :maybe :type (member t nil :maybe))
360   ;; the element type as originally specified
361   (element-type (missing-arg) :type ctype)
362   ;; the element type as it is specialized in this implementation
363   (specialized-element-type *wild-type* :type ctype))
364 (define-cached-synonym make-array-type)
365
366 ;;; A MEMBER-TYPE represent a use of the MEMBER type specifier. We
367 ;;; bother with this at this level because MEMBER types are fairly
368 ;;; important and union and intersection are well defined.
369 (defstruct (member-type (:include ctype
370                                   (class-info (type-class-or-lose 'member))
371                                   (enumerable t))
372                         (:copier nil)
373                         (:constructor %make-member-type (xset fp-zeroes))
374                         #-sb-xc-host (:pure nil))
375   (xset (missing-arg) :type xset)
376   (fp-zeroes (missing-arg) :type list))
377 (defun make-member-type (&key xset fp-zeroes members)
378   (unless xset
379     (aver (not fp-zeroes))
380     (setf xset (alloc-xset))
381     (dolist (elt members)
382       (if (fp-zero-p elt)
383           (pushnew elt fp-zeroes)
384           (add-to-xset elt xset))))
385   ;; if we have a pair of zeros (e.g. 0.0d0 and -0.0d0), then we can
386   ;; canonicalize to (DOUBLE-FLOAT 0.0d0 0.0d0), because numeric
387   ;; ranges are compared by arithmetic operators (while MEMBERship is
388   ;; compared by EQL).  -- CSR, 2003-04-23
389   (let ((unpaired nil)
390         (union-types nil))
391     (do ((tail (cdr fp-zeroes) (cdr tail))
392          (zero (car fp-zeroes) (car tail)))
393         ((not zero))
394       (macrolet ((frob (c)
395                    `(let ((neg (neg-fp-zero zero)))
396                       (if (member neg tail)
397                           (push (ctype-of ,c) union-types)
398                           (push zero unpaired)))))
399         (etypecase zero
400           (single-float (frob 0.0f0))
401           (double-float (frob 0.0d0))
402           #!+long-float
403           (long-float (frob 0.0l0)))))
404     ;; The actual member-type contains the XSET (with no FP zeroes),
405     ;; and a list of unpaired zeroes.
406     (let ((member-type (unless (and (xset-empty-p xset) (not unpaired))
407                          (%make-member-type xset unpaired))))
408       (cond (union-types
409              (make-union-type t (if member-type
410                                     (cons member-type union-types)
411                                     union-types)))
412             (member-type
413              member-type)
414             (t
415              *empty-type*)))))
416
417 (defun member-type-size (type)
418   (+ (length (member-type-fp-zeroes type))
419      (xset-count (member-type-xset type))))
420
421 (defun member-type-member-p (x type)
422   (if (fp-zero-p x)
423       (and (member x (member-type-fp-zeroes type)) t)
424       (xset-member-p x (member-type-xset type))))
425
426 (defun mapcar-member-type-members (function type)
427   (declare (function function))
428   (collect ((results))
429     (map-xset (lambda (x)
430                 (results (funcall function x)))
431               (member-type-xset type))
432     (dolist (zero (member-type-fp-zeroes type))
433       (results (funcall function zero)))
434     (results)))
435
436 (defun mapc-member-type-members (function type)
437   (declare (function function))
438   (map-xset function (member-type-xset type))
439   (dolist (zero (member-type-fp-zeroes type))
440     (funcall function zero)))
441
442 (defun member-type-members (type)
443   (append (member-type-fp-zeroes type)
444           (xset-members (member-type-xset type))))
445
446 ;;; A COMPOUND-TYPE is a type defined out of a set of types, the
447 ;;; common parent of UNION-TYPE and INTERSECTION-TYPE.
448 (defstruct (compound-type (:include ctype
449                                     (might-contain-other-types-p t))
450                           (:constructor nil)
451                           (:copier nil))
452   (types nil :type list :read-only t))
453
454 ;;; A UNION-TYPE represents a use of the OR type specifier which we
455 ;;; couldn't canonicalize to something simpler. Canonical form:
456 ;;;   1. All possible pairwise simplifications (using the UNION2 type
457 ;;;      methods) have been performed. Thus e.g. there is never more
458 ;;;      than one MEMBER-TYPE component. FIXME: As of sbcl-0.6.11.13,
459 ;;;      this hadn't been fully implemented yet.
460 ;;;   2. There are never any UNION-TYPE components.
461 (defstruct (union-type (:include compound-type
462                                  (class-info (type-class-or-lose 'union)))
463                        (:constructor %make-union-type (enumerable types))
464                        (:copier nil)))
465 (define-cached-synonym make-union-type)
466
467 ;;; An INTERSECTION-TYPE represents a use of the AND type specifier
468 ;;; which we couldn't canonicalize to something simpler. Canonical form:
469 ;;;   1. All possible pairwise simplifications (using the INTERSECTION2
470 ;;;      type methods) have been performed. Thus e.g. there is never more
471 ;;;      than one MEMBER-TYPE component.
472 ;;;   2. There are never any INTERSECTION-TYPE components: we've
473 ;;;      flattened everything into a single INTERSECTION-TYPE object.
474 ;;;   3. There are never any UNION-TYPE components. Either we should
475 ;;;      use the distributive rule to rearrange things so that
476 ;;;      unions contain intersections and not vice versa, or we
477 ;;;      should just punt to using a HAIRY-TYPE.
478 (defstruct (intersection-type (:include compound-type
479                                         (class-info (type-class-or-lose
480                                                      'intersection)))
481                               (:constructor %make-intersection-type
482                                             (enumerable types))
483                               (:copier nil)))
484
485 ;;; Return TYPE converted to canonical form for a situation where the
486 ;;; "type" '* (which SBCL still represents as a type even though ANSI
487 ;;; CL defines it as a related but different kind of placeholder) is
488 ;;; equivalent to type T.
489 (defun type-*-to-t (type)
490   (if (type= type *wild-type*)
491       *universal-type*
492       type))
493
494 ;;; A CONS-TYPE is used to represent a CONS type.
495 (defstruct (cons-type (:include ctype (class-info (type-class-or-lose 'cons)))
496                       (:constructor
497                        %make-cons-type (car-type
498                                         cdr-type))
499                       (:copier nil))
500   ;; the CAR and CDR element types (to support ANSI (CONS FOO BAR) types)
501   ;;
502   ;; FIXME: Most or all other type structure slots could also be :READ-ONLY.
503   (car-type (missing-arg) :type ctype :read-only t)
504   (cdr-type (missing-arg) :type ctype :read-only t))
505 (defun make-cons-type (car-type cdr-type)
506   (aver (not (or (eq car-type *wild-type*)
507                  (eq cdr-type *wild-type*))))
508   (if (or (eq car-type *empty-type*)
509           (eq cdr-type *empty-type*))
510       *empty-type*
511       (%make-cons-type car-type cdr-type)))
512
513 (defun cons-type-length-info (type)
514   (declare (type cons-type type))
515   (do ((min 1 (1+ min))
516        (cdr (cons-type-cdr-type type) (cons-type-cdr-type cdr)))
517       ((not (cons-type-p cdr))
518        (cond
519          ((csubtypep cdr (specifier-type 'null))
520           (values min t))
521          ((csubtypep *universal-type* cdr)
522           (values min nil))
523          ((type/= (type-intersection (specifier-type 'cons) cdr) *empty-type*)
524           (values min nil))
525          ((type/= (type-intersection (specifier-type 'null) cdr) *empty-type*)
526           (values min t))
527          (t (values min :maybe))))
528     ()))
529
530 \f
531 ;;;; type utilities
532
533 ;;; Return the type structure corresponding to a type specifier. We
534 ;;; pick off structure types as a special case.
535 ;;;
536 ;;; Note: VALUES-SPECIFIER-TYPE-CACHE-CLEAR must be called whenever a
537 ;;; type is defined (or redefined).
538 (defun-cached (values-specifier-type
539                :hash-function (lambda (x)
540                                 (logand (sxhash x) #x3FF))
541                :hash-bits 10
542                :init-wrapper !cold-init-forms)
543               ((orig equal-but-no-car-recursion))
544   (let ((u (uncross orig)))
545     (or (info :type :builtin u)
546         (let ((spec (typexpand u)))
547           (cond
548            ((and (not (eq spec u))
549                  (info :type :builtin spec)))
550            ((eq (info :type :kind spec) :instance)
551             (find-classoid spec))
552            ((typep spec 'classoid)
553             (if (typep spec 'built-in-classoid)
554                 (or (built-in-classoid-translation spec) spec)
555                 spec))
556            (t
557             (when (and (atom spec)
558                        (member spec '(and or not member eql satisfies values)))
559               (error "The symbol ~S is not valid as a type specifier." spec))
560             (let* ((lspec (if (atom spec) (list spec) spec))
561                    (fun (info :type :translator (car lspec))))
562               (cond (fun
563                      (funcall fun lspec))
564                     ((or (and (consp spec) (symbolp (car spec))
565                               (not (info :type :builtin (car spec))))
566                          (and (symbolp spec) (not (info :type :builtin spec))))
567                      (when (and *type-system-initialized*
568                                 (not (eq (info :type :kind spec)
569                                          :forthcoming-defclass-type)))
570                        (signal 'parse-unknown-type :specifier spec))
571                      ;; (The RETURN-FROM here inhibits caching; this
572                      ;; does not only make sense from a compiler
573                      ;; diagnostics point of view but is also
574                      ;; indispensable for proper workingness of
575                      ;; VALID-TYPE-SPECIFIER-P.)
576                      (return-from values-specifier-type
577                        (make-unknown-type :specifier spec)))
578                     (t
579                      (error "bad thing to be a type specifier: ~S"
580                             spec))))))))))
581
582 ;;; This is like VALUES-SPECIFIER-TYPE, except that we guarantee to
583 ;;; never return a VALUES type.
584 (defun specifier-type (x)
585   (let ((res (values-specifier-type x)))
586     (when (or (values-type-p res)
587               ;; bootstrap magic :-(
588               (and (named-type-p res)
589                    (eq (named-type-name res) '*)))
590       (error "VALUES type illegal in this context:~%  ~S" x))
591     res))
592
593 (defun single-value-specifier-type (x)
594   (if (eq x '*)
595       *universal-type*
596       (specifier-type x)))
597
598 (defun typexpand-1 (type-specifier &optional env)
599   #!+sb-doc
600   "Takes and expands a type specifier once like MACROEXPAND-1.
601 Returns two values: the expansion, and a boolean that is true when
602 expansion happened."
603   (declare (type type-specifier type-specifier))
604   (declare (ignore env))
605   (multiple-value-bind (expander lspec)
606       (let ((spec type-specifier))
607         (cond ((and (symbolp spec) (info :type :builtin spec))
608                ;; We do not expand builtins even though it'd be
609                ;; possible to do so sometimes (e.g. STRING) for two
610                ;; reasons:
611                ;;
612                ;; a) From a user's point of view, CL types are opaque.
613                ;;
614                ;; b) so (EQUAL (TYPEXPAND 'STRING) (TYPEXPAND-ALL 'STRING))
615                (values nil nil))
616               ((symbolp spec)
617                (values (info :type :expander spec) (list spec)))
618               ((and (consp spec) (symbolp (car spec)))
619                (values (info :type :expander (car spec)) spec))
620               (t nil)))
621     (if expander
622         (values (funcall expander lspec) t)
623         (values type-specifier nil))))
624
625 (defun typexpand (type-specifier &optional env)
626   #!+sb-doc
627   "Takes and expands a type specifier repeatedly like MACROEXPAND.
628 Returns two values: the expansion, and a boolean that is true when
629 expansion happened."
630   (declare (type type-specifier type-specifier))
631   (multiple-value-bind (expansion flag)
632       (typexpand-1 type-specifier env)
633     (if flag
634         (values (typexpand expansion env) t)
635         (values expansion flag))))
636
637 (defun typexpand-all (type-specifier &optional env)
638   #!+sb-doc
639   "Takes and expands a type specifier recursively like MACROEXPAND-ALL."
640   (declare (type type-specifier type-specifier))
641   (declare (ignore env))
642   ;; I first thought this would not be a good implementation because
643   ;; it signals an error on e.g. (CONS 1 2) until I realized that
644   ;; walking and calling TYPEXPAND would also result in errors, and
645   ;; it actually makes sense.
646   ;;
647   ;; There's still a small problem in that
648   ;;   (TYPEXPAND-ALL '(CONS * FIXNUM)) => (CONS T FIXNUM)
649   ;; whereas walking+typexpand would result in (CONS * FIXNUM).
650   ;;
651   ;; Similiarly, (TYPEXPAND-ALL '(FUNCTION (&REST T) *)) => FUNCTION.
652   (type-specifier (values-specifier-type type-specifier)))
653
654 (defun defined-type-name-p (name &optional env)
655   #!+sb-doc
656   "Returns T if NAME is known to name a type specifier, otherwise NIL."
657   (declare (symbol name))
658   (declare (ignore env))
659   (and (info :type :kind name) t))
660
661 (defun valid-type-specifier-p (type-specifier &optional env)
662   #!+sb-doc
663   "Returns T if TYPE-SPECIFIER is a valid type specifier, otherwise NIL.
664
665 There may be different metrics on what constitutes a \"valid type
666 specifier\" depending on context. If this function does not suit your
667 exact need, you may be able to craft a particular solution using a
668 combination of DEFINED-TYPE-NAME-P and the TYPEXPAND functions.
669
670 The definition of \"valid type specifier\" employed by this function
671 is based on the following mnemonic:
672
673           \"Would TYPEP accept it as second argument?\"
674
675 Except that unlike TYPEP, this function fully supports compound
676 FUNCTION type specifiers, and the VALUES type specifier, too.
677
678 In particular, VALID-TYPE-SPECIFIER-P will return NIL if
679 TYPE-SPECIFIER is not a class, not a symbol that is known to name a
680 type specifier, and not a cons that represents a known compound type
681 specifier in a syntactically and recursively correct way.
682
683 Examples:
684
685   (valid-type-specifier-p '(cons * *))     => T
686   (valid-type-specifier-p '#:foo)          => NIL
687   (valid-type-specifier-p '(cons * #:foo)) => NIL
688   (valid-type-specifier-p '(cons 1 *)      => NIL
689
690 Experimental."
691   (declare (ignore env))
692   (handler-case (prog1 t (values-specifier-type type-specifier))
693     (parse-unknown-type () nil)
694     (error () nil)))
695
696 ;;; Note that the type NAME has been (re)defined, updating the
697 ;;; undefined warnings and VALUES-SPECIFIER-TYPE cache.
698 (defun %note-type-defined (name)
699   (declare (symbol name))
700   (note-name-defined name :type)
701   (values-specifier-type-cache-clear)
702   (values))
703
704 \f
705 (!defun-from-collected-cold-init-forms !early-type-cold-init)