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