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