Mon, 17 Dec 2012 07:47:05 -0800
8004832: Add new doclint package
Reviewed-by: mcimadamore
1 /*
2 * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.comp;
28 import java.util.*;
29 import java.util.Set;
30 import javax.tools.JavaFileObject;
32 import com.sun.tools.javac.code.*;
33 import com.sun.tools.javac.jvm.*;
34 import com.sun.tools.javac.tree.*;
35 import com.sun.tools.javac.util.*;
36 import com.sun.tools.javac.util.List;
38 import com.sun.tools.javac.code.Type.*;
39 import com.sun.tools.javac.code.Symbol.*;
40 import com.sun.tools.javac.tree.JCTree.*;
42 import static com.sun.tools.javac.code.Flags.*;
43 import static com.sun.tools.javac.code.Flags.ANNOTATION;
44 import static com.sun.tools.javac.code.Kinds.*;
45 import static com.sun.tools.javac.code.TypeTag.CLASS;
46 import static com.sun.tools.javac.code.TypeTag.ERROR;
47 import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
48 import static com.sun.tools.javac.tree.JCTree.Tag.*;
49 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
50 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
52 /** This is the second phase of Enter, in which classes are completed
53 * by entering their members into the class scope using
54 * MemberEnter.complete(). See Enter for an overview.
55 *
56 * <p><b>This is NOT part of any supported API.
57 * If you write code that depends on this, you do so at your own risk.
58 * This code and its internal interfaces are subject to change or
59 * deletion without notice.</b>
60 */
61 public class MemberEnter extends JCTree.Visitor implements Completer {
62 protected static final Context.Key<MemberEnter> memberEnterKey =
63 new Context.Key<MemberEnter>();
65 /** A switch to determine whether we check for package/class conflicts
66 */
67 final static boolean checkClash = true;
69 private final Names names;
70 private final Enter enter;
71 private final Log log;
72 private final Check chk;
73 private final Attr attr;
74 private final Symtab syms;
75 private final TreeMaker make;
76 private final ClassReader reader;
77 private final Todo todo;
78 private final Annotate annotate;
79 private final Types types;
80 private final JCDiagnostic.Factory diags;
81 private final Source source;
82 private final Target target;
83 private final DeferredLintHandler deferredLintHandler;
85 public static MemberEnter instance(Context context) {
86 MemberEnter instance = context.get(memberEnterKey);
87 if (instance == null)
88 instance = new MemberEnter(context);
89 return instance;
90 }
92 protected MemberEnter(Context context) {
93 context.put(memberEnterKey, this);
94 names = Names.instance(context);
95 enter = Enter.instance(context);
96 log = Log.instance(context);
97 chk = Check.instance(context);
98 attr = Attr.instance(context);
99 syms = Symtab.instance(context);
100 make = TreeMaker.instance(context);
101 reader = ClassReader.instance(context);
102 todo = Todo.instance(context);
103 annotate = Annotate.instance(context);
104 types = Types.instance(context);
105 diags = JCDiagnostic.Factory.instance(context);
106 source = Source.instance(context);
107 target = Target.instance(context);
108 deferredLintHandler = DeferredLintHandler.instance(context);
109 }
111 /** A queue for classes whose members still need to be entered into the
112 * symbol table.
113 */
114 ListBuffer<Env<AttrContext>> halfcompleted = new ListBuffer<Env<AttrContext>>();
116 /** Set to true only when the first of a set of classes is
117 * processed from the halfcompleted queue.
118 */
119 boolean isFirst = true;
121 /** A flag to disable completion from time to time during member
122 * enter, as we only need to look up types. This avoids
123 * unnecessarily deep recursion.
124 */
125 boolean completionEnabled = true;
127 /* ---------- Processing import clauses ----------------
128 */
130 /** Import all classes of a class or package on demand.
131 * @param pos Position to be used for error reporting.
132 * @param tsym The class or package the members of which are imported.
133 * @param env The env in which the imported classes will be entered.
134 */
135 private void importAll(int pos,
136 final TypeSymbol tsym,
137 Env<AttrContext> env) {
138 // Check that packages imported from exist (JLS ???).
139 if (tsym.kind == PCK && tsym.members().elems == null && !tsym.exists()) {
140 // If we can't find java.lang, exit immediately.
141 if (((PackageSymbol)tsym).fullname.equals(names.java_lang)) {
142 JCDiagnostic msg = diags.fragment("fatal.err.no.java.lang");
143 throw new FatalError(msg);
144 } else {
145 log.error(DiagnosticFlag.RESOLVE_ERROR, pos, "doesnt.exist", tsym);
146 }
147 }
148 env.toplevel.starImportScope.importAll(tsym.members());
149 }
151 /** Import all static members of a class or package on demand.
152 * @param pos Position to be used for error reporting.
153 * @param tsym The class or package the members of which are imported.
154 * @param env The env in which the imported classes will be entered.
155 */
156 private void importStaticAll(int pos,
157 final TypeSymbol tsym,
158 Env<AttrContext> env) {
159 final JavaFileObject sourcefile = env.toplevel.sourcefile;
160 final Scope toScope = env.toplevel.starImportScope;
161 final PackageSymbol packge = env.toplevel.packge;
162 final TypeSymbol origin = tsym;
164 // enter imported types immediately
165 new Object() {
166 Set<Symbol> processed = new HashSet<Symbol>();
167 void importFrom(TypeSymbol tsym) {
168 if (tsym == null || !processed.add(tsym))
169 return;
171 // also import inherited names
172 importFrom(types.supertype(tsym.type).tsym);
173 for (Type t : types.interfaces(tsym.type))
174 importFrom(t.tsym);
176 final Scope fromScope = tsym.members();
177 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
178 Symbol sym = e.sym;
179 if (sym.kind == TYP &&
180 (sym.flags() & STATIC) != 0 &&
181 staticImportAccessible(sym, packge) &&
182 sym.isMemberOf(origin, types) &&
183 !toScope.includes(sym))
184 toScope.enter(sym, fromScope, origin.members());
185 }
186 }
187 }.importFrom(tsym);
189 // enter non-types before annotations that might use them
190 annotate.earlier(new Annotate.Annotator() {
191 Set<Symbol> processed = new HashSet<Symbol>();
193 public String toString() {
194 return "import static " + tsym + ".*" + " in " + sourcefile;
195 }
196 void importFrom(TypeSymbol tsym) {
197 if (tsym == null || !processed.add(tsym))
198 return;
200 // also import inherited names
201 importFrom(types.supertype(tsym.type).tsym);
202 for (Type t : types.interfaces(tsym.type))
203 importFrom(t.tsym);
205 final Scope fromScope = tsym.members();
206 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
207 Symbol sym = e.sym;
208 if (sym.isStatic() && sym.kind != TYP &&
209 staticImportAccessible(sym, packge) &&
210 !toScope.includes(sym) &&
211 sym.isMemberOf(origin, types)) {
212 toScope.enter(sym, fromScope, origin.members());
213 }
214 }
215 }
216 public void enterAnnotation() {
217 importFrom(tsym);
218 }
219 });
220 }
222 // is the sym accessible everywhere in packge?
223 boolean staticImportAccessible(Symbol sym, PackageSymbol packge) {
224 int flags = (int)(sym.flags() & AccessFlags);
225 switch (flags) {
226 default:
227 case PUBLIC:
228 return true;
229 case PRIVATE:
230 return false;
231 case 0:
232 case PROTECTED:
233 return sym.packge() == packge;
234 }
235 }
237 /** Import statics types of a given name. Non-types are handled in Attr.
238 * @param pos Position to be used for error reporting.
239 * @param tsym The class from which the name is imported.
240 * @param name The (simple) name being imported.
241 * @param env The environment containing the named import
242 * scope to add to.
243 */
244 private void importNamedStatic(final DiagnosticPosition pos,
245 final TypeSymbol tsym,
246 final Name name,
247 final Env<AttrContext> env) {
248 if (tsym.kind != TYP) {
249 log.error(DiagnosticFlag.RECOVERABLE, pos, "static.imp.only.classes.and.interfaces");
250 return;
251 }
253 final Scope toScope = env.toplevel.namedImportScope;
254 final PackageSymbol packge = env.toplevel.packge;
255 final TypeSymbol origin = tsym;
257 // enter imported types immediately
258 new Object() {
259 Set<Symbol> processed = new HashSet<Symbol>();
260 void importFrom(TypeSymbol tsym) {
261 if (tsym == null || !processed.add(tsym))
262 return;
264 // also import inherited names
265 importFrom(types.supertype(tsym.type).tsym);
266 for (Type t : types.interfaces(tsym.type))
267 importFrom(t.tsym);
269 for (Scope.Entry e = tsym.members().lookup(name);
270 e.scope != null;
271 e = e.next()) {
272 Symbol sym = e.sym;
273 if (sym.isStatic() &&
274 sym.kind == TYP &&
275 staticImportAccessible(sym, packge) &&
276 sym.isMemberOf(origin, types) &&
277 chk.checkUniqueStaticImport(pos, sym, toScope))
278 toScope.enter(sym, sym.owner.members(), origin.members());
279 }
280 }
281 }.importFrom(tsym);
283 // enter non-types before annotations that might use them
284 annotate.earlier(new Annotate.Annotator() {
285 Set<Symbol> processed = new HashSet<Symbol>();
286 boolean found = false;
288 public String toString() {
289 return "import static " + tsym + "." + name;
290 }
291 void importFrom(TypeSymbol tsym) {
292 if (tsym == null || !processed.add(tsym))
293 return;
295 // also import inherited names
296 importFrom(types.supertype(tsym.type).tsym);
297 for (Type t : types.interfaces(tsym.type))
298 importFrom(t.tsym);
300 for (Scope.Entry e = tsym.members().lookup(name);
301 e.scope != null;
302 e = e.next()) {
303 Symbol sym = e.sym;
304 if (sym.isStatic() &&
305 staticImportAccessible(sym, packge) &&
306 sym.isMemberOf(origin, types)) {
307 found = true;
308 if (sym.kind == MTH ||
309 sym.kind != TYP && chk.checkUniqueStaticImport(pos, sym, toScope))
310 toScope.enter(sym, sym.owner.members(), origin.members());
311 }
312 }
313 }
314 public void enterAnnotation() {
315 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
316 try {
317 importFrom(tsym);
318 if (!found) {
319 log.error(pos, "cant.resolve.location",
320 KindName.STATIC,
321 name, List.<Type>nil(), List.<Type>nil(),
322 Kinds.typeKindName(tsym.type),
323 tsym.type);
324 }
325 } finally {
326 log.useSource(prev);
327 }
328 }
329 });
330 }
331 /** Import given class.
332 * @param pos Position to be used for error reporting.
333 * @param tsym The class to be imported.
334 * @param env The environment containing the named import
335 * scope to add to.
336 */
337 private void importNamed(DiagnosticPosition pos, Symbol tsym, Env<AttrContext> env) {
338 if (tsym.kind == TYP &&
339 chk.checkUniqueImport(pos, tsym, env.toplevel.namedImportScope))
340 env.toplevel.namedImportScope.enter(tsym, tsym.owner.members());
341 }
343 /** Construct method type from method signature.
344 * @param typarams The method's type parameters.
345 * @param params The method's value parameters.
346 * @param res The method's result type,
347 * null if it is a constructor.
348 * @param thrown The method's thrown exceptions.
349 * @param env The method's (local) environment.
350 */
351 Type signature(List<JCTypeParameter> typarams,
352 List<JCVariableDecl> params,
353 JCTree res,
354 List<JCExpression> thrown,
355 Env<AttrContext> env) {
357 // Enter and attribute type parameters.
358 List<Type> tvars = enter.classEnter(typarams, env);
359 attr.attribTypeVariables(typarams, env);
361 // Enter and attribute value parameters.
362 ListBuffer<Type> argbuf = new ListBuffer<Type>();
363 for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) {
364 memberEnter(l.head, env);
365 argbuf.append(l.head.vartype.type);
366 }
368 // Attribute result type, if one is given.
369 Type restype = res == null ? syms.voidType : attr.attribType(res, env);
371 // Attribute thrown exceptions.
372 ListBuffer<Type> thrownbuf = new ListBuffer<Type>();
373 for (List<JCExpression> l = thrown; l.nonEmpty(); l = l.tail) {
374 Type exc = attr.attribType(l.head, env);
375 if (!exc.hasTag(TYPEVAR))
376 exc = chk.checkClassType(l.head.pos(), exc);
377 thrownbuf.append(exc);
378 }
379 Type mtype = new MethodType(argbuf.toList(),
380 restype,
381 thrownbuf.toList(),
382 syms.methodClass);
383 return tvars.isEmpty() ? mtype : new ForAll(tvars, mtype);
384 }
386 /* ********************************************************************
387 * Visitor methods for member enter
388 *********************************************************************/
390 /** Visitor argument: the current environment
391 */
392 protected Env<AttrContext> env;
394 /** Enter field and method definitions and process import
395 * clauses, catching any completion failure exceptions.
396 */
397 protected void memberEnter(JCTree tree, Env<AttrContext> env) {
398 Env<AttrContext> prevEnv = this.env;
399 try {
400 this.env = env;
401 tree.accept(this);
402 } catch (CompletionFailure ex) {
403 chk.completionError(tree.pos(), ex);
404 } finally {
405 this.env = prevEnv;
406 }
407 }
409 /** Enter members from a list of trees.
410 */
411 void memberEnter(List<? extends JCTree> trees, Env<AttrContext> env) {
412 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
413 memberEnter(l.head, env);
414 }
416 /** Enter members for a class.
417 */
418 void finishClass(JCClassDecl tree, Env<AttrContext> env) {
419 if ((tree.mods.flags & Flags.ENUM) != 0 &&
420 (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
421 addEnumMembers(tree, env);
422 }
423 memberEnter(tree.defs, env);
424 }
426 /** Add the implicit members for an enum type
427 * to the symbol table.
428 */
429 private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
430 JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass));
432 // public static T[] values() { return ???; }
433 JCMethodDecl values = make.
434 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
435 names.values,
436 valuesType,
437 List.<JCTypeParameter>nil(),
438 List.<JCVariableDecl>nil(),
439 List.<JCExpression>nil(), // thrown
440 null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
441 null);
442 memberEnter(values, env);
444 // public static T valueOf(String name) { return ???; }
445 JCMethodDecl valueOf = make.
446 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
447 names.valueOf,
448 make.Type(tree.sym.type),
449 List.<JCTypeParameter>nil(),
450 List.of(make.VarDef(make.Modifiers(Flags.PARAMETER),
451 names.fromString("name"),
452 make.Type(syms.stringType), null)),
453 List.<JCExpression>nil(), // thrown
454 null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
455 null);
456 memberEnter(valueOf, env);
458 // the remaining members are for bootstrapping only
459 if (!target.compilerBootstrap(tree.sym)) return;
461 // public final int ordinal() { return ???; }
462 JCMethodDecl ordinal = make.at(tree.pos).
463 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.FINAL),
464 names.ordinal,
465 make.Type(syms.intType),
466 List.<JCTypeParameter>nil(),
467 List.<JCVariableDecl>nil(),
468 List.<JCExpression>nil(),
469 null,
470 null);
471 memberEnter(ordinal, env);
473 // public final String name() { return ???; }
474 JCMethodDecl name = make.
475 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.FINAL),
476 names._name,
477 make.Type(syms.stringType),
478 List.<JCTypeParameter>nil(),
479 List.<JCVariableDecl>nil(),
480 List.<JCExpression>nil(),
481 null,
482 null);
483 memberEnter(name, env);
485 // public int compareTo(E other) { return ???; }
486 MethodSymbol compareTo = new
487 MethodSymbol(Flags.PUBLIC,
488 names.compareTo,
489 new MethodType(List.of(tree.sym.type),
490 syms.intType,
491 List.<Type>nil(),
492 syms.methodClass),
493 tree.sym);
494 memberEnter(make.MethodDef(compareTo, null), env);
495 }
497 public void visitTopLevel(JCCompilationUnit tree) {
498 if (tree.starImportScope.elems != null) {
499 // we must have already processed this toplevel
500 return;
501 }
503 // check that no class exists with same fully qualified name as
504 // toplevel package
505 if (checkClash && tree.pid != null) {
506 Symbol p = tree.packge;
507 while (p.owner != syms.rootPackage) {
508 p.owner.complete(); // enter all class members of p
509 if (syms.classes.get(p.getQualifiedName()) != null) {
510 log.error(tree.pos,
511 "pkg.clashes.with.class.of.same.name",
512 p);
513 }
514 p = p.owner;
515 }
516 }
518 // process package annotations
519 annotateLater(tree.packageAnnotations, env, tree.packge);
521 // Import-on-demand java.lang.
522 importAll(tree.pos, reader.enterPackage(names.java_lang), env);
524 // Process all import clauses.
525 memberEnter(tree.defs, env);
526 }
528 // process the non-static imports and the static imports of types.
529 public void visitImport(JCImport tree) {
530 JCFieldAccess imp = (JCFieldAccess)tree.qualid;
531 Name name = TreeInfo.name(imp);
533 // Create a local environment pointing to this tree to disable
534 // effects of other imports in Resolve.findGlobalType
535 Env<AttrContext> localEnv = env.dup(tree);
537 TypeSymbol p = attr.attribImportQualifier(tree, localEnv).tsym;
538 if (name == names.asterisk) {
539 // Import on demand.
540 chk.checkCanonical(imp.selected);
541 if (tree.staticImport)
542 importStaticAll(tree.pos, p, env);
543 else
544 importAll(tree.pos, p, env);
545 } else {
546 // Named type import.
547 if (tree.staticImport) {
548 importNamedStatic(tree.pos(), p, name, localEnv);
549 chk.checkCanonical(imp.selected);
550 } else {
551 TypeSymbol c = attribImportType(imp, localEnv).tsym;
552 chk.checkCanonical(imp);
553 importNamed(tree.pos(), c, env);
554 }
555 }
556 }
558 public void visitMethodDef(JCMethodDecl tree) {
559 Scope enclScope = enter.enterScope(env);
560 MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner);
561 m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree);
562 tree.sym = m;
564 //if this is a default method, add the DEFAULT flag to the enclosing interface
565 if ((tree.mods.flags & DEFAULT) != 0) {
566 m.enclClass().flags_field |= DEFAULT;
567 }
569 Env<AttrContext> localEnv = methodEnv(tree, env);
571 DeferredLintHandler prevLintHandler =
572 chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos()));
573 try {
574 // Compute the method type
575 m.type = signature(tree.typarams, tree.params,
576 tree.restype, tree.thrown,
577 localEnv);
578 } finally {
579 chk.setDeferredLintHandler(prevLintHandler);
580 }
582 // Set m.params
583 ListBuffer<VarSymbol> params = new ListBuffer<VarSymbol>();
584 JCVariableDecl lastParam = null;
585 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
586 JCVariableDecl param = lastParam = l.head;
587 params.append(Assert.checkNonNull(param.sym));
588 }
589 m.params = params.toList();
591 // mark the method varargs, if necessary
592 if (lastParam != null && (lastParam.mods.flags & Flags.VARARGS) != 0)
593 m.flags_field |= Flags.VARARGS;
595 localEnv.info.scope.leave();
596 if (chk.checkUnique(tree.pos(), m, enclScope)) {
597 enclScope.enter(m);
598 }
599 annotateLater(tree.mods.annotations, localEnv, m);
600 if (tree.defaultValue != null)
601 annotateDefaultValueLater(tree.defaultValue, localEnv, m);
602 }
604 /** Create a fresh environment for method bodies.
605 * @param tree The method definition.
606 * @param env The environment current outside of the method definition.
607 */
608 Env<AttrContext> methodEnv(JCMethodDecl tree, Env<AttrContext> env) {
609 Env<AttrContext> localEnv =
610 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
611 localEnv.enclMethod = tree;
612 localEnv.info.scope.owner = tree.sym;
613 if (tree.sym.type != null) {
614 //when this is called in the enter stage, there's no type to be set
615 localEnv.info.returnResult = attr.new ResultInfo(VAL, tree.sym.type.getReturnType());
616 }
617 if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++;
618 return localEnv;
619 }
621 public void visitVarDef(JCVariableDecl tree) {
622 Env<AttrContext> localEnv = env;
623 if ((tree.mods.flags & STATIC) != 0 ||
624 (env.info.scope.owner.flags() & INTERFACE) != 0) {
625 localEnv = env.dup(tree, env.info.dup());
626 localEnv.info.staticLevel++;
627 }
628 DeferredLintHandler prevLintHandler =
629 chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos()));
630 try {
631 if (TreeInfo.isEnumInit(tree)) {
632 attr.attribIdentAsEnumType(localEnv, (JCIdent)tree.vartype);
633 } else {
634 attr.attribType(tree.vartype, localEnv);
635 }
636 } finally {
637 chk.setDeferredLintHandler(prevLintHandler);
638 }
640 if ((tree.mods.flags & VARARGS) != 0) {
641 //if we are entering a varargs parameter, we need to replace its type
642 //(a plain array type) with the more precise VarargsType --- we need
643 //to do it this way because varargs is represented in the tree as a modifier
644 //on the parameter declaration, and not as a distinct type of array node.
645 ArrayType atype = (ArrayType)tree.vartype.type;
646 tree.vartype.type = atype.makeVarargs();
647 }
648 Scope enclScope = enter.enterScope(env);
649 VarSymbol v =
650 new VarSymbol(0, tree.name, tree.vartype.type, enclScope.owner);
651 v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree);
652 tree.sym = v;
653 if (tree.init != null) {
654 v.flags_field |= HASINIT;
655 if ((v.flags_field & FINAL) != 0 &&
656 !tree.init.hasTag(NEWCLASS) &&
657 !tree.init.hasTag(LAMBDA)) {
658 Env<AttrContext> initEnv = getInitEnv(tree, env);
659 initEnv.info.enclVar = v;
660 v.setLazyConstValue(initEnv(tree, initEnv), attr, tree.init);
661 }
662 }
663 if (chk.checkUnique(tree.pos(), v, enclScope)) {
664 chk.checkTransparentVar(tree.pos(), v, enclScope);
665 enclScope.enter(v);
666 }
667 annotateLater(tree.mods.annotations, localEnv, v);
668 v.pos = tree.pos;
669 }
671 /** Create a fresh environment for a variable's initializer.
672 * If the variable is a field, the owner of the environment's scope
673 * is be the variable itself, otherwise the owner is the method
674 * enclosing the variable definition.
675 *
676 * @param tree The variable definition.
677 * @param env The environment current outside of the variable definition.
678 */
679 Env<AttrContext> initEnv(JCVariableDecl tree, Env<AttrContext> env) {
680 Env<AttrContext> localEnv = env.dupto(new AttrContextEnv(tree, env.info.dup()));
681 if (tree.sym.owner.kind == TYP) {
682 localEnv.info.scope = env.info.scope.dupUnshared();
683 localEnv.info.scope.owner = tree.sym;
684 }
685 if ((tree.mods.flags & STATIC) != 0 ||
686 ((env.enclClass.sym.flags() & INTERFACE) != 0 && env.enclMethod == null))
687 localEnv.info.staticLevel++;
688 return localEnv;
689 }
691 /** Default member enter visitor method: do nothing
692 */
693 public void visitTree(JCTree tree) {
694 }
696 public void visitErroneous(JCErroneous tree) {
697 if (tree.errs != null)
698 memberEnter(tree.errs, env);
699 }
701 public Env<AttrContext> getMethodEnv(JCMethodDecl tree, Env<AttrContext> env) {
702 Env<AttrContext> mEnv = methodEnv(tree, env);
703 mEnv.info.lint = mEnv.info.lint.augment(tree.sym.annotations, tree.sym.flags());
704 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
705 mEnv.info.scope.enterIfAbsent(l.head.type.tsym);
706 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail)
707 mEnv.info.scope.enterIfAbsent(l.head.sym);
708 return mEnv;
709 }
711 public Env<AttrContext> getInitEnv(JCVariableDecl tree, Env<AttrContext> env) {
712 Env<AttrContext> iEnv = initEnv(tree, env);
713 return iEnv;
714 }
716 /* ********************************************************************
717 * Type completion
718 *********************************************************************/
720 Type attribImportType(JCTree tree, Env<AttrContext> env) {
721 Assert.check(completionEnabled);
722 try {
723 // To prevent deep recursion, suppress completion of some
724 // types.
725 completionEnabled = false;
726 return attr.attribType(tree, env);
727 } finally {
728 completionEnabled = true;
729 }
730 }
732 /* ********************************************************************
733 * Annotation processing
734 *********************************************************************/
736 /** Queue annotations for later processing. */
737 void annotateLater(final List<JCAnnotation> annotations,
738 final Env<AttrContext> localEnv,
739 final Symbol s) {
740 if (annotations.isEmpty()) {
741 return;
742 }
743 if (s.kind != PCK) {
744 s.annotations.reset(); // mark Annotations as incomplete for now
745 }
746 annotate.normal(new Annotate.Annotator() {
747 @Override
748 public String toString() {
749 return "annotate " + annotations + " onto " + s + " in " + s.owner;
750 }
752 @Override
753 public void enterAnnotation() {
754 Assert.check(s.kind == PCK || s.annotations.pendingCompletion());
755 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
756 try {
757 if (!s.annotations.isEmpty() &&
758 annotations.nonEmpty())
759 log.error(annotations.head.pos,
760 "already.annotated",
761 kindName(s), s);
762 enterAnnotations(annotations, localEnv, s);
763 } finally {
764 log.useSource(prev);
765 }
766 }
767 });
768 }
770 /**
771 * Check if a list of annotations contains a reference to
772 * java.lang.Deprecated.
773 **/
774 private boolean hasDeprecatedAnnotation(List<JCAnnotation> annotations) {
775 for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
776 JCAnnotation a = al.head;
777 if (a.annotationType.type == syms.deprecatedType && a.args.isEmpty())
778 return true;
779 }
780 return false;
781 }
783 /** Enter a set of annotations. */
784 private void enterAnnotations(List<JCAnnotation> annotations,
785 Env<AttrContext> env,
786 Symbol s) {
787 Map<TypeSymbol, ListBuffer<Attribute.Compound>> annotated =
788 new LinkedHashMap<TypeSymbol, ListBuffer<Attribute.Compound>>();
789 Map<Attribute.Compound, DiagnosticPosition> pos =
790 new HashMap<Attribute.Compound, DiagnosticPosition>();
792 for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
793 JCAnnotation a = al.head;
794 Attribute.Compound c = annotate.enterAnnotation(a,
795 syms.annotationType,
796 env);
797 if (c == null) {
798 continue;
799 }
801 if (annotated.containsKey(a.type.tsym)) {
802 if (source.allowRepeatedAnnotations()) {
803 ListBuffer<Attribute.Compound> l = annotated.get(a.type.tsym);
804 l = l.append(c);
805 annotated.put(a.type.tsym, l);
806 pos.put(c, a.pos());
807 } else {
808 log.error(a.pos(), "duplicate.annotation");
809 }
810 } else {
811 annotated.put(a.type.tsym, ListBuffer.of(c));
812 pos.put(c, a.pos());
813 }
815 // Note: @Deprecated has no effect on local variables and parameters
816 if (!c.type.isErroneous()
817 && s.owner.kind != MTH
818 && types.isSameType(c.type, syms.deprecatedType)) {
819 s.flags_field |= Flags.DEPRECATED;
820 }
821 }
823 s.annotations.setAttributesWithCompletion(
824 annotate.new AnnotateRepeatedContext(env, annotated, pos, log));
825 }
827 /** Queue processing of an attribute default value. */
828 void annotateDefaultValueLater(final JCExpression defaultValue,
829 final Env<AttrContext> localEnv,
830 final MethodSymbol m) {
831 annotate.normal(new Annotate.Annotator() {
832 @Override
833 public String toString() {
834 return "annotate " + m.owner + "." +
835 m + " default " + defaultValue;
836 }
838 @Override
839 public void enterAnnotation() {
840 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
841 try {
842 enterDefaultValue(defaultValue, localEnv, m);
843 } finally {
844 log.useSource(prev);
845 }
846 }
847 });
848 }
850 /** Enter a default value for an attribute method. */
851 private void enterDefaultValue(final JCExpression defaultValue,
852 final Env<AttrContext> localEnv,
853 final MethodSymbol m) {
854 m.defaultValue = annotate.enterAttributeValue(m.type.getReturnType(),
855 defaultValue,
856 localEnv);
857 }
859 /* ********************************************************************
860 * Source completer
861 *********************************************************************/
863 /** Complete entering a class.
864 * @param sym The symbol of the class to be completed.
865 */
866 public void complete(Symbol sym) throws CompletionFailure {
867 // Suppress some (recursive) MemberEnter invocations
868 if (!completionEnabled) {
869 // Re-install same completer for next time around and return.
870 Assert.check((sym.flags() & Flags.COMPOUND) == 0);
871 sym.completer = this;
872 return;
873 }
875 ClassSymbol c = (ClassSymbol)sym;
876 ClassType ct = (ClassType)c.type;
877 Env<AttrContext> env = enter.typeEnvs.get(c);
878 JCClassDecl tree = (JCClassDecl)env.tree;
879 boolean wasFirst = isFirst;
880 isFirst = false;
882 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
883 try {
884 // Save class environment for later member enter (2) processing.
885 halfcompleted.append(env);
887 // Mark class as not yet attributed.
888 c.flags_field |= UNATTRIBUTED;
890 // If this is a toplevel-class, make sure any preceding import
891 // clauses have been seen.
892 if (c.owner.kind == PCK) {
893 memberEnter(env.toplevel, env.enclosing(TOPLEVEL));
894 todo.append(env);
895 }
897 if (c.owner.kind == TYP)
898 c.owner.complete();
900 // create an environment for evaluating the base clauses
901 Env<AttrContext> baseEnv = baseEnv(tree, env);
903 // Determine supertype.
904 Type supertype =
905 (tree.extending != null)
906 ? attr.attribBase(tree.extending, baseEnv, true, false, true)
907 : ((tree.mods.flags & Flags.ENUM) != 0 && !target.compilerBootstrap(c))
908 ? attr.attribBase(enumBase(tree.pos, c), baseEnv,
909 true, false, false)
910 : (c.fullname == names.java_lang_Object)
911 ? Type.noType
912 : syms.objectType;
913 ct.supertype_field = modelMissingTypes(supertype, tree.extending, false);
915 // Determine interfaces.
916 ListBuffer<Type> interfaces = new ListBuffer<Type>();
917 ListBuffer<Type> all_interfaces = null; // lazy init
918 Set<Type> interfaceSet = new HashSet<Type>();
919 List<JCExpression> interfaceTrees = tree.implementing;
920 if ((tree.mods.flags & Flags.ENUM) != 0 && target.compilerBootstrap(c)) {
921 // add interface Comparable<T>
922 interfaceTrees =
923 interfaceTrees.prepend(make.Type(new ClassType(syms.comparableType.getEnclosingType(),
924 List.of(c.type),
925 syms.comparableType.tsym)));
926 // add interface Serializable
927 interfaceTrees =
928 interfaceTrees.prepend(make.Type(syms.serializableType));
929 }
930 for (JCExpression iface : interfaceTrees) {
931 Type i = attr.attribBase(iface, baseEnv, false, true, true);
932 if (i.hasTag(CLASS)) {
933 interfaces.append(i);
934 if (all_interfaces != null) all_interfaces.append(i);
935 chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet);
936 } else {
937 if (all_interfaces == null)
938 all_interfaces = new ListBuffer<Type>().appendList(interfaces);
939 all_interfaces.append(modelMissingTypes(i, iface, true));
940 }
941 }
942 if ((c.flags_field & ANNOTATION) != 0) {
943 ct.interfaces_field = List.of(syms.annotationType);
944 ct.all_interfaces_field = ct.interfaces_field;
945 } else {
946 ct.interfaces_field = interfaces.toList();
947 ct.all_interfaces_field = (all_interfaces == null)
948 ? ct.interfaces_field : all_interfaces.toList();
949 }
951 if (c.fullname == names.java_lang_Object) {
952 if (tree.extending != null) {
953 chk.checkNonCyclic(tree.extending.pos(),
954 supertype);
955 ct.supertype_field = Type.noType;
956 }
957 else if (tree.implementing.nonEmpty()) {
958 chk.checkNonCyclic(tree.implementing.head.pos(),
959 ct.interfaces_field.head);
960 ct.interfaces_field = List.nil();
961 }
962 }
964 // Annotations.
965 // In general, we cannot fully process annotations yet, but we
966 // can attribute the annotation types and then check to see if the
967 // @Deprecated annotation is present.
968 attr.attribAnnotationTypes(tree.mods.annotations, baseEnv);
969 if (hasDeprecatedAnnotation(tree.mods.annotations))
970 c.flags_field |= DEPRECATED;
971 annotateLater(tree.mods.annotations, baseEnv, c);
973 chk.checkNonCyclicDecl(tree);
975 attr.attribTypeVariables(tree.typarams, baseEnv);
977 // Add default constructor if needed.
978 if ((c.flags() & INTERFACE) == 0 &&
979 !TreeInfo.hasConstructors(tree.defs)) {
980 List<Type> argtypes = List.nil();
981 List<Type> typarams = List.nil();
982 List<Type> thrown = List.nil();
983 long ctorFlags = 0;
984 boolean based = false;
985 boolean addConstructor = true;
986 if (c.name.isEmpty()) {
987 JCNewClass nc = (JCNewClass)env.next.tree;
988 if (nc.constructor != null) {
989 addConstructor = nc.constructor.kind != ERR;
990 Type superConstrType = types.memberType(c.type,
991 nc.constructor);
992 argtypes = superConstrType.getParameterTypes();
993 typarams = superConstrType.getTypeArguments();
994 ctorFlags = nc.constructor.flags() & VARARGS;
995 if (nc.encl != null) {
996 argtypes = argtypes.prepend(nc.encl.type);
997 based = true;
998 }
999 thrown = superConstrType.getThrownTypes();
1000 }
1001 }
1002 if (addConstructor) {
1003 JCTree constrDef = DefaultConstructor(make.at(tree.pos), c,
1004 typarams, argtypes, thrown,
1005 ctorFlags, based);
1006 tree.defs = tree.defs.prepend(constrDef);
1007 }
1008 }
1010 // enter symbols for 'this' into current scope.
1011 VarSymbol thisSym =
1012 new VarSymbol(FINAL | HASINIT, names._this, c.type, c);
1013 thisSym.pos = Position.FIRSTPOS;
1014 env.info.scope.enter(thisSym);
1015 // if this is a class, enter symbol for 'super' into current scope.
1016 if ((c.flags_field & INTERFACE) == 0 &&
1017 ct.supertype_field.hasTag(CLASS)) {
1018 VarSymbol superSym =
1019 new VarSymbol(FINAL | HASINIT, names._super,
1020 ct.supertype_field, c);
1021 superSym.pos = Position.FIRSTPOS;
1022 env.info.scope.enter(superSym);
1023 }
1025 // check that no package exists with same fully qualified name,
1026 // but admit classes in the unnamed package which have the same
1027 // name as a top-level package.
1028 if (checkClash &&
1029 c.owner.kind == PCK && c.owner != syms.unnamedPackage &&
1030 reader.packageExists(c.fullname)) {
1031 log.error(tree.pos, "clash.with.pkg.of.same.name", Kinds.kindName(sym), c);
1032 }
1033 if (c.owner.kind == PCK && (c.flags_field & PUBLIC) == 0 &&
1034 !env.toplevel.sourcefile.isNameCompatible(c.name.toString(),JavaFileObject.Kind.SOURCE)) {
1035 c.flags_field |= AUXILIARY;
1036 }
1037 } catch (CompletionFailure ex) {
1038 chk.completionError(tree.pos(), ex);
1039 } finally {
1040 log.useSource(prev);
1041 }
1043 // Enter all member fields and methods of a set of half completed
1044 // classes in a second phase.
1045 if (wasFirst) {
1046 try {
1047 while (halfcompleted.nonEmpty()) {
1048 finish(halfcompleted.next());
1049 }
1050 } finally {
1051 isFirst = true;
1052 }
1054 // commit pending annotations
1055 annotate.flush();
1056 }
1057 }
1059 private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
1060 Scope baseScope = new Scope(tree.sym);
1061 //import already entered local classes into base scope
1062 for (Scope.Entry e = env.outer.info.scope.elems ; e != null ; e = e.sibling) {
1063 if (e.sym.isLocal()) {
1064 baseScope.enter(e.sym);
1065 }
1066 }
1067 //import current type-parameters into base scope
1068 if (tree.typarams != null)
1069 for (List<JCTypeParameter> typarams = tree.typarams;
1070 typarams.nonEmpty();
1071 typarams = typarams.tail)
1072 baseScope.enter(typarams.head.type.tsym);
1073 Env<AttrContext> outer = env.outer; // the base clause can't see members of this class
1074 Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(baseScope));
1075 localEnv.baseClause = true;
1076 localEnv.outer = outer;
1077 localEnv.info.isSelfCall = false;
1078 return localEnv;
1079 }
1081 /** Enter member fields and methods of a class
1082 * @param env the environment current for the class block.
1083 */
1084 private void finish(Env<AttrContext> env) {
1085 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
1086 try {
1087 JCClassDecl tree = (JCClassDecl)env.tree;
1088 finishClass(tree, env);
1089 } finally {
1090 log.useSource(prev);
1091 }
1092 }
1094 /** Generate a base clause for an enum type.
1095 * @param pos The position for trees and diagnostics, if any
1096 * @param c The class symbol of the enum
1097 */
1098 private JCExpression enumBase(int pos, ClassSymbol c) {
1099 JCExpression result = make.at(pos).
1100 TypeApply(make.QualIdent(syms.enumSym),
1101 List.<JCExpression>of(make.Type(c.type)));
1102 return result;
1103 }
1105 Type modelMissingTypes(Type t, final JCExpression tree, final boolean interfaceExpected) {
1106 if (!t.hasTag(ERROR))
1107 return t;
1109 return new ErrorType(((ErrorType) t).getOriginalType(), t.tsym) {
1110 private Type modelType;
1112 @Override
1113 public Type getModelType() {
1114 if (modelType == null)
1115 modelType = new Synthesizer(getOriginalType(), interfaceExpected).visit(tree);
1116 return modelType;
1117 }
1118 };
1119 }
1120 // where
1121 private class Synthesizer extends JCTree.Visitor {
1122 Type originalType;
1123 boolean interfaceExpected;
1124 List<ClassSymbol> synthesizedSymbols = List.nil();
1125 Type result;
1127 Synthesizer(Type originalType, boolean interfaceExpected) {
1128 this.originalType = originalType;
1129 this.interfaceExpected = interfaceExpected;
1130 }
1132 Type visit(JCTree tree) {
1133 tree.accept(this);
1134 return result;
1135 }
1137 List<Type> visit(List<? extends JCTree> trees) {
1138 ListBuffer<Type> lb = new ListBuffer<Type>();
1139 for (JCTree t: trees)
1140 lb.append(visit(t));
1141 return lb.toList();
1142 }
1144 @Override
1145 public void visitTree(JCTree tree) {
1146 result = syms.errType;
1147 }
1149 @Override
1150 public void visitIdent(JCIdent tree) {
1151 if (!tree.type.hasTag(ERROR)) {
1152 result = tree.type;
1153 } else {
1154 result = synthesizeClass(tree.name, syms.unnamedPackage).type;
1155 }
1156 }
1158 @Override
1159 public void visitSelect(JCFieldAccess tree) {
1160 if (!tree.type.hasTag(ERROR)) {
1161 result = tree.type;
1162 } else {
1163 Type selectedType;
1164 boolean prev = interfaceExpected;
1165 try {
1166 interfaceExpected = false;
1167 selectedType = visit(tree.selected);
1168 } finally {
1169 interfaceExpected = prev;
1170 }
1171 ClassSymbol c = synthesizeClass(tree.name, selectedType.tsym);
1172 result = c.type;
1173 }
1174 }
1176 @Override
1177 public void visitTypeApply(JCTypeApply tree) {
1178 if (!tree.type.hasTag(ERROR)) {
1179 result = tree.type;
1180 } else {
1181 ClassType clazzType = (ClassType) visit(tree.clazz);
1182 if (synthesizedSymbols.contains(clazzType.tsym))
1183 synthesizeTyparams((ClassSymbol) clazzType.tsym, tree.arguments.size());
1184 final List<Type> actuals = visit(tree.arguments);
1185 result = new ErrorType(tree.type, clazzType.tsym) {
1186 @Override
1187 public List<Type> getTypeArguments() {
1188 return actuals;
1189 }
1190 };
1191 }
1192 }
1194 ClassSymbol synthesizeClass(Name name, Symbol owner) {
1195 int flags = interfaceExpected ? INTERFACE : 0;
1196 ClassSymbol c = new ClassSymbol(flags, name, owner);
1197 c.members_field = new Scope.ErrorScope(c);
1198 c.type = new ErrorType(originalType, c) {
1199 @Override
1200 public List<Type> getTypeArguments() {
1201 return typarams_field;
1202 }
1203 };
1204 synthesizedSymbols = synthesizedSymbols.prepend(c);
1205 return c;
1206 }
1208 void synthesizeTyparams(ClassSymbol sym, int n) {
1209 ClassType ct = (ClassType) sym.type;
1210 Assert.check(ct.typarams_field.isEmpty());
1211 if (n == 1) {
1212 TypeVar v = new TypeVar(names.fromString("T"), sym, syms.botType);
1213 ct.typarams_field = ct.typarams_field.prepend(v);
1214 } else {
1215 for (int i = n; i > 0; i--) {
1216 TypeVar v = new TypeVar(names.fromString("T" + i), sym, syms.botType);
1217 ct.typarams_field = ct.typarams_field.prepend(v);
1218 }
1219 }
1220 }
1221 }
1224 /* ***************************************************************************
1225 * tree building
1226 ****************************************************************************/
1228 /** Generate default constructor for given class. For classes different
1229 * from java.lang.Object, this is:
1230 *
1231 * c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
1232 * super(x_0, ..., x_n)
1233 * }
1234 *
1235 * or, if based == true:
1236 *
1237 * c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
1238 * x_0.super(x_1, ..., x_n)
1239 * }
1240 *
1241 * @param make The tree factory.
1242 * @param c The class owning the default constructor.
1243 * @param argtypes The parameter types of the constructor.
1244 * @param thrown The thrown exceptions of the constructor.
1245 * @param based Is first parameter a this$n?
1246 */
1247 JCTree DefaultConstructor(TreeMaker make,
1248 ClassSymbol c,
1249 List<Type> typarams,
1250 List<Type> argtypes,
1251 List<Type> thrown,
1252 long flags,
1253 boolean based) {
1254 List<JCVariableDecl> params = make.Params(argtypes, syms.noSymbol);
1255 List<JCStatement> stats = List.nil();
1256 if (c.type != syms.objectType)
1257 stats = stats.prepend(SuperCall(make, typarams, params, based));
1258 if ((c.flags() & ENUM) != 0 &&
1259 (types.supertype(c.type).tsym == syms.enumSym ||
1260 target.compilerBootstrap(c))) {
1261 // constructors of true enums are private
1262 flags = (flags & ~AccessFlags) | PRIVATE | GENERATEDCONSTR;
1263 } else
1264 flags |= (c.flags() & AccessFlags) | GENERATEDCONSTR;
1265 if (c.name.isEmpty()) flags |= ANONCONSTR;
1266 JCTree result = make.MethodDef(
1267 make.Modifiers(flags),
1268 names.init,
1269 null,
1270 make.TypeParams(typarams),
1271 params,
1272 make.Types(thrown),
1273 make.Block(0, stats),
1274 null);
1275 return result;
1276 }
1278 /** Generate call to superclass constructor. This is:
1279 *
1280 * super(id_0, ..., id_n)
1281 *
1282 * or, if based == true
1283 *
1284 * id_0.super(id_1,...,id_n)
1285 *
1286 * where id_0, ..., id_n are the names of the given parameters.
1287 *
1288 * @param make The tree factory
1289 * @param params The parameters that need to be passed to super
1290 * @param typarams The type parameters that need to be passed to super
1291 * @param based Is first parameter a this$n?
1292 */
1293 JCExpressionStatement SuperCall(TreeMaker make,
1294 List<Type> typarams,
1295 List<JCVariableDecl> params,
1296 boolean based) {
1297 JCExpression meth;
1298 if (based) {
1299 meth = make.Select(make.Ident(params.head), names._super);
1300 params = params.tail;
1301 } else {
1302 meth = make.Ident(names._super);
1303 }
1304 List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null;
1305 return make.Exec(make.Apply(typeargs, meth, make.Idents(params)));
1306 }
1307 }