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 */
25
26 package com.sun.tools.javac.comp;
27
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;
33
34 import javax.tools.JavaFileObject;
35
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.*;
40
41 import com.sun.tools.javac.code.Type.*;
42 import com.sun.tools.javac.code.Symbol.*;
43 import com.sun.tools.javac.tree.JCTree.*;
44
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;
54
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 */
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 typeAnnotations = TypeAnnotations.instance(context);
109 types = Types.instance(context);
110 diags = JCDiagnostic.Factory.instance(context);
111 source = Source.instance(context);
112 target = Target.instance(context);
113 deferredLintHandler = DeferredLintHandler.instance(context);
114 lint = Lint.instance(context);
115 allowTypeAnnos = source.allowTypeAnnotations();
116 }
117
118 /** Switch: support type annotations.
119 */
120 boolean allowTypeAnnos;
121
122 /** A queue for classes whose members still need to be entered into the
123 * symbol table.
124 */
125 ListBuffer<Env<AttrContext>> halfcompleted = new ListBuffer<>();
126
127 /** Set to true only when the first of a set of classes is
128 * processed from the half completed queue.
129 */
130 boolean isFirst = true;
131
132 /** A flag to disable completion from time to time during member
133 * enter, as we only need to look up types. This avoids
134 * unnecessarily deep recursion.
135 */
136 boolean completionEnabled = true;
137
138 /* ---------- Processing import clauses ----------------
139 */
140
141 /** Import all classes of a class or package on demand.
142 * @param pos Position to be used for error reporting.
143 * @param tsym The class or package the members of which are imported.
144 * @param env The env in which the imported classes will be entered.
145 */
146 private void importAll(int pos,
147 final TypeSymbol tsym,
148 Env<AttrContext> env) {
149 // Check that packages imported from exist (JLS ???).
150 if (tsym.kind == PCK && tsym.members().elems == null && !tsym.exists()) {
151 // If we can't find java.lang, exit immediately.
152 if (((PackageSymbol)tsym).fullname.equals(names.java_lang)) {
153 JCDiagnostic msg = diags.fragment("fatal.err.no.java.lang");
154 throw new FatalError(msg);
155 } else {
156 log.error(DiagnosticFlag.RESOLVE_ERROR, pos, "doesnt.exist", tsym);
157 }
344 * @param tsym The class to be imported.
345 * @param env The environment containing the named import
346 * scope to add to.
347 */
348 private void importNamed(DiagnosticPosition pos, Symbol tsym, Env<AttrContext> env) {
349 if (tsym.kind == TYP &&
350 chk.checkUniqueImport(pos, tsym, env.toplevel.namedImportScope))
351 env.toplevel.namedImportScope.enter(tsym, tsym.owner.members());
352 }
353
354 /** Construct method type from method signature.
355 * @param typarams The method's type parameters.
356 * @param params The method's value parameters.
357 * @param res The method's result type,
358 * null if it is a constructor.
359 * @param recvparam The method's receiver parameter,
360 * null if none given; TODO: or already set here?
361 * @param thrown The method's thrown exceptions.
362 * @param env The method's (local) environment.
363 */
364 Type signature(MethodSymbol msym,
365 List<JCTypeParameter> typarams,
366 List<JCVariableDecl> params,
367 JCTree res,
368 JCVariableDecl recvparam,
369 List<JCExpression> thrown,
370 Env<AttrContext> env) {
371
372 // Enter and attribute type parameters.
373 List<Type> tvars = enter.classEnter(typarams, env);
374 attr.attribTypeVariables(typarams, env);
375
376 // Enter and attribute value parameters.
377 ListBuffer<Type> argbuf = new ListBuffer<>();
378 for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) {
379 memberEnter(l.head, env);
380 argbuf.append(l.head.vartype.type);
381 }
382
383 // Attribute result type, if one is given.
384 Type restype = res == null ? syms.voidType : attr.attribType(res, env);
385
386 // Attribute receiver type, if one is given.
387 Type recvtype;
388 if (recvparam!=null) {
389 memberEnter(recvparam, env);
390 recvtype = recvparam.vartype.type;
391 } else {
392 recvtype = null;
393 }
394
395 // Attribute thrown exceptions.
396 ListBuffer<Type> thrownbuf = new ListBuffer<>();
397 for (List<JCExpression> l = thrown; l.nonEmpty(); l = l.tail) {
398 Type exc = attr.attribType(l.head, env);
399 if (!exc.hasTag(TYPEVAR)) {
400 exc = chk.checkClassType(l.head.pos(), exc);
401 } else if (exc.tsym.owner == msym) {
402 //mark inference variables in 'throws' clause
403 exc.tsym.flags_field |= THROWS;
404 }
405 thrownbuf.append(exc);
406 }
407 MethodType mtype = new MethodType(argbuf.toList(),
408 restype,
409 thrownbuf.toList(),
410 syms.methodClass);
411 mtype.recvtype = recvtype;
412
413 return tvars.isEmpty() ? mtype : new ForAll(tvars, mtype);
414 }
415
416 /* ********************************************************************
417 * Visitor methods for member enter
418 *********************************************************************/
419
420 /** Visitor argument: the current environment
421 */
422 protected Env<AttrContext> env;
423
424 /** Enter field and method definitions and process import
425 * clauses, catching any completion failure exceptions.
426 */
427 protected void memberEnter(JCTree tree, Env<AttrContext> env) {
428 Env<AttrContext> prevEnv = this.env;
429 try {
430 this.env = env;
431 tree.accept(this);
432 } catch (CompletionFailure ex) {
433 chk.completionError(tree.pos(), ex);
434 } finally {
435 this.env = prevEnv;
436 }
437 }
438
439 /** Enter members from a list of trees.
440 */
441 void memberEnter(List<? extends JCTree> trees, Env<AttrContext> env) {
442 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
443 memberEnter(l.head, env);
444 }
445
446 /** Enter members for a class.
447 */
448 void finishClass(JCClassDecl tree, Env<AttrContext> env) {
449 if ((tree.mods.flags & Flags.ENUM) != 0 &&
450 (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
451 addEnumMembers(tree, env);
452 }
453 memberEnter(tree.defs, env);
454 }
455
456 /** Add the implicit members for an enum type
457 * to the symbol table.
458 */
459 private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
460 JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass,
461 Type.noAnnotations));
462
463 // public static T[] values() { return ???; }
464 JCMethodDecl values = make.
465 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
466 names.values,
467 valuesType,
468 List.<JCTypeParameter>nil(),
469 List.<JCVariableDecl>nil(),
470 List.<JCExpression>nil(), // thrown
471 null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
472 null);
473 memberEnter(values, env);
508 deferredLintHandler.setPos(prevLintPos);
509 }
510 }
511
512 public void visitPackageDef(JCPackageDecl tree) {
513 // check that no class exists with same fully qualified name as
514 // toplevel package
515 if (checkClash && tree.pid != null) {
516 Symbol p = env.toplevel.packge;
517 while (p.owner != syms.rootPackage) {
518 p.owner.complete(); // enter all class members of p
519 if (syms.classes.get(p.getQualifiedName()) != null) {
520 log.error(tree.pos,
521 "pkg.clashes.with.class.of.same.name",
522 p);
523 }
524 p = p.owner;
525 }
526 }
527 // process package annotations
528 annotate.annotateLater(tree.annotations, env, env.toplevel.packge, null);
529 }
530
531 // process the non-static imports and the static imports of types.
532 public void visitImport(JCImport tree) {
533 JCFieldAccess imp = (JCFieldAccess)tree.qualid;
534 Name name = TreeInfo.name(imp);
535
536 // Create a local environment pointing to this tree to disable
537 // effects of other imports in Resolve.findGlobalType
538 Env<AttrContext> localEnv = env.dup(tree);
539
540 TypeSymbol p = attr.attribImportQualifier(tree, localEnv).tsym;
541 if (name == names.asterisk) {
542 // Import on demand.
543 chk.checkCanonical(imp.selected);
544 if (tree.staticImport)
545 importStaticAll(tree.pos, p, env);
546 else
547 importAll(tree.pos, p, env);
548 } else {
549 // Named type import.
550 if (tree.staticImport) {
551 importNamedStatic(tree.pos(), p, name, localEnv);
552 chk.checkCanonical(imp.selected);
553 } else {
554 TypeSymbol c = attribImportType(imp, localEnv).tsym;
555 chk.checkCanonical(imp);
556 importNamed(tree.pos(), c, env);
557 }
558 }
559 }
560
561 public void visitMethodDef(JCMethodDecl tree) {
562 Scope enclScope = enter.enterScope(env);
563 MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner);
564 m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree);
565 tree.sym = m;
566
567 //if this is a default method, add the DEFAULT flag to the enclosing interface
568 if ((tree.mods.flags & DEFAULT) != 0) {
569 m.enclClass().flags_field |= DEFAULT;
570 }
571
572 Env<AttrContext> localEnv = methodEnv(tree, env);
573
574 annotate.enterStart();
575 try {
576 DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());
577 try {
578 // Compute the method type
579 m.type = signature(m, tree.typarams, tree.params,
580 tree.restype, tree.recvparam,
581 tree.thrown,
582 localEnv);
583 } finally {
584 deferredLintHandler.setPos(prevLintPos);
585 }
586
587 if (types.isSignaturePolymorphic(m)) {
588 m.flags_field |= SIGNATURE_POLYMORPHIC;
589 }
590
591 // Set m.params
592 ListBuffer<VarSymbol> params = new ListBuffer<>();
593 JCVariableDecl lastParam = null;
594 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
595 JCVariableDecl param = lastParam = l.head;
596 params.append(Assert.checkNonNull(param.sym));
597 }
598 m.params = params.toList();
599
600 // mark the method varargs, if necessary
601 if (lastParam != null && (lastParam.mods.flags & Flags.VARARGS) != 0)
602 m.flags_field |= Flags.VARARGS;
603
604 localEnv.info.scope.leave();
605 if (chk.checkUnique(tree.pos(), m, enclScope)) {
606 enclScope.enter(m);
607 }
608
609 annotate.annotateLater(tree.mods.annotations, localEnv, m, tree.pos());
610 // Visit the signature of the method. Note that
611 // TypeAnnotate doesn't descend into the body.
612 annotate.annotateTypeLater(tree, localEnv, m, tree.pos());
613
614 if (tree.defaultValue != null)
615 annotateDefaultValueLater(tree.defaultValue, localEnv, m);
616 } finally {
617 annotate.enterDone();
618 }
619 }
620
621 /** Create a fresh environment for method bodies.
622 * @param tree The method definition.
623 * @param env The environment current outside of the method definition.
624 */
625 Env<AttrContext> methodEnv(JCMethodDecl tree, Env<AttrContext> env) {
626 Env<AttrContext> localEnv =
627 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
628 localEnv.enclMethod = tree;
629 localEnv.info.scope.owner = tree.sym;
630 if (tree.sym.type != null) {
631 //when this is called in the enter stage, there's no type to be set
632 localEnv.info.returnResult = attr.new ResultInfo(VAL, tree.sym.type.getReturnType());
633 }
634 if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++;
635 return localEnv;
636 }
637
638 public void visitVarDef(JCVariableDecl tree) {
639 Env<AttrContext> localEnv = env;
640 if ((tree.mods.flags & STATIC) != 0 ||
641 (env.info.scope.owner.flags() & INTERFACE) != 0) {
642 localEnv = env.dup(tree, env.info.dup());
643 localEnv.info.staticLevel++;
644 }
645 DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());
646 annotate.enterStart();
647 try {
648 try {
649 if (TreeInfo.isEnumInit(tree)) {
650 attr.attribIdentAsEnumType(localEnv, (JCIdent)tree.vartype);
651 } else {
652 attr.attribType(tree.vartype, localEnv);
653 if (tree.nameexpr != null) {
654 attr.attribExpr(tree.nameexpr, localEnv);
655 MethodSymbol m = localEnv.enclMethod.sym;
656 if (m.isConstructor()) {
657 Type outertype = m.owner.owner.type;
658 if (outertype.hasTag(TypeTag.CLASS)) {
659 checkType(tree.vartype, outertype, "incorrect.constructor.receiver.type");
660 checkType(tree.nameexpr, outertype, "incorrect.constructor.receiver.name");
661 } else {
662 log.error(tree, "receiver.parameter.not.applicable.constructor.toplevel.class");
663 }
664 } else {
665 checkType(tree.vartype, m.owner.type, "incorrect.receiver.type");
666 checkType(tree.nameexpr, m.owner.type, "incorrect.receiver.name");
667 }
668 }
669 }
670 } finally {
671 deferredLintHandler.setPos(prevLintPos);
672 }
675 //if we are entering a varargs parameter, we need to
676 //replace its type (a plain array type) with the more
677 //precise VarargsType --- we need to do it this way
678 //because varargs is represented in the tree as a
679 //modifier on the parameter declaration, and not as a
680 //distinct type of array node.
681 ArrayType atype = (ArrayType)tree.vartype.type;
682 tree.vartype.type = atype.makeVarargs();
683 }
684 Scope enclScope = enter.enterScope(env);
685 VarSymbol v =
686 new VarSymbol(0, tree.name, tree.vartype.type, enclScope.owner);
687 v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree);
688 tree.sym = v;
689 if (tree.init != null) {
690 v.flags_field |= HASINIT;
691 if ((v.flags_field & FINAL) != 0 &&
692 needsLazyConstValue(tree.init)) {
693 Env<AttrContext> initEnv = getInitEnv(tree, env);
694 initEnv.info.enclVar = v;
695 v.setLazyConstValue(initEnv(tree, initEnv), attr, tree);
696 }
697 }
698 if (chk.checkUnique(tree.pos(), v, enclScope)) {
699 chk.checkTransparentVar(tree.pos(), v, enclScope);
700 enclScope.enter(v);
701 }
702 annotate.annotateLater(tree.mods.annotations, localEnv, v, tree.pos());
703 annotate.annotateTypeLater(tree.vartype, env, v, tree.pos());
704 v.pos = tree.pos;
705 } finally {
706 annotate.enterDone();
707 }
708 }
709 // where
710 void checkType(JCTree tree, Type type, String diag) {
711 if (!tree.type.isErroneous() && !types.isSameType(tree.type, type)) {
712 log.error(tree, diag, type, tree.type);
713 }
714 }
715
716 public boolean needsLazyConstValue(JCTree tree) {
717 InitTreeVisitor initTreeVisitor = new InitTreeVisitor();
718 tree.accept(initTreeVisitor);
719 return initTreeVisitor.result;
720 }
721
722 /** Visitor class for expressions which might be constant expressions.
723 */
814 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail)
815 mEnv.info.scope.enterIfAbsent(l.head.sym);
816 return mEnv;
817 }
818
819 public Env<AttrContext> getInitEnv(JCVariableDecl tree, Env<AttrContext> env) {
820 Env<AttrContext> iEnv = initEnv(tree, env);
821 return iEnv;
822 }
823
824 /* ********************************************************************
825 * Type completion
826 *********************************************************************/
827
828 Type attribImportType(JCTree tree, Env<AttrContext> env) {
829 Assert.check(completionEnabled);
830 try {
831 // To prevent deep recursion, suppress completion of some
832 // types.
833 completionEnabled = false;
834 return attr.attribType(tree, env);
835 } finally {
836 completionEnabled = true;
837 }
838 }
839
840 /**
841 * Check if a list of annotations contains a reference to
842 * java.lang.Deprecated.
843 **/
844 private boolean hasDeprecatedAnnotation(List<JCAnnotation> annotations) {
845 for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
846 JCAnnotation a = al.head;
847 if (a.annotationType.type == syms.deprecatedType && a.args.isEmpty())
848 return true;
849 }
850 return false;
851 }
852
853 /** Queue processing of an attribute default value. */
854 void annotateDefaultValueLater(final JCExpression defaultValue,
855 final Env<AttrContext> localEnv,
856 final MethodSymbol m) {
857 annotate.normal(new Annotate.Worker() {
858 @Override
859 public String toString() {
860 return "annotate " + m.owner + "." +
861 m + " default " + defaultValue;
862 }
863
864 @Override
865 public void run() {
866 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
867 try {
868 enterDefaultValue(defaultValue, localEnv, m);
869 } finally {
870 log.useSource(prev);
871 }
872 }
873 });
874 annotate.validate(new Annotate.Worker() { //validate annotations
875 @Override
876 public void run() {
877 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
878 try {
879 // if default value is an annotation, check it is a well-formed
880 // annotation value (e.g. no duplicate values, no missing values, etc.)
881 chk.validateAnnotationTree(defaultValue);
882 } finally {
883 log.useSource(prev);
884 }
885 }
886 });
887 }
888
889 /** Enter a default value for an attribute method. */
890 private void enterDefaultValue(final JCExpression defaultValue,
891 final Env<AttrContext> localEnv,
892 final MethodSymbol m) {
893 m.defaultValue = annotate.enterAttributeValue(m.type.getReturnType(),
894 defaultValue,
895 localEnv);
896 }
897
898 /* ********************************************************************
899 * Source completer
900 *********************************************************************/
901
902 /** Complete entering a class.
903 * @param sym The symbol of the class to be completed.
904 */
905 public void complete(Symbol sym) throws CompletionFailure {
906 // Suppress some (recursive) MemberEnter invocations
907 if (!completionEnabled) {
908 // Re-install same completer for next time around and return.
909 Assert.check((sym.flags() & Flags.COMPOUND) == 0);
910 sym.completer = this;
911 return;
912 }
913
914 ClassSymbol c = (ClassSymbol)sym;
915 ClassType ct = (ClassType)c.type;
916 Env<AttrContext> env = enter.typeEnvs.get(c);
917 JCClassDecl tree = (JCClassDecl)env.tree;
918 boolean wasFirst = isFirst;
919 isFirst = false;
920
921 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
922 DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());
923 try {
924 // Save class environment for later member enter (2) processing.
925 halfcompleted.append(env);
926
927 // Mark class as not yet attributed.
928 c.flags_field |= UNATTRIBUTED;
929
930 // If this is a toplevel-class, make sure any preceding import
931 // clauses have been seen.
932 if (c.owner.kind == PCK) {
933 memberEnter(env.toplevel, env.enclosing(TOPLEVEL));
934 todo.append(env);
935 }
936
937 if (c.owner.kind == TYP)
938 c.owner.complete();
939
940 // create an environment for evaluating the base clauses
941 Env<AttrContext> baseEnv = baseEnv(tree, env);
942
943 if (tree.extending != null)
944 annotate.annotateTypeLater(tree.extending, baseEnv, sym, tree.pos());
945 for (JCExpression impl : tree.implementing)
946 annotate.annotateTypeLater(impl, baseEnv, sym, tree.pos());
947 annotate.flush();
948
949 // Determine supertype.
950 Type supertype =
951 (tree.extending != null)
952 ? attr.attribBase(tree.extending, baseEnv, true, false, true)
953 : ((tree.mods.flags & Flags.ENUM) != 0)
954 ? attr.attribBase(enumBase(tree.pos, c), baseEnv,
955 true, false, false)
956 : (c.fullname == names.java_lang_Object)
957 ? Type.noType
958 : syms.objectType;
959 ct.supertype_field = modelMissingTypes(supertype, tree.extending, false);
960
961 // Determine interfaces.
962 ListBuffer<Type> interfaces = new ListBuffer<>();
963 ListBuffer<Type> all_interfaces = null; // lazy init
964 Set<Type> interfaceSet = new HashSet<>();
965 List<JCExpression> interfaceTrees = tree.implementing;
966 for (JCExpression iface : interfaceTrees) {
967 Type i = attr.attribBase(iface, baseEnv, false, true, true);
968 if (i.hasTag(CLASS)) {
969 interfaces.append(i);
970 if (all_interfaces != null) all_interfaces.append(i);
971 chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet);
972 } else {
973 if (all_interfaces == null)
974 all_interfaces = new ListBuffer<Type>().appendList(interfaces);
975 all_interfaces.append(modelMissingTypes(i, iface, true));
976 }
977 }
978 if ((c.flags_field & ANNOTATION) != 0) {
979 ct.interfaces_field = List.of(syms.annotationType);
980 ct.all_interfaces_field = ct.interfaces_field;
981 } else {
982 ct.interfaces_field = interfaces.toList();
983 ct.all_interfaces_field = (all_interfaces == null)
984 ? ct.interfaces_field : all_interfaces.toList();
985 }
986
987 if (c.fullname == names.java_lang_Object) {
988 if (tree.extending != null) {
989 chk.checkNonCyclic(tree.extending.pos(),
990 supertype);
991 ct.supertype_field = Type.noType;
992 }
993 else if (tree.implementing.nonEmpty()) {
994 chk.checkNonCyclic(tree.implementing.head.pos(),
995 ct.interfaces_field.head);
996 ct.interfaces_field = List.nil();
997 }
998 }
999
1000 // Annotations.
1001 // In general, we cannot fully process annotations yet, but we
1002 // can attribute the annotation types and then check to see if the
1003 // @Deprecated annotation is present.
1004 attr.attribAnnotationTypes(tree.mods.annotations, baseEnv);
1005 if (hasDeprecatedAnnotation(tree.mods.annotations))
1006 c.flags_field |= DEPRECATED;
1007 annotate.annotateLater(tree.mods.annotations, baseEnv, c, tree.pos());
1008 // class type parameters use baseEnv but everything uses env
1009
1010 chk.checkNonCyclicDecl(tree);
1011
1012 attr.attribTypeVariables(tree.typarams, baseEnv);
1013 // Do this here, where we have the symbol.
1014 for (JCTypeParameter tp : tree.typarams)
1015 annotate.annotateTypeLater(tp, baseEnv, sym, tree.pos());
1016
1017 // Add default constructor if needed.
1018 if ((c.flags() & INTERFACE) == 0 &&
1019 !TreeInfo.hasConstructors(tree.defs)) {
1020 List<Type> argtypes = List.nil();
1021 List<Type> typarams = List.nil();
1022 List<Type> thrown = List.nil();
1023 long ctorFlags = 0;
1024 boolean based = false;
1025 boolean addConstructor = true;
1026 JCNewClass nc = null;
1027 if (c.name.isEmpty()) {
1028 nc = (JCNewClass)env.next.tree;
1029 if (nc.constructor != null) {
1030 addConstructor = nc.constructor.kind != ERR;
1031 Type superConstrType = types.memberType(c.type,
1032 nc.constructor);
1033 argtypes = superConstrType.getParameterTypes();
1034 typarams = superConstrType.getTypeArguments();
1035 ctorFlags = nc.constructor.flags() & VARARGS;
1076 }
1077 if (c.owner.kind == PCK && (c.flags_field & PUBLIC) == 0 &&
1078 !env.toplevel.sourcefile.isNameCompatible(c.name.toString(),JavaFileObject.Kind.SOURCE)) {
1079 c.flags_field |= AUXILIARY;
1080 }
1081 } catch (CompletionFailure ex) {
1082 chk.completionError(tree.pos(), ex);
1083 } finally {
1084 deferredLintHandler.setPos(prevLintPos);
1085 log.useSource(prev);
1086 }
1087
1088 // Enter all member fields and methods of a set of half completed
1089 // classes in a second phase.
1090 if (wasFirst) {
1091 try {
1092 while (halfcompleted.nonEmpty()) {
1093 Env<AttrContext> toFinish = halfcompleted.next();
1094 finish(toFinish);
1095 if (allowTypeAnnos) {
1096 typeAnnotations.organizeTypeAnnotationsSignatures(toFinish, (JCClassDecl)toFinish.tree);
1097 typeAnnotations.validateTypeAnnotationsSignatures(toFinish, (JCClassDecl)toFinish.tree);
1098 }
1099 }
1100 } finally {
1101 isFirst = true;
1102 }
1103 }
1104 }
1105
1106 private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
1107 Scope baseScope = new Scope(tree.sym);
1108 //import already entered local classes into base scope
1109 for (Scope.Entry e = env.outer.info.scope.elems ; e != null ; e = e.sibling) {
1110 if (e.sym.isLocal()) {
1111 baseScope.enter(e.sym);
1112 }
1113 }
1114 //import current type-parameters into base scope
1115 if (tree.typarams != null)
1116 for (List<JCTypeParameter> typarams = tree.typarams;
|
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 */
25
26 package com.sun.tools.javac.comp;
27
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;
33
34 import javax.lang.model.type.TypeKind;
35 import javax.tools.JavaFileObject;
36
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.*;
41
42 import com.sun.tools.javac.code.Type.*;
43 import com.sun.tools.javac.code.Symbol.*;
44 import com.sun.tools.javac.tree.JCTree.*;
45 import com.sun.tools.javac.code.TypeAnnotationPosition.*;
46
47 import static com.sun.tools.javac.code.Flags.*;
48 import static com.sun.tools.javac.code.Flags.ANNOTATION;
49 import static com.sun.tools.javac.code.Kinds.*;
50 import static com.sun.tools.javac.code.TypeTag.CLASS;
51 import static com.sun.tools.javac.code.TypeTag.ERROR;
52 import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
53 import static com.sun.tools.javac.tree.JCTree.Tag.*;
54 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
55 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
56
57 /** This is the second phase of Enter, in which classes are completed
58 * by entering their members into the class scope using
59 * MemberEnter.complete(). See Enter for an overview.
60 *
61 * <p><b>This is NOT part of any supported API.
62 * If you write code that depends on this, you do so at your own risk.
63 * This code and its internal interfaces are subject to change or
64 * deletion without notice.</b>
65 */
98 protected MemberEnter(Context context) {
99 context.put(memberEnterKey, this);
100 names = Names.instance(context);
101 enter = Enter.instance(context);
102 log = Log.instance(context);
103 chk = Check.instance(context);
104 attr = Attr.instance(context);
105 syms = Symtab.instance(context);
106 make = TreeMaker.instance(context);
107 reader = ClassReader.instance(context);
108 todo = Todo.instance(context);
109 annotate = Annotate.instance(context);
110 typeAnnotations = TypeAnnotations.instance(context);
111 types = Types.instance(context);
112 diags = JCDiagnostic.Factory.instance(context);
113 source = Source.instance(context);
114 target = Target.instance(context);
115 deferredLintHandler = DeferredLintHandler.instance(context);
116 lint = Lint.instance(context);
117 allowTypeAnnos = source.allowTypeAnnotations();
118 speculative = false;
119 }
120
121 /** Switch: support type annotations.
122 */
123 boolean allowTypeAnnos;
124
125 /** A queue for classes whose members still need to be entered into the
126 * symbol table.
127 */
128 ListBuffer<Env<AttrContext>> halfcompleted = new ListBuffer<>();
129
130 /** Set to true only when the first of a set of classes is
131 * processed from the half completed queue.
132 */
133 boolean isFirst = true;
134
135 /** A flag to disable completion from time to time during member
136 * enter, as we only need to look up types. This avoids
137 * unnecessarily deep recursion.
138 */
139 boolean completionEnabled = true;
140
141 /** The creator that will be used for any varDef's we visit. */
142 Annotate.PositionCreator creator;
143
144 boolean speculative;
145
146 /* ---------- Processing import clauses ----------------
147 */
148
149 /** Import all classes of a class or package on demand.
150 * @param pos Position to be used for error reporting.
151 * @param tsym The class or package the members of which are imported.
152 * @param env The env in which the imported classes will be entered.
153 */
154 private void importAll(int pos,
155 final TypeSymbol tsym,
156 Env<AttrContext> env) {
157 // Check that packages imported from exist (JLS ???).
158 if (tsym.kind == PCK && tsym.members().elems == null && !tsym.exists()) {
159 // If we can't find java.lang, exit immediately.
160 if (((PackageSymbol)tsym).fullname.equals(names.java_lang)) {
161 JCDiagnostic msg = diags.fragment("fatal.err.no.java.lang");
162 throw new FatalError(msg);
163 } else {
164 log.error(DiagnosticFlag.RESOLVE_ERROR, pos, "doesnt.exist", tsym);
165 }
352 * @param tsym The class to be imported.
353 * @param env The environment containing the named import
354 * scope to add to.
355 */
356 private void importNamed(DiagnosticPosition pos, Symbol tsym, Env<AttrContext> env) {
357 if (tsym.kind == TYP &&
358 chk.checkUniqueImport(pos, tsym, env.toplevel.namedImportScope))
359 env.toplevel.namedImportScope.enter(tsym, tsym.owner.members());
360 }
361
362 /** Construct method type from method signature.
363 * @param typarams The method's type parameters.
364 * @param params The method's value parameters.
365 * @param res The method's result type,
366 * null if it is a constructor.
367 * @param recvparam The method's receiver parameter,
368 * null if none given; TODO: or already set here?
369 * @param thrown The method's thrown exceptions.
370 * @param env The method's (local) environment.
371 */
372 Type signature(final MethodSymbol msym,
373 final List<JCTypeParameter> typarams,
374 final List<JCVariableDecl> params,
375 final JCTree res,
376 final JCVariableDecl recvparam,
377 final List<JCExpression> thrown,
378 final Env<AttrContext> env,
379 final List<JCAnnotation> declAnnos,
380 final DiagnosticPosition deferPos) {
381 int i;
382
383 // Enter and attribute type parameters.
384 List<Type> tvars = enter.classEnter(typarams, env);
385 attr.attribTypeVariables(typarams, env, currentLambda, speculative);
386
387 // Handle type annotations on type parameters
388 i = 0;
389 for (List<JCTypeParameter> l = typarams; l.nonEmpty();
390 l = l.tail, i++) {
391 final JCTypeParameter param = l.head;
392 annotate.annotateTypeLater(param, env, msym, deferPos, currentLambda,
393 annotate.methodTypeParamCreator(i),
394 speculative);
395
396 int j = 0;
397 for (List<JCExpression> bounds = param.bounds;
398 bounds.nonEmpty(); bounds = bounds.tail, j++) {
399 annotate.annotateTypeLater(bounds.head, env, msym, deferPos, currentLambda,
400 annotate.methodTypeParamBoundCreator(param, i, j),
401 speculative);
402 }
403 }
404
405 // Enter and attribute value parameters.
406 ListBuffer<Type> argbuf = new ListBuffer<>();
407 i = 0;
408 for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail, i++) {
409 memberEnter(l.head, env, annotate.paramCreator(i));
410 argbuf.append(l.head.vartype.type);
411 }
412
413 // Attribute result type, if one is given.
414 Type restype;
415
416 if (res != null) {
417 restype = attr.attribType(res, env, currentLambda, speculative);
418 annotate.annotateTypeLater(res, declAnnos, env, msym, deferPos,
419 currentLambda, annotate.returnCreator,
420 speculative);
421 } else {
422 // For constructors, synthesize a type annotation position
423 List<TypePathEntry> typepath = List.nil();
424 Type encl = msym.owner.type.getEnclosingType();
425 while (encl != null && encl.getKind() != TypeKind.NONE &&
426 encl.getKind() != TypeKind.ERROR) {
427 typepath = typepath.prepend(TypePathEntry.INNER_TYPE);
428 encl = encl.getEnclosingType();
429 }
430 TypeAnnotationPosition tapos =
431 TypeAnnotationPosition.methodReturn(typepath, currentLambda, -1);
432 annotate.annotateLater(declAnnos, env, msym, deferPos, tapos);
433 restype = syms.voidType;
434 }
435
436
437 // Attribute receiver type, if one is given.
438 Type recvtype;
439 if (recvparam!=null) {
440 memberEnter(recvparam, env, annotate.receiverCreator);
441 recvtype = recvparam.vartype.type;
442 } else {
443 recvtype = null;
444 }
445
446 // Attribute thrown exceptions.
447 ListBuffer<Type> thrownbuf = new ListBuffer<>();
448 i = 0;
449 for (List<JCExpression> l = thrown; l.nonEmpty(); l = l.tail, i++) {
450 Type exc = attr.attribType(l.head, env, currentLambda, speculative);
451 annotate.annotateTypeLater(l.head, env, msym, deferPos,
452 currentLambda,
453 annotate.throwCreator(i),
454 speculative);
455 if (!exc.hasTag(TYPEVAR)) {
456 exc = chk.checkClassType(l.head.pos(), exc);
457 } else if (exc.tsym.owner == msym) {
458 //mark inference variables in 'throws' clause
459 exc.tsym.flags_field |= THROWS;
460 }
461 thrownbuf.append(exc);
462 }
463 MethodType mtype = new MethodType(argbuf.toList(),
464 restype,
465 thrownbuf.toList(),
466 syms.methodClass);
467 mtype.recvtype = recvtype;
468
469 return tvars.isEmpty() ? mtype : new ForAll(tvars, mtype);
470 }
471
472 /* ********************************************************************
473 * Visitor methods for member enter
474 *********************************************************************/
475
476 /** Visitor argument: the current environment
477 */
478 protected Env<AttrContext> env;
479
480 protected JCLambda currentLambda;
481
482 /** Enter field and method definitions and process import
483 * clauses, catching any completion failure exceptions.
484 */
485 protected void memberEnter(JCTree tree, Env<AttrContext> env,
486 Annotate.PositionCreator creator,
487 JCLambda lambda,
488 boolean speculative) {
489 Env<AttrContext> prevEnv = this.env;
490 Annotate.PositionCreator prevCreator = this.creator;
491 JCLambda prevLambda = this.currentLambda;
492 boolean prevSpeculative = this.speculative;
493 try {
494 this.env = env;
495 this.creator = creator;
496 this.currentLambda = lambda;
497 this.speculative = speculative;
498 tree.accept(this);
499 } catch (CompletionFailure ex) {
500 chk.completionError(tree.pos(), ex);
501 } finally {
502 this.creator = prevCreator;
503 this.env = prevEnv;
504 this.currentLambda = prevLambda;
505 this.speculative = prevSpeculative;
506 }
507 }
508
509 protected void memberEnter(JCTree tree,
510 Env<AttrContext> env,
511 Annotate.PositionCreator creator) {
512 memberEnter(tree, env, creator, currentLambda, speculative);
513 }
514
515 protected void memberEnter(JCTree tree, Env<AttrContext> env) {
516 memberEnter(tree, env, annotate.noCreator, currentLambda, speculative);
517 }
518
519 /** Enter members from a list of trees.
520 */
521 void memberEnter(List<? extends JCTree> trees,
522 Env<AttrContext> env,
523 Annotate.PositionCreator creator,
524 JCLambda lambda,
525 boolean speculative) {
526 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
527 memberEnter(l.head, env, creator, lambda, speculative);
528 }
529
530 void memberEnter(List<? extends JCTree> trees,
531 Env<AttrContext> env,
532 Annotate.PositionCreator creator) {
533 memberEnter(trees, env, creator, currentLambda, speculative);
534 }
535
536 void memberEnter(List<? extends JCTree> trees,
537 Env<AttrContext> env) {
538 memberEnter(trees, env, annotate.noCreator, currentLambda, speculative);
539 }
540
541 /** Enter members for a class.
542 */
543 void finishClass(final JCClassDecl tree, final Env<AttrContext> env) {
544 if ((tree.mods.flags & Flags.ENUM) != 0 &&
545 (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
546 addEnumMembers(tree, env);
547 }
548 memberEnter(tree.defs, env, annotate.fieldCreator);
549 }
550
551 /** Add the implicit members for an enum type
552 * to the symbol table.
553 */
554 private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
555 JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass,
556 Type.noAnnotations));
557
558 // public static T[] values() { return ???; }
559 JCMethodDecl values = make.
560 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
561 names.values,
562 valuesType,
563 List.<JCTypeParameter>nil(),
564 List.<JCVariableDecl>nil(),
565 List.<JCExpression>nil(), // thrown
566 null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
567 null);
568 memberEnter(values, env);
603 deferredLintHandler.setPos(prevLintPos);
604 }
605 }
606
607 public void visitPackageDef(JCPackageDecl tree) {
608 // check that no class exists with same fully qualified name as
609 // toplevel package
610 if (checkClash && tree.pid != null) {
611 Symbol p = env.toplevel.packge;
612 while (p.owner != syms.rootPackage) {
613 p.owner.complete(); // enter all class members of p
614 if (syms.classes.get(p.getQualifiedName()) != null) {
615 log.error(tree.pos,
616 "pkg.clashes.with.class.of.same.name",
617 p);
618 }
619 p = p.owner;
620 }
621 }
622 // process package annotations
623 annotate.annotateLater(tree.annotations, env, env.toplevel.packge);
624 }
625
626 // process the non-static imports and the static imports of types.
627 public void visitImport(JCImport tree) {
628 JCFieldAccess imp = (JCFieldAccess)tree.qualid;
629 Name name = TreeInfo.name(imp);
630
631 // Create a local environment pointing to this tree to disable
632 // effects of other imports in Resolve.findGlobalType
633 Env<AttrContext> localEnv = env.dup(tree);
634
635 TypeSymbol p = attr.attribImportQualifier(tree, localEnv, currentLambda,
636 speculative).tsym;
637 if (name == names.asterisk) {
638 // Import on demand.
639 chk.checkCanonical(imp.selected);
640 if (tree.staticImport)
641 importStaticAll(tree.pos, p, env);
642 else
643 importAll(tree.pos, p, env);
644 } else {
645 // Named type import.
646 if (tree.staticImport) {
647 importNamedStatic(tree.pos(), p, name, localEnv);
648 chk.checkCanonical(imp.selected);
649 } else {
650 TypeSymbol c = attribImportType(imp, localEnv).tsym;
651 chk.checkCanonical(imp);
652 importNamed(tree.pos(), c, env);
653 }
654 }
655 }
656
657 public void visitMethodDef(JCMethodDecl tree) {
658 Scope enclScope = enter.enterScope(env);
659 MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner);
660 m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree);
661 tree.sym = m;
662
663 //if this is a default method, add the DEFAULT flag to the enclosing interface
664 if ((tree.mods.flags & DEFAULT) != 0) {
665 m.enclClass().flags_field |= DEFAULT;
666 }
667
668 Env<AttrContext> localEnv = methodEnv(tree, env);
669
670 annotate.enterStart();
671 try {
672 DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());
673 try {
674 // Compute the method type
675 m.type = signature(m, tree.typarams, tree.params,
676 tree.restype, tree.recvparam,
677 tree.thrown, localEnv,
678 tree.mods.annotations, tree.pos());
679 } finally {
680 deferredLintHandler.setPos(prevLintPos);
681 }
682
683 if (types.isSignaturePolymorphic(m)) {
684 m.flags_field |= SIGNATURE_POLYMORPHIC;
685 }
686
687 // Set m.params
688 ListBuffer<VarSymbol> params = new ListBuffer<>();
689 JCVariableDecl lastParam = null;
690 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
691 JCVariableDecl param = lastParam = l.head;
692 params.append(Assert.checkNonNull(param.sym));
693 }
694 m.params = params.toList();
695
696 // mark the method varargs, if necessary
697 if (lastParam != null && (lastParam.mods.flags & Flags.VARARGS) != 0)
698 m.flags_field |= Flags.VARARGS;
699
700 localEnv.info.scope.leave();
701 if (chk.checkUnique(tree.pos(), m, enclScope)) {
702 enclScope.enter(m);
703 }
704
705 if (tree.defaultValue != null)
706 annotateDefaultValueLater(tree.defaultValue, localEnv,
707 m, annotate.noCreator);
708 } finally {
709 annotate.enterDone();
710 }
711 }
712
713 /** Create a fresh environment for method bodies.
714 * @param tree The method definition.
715 * @param env The environment current outside of the method definition.
716 */
717 Env<AttrContext> methodEnv(JCMethodDecl tree, Env<AttrContext> env) {
718 Env<AttrContext> localEnv =
719 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
720 localEnv.enclMethod = tree;
721 localEnv.info.scope.owner = tree.sym;
722 if (tree.sym.type != null) {
723 //when this is called in the enter stage, there's no type to be set
724 localEnv.info.returnResult = attr.new ResultInfo(VAL, tree.sym.type.getReturnType());
725 }
726 if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++;
727 return localEnv;
728 }
729
730 public void visitVarDef(JCVariableDecl tree) {
731 Env<AttrContext> localEnv = env;
732 if ((tree.mods.flags & STATIC) != 0 ||
733 (env.info.scope.owner.flags() & INTERFACE) != 0) {
734 localEnv = env.dup(tree, env.info.dup());
735 localEnv.info.staticLevel++;
736 }
737 DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());
738 annotate.enterStart();
739 try {
740 try {
741 if (TreeInfo.isEnumInit(tree)) {
742 attr.attribIdentAsEnumType(localEnv, (JCIdent)tree.vartype);
743 } else {
744 attr.attribType(tree.vartype, localEnv,
745 currentLambda, speculative);
746 if (tree.nameexpr != null) {
747 attr.attribExpr(tree.nameexpr, localEnv);
748 MethodSymbol m = localEnv.enclMethod.sym;
749 if (m.isConstructor()) {
750 Type outertype = m.owner.owner.type;
751 if (outertype.hasTag(TypeTag.CLASS)) {
752 checkType(tree.vartype, outertype, "incorrect.constructor.receiver.type");
753 checkType(tree.nameexpr, outertype, "incorrect.constructor.receiver.name");
754 } else {
755 log.error(tree, "receiver.parameter.not.applicable.constructor.toplevel.class");
756 }
757 } else {
758 checkType(tree.vartype, m.owner.type, "incorrect.receiver.type");
759 checkType(tree.nameexpr, m.owner.type, "incorrect.receiver.name");
760 }
761 }
762 }
763 } finally {
764 deferredLintHandler.setPos(prevLintPos);
765 }
768 //if we are entering a varargs parameter, we need to
769 //replace its type (a plain array type) with the more
770 //precise VarargsType --- we need to do it this way
771 //because varargs is represented in the tree as a
772 //modifier on the parameter declaration, and not as a
773 //distinct type of array node.
774 ArrayType atype = (ArrayType)tree.vartype.type;
775 tree.vartype.type = atype.makeVarargs();
776 }
777 Scope enclScope = enter.enterScope(env);
778 VarSymbol v =
779 new VarSymbol(0, tree.name, tree.vartype.type, enclScope.owner);
780 v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree);
781 tree.sym = v;
782 if (tree.init != null) {
783 v.flags_field |= HASINIT;
784 if ((v.flags_field & FINAL) != 0 &&
785 needsLazyConstValue(tree.init)) {
786 Env<AttrContext> initEnv = getInitEnv(tree, env);
787 initEnv.info.enclVar = v;
788 v.setLazyConstValue(initEnv(tree, initEnv), attr, tree,
789 currentLambda, speculative);
790 }
791 }
792 if (chk.checkUnique(tree.pos(), v, enclScope)) {
793 chk.checkTransparentVar(tree.pos(), v, enclScope);
794 enclScope.enter(v);
795 }
796 annotate.annotateTypeLater(tree.vartype, tree.mods.annotations,
797 localEnv, v, tree.pos(),
798 currentLambda, creator, speculative);
799 v.pos = tree.pos;
800 } finally {
801 annotate.enterDone();
802 }
803 }
804 // where
805 void checkType(JCTree tree, Type type, String diag) {
806 if (!tree.type.isErroneous() && !types.isSameType(tree.type, type)) {
807 log.error(tree, diag, type, tree.type);
808 }
809 }
810
811 public boolean needsLazyConstValue(JCTree tree) {
812 InitTreeVisitor initTreeVisitor = new InitTreeVisitor();
813 tree.accept(initTreeVisitor);
814 return initTreeVisitor.result;
815 }
816
817 /** Visitor class for expressions which might be constant expressions.
818 */
909 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail)
910 mEnv.info.scope.enterIfAbsent(l.head.sym);
911 return mEnv;
912 }
913
914 public Env<AttrContext> getInitEnv(JCVariableDecl tree, Env<AttrContext> env) {
915 Env<AttrContext> iEnv = initEnv(tree, env);
916 return iEnv;
917 }
918
919 /* ********************************************************************
920 * Type completion
921 *********************************************************************/
922
923 Type attribImportType(JCTree tree, Env<AttrContext> env) {
924 Assert.check(completionEnabled);
925 try {
926 // To prevent deep recursion, suppress completion of some
927 // types.
928 completionEnabled = false;
929 return attr.attribType(tree, env, currentLambda, speculative);
930 } finally {
931 completionEnabled = true;
932 }
933 }
934
935 /**
936 * Check if a list of annotations contains a reference to
937 * java.lang.Deprecated.
938 **/
939 private boolean hasDeprecatedAnnotation(List<JCAnnotation> annotations) {
940 for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
941 JCAnnotation a = al.head;
942 if (a.annotationType.type == syms.deprecatedType && a.args.isEmpty())
943 return true;
944 }
945 return false;
946 }
947
948 /** Queue processing of an attribute default value. */
949 void annotateDefaultValueLater(final JCExpression defaultValue,
950 final Env<AttrContext> localEnv,
951 final MethodSymbol m,
952 final Annotate.PositionCreator creator) {
953 annotate.normal(new Annotate.Worker() {
954 @Override
955 public String toString() {
956 return "annotate " + m.owner + "." +
957 m + " default " + defaultValue;
958 }
959
960 @Override
961 public void run() {
962 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
963 final TypeAnnotationPosition position = creator.create();
964 try {
965 enterDefaultValue(defaultValue, localEnv, m, position);
966 } finally {
967 log.useSource(prev);
968 }
969 }
970 });
971 annotate.validate(new Annotate.Worker() { //validate annotations
972 @Override
973 public void run() {
974 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
975 try {
976 // if default value is an annotation, check it is a well-formed
977 // annotation value (e.g. no duplicate values, no missing values, etc.)
978 chk.validateAnnotationTree(defaultValue);
979 } finally {
980 log.useSource(prev);
981 }
982 }
983 });
984 }
985
986 /** Enter a default value for an attribute method. */
987 private void enterDefaultValue(final JCExpression defaultValue,
988 final Env<AttrContext> localEnv,
989 final MethodSymbol m,
990 final TypeAnnotationPosition position) {
991 m.defaultValue = annotate.enterAttributeValue(m.type.getReturnType(),
992 defaultValue,
993 localEnv,
994 position);
995 }
996
997 /* ********************************************************************
998 * Source completer
999 *********************************************************************/
1000
1001 /** Complete entering a class.
1002 * @param sym The symbol of the class to be completed.
1003 */
1004 public void complete(Symbol sym) throws CompletionFailure {
1005 // Suppress some (recursive) MemberEnter invocations
1006 if (!completionEnabled) {
1007 // Re-install same completer for next time around and return.
1008 Assert.check((sym.flags() & Flags.COMPOUND) == 0);
1009 sym.completer = this;
1010 return;
1011 }
1012
1013 int i;
1014 ClassSymbol c = (ClassSymbol)sym;
1015 ClassType ct = (ClassType)c.type;
1016 Env<AttrContext> env = enter.typeEnvs.get(c);
1017 JCClassDecl tree = (JCClassDecl)env.tree;
1018 boolean wasFirst = isFirst;
1019 isFirst = false;
1020
1021 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
1022 DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());
1023 try {
1024 // Save class environment for later member enter (2) processing.
1025 halfcompleted.append(env);
1026
1027 // Mark class as not yet attributed.
1028 c.flags_field |= UNATTRIBUTED;
1029
1030 // If this is a toplevel-class, make sure any preceding import
1031 // clauses have been seen.
1032 if (c.owner.kind == PCK) {
1033 memberEnter(env.toplevel, env.enclosing(TOPLEVEL));
1034 todo.append(env);
1035 }
1036
1037 if (c.owner.kind == TYP)
1038 c.owner.complete();
1039
1040 // create an environment for evaluating the base clauses
1041 Env<AttrContext> baseEnv = baseEnv(tree, env);
1042
1043 // Determine supertype.
1044 Type supertype;
1045
1046 if (tree.extending != null) {
1047 supertype = attr.attribBase(tree.extending, baseEnv,
1048 true, false, true, currentLambda,
1049 speculative);
1050 annotate.annotateTypeLater(tree.extending, baseEnv, sym,
1051 tree.pos(), currentLambda,
1052 annotate.extendsCreator,
1053 speculative);
1054 } else {
1055 supertype = ((tree.mods.flags & Flags.ENUM) != 0)
1056 ? attr.attribBase(enumBase(tree.pos, c), baseEnv,
1057 true, false, false, currentLambda,
1058 speculative)
1059 : (c.fullname == names.java_lang_Object)
1060 ? Type.noType
1061 : syms.objectType;
1062 }
1063 ct.supertype_field = modelMissingTypes(supertype, tree.extending, false);
1064
1065 // Determine interfaces.
1066 ListBuffer<Type> interfaces = new ListBuffer<>();
1067 ListBuffer<Type> all_interfaces = null; // lazy init
1068 Set<Type> interfaceSet = new HashSet<>();
1069 List<JCExpression> interfaceTrees = tree.implementing;
1070 i = 0;
1071 for (JCExpression iface : interfaceTrees) {
1072 Type it = attr.attribBase(iface, baseEnv, false, true, true,
1073 currentLambda, speculative);
1074 if (it.hasTag(CLASS)) {
1075 interfaces.append(it);
1076 if (all_interfaces != null) all_interfaces.append(it);
1077 chk.checkNotRepeated(iface.pos(), types.erasure(it), interfaceSet);
1078 } else {
1079 if (all_interfaces == null)
1080 all_interfaces = new ListBuffer<Type>().appendList(interfaces);
1081 all_interfaces.append(modelMissingTypes(it, iface, true));
1082
1083 }
1084 annotate.annotateTypeLater(iface, baseEnv, sym, tree.pos(),
1085 currentLambda, annotate.implementsCreator(i++),
1086 speculative);
1087 }
1088 annotate.flush();
1089
1090 if ((c.flags_field & ANNOTATION) != 0) {
1091 ct.interfaces_field = List.of(syms.annotationType);
1092 ct.all_interfaces_field = ct.interfaces_field;
1093 } else {
1094 ct.interfaces_field = interfaces.toList();
1095 ct.all_interfaces_field = (all_interfaces == null)
1096 ? ct.interfaces_field : all_interfaces.toList();
1097 }
1098
1099 if (c.fullname == names.java_lang_Object) {
1100 if (tree.extending != null) {
1101 chk.checkNonCyclic(tree.extending.pos(),
1102 supertype);
1103 ct.supertype_field = Type.noType;
1104 }
1105 else if (tree.implementing.nonEmpty()) {
1106 chk.checkNonCyclic(tree.implementing.head.pos(),
1107 ct.interfaces_field.head);
1108 ct.interfaces_field = List.nil();
1109 }
1110 }
1111
1112 // Annotations.
1113 // In general, we cannot fully process annotations yet, but we
1114 // can attribute the annotation types and then check to see if the
1115 // @Deprecated annotation is present.
1116 attr.attribAnnotationTypes(tree.mods.annotations, baseEnv,
1117 currentLambda, speculative);
1118 if (hasDeprecatedAnnotation(tree.mods.annotations))
1119 c.flags_field |= DEPRECATED;
1120 annotate.annotateLater(tree.mods.annotations, baseEnv, c, tree.pos());
1121 // class type parameters use baseEnv but everything uses env
1122
1123 chk.checkNonCyclicDecl(tree);
1124
1125 attr.attribTypeVariables(tree.typarams, baseEnv,
1126 currentLambda, speculative);
1127 // Do this here, where we have the symbol.
1128 i = 0;
1129 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty();
1130 l = l.tail, i++) {
1131 final JCTypeParameter typaram = l.head;
1132 annotate.annotateTypeLater(typaram, baseEnv, sym, tree.pos(),
1133 currentLambda, annotate.typeParamCreator(i),
1134 speculative);
1135
1136 int j = 0;
1137 for(List<JCExpression> b = typaram.bounds; b.nonEmpty();
1138 b = b.tail, j++) {
1139 final JCExpression bound = b.head;
1140 annotate.annotateTypeLater(bound, baseEnv, sym,
1141 tree.pos(), currentLambda,
1142 annotate.typeParamBoundCreator(typaram, i, j),
1143 speculative);
1144 }
1145
1146 }
1147
1148 // Add default constructor if needed.
1149 if ((c.flags() & INTERFACE) == 0 &&
1150 !TreeInfo.hasConstructors(tree.defs)) {
1151 List<Type> argtypes = List.nil();
1152 List<Type> typarams = List.nil();
1153 List<Type> thrown = List.nil();
1154 long ctorFlags = 0;
1155 boolean based = false;
1156 boolean addConstructor = true;
1157 JCNewClass nc = null;
1158 if (c.name.isEmpty()) {
1159 nc = (JCNewClass)env.next.tree;
1160 if (nc.constructor != null) {
1161 addConstructor = nc.constructor.kind != ERR;
1162 Type superConstrType = types.memberType(c.type,
1163 nc.constructor);
1164 argtypes = superConstrType.getParameterTypes();
1165 typarams = superConstrType.getTypeArguments();
1166 ctorFlags = nc.constructor.flags() & VARARGS;
1207 }
1208 if (c.owner.kind == PCK && (c.flags_field & PUBLIC) == 0 &&
1209 !env.toplevel.sourcefile.isNameCompatible(c.name.toString(),JavaFileObject.Kind.SOURCE)) {
1210 c.flags_field |= AUXILIARY;
1211 }
1212 } catch (CompletionFailure ex) {
1213 chk.completionError(tree.pos(), ex);
1214 } finally {
1215 deferredLintHandler.setPos(prevLintPos);
1216 log.useSource(prev);
1217 }
1218
1219 // Enter all member fields and methods of a set of half completed
1220 // classes in a second phase.
1221 if (wasFirst) {
1222 try {
1223 while (halfcompleted.nonEmpty()) {
1224 Env<AttrContext> toFinish = halfcompleted.next();
1225 finish(toFinish);
1226 if (allowTypeAnnos) {
1227 // Note: This call is slated for removal in
1228 // the next patch
1229 typeAnnotations.validateTypeAnnotationsSignatures(toFinish, (JCClassDecl)toFinish.tree);
1230 }
1231 }
1232 } finally {
1233 isFirst = true;
1234 }
1235 }
1236 }
1237
1238 private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
1239 Scope baseScope = new Scope(tree.sym);
1240 //import already entered local classes into base scope
1241 for (Scope.Entry e = env.outer.info.scope.elems ; e != null ; e = e.sibling) {
1242 if (e.sym.isLocal()) {
1243 baseScope.enter(e.sym);
1244 }
1245 }
1246 //import current type-parameters into base scope
1247 if (tree.typarams != null)
1248 for (List<JCTypeParameter> typarams = tree.typarams;
|