Mon, 03 Jun 2013 17:09:26 -0700
8006615: [doclint] move remaining messages into resource bundle
Reviewed-by: mcimadamore, vromero
1 /*
2 * Copyright (c) 2003, 2013, 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.HashMap;
29 import java.util.HashSet;
30 import java.util.LinkedHashMap;
31 import java.util.Map;
32 import java.util.Set;
34 import javax.tools.JavaFileObject;
36 import com.sun.tools.javac.code.*;
37 import com.sun.tools.javac.jvm.*;
38 import com.sun.tools.javac.tree.*;
39 import com.sun.tools.javac.util.*;
41 import com.sun.tools.javac.code.Type.*;
42 import com.sun.tools.javac.code.Symbol.*;
43 import com.sun.tools.javac.tree.JCTree.*;
45 import static com.sun.tools.javac.code.Flags.*;
46 import static com.sun.tools.javac.code.Flags.ANNOTATION;
47 import static com.sun.tools.javac.code.Kinds.*;
48 import static com.sun.tools.javac.code.TypeTag.CLASS;
49 import static com.sun.tools.javac.code.TypeTag.ERROR;
50 import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
51 import static com.sun.tools.javac.tree.JCTree.Tag.*;
52 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
53 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
55 /** This is the second phase of Enter, in which classes are completed
56 * by entering their members into the class scope using
57 * MemberEnter.complete(). See Enter for an overview.
58 *
59 * <p><b>This is NOT part of any supported API.
60 * If you write code that depends on this, you do so at your own risk.
61 * This code and its internal interfaces are subject to change or
62 * deletion without notice.</b>
63 */
64 public class MemberEnter extends JCTree.Visitor implements Completer {
65 protected static final Context.Key<MemberEnter> memberEnterKey =
66 new Context.Key<MemberEnter>();
68 /** A switch to determine whether we check for package/class conflicts
69 */
70 final static boolean checkClash = true;
72 private final Names names;
73 private final Enter enter;
74 private final Log log;
75 private final Check chk;
76 private final Attr attr;
77 private final Symtab syms;
78 private final TreeMaker make;
79 private final ClassReader reader;
80 private final Todo todo;
81 private final Annotate annotate;
82 private final Types types;
83 private final JCDiagnostic.Factory diags;
84 private final Source source;
85 private final Target target;
86 private final DeferredLintHandler deferredLintHandler;
88 public static MemberEnter instance(Context context) {
89 MemberEnter instance = context.get(memberEnterKey);
90 if (instance == null)
91 instance = new MemberEnter(context);
92 return instance;
93 }
95 protected MemberEnter(Context context) {
96 context.put(memberEnterKey, this);
97 names = Names.instance(context);
98 enter = Enter.instance(context);
99 log = Log.instance(context);
100 chk = Check.instance(context);
101 attr = Attr.instance(context);
102 syms = Symtab.instance(context);
103 make = TreeMaker.instance(context);
104 reader = ClassReader.instance(context);
105 todo = Todo.instance(context);
106 annotate = Annotate.instance(context);
107 types = Types.instance(context);
108 diags = JCDiagnostic.Factory.instance(context);
109 source = Source.instance(context);
110 target = Target.instance(context);
111 deferredLintHandler = DeferredLintHandler.instance(context);
112 }
114 /** A queue for classes whose members still need to be entered into the
115 * symbol table.
116 */
117 ListBuffer<Env<AttrContext>> halfcompleted = new ListBuffer<Env<AttrContext>>();
119 /** Set to true only when the first of a set of classes is
120 * processed from the halfcompleted queue.
121 */
122 boolean isFirst = true;
124 /** A flag to disable completion from time to time during member
125 * enter, as we only need to look up types. This avoids
126 * unnecessarily deep recursion.
127 */
128 boolean completionEnabled = true;
130 /* ---------- Processing import clauses ----------------
131 */
133 /** Import all classes of a class or package on demand.
134 * @param pos Position to be used for error reporting.
135 * @param tsym The class or package the members of which are imported.
136 * @param env The env in which the imported classes will be entered.
137 */
138 private void importAll(int pos,
139 final TypeSymbol tsym,
140 Env<AttrContext> env) {
141 // Check that packages imported from exist (JLS ???).
142 if (tsym.kind == PCK && tsym.members().elems == null && !tsym.exists()) {
143 // If we can't find java.lang, exit immediately.
144 if (((PackageSymbol)tsym).fullname.equals(names.java_lang)) {
145 JCDiagnostic msg = diags.fragment("fatal.err.no.java.lang");
146 throw new FatalError(msg);
147 } else {
148 log.error(DiagnosticFlag.RESOLVE_ERROR, pos, "doesnt.exist", tsym);
149 }
150 }
151 env.toplevel.starImportScope.importAll(tsym.members());
152 }
154 /** Import all static members of a class or package on demand.
155 * @param pos Position to be used for error reporting.
156 * @param tsym The class or package the members of which are imported.
157 * @param env The env in which the imported classes will be entered.
158 */
159 private void importStaticAll(int pos,
160 final TypeSymbol tsym,
161 Env<AttrContext> env) {
162 final JavaFileObject sourcefile = env.toplevel.sourcefile;
163 final Scope toScope = env.toplevel.starImportScope;
164 final PackageSymbol packge = env.toplevel.packge;
165 final TypeSymbol origin = tsym;
167 // enter imported types immediately
168 new Object() {
169 Set<Symbol> processed = new HashSet<Symbol>();
170 void importFrom(TypeSymbol tsym) {
171 if (tsym == null || !processed.add(tsym))
172 return;
174 // also import inherited names
175 importFrom(types.supertype(tsym.type).tsym);
176 for (Type t : types.interfaces(tsym.type))
177 importFrom(t.tsym);
179 final Scope fromScope = tsym.members();
180 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
181 Symbol sym = e.sym;
182 if (sym.kind == TYP &&
183 (sym.flags() & STATIC) != 0 &&
184 staticImportAccessible(sym, packge) &&
185 sym.isMemberOf(origin, types) &&
186 !toScope.includes(sym))
187 toScope.enter(sym, fromScope, origin.members());
188 }
189 }
190 }.importFrom(tsym);
192 // enter non-types before annotations that might use them
193 annotate.earlier(new Annotate.Annotator() {
194 Set<Symbol> processed = new HashSet<Symbol>();
196 public String toString() {
197 return "import static " + tsym + ".*" + " in " + sourcefile;
198 }
199 void importFrom(TypeSymbol tsym) {
200 if (tsym == null || !processed.add(tsym))
201 return;
203 // also import inherited names
204 importFrom(types.supertype(tsym.type).tsym);
205 for (Type t : types.interfaces(tsym.type))
206 importFrom(t.tsym);
208 final Scope fromScope = tsym.members();
209 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
210 Symbol sym = e.sym;
211 if (sym.isStatic() && sym.kind != TYP &&
212 staticImportAccessible(sym, packge) &&
213 !toScope.includes(sym) &&
214 sym.isMemberOf(origin, types)) {
215 toScope.enter(sym, fromScope, origin.members());
216 }
217 }
218 }
219 public void enterAnnotation() {
220 importFrom(tsym);
221 }
222 });
223 }
225 // is the sym accessible everywhere in packge?
226 boolean staticImportAccessible(Symbol sym, PackageSymbol packge) {
227 int flags = (int)(sym.flags() & AccessFlags);
228 switch (flags) {
229 default:
230 case PUBLIC:
231 return true;
232 case PRIVATE:
233 return false;
234 case 0:
235 case PROTECTED:
236 return sym.packge() == packge;
237 }
238 }
240 /** Import statics types of a given name. Non-types are handled in Attr.
241 * @param pos Position to be used for error reporting.
242 * @param tsym The class from which the name is imported.
243 * @param name The (simple) name being imported.
244 * @param env The environment containing the named import
245 * scope to add to.
246 */
247 private void importNamedStatic(final DiagnosticPosition pos,
248 final TypeSymbol tsym,
249 final Name name,
250 final Env<AttrContext> env) {
251 if (tsym.kind != TYP) {
252 log.error(DiagnosticFlag.RECOVERABLE, pos, "static.imp.only.classes.and.interfaces");
253 return;
254 }
256 final Scope toScope = env.toplevel.namedImportScope;
257 final PackageSymbol packge = env.toplevel.packge;
258 final TypeSymbol origin = tsym;
260 // enter imported types immediately
261 new Object() {
262 Set<Symbol> processed = new HashSet<Symbol>();
263 void importFrom(TypeSymbol tsym) {
264 if (tsym == null || !processed.add(tsym))
265 return;
267 // also import inherited names
268 importFrom(types.supertype(tsym.type).tsym);
269 for (Type t : types.interfaces(tsym.type))
270 importFrom(t.tsym);
272 for (Scope.Entry e = tsym.members().lookup(name);
273 e.scope != null;
274 e = e.next()) {
275 Symbol sym = e.sym;
276 if (sym.isStatic() &&
277 sym.kind == TYP &&
278 staticImportAccessible(sym, packge) &&
279 sym.isMemberOf(origin, types) &&
280 chk.checkUniqueStaticImport(pos, sym, toScope))
281 toScope.enter(sym, sym.owner.members(), origin.members());
282 }
283 }
284 }.importFrom(tsym);
286 // enter non-types before annotations that might use them
287 annotate.earlier(new Annotate.Annotator() {
288 Set<Symbol> processed = new HashSet<Symbol>();
289 boolean found = false;
291 public String toString() {
292 return "import static " + tsym + "." + name;
293 }
294 void importFrom(TypeSymbol tsym) {
295 if (tsym == null || !processed.add(tsym))
296 return;
298 // also import inherited names
299 importFrom(types.supertype(tsym.type).tsym);
300 for (Type t : types.interfaces(tsym.type))
301 importFrom(t.tsym);
303 for (Scope.Entry e = tsym.members().lookup(name);
304 e.scope != null;
305 e = e.next()) {
306 Symbol sym = e.sym;
307 if (sym.isStatic() &&
308 staticImportAccessible(sym, packge) &&
309 sym.isMemberOf(origin, types)) {
310 found = true;
311 if (sym.kind == MTH ||
312 sym.kind != TYP && chk.checkUniqueStaticImport(pos, sym, toScope))
313 toScope.enter(sym, sym.owner.members(), origin.members());
314 }
315 }
316 }
317 public void enterAnnotation() {
318 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
319 try {
320 importFrom(tsym);
321 if (!found) {
322 log.error(pos, "cant.resolve.location",
323 KindName.STATIC,
324 name, List.<Type>nil(), List.<Type>nil(),
325 Kinds.typeKindName(tsym.type),
326 tsym.type);
327 }
328 } finally {
329 log.useSource(prev);
330 }
331 }
332 });
333 }
334 /** Import given class.
335 * @param pos Position to be used for error reporting.
336 * @param tsym The class to be imported.
337 * @param env The environment containing the named import
338 * scope to add to.
339 */
340 private void importNamed(DiagnosticPosition pos, Symbol tsym, Env<AttrContext> env) {
341 if (tsym.kind == TYP &&
342 chk.checkUniqueImport(pos, tsym, env.toplevel.namedImportScope))
343 env.toplevel.namedImportScope.enter(tsym, tsym.owner.members());
344 }
346 /** Construct method type from method signature.
347 * @param typarams The method's type parameters.
348 * @param params The method's value parameters.
349 * @param res The method's result type,
350 * null if it is a constructor.
351 * @param recvparam The method's receiver parameter,
352 * null if none given; TODO: or already set here?
353 * @param thrown The method's thrown exceptions.
354 * @param env The method's (local) environment.
355 */
356 Type signature(List<JCTypeParameter> typarams,
357 List<JCVariableDecl> params,
358 JCTree res,
359 JCVariableDecl recvparam,
360 List<JCExpression> thrown,
361 Env<AttrContext> env) {
363 // Enter and attribute type parameters.
364 List<Type> tvars = enter.classEnter(typarams, env);
365 attr.attribTypeVariables(typarams, env);
367 // Enter and attribute value parameters.
368 ListBuffer<Type> argbuf = new ListBuffer<Type>();
369 for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) {
370 memberEnter(l.head, env);
371 argbuf.append(l.head.vartype.type);
372 }
374 // Attribute result type, if one is given.
375 Type restype = res == null ? syms.voidType : attr.attribType(res, env);
377 // Attribute receiver type, if one is given.
378 Type recvtype;
379 if (recvparam!=null) {
380 memberEnter(recvparam, env);
381 recvtype = recvparam.vartype.type;
382 } else {
383 recvtype = null;
384 }
386 // Attribute thrown exceptions.
387 ListBuffer<Type> thrownbuf = new ListBuffer<Type>();
388 for (List<JCExpression> l = thrown; l.nonEmpty(); l = l.tail) {
389 Type exc = attr.attribType(l.head, env);
390 if (!exc.hasTag(TYPEVAR))
391 exc = chk.checkClassType(l.head.pos(), exc);
392 thrownbuf.append(exc);
393 }
394 MethodType mtype = new MethodType(argbuf.toList(),
395 restype,
396 thrownbuf.toList(),
397 syms.methodClass);
398 mtype.recvtype = recvtype;
400 return tvars.isEmpty() ? mtype : new ForAll(tvars, mtype);
401 }
403 /* ********************************************************************
404 * Visitor methods for member enter
405 *********************************************************************/
407 /** Visitor argument: the current environment
408 */
409 protected Env<AttrContext> env;
411 /** Enter field and method definitions and process import
412 * clauses, catching any completion failure exceptions.
413 */
414 protected void memberEnter(JCTree tree, Env<AttrContext> env) {
415 Env<AttrContext> prevEnv = this.env;
416 try {
417 this.env = env;
418 tree.accept(this);
419 } catch (CompletionFailure ex) {
420 chk.completionError(tree.pos(), ex);
421 } finally {
422 this.env = prevEnv;
423 }
424 }
426 /** Enter members from a list of trees.
427 */
428 void memberEnter(List<? extends JCTree> trees, Env<AttrContext> env) {
429 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
430 memberEnter(l.head, env);
431 }
433 /** Enter members for a class.
434 */
435 void finishClass(JCClassDecl tree, Env<AttrContext> env) {
436 if ((tree.mods.flags & Flags.ENUM) != 0 &&
437 (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
438 addEnumMembers(tree, env);
439 }
440 memberEnter(tree.defs, env);
441 }
443 /** Add the implicit members for an enum type
444 * to the symbol table.
445 */
446 private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
447 JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass));
449 // public static T[] values() { return ???; }
450 JCMethodDecl values = make.
451 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
452 names.values,
453 valuesType,
454 List.<JCTypeParameter>nil(),
455 List.<JCVariableDecl>nil(),
456 List.<JCExpression>nil(), // thrown
457 null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
458 null);
459 memberEnter(values, env);
461 // public static T valueOf(String name) { return ???; }
462 JCMethodDecl valueOf = make.
463 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
464 names.valueOf,
465 make.Type(tree.sym.type),
466 List.<JCTypeParameter>nil(),
467 List.of(make.VarDef(make.Modifiers(Flags.PARAMETER |
468 Flags.MANDATED),
469 names.fromString("name"),
470 make.Type(syms.stringType), null)),
471 List.<JCExpression>nil(), // thrown
472 null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
473 null);
474 memberEnter(valueOf, env);
475 }
477 public void visitTopLevel(JCCompilationUnit tree) {
478 if (tree.starImportScope.elems != null) {
479 // we must have already processed this toplevel
480 return;
481 }
483 // check that no class exists with same fully qualified name as
484 // toplevel package
485 if (checkClash && tree.pid != null) {
486 Symbol p = tree.packge;
487 while (p.owner != syms.rootPackage) {
488 p.owner.complete(); // enter all class members of p
489 if (syms.classes.get(p.getQualifiedName()) != null) {
490 log.error(tree.pos,
491 "pkg.clashes.with.class.of.same.name",
492 p);
493 }
494 p = p.owner;
495 }
496 }
498 // process package annotations
499 annotateLater(tree.packageAnnotations, env, tree.packge);
501 // Import-on-demand java.lang.
502 importAll(tree.pos, reader.enterPackage(names.java_lang), env);
504 // Process all import clauses.
505 memberEnter(tree.defs, env);
506 }
508 // process the non-static imports and the static imports of types.
509 public void visitImport(JCImport tree) {
510 JCFieldAccess imp = (JCFieldAccess)tree.qualid;
511 Name name = TreeInfo.name(imp);
513 // Create a local environment pointing to this tree to disable
514 // effects of other imports in Resolve.findGlobalType
515 Env<AttrContext> localEnv = env.dup(tree);
517 TypeSymbol p = attr.attribImportQualifier(tree, localEnv).tsym;
518 if (name == names.asterisk) {
519 // Import on demand.
520 chk.checkCanonical(imp.selected);
521 if (tree.staticImport)
522 importStaticAll(tree.pos, p, env);
523 else
524 importAll(tree.pos, p, env);
525 } else {
526 // Named type import.
527 if (tree.staticImport) {
528 importNamedStatic(tree.pos(), p, name, localEnv);
529 chk.checkCanonical(imp.selected);
530 } else {
531 TypeSymbol c = attribImportType(imp, localEnv).tsym;
532 chk.checkCanonical(imp);
533 importNamed(tree.pos(), c, env);
534 }
535 }
536 }
538 public void visitMethodDef(JCMethodDecl tree) {
539 Scope enclScope = enter.enterScope(env);
540 MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner);
541 m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree);
542 tree.sym = m;
544 //if this is a default method, add the DEFAULT flag to the enclosing interface
545 if ((tree.mods.flags & DEFAULT) != 0) {
546 m.enclClass().flags_field |= DEFAULT;
547 }
549 Env<AttrContext> localEnv = methodEnv(tree, env);
551 DeferredLintHandler prevLintHandler =
552 chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos()));
553 try {
554 // Compute the method type
555 m.type = signature(tree.typarams, tree.params,
556 tree.restype, tree.recvparam,
557 tree.thrown,
558 localEnv);
559 } finally {
560 chk.setDeferredLintHandler(prevLintHandler);
561 }
563 // Set m.params
564 ListBuffer<VarSymbol> params = new ListBuffer<VarSymbol>();
565 JCVariableDecl lastParam = null;
566 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
567 JCVariableDecl param = lastParam = l.head;
568 params.append(Assert.checkNonNull(param.sym));
569 }
570 m.params = params.toList();
572 // mark the method varargs, if necessary
573 if (lastParam != null && (lastParam.mods.flags & Flags.VARARGS) != 0)
574 m.flags_field |= Flags.VARARGS;
576 localEnv.info.scope.leave();
577 if (chk.checkUnique(tree.pos(), m, enclScope)) {
578 enclScope.enter(m);
579 }
580 annotateLater(tree.mods.annotations, localEnv, m);
581 // Visit the signature of the method. Note that
582 // TypeAnnotate doesn't descend into the body.
583 typeAnnotate(tree, localEnv, m);
585 if (tree.defaultValue != null)
586 annotateDefaultValueLater(tree.defaultValue, localEnv, m);
587 }
589 /** Create a fresh environment for method bodies.
590 * @param tree The method definition.
591 * @param env The environment current outside of the method definition.
592 */
593 Env<AttrContext> methodEnv(JCMethodDecl tree, Env<AttrContext> env) {
594 Env<AttrContext> localEnv =
595 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
596 localEnv.enclMethod = tree;
597 localEnv.info.scope.owner = tree.sym;
598 if (tree.sym.type != null) {
599 //when this is called in the enter stage, there's no type to be set
600 localEnv.info.returnResult = attr.new ResultInfo(VAL, tree.sym.type.getReturnType());
601 }
602 if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++;
603 return localEnv;
604 }
606 public void visitVarDef(JCVariableDecl tree) {
607 Env<AttrContext> localEnv = env;
608 if ((tree.mods.flags & STATIC) != 0 ||
609 (env.info.scope.owner.flags() & INTERFACE) != 0) {
610 localEnv = env.dup(tree, env.info.dup());
611 localEnv.info.staticLevel++;
612 }
613 DeferredLintHandler prevLintHandler =
614 chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos()));
615 try {
616 if (TreeInfo.isEnumInit(tree)) {
617 attr.attribIdentAsEnumType(localEnv, (JCIdent)tree.vartype);
618 } else {
619 // Make sure type annotations are processed.
620 // But we don't have a symbol to attach them to yet - use null.
621 typeAnnotate(tree.vartype, env, null);
622 attr.attribType(tree.vartype, localEnv);
623 if (tree.nameexpr != null) {
624 attr.attribExpr(tree.nameexpr, localEnv);
625 MethodSymbol m = localEnv.enclMethod.sym;
626 if (m.isConstructor()) {
627 Type outertype = m.owner.owner.type;
628 if (outertype.hasTag(TypeTag.CLASS)) {
629 checkType(tree.vartype, outertype, "incorrect.constructor.receiver.type");
630 checkType(tree.nameexpr, outertype, "incorrect.constructor.receiver.name");
631 } else {
632 log.error(tree, "receiver.parameter.not.applicable.constructor.toplevel.class");
633 }
634 } else {
635 checkType(tree.vartype, m.owner.type, "incorrect.receiver.type");
636 checkType(tree.nameexpr, m.owner.type, "incorrect.receiver.name");
637 }
638 }
639 }
640 } finally {
641 chk.setDeferredLintHandler(prevLintHandler);
642 }
644 if ((tree.mods.flags & VARARGS) != 0) {
645 //if we are entering a varargs parameter, we need to replace its type
646 //(a plain array type) with the more precise VarargsType --- we need
647 //to do it this way because varargs is represented in the tree as a modifier
648 //on the parameter declaration, and not as a distinct type of array node.
649 ArrayType atype = (ArrayType)tree.vartype.type.unannotatedType();
650 tree.vartype.type = atype.makeVarargs();
651 }
652 Scope enclScope = enter.enterScope(env);
653 VarSymbol v =
654 new VarSymbol(0, tree.name, tree.vartype.type, enclScope.owner);
655 v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree);
656 tree.sym = v;
657 if (tree.init != null) {
658 v.flags_field |= HASINIT;
659 if ((v.flags_field & FINAL) != 0 &&
660 !tree.init.hasTag(NEWCLASS) &&
661 !tree.init.hasTag(LAMBDA)) {
662 Env<AttrContext> initEnv = getInitEnv(tree, env);
663 initEnv.info.enclVar = v;
664 v.setLazyConstValue(initEnv(tree, initEnv), attr, tree.init);
665 }
666 }
667 if (chk.checkUnique(tree.pos(), v, enclScope)) {
668 chk.checkTransparentVar(tree.pos(), v, enclScope);
669 enclScope.enter(v);
670 }
671 annotateLater(tree.mods.annotations, localEnv, v);
672 typeAnnotate(tree.vartype, env, v);
673 annotate.flush();
674 v.pos = tree.pos;
675 }
676 // where
677 void checkType(JCTree tree, Type type, String diag) {
678 if (!tree.type.isErroneous() && !types.isSameType(tree.type, type)) {
679 log.error(tree, diag, type, tree.type);
680 }
681 }
683 /** Create a fresh environment for a variable's initializer.
684 * If the variable is a field, the owner of the environment's scope
685 * is be the variable itself, otherwise the owner is the method
686 * enclosing the variable definition.
687 *
688 * @param tree The variable definition.
689 * @param env The environment current outside of the variable definition.
690 */
691 Env<AttrContext> initEnv(JCVariableDecl tree, Env<AttrContext> env) {
692 Env<AttrContext> localEnv = env.dupto(new AttrContextEnv(tree, env.info.dup()));
693 if (tree.sym.owner.kind == TYP) {
694 localEnv.info.scope = env.info.scope.dupUnshared();
695 localEnv.info.scope.owner = tree.sym;
696 }
697 if ((tree.mods.flags & STATIC) != 0 ||
698 ((env.enclClass.sym.flags() & INTERFACE) != 0 && env.enclMethod == null))
699 localEnv.info.staticLevel++;
700 return localEnv;
701 }
703 /** Default member enter visitor method: do nothing
704 */
705 public void visitTree(JCTree tree) {
706 }
708 public void visitErroneous(JCErroneous tree) {
709 if (tree.errs != null)
710 memberEnter(tree.errs, env);
711 }
713 public Env<AttrContext> getMethodEnv(JCMethodDecl tree, Env<AttrContext> env) {
714 Env<AttrContext> mEnv = methodEnv(tree, env);
715 mEnv.info.lint = mEnv.info.lint.augment(tree.sym.annotations, tree.sym.flags());
716 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
717 mEnv.info.scope.enterIfAbsent(l.head.type.tsym);
718 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail)
719 mEnv.info.scope.enterIfAbsent(l.head.sym);
720 return mEnv;
721 }
723 public Env<AttrContext> getInitEnv(JCVariableDecl tree, Env<AttrContext> env) {
724 Env<AttrContext> iEnv = initEnv(tree, env);
725 return iEnv;
726 }
728 /* ********************************************************************
729 * Type completion
730 *********************************************************************/
732 Type attribImportType(JCTree tree, Env<AttrContext> env) {
733 Assert.check(completionEnabled);
734 try {
735 // To prevent deep recursion, suppress completion of some
736 // types.
737 completionEnabled = false;
738 return attr.attribType(tree, env);
739 } finally {
740 completionEnabled = true;
741 }
742 }
744 /* ********************************************************************
745 * Annotation processing
746 *********************************************************************/
748 /** Queue annotations for later processing. */
749 void annotateLater(final List<JCAnnotation> annotations,
750 final Env<AttrContext> localEnv,
751 final Symbol s) {
752 if (annotations.isEmpty()) {
753 return;
754 }
755 if (s.kind != PCK) {
756 s.annotations.reset(); // mark Annotations as incomplete for now
757 }
758 annotate.normal(new Annotate.Annotator() {
759 @Override
760 public String toString() {
761 return "annotate " + annotations + " onto " + s + " in " + s.owner;
762 }
764 @Override
765 public void enterAnnotation() {
766 Assert.check(s.kind == PCK || s.annotations.pendingCompletion());
767 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
768 try {
769 if (!s.annotations.isEmpty() &&
770 annotations.nonEmpty())
771 log.error(annotations.head.pos,
772 "already.annotated",
773 kindName(s), s);
774 actualEnterAnnotations(annotations, localEnv, s);
775 } finally {
776 log.useSource(prev);
777 }
778 }
779 });
780 }
782 /**
783 * Check if a list of annotations contains a reference to
784 * java.lang.Deprecated.
785 **/
786 private boolean hasDeprecatedAnnotation(List<JCAnnotation> annotations) {
787 for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
788 JCAnnotation a = al.head;
789 if (a.annotationType.type == syms.deprecatedType && a.args.isEmpty())
790 return true;
791 }
792 return false;
793 }
795 /** Enter a set of annotations. */
796 private void actualEnterAnnotations(List<JCAnnotation> annotations,
797 Env<AttrContext> env,
798 Symbol s) {
799 Map<TypeSymbol, ListBuffer<Attribute.Compound>> annotated =
800 new LinkedHashMap<TypeSymbol, ListBuffer<Attribute.Compound>>();
801 Map<Attribute.Compound, DiagnosticPosition> pos =
802 new HashMap<Attribute.Compound, DiagnosticPosition>();
804 for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
805 JCAnnotation a = al.head;
806 Attribute.Compound c = annotate.enterAnnotation(a,
807 syms.annotationType,
808 env);
809 if (c == null) {
810 continue;
811 }
813 if (annotated.containsKey(a.type.tsym)) {
814 if (source.allowRepeatedAnnotations()) {
815 ListBuffer<Attribute.Compound> l = annotated.get(a.type.tsym);
816 l = l.append(c);
817 annotated.put(a.type.tsym, l);
818 pos.put(c, a.pos());
819 } else {
820 log.error(a.pos(), "duplicate.annotation");
821 }
822 } else {
823 annotated.put(a.type.tsym, ListBuffer.of(c));
824 pos.put(c, a.pos());
825 }
827 // Note: @Deprecated has no effect on local variables and parameters
828 if (!c.type.isErroneous()
829 && s.owner.kind != MTH
830 && types.isSameType(c.type, syms.deprecatedType)) {
831 s.flags_field |= Flags.DEPRECATED;
832 }
833 }
835 s.annotations.setDeclarationAttributesWithCompletion(
836 annotate.new AnnotateRepeatedContext<Attribute.Compound>(env, annotated, pos, log, false));
837 }
839 /** Queue processing of an attribute default value. */
840 void annotateDefaultValueLater(final JCExpression defaultValue,
841 final Env<AttrContext> localEnv,
842 final MethodSymbol m) {
843 annotate.normal(new Annotate.Annotator() {
844 @Override
845 public String toString() {
846 return "annotate " + m.owner + "." +
847 m + " default " + defaultValue;
848 }
850 @Override
851 public void enterAnnotation() {
852 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
853 try {
854 enterDefaultValue(defaultValue, localEnv, m);
855 } finally {
856 log.useSource(prev);
857 }
858 }
859 });
860 }
862 /** Enter a default value for an attribute method. */
863 private void enterDefaultValue(final JCExpression defaultValue,
864 final Env<AttrContext> localEnv,
865 final MethodSymbol m) {
866 m.defaultValue = annotate.enterAttributeValue(m.type.getReturnType(),
867 defaultValue,
868 localEnv);
869 }
871 /* ********************************************************************
872 * Source completer
873 *********************************************************************/
875 /** Complete entering a class.
876 * @param sym The symbol of the class to be completed.
877 */
878 public void complete(Symbol sym) throws CompletionFailure {
879 // Suppress some (recursive) MemberEnter invocations
880 if (!completionEnabled) {
881 // Re-install same completer for next time around and return.
882 Assert.check((sym.flags() & Flags.COMPOUND) == 0);
883 sym.completer = this;
884 return;
885 }
887 ClassSymbol c = (ClassSymbol)sym;
888 ClassType ct = (ClassType)c.type;
889 Env<AttrContext> env = enter.typeEnvs.get(c);
890 JCClassDecl tree = (JCClassDecl)env.tree;
891 boolean wasFirst = isFirst;
892 isFirst = false;
894 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
895 try {
896 // Save class environment for later member enter (2) processing.
897 halfcompleted.append(env);
899 // Mark class as not yet attributed.
900 c.flags_field |= UNATTRIBUTED;
902 // If this is a toplevel-class, make sure any preceding import
903 // clauses have been seen.
904 if (c.owner.kind == PCK) {
905 memberEnter(env.toplevel, env.enclosing(TOPLEVEL));
906 todo.append(env);
907 }
909 if (c.owner.kind == TYP)
910 c.owner.complete();
912 // create an environment for evaluating the base clauses
913 Env<AttrContext> baseEnv = baseEnv(tree, env);
915 if (tree.extending != null)
916 typeAnnotate(tree.extending, baseEnv, sym);
917 for (JCExpression impl : tree.implementing)
918 typeAnnotate(impl, baseEnv, sym);
919 annotate.flush();
921 // Determine supertype.
922 Type supertype =
923 (tree.extending != null)
924 ? attr.attribBase(tree.extending, baseEnv, true, false, true)
925 : ((tree.mods.flags & Flags.ENUM) != 0)
926 ? attr.attribBase(enumBase(tree.pos, c), baseEnv,
927 true, false, false)
928 : (c.fullname == names.java_lang_Object)
929 ? Type.noType
930 : syms.objectType;
931 ct.supertype_field = modelMissingTypes(supertype, tree.extending, false);
933 // Determine interfaces.
934 ListBuffer<Type> interfaces = new ListBuffer<Type>();
935 ListBuffer<Type> all_interfaces = null; // lazy init
936 Set<Type> interfaceSet = new HashSet<Type>();
937 List<JCExpression> interfaceTrees = tree.implementing;
938 for (JCExpression iface : interfaceTrees) {
939 Type i = attr.attribBase(iface, baseEnv, false, true, true);
940 if (i.hasTag(CLASS)) {
941 interfaces.append(i);
942 if (all_interfaces != null) all_interfaces.append(i);
943 chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet);
944 } else {
945 if (all_interfaces == null)
946 all_interfaces = new ListBuffer<Type>().appendList(interfaces);
947 all_interfaces.append(modelMissingTypes(i, iface, true));
948 }
949 }
950 if ((c.flags_field & ANNOTATION) != 0) {
951 ct.interfaces_field = List.of(syms.annotationType);
952 ct.all_interfaces_field = ct.interfaces_field;
953 } else {
954 ct.interfaces_field = interfaces.toList();
955 ct.all_interfaces_field = (all_interfaces == null)
956 ? ct.interfaces_field : all_interfaces.toList();
957 }
959 if (c.fullname == names.java_lang_Object) {
960 if (tree.extending != null) {
961 chk.checkNonCyclic(tree.extending.pos(),
962 supertype);
963 ct.supertype_field = Type.noType;
964 }
965 else if (tree.implementing.nonEmpty()) {
966 chk.checkNonCyclic(tree.implementing.head.pos(),
967 ct.interfaces_field.head);
968 ct.interfaces_field = List.nil();
969 }
970 }
972 // Annotations.
973 // In general, we cannot fully process annotations yet, but we
974 // can attribute the annotation types and then check to see if the
975 // @Deprecated annotation is present.
976 attr.attribAnnotationTypes(tree.mods.annotations, baseEnv);
977 if (hasDeprecatedAnnotation(tree.mods.annotations))
978 c.flags_field |= DEPRECATED;
979 annotateLater(tree.mods.annotations, baseEnv, c);
980 // class type parameters use baseEnv but everything uses env
982 chk.checkNonCyclicDecl(tree);
984 attr.attribTypeVariables(tree.typarams, baseEnv);
985 // Do this here, where we have the symbol.
986 for (JCTypeParameter tp : tree.typarams)
987 typeAnnotate(tp, baseEnv, sym);
988 annotate.flush();
990 // Add default constructor if needed.
991 if ((c.flags() & INTERFACE) == 0 &&
992 !TreeInfo.hasConstructors(tree.defs)) {
993 List<Type> argtypes = List.nil();
994 List<Type> typarams = List.nil();
995 List<Type> thrown = List.nil();
996 long ctorFlags = 0;
997 boolean based = false;
998 boolean addConstructor = true;
999 JCNewClass nc = null;
1000 if (c.name.isEmpty()) {
1001 nc = (JCNewClass)env.next.tree;
1002 if (nc.constructor != null) {
1003 addConstructor = nc.constructor.kind != ERR;
1004 Type superConstrType = types.memberType(c.type,
1005 nc.constructor);
1006 argtypes = superConstrType.getParameterTypes();
1007 typarams = superConstrType.getTypeArguments();
1008 ctorFlags = nc.constructor.flags() & VARARGS;
1009 if (nc.encl != null) {
1010 argtypes = argtypes.prepend(nc.encl.type);
1011 based = true;
1012 }
1013 thrown = superConstrType.getThrownTypes();
1014 }
1015 }
1016 if (addConstructor) {
1017 MethodSymbol basedConstructor = nc != null ?
1018 (MethodSymbol)nc.constructor : null;
1019 JCTree constrDef = DefaultConstructor(make.at(tree.pos), c,
1020 basedConstructor,
1021 typarams, argtypes, thrown,
1022 ctorFlags, based);
1023 tree.defs = tree.defs.prepend(constrDef);
1024 }
1025 }
1027 // enter symbols for 'this' into current scope.
1028 VarSymbol thisSym =
1029 new VarSymbol(FINAL | HASINIT, names._this, c.type, c);
1030 thisSym.pos = Position.FIRSTPOS;
1031 env.info.scope.enter(thisSym);
1032 // if this is a class, enter symbol for 'super' into current scope.
1033 if ((c.flags_field & INTERFACE) == 0 &&
1034 ct.supertype_field.hasTag(CLASS)) {
1035 VarSymbol superSym =
1036 new VarSymbol(FINAL | HASINIT, names._super,
1037 ct.supertype_field, c);
1038 superSym.pos = Position.FIRSTPOS;
1039 env.info.scope.enter(superSym);
1040 }
1042 // check that no package exists with same fully qualified name,
1043 // but admit classes in the unnamed package which have the same
1044 // name as a top-level package.
1045 if (checkClash &&
1046 c.owner.kind == PCK && c.owner != syms.unnamedPackage &&
1047 reader.packageExists(c.fullname)) {
1048 log.error(tree.pos, "clash.with.pkg.of.same.name", Kinds.kindName(sym), c);
1049 }
1050 if (c.owner.kind == PCK && (c.flags_field & PUBLIC) == 0 &&
1051 !env.toplevel.sourcefile.isNameCompatible(c.name.toString(),JavaFileObject.Kind.SOURCE)) {
1052 c.flags_field |= AUXILIARY;
1053 }
1054 } catch (CompletionFailure ex) {
1055 chk.completionError(tree.pos(), ex);
1056 } finally {
1057 log.useSource(prev);
1058 }
1060 // Enter all member fields and methods of a set of half completed
1061 // classes in a second phase.
1062 if (wasFirst) {
1063 try {
1064 while (halfcompleted.nonEmpty()) {
1065 finish(halfcompleted.next());
1066 }
1067 } finally {
1068 isFirst = true;
1069 }
1070 }
1071 TypeAnnotations.organizeTypeAnnotationsSignatures(syms, names, log, tree, annotate);
1072 }
1074 /*
1075 * If the symbol is non-null, attach the type annotation to it.
1076 */
1077 private void actualEnterTypeAnnotations(final List<JCAnnotation> annotations,
1078 final Env<AttrContext> env,
1079 final Symbol s) {
1080 Map<TypeSymbol, ListBuffer<Attribute.TypeCompound>> annotated =
1081 new LinkedHashMap<TypeSymbol, ListBuffer<Attribute.TypeCompound>>();
1082 Map<Attribute.TypeCompound, DiagnosticPosition> pos =
1083 new HashMap<Attribute.TypeCompound, DiagnosticPosition>();
1085 for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
1086 JCAnnotation a = al.head;
1087 Attribute.TypeCompound tc = annotate.enterTypeAnnotation(a,
1088 syms.annotationType,
1089 env);
1090 if (tc == null) {
1091 continue;
1092 }
1094 if (annotated.containsKey(a.type.tsym)) {
1095 if (source.allowRepeatedAnnotations()) {
1096 ListBuffer<Attribute.TypeCompound> l = annotated.get(a.type.tsym);
1097 l = l.append(tc);
1098 annotated.put(a.type.tsym, l);
1099 pos.put(tc, a.pos());
1100 } else {
1101 log.error(a.pos(), "duplicate.annotation");
1102 }
1103 } else {
1104 annotated.put(a.type.tsym, ListBuffer.of(tc));
1105 pos.put(tc, a.pos());
1106 }
1107 }
1109 if (s != null) {
1110 s.annotations.appendTypeAttributesWithCompletion(
1111 annotate.new AnnotateRepeatedContext<Attribute.TypeCompound>(env, annotated, pos, log, true));
1112 }
1113 }
1115 public void typeAnnotate(final JCTree tree, final Env<AttrContext> env, final Symbol sym) {
1116 tree.accept(new TypeAnnotate(env, sym));
1117 }
1119 /**
1120 * We need to use a TreeScanner, because it is not enough to visit the top-level
1121 * annotations. We also need to visit type arguments, etc.
1122 */
1123 private class TypeAnnotate extends TreeScanner {
1124 private Env<AttrContext> env;
1125 private Symbol sym;
1127 public TypeAnnotate(final Env<AttrContext> env, final Symbol sym) {
1128 this.env = env;
1129 this.sym = sym;
1130 }
1132 void annotateTypeLater(final List<JCAnnotation> annotations) {
1133 if (annotations.isEmpty()) {
1134 return;
1135 }
1137 annotate.normal(new Annotate.Annotator() {
1138 @Override
1139 public String toString() {
1140 return "type annotate " + annotations + " onto " + sym + " in " + sym.owner;
1141 }
1142 @Override
1143 public void enterAnnotation() {
1144 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
1145 try {
1146 actualEnterTypeAnnotations(annotations, env, sym);
1147 } finally {
1148 log.useSource(prev);
1149 }
1150 }
1151 });
1152 }
1154 @Override
1155 public void visitAnnotatedType(final JCAnnotatedType tree) {
1156 annotateTypeLater(tree.annotations);
1157 super.visitAnnotatedType(tree);
1158 }
1160 @Override
1161 public void visitTypeParameter(final JCTypeParameter tree) {
1162 annotateTypeLater(tree.annotations);
1163 super.visitTypeParameter(tree);
1164 }
1166 @Override
1167 public void visitNewArray(final JCNewArray tree) {
1168 annotateTypeLater(tree.annotations);
1169 for (List<JCAnnotation> dimAnnos : tree.dimAnnotations)
1170 annotateTypeLater(dimAnnos);
1171 super.visitNewArray(tree);
1172 }
1174 @Override
1175 public void visitMethodDef(final JCMethodDecl tree) {
1176 scan(tree.mods);
1177 scan(tree.restype);
1178 scan(tree.typarams);
1179 scan(tree.recvparam);
1180 scan(tree.params);
1181 scan(tree.thrown);
1182 scan(tree.defaultValue);
1183 // Do not annotate the body, just the signature.
1184 // scan(tree.body);
1185 }
1187 @Override
1188 public void visitVarDef(final JCVariableDecl tree) {
1189 if (sym != null && sym.kind == Kinds.VAR) {
1190 // Don't visit a parameter once when the sym is the method
1191 // and once when the sym is the parameter.
1192 scan(tree.mods);
1193 scan(tree.vartype);
1194 }
1195 scan(tree.init);
1196 }
1198 @Override
1199 public void visitClassDef(JCClassDecl tree) {
1200 // We can only hit a classdef if it is declared within
1201 // a method. Ignore it - the class will be visited
1202 // separately later.
1203 }
1205 @Override
1206 public void visitNewClass(JCNewClass tree) {
1207 if (tree.def == null) {
1208 // For an anonymous class instantiation the class
1209 // will be visited separately.
1210 super.visitNewClass(tree);
1211 }
1212 }
1213 }
1216 private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
1217 Scope baseScope = new Scope(tree.sym);
1218 //import already entered local classes into base scope
1219 for (Scope.Entry e = env.outer.info.scope.elems ; e != null ; e = e.sibling) {
1220 if (e.sym.isLocal()) {
1221 baseScope.enter(e.sym);
1222 }
1223 }
1224 //import current type-parameters into base scope
1225 if (tree.typarams != null)
1226 for (List<JCTypeParameter> typarams = tree.typarams;
1227 typarams.nonEmpty();
1228 typarams = typarams.tail)
1229 baseScope.enter(typarams.head.type.tsym);
1230 Env<AttrContext> outer = env.outer; // the base clause can't see members of this class
1231 Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(baseScope));
1232 localEnv.baseClause = true;
1233 localEnv.outer = outer;
1234 localEnv.info.isSelfCall = false;
1235 return localEnv;
1236 }
1238 /** Enter member fields and methods of a class
1239 * @param env the environment current for the class block.
1240 */
1241 private void finish(Env<AttrContext> env) {
1242 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
1243 try {
1244 JCClassDecl tree = (JCClassDecl)env.tree;
1245 finishClass(tree, env);
1246 } finally {
1247 log.useSource(prev);
1248 }
1249 }
1251 /** Generate a base clause for an enum type.
1252 * @param pos The position for trees and diagnostics, if any
1253 * @param c The class symbol of the enum
1254 */
1255 private JCExpression enumBase(int pos, ClassSymbol c) {
1256 JCExpression result = make.at(pos).
1257 TypeApply(make.QualIdent(syms.enumSym),
1258 List.<JCExpression>of(make.Type(c.type)));
1259 return result;
1260 }
1262 Type modelMissingTypes(Type t, final JCExpression tree, final boolean interfaceExpected) {
1263 if (!t.hasTag(ERROR))
1264 return t;
1266 return new ErrorType(((ErrorType) t).getOriginalType(), t.tsym) {
1267 private Type modelType;
1269 @Override
1270 public Type getModelType() {
1271 if (modelType == null)
1272 modelType = new Synthesizer(getOriginalType(), interfaceExpected).visit(tree);
1273 return modelType;
1274 }
1275 };
1276 }
1277 // where
1278 private class Synthesizer extends JCTree.Visitor {
1279 Type originalType;
1280 boolean interfaceExpected;
1281 List<ClassSymbol> synthesizedSymbols = List.nil();
1282 Type result;
1284 Synthesizer(Type originalType, boolean interfaceExpected) {
1285 this.originalType = originalType;
1286 this.interfaceExpected = interfaceExpected;
1287 }
1289 Type visit(JCTree tree) {
1290 tree.accept(this);
1291 return result;
1292 }
1294 List<Type> visit(List<? extends JCTree> trees) {
1295 ListBuffer<Type> lb = new ListBuffer<Type>();
1296 for (JCTree t: trees)
1297 lb.append(visit(t));
1298 return lb.toList();
1299 }
1301 @Override
1302 public void visitTree(JCTree tree) {
1303 result = syms.errType;
1304 }
1306 @Override
1307 public void visitIdent(JCIdent tree) {
1308 if (!tree.type.hasTag(ERROR)) {
1309 result = tree.type;
1310 } else {
1311 result = synthesizeClass(tree.name, syms.unnamedPackage).type;
1312 }
1313 }
1315 @Override
1316 public void visitSelect(JCFieldAccess tree) {
1317 if (!tree.type.hasTag(ERROR)) {
1318 result = tree.type;
1319 } else {
1320 Type selectedType;
1321 boolean prev = interfaceExpected;
1322 try {
1323 interfaceExpected = false;
1324 selectedType = visit(tree.selected);
1325 } finally {
1326 interfaceExpected = prev;
1327 }
1328 ClassSymbol c = synthesizeClass(tree.name, selectedType.tsym);
1329 result = c.type;
1330 }
1331 }
1333 @Override
1334 public void visitTypeApply(JCTypeApply tree) {
1335 if (!tree.type.hasTag(ERROR)) {
1336 result = tree.type;
1337 } else {
1338 ClassType clazzType = (ClassType) visit(tree.clazz);
1339 if (synthesizedSymbols.contains(clazzType.tsym))
1340 synthesizeTyparams((ClassSymbol) clazzType.tsym, tree.arguments.size());
1341 final List<Type> actuals = visit(tree.arguments);
1342 result = new ErrorType(tree.type, clazzType.tsym) {
1343 @Override
1344 public List<Type> getTypeArguments() {
1345 return actuals;
1346 }
1347 };
1348 }
1349 }
1351 ClassSymbol synthesizeClass(Name name, Symbol owner) {
1352 int flags = interfaceExpected ? INTERFACE : 0;
1353 ClassSymbol c = new ClassSymbol(flags, name, owner);
1354 c.members_field = new Scope.ErrorScope(c);
1355 c.type = new ErrorType(originalType, c) {
1356 @Override
1357 public List<Type> getTypeArguments() {
1358 return typarams_field;
1359 }
1360 };
1361 synthesizedSymbols = synthesizedSymbols.prepend(c);
1362 return c;
1363 }
1365 void synthesizeTyparams(ClassSymbol sym, int n) {
1366 ClassType ct = (ClassType) sym.type;
1367 Assert.check(ct.typarams_field.isEmpty());
1368 if (n == 1) {
1369 TypeVar v = new TypeVar(names.fromString("T"), sym, syms.botType);
1370 ct.typarams_field = ct.typarams_field.prepend(v);
1371 } else {
1372 for (int i = n; i > 0; i--) {
1373 TypeVar v = new TypeVar(names.fromString("T" + i), sym, syms.botType);
1374 ct.typarams_field = ct.typarams_field.prepend(v);
1375 }
1376 }
1377 }
1378 }
1381 /* ***************************************************************************
1382 * tree building
1383 ****************************************************************************/
1385 /** Generate default constructor for given class. For classes different
1386 * from java.lang.Object, this is:
1387 *
1388 * c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
1389 * super(x_0, ..., x_n)
1390 * }
1391 *
1392 * or, if based == true:
1393 *
1394 * c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
1395 * x_0.super(x_1, ..., x_n)
1396 * }
1397 *
1398 * @param make The tree factory.
1399 * @param c The class owning the default constructor.
1400 * @param argtypes The parameter types of the constructor.
1401 * @param thrown The thrown exceptions of the constructor.
1402 * @param based Is first parameter a this$n?
1403 */
1404 JCTree DefaultConstructor(TreeMaker make,
1405 ClassSymbol c,
1406 MethodSymbol baseInit,
1407 List<Type> typarams,
1408 List<Type> argtypes,
1409 List<Type> thrown,
1410 long flags,
1411 boolean based) {
1412 JCTree result;
1413 if ((c.flags() & ENUM) != 0 &&
1414 (types.supertype(c.type).tsym == syms.enumSym)) {
1415 // constructors of true enums are private
1416 flags = (flags & ~AccessFlags) | PRIVATE | GENERATEDCONSTR;
1417 } else
1418 flags |= (c.flags() & AccessFlags) | GENERATEDCONSTR;
1419 if (c.name.isEmpty()) {
1420 flags |= ANONCONSTR;
1421 }
1422 Type mType = new MethodType(argtypes, null, thrown, c);
1423 Type initType = typarams.nonEmpty() ?
1424 new ForAll(typarams, mType) :
1425 mType;
1426 MethodSymbol init = new MethodSymbol(flags, names.init,
1427 initType, c);
1428 init.params = createDefaultConstructorParams(make, baseInit, init,
1429 argtypes, based);
1430 List<JCVariableDecl> params = make.Params(argtypes, init);
1431 List<JCStatement> stats = List.nil();
1432 if (c.type != syms.objectType) {
1433 stats = stats.prepend(SuperCall(make, typarams, params, based));
1434 }
1435 result = make.MethodDef(init, make.Block(0, stats));
1436 return result;
1437 }
1439 private List<VarSymbol> createDefaultConstructorParams(
1440 TreeMaker make,
1441 MethodSymbol baseInit,
1442 MethodSymbol init,
1443 List<Type> argtypes,
1444 boolean based) {
1445 List<VarSymbol> initParams = null;
1446 List<Type> argTypesList = argtypes;
1447 if (based) {
1448 /* In this case argtypes will have an extra type, compared to baseInit,
1449 * corresponding to the type of the enclosing instance i.e.:
1450 *
1451 * Inner i = outer.new Inner(1){}
1452 *
1453 * in the above example argtypes will be (Outer, int) and baseInit
1454 * will have parameter's types (int). So in this case we have to add
1455 * first the extra type in argtypes and then get the names of the
1456 * parameters from baseInit.
1457 */
1458 initParams = List.nil();
1459 VarSymbol param = new VarSymbol(0, make.paramName(0), argtypes.head, init);
1460 initParams = initParams.append(param);
1461 argTypesList = argTypesList.tail;
1462 }
1463 if (baseInit != null && baseInit.params != null &&
1464 baseInit.params.nonEmpty() && argTypesList.nonEmpty()) {
1465 initParams = (initParams == null) ? List.<VarSymbol>nil() : initParams;
1466 List<VarSymbol> baseInitParams = baseInit.params;
1467 while (baseInitParams.nonEmpty() && argTypesList.nonEmpty()) {
1468 VarSymbol param = new VarSymbol(baseInitParams.head.flags(),
1469 baseInitParams.head.name, argTypesList.head, init);
1470 initParams = initParams.append(param);
1471 baseInitParams = baseInitParams.tail;
1472 argTypesList = argTypesList.tail;
1473 }
1474 }
1475 return initParams;
1476 }
1478 /** Generate call to superclass constructor. This is:
1479 *
1480 * super(id_0, ..., id_n)
1481 *
1482 * or, if based == true
1483 *
1484 * id_0.super(id_1,...,id_n)
1485 *
1486 * where id_0, ..., id_n are the names of the given parameters.
1487 *
1488 * @param make The tree factory
1489 * @param params The parameters that need to be passed to super
1490 * @param typarams The type parameters that need to be passed to super
1491 * @param based Is first parameter a this$n?
1492 */
1493 JCExpressionStatement SuperCall(TreeMaker make,
1494 List<Type> typarams,
1495 List<JCVariableDecl> params,
1496 boolean based) {
1497 JCExpression meth;
1498 if (based) {
1499 meth = make.Select(make.Ident(params.head), names._super);
1500 params = params.tail;
1501 } else {
1502 meth = make.Ident(names._super);
1503 }
1504 List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null;
1505 return make.Exec(make.Apply(typeargs, meth, make.Idents(params)));
1506 }
1507 }