src/share/classes/com/sun/tools/javac/code/Type.java

Fri, 30 Nov 2012 15:14:48 +0000

author
mcimadamore
date
Fri, 30 Nov 2012 15:14:48 +0000
changeset 1436
f6f1fd261f57
parent 1374
c002fdee76fd
child 1452
de1ec6fc93fe
permissions
-rw-r--r--

8002099: Add support for intersection types in cast expression
Summary: Add parser and type-checking support for intersection types in cast expressions
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.code;
    28 import java.util.Collections;
    29 import java.util.EnumMap;
    30 import java.util.EnumSet;
    31 import java.util.Map;
    32 import java.util.Set;
    34 import javax.lang.model.type.*;
    36 import com.sun.tools.javac.code.Symbol.*;
    37 import com.sun.tools.javac.util.*;
    38 import static com.sun.tools.javac.code.BoundKind.*;
    39 import static com.sun.tools.javac.code.Flags.*;
    40 import static com.sun.tools.javac.code.Kinds.*;
    41 import static com.sun.tools.javac.code.TypeTag.*;
    43 /** This class represents Java types. The class itself defines the behavior of
    44  *  the following types:
    45  *  <pre>
    46  *  base types (tags: BYTE, CHAR, SHORT, INT, LONG, FLOAT, DOUBLE, BOOLEAN),
    47  *  type `void' (tag: VOID),
    48  *  the bottom type (tag: BOT),
    49  *  the missing type (tag: NONE).
    50  *  </pre>
    51  *  <p>The behavior of the following types is defined in subclasses, which are
    52  *  all static inner classes of this class:
    53  *  <pre>
    54  *  class types (tag: CLASS, class: ClassType),
    55  *  array types (tag: ARRAY, class: ArrayType),
    56  *  method types (tag: METHOD, class: MethodType),
    57  *  package types (tag: PACKAGE, class: PackageType),
    58  *  type variables (tag: TYPEVAR, class: TypeVar),
    59  *  type arguments (tag: WILDCARD, class: WildcardType),
    60  *  generic method types (tag: FORALL, class: ForAll),
    61  *  the error type (tag: ERROR, class: ErrorType).
    62  *  </pre>
    63  *
    64  *  <p><b>This is NOT part of any supported API.
    65  *  If you write code that depends on this, you do so at your own risk.
    66  *  This code and its internal interfaces are subject to change or
    67  *  deletion without notice.</b>
    68  *
    69  *  @see TypeTag
    70  */
    71 public class Type implements PrimitiveType {
    73     /** Constant type: no type at all. */
    74     public static final JCNoType noType = new JCNoType(NONE);
    76     /** Constant type: special type to be used during recovery of deferred expressions. */
    77     public static final JCNoType recoveryType = new JCNoType(NONE);
    79     /** If this switch is turned on, the names of type variables
    80      *  and anonymous classes are printed with hashcodes appended.
    81      */
    82     public static boolean moreInfo = false;
    84     /** The tag of this type.
    85      *
    86      *  @see TypeTag
    87      */
    88     protected TypeTag tag;
    90     /** The defining class / interface / package / type variable
    91      */
    92     public TypeSymbol tsym;
    94     /**
    95      * Checks if the current type tag is equal to the given tag.
    96      * @return true if tag is equal to the current type tag.
    97      */
    98     public boolean hasTag(TypeTag tag) {
    99         return this.tag == tag;
   100     }
   102     /**
   103      * Returns the current type tag.
   104      * @return the value of the current type tag.
   105      */
   106     public TypeTag getTag() {
   107         return tag;
   108     }
   110     public boolean isNumeric() {
   111         switch (tag) {
   112             case BYTE: case CHAR:
   113             case SHORT:
   114             case INT: case LONG:
   115             case FLOAT: case DOUBLE:
   116                 return true;
   117             default:
   118                 return false;
   119         }
   120     }
   122     public boolean isPrimitive() {
   123         return (isNumeric() || tag == BOOLEAN);
   124     }
   126     public boolean isPrimitiveOrVoid() {
   127         return (isPrimitive() || tag == VOID);
   128     }
   130     public boolean isReference() {
   131         switch (tag) {
   132         case CLASS:
   133         case ARRAY:
   134         case TYPEVAR:
   135         case WILDCARD:
   136         case ERROR:
   137             return true;
   138         default:
   139             return false;
   140         }
   141     }
   143     public boolean isNullOrReference() {
   144         return (tag == BOT || isReference());
   145     }
   147     public boolean isPartial() {
   148         switch(tag) {
   149             case ERROR: case UNKNOWN: case UNDETVAR:
   150                 return true;
   151             default:
   152                 return false;
   153         }
   154     }
   156     /**
   157      * The constant value of this type, null if this type does not
   158      * have a constant value attribute. Only primitive types and
   159      * strings (ClassType) can have a constant value attribute.
   160      * @return the constant value attribute of this type
   161      */
   162     public Object constValue() {
   163         return null;
   164     }
   166     /**
   167      * Get the representation of this type used for modelling purposes.
   168      * By default, this is itself. For ErrorType, a different value
   169      * may be provided,
   170      */
   171     public Type getModelType() {
   172         return this;
   173     }
   175     public static List<Type> getModelTypes(List<Type> ts) {
   176         ListBuffer<Type> lb = new ListBuffer<Type>();
   177         for (Type t: ts)
   178             lb.append(t.getModelType());
   179         return lb.toList();
   180     }
   182     public <R,S> R accept(Type.Visitor<R,S> v, S s) { return v.visitType(this, s); }
   184     /** Define a type given its tag and type symbol
   185      */
   186     public Type(TypeTag tag, TypeSymbol tsym) {
   187         this.tag = tag;
   188         this.tsym = tsym;
   189     }
   191     /** An abstract class for mappings from types to types
   192      */
   193     public static abstract class Mapping {
   194         private String name;
   195         public Mapping(String name) {
   196             this.name = name;
   197         }
   198         public abstract Type apply(Type t);
   199         public String toString() {
   200             return name;
   201         }
   202     }
   204     /** map a type function over all immediate descendants of this type
   205      */
   206     public Type map(Mapping f) {
   207         return this;
   208     }
   210     /** map a type function over a list of types
   211      */
   212     public static List<Type> map(List<Type> ts, Mapping f) {
   213         if (ts.nonEmpty()) {
   214             List<Type> tail1 = map(ts.tail, f);
   215             Type t = f.apply(ts.head);
   216             if (tail1 != ts.tail || t != ts.head)
   217                 return tail1.prepend(t);
   218         }
   219         return ts;
   220     }
   222     /** Define a constant type, of the same kind as this type
   223      *  and with given constant value
   224      */
   225     public Type constType(Object constValue) {
   226         final Object value = constValue;
   227         Assert.check(isPrimitive());
   228         return new Type(tag, tsym) {
   229                 @Override
   230                 public Object constValue() {
   231                     return value;
   232                 }
   233                 @Override
   234                 public Type baseType() {
   235                     return tsym.type;
   236                 }
   237             };
   238     }
   240     /**
   241      * If this is a constant type, return its underlying type.
   242      * Otherwise, return the type itself.
   243      */
   244     public Type baseType() {
   245         return this;
   246     }
   248     /** Return the base types of a list of types.
   249      */
   250     public static List<Type> baseTypes(List<Type> ts) {
   251         if (ts.nonEmpty()) {
   252             Type t = ts.head.baseType();
   253             List<Type> baseTypes = baseTypes(ts.tail);
   254             if (t != ts.head || baseTypes != ts.tail)
   255                 return baseTypes.prepend(t);
   256         }
   257         return ts;
   258     }
   260     /** The Java source which this type represents.
   261      */
   262     public String toString() {
   263         String s = (tsym == null || tsym.name == null)
   264             ? "<none>"
   265             : tsym.name.toString();
   266         if (moreInfo && tag == TYPEVAR) s = s + hashCode();
   267         return s;
   268     }
   270     /**
   271      * The Java source which this type list represents.  A List is
   272      * represented as a comma-spearated listing of the elements in
   273      * that list.
   274      */
   275     public static String toString(List<Type> ts) {
   276         if (ts.isEmpty()) {
   277             return "";
   278         } else {
   279             StringBuilder buf = new StringBuilder();
   280             buf.append(ts.head.toString());
   281             for (List<Type> l = ts.tail; l.nonEmpty(); l = l.tail)
   282                 buf.append(",").append(l.head.toString());
   283             return buf.toString();
   284         }
   285     }
   287     /**
   288      * The constant value of this type, converted to String
   289      */
   290     public String stringValue() {
   291         Object cv = Assert.checkNonNull(constValue());
   292         if (tag == BOOLEAN)
   293             return ((Integer) cv).intValue() == 0 ? "false" : "true";
   294         else if (tag == CHAR)
   295             return String.valueOf((char) ((Integer) cv).intValue());
   296         else
   297             return cv.toString();
   298     }
   300     /**
   301      * This method is analogous to isSameType, but weaker, since we
   302      * never complete classes. Where isSameType would complete a
   303      * class, equals assumes that the two types are different.
   304      */
   305     public boolean equals(Object t) {
   306         return super.equals(t);
   307     }
   309     public int hashCode() {
   310         return super.hashCode();
   311     }
   313     /** Is this a constant type whose value is false?
   314      */
   315     public boolean isFalse() {
   316         return
   317             tag == BOOLEAN &&
   318             constValue() != null &&
   319             ((Integer)constValue()).intValue() == 0;
   320     }
   322     /** Is this a constant type whose value is true?
   323      */
   324     public boolean isTrue() {
   325         return
   326             tag == BOOLEAN &&
   327             constValue() != null &&
   328             ((Integer)constValue()).intValue() != 0;
   329     }
   331     public String argtypes(boolean varargs) {
   332         List<Type> args = getParameterTypes();
   333         if (!varargs) return args.toString();
   334         StringBuilder buf = new StringBuilder();
   335         while (args.tail.nonEmpty()) {
   336             buf.append(args.head);
   337             args = args.tail;
   338             buf.append(',');
   339         }
   340         if (args.head.tag == ARRAY) {
   341             buf.append(((ArrayType)args.head).elemtype);
   342             buf.append("...");
   343         } else {
   344             buf.append(args.head);
   345         }
   346         return buf.toString();
   347     }
   349     /** Access methods.
   350      */
   351     public List<Type>        getTypeArguments()  { return List.nil(); }
   352     public Type              getEnclosingType() { return null; }
   353     public List<Type>        getParameterTypes() { return List.nil(); }
   354     public Type              getReturnType()     { return null; }
   355     public List<Type>        getThrownTypes()    { return List.nil(); }
   356     public Type              getUpperBound()     { return null; }
   357     public Type              getLowerBound()     { return null; }
   359     /** Navigation methods, these will work for classes, type variables,
   360      *  foralls, but will return null for arrays and methods.
   361      */
   363    /** Return all parameters of this type and all its outer types in order
   364     *  outer (first) to inner (last).
   365     */
   366     public List<Type> allparams() { return List.nil(); }
   368     /** Does this type contain "error" elements?
   369      */
   370     public boolean isErroneous() {
   371         return false;
   372     }
   374     public static boolean isErroneous(List<Type> ts) {
   375         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   376             if (l.head.isErroneous()) return true;
   377         return false;
   378     }
   380     /** Is this type parameterized?
   381      *  A class type is parameterized if it has some parameters.
   382      *  An array type is parameterized if its element type is parameterized.
   383      *  All other types are not parameterized.
   384      */
   385     public boolean isParameterized() {
   386         return false;
   387     }
   389     /** Is this type a raw type?
   390      *  A class type is a raw type if it misses some of its parameters.
   391      *  An array type is a raw type if its element type is raw.
   392      *  All other types are not raw.
   393      *  Type validation will ensure that the only raw types
   394      *  in a program are types that miss all their type variables.
   395      */
   396     public boolean isRaw() {
   397         return false;
   398     }
   400     public boolean isCompound() {
   401         return tsym.completer == null
   402             // Compound types can't have a completer.  Calling
   403             // flags() will complete the symbol causing the
   404             // compiler to load classes unnecessarily.  This led
   405             // to regression 6180021.
   406             && (tsym.flags() & COMPOUND) != 0;
   407     }
   409     public boolean isInterface() {
   410         return (tsym.flags() & INTERFACE) != 0;
   411     }
   413     public boolean isFinal() {
   414         return (tsym.flags() & FINAL) != 0;
   415     }
   417     /**
   418      * Does this type contain occurrences of type t?
   419      */
   420     public boolean contains(Type t) {
   421         return t == this;
   422     }
   424     public static boolean contains(List<Type> ts, Type t) {
   425         for (List<Type> l = ts;
   426              l.tail != null /*inlined: l.nonEmpty()*/;
   427              l = l.tail)
   428             if (l.head.contains(t)) return true;
   429         return false;
   430     }
   432     /** Does this type contain an occurrence of some type in 'ts'?
   433      */
   434     public boolean containsAny(List<Type> ts) {
   435         for (Type t : ts)
   436             if (this.contains(t)) return true;
   437         return false;
   438     }
   440     public static boolean containsAny(List<Type> ts1, List<Type> ts2) {
   441         for (Type t : ts1)
   442             if (t.containsAny(ts2)) return true;
   443         return false;
   444     }
   446     public static List<Type> filter(List<Type> ts, Filter<Type> tf) {
   447         ListBuffer<Type> buf = ListBuffer.lb();
   448         for (Type t : ts) {
   449             if (tf.accepts(t)) {
   450                 buf.append(t);
   451             }
   452         }
   453         return buf.toList();
   454     }
   456     public boolean isSuperBound() { return false; }
   457     public boolean isExtendsBound() { return false; }
   458     public boolean isUnbound() { return false; }
   459     public Type withTypeVar(Type t) { return this; }
   461     /** The underlying method type of this type.
   462      */
   463     public MethodType asMethodType() { throw new AssertionError(); }
   465     /** Complete loading all classes in this type.
   466      */
   467     public void complete() {}
   469     public TypeSymbol asElement() {
   470         return tsym;
   471     }
   473     public TypeKind getKind() {
   474         switch (tag) {
   475         case BYTE:      return TypeKind.BYTE;
   476         case CHAR:      return TypeKind.CHAR;
   477         case SHORT:     return TypeKind.SHORT;
   478         case INT:       return TypeKind.INT;
   479         case LONG:      return TypeKind.LONG;
   480         case FLOAT:     return TypeKind.FLOAT;
   481         case DOUBLE:    return TypeKind.DOUBLE;
   482         case BOOLEAN:   return TypeKind.BOOLEAN;
   483         case VOID:      return TypeKind.VOID;
   484         case BOT:       return TypeKind.NULL;
   485         case NONE:      return TypeKind.NONE;
   486         default:        return TypeKind.OTHER;
   487         }
   488     }
   490     public <R, P> R accept(TypeVisitor<R, P> v, P p) {
   491         if (isPrimitive())
   492             return v.visitPrimitive(this, p);
   493         else
   494             throw new AssertionError();
   495     }
   497     public static class WildcardType extends Type
   498             implements javax.lang.model.type.WildcardType {
   500         public Type type;
   501         public BoundKind kind;
   502         public TypeVar bound;
   504         @Override
   505         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
   506             return v.visitWildcardType(this, s);
   507         }
   509         public WildcardType(Type type, BoundKind kind, TypeSymbol tsym) {
   510             super(WILDCARD, tsym);
   511             this.type = Assert.checkNonNull(type);
   512             this.kind = kind;
   513         }
   514         public WildcardType(WildcardType t, TypeVar bound) {
   515             this(t.type, t.kind, t.tsym, bound);
   516         }
   518         public WildcardType(Type type, BoundKind kind, TypeSymbol tsym, TypeVar bound) {
   519             this(type, kind, tsym);
   520             this.bound = bound;
   521         }
   523         public boolean contains(Type t) {
   524             return kind != UNBOUND && type.contains(t);
   525         }
   527         public boolean isSuperBound() {
   528             return kind == SUPER ||
   529                 kind == UNBOUND;
   530         }
   531         public boolean isExtendsBound() {
   532             return kind == EXTENDS ||
   533                 kind == UNBOUND;
   534         }
   535         public boolean isUnbound() {
   536             return kind == UNBOUND;
   537         }
   539         public Type withTypeVar(Type t) {
   540             //-System.err.println(this+".withTypeVar("+t+");");//DEBUG
   541             if (bound == t)
   542                 return this;
   543             bound = (TypeVar)t;
   544             return this;
   545         }
   547         boolean isPrintingBound = false;
   548         public String toString() {
   549             StringBuilder s = new StringBuilder();
   550             s.append(kind.toString());
   551             if (kind != UNBOUND)
   552                 s.append(type);
   553             if (moreInfo && bound != null && !isPrintingBound)
   554                 try {
   555                     isPrintingBound = true;
   556                     s.append("{:").append(bound.bound).append(":}");
   557                 } finally {
   558                     isPrintingBound = false;
   559                 }
   560             return s.toString();
   561         }
   563         public Type map(Mapping f) {
   564             //- System.err.println("   (" + this + ").map(" + f + ")");//DEBUG
   565             Type t = type;
   566             if (t != null)
   567                 t = f.apply(t);
   568             if (t == type)
   569                 return this;
   570             else
   571                 return new WildcardType(t, kind, tsym, bound);
   572         }
   574         public Type getExtendsBound() {
   575             if (kind == EXTENDS)
   576                 return type;
   577             else
   578                 return null;
   579         }
   581         public Type getSuperBound() {
   582             if (kind == SUPER)
   583                 return type;
   584             else
   585                 return null;
   586         }
   588         public TypeKind getKind() {
   589             return TypeKind.WILDCARD;
   590         }
   592         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
   593             return v.visitWildcard(this, p);
   594         }
   595     }
   597     public static class ClassType extends Type implements DeclaredType {
   599         /** The enclosing type of this type. If this is the type of an inner
   600          *  class, outer_field refers to the type of its enclosing
   601          *  instance class, in all other cases it referes to noType.
   602          */
   603         private Type outer_field;
   605         /** The type parameters of this type (to be set once class is loaded).
   606          */
   607         public List<Type> typarams_field;
   609         /** A cache variable for the type parameters of this type,
   610          *  appended to all parameters of its enclosing class.
   611          *  @see #allparams
   612          */
   613         public List<Type> allparams_field;
   615         /** The supertype of this class (to be set once class is loaded).
   616          */
   617         public Type supertype_field;
   619         /** The interfaces of this class (to be set once class is loaded).
   620          */
   621         public List<Type> interfaces_field;
   623         /** All the interfaces of this class, including missing ones.
   624          */
   625         public List<Type> all_interfaces_field;
   627         public ClassType(Type outer, List<Type> typarams, TypeSymbol tsym) {
   628             super(CLASS, tsym);
   629             this.outer_field = outer;
   630             this.typarams_field = typarams;
   631             this.allparams_field = null;
   632             this.supertype_field = null;
   633             this.interfaces_field = null;
   634             /*
   635             // this can happen during error recovery
   636             assert
   637                 outer.isParameterized() ?
   638                 typarams.length() == tsym.type.typarams().length() :
   639                 outer.isRaw() ?
   640                 typarams.length() == 0 :
   641                 true;
   642             */
   643         }
   645         @Override
   646         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
   647             return v.visitClassType(this, s);
   648         }
   650         public Type constType(Object constValue) {
   651             final Object value = constValue;
   652             return new ClassType(getEnclosingType(), typarams_field, tsym) {
   653                     @Override
   654                     public Object constValue() {
   655                         return value;
   656                     }
   657                     @Override
   658                     public Type baseType() {
   659                         return tsym.type;
   660                     }
   661                 };
   662         }
   664         /** The Java source which this type represents.
   665          */
   666         public String toString() {
   667             StringBuilder buf = new StringBuilder();
   668             if (getEnclosingType().tag == CLASS && tsym.owner.kind == TYP) {
   669                 buf.append(getEnclosingType().toString());
   670                 buf.append(".");
   671                 buf.append(className(tsym, false));
   672             } else {
   673                 buf.append(className(tsym, true));
   674             }
   675             if (getTypeArguments().nonEmpty()) {
   676                 buf.append('<');
   677                 buf.append(getTypeArguments().toString());
   678                 buf.append(">");
   679             }
   680             return buf.toString();
   681         }
   682 //where
   683             private String className(Symbol sym, boolean longform) {
   684                 if (sym.name.isEmpty() && (sym.flags() & COMPOUND) != 0) {
   685                     StringBuilder s = new StringBuilder(supertype_field.toString());
   686                     for (List<Type> is=interfaces_field; is.nonEmpty(); is = is.tail) {
   687                         s.append("&");
   688                         s.append(is.head.toString());
   689                     }
   690                     return s.toString();
   691                 } else if (sym.name.isEmpty()) {
   692                     String s;
   693                     ClassType norm = (ClassType) tsym.type;
   694                     if (norm == null) {
   695                         s = Log.getLocalizedString("anonymous.class", (Object)null);
   696                     } else if (norm.interfaces_field != null && norm.interfaces_field.nonEmpty()) {
   697                         s = Log.getLocalizedString("anonymous.class",
   698                                                    norm.interfaces_field.head);
   699                     } else {
   700                         s = Log.getLocalizedString("anonymous.class",
   701                                                    norm.supertype_field);
   702                     }
   703                     if (moreInfo)
   704                         s += String.valueOf(sym.hashCode());
   705                     return s;
   706                 } else if (longform) {
   707                     return sym.getQualifiedName().toString();
   708                 } else {
   709                     return sym.name.toString();
   710                 }
   711             }
   713         public List<Type> getTypeArguments() {
   714             if (typarams_field == null) {
   715                 complete();
   716                 if (typarams_field == null)
   717                     typarams_field = List.nil();
   718             }
   719             return typarams_field;
   720         }
   722         public boolean hasErasedSupertypes() {
   723             return isRaw();
   724         }
   726         public Type getEnclosingType() {
   727             return outer_field;
   728         }
   730         public void setEnclosingType(Type outer) {
   731             outer_field = outer;
   732         }
   734         public List<Type> allparams() {
   735             if (allparams_field == null) {
   736                 allparams_field = getTypeArguments().prependList(getEnclosingType().allparams());
   737             }
   738             return allparams_field;
   739         }
   741         public boolean isErroneous() {
   742             return
   743                 getEnclosingType().isErroneous() ||
   744                 isErroneous(getTypeArguments()) ||
   745                 this != tsym.type && tsym.type.isErroneous();
   746         }
   748         public boolean isParameterized() {
   749             return allparams().tail != null;
   750             // optimization, was: allparams().nonEmpty();
   751         }
   753         /** A cache for the rank. */
   754         int rank_field = -1;
   756         /** A class type is raw if it misses some
   757          *  of its type parameter sections.
   758          *  After validation, this is equivalent to:
   759          *  {@code allparams.isEmpty() && tsym.type.allparams.nonEmpty(); }
   760          */
   761         public boolean isRaw() {
   762             return
   763                 this != tsym.type && // necessary, but not sufficient condition
   764                 tsym.type.allparams().nonEmpty() &&
   765                 allparams().isEmpty();
   766         }
   768         public Type map(Mapping f) {
   769             Type outer = getEnclosingType();
   770             Type outer1 = f.apply(outer);
   771             List<Type> typarams = getTypeArguments();
   772             List<Type> typarams1 = map(typarams, f);
   773             if (outer1 == outer && typarams1 == typarams) return this;
   774             else return new ClassType(outer1, typarams1, tsym);
   775         }
   777         public boolean contains(Type elem) {
   778             return
   779                 elem == this
   780                 || (isParameterized()
   781                     && (getEnclosingType().contains(elem) || contains(getTypeArguments(), elem)))
   782                 || (isCompound()
   783                     && (supertype_field.contains(elem) || contains(interfaces_field, elem)));
   784         }
   786         public void complete() {
   787             if (tsym.completer != null) tsym.complete();
   788         }
   790         public TypeKind getKind() {
   791             return TypeKind.DECLARED;
   792         }
   794         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
   795             return v.visitDeclared(this, p);
   796         }
   797     }
   799     public static class ErasedClassType extends ClassType {
   800         public ErasedClassType(Type outer, TypeSymbol tsym) {
   801             super(outer, List.<Type>nil(), tsym);
   802         }
   804         @Override
   805         public boolean hasErasedSupertypes() {
   806             return true;
   807         }
   808     }
   810     // a clone of a ClassType that knows about the alternatives of a union type.
   811     public static class UnionClassType extends ClassType implements UnionType {
   812         final List<? extends Type> alternatives_field;
   814         public UnionClassType(ClassType ct, List<? extends Type> alternatives) {
   815             super(ct.outer_field, ct.typarams_field, ct.tsym);
   816             allparams_field = ct.allparams_field;
   817             supertype_field = ct.supertype_field;
   818             interfaces_field = ct.interfaces_field;
   819             all_interfaces_field = ct.interfaces_field;
   820             alternatives_field = alternatives;
   821         }
   823         public Type getLub() {
   824             return tsym.type;
   825         }
   827         public java.util.List<? extends TypeMirror> getAlternatives() {
   828             return Collections.unmodifiableList(alternatives_field);
   829         }
   831         @Override
   832         public TypeKind getKind() {
   833             return TypeKind.UNION;
   834         }
   836         @Override
   837         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
   838             return v.visitUnion(this, p);
   839         }
   840     }
   842     // a clone of a ClassType that knows about the bounds of an intersection type.
   843     public static class IntersectionClassType extends ClassType implements IntersectionType {
   845         public boolean allInterfaces;
   847         public enum IntersectionKind {
   848             EXPLICIT,
   849             IMPLICT;
   850         }
   852         public IntersectionKind intersectionKind;
   854         public IntersectionClassType(List<Type> bounds, ClassSymbol csym, boolean allInterfaces) {
   855             super(Type.noType, List.<Type>nil(), csym);
   856             this.allInterfaces = allInterfaces;
   857             Assert.check((csym.flags() & COMPOUND) != 0);
   858             supertype_field = bounds.head;
   859             interfaces_field = bounds.tail;
   860             Assert.check(supertype_field.tsym.completer != null ||
   861                     !supertype_field.isInterface(), supertype_field);
   862         }
   864         public java.util.List<? extends TypeMirror> getBounds() {
   865             return Collections.unmodifiableList(getComponents());
   866         }
   868         public List<Type> getComponents() {
   869             return interfaces_field.prepend(supertype_field);
   870         }
   872         @Override
   873         public TypeKind getKind() {
   874             return TypeKind.INTERSECTION;
   875         }
   877         @Override
   878         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
   879             return intersectionKind == IntersectionKind.EXPLICIT ?
   880                 v.visitIntersection(this, p) :
   881                 v.visitDeclared(this, p);
   882         }
   883     }
   885     public static class ArrayType extends Type
   886             implements javax.lang.model.type.ArrayType {
   888         public Type elemtype;
   890         public ArrayType(Type elemtype, TypeSymbol arrayClass) {
   891             super(ARRAY, arrayClass);
   892             this.elemtype = elemtype;
   893         }
   895         @Override
   896         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
   897             return v.visitArrayType(this, s);
   898         }
   900         public String toString() {
   901             return elemtype + "[]";
   902         }
   904         public boolean equals(Object obj) {
   905             return
   906                 this == obj ||
   907                 (obj instanceof ArrayType &&
   908                  this.elemtype.equals(((ArrayType)obj).elemtype));
   909         }
   911         public int hashCode() {
   912             return (ARRAY.ordinal() << 5) + elemtype.hashCode();
   913         }
   915         public boolean isVarargs() {
   916             return false;
   917         }
   919         public List<Type> allparams() { return elemtype.allparams(); }
   921         public boolean isErroneous() {
   922             return elemtype.isErroneous();
   923         }
   925         public boolean isParameterized() {
   926             return elemtype.isParameterized();
   927         }
   929         public boolean isRaw() {
   930             return elemtype.isRaw();
   931         }
   933         public ArrayType makeVarargs() {
   934             return new ArrayType(elemtype, tsym) {
   935                 @Override
   936                 public boolean isVarargs() {
   937                     return true;
   938                 }
   939             };
   940         }
   942         public Type map(Mapping f) {
   943             Type elemtype1 = f.apply(elemtype);
   944             if (elemtype1 == elemtype) return this;
   945             else return new ArrayType(elemtype1, tsym);
   946         }
   948         public boolean contains(Type elem) {
   949             return elem == this || elemtype.contains(elem);
   950         }
   952         public void complete() {
   953             elemtype.complete();
   954         }
   956         public Type getComponentType() {
   957             return elemtype;
   958         }
   960         public TypeKind getKind() {
   961             return TypeKind.ARRAY;
   962         }
   964         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
   965             return v.visitArray(this, p);
   966         }
   967     }
   969     public static class MethodType extends Type implements ExecutableType {
   971         public List<Type> argtypes;
   972         public Type restype;
   973         public List<Type> thrown;
   975         public MethodType(List<Type> argtypes,
   976                           Type restype,
   977                           List<Type> thrown,
   978                           TypeSymbol methodClass) {
   979             super(METHOD, methodClass);
   980             this.argtypes = argtypes;
   981             this.restype = restype;
   982             this.thrown = thrown;
   983         }
   985         @Override
   986         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
   987             return v.visitMethodType(this, s);
   988         }
   990         /** The Java source which this type represents.
   991          *
   992          *  XXX 06/09/99 iris This isn't correct Java syntax, but it probably
   993          *  should be.
   994          */
   995         public String toString() {
   996             return "(" + argtypes + ")" + restype;
   997         }
   999         public boolean equals(Object obj) {
  1000             if (this == obj)
  1001                 return true;
  1002             if (!(obj instanceof MethodType))
  1003                 return false;
  1004             MethodType m = (MethodType)obj;
  1005             List<Type> args1 = argtypes;
  1006             List<Type> args2 = m.argtypes;
  1007             while (!args1.isEmpty() && !args2.isEmpty()) {
  1008                 if (!args1.head.equals(args2.head))
  1009                     return false;
  1010                 args1 = args1.tail;
  1011                 args2 = args2.tail;
  1013             if (!args1.isEmpty() || !args2.isEmpty())
  1014                 return false;
  1015             return restype.equals(m.restype);
  1018         public int hashCode() {
  1019             int h = METHOD.ordinal();
  1020             for (List<Type> thisargs = this.argtypes;
  1021                  thisargs.tail != null; /*inlined: thisargs.nonEmpty()*/
  1022                  thisargs = thisargs.tail)
  1023                 h = (h << 5) + thisargs.head.hashCode();
  1024             return (h << 5) + this.restype.hashCode();
  1027         public List<Type>        getParameterTypes() { return argtypes; }
  1028         public Type              getReturnType()     { return restype; }
  1029         public List<Type>        getThrownTypes()    { return thrown; }
  1031         public boolean isErroneous() {
  1032             return
  1033                 isErroneous(argtypes) ||
  1034                 restype != null && restype.isErroneous();
  1037         public Type map(Mapping f) {
  1038             List<Type> argtypes1 = map(argtypes, f);
  1039             Type restype1 = f.apply(restype);
  1040             List<Type> thrown1 = map(thrown, f);
  1041             if (argtypes1 == argtypes &&
  1042                 restype1 == restype &&
  1043                 thrown1 == thrown) return this;
  1044             else return new MethodType(argtypes1, restype1, thrown1, tsym);
  1047         public boolean contains(Type elem) {
  1048             return elem == this || contains(argtypes, elem) || restype.contains(elem);
  1051         public MethodType asMethodType() { return this; }
  1053         public void complete() {
  1054             for (List<Type> l = argtypes; l.nonEmpty(); l = l.tail)
  1055                 l.head.complete();
  1056             restype.complete();
  1057             for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1058                 l.head.complete();
  1061         public List<TypeVar> getTypeVariables() {
  1062             return List.nil();
  1065         public TypeSymbol asElement() {
  1066             return null;
  1069         public TypeKind getKind() {
  1070             return TypeKind.EXECUTABLE;
  1073         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
  1074             return v.visitExecutable(this, p);
  1078     public static class PackageType extends Type implements NoType {
  1080         PackageType(TypeSymbol tsym) {
  1081             super(PACKAGE, tsym);
  1084         @Override
  1085         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
  1086             return v.visitPackageType(this, s);
  1089         public String toString() {
  1090             return tsym.getQualifiedName().toString();
  1093         public TypeKind getKind() {
  1094             return TypeKind.PACKAGE;
  1097         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
  1098             return v.visitNoType(this, p);
  1102     public static class TypeVar extends Type implements TypeVariable {
  1104         /** The upper bound of this type variable; set from outside.
  1105          *  Must be nonempty once it is set.
  1106          *  For a bound, `bound' is the bound type itself.
  1107          *  Multiple bounds are expressed as a single class type which has the
  1108          *  individual bounds as superclass, respectively interfaces.
  1109          *  The class type then has as `tsym' a compiler generated class `c',
  1110          *  which has a flag COMPOUND and whose owner is the type variable
  1111          *  itself. Furthermore, the erasure_field of the class
  1112          *  points to the first class or interface bound.
  1113          */
  1114         public Type bound = null;
  1116         /** The lower bound of this type variable.
  1117          *  TypeVars don't normally have a lower bound, so it is normally set
  1118          *  to syms.botType.
  1119          *  Subtypes, such as CapturedType, may provide a different value.
  1120          */
  1121         public Type lower;
  1123         public TypeVar(Name name, Symbol owner, Type lower) {
  1124             super(TYPEVAR, null);
  1125             tsym = new TypeSymbol(0, name, this, owner);
  1126             this.lower = lower;
  1129         public TypeVar(TypeSymbol tsym, Type bound, Type lower) {
  1130             super(TYPEVAR, tsym);
  1131             this.bound = bound;
  1132             this.lower = lower;
  1135         @Override
  1136         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
  1137             return v.visitTypeVar(this, s);
  1140         @Override
  1141         public Type getUpperBound() { return bound; }
  1143         int rank_field = -1;
  1145         @Override
  1146         public Type getLowerBound() {
  1147             return lower;
  1150         public TypeKind getKind() {
  1151             return TypeKind.TYPEVAR;
  1154         public boolean isCaptured() {
  1155             return false;
  1158         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
  1159             return v.visitTypeVariable(this, p);
  1163     /** A captured type variable comes from wildcards which can have
  1164      *  both upper and lower bound.  CapturedType extends TypeVar with
  1165      *  a lower bound.
  1166      */
  1167     public static class CapturedType extends TypeVar {
  1169         public WildcardType wildcard;
  1171         public CapturedType(Name name,
  1172                             Symbol owner,
  1173                             Type upper,
  1174                             Type lower,
  1175                             WildcardType wildcard) {
  1176             super(name, owner, lower);
  1177             this.lower = Assert.checkNonNull(lower);
  1178             this.bound = upper;
  1179             this.wildcard = wildcard;
  1182         @Override
  1183         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
  1184             return v.visitCapturedType(this, s);
  1187         @Override
  1188         public boolean isCaptured() {
  1189             return true;
  1192         @Override
  1193         public String toString() {
  1194             return "capture#"
  1195                 + (hashCode() & 0xFFFFFFFFL) % Printer.PRIME
  1196                 + " of "
  1197                 + wildcard;
  1201     public static abstract class DelegatedType extends Type {
  1202         public Type qtype;
  1203         public DelegatedType(TypeTag tag, Type qtype) {
  1204             super(tag, qtype.tsym);
  1205             this.qtype = qtype;
  1207         public String toString() { return qtype.toString(); }
  1208         public List<Type> getTypeArguments() { return qtype.getTypeArguments(); }
  1209         public Type getEnclosingType() { return qtype.getEnclosingType(); }
  1210         public List<Type> getParameterTypes() { return qtype.getParameterTypes(); }
  1211         public Type getReturnType() { return qtype.getReturnType(); }
  1212         public List<Type> getThrownTypes() { return qtype.getThrownTypes(); }
  1213         public List<Type> allparams() { return qtype.allparams(); }
  1214         public Type getUpperBound() { return qtype.getUpperBound(); }
  1215         public boolean isErroneous() { return qtype.isErroneous(); }
  1218     /**
  1219      * The type of a generic method type. It consists of a method type and
  1220      * a list of method type-parameters that are used within the method
  1221      * type.
  1222      */
  1223     public static class ForAll extends DelegatedType implements ExecutableType {
  1224         public List<Type> tvars;
  1226         public ForAll(List<Type> tvars, Type qtype) {
  1227             super(FORALL, (MethodType)qtype);
  1228             this.tvars = tvars;
  1231         @Override
  1232         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
  1233             return v.visitForAll(this, s);
  1236         public String toString() {
  1237             return "<" + tvars + ">" + qtype;
  1240         public List<Type> getTypeArguments()   { return tvars; }
  1242         public boolean isErroneous()  {
  1243             return qtype.isErroneous();
  1246         public Type map(Mapping f) {
  1247             return f.apply(qtype);
  1250         public boolean contains(Type elem) {
  1251             return qtype.contains(elem);
  1254         public MethodType asMethodType() {
  1255             return (MethodType)qtype;
  1258         public void complete() {
  1259             for (List<Type> l = tvars; l.nonEmpty(); l = l.tail) {
  1260                 ((TypeVar)l.head).bound.complete();
  1262             qtype.complete();
  1265         public List<TypeVar> getTypeVariables() {
  1266             return List.convert(TypeVar.class, getTypeArguments());
  1269         public TypeKind getKind() {
  1270             return TypeKind.EXECUTABLE;
  1273         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
  1274             return v.visitExecutable(this, p);
  1278     /** A class for inference variables, for use during method/diamond type
  1279      *  inference. An inference variable has upper/lower bounds and a set
  1280      *  of equality constraints. Such bounds are set during subtyping, type-containment,
  1281      *  type-equality checks, when the types being tested contain inference variables.
  1282      *  A change listener can be attached to an inference variable, to receive notifications
  1283      *  whenever the bounds of an inference variable change.
  1284      */
  1285     public static class UndetVar extends DelegatedType {
  1287         /** Inference variable change listener. The listener method is called
  1288          *  whenever a change to the inference variable's bounds occurs
  1289          */
  1290         public interface UndetVarListener {
  1291             /** called when some inference variable bounds (of given kinds ibs) change */
  1292             void varChanged(UndetVar uv, Set<InferenceBound> ibs);
  1295         /**
  1296          * Inference variable bound kinds
  1297          */
  1298         public enum InferenceBound {
  1299             /** upper bounds */
  1300             UPPER,
  1301             /** lower bounds */
  1302             LOWER,
  1303             /** equality constraints */
  1304             EQ;
  1307         /** inference variable bounds */
  1308         private Map<InferenceBound, List<Type>> bounds;
  1310         /** inference variable's inferred type (set from Infer.java) */
  1311         public Type inst = null;
  1313         /** inference variable's change listener */
  1314         public UndetVarListener listener = null;
  1316         @Override
  1317         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
  1318             return v.visitUndetVar(this, s);
  1321         public UndetVar(TypeVar origin, Types types) {
  1322             this(origin, types, true);
  1325         public UndetVar(TypeVar origin, Types types, boolean includeBounds) {
  1326             super(UNDETVAR, origin);
  1327             bounds = new EnumMap<InferenceBound, List<Type>>(InferenceBound.class);
  1328             bounds.put(InferenceBound.UPPER, includeBounds ? types.getBounds(origin) : List.<Type>nil());
  1329             bounds.put(InferenceBound.LOWER, List.<Type>nil());
  1330             bounds.put(InferenceBound.EQ, List.<Type>nil());
  1333         public String toString() {
  1334             if (inst != null) return inst.toString();
  1335             else return qtype + "?";
  1338         public Type baseType() {
  1339             if (inst != null) return inst.baseType();
  1340             else return this;
  1343         /** get all bounds of a given kind */
  1344         public List<Type> getBounds(InferenceBound ib) {
  1345             return bounds.get(ib);
  1348         /** add a bound of a given kind - this might trigger listener notification */
  1349         public void addBound(InferenceBound ib, Type bound, Types types) {
  1350             List<Type> prevBounds = bounds.get(ib);
  1351             for (Type b : prevBounds) {
  1352                 if (types.isSameType(b, bound)) {
  1353                     return;
  1356             bounds.put(ib, prevBounds.prepend(bound));
  1357             notifyChange(EnumSet.of(ib));
  1360         /** replace types in all bounds - this might trigger listener notification */
  1361         public void substBounds(List<Type> from, List<Type> to, Types types) {
  1362             EnumSet<InferenceBound> changed = EnumSet.noneOf(InferenceBound.class);
  1363             Map<InferenceBound, List<Type>> bounds2 = new EnumMap<InferenceBound, List<Type>>(InferenceBound.class);
  1364             for (Map.Entry<InferenceBound, List<Type>> _entry : bounds.entrySet()) {
  1365                 InferenceBound ib = _entry.getKey();
  1366                 List<Type> prevBounds = _entry.getValue();
  1367                 List<Type> newBounds = types.subst(prevBounds, from, to);
  1368                 bounds2.put(ib, newBounds);
  1369                 if (prevBounds != newBounds) {
  1370                     changed.add(ib);
  1373             if (!changed.isEmpty()) {
  1374                 bounds = bounds2;
  1375                 notifyChange(changed);
  1379         private void notifyChange(EnumSet<InferenceBound> ibs) {
  1380             if (listener != null) {
  1381                 listener.varChanged(this, ibs);
  1386     /** Represents VOID or NONE.
  1387      */
  1388     static class JCNoType extends Type implements NoType {
  1389         public JCNoType(TypeTag tag) {
  1390             super(tag, null);
  1393         @Override
  1394         public TypeKind getKind() {
  1395             switch (tag) {
  1396             case VOID:  return TypeKind.VOID;
  1397             case NONE:  return TypeKind.NONE;
  1398             default:
  1399                 throw new AssertionError("Unexpected tag: " + tag);
  1403         @Override
  1404         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
  1405             return v.visitNoType(this, p);
  1409     static class BottomType extends Type implements NullType {
  1410         public BottomType() {
  1411             super(BOT, null);
  1414         @Override
  1415         public TypeKind getKind() {
  1416             return TypeKind.NULL;
  1419         @Override
  1420         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
  1421             return v.visitNull(this, p);
  1424         @Override
  1425         public Type constType(Object value) {
  1426             return this;
  1429         @Override
  1430         public String stringValue() {
  1431             return "null";
  1435     public static class ErrorType extends ClassType
  1436             implements javax.lang.model.type.ErrorType {
  1438         private Type originalType = null;
  1440         public ErrorType(Type originalType, TypeSymbol tsym) {
  1441             super(noType, List.<Type>nil(), null);
  1442             tag = ERROR;
  1443             this.tsym = tsym;
  1444             this.originalType = (originalType == null ? noType : originalType);
  1447         public ErrorType(ClassSymbol c, Type originalType) {
  1448             this(originalType, c);
  1449             c.type = this;
  1450             c.kind = ERR;
  1451             c.members_field = new Scope.ErrorScope(c);
  1454         public ErrorType(Name name, TypeSymbol container, Type originalType) {
  1455             this(new ClassSymbol(PUBLIC|STATIC|ACYCLIC, name, null, container), originalType);
  1458         @Override
  1459         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
  1460             return v.visitErrorType(this, s);
  1463         public Type constType(Object constValue) { return this; }
  1464         public Type getEnclosingType()          { return this; }
  1465         public Type getReturnType()              { return this; }
  1466         public Type asSub(Symbol sym)            { return this; }
  1467         public Type map(Mapping f)               { return this; }
  1469         public boolean isGenType(Type t)         { return true; }
  1470         public boolean isErroneous()             { return true; }
  1471         public boolean isCompound()              { return false; }
  1472         public boolean isInterface()             { return false; }
  1474         public List<Type> allparams()            { return List.nil(); }
  1475         public List<Type> getTypeArguments()     { return List.nil(); }
  1477         public TypeKind getKind() {
  1478             return TypeKind.ERROR;
  1481         public Type getOriginalType() {
  1482             return originalType;
  1485         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
  1486             return v.visitError(this, p);
  1490     /**
  1491      * A visitor for types.  A visitor is used to implement operations
  1492      * (or relations) on types.  Most common operations on types are
  1493      * binary relations and this interface is designed for binary
  1494      * relations, that is, operations on the form
  1495      * Type&nbsp;&times;&nbsp;S&nbsp;&rarr;&nbsp;R.
  1496      * <!-- In plain text: Type x S -> R -->
  1498      * @param <R> the return type of the operation implemented by this
  1499      * visitor; use Void if no return type is needed.
  1500      * @param <S> the type of the second argument (the first being the
  1501      * type itself) of the operation implemented by this visitor; use
  1502      * Void if a second argument is not needed.
  1503      */
  1504     public interface Visitor<R,S> {
  1505         R visitClassType(ClassType t, S s);
  1506         R visitWildcardType(WildcardType t, S s);
  1507         R visitArrayType(ArrayType t, S s);
  1508         R visitMethodType(MethodType t, S s);
  1509         R visitPackageType(PackageType t, S s);
  1510         R visitTypeVar(TypeVar t, S s);
  1511         R visitCapturedType(CapturedType t, S s);
  1512         R visitForAll(ForAll t, S s);
  1513         R visitUndetVar(UndetVar t, S s);
  1514         R visitErrorType(ErrorType t, S s);
  1515         R visitType(Type t, S s);

mercurial