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