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