Enter.java revision 2868:816bd88d33a8
1/* 2 * Copyright (c) 1999, 2015, 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 */ 25 26package com.sun.tools.javac.comp; 27 28import java.util.*; 29import javax.tools.JavaFileObject; 30import javax.tools.JavaFileManager; 31 32import com.sun.tools.javac.code.*; 33import com.sun.tools.javac.code.Kinds.KindSelector; 34import com.sun.tools.javac.code.Scope.*; 35import com.sun.tools.javac.code.Symbol.*; 36import com.sun.tools.javac.code.Type.*; 37import com.sun.tools.javac.jvm.*; 38import com.sun.tools.javac.main.Option.PkgInfo; 39import com.sun.tools.javac.tree.*; 40import com.sun.tools.javac.tree.JCTree.*; 41import com.sun.tools.javac.util.*; 42import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 43import com.sun.tools.javac.util.List; 44 45 46import static com.sun.tools.javac.code.Flags.*; 47import static com.sun.tools.javac.code.Kinds.Kind.*; 48 49/** This class enters symbols for all encountered definitions into 50 * the symbol table. The pass consists of high-level two phases, 51 * organized as follows: 52 * 53 * <p>In the first phase, all class symbols are entered into their 54 * enclosing scope, descending recursively down the tree for classes 55 * which are members of other classes. The class symbols are given a 56 * TypeEnter object as completer. 57 * 58 * <p>In the second phase classes are completed using 59 * TypeEnter.complete(). Completion might occur on demand, but 60 * any classes that are not completed that way will be eventually 61 * completed by processing the `uncompleted' queue. Completion 62 * entails determination of a class's parameters, supertype and 63 * interfaces, as well as entering all symbols defined in the 64 * class into its scope, with the exception of class symbols which 65 * have been entered in phase 1. 66 * 67 * <p>Whereas the first phase is organized as a sweep through all 68 * compiled syntax trees, the second phase is on-demand. Members of a 69 * class are entered when the contents of a class are first 70 * accessed. This is accomplished by installing completer objects in 71 * class symbols for compiled classes which invoke the type-enter 72 * phase for the corresponding class tree. 73 * 74 * <p>Classes migrate from one phase to the next via queues: 75 * 76 * <pre>{@literal 77 * class enter -> (Enter.uncompleted) --> type enter 78 * -> (Todo) --> attribute 79 * (only for toplevel classes) 80 * }</pre> 81 * 82 * <p><b>This is NOT part of any supported API. 83 * If you write code that depends on this, you do so at your own risk. 84 * This code and its internal interfaces are subject to change or 85 * deletion without notice.</b> 86 */ 87public class Enter extends JCTree.Visitor { 88 protected static final Context.Key<Enter> enterKey = new Context.Key<>(); 89 90 Log log; 91 Symtab syms; 92 Check chk; 93 TreeMaker make; 94 Annotate annotate; 95 TypeEnter typeEnter; 96 Types types; 97 Lint lint; 98 Names names; 99 JavaFileManager fileManager; 100 PkgInfo pkginfoOpt; 101 TypeEnvs typeEnvs; 102 103 private final Todo todo; 104 105 public static Enter instance(Context context) { 106 Enter instance = context.get(enterKey); 107 if (instance == null) 108 instance = new Enter(context); 109 return instance; 110 } 111 112 protected Enter(Context context) { 113 context.put(enterKey, this); 114 115 log = Log.instance(context); 116 make = TreeMaker.instance(context); 117 syms = Symtab.instance(context); 118 chk = Check.instance(context); 119 typeEnter = TypeEnter.instance(context); 120 types = Types.instance(context); 121 annotate = Annotate.instance(context); 122 lint = Lint.instance(context); 123 names = Names.instance(context); 124 125 predefClassDef = make.ClassDef( 126 make.Modifiers(PUBLIC), 127 syms.predefClass.name, 128 List.<JCTypeParameter>nil(), 129 null, 130 List.<JCExpression>nil(), 131 List.<JCTree>nil()); 132 predefClassDef.sym = syms.predefClass; 133 todo = Todo.instance(context); 134 fileManager = context.get(JavaFileManager.class); 135 136 Options options = Options.instance(context); 137 pkginfoOpt = PkgInfo.get(options); 138 typeEnvs = TypeEnvs.instance(context); 139 } 140 141 /** Accessor for typeEnvs 142 */ 143 public Env<AttrContext> getEnv(TypeSymbol sym) { 144 return typeEnvs.get(sym); 145 } 146 147 public Iterable<Env<AttrContext>> getEnvs() { 148 return typeEnvs.values(); 149 } 150 151 public Env<AttrContext> getClassEnv(TypeSymbol sym) { 152 Env<AttrContext> localEnv = getEnv(sym); 153 Env<AttrContext> lintEnv = localEnv; 154 while (lintEnv.info.lint == null) 155 lintEnv = lintEnv.next; 156 localEnv.info.lint = lintEnv.info.lint.augment(sym); 157 return localEnv; 158 } 159 160 /** The queue of all classes that might still need to be completed; 161 * saved and initialized by main(). 162 */ 163 ListBuffer<ClassSymbol> uncompleted; 164 165 /** A dummy class to serve as enclClass for toplevel environments. 166 */ 167 private JCClassDecl predefClassDef; 168 169/* ************************************************************************ 170 * environment construction 171 *************************************************************************/ 172 173 174 /** Create a fresh environment for class bodies. 175 * This will create a fresh scope for local symbols of a class, referred 176 * to by the environments info.scope field. 177 * This scope will contain 178 * - symbols for this and super 179 * - symbols for any type parameters 180 * In addition, it serves as an anchor for scopes of methods and initializers 181 * which are nested in this scope via Scope.dup(). 182 * This scope should not be confused with the members scope of a class. 183 * 184 * @param tree The class definition. 185 * @param env The environment current outside of the class definition. 186 */ 187 public Env<AttrContext> classEnv(JCClassDecl tree, Env<AttrContext> env) { 188 Env<AttrContext> localEnv = 189 env.dup(tree, env.info.dup(WriteableScope.create(tree.sym))); 190 localEnv.enclClass = tree; 191 localEnv.outer = env; 192 localEnv.info.isSelfCall = false; 193 localEnv.info.lint = null; // leave this to be filled in by Attr, 194 // when annotations have been processed 195 localEnv.info.isAnonymousDiamond = TreeInfo.isDiamond(env.tree); 196 return localEnv; 197 } 198 199 /** Create a fresh environment for toplevels. 200 * @param tree The toplevel tree. 201 */ 202 Env<AttrContext> topLevelEnv(JCCompilationUnit tree) { 203 Env<AttrContext> localEnv = new Env<>(tree, new AttrContext()); 204 localEnv.toplevel = tree; 205 localEnv.enclClass = predefClassDef; 206 tree.toplevelScope = WriteableScope.create(tree.packge); 207 tree.namedImportScope = new NamedImportScope(tree.packge, tree.toplevelScope); 208 tree.starImportScope = new StarImportScope(tree.packge); 209 localEnv.info.scope = tree.toplevelScope; 210 localEnv.info.lint = lint; 211 return localEnv; 212 } 213 214 public Env<AttrContext> getTopLevelEnv(JCCompilationUnit tree) { 215 Env<AttrContext> localEnv = new Env<>(tree, new AttrContext()); 216 localEnv.toplevel = tree; 217 localEnv.enclClass = predefClassDef; 218 localEnv.info.scope = tree.toplevelScope; 219 localEnv.info.lint = lint; 220 return localEnv; 221 } 222 223 /** The scope in which a member definition in environment env is to be entered 224 * This is usually the environment's scope, except for class environments, 225 * where the local scope is for type variables, and the this and super symbol 226 * only, and members go into the class member scope. 227 */ 228 WriteableScope enterScope(Env<AttrContext> env) { 229 return (env.tree.hasTag(JCTree.Tag.CLASSDEF)) 230 ? ((JCClassDecl) env.tree).sym.members_field 231 : env.info.scope; 232 } 233 234/* ************************************************************************ 235 * Visitor methods for phase 1: class enter 236 *************************************************************************/ 237 238 /** Visitor argument: the current environment. 239 */ 240 protected Env<AttrContext> env; 241 242 /** Visitor result: the computed type. 243 */ 244 Type result; 245 246 /** Visitor method: enter all classes in given tree, catching any 247 * completion failure exceptions. Return the tree's type. 248 * 249 * @param tree The tree to be visited. 250 * @param env The environment visitor argument. 251 */ 252 Type classEnter(JCTree tree, Env<AttrContext> env) { 253 Env<AttrContext> prevEnv = this.env; 254 try { 255 this.env = env; 256 tree.accept(this); 257 return result; 258 } catch (CompletionFailure ex) { 259 return chk.completionError(tree.pos(), ex); 260 } finally { 261 this.env = prevEnv; 262 } 263 } 264 265 /** Visitor method: enter classes of a list of trees, returning a list of types. 266 */ 267 <T extends JCTree> List<Type> classEnter(List<T> trees, Env<AttrContext> env) { 268 ListBuffer<Type> ts = new ListBuffer<>(); 269 for (List<T> l = trees; l.nonEmpty(); l = l.tail) { 270 Type t = classEnter(l.head, env); 271 if (t != null) 272 ts.append(t); 273 } 274 return ts.toList(); 275 } 276 277 @Override 278 public void visitTopLevel(JCCompilationUnit tree) { 279 JavaFileObject prev = log.useSource(tree.sourcefile); 280 boolean addEnv = false; 281 boolean isPkgInfo = tree.sourcefile.isNameCompatible("package-info", 282 JavaFileObject.Kind.SOURCE); 283 JCPackageDecl pd = tree.getPackage(); 284 if (pd != null) { 285 tree.packge = pd.packge = syms.enterPackage(TreeInfo.fullName(pd.pid)); 286 if ( pd.annotations.nonEmpty() 287 || pkginfoOpt == PkgInfo.ALWAYS 288 || tree.docComments != null) { 289 if (isPkgInfo) { 290 addEnv = true; 291 } else if (pd.annotations.nonEmpty()) { 292 log.error(pd.annotations.head.pos(), 293 "pkg.annotations.sb.in.package-info.java"); 294 } 295 } 296 } else { 297 tree.packge = syms.unnamedPackage; 298 } 299 tree.packge.complete(); // Find all classes in package. 300 Env<AttrContext> topEnv = topLevelEnv(tree); 301 Env<AttrContext> packageEnv = isPkgInfo ? topEnv.dup(pd) : null; 302 303 // Save environment of package-info.java file. 304 if (isPkgInfo) { 305 Env<AttrContext> env0 = typeEnvs.get(tree.packge); 306 if (env0 != null) { 307 JCCompilationUnit tree0 = env0.toplevel; 308 if (!fileManager.isSameFile(tree.sourcefile, tree0.sourcefile)) { 309 log.warning(pd != null ? pd.pid.pos() : null, 310 "pkg-info.already.seen", 311 tree.packge); 312 } 313 } 314 typeEnvs.put(tree.packge, packageEnv); 315 316 for (Symbol q = tree.packge; q != null && q.kind == PCK; q = q.owner) 317 q.flags_field |= EXISTS; 318 319 Name name = names.package_info; 320 ClassSymbol c = syms.enterClass(name, tree.packge); 321 c.flatname = names.fromString(tree.packge + "." + name); 322 c.sourcefile = tree.sourcefile; 323 c.completer = null; 324 c.members_field = WriteableScope.create(c); 325 tree.packge.package_info = c; 326 } 327 classEnter(tree.defs, topEnv); 328 if (addEnv) { 329 todo.append(packageEnv); 330 } 331 log.useSource(prev); 332 result = null; 333 } 334 335 @Override 336 public void visitClassDef(JCClassDecl tree) { 337 Symbol owner = env.info.scope.owner; 338 WriteableScope enclScope = enterScope(env); 339 ClassSymbol c; 340 if (owner.kind == PCK) { 341 // We are seeing a toplevel class. 342 PackageSymbol packge = (PackageSymbol)owner; 343 for (Symbol q = packge; q != null && q.kind == PCK; q = q.owner) 344 q.flags_field |= EXISTS; 345 c = syms.enterClass(tree.name, packge); 346 packge.members().enterIfAbsent(c); 347 if ((tree.mods.flags & PUBLIC) != 0 && !classNameMatchesFileName(c, env)) { 348 log.error(tree.pos(), 349 "class.public.should.be.in.file", tree.name); 350 } 351 } else { 352 if (!tree.name.isEmpty() && 353 !chk.checkUniqueClassName(tree.pos(), tree.name, enclScope)) { 354 result = null; 355 return; 356 } 357 if (owner.kind == TYP) { 358 // We are seeing a member class. 359 c = syms.enterClass(tree.name, (TypeSymbol)owner); 360 if ((owner.flags_field & INTERFACE) != 0) { 361 tree.mods.flags |= PUBLIC | STATIC; 362 } 363 } else { 364 // We are seeing a local class. 365 c = syms.defineClass(tree.name, owner); 366 c.flatname = chk.localClassName(c); 367 if (!c.name.isEmpty()) 368 chk.checkTransparentClass(tree.pos(), c, env.info.scope); 369 } 370 } 371 tree.sym = c; 372 373 // Enter class into `compiled' table and enclosing scope. 374 if (chk.compiled.get(c.flatname) != null) { 375 duplicateClass(tree.pos(), c); 376 result = types.createErrorType(tree.name, (TypeSymbol)owner, Type.noType); 377 tree.sym = (ClassSymbol)result.tsym; 378 return; 379 } 380 chk.compiled.put(c.flatname, c); 381 enclScope.enter(c); 382 383 // Set up an environment for class block and store in `typeEnvs' 384 // table, to be retrieved later in memberEnter and attribution. 385 Env<AttrContext> localEnv = classEnv(tree, env); 386 typeEnvs.put(c, localEnv); 387 388 // Fill out class fields. 389 c.completer = null; // do not allow the initial completer linger on. 390 c.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, c, tree); 391 c.sourcefile = env.toplevel.sourcefile; 392 c.members_field = WriteableScope.create(c); 393 394 ClassType ct = (ClassType)c.type; 395 if (owner.kind != PCK && (c.flags_field & STATIC) == 0) { 396 // We are seeing a local or inner class. 397 // Set outer_field of this class to closest enclosing class 398 // which contains this class in a non-static context 399 // (its "enclosing instance class"), provided such a class exists. 400 Symbol owner1 = owner; 401 while (owner1.kind.matches(KindSelector.VAL_MTH) && 402 (owner1.flags_field & STATIC) == 0) { 403 owner1 = owner1.owner; 404 } 405 if (owner1.kind == TYP) { 406 ct.setEnclosingType(owner1.type); 407 } 408 } 409 410 // Enter type parameters. 411 ct.typarams_field = classEnter(tree.typarams, localEnv); 412 413 // install further completer for this type. 414 c.completer = typeEnter; 415 416 // Add non-local class to uncompleted, to make sure it will be 417 // completed later. 418 if (!c.isLocal() && uncompleted != null) uncompleted.append(c); 419// System.err.println("entering " + c.fullname + " in " + c.owner);//DEBUG 420 421 // Recursively enter all member classes. 422 classEnter(tree.defs, localEnv); 423 424 result = c.type; 425 } 426 //where 427 /** Does class have the same name as the file it appears in? 428 */ 429 private static boolean classNameMatchesFileName(ClassSymbol c, 430 Env<AttrContext> env) { 431 return env.toplevel.sourcefile.isNameCompatible(c.name.toString(), 432 JavaFileObject.Kind.SOURCE); 433 } 434 435 /** Complain about a duplicate class. */ 436 protected void duplicateClass(DiagnosticPosition pos, ClassSymbol c) { 437 log.error(pos, "duplicate.class", c.fullname); 438 } 439 440 /** Class enter visitor method for type parameters. 441 * Enter a symbol for type parameter in local scope, after checking that it 442 * is unique. 443 */ 444 @Override 445 public void visitTypeParameter(JCTypeParameter tree) { 446 TypeVar a = (tree.type != null) 447 ? (TypeVar)tree.type 448 : new TypeVar(tree.name, env.info.scope.owner, syms.botType); 449 tree.type = a; 450 if (chk.checkUnique(tree.pos(), a.tsym, env.info.scope)) { 451 env.info.scope.enter(a.tsym); 452 } 453 result = a; 454 } 455 456 /** Default class enter visitor method: do nothing. 457 */ 458 @Override 459 public void visitTree(JCTree tree) { 460 result = null; 461 } 462 463 /** Main method: enter all classes in a list of toplevel trees. 464 * @param trees The list of trees to be processed. 465 */ 466 public void main(List<JCCompilationUnit> trees) { 467 complete(trees, null); 468 } 469 470 /** Main method: enter classes from the list of toplevel trees, possibly 471 * skipping TypeEnter for all but 'c' by placing them on the uncompleted 472 * list. 473 * @param trees The list of trees to be processed. 474 * @param c The class symbol to be processed or null to process all. 475 */ 476 public void complete(List<JCCompilationUnit> trees, ClassSymbol c) { 477 annotate.enterStart(); 478 ListBuffer<ClassSymbol> prevUncompleted = uncompleted; 479 if (typeEnter.completionEnabled) uncompleted = new ListBuffer<>(); 480 481 try { 482 // enter all classes, and construct uncompleted list 483 classEnter(trees, null); 484 485 // complete all uncompleted classes in memberEnter 486 if (typeEnter.completionEnabled) { 487 while (uncompleted.nonEmpty()) { 488 ClassSymbol clazz = uncompleted.next(); 489 if (c == null || c == clazz || prevUncompleted == null) 490 clazz.complete(); 491 else 492 // defer 493 prevUncompleted.append(clazz); 494 } 495 496 typeEnter.ensureImportsChecked(trees); 497 } 498 } finally { 499 uncompleted = prevUncompleted; 500 annotate.enterDone(); 501 } 502 } 503 504 public void newRound() { 505 typeEnvs.clear(); 506 } 507} 508