< prev index next >

src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TypeEnter.java

Print this page




  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  */
  25 
  26 package com.sun.tools.javac.comp;
  27 
  28 import java.util.HashSet;
  29 import java.util.Set;
  30 import java.util.function.BiConsumer;

  31 

  32 import javax.tools.JavaFileObject;
  33 
  34 import com.sun.tools.javac.code.*;
  35 import com.sun.tools.javac.code.Lint.LintCategory;
  36 import com.sun.tools.javac.code.Scope.ImportFilter;
  37 import com.sun.tools.javac.code.Scope.NamedImportScope;
  38 import com.sun.tools.javac.code.Scope.StarImportScope;
  39 import com.sun.tools.javac.code.Scope.WriteableScope;
  40 import com.sun.tools.javac.code.Source.Feature;
  41 import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata;
  42 import com.sun.tools.javac.tree.*;
  43 import com.sun.tools.javac.util.*;
  44 import com.sun.tools.javac.util.DefinedBy.Api;
  45 
  46 import com.sun.tools.javac.code.Symbol.*;
  47 import com.sun.tools.javac.code.Type.*;
  48 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  49 import com.sun.tools.javac.tree.JCTree.*;
  50 
  51 import static com.sun.tools.javac.code.Flags.*;
  52 import static com.sun.tools.javac.code.Flags.ANNOTATION;
  53 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
  54 import static com.sun.tools.javac.code.Kinds.Kind.*;
  55 import static com.sun.tools.javac.code.TypeTag.CLASS;
  56 import static com.sun.tools.javac.code.TypeTag.ERROR;


  57 import com.sun.tools.javac.resources.CompilerProperties.Fragments;

  58 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  59 
  60 import com.sun.tools.javac.util.Dependencies.CompletionCause;
  61 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
  62 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  63 
  64 /** This is the second phase of Enter, in which classes are completed
  65  *  by resolving their headers and entering their members in the into
  66  *  the class scope. See Enter for an overall overview.
  67  *
  68  *  This class uses internal phases to process the classes. When a phase
  69  *  processes classes, the lower phases are not invoked until all classes
  70  *  pass through the current phase. Note that it is possible that upper phases
  71  *  are run due to recursive completion. The internal phases are:
  72  *  - ImportPhase: shallow pass through imports, adds information about imports
  73  *                 the NamedImportScope and StarImportScope, but avoids queries
  74  *                 about class hierarchy.
  75  *  - HierarchyPhase: resolves the supertypes of the given class. Does not handle
  76  *                    type parameters of the class or type argument of the supertypes.
  77  *  - HeaderPhase: finishes analysis of the header of the given class by resolving


 123         names = Names.instance(context);
 124         enter = Enter.instance(context);
 125         memberEnter = MemberEnter.instance(context);
 126         log = Log.instance(context);
 127         chk = Check.instance(context);
 128         attr = Attr.instance(context);
 129         syms = Symtab.instance(context);
 130         make = TreeMaker.instance(context);
 131         todo = Todo.instance(context);
 132         annotate = Annotate.instance(context);
 133         typeAnnotations = TypeAnnotations.instance(context);
 134         types = Types.instance(context);
 135         diags = JCDiagnostic.Factory.instance(context);
 136         deferredLintHandler = DeferredLintHandler.instance(context);
 137         lint = Lint.instance(context);
 138         typeEnvs = TypeEnvs.instance(context);
 139         dependencies = Dependencies.instance(context);
 140         Source source = Source.instance(context);
 141         allowTypeAnnos = Feature.TYPE_ANNOTATIONS.allowedInSource(source);
 142         allowDeprecationOnImport = Feature.DEPRECATION_ON_IMPORT.allowedInSource(source);


 143     }
 144 
 145     /** Switch: support type annotations.
 146      */
 147     boolean allowTypeAnnos;
 148 
 149     /**
 150      * Switch: should deprecation warnings be issued on import
 151      */
 152     boolean allowDeprecationOnImport;
 153 
 154     /** A flag to disable completion from time to time during member
 155      *  enter, as we only need to look up types.  This avoids
 156      *  unnecessarily deep recursion.
 157      */
 158     boolean completionEnabled = true;
 159 







 160     /* Verify Imports:
 161      */
 162     protected void ensureImportsChecked(List<JCCompilationUnit> trees) {
 163         // if there remain any unimported toplevels (these must have
 164         // no classes at all), process their import statements as well.
 165         for (JCCompilationUnit tree : trees) {
 166             if (!tree.starImportScope.isFilled()) {
 167                 Env<AttrContext> topEnv = enter.topLevelEnv(tree);
 168                 finishImports(tree, () -> { completeClass.resolveImports(tree, topEnv); });
 169             }
 170         }
 171     }
 172 
 173 /* ********************************************************************
 174  * Source completer
 175  *********************************************************************/
 176 
 177     /** Complete entering a class.
 178      *  @param sym         The symbol of the class to be completed.
 179      */


 660                     } else {
 661                         for (int i = n; i > 0; i--) {
 662                             TypeVar v = new TypeVar(names.fromString("T" + i), sym,
 663                                                     syms.botType);
 664                             ct.typarams_field = ct.typarams_field.prepend(v);
 665                         }
 666                     }
 667                 }
 668             }
 669 
 670         protected void attribSuperTypes(Env<AttrContext> env, Env<AttrContext> baseEnv) {
 671             JCClassDecl tree = env.enclClass;
 672             ClassSymbol sym = tree.sym;
 673             ClassType ct = (ClassType)sym.type;
 674             // Determine supertype.
 675             Type supertype;
 676             JCExpression extending;
 677 
 678             if (tree.extending != null) {
 679                 extending = clearTypeParams(tree.extending);
 680                 supertype = attr.attribBase(extending, baseEnv, true, false, true);
 681             } else {
 682                 extending = null;
 683                 supertype = ((tree.mods.flags & Flags.ENUM) != 0)
 684                 ? attr.attribBase(enumBase(tree.pos, sym), baseEnv,
 685                                   true, false, false)
 686                 : (sym.fullname == names.java_lang_Object)
 687                 ? Type.noType
 688                 : syms.objectType;
 689             }
 690             ct.supertype_field = modelMissingTypes(baseEnv, supertype, extending, false);
 691 
 692             // Determine interfaces.
 693             ListBuffer<Type> interfaces = new ListBuffer<>();
 694             ListBuffer<Type> all_interfaces = null; // lazy init
 695             List<JCExpression> interfaceTrees = tree.implementing;
 696             for (JCExpression iface : interfaceTrees) {
 697                 iface = clearTypeParams(iface);
 698                 Type it = attr.attribBase(iface, baseEnv, false, true, true);
 699                 if (it.hasTag(CLASS)) {
 700                     interfaces.append(it);
 701                     if (all_interfaces != null) all_interfaces.append(it);
 702                 } else {
 703                     if (all_interfaces == null)
 704                         all_interfaces = new ListBuffer<Type>().appendList(interfaces);
 705                     all_interfaces.append(modelMissingTypes(baseEnv, it, iface, true));
 706                 }
 707             }
 708 









 709             if ((sym.flags_field & ANNOTATION) != 0) {
 710                 ct.interfaces_field = List.of(syms.annotationType);
 711                 ct.all_interfaces_field = ct.interfaces_field;
 712             }  else {
 713                 ct.interfaces_field = interfaces.toList();
 714                 ct.all_interfaces_field = (all_interfaces == null)
 715                         ? ct.interfaces_field : all_interfaces.toList();
 716             }



 717         }
 718             //where:
 719             protected JCExpression clearTypeParams(JCExpression superType) {
 720                 return superType;
 721             }
 722     }
 723 
 724     private final class HierarchyPhase extends AbstractHeaderPhase implements Completer {
 725 
 726         public HierarchyPhase() {
 727             super(CompletionCause.HIERARCHY_PHASE, new HeaderPhase());
 728         }
 729 
 730         @Override
 731         protected void doCompleteEnvs(List<Env<AttrContext>> envs) {
 732             //The ClassSymbols in the envs list may not be in the dependency order.
 733             //To get proper results, for every class or interface C, the supertypes of
 734             //C must be processed by the HierarchyPhase phase before C.
 735             //To achieve that, the HierarchyPhase is registered as the Completer for
 736             //all the classes first, and then all the classes are completed.


 784         public void complete(Symbol sym) throws CompletionFailure {
 785             Assert.check((topLevelPhase instanceof ImportsPhase) ||
 786                          (topLevelPhase == this));
 787 
 788             if (topLevelPhase != this) {
 789                 //only do the processing based on dependencies in the HierarchyPhase:
 790                 sym.completer = this;
 791                 return ;
 792             }
 793 
 794             Env<AttrContext> env = typeEnvs.get((ClassSymbol) sym);
 795 
 796             super.doCompleteEnvs(List.of(env));
 797         }
 798 
 799     }
 800 
 801     private final class HeaderPhase extends AbstractHeaderPhase {
 802 
 803         public HeaderPhase() {
 804             super(CompletionCause.HEADER_PHASE, new MembersPhase());
 805         }
 806 
 807         @Override
 808         protected void runPhase(Env<AttrContext> env) {
 809             JCClassDecl tree = env.enclClass;
 810             ClassSymbol sym = tree.sym;
 811             ClassType ct = (ClassType)sym.type;
 812 
 813             // create an environment for evaluating the base clauses
 814             Env<AttrContext> baseEnv = baseEnv(tree, env);
 815 
 816             if (tree.extending != null)
 817                 annotate.queueScanTreeAndTypeAnnotate(tree.extending, baseEnv, sym, tree.pos());
 818             for (JCExpression impl : tree.implementing)
 819                 annotate.queueScanTreeAndTypeAnnotate(impl, baseEnv, sym, tree.pos());
 820             annotate.flush();
 821 
 822             attribSuperTypes(env, baseEnv);
 823 
 824             Set<Type> interfaceSet = new HashSet<>();


 834             attr.attribTypeVariables(tree.typarams, baseEnv, false);
 835 
 836             for (JCTypeParameter tp : tree.typarams)
 837                 annotate.queueScanTreeAndTypeAnnotate(tp, baseEnv, sym, tree.pos());
 838 
 839             // check that no package exists with same fully qualified name,
 840             // but admit classes in the unnamed package which have the same
 841             // name as a top-level package.
 842             if (checkClash &&
 843                 sym.owner.kind == PCK && sym.owner != env.toplevel.modle.unnamedPackage &&
 844                 syms.packageExists(env.toplevel.modle, sym.fullname)) {
 845                 log.error(tree.pos, Errors.ClashWithPkgOfSameName(Kinds.kindName(sym),sym));
 846             }
 847             if (sym.owner.kind == PCK && (sym.flags_field & PUBLIC) == 0 &&
 848                 !env.toplevel.sourcefile.isNameCompatible(sym.name.toString(),JavaFileObject.Kind.SOURCE)) {
 849                 sym.flags_field |= AUXILIARY;
 850             }
 851         }
 852     }
 853 
 854     /** Enter member fields and methods of a class
 855      */
 856     private final class MembersPhase extends Phase {
 857 
 858         public MembersPhase() {
 859             super(CompletionCause.MEMBERS_PHASE, null);
 860         }
 861 
 862         private boolean completing;
 863         private List<Env<AttrContext>> todo = List.nil();
 864 
 865         @Override
 866         protected void doCompleteEnvs(List<Env<AttrContext>> envs) {
 867             todo = todo.prependList(envs);
 868             if (completing) {
 869                 return ; //the top-level invocation will handle all envs
 870             }
 871             boolean prevCompleting = completing;
 872             completing = true;
 873             try {
 874                 while (todo.nonEmpty()) {
 875                     Env<AttrContext> head = todo.head;
 876                     todo = todo.tail;
 877                     super.doCompleteEnvs(List.of(head));
 878                 }
 879             } finally {
 880                 completing = prevCompleting;
 881             }
 882         }

























 883 
 884         @Override
 885         protected void runPhase(Env<AttrContext> env) {
 886             JCClassDecl tree = env.enclClass;
 887             ClassSymbol sym = tree.sym;
 888             ClassType ct = (ClassType)sym.type;

 889 
 890             // Add default constructor if needed.
 891             if ((sym.flags() & INTERFACE) == 0 &&
 892                 !TreeInfo.hasConstructors(tree.defs)) {
 893                 List<Type> argtypes = List.nil();
 894                 List<Type> typarams = List.nil();
 895                 List<Type> thrown = List.nil();
 896                 long ctorFlags = 0;
 897                 boolean based = false;
 898                 boolean addConstructor = true;
 899                 JCNewClass nc = null;
 900                 if (sym.name.isEmpty()) {
 901                     nc = (JCNewClass)env.next.tree;
 902                     if (nc.constructor != null) {
 903                         addConstructor = nc.constructor.kind != ERR;
 904                         Type superConstrType = types.memberType(sym.type,
 905                                                                 nc.constructor);
 906                         argtypes = superConstrType.getParameterTypes();
 907                         typarams = superConstrType.getTypeArguments();
 908                         ctorFlags = nc.constructor.flags() & VARARGS;
 909                         if (nc.encl != null) {
 910                             argtypes = argtypes.prepend(nc.encl.type);
 911                             based = true;
 912                         }
 913                         thrown = superConstrType.getThrownTypes();
 914                     }


 915                 }
 916                 if (addConstructor) {
 917                     MethodSymbol basedConstructor = nc != null ?
 918                             (MethodSymbol)nc.constructor : null;
 919                     JCTree constrDef = DefaultConstructor(make.at(tree.pos), sym,
 920                                                         basedConstructor,
 921                                                         typarams, argtypes, thrown,
 922                                                         ctorFlags, based);
 923                     tree.defs = tree.defs.prepend(constrDef);


































 924                 }
 925             }
 926 
 927             // enter symbols for 'this' into current scope.
 928             VarSymbol thisSym =
 929                 new VarSymbol(FINAL | HASINIT, names._this, sym.type, sym);
 930             thisSym.pos = Position.FIRSTPOS;
 931             env.info.scope.enter(thisSym);
 932             // if this is a class, enter symbol for 'super' into current scope.
 933             if ((sym.flags_field & INTERFACE) == 0 &&
 934                     ct.supertype_field.hasTag(CLASS)) {
 935                 VarSymbol superSym =
 936                     new VarSymbol(FINAL | HASINIT, names._super,
 937                                   ct.supertype_field, sym);
 938                 superSym.pos = Position.FIRSTPOS;
 939                 env.info.scope.enter(superSym);
 940             }
 941 
 942             if (!tree.typarams.isEmpty()) {
 943                 for (JCTypeParameter tvar : tree.typarams) {
 944                     chk.checkNonCyclic(tvar, (TypeVar)tvar.type);
 945                 }
 946             }
 947 
 948             finishClass(tree, env);
 949 
 950             if (allowTypeAnnos) {
 951                 typeAnnotations.organizeTypeAnnotationsSignatures(env, (JCClassDecl)env.tree);
 952                 typeAnnotations.validateTypeAnnotationsSignatures(env, (JCClassDecl)env.tree);
 953             }
 954         }
 955 























 956         /** Enter members for a class.
 957          */
 958         void finishClass(JCClassDecl tree, Env<AttrContext> env) {
 959             if ((tree.mods.flags & Flags.ENUM) != 0 &&
 960                 !tree.sym.type.hasTag(ERROR) &&
 961                 (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
 962                 addEnumMembers(tree, env);
 963             }
 964             memberEnter.memberEnter(tree.defs, env);










 965 
 966             if (tree.sym.isAnnotationType()) {
 967                 Assert.check(tree.sym.isCompleted());
 968                 tree.sym.setAnnotationTypeMetadata(new AnnotationTypeMetadata(tree.sym, annotate.annotationTypeSourceCompleter()));
 969             }





















































































 970         }
 971 
 972         /** Add the implicit members for an enum type
 973          *  to the symbol table.
 974          */
 975         private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
 976             JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass));
 977 
 978             // public static T[] values() { return ???; }
 979             JCMethodDecl values = make.
 980                 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
 981                           names.values,
 982                           valuesType,
 983                           List.nil(),
 984                           List.nil(),
 985                           List.nil(), // thrown
 986                           null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
 987                           null);
 988             memberEnter.memberEnter(values, env);
 989 
 990             // public static T valueOf(String name) { return ???; }
 991             JCMethodDecl valueOf = make.
 992                 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
 993                           names.valueOf,
 994                           make.Type(tree.sym.type),
 995                           List.nil(),
 996                           List.of(make.VarDef(make.Modifiers(Flags.PARAMETER |
 997                                                              Flags.MANDATED),
 998                                                 names.fromString("name"),
 999                                                 make.Type(syms.stringType), null)),
1000                           List.nil(), // thrown
1001                           null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
1002                           null);
1003             memberEnter.memberEnter(valueOf, env);
1004         }
1005 


















































































































1006     }
1007 
1008 /* ***************************************************************************
1009  * tree building
1010  ****************************************************************************/
1011 
1012     /** Generate default constructor for given class. For classes different
1013      *  from java.lang.Object, this is:
1014      *
1015      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
1016      *      super(x_0, ..., x_n)
1017      *    }
1018      *
1019      *  or, if based == true:
1020      *
1021      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
1022      *      x_0.super(x_1, ..., x_n)
1023      *    }
1024      *
1025      *  @param make     The tree factory.
1026      *  @param c        The class owning the default constructor.
1027      *  @param argtypes The parameter types of the constructor.
1028      *  @param thrown   The thrown exceptions of the constructor.
1029      *  @param based    Is first parameter a this$n?
1030      */
1031     JCTree DefaultConstructor(TreeMaker make,
1032                             ClassSymbol c,
1033                             MethodSymbol baseInit,
1034                             List<Type> typarams,
1035                             List<Type> argtypes,
1036                             List<Type> thrown,
1037                             long flags,
1038                             boolean based) {
1039         JCTree result;
1040         if ((c.flags() & ENUM) != 0 &&
1041             (types.supertype(c.type).tsym == syms.enumSym)) {
1042             // constructors of true enums are private
1043             flags = (flags & ~AccessFlags) | PRIVATE | GENERATEDCONSTR;
1044         } else
1045             flags |= (c.flags() & AccessFlags) | GENERATEDCONSTR;
1046         if (c.name.isEmpty()) {
1047             flags |= ANONCONSTR;
1048         }
1049         if (based) {
1050             flags |= ANONCONSTR_BASED;
1051         }
1052         Type mType = new MethodType(argtypes, null, thrown, c);
1053         Type initType = typarams.nonEmpty() ?
1054             new ForAll(typarams, mType) :
1055             mType;
1056         MethodSymbol init = new MethodSymbol(flags, names.init,
1057                 initType, c);
1058         init.params = createDefaultConstructorParams(make, baseInit, init,
1059                 argtypes, based);
1060         List<JCVariableDecl> params = make.Params(argtypes, init);
1061         List<JCStatement> stats = List.nil();
1062         if (c.type != syms.objectType) {
1063             stats = stats.prepend(SuperCall(make, typarams, params, based));











1064         }
1065         result = make.MethodDef(init, make.Block(0, stats));
1066         return result;
1067     }
1068 
1069     private List<VarSymbol> createDefaultConstructorParams(
1070             TreeMaker make,
1071             MethodSymbol baseInit,
1072             MethodSymbol init,
1073             List<Type> argtypes,
1074             boolean based) {
1075         List<VarSymbol> initParams = null;
1076         List<Type> argTypesList = argtypes;
1077         if (based) {
1078             /*  In this case argtypes will have an extra type, compared to baseInit,
1079              *  corresponding to the type of the enclosing instance i.e.:
1080              *
1081              *  Inner i = outer.new Inner(1){}
1082              *
1083              *  in the above example argtypes will be (Outer, int) and baseInit
1084              *  will have parameter's types (int). So in this case we have to add
1085              *  first the extra type in argtypes and then get the names of the
1086              *  parameters from baseInit.
1087              */
1088             initParams = List.nil();
1089             VarSymbol param = new VarSymbol(PARAMETER, make.paramName(0), argtypes.head, init);
1090             initParams = initParams.append(param);
1091             argTypesList = argTypesList.tail;
1092         }
1093         if (baseInit != null && baseInit.params != null &&
1094             baseInit.params.nonEmpty() && argTypesList.nonEmpty()) {
1095             initParams = (initParams == null) ? List.nil() : initParams;
1096             List<VarSymbol> baseInitParams = baseInit.params;
1097             while (baseInitParams.nonEmpty() && argTypesList.nonEmpty()) {
1098                 VarSymbol param = new VarSymbol(baseInitParams.head.flags() | PARAMETER,
1099                         baseInitParams.head.name, argTypesList.head, init);
1100                 initParams = initParams.append(param);
1101                 baseInitParams = baseInitParams.tail;
1102                 argTypesList = argTypesList.tail;







1103             }
















1104         }
1105         return initParams;
1106     }
1107 
1108     /** Generate call to superclass constructor. This is:
1109      *
1110      *    super(id_0, ..., id_n)
1111      *
1112      * or, if based == true
1113      *
1114      *    id_0.super(id_1,...,id_n)
1115      *
1116      *  where id_0, ..., id_n are the names of the given parameters.
1117      *
1118      *  @param make    The tree factory
1119      *  @param params  The parameters that need to be passed to super
1120      *  @param typarams  The type parameters that need to be passed to super
1121      *  @param based   Is first parameter a this$n?
1122      */
1123     JCExpressionStatement SuperCall(TreeMaker make,
1124                    List<Type> typarams,
1125                    List<JCVariableDecl> params,
1126                    boolean based) {
1127         JCExpression meth;
1128         if (based) {
1129             meth = make.Select(make.Ident(params.head), names._super);
1130             params = params.tail;
1131         } else {
1132             meth = make.Ident(names._super);
1133         }
1134         List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null;
1135         return make.Exec(make.Apply(typeargs, meth, make.Idents(params)));
















































1136     }
1137 
1138     /**
1139      * Mark sym deprecated if annotations contain @Deprecated annotation.
1140      */
1141     public void markDeprecated(Symbol sym, List<JCAnnotation> annotations, Env<AttrContext> env) {
1142         // In general, we cannot fully process annotations yet,  but we
1143         // can attribute the annotation types and then check to see if the
1144         // @Deprecated annotation is present.
1145         attr.attribAnnotationTypes(annotations, env);
1146         handleDeprecatedAnnotations(annotations, sym);
1147     }
1148 
1149     /**
1150      * If a list of annotations contains a reference to java.lang.Deprecated,
1151      * set the DEPRECATED flag.
1152      * If the annotation is marked forRemoval=true, also set DEPRECATED_REMOVAL.
1153      **/
1154     private void handleDeprecatedAnnotations(List<JCAnnotation> annotations, Symbol sym) {
1155         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {


  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  */
  25 
  26 package com.sun.tools.javac.comp;
  27 
  28 import java.util.HashSet;
  29 import java.util.Set;
  30 import java.util.function.BiConsumer;
  31 import java.util.stream.Collectors;
  32 
  33 import javax.lang.model.element.ElementKind;
  34 import javax.tools.JavaFileObject;
  35 
  36 import com.sun.tools.javac.code.*;
  37 import com.sun.tools.javac.code.Lint.LintCategory;
  38 import com.sun.tools.javac.code.Scope.ImportFilter;
  39 import com.sun.tools.javac.code.Scope.NamedImportScope;
  40 import com.sun.tools.javac.code.Scope.StarImportScope;
  41 import com.sun.tools.javac.code.Scope.WriteableScope;
  42 import com.sun.tools.javac.code.Source.Feature;
  43 import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata;
  44 import com.sun.tools.javac.tree.*;
  45 import com.sun.tools.javac.util.*;
  46 import com.sun.tools.javac.util.DefinedBy.Api;
  47 
  48 import com.sun.tools.javac.code.Symbol.*;
  49 import com.sun.tools.javac.code.Type.*;
  50 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  51 import com.sun.tools.javac.tree.JCTree.*;
  52 
  53 import static com.sun.tools.javac.code.Flags.*;
  54 import static com.sun.tools.javac.code.Flags.ANNOTATION;
  55 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
  56 import static com.sun.tools.javac.code.Kinds.Kind.*;
  57 import static com.sun.tools.javac.code.TypeTag.CLASS;
  58 import static com.sun.tools.javac.code.TypeTag.ERROR;
  59 import static com.sun.tools.javac.code.TypeTag.NONE;
  60 
  61 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  62 
  63 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  64 
  65 import com.sun.tools.javac.util.Dependencies.CompletionCause;
  66 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
  67 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  68 
  69 /** This is the second phase of Enter, in which classes are completed
  70  *  by resolving their headers and entering their members in the into
  71  *  the class scope. See Enter for an overall overview.
  72  *
  73  *  This class uses internal phases to process the classes. When a phase
  74  *  processes classes, the lower phases are not invoked until all classes
  75  *  pass through the current phase. Note that it is possible that upper phases
  76  *  are run due to recursive completion. The internal phases are:
  77  *  - ImportPhase: shallow pass through imports, adds information about imports
  78  *                 the NamedImportScope and StarImportScope, but avoids queries
  79  *                 about class hierarchy.
  80  *  - HierarchyPhase: resolves the supertypes of the given class. Does not handle
  81  *                    type parameters of the class or type argument of the supertypes.
  82  *  - HeaderPhase: finishes analysis of the header of the given class by resolving


 128         names = Names.instance(context);
 129         enter = Enter.instance(context);
 130         memberEnter = MemberEnter.instance(context);
 131         log = Log.instance(context);
 132         chk = Check.instance(context);
 133         attr = Attr.instance(context);
 134         syms = Symtab.instance(context);
 135         make = TreeMaker.instance(context);
 136         todo = Todo.instance(context);
 137         annotate = Annotate.instance(context);
 138         typeAnnotations = TypeAnnotations.instance(context);
 139         types = Types.instance(context);
 140         diags = JCDiagnostic.Factory.instance(context);
 141         deferredLintHandler = DeferredLintHandler.instance(context);
 142         lint = Lint.instance(context);
 143         typeEnvs = TypeEnvs.instance(context);
 144         dependencies = Dependencies.instance(context);
 145         Source source = Source.instance(context);
 146         allowTypeAnnos = Feature.TYPE_ANNOTATIONS.allowedInSource(source);
 147         allowDeprecationOnImport = Feature.DEPRECATION_ON_IMPORT.allowedInSource(source);
 148         Options options = Options.instance(context);
 149         dontErrorIfSealedExtended = options.isSet("dontErrorIfSealedExtended");
 150     }
 151 
 152     /** Switch: support type annotations.
 153      */
 154     boolean allowTypeAnnos;
 155 
 156     /**
 157      * Switch: should deprecation warnings be issued on import
 158      */
 159     boolean allowDeprecationOnImport;
 160 
 161     /** A flag to disable completion from time to time during member
 162      *  enter, as we only need to look up types.  This avoids
 163      *  unnecessarily deep recursion.
 164      */
 165     boolean completionEnabled = true;
 166 
 167     /**
 168      * Temporary switch, false by default but if set, allows generating classes that can extend a sealed class
 169      * even if not listed as a permitted subtype. This allows testing the VM runtime. Should be removed before sealed types
 170      * gets integrated
 171      */
 172     boolean dontErrorIfSealedExtended;
 173 
 174     /* Verify Imports:
 175      */
 176     protected void ensureImportsChecked(List<JCCompilationUnit> trees) {
 177         // if there remain any unimported toplevels (these must have
 178         // no classes at all), process their import statements as well.
 179         for (JCCompilationUnit tree : trees) {
 180             if (!tree.starImportScope.isFilled()) {
 181                 Env<AttrContext> topEnv = enter.topLevelEnv(tree);
 182                 finishImports(tree, () -> { completeClass.resolveImports(tree, topEnv); });
 183             }
 184         }
 185     }
 186 
 187 /* ********************************************************************
 188  * Source completer
 189  *********************************************************************/
 190 
 191     /** Complete entering a class.
 192      *  @param sym         The symbol of the class to be completed.
 193      */


 674                     } else {
 675                         for (int i = n; i > 0; i--) {
 676                             TypeVar v = new TypeVar(names.fromString("T" + i), sym,
 677                                                     syms.botType);
 678                             ct.typarams_field = ct.typarams_field.prepend(v);
 679                         }
 680                     }
 681                 }
 682             }
 683 
 684         protected void attribSuperTypes(Env<AttrContext> env, Env<AttrContext> baseEnv) {
 685             JCClassDecl tree = env.enclClass;
 686             ClassSymbol sym = tree.sym;
 687             ClassType ct = (ClassType)sym.type;
 688             // Determine supertype.
 689             Type supertype;
 690             JCExpression extending;
 691 
 692             if (tree.extending != null) {
 693                 extending = clearTypeParams(tree.extending);
 694                 supertype = attr.attribBase(extending, sym, baseEnv, true, false, true);
 695             } else {
 696                 extending = null;
 697                 supertype = ((tree.mods.flags & Flags.ENUM) != 0)
 698                 ? attr.attribBase(enumBase(tree.pos, sym), sym, baseEnv,
 699                                   true, false, false)
 700                 : (sym.fullname == names.java_lang_Object)
 701                 ? Type.noType
 702                 : syms.objectType;
 703             }
 704             ct.supertype_field = modelMissingTypes(baseEnv, supertype, extending, false);
 705 
 706             // Determine interfaces.
 707             ListBuffer<Type> interfaces = new ListBuffer<>();
 708             ListBuffer<Type> all_interfaces = null; // lazy init
 709             List<JCExpression> interfaceTrees = tree.implementing;
 710             for (JCExpression iface : interfaceTrees) {
 711                 iface = clearTypeParams(iface);
 712                 Type it = attr.attribBase(iface, sym, baseEnv, false, true, true);
 713                 if (it.hasTag(CLASS)) {
 714                     interfaces.append(it);
 715                     if (all_interfaces != null) all_interfaces.append(it);
 716                 } else {
 717                     if (all_interfaces == null)
 718                         all_interfaces = new ListBuffer<Type>().appendList(interfaces);
 719                     all_interfaces.append(modelMissingTypes(baseEnv, it, iface, true));
 720                 }
 721             }
 722 
 723             // Determine permits.
 724             ListBuffer<Type> permittedSubtypes = new ListBuffer<>();
 725             List<JCExpression> permittedTrees = tree.permitting;
 726             for (JCExpression permitted : permittedTrees) {
 727                 permitted = clearTypeParams(permitted);
 728                 Type pt = attr.attribBase(permitted, sym, baseEnv, false, false, false);
 729                 permittedSubtypes.append(pt);
 730             }
 731 
 732             if ((sym.flags_field & ANNOTATION) != 0) {
 733                 ct.interfaces_field = List.of(syms.annotationType);
 734                 ct.all_interfaces_field = ct.interfaces_field;
 735             }  else {
 736                 ct.interfaces_field = interfaces.toList();
 737                 ct.all_interfaces_field = (all_interfaces == null)
 738                         ? ct.interfaces_field : all_interfaces.toList();
 739             }
 740 
 741             ct.permitted = permittedSubtypes.toList();
 742             ct.isPermittedExplicit = !permittedSubtypes.isEmpty();
 743         }
 744             //where:
 745             protected JCExpression clearTypeParams(JCExpression superType) {
 746                 return superType;
 747             }
 748     }
 749 
 750     private final class HierarchyPhase extends AbstractHeaderPhase implements Completer {
 751 
 752         public HierarchyPhase() {
 753             super(CompletionCause.HIERARCHY_PHASE, new HeaderPhase());
 754         }
 755 
 756         @Override
 757         protected void doCompleteEnvs(List<Env<AttrContext>> envs) {
 758             //The ClassSymbols in the envs list may not be in the dependency order.
 759             //To get proper results, for every class or interface C, the supertypes of
 760             //C must be processed by the HierarchyPhase phase before C.
 761             //To achieve that, the HierarchyPhase is registered as the Completer for
 762             //all the classes first, and then all the classes are completed.


 810         public void complete(Symbol sym) throws CompletionFailure {
 811             Assert.check((topLevelPhase instanceof ImportsPhase) ||
 812                          (topLevelPhase == this));
 813 
 814             if (topLevelPhase != this) {
 815                 //only do the processing based on dependencies in the HierarchyPhase:
 816                 sym.completer = this;
 817                 return ;
 818             }
 819 
 820             Env<AttrContext> env = typeEnvs.get((ClassSymbol) sym);
 821 
 822             super.doCompleteEnvs(List.of(env));
 823         }
 824 
 825     }
 826 
 827     private final class HeaderPhase extends AbstractHeaderPhase {
 828 
 829         public HeaderPhase() {
 830             super(CompletionCause.HEADER_PHASE, new RecordPhase());
 831         }
 832 
 833         @Override
 834         protected void runPhase(Env<AttrContext> env) {
 835             JCClassDecl tree = env.enclClass;
 836             ClassSymbol sym = tree.sym;
 837             ClassType ct = (ClassType)sym.type;
 838 
 839             // create an environment for evaluating the base clauses
 840             Env<AttrContext> baseEnv = baseEnv(tree, env);
 841 
 842             if (tree.extending != null)
 843                 annotate.queueScanTreeAndTypeAnnotate(tree.extending, baseEnv, sym, tree.pos());
 844             for (JCExpression impl : tree.implementing)
 845                 annotate.queueScanTreeAndTypeAnnotate(impl, baseEnv, sym, tree.pos());
 846             annotate.flush();
 847 
 848             attribSuperTypes(env, baseEnv);
 849 
 850             Set<Type> interfaceSet = new HashSet<>();


 860             attr.attribTypeVariables(tree.typarams, baseEnv, false);
 861 
 862             for (JCTypeParameter tp : tree.typarams)
 863                 annotate.queueScanTreeAndTypeAnnotate(tp, baseEnv, sym, tree.pos());
 864 
 865             // check that no package exists with same fully qualified name,
 866             // but admit classes in the unnamed package which have the same
 867             // name as a top-level package.
 868             if (checkClash &&
 869                 sym.owner.kind == PCK && sym.owner != env.toplevel.modle.unnamedPackage &&
 870                 syms.packageExists(env.toplevel.modle, sym.fullname)) {
 871                 log.error(tree.pos, Errors.ClashWithPkgOfSameName(Kinds.kindName(sym),sym));
 872             }
 873             if (sym.owner.kind == PCK && (sym.flags_field & PUBLIC) == 0 &&
 874                 !env.toplevel.sourcefile.isNameCompatible(sym.name.toString(),JavaFileObject.Kind.SOURCE)) {
 875                 sym.flags_field |= AUXILIARY;
 876             }
 877         }
 878     }
 879 
 880     private abstract class AbstractMembersPhase extends Phase {


 881 
 882         public AbstractMembersPhase(CompletionCause completionCause, Phase next) {
 883             super(completionCause, next);
 884         }
 885 
 886         private boolean completing;
 887         private List<Env<AttrContext>> todo = List.nil();
 888 
 889         @Override
 890         protected void doCompleteEnvs(List<Env<AttrContext>> envs) {
 891             todo = todo.prependList(envs);
 892             if (completing) {
 893                 return ; //the top-level invocation will handle all envs
 894             }
 895             boolean prevCompleting = completing;
 896             completing = true;
 897             try {
 898                 while (todo.nonEmpty()) {
 899                     Env<AttrContext> head = todo.head;
 900                     todo = todo.tail;
 901                     super.doCompleteEnvs(List.of(head));
 902                 }
 903             } finally {
 904                 completing = prevCompleting;
 905             }
 906         }
 907     }
 908 
 909     private final class RecordPhase extends AbstractMembersPhase {
 910 
 911         public RecordPhase() {
 912             super(CompletionCause.RECORD_PHASE, new MembersPhase());
 913         }
 914 
 915         @Override
 916         protected void runPhase(Env<AttrContext> env) {
 917             JCClassDecl tree = env.enclClass;
 918             ClassSymbol sym = tree.sym;
 919             if ((sym.flags_field & RECORD) != 0) {
 920                 memberEnter.memberEnter(TreeInfo.recordFields(tree), env);
 921             }
 922         }
 923     }
 924 
 925     /** Enter member fields and methods of a class
 926      */
 927     private final class MembersPhase extends AbstractMembersPhase {
 928 
 929         public MembersPhase() {
 930             super(CompletionCause.MEMBERS_PHASE, null);
 931         }
 932 
 933         @Override
 934         protected void runPhase(Env<AttrContext> env) {
 935             JCClassDecl tree = env.enclClass;
 936             ClassSymbol sym = tree.sym;
 937             ClassType ct = (ClassType)sym.type;
 938             boolean defaultConstructorGenerated = false;
 939 
 940             // Add default constructor if needed.
 941             if ((sym.flags() & INTERFACE) == 0 &&
 942                 !TreeInfo.hasConstructors(tree.defs)) {
 943                 DefaultConstructorHelper helper = new BasicConstructorHelper(sym);






 944                 if (sym.name.isEmpty()) {
 945                     JCNewClass nc = (JCNewClass)env.next.tree;
 946                     if (nc.constructor != null) {
 947                         if (nc.constructor.kind != ERR) {
 948                             helper = new AnonClassConstructorHelper(sym, (MethodSymbol)nc.constructor, nc.encl);
 949                         } else {
 950                             helper = null;





 951                         }

 952                     }
 953                 } else if ((sym.flags() & RECORD) != 0) {
 954                     helper = new RecordConstructorHelper(sym, TreeInfo.recordFields(tree));
 955                 }
 956                 if (helper != null) {
 957                     JCTree constrDef = defaultConstructor(make.at(tree.pos), helper);





 958                     tree.defs = tree.defs.prepend(constrDef);
 959                     defaultConstructorGenerated = true;
 960                 }
 961             } else {
 962                 if ((sym.flags() & RECORD) != 0) {
 963                     // there are constructors but they could be incomplete
 964                     for (JCTree def : tree.defs) {
 965                         if (TreeInfo.isConstructor(def)) {
 966                             Name constructorInvocationName =
 967                                     TreeInfo.getConstructorInvocationName(((JCMethodDecl)def).body.stats, names, true);
 968                             if (constructorInvocationName == names.empty ||
 969                                     constructorInvocationName == names._super) {
 970                                 RecordConstructorHelper helper = new RecordConstructorHelper(sym, TreeInfo.recordFields(tree));
 971                                 JCMethodDecl methDecl = (JCMethodDecl)def;
 972                                 if (constructorInvocationName == names.empty) {
 973                                     JCStatement supCall = make.at(methDecl.body.pos).Exec(make.Apply(List.nil(),
 974                                             make.Ident(names._super), List.nil()));
 975                                     methDecl.body.stats = methDecl.body.stats.prepend(supCall);
 976                                 }
 977                                 ListBuffer<JCStatement> initializations = new ListBuffer<>();
 978                                 List<Name> inits = helper.inits();
 979                                 InitializationFinder initFinder = new InitializationFinder(inits);
 980                                 initFinder.scan(methDecl.body.stats);
 981                                 List<Name> found = initFinder.found.toList();
 982                                 inits = inits.diff(found);
 983                                 if (!inits.isEmpty()) {
 984                                     for (Name initName : inits) {
 985                                         initializations.add(make.Exec(make.Assign(make.Select(make.Ident(names._this),
 986                                                 initName), make.Ident(initName))));
 987                                     }
 988                                     methDecl.body.stats = methDecl.body.stats.appendList(initializations.toList());
 989                                 }
 990                             }
 991                         }
 992                     }
 993                 }
 994             }

 995             // enter symbols for 'this' into current scope.
 996             VarSymbol thisSym =
 997                 new VarSymbol(FINAL | HASINIT, names._this, sym.type, sym);
 998             thisSym.pos = Position.FIRSTPOS;
 999             env.info.scope.enter(thisSym);
1000             // if this is a class, enter symbol for 'super' into current scope.
1001             if ((sym.flags_field & INTERFACE) == 0 &&
1002                     ct.supertype_field.hasTag(CLASS)) {
1003                 VarSymbol superSym =
1004                     new VarSymbol(FINAL | HASINIT, names._super,
1005                                   ct.supertype_field, sym);
1006                 superSym.pos = Position.FIRSTPOS;
1007                 env.info.scope.enter(superSym);
1008             }
1009 
1010             if (!tree.typarams.isEmpty()) {
1011                 for (JCTypeParameter tvar : tree.typarams) {
1012                     chk.checkNonCyclic(tvar, (TypeVar)tvar.type);
1013                 }
1014             }
1015 
1016             finishClass(tree, env, defaultConstructorGenerated);
1017 
1018             if (allowTypeAnnos) {
1019                 typeAnnotations.organizeTypeAnnotationsSignatures(env, (JCClassDecl)env.tree);
1020                 typeAnnotations.validateTypeAnnotationsSignatures(env, (JCClassDecl)env.tree);
1021             }
1022         }
1023 
1024         class InitializationFinder extends TreeScanner {
1025             List<Name> fieldNames;
1026             ListBuffer<Name> found = new ListBuffer<>();
1027 
1028             public InitializationFinder(List<Name> fieldNames) {
1029                 this.fieldNames = fieldNames;
1030             }
1031 
1032             @Override
1033             public void visitAssign(JCAssign tree) {
1034                 super.visitAssign(tree);
1035                 if (tree.lhs.hasTag(SELECT)) {
1036                     JCFieldAccess select = (JCFieldAccess)tree.lhs;
1037                     if ((select.selected.hasTag(IDENT)) &&
1038                             ((JCIdent)select.selected).name == names._this) {
1039                         if (fieldNames.contains(select.name)) {
1040                             found.add(select.name);
1041                         }
1042                     }
1043                 }
1044             }
1045         }
1046 
1047         /** Enter members for a class.
1048          */
1049         void finishClass(JCClassDecl tree, Env<AttrContext> env, boolean defaultConstructorGenerated) {
1050             if ((tree.mods.flags & Flags.ENUM) != 0 &&
1051                 !tree.sym.type.hasTag(ERROR) &&
1052                 (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
1053                 addEnumMembers(tree, env);
1054             }
1055             boolean isRecord = (tree.sym.flags_field & RECORD) != 0;
1056             List<JCTree> defsToEnter = isRecord ?
1057                     tree.defs.diff(List.convert(JCTree.class, TreeInfo.recordFields(tree))) : tree.defs;
1058             memberEnter.memberEnter(defsToEnter, env);
1059             List<JCTree> defsBeforeAddingNewMembers = tree.defs;
1060             if (isRecord) {
1061                 addRecordMembersIfNeeded(tree, env, defaultConstructorGenerated);
1062                 addAccessorsIfNeeded(tree, env);
1063             }
1064             // now we need to enter any additional mandated member that could have been added in the previous step
1065             memberEnter.memberEnter(tree.defs.diff(List.convert(JCTree.class, defsBeforeAddingNewMembers)), env);
1066 
1067             if (tree.sym.isAnnotationType()) {
1068                 Assert.check(tree.sym.isCompleted());
1069                 tree.sym.setAnnotationTypeMetadata(new AnnotationTypeMetadata(tree.sym, annotate.annotationTypeSourceCompleter()));
1070             }
1071 
1072             Type st = types.supertype(tree.sym.type);
1073             boolean anyParentIsSealed = false;
1074             ListBuffer<Pair<ClassType, JCExpression>> potentiallySealedParents = new ListBuffer<>();
1075             if (st != Type.noType && (st.tsym.isSealed())) {
1076                 potentiallySealedParents.add(new Pair<>((ClassType)st, tree.extending));
1077                 anyParentIsSealed = true;
1078             }
1079 
1080             if (tree.implementing != null) {
1081                 for (JCExpression expr : tree.implementing) {
1082                     if (expr.type.tsym.isSealed()) {
1083                         potentiallySealedParents.add(new Pair<>((ClassType)expr.type, expr));
1084                         anyParentIsSealed = true;
1085                     }
1086                 }
1087             }
1088 
1089             for (Pair<ClassType, JCExpression> sealedParentPair: potentiallySealedParents) {
1090                 if (!sealedParentPair.fst.permitted.map(t -> t.tsym).contains(tree.sym.type.tsym)) {
1091                     boolean areInSameCompilationUnit = TreeInfo.declarationFor(sealedParentPair.fst.tsym, env.toplevel) != null &&
1092                             TreeInfo.declarationFor(tree.sym.outermostClass(), env.toplevel) != null;
1093                     boolean isSealed = sealedParentPair.fst.tsym.isSealed();
1094                     if (areInSameCompilationUnit) {
1095                         if (sealedParentPair.fst.tsym.isSealed() && !((ClassType)sealedParentPair.fst.tsym.type).isPermittedExplicit) {
1096                             if (tree.sym.isAnonymous()) {
1097                                 log.error(sealedParentPair.snd, Errors.CantInheritFromSealed(sealedParentPair.fst.tsym));
1098                             } else {
1099                                 sealedParentPair.fst.permitted = sealedParentPair.fst.permitted.prepend(tree.sym.type);
1100                             }
1101                         } else if (!dontErrorIfSealedExtended) {
1102                             log.error(sealedParentPair.snd, Errors.CantInheritFromSealed(sealedParentPair.fst.tsym));
1103                         }
1104                     } else if (!dontErrorIfSealedExtended) {
1105                         log.error(sealedParentPair.snd, Errors.CantInheritFromSealed(sealedParentPair.fst.tsym));
1106                     }
1107                 }
1108             }
1109 
1110             if (anyParentIsSealed && ((tree.sym.flags_field & Flags.NON_SEALED) == 0) ) {
1111                 // once we have the non-final keyword this will change
1112                 tree.sym.flags_field |= (tree.sym.flags_field & ABSTRACT) != 0 ? SEALED : FINAL;
1113             }
1114 
1115             if (!anyParentIsSealed && ((tree.sym.flags_field & Flags.NON_SEALED) != 0) ) {
1116                 log.error(tree, Errors.NonSealedWithNoSealedSupertype);
1117             }
1118         }
1119 
1120         /** Add the accessors for fields to the symbol table.
1121          */
1122         private void addAccessorsIfNeeded(JCClassDecl tree, Env<AttrContext> env) {
1123             tree.defs.stream()
1124                     .filter(t -> t.hasTag(VARDEF))
1125                     .map(t -> (JCVariableDecl)t)
1126                     .filter(vd -> vd.accessors != null && vd.accessors.nonEmpty())
1127                     .forEach(vd -> addAccessors(vd, env));
1128         }
1129 
1130         private void addAccessors(JCVariableDecl tree, Env<AttrContext> env) {
1131             for (Pair<Accessors.Kind, Name> accessor : tree.accessors) {
1132                 Type accessorType = accessor.fst.accessorType(syms, tree.sym.type);
1133                 MethodSymbol implSym = lookupMethod(env.enclClass.sym, accessor.snd, accessorType.getParameterTypes());
1134                 if (implSym == null || (implSym.flags_field & MANDATED) != 0) {
1135                     JCMethodDecl getter = make.at(tree.pos).MethodDef(make.Modifiers(Flags.PUBLIC | Flags.MANDATED, tree.mods.annotations),
1136                               accessor.snd,
1137                               make.Type(accessorType.getReturnType()),
1138                               List.nil(),
1139                               accessorType.getParameterTypes().stream()
1140                                       .map(ptype -> make.Param(tree.name, tree.sym.type, env.enclClass.sym))
1141                                       .collect(List.collector()),
1142                               List.nil(), // thrown
1143                               null,
1144                               null);
1145                     memberEnter.memberEnter(getter, env);
1146                     tree.sym.accessors = tree.sym.accessors.prepend(new Pair<>(accessor.fst, getter.sym));
1147                 } else if (implSym != null) {
1148                     if ((implSym.flags() & Flags.PUBLIC) == 0) {
1149                         log.error(TreeInfo.declarationFor(implSym, env.enclClass), Errors.MethodMustBePublic(implSym.name));
1150                     }
1151                     if (!types.isSameType(implSym.type.getReturnType(), tree.sym.type)) {
1152                         log.error(TreeInfo.declarationFor(implSym, env.enclClass), Errors.AccessorReturnTypeDoesntMatch(tree.sym.type, implSym.type.getReturnType()));
1153                     }
1154                 }
1155             }
1156         }
1157 
1158         /** Add the implicit members for an enum type
1159          *  to the symbol table.
1160          */
1161         private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
1162             JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass));
1163 
1164             // public static T[] values() { return ???; }
1165             JCMethodDecl values = make.
1166                 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
1167                           names.values,
1168                           valuesType,
1169                           List.nil(),
1170                           List.nil(),
1171                           List.nil(), // thrown
1172                           null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
1173                           null);
1174             memberEnter.memberEnter(values, env);
1175 
1176             // public static T valueOf(String name) { return ???; }
1177             JCMethodDecl valueOf = make.
1178                 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
1179                           names.valueOf,
1180                           make.Type(tree.sym.type),
1181                           List.nil(),
1182                           List.of(make.VarDef(make.Modifiers(Flags.PARAMETER |
1183                                                              Flags.MANDATED),
1184                                                 names.fromString("name"),
1185                                                 make.Type(syms.stringType), null)),
1186                           List.nil(), // thrown
1187                           null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
1188                           null);
1189             memberEnter.memberEnter(valueOf, env);
1190         }
1191 
1192         /** Add the implicit members for a record
1193          *  to the symbol table.
1194          */
1195         private void addRecordMembersIfNeeded(JCClassDecl tree, Env<AttrContext> env, boolean defaultConstructorGenerated) {
1196             if (!defaultConstructorGenerated) {
1197                 // let's check if there is a constructor with exactly the same arguments as the record components
1198                 List<Type> recordComponentTypes = TreeInfo.recordFields(tree).map(vd -> vd.sym.type);
1199                 List<Type> erasedTypes = types.erasure(recordComponentTypes);
1200                 JCMethodDecl canonicalDecl = null;
1201                 for (JCTree def : tree.defs) {
1202                     if (TreeInfo.isConstructor(def)) {
1203                         JCMethodDecl mdecl = (JCMethodDecl)def;
1204                         if (types.isSameTypes(mdecl.sym.type.getParameterTypes(), erasedTypes)) {
1205                             canonicalDecl = mdecl;
1206                             break;
1207                         }
1208                     }
1209                 }
1210                 if (canonicalDecl != null && !types.isSameTypes(erasedTypes, recordComponentTypes)) {
1211                     // error we found a constructor with the same erasure as the canonical constructor
1212                     log.error(canonicalDecl, Errors.ConstructorWithSameErasureAsCanonical);
1213                 }
1214                 MethodSymbol canonicalInit = canonicalDecl == null ?
1215                         null :
1216                         canonicalDecl.sym;
1217                 if (canonicalInit == null) {
1218                     RecordConstructorHelper helper = new RecordConstructorHelper(tree.sym, TreeInfo.recordFields(tree));
1219                     JCTree constrDef = defaultConstructor(make.at(tree.pos), helper);
1220                     tree.defs = tree.defs.prepend(constrDef);
1221                     defaultConstructorGenerated = true;
1222                 } else {
1223                     /* there is an explicit constructor that match the canonical constructor by type
1224                        let's check that the match is also by name
1225                     */
1226                     List<Name> recordComponentNames = TreeInfo.recordFields(tree).map(vd -> vd.sym.name);
1227                     List<Name> initParamNames = canonicalInit.params.map(p -> p.name);
1228                     if (!initParamNames.equals(recordComponentNames)) {
1229                         log.error(canonicalDecl, Errors.CanonicalWithNameMismatch);
1230                     }
1231                     // let's use the RECORD flag to mark it as the canonical constructor
1232                     canonicalInit.flags_field |= Flags.RECORD;
1233                 }
1234             }
1235 
1236             if (lookupMethod(tree.sym, names.toString, List.nil()) == null) {
1237                 // public String toString() { return ???; }
1238                 JCMethodDecl toString = make.
1239                     MethodDef(make.Modifiers(Flags.PUBLIC | Flags.RECORD | Flags.MANDATED),
1240                               names.toString,
1241                               make.Type(syms.stringType),
1242                               List.nil(),
1243                               List.nil(),
1244                               List.nil(), // thrown
1245                               null,
1246                               null);
1247                 memberEnter.memberEnter(toString, env);
1248             }
1249 
1250             if (lookupMethod(tree.sym, names.hashCode, List.nil()) == null) {
1251                 // public int hashCode() { return ???; }
1252                 JCMethodDecl hashCode = make.
1253                     MethodDef(make.Modifiers(Flags.PUBLIC | Flags.RECORD | Flags.FINAL | Flags.MANDATED),
1254                               names.hashCode,
1255                               make.Type(syms.intType),
1256                               List.nil(),
1257                               List.nil(),
1258                               List.nil(), // thrown
1259                               null,
1260                               null);
1261                 memberEnter.memberEnter(hashCode, env);
1262             }
1263 
1264             if (lookupMethod(tree.sym, names.equals, List.of(syms.objectType)) == null) {
1265                 // public boolean equals(Object o) { return ???; }
1266                 JCMethodDecl equals = make.
1267                     MethodDef(make.Modifiers(Flags.PUBLIC | Flags.RECORD | Flags.FINAL | Flags.MANDATED),
1268                               names.equals,
1269                               make.Type(syms.booleanType),
1270                               List.nil(),
1271                               List.of(make.VarDef(make.Modifiers(Flags.PARAMETER),
1272                                                 names.fromString("o"),
1273                                                 make.Type(syms.objectType), null)),
1274                               List.nil(), // thrown
1275                               null,
1276                               null);
1277                 memberEnter.memberEnter(equals, env);
1278             }
1279 
1280             if (attr.isSerializable(tree.sym.type)) {
1281                 if (lookupMethod(tree.sym, names.readResolve, List.nil()) == null &&
1282                     lookupMethod(tree.sym, names.readObject, List.nil()) == null) {
1283                     // private Object readResolve() { return ???; }
1284                     JCMethodDecl readResolve = make.
1285                         MethodDef(make.Modifiers(Flags.PRIVATE | Flags.RECORD | Flags.FINAL | Flags.MANDATED),
1286                                   names.readResolve,
1287                                   make.Type(syms.objectType),
1288                                   List.nil(),
1289                                   List.nil(),
1290                                   List.nil(), // thrown
1291                                   null,
1292                                   null);
1293                     memberEnter.memberEnter(readResolve, env);
1294                 }
1295             }
1296         }
1297     }
1298 
1299     private MethodSymbol lookupMethod(TypeSymbol tsym, Name name, List<Type> argtypes) {
1300         for (Symbol s : tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {
1301             if (types.isSameTypes(s.type.getParameterTypes(), argtypes)) {
1302                 return (MethodSymbol) s;
1303             }
1304         }
1305         return null;
1306     }
1307 
1308 /* ***************************************************************************
1309  * tree building
1310  ****************************************************************************/
1311 
1312     interface DefaultConstructorHelper {
1313        Type constructorType();
1314        MethodSymbol constructorSymbol();
1315        Type enclosingType();
1316        TypeSymbol owner();
1317        List<Name> superArgs();
1318        List<Name> inits();
1319        default JCMethodDecl finalAdjustment(JCMethodDecl md) { return md; }
1320     }
1321 
1322     class BasicConstructorHelper implements DefaultConstructorHelper {
1323 
1324         TypeSymbol owner;
1325         Type constructorType;
1326         MethodSymbol constructorSymbol;
1327 
1328         BasicConstructorHelper(TypeSymbol owner) {
1329             this.owner = owner;
1330         }
1331 
1332         @Override
1333         public Type constructorType() {
1334             if (constructorType == null) {
1335                 constructorType = new MethodType(List.nil(), syms.voidType, List.nil(), syms.methodClass);
1336             }
1337             return constructorType;
1338         }
1339 
1340         @Override
1341         public MethodSymbol constructorSymbol() {
1342             if (constructorSymbol == null) {
1343                 long flags;
1344                 if ((owner().flags() & ENUM) != 0 &&
1345                     (types.supertype(owner().type).tsym == syms.enumSym)) {
1346                     // constructors of true enums are private
1347                     flags = PRIVATE | GENERATEDCONSTR;
1348                 } else {
1349                     flags = (owner().flags() & AccessFlags) | GENERATEDCONSTR;
1350                 }
1351                 constructorSymbol = new MethodSymbol(flags, names.init,
1352                     constructorType(), owner());
1353             }
1354             return constructorSymbol;
1355         }
1356 
1357         @Override
1358         public Type enclosingType() {
1359             return Type.noType;
1360         }
1361 
1362         @Override
1363         public TypeSymbol owner() {
1364             return owner;
1365         }
1366 
1367         @Override
1368         public List<Name> superArgs() {
1369             return List.nil();
1370         }
1371 
1372         @Override
1373         public List<Name> inits() {
1374             return List.nil();
1375         }


1376     }
1377 
1378     class AnonClassConstructorHelper extends BasicConstructorHelper {
1379 
1380         MethodSymbol constr;
1381         Type encl;
1382         boolean based = false;
1383 
1384         AnonClassConstructorHelper(TypeSymbol owner, MethodSymbol constr, JCExpression encl) {
1385             super(owner);
1386             this.constr = constr;
1387             this.encl = encl != null ? encl.type : Type.noType;
1388         }
1389 
1390         @Override
1391         public Type constructorType() {
1392             if (constructorType == null) {
1393                 Type ctype = types.memberType(owner.type, constr);
1394                 if (!enclosingType().hasTag(NONE)) {
1395                     ctype = types.createMethodTypeWithParameters(ctype, ctype.getParameterTypes().prepend(enclosingType()));
1396                     based = true;
1397                 }
1398                 constructorType = ctype;
1399             }
1400             return constructorType;
1401         }
1402 
1403         @Override
1404         public MethodSymbol constructorSymbol() {
1405             MethodSymbol csym = super.constructorSymbol();
1406             csym.flags_field |= ANONCONSTR | (constr.flags() & VARARGS);
1407             csym.flags_field |= based ? ANONCONSTR_BASED : 0;
1408             ListBuffer<VarSymbol> params = new ListBuffer<>();
1409             List<Type> argtypes = constructorType().getParameterTypes();
1410             if (!enclosingType().hasTag(NONE)) {
1411                 argtypes = argtypes.tail;
1412                 params = params.prepend(new VarSymbol(PARAMETER, make.paramName(0), enclosingType(), csym));
1413             }
1414             if (constr.params != null) {
1415                 for (VarSymbol p : constr.params) {
1416                     params.add(new VarSymbol(PARAMETER | p.flags(), p.name, argtypes.head, csym));
1417                     argtypes = argtypes.tail;
1418                 }
1419             }
1420             csym.params = params.toList();
1421             return csym;
1422         }
1423 
1424         @Override
1425         public Type enclosingType() {
1426             return encl;
1427         }
1428 
1429         @Override
1430         public List<Name> superArgs() {
1431             List<JCVariableDecl> params = make.Params(constructorType().getParameterTypes(), constructorSymbol());
1432             if (!enclosingType().hasTag(NONE)) {
1433                 params = params.tail;
1434             }
1435             return params.map(vd -> vd.name);
1436         }

1437     }
1438 
1439     class RecordConstructorHelper extends BasicConstructorHelper {
1440 
1441         List<VarSymbol> recordFieldSymbols;
1442         List<JCVariableDecl> recordFieldDecls;
1443 
1444         RecordConstructorHelper(TypeSymbol owner, List<JCVariableDecl> recordFieldDecls) {
1445             super(owner);
1446             this.recordFieldDecls = recordFieldDecls;
1447             this.recordFieldSymbols = recordFieldDecls.map(vd -> vd.sym);
1448         }
1449 
1450         @Override
1451         public Type constructorType() {
1452             if (constructorType == null) {
1453                 List<Type> argtypes = recordFieldSymbols.map(v -> v.type);
1454                 constructorType = new MethodType(argtypes, syms.voidType, List.nil(), syms.methodClass);
1455             }
1456             return constructorType;







1457         }
1458 
1459         @Override
1460         public MethodSymbol constructorSymbol() {
1461             MethodSymbol csym = super.constructorSymbol();
1462             ListBuffer<VarSymbol> params = new ListBuffer<>();
1463             for (VarSymbol p : recordFieldSymbols) {
1464                 params.add(new VarSymbol(MANDATED | PARAMETER | RECORD, p.name, p.type, csym));
1465             }
1466             csym.params = params.toList();
1467             csym.flags_field |= RECORD | PUBLIC;
1468             return csym;
1469         }
1470 
1471         @Override
1472         public List<Name> inits() {
1473             return recordFieldSymbols.map(v -> v.name);
1474         }
1475 
1476         @Override
1477         public JCMethodDecl finalAdjustment(JCMethodDecl md) {
1478             List<JCVariableDecl> tmpRecordFieldDecls = recordFieldDecls;
1479             for (JCVariableDecl arg : md.params) {
1480                 arg.mods.annotations = tmpRecordFieldDecls.head.mods.annotations;
1481                 tmpRecordFieldDecls = tmpRecordFieldDecls.tail;
1482             }
1483             return md;
1484         }
1485     }
1486 
1487     JCTree defaultConstructor(TreeMaker make, DefaultConstructorHelper helper) {
1488         Type initType = helper.constructorType();
1489         MethodSymbol initSym = helper.constructorSymbol();
1490         ListBuffer<JCStatement> stats = new ListBuffer<>();
1491         if (helper.owner().type != syms.objectType) {
1492             JCExpression meth;
1493             if (!helper.enclosingType().hasTag(NONE)) {
1494                 meth = make.Select(make.Ident(initSym.params.head), names._super);
1495             } else {
1496                 meth = make.Ident(names._super);
1497             }
1498             List<JCExpression> typeargs = initType.getTypeArguments().nonEmpty() ?
1499                     make.Types(initType.getTypeArguments()) : null;
1500             JCStatement superCall = make.Exec(make.Apply(typeargs, meth, helper.superArgs().map(make::Ident)));
1501             stats.add(superCall);
1502         }
1503         helper.inits().forEach((initName) -> {
1504             stats.add(make.Exec(make.Assign(make.Select(make.Ident(names._this), initName), make.Ident(initName))));
1505         });
1506         JCMethodDecl result = make.MethodDef(initSym, make.Block(0, stats.toList()));
1507         return helper.finalAdjustment(result);
1508     }
1509 
1510     /**
1511      * Mark sym deprecated if annotations contain @Deprecated annotation.
1512      */
1513     public void markDeprecated(Symbol sym, List<JCAnnotation> annotations, Env<AttrContext> env) {
1514         // In general, we cannot fully process annotations yet,  but we
1515         // can attribute the annotation types and then check to see if the
1516         // @Deprecated annotation is present.
1517         attr.attribAnnotationTypes(annotations, env);
1518         handleDeprecatedAnnotations(annotations, sym);
1519     }
1520 
1521     /**
1522      * If a list of annotations contains a reference to java.lang.Deprecated,
1523      * set the DEPRECATED flag.
1524      * If the annotation is marked forRemoval=true, also set DEPRECATED_REMOVAL.
1525      **/
1526     private void handleDeprecatedAnnotations(List<JCAnnotation> annotations, Symbol sym) {
1527         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
< prev index next >