src/share/classes/com/sun/tools/javac/parser/JavacParser.java

changeset 1521
71f35e4b93a5
parent 1513
cf84b07a82db
child 1556
b1deb90d2e37
equal deleted inserted replaced
1520:5c956be64b9e 1521:71f35e4b93a5
1 /* 1 /*
2 * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved. 2 * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 * 4 *
5 * This code is free software; you can redistribute it and/or modify it 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 6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this 7 * published by the Free Software Foundation. Oracle designates this
85 /** The name table. */ 85 /** The name table. */
86 private Names names; 86 private Names names;
87 87
88 /** End position mappings container */ 88 /** End position mappings container */
89 private final AbstractEndPosTable endPosTable; 89 private final AbstractEndPosTable endPosTable;
90
91 // Because of javac's limited lookahead, some contexts are ambiguous in
92 // the presence of type annotations even though they are not ambiguous
93 // in the absence of type annotations. Consider this code:
94 // void m(String [] m) { }
95 // void m(String ... m) { }
96 // After parsing "String", javac calls bracketsOpt which immediately
97 // returns if the next character is not '['. Similarly, javac can see
98 // if the next token is ... and in that case parse an ellipsis. But in
99 // the presence of type annotations:
100 // void m(String @A [] m) { }
101 // void m(String @A ... m) { }
102 // no finite lookahead is enough to determine whether to read array
103 // levels or an ellipsis. Furthermore, if you call bracketsOpt, then
104 // bracketsOpt first reads all the leading annotations and only then
105 // discovers that it needs to fail. bracketsOpt needs a way to push
106 // back the extra annotations that it read. (But, bracketsOpt should
107 // not *always* be allowed to push back extra annotations that it finds
108 // -- in most contexts, any such extra annotation is an error.
109 //
110 // The following two variables permit type annotations that have
111 // already been read to be stored for later use. Alternate
112 // implementations are possible but would cause much larger changes to
113 // the parser.
114
115 /** Type annotations that have already been read but have not yet been used. **/
116 private List<JCAnnotation> typeAnnotationsPushedBack = List.nil();
117
118 /**
119 * If the parser notices extra annotations, then it either immediately
120 * issues an error (if this variable is false) or places the extra
121 * annotations in variable typeAnnotationsPushedBack (if this variable
122 * is true).
123 */
124 private boolean permitTypeAnnotationsPushBack = false;
90 125
91 interface ErrorRecoveryAction { 126 interface ErrorRecoveryAction {
92 JCTree doRecover(JavacParser parser); 127 JCTree doRecover(JavacParser parser);
93 } 128 }
94 129
124 this.allowLambda = source.allowLambda(); 159 this.allowLambda = source.allowLambda();
125 this.allowMethodReferences = source.allowMethodReferences(); 160 this.allowMethodReferences = source.allowMethodReferences();
126 this.allowDefaultMethods = source.allowDefaultMethods(); 161 this.allowDefaultMethods = source.allowDefaultMethods();
127 this.allowStaticInterfaceMethods = source.allowStaticInterfaceMethods(); 162 this.allowStaticInterfaceMethods = source.allowStaticInterfaceMethods();
128 this.allowIntersectionTypesInCast = source.allowIntersectionTypesInCast(); 163 this.allowIntersectionTypesInCast = source.allowIntersectionTypesInCast();
164 this.allowTypeAnnotations = source.allowTypeAnnotations();
129 this.keepDocComments = keepDocComments; 165 this.keepDocComments = keepDocComments;
130 docComments = newDocCommentTable(keepDocComments, fac); 166 docComments = newDocCommentTable(keepDocComments, fac);
131 this.keepLineMap = keepLineMap; 167 this.keepLineMap = keepLineMap;
132 this.errorTree = F.Erroneous(); 168 this.errorTree = F.Erroneous();
133 endPosTable = newEndPosTable(keepEndPositions); 169 endPosTable = newEndPosTable(keepEndPositions);
212 boolean keepDocComments; 248 boolean keepDocComments;
213 249
214 /** Switch: should we keep line table? 250 /** Switch: should we keep line table?
215 */ 251 */
216 boolean keepLineMap; 252 boolean keepLineMap;
253
254 /** Switch: should we recognize type annotations?
255 */
256 boolean allowTypeAnnotations;
257
258 /** Switch: is "this" allowed as an identifier?
259 * This is needed to parse receiver types.
260 */
261 boolean allowThisIdent;
262
263 /** The type of the method receiver, as specified by a first "this" parameter.
264 */
265 JCVariableDecl receiverParam;
266
217 267
218 /** When terms are parsed, the mode determines which is expected: 268 /** When terms are parsed, the mode determines which is expected:
219 * mode = EXPR : an expression 269 * mode = EXPR : an expression
220 * mode = TYPE : a type 270 * mode = TYPE : a type
221 * mode = NOPARAMS : no parameters allowed for type 271 * mode = NOPARAMS : no parameters allowed for type
556 warning(token.pos, "enum.as.identifier"); 606 warning(token.pos, "enum.as.identifier");
557 Name name = token.name(); 607 Name name = token.name();
558 nextToken(); 608 nextToken();
559 return name; 609 return name;
560 } 610 }
611 } else if (token.kind == THIS) {
612 if (allowThisIdent) {
613 // Make sure we're using a supported source version.
614 checkTypeAnnotations();
615 Name name = token.name();
616 nextToken();
617 return name;
618 } else {
619 error(token.pos, "this.as.identifier");
620 nextToken();
621 return names.error;
622 }
561 } else if (token.kind == UNDERSCORE) { 623 } else if (token.kind == UNDERSCORE) {
562 warning(token.pos, "underscore.as.identifier"); 624 warning(token.pos, "underscore.as.identifier");
563 Name name = token.name(); 625 Name name = token.name();
564 nextToken(); 626 nextToken();
565 return name; 627 return name;
568 return names.error; 630 return names.error;
569 } 631 }
570 } 632 }
571 633
572 /** 634 /**
573 * Qualident = Ident { DOT Ident } 635 * Qualident = Ident { DOT [Annotations] Ident }
574 */ 636 */
575 public JCExpression qualident() { 637 public JCExpression qualident(boolean allowAnnos) {
576 JCExpression t = toP(F.at(token.pos).Ident(ident())); 638 JCExpression t = toP(F.at(token.pos).Ident(ident()));
577 while (token.kind == DOT) { 639 while (token.kind == DOT) {
578 int pos = token.pos; 640 int pos = token.pos;
579 nextToken(); 641 nextToken();
642 List<JCAnnotation> tyannos = null;
643 if (allowAnnos) {
644 tyannos = typeAnnotationsOpt();
645 }
580 t = toP(F.at(pos).Select(t, ident())); 646 t = toP(F.at(pos).Select(t, ident()));
647 if (tyannos != null && tyannos.nonEmpty()) {
648 t = toP(F.at(tyannos.head.pos).AnnotatedType(tyannos, t));
649 }
581 } 650 }
582 return t; 651 return t;
583 } 652 }
584 653
585 JCExpression literal(Name prefix) { 654 JCExpression literal(Name prefix) {
684 t = F.at(pos).Erroneous(); 753 t = F.at(pos).Erroneous();
685 storeEnd(t, token.endPos); 754 storeEnd(t, token.endPos);
686 nextToken(); 755 nextToken();
687 return t; 756 return t;
688 } 757 }
689 //where 758 //where
690 boolean isZero(String s) { 759 boolean isZero(String s) {
691 char[] cs = s.toCharArray(); 760 char[] cs = s.toCharArray();
692 int base = ((cs.length > 1 && Character.toLowerCase(cs[1]) == 'x') ? 16 : 10); 761 int base = ((cs.length > 1 && Character.toLowerCase(cs[1]) == 'x') ? 16 : 10);
693 int i = ((base==16) ? 2 : 0); 762 int i = ((base==16) ? 2 : 0);
694 while (i < cs.length && (cs[i] == '0' || cs[i] == '.')) i++; 763 while (i < cs.length && (cs[i] == '0' || cs[i] == '.')) i++;
704 */ 773 */
705 public JCExpression parseExpression() { 774 public JCExpression parseExpression() {
706 return term(EXPR); 775 return term(EXPR);
707 } 776 }
708 777
778 /**
779 * parses (optional) type annotations followed by a type. If the
780 * annotations are present before the type and are not consumed during array
781 * parsing, this method returns a {@link JCAnnotatedType} consisting of
782 * these annotations and the underlying type. Otherwise, it returns the
783 * underlying type.
784 *
785 * <p>
786 *
787 * Note that this method sets {@code mode} to {@code TYPE} first, before
788 * parsing annotations.
789 */
709 public JCExpression parseType() { 790 public JCExpression parseType() {
791 List<JCAnnotation> annotations = typeAnnotationsOpt();
792 return parseType(annotations);
793 }
794
795 public JCExpression parseType(List<JCAnnotation> annotations) {
796 JCExpression result = unannotatedType();
797
798 if (annotations.nonEmpty()) {
799 result = insertAnnotationsToMostInner(result, annotations, false);
800 }
801
802 return result;
803 }
804
805 public JCExpression unannotatedType() {
710 return term(TYPE); 806 return term(TYPE);
711 } 807 }
712 808
713 JCExpression term(int newmode) { 809 JCExpression term(int newmode) {
714 int prevmode = mode; 810 int prevmode = mode;
862 958
863 odStackSupply.add(odStack); 959 odStackSupply.add(odStack);
864 opStackSupply.add(opStack); 960 opStackSupply.add(opStack);
865 return t; 961 return t;
866 } 962 }
867 //where 963 //where
868 /** Construct a binary or type test node. 964 /** Construct a binary or type test node.
869 */ 965 */
870 private JCExpression makeOp(int pos, 966 private JCExpression makeOp(int pos,
871 TokenKind topOp, 967 TokenKind topOp,
872 JCExpression od1, 968 JCExpression od1,
941 * | [TypeArguments] THIS [Arguments] 1037 * | [TypeArguments] THIS [Arguments]
942 * | [TypeArguments] SUPER SuperSuffix 1038 * | [TypeArguments] SUPER SuperSuffix
943 * | NEW [TypeArguments] Creator 1039 * | NEW [TypeArguments] Creator
944 * | "(" Arguments ")" "->" ( Expression | Block ) 1040 * | "(" Arguments ")" "->" ( Expression | Block )
945 * | Ident "->" ( Expression | Block ) 1041 * | Ident "->" ( Expression | Block )
946 * | Ident { "." Ident } 1042 * | [Annotations] Ident { "." [Annotations] Ident }
947 * | Expression3 MemberReferenceSuffix 1043 * | Expression3 MemberReferenceSuffix
948 * [ "[" ( "]" BracketsOpt "." CLASS | Expression "]" ) 1044 * [ [Annotations] "[" ( "]" BracketsOpt "." CLASS | Expression "]" )
949 * | Arguments 1045 * | Arguments
950 * | "." ( CLASS | THIS | [TypeArguments] SUPER Arguments | NEW [TypeArguments] InnerCreator ) 1046 * | "." ( CLASS | THIS | [TypeArguments] SUPER Arguments | NEW [TypeArguments] InnerCreator )
951 * ] 1047 * ]
952 * | BasicType BracketsOpt "." CLASS 1048 * | BasicType BracketsOpt "." CLASS
953 * } 1049 * }
1065 if (token.kind == LT) typeArgs = typeArguments(false); 1161 if (token.kind == LT) typeArgs = typeArguments(false);
1066 t = creator(pos, typeArgs); 1162 t = creator(pos, typeArgs);
1067 typeArgs = null; 1163 typeArgs = null;
1068 } else return illegal(); 1164 } else return illegal();
1069 break; 1165 break;
1166 case MONKEYS_AT:
1167 // Only annotated cast types are valid
1168 List<JCAnnotation> typeAnnos = typeAnnotationsOpt();
1169 if (typeAnnos.isEmpty()) {
1170 // else there would be no '@'
1171 throw new AssertionError("Expected type annotations, but found none!");
1172 }
1173
1174 JCExpression expr = term3();
1175
1176 if ((mode & TYPE) == 0) {
1177 // Type annotations on class literals no longer legal
1178 if (!expr.hasTag(Tag.SELECT)) {
1179 return illegal(typeAnnos.head.pos);
1180 }
1181 JCFieldAccess sel = (JCFieldAccess)expr;
1182
1183 if (sel.name != names._class) {
1184 return illegal();
1185 } else {
1186 log.error(token.pos, "no.annotations.on.dot.class");
1187 return expr;
1188 }
1189 } else {
1190 // Type annotations targeting a cast
1191 t = insertAnnotationsToMostInner(expr, typeAnnos, false);
1192 }
1193 break;
1070 case UNDERSCORE: case IDENTIFIER: case ASSERT: case ENUM: 1194 case UNDERSCORE: case IDENTIFIER: case ASSERT: case ENUM:
1071 if (typeArgs != null) return illegal(); 1195 if (typeArgs != null) return illegal();
1072 if ((mode & EXPR) != 0 && peekToken(ARROW)) { 1196 if ((mode & EXPR) != 0 && peekToken(ARROW)) {
1073 t = lambdaExpressionOrStatement(false, false, pos); 1197 t = lambdaExpressionOrStatement(false, false, pos);
1074 } else { 1198 } else {
1075 t = toP(F.at(token.pos).Ident(ident())); 1199 t = toP(F.at(token.pos).Ident(ident()));
1076 loop: while (true) { 1200 loop: while (true) {
1077 pos = token.pos; 1201 pos = token.pos;
1202 final List<JCAnnotation> annos = typeAnnotationsOpt();
1203
1204 // need to report an error later if LBRACKET is for array
1205 // index access rather than array creation level
1206 if (!annos.isEmpty() && token.kind != LBRACKET && token.kind != ELLIPSIS)
1207 return illegal(annos.head.pos);
1208
1078 switch (token.kind) { 1209 switch (token.kind) {
1079 case LBRACKET: 1210 case LBRACKET:
1080 nextToken(); 1211 nextToken();
1081 if (token.kind == RBRACKET) { 1212 if (token.kind == RBRACKET) {
1082 nextToken(); 1213 nextToken();
1083 t = bracketsOpt(t); 1214 t = bracketsOpt(t);
1084 t = toP(F.at(pos).TypeArray(t)); 1215 t = toP(F.at(pos).TypeArray(t));
1085 t = bracketsSuffix(t); 1216 if (annos.nonEmpty()) {
1217 t = toP(F.at(pos).AnnotatedType(annos, t));
1218 }
1219 // .class is only allowed if there were no annotations
1220 JCExpression nt = bracketsSuffix(t);
1221 if (nt != t && (annos.nonEmpty() || TreeInfo.containsTypeAnnotation(t))) {
1222 // t and nt are different if bracketsSuffix parsed a .class.
1223 // The check for nonEmpty covers the case when the whole array is annotated.
1224 // Helper method isAnnotated looks for annos deeply within t.
1225 syntaxError("no.annotations.on.dot.class");
1226 }
1227 t = nt;
1086 } else { 1228 } else {
1087 if ((mode & EXPR) != 0) { 1229 if ((mode & EXPR) != 0) {
1088 mode = EXPR; 1230 mode = EXPR;
1089 JCExpression t1 = term(); 1231 JCExpression t1 = term();
1232 if (!annos.isEmpty()) t = illegal(annos.head.pos);
1090 t = to(F.at(pos).Indexed(t, t1)); 1233 t = to(F.at(pos).Indexed(t, t1));
1091 } 1234 }
1092 accept(RBRACKET); 1235 accept(RBRACKET);
1093 } 1236 }
1094 break loop; 1237 break loop;
1095 case LPAREN: 1238 case LPAREN:
1096 if ((mode & EXPR) != 0) { 1239 if ((mode & EXPR) != 0) {
1097 mode = EXPR; 1240 mode = EXPR;
1098 t = arguments(typeArgs, t); 1241 t = arguments(typeArgs, t);
1242 if (!annos.isEmpty()) t = illegal(annos.head.pos);
1099 typeArgs = null; 1243 typeArgs = null;
1100 } 1244 }
1101 break loop; 1245 break loop;
1102 case DOT: 1246 case DOT:
1103 nextToken(); 1247 nextToken();
1134 t = innerCreator(pos1, typeArgs, t); 1278 t = innerCreator(pos1, typeArgs, t);
1135 typeArgs = null; 1279 typeArgs = null;
1136 break loop; 1280 break loop;
1137 } 1281 }
1138 } 1282 }
1283
1284 List<JCAnnotation> tyannos = null;
1285 if ((mode & TYPE) != 0 && token.kind == MONKEYS_AT) {
1286 tyannos = typeAnnotationsOpt();
1287 }
1139 // typeArgs saved for next loop iteration. 1288 // typeArgs saved for next loop iteration.
1140 t = toP(F.at(pos).Select(t, ident())); 1289 t = toP(F.at(pos).Select(t, ident()));
1290 if (tyannos != null && tyannos.nonEmpty()) {
1291 t = toP(F.at(tyannos.head.pos).AnnotatedType(tyannos, t));
1292 }
1141 break; 1293 break;
1294 case ELLIPSIS:
1295 if (this.permitTypeAnnotationsPushBack) {
1296 this.typeAnnotationsPushedBack = annos;
1297 } else if (annos.nonEmpty()) {
1298 // Don't return here -- error recovery attempt
1299 illegal(annos.head.pos);
1300 }
1301 break loop;
1142 case LT: 1302 case LT:
1143 if ((mode & TYPE) == 0 && isUnboundMemberRef()) { 1303 if ((mode & TYPE) == 0 && isUnboundMemberRef()) {
1144 //this is an unbound method reference whose qualifier 1304 //this is an unbound method reference whose qualifier
1145 //is a generic type i.e. A<S>::m 1305 //is a generic type i.e. A<S>::m
1146 int pos1 = token.pos; 1306 int pos1 = token.pos;
1210 1370
1211 JCExpression term3Rest(JCExpression t, List<JCExpression> typeArgs) { 1371 JCExpression term3Rest(JCExpression t, List<JCExpression> typeArgs) {
1212 if (typeArgs != null) illegal(); 1372 if (typeArgs != null) illegal();
1213 while (true) { 1373 while (true) {
1214 int pos1 = token.pos; 1374 int pos1 = token.pos;
1375 final List<JCAnnotation> annos = typeAnnotationsOpt();
1376
1215 if (token.kind == LBRACKET) { 1377 if (token.kind == LBRACKET) {
1216 nextToken(); 1378 nextToken();
1217 if ((mode & TYPE) != 0) { 1379 if ((mode & TYPE) != 0) {
1218 int oldmode = mode; 1380 int oldmode = mode;
1219 mode = TYPE; 1381 mode = TYPE;
1222 t = bracketsOpt(t); 1384 t = bracketsOpt(t);
1223 t = toP(F.at(pos1).TypeArray(t)); 1385 t = toP(F.at(pos1).TypeArray(t));
1224 if (token.kind == COLCOL) { 1386 if (token.kind == COLCOL) {
1225 mode = EXPR; 1387 mode = EXPR;
1226 continue; 1388 continue;
1389 }
1390 if (annos.nonEmpty()) {
1391 t = toP(F.at(pos1).AnnotatedType(annos, t));
1227 } 1392 }
1228 return t; 1393 return t;
1229 } 1394 }
1230 mode = oldmode; 1395 mode = oldmode;
1231 } 1396 }
1251 nextToken(); 1416 nextToken();
1252 if (token.kind == LT) typeArgs = typeArguments(false); 1417 if (token.kind == LT) typeArgs = typeArguments(false);
1253 t = innerCreator(pos2, typeArgs, t); 1418 t = innerCreator(pos2, typeArgs, t);
1254 typeArgs = null; 1419 typeArgs = null;
1255 } else { 1420 } else {
1421 List<JCAnnotation> tyannos = null;
1422 if ((mode & TYPE) != 0 && token.kind == MONKEYS_AT) {
1423 // is the mode check needed?
1424 tyannos = typeAnnotationsOpt();
1425 }
1256 t = toP(F.at(pos1).Select(t, ident())); 1426 t = toP(F.at(pos1).Select(t, ident()));
1427 if (tyannos != null && tyannos.nonEmpty()) {
1428 t = toP(F.at(tyannos.head.pos).AnnotatedType(tyannos, t));
1429 }
1257 t = argumentsOpt(typeArgs, typeArgumentsOpt(t)); 1430 t = argumentsOpt(typeArgs, typeArgumentsOpt(t));
1258 typeArgs = null; 1431 typeArgs = null;
1259 } 1432 }
1260 } else if ((mode & EXPR) != 0 && token.kind == COLCOL) { 1433 } else if ((mode & EXPR) != 0 && token.kind == COLCOL) {
1261 mode = EXPR; 1434 mode = EXPR;
1262 if (typeArgs != null) return illegal(); 1435 if (typeArgs != null) return illegal();
1263 accept(COLCOL); 1436 accept(COLCOL);
1264 t = memberReferenceSuffix(pos1, t); 1437 t = memberReferenceSuffix(pos1, t);
1265 } else { 1438 } else {
1439 if (!annos.isEmpty()) {
1440 if (permitTypeAnnotationsPushBack)
1441 typeAnnotationsPushedBack = annos;
1442 else
1443 return illegal(annos.head.pos);
1444 }
1266 break; 1445 break;
1267 } 1446 }
1268 } 1447 }
1269 while ((token.kind == PLUSPLUS || token.kind == SUBSUB) && (mode & EXPR) != 0) { 1448 while ((token.kind == PLUSPLUS || token.kind == SUBSUB) && (mode & EXPR) != 0) {
1270 mode = EXPR; 1449 mode = EXPR;
1319 */ 1498 */
1320 @SuppressWarnings("fallthrough") 1499 @SuppressWarnings("fallthrough")
1321 ParensResult analyzeParens() { 1500 ParensResult analyzeParens() {
1322 int depth = 0; 1501 int depth = 0;
1323 boolean type = false; 1502 boolean type = false;
1324 for (int lookahead = 0 ; ; lookahead++) { 1503 outer: for (int lookahead = 0 ; ; lookahead++) {
1325 TokenKind tk = S.token(lookahead).kind; 1504 TokenKind tk = S.token(lookahead).kind;
1326 switch (tk) { 1505 switch (tk) {
1327 case EXTENDS: case SUPER: case COMMA: 1506 case EXTENDS: case SUPER: case COMMA:
1328 type = true; 1507 type = true;
1329 case QUES: case DOT: case AMP: 1508 case QUES: case DOT: case AMP:
1380 return ParensResult.IMPLICIT_LAMBDA; 1559 return ParensResult.IMPLICIT_LAMBDA;
1381 } 1560 }
1382 break; 1561 break;
1383 case FINAL: 1562 case FINAL:
1384 case ELLIPSIS: 1563 case ELLIPSIS:
1385 case MONKEYS_AT:
1386 //those can only appear in explicit lambdas 1564 //those can only appear in explicit lambdas
1387 return ParensResult.EXPLICIT_LAMBDA; 1565 return ParensResult.EXPLICIT_LAMBDA;
1566 case MONKEYS_AT:
1567 type = true;
1568 lookahead += 1; //skip '@'
1569 while (peekToken(lookahead, DOT)) {
1570 lookahead += 2;
1571 }
1572 if (peekToken(lookahead, LPAREN)) {
1573 lookahead++;
1574 //skip annotation values
1575 int nesting = 0;
1576 for (; ; lookahead++) {
1577 TokenKind tk2 = S.token(lookahead).kind;
1578 switch (tk2) {
1579 case EOF:
1580 return ParensResult.PARENS;
1581 case LPAREN:
1582 nesting++;
1583 break;
1584 case RPAREN:
1585 nesting--;
1586 if (nesting == 0) {
1587 continue outer;
1588 }
1589 break;
1590 }
1591 }
1592 }
1593 break;
1388 case LBRACKET: 1594 case LBRACKET:
1389 if (peekToken(lookahead, RBRACKET, LAX_IDENTIFIER)) { 1595 if (peekToken(lookahead, RBRACKET, LAX_IDENTIFIER)) {
1390 // '[', ']', Identifier/'_'/'assert'/'enum' -> explicit lambda 1596 // '[', ']', Identifier/'_'/'assert'/'enum' -> explicit lambda
1391 return ParensResult.EXPLICIT_LAMBDA; 1597 return ParensResult.EXPLICIT_LAMBDA;
1392 } else if (peekToken(lookahead, RBRACKET, RPAREN) || 1598 } else if (peekToken(lookahead, RBRACKET, RPAREN) ||
1616 } 1822 }
1617 1823
1618 /** 1824 /**
1619 * {@literal 1825 * {@literal
1620 * TypeArgument = Type 1826 * TypeArgument = Type
1621 * | "?" 1827 * | [Annotations] "?"
1622 * | "?" EXTENDS Type {"&" Type} 1828 * | [Annotations] "?" EXTENDS Type {"&" Type}
1623 * | "?" SUPER Type 1829 * | [Annotations] "?" SUPER Type
1624 * } 1830 * }
1625 */ 1831 */
1626 JCExpression typeArgument() { 1832 JCExpression typeArgument() {
1627 if (token.kind != QUES) return parseType(); 1833 List<JCAnnotation> annotations = typeAnnotationsOpt();
1834 if (token.kind != QUES) return parseType(annotations);
1628 int pos = token.pos; 1835 int pos = token.pos;
1629 nextToken(); 1836 nextToken();
1837 JCExpression result;
1630 if (token.kind == EXTENDS) { 1838 if (token.kind == EXTENDS) {
1631 TypeBoundKind t = to(F.at(pos).TypeBoundKind(BoundKind.EXTENDS)); 1839 TypeBoundKind t = to(F.at(pos).TypeBoundKind(BoundKind.EXTENDS));
1632 nextToken(); 1840 nextToken();
1633 JCExpression bound = parseType(); 1841 JCExpression bound = parseType();
1634 return F.at(pos).Wildcard(t, bound); 1842 result = F.at(pos).Wildcard(t, bound);
1635 } else if (token.kind == SUPER) { 1843 } else if (token.kind == SUPER) {
1636 TypeBoundKind t = to(F.at(pos).TypeBoundKind(BoundKind.SUPER)); 1844 TypeBoundKind t = to(F.at(pos).TypeBoundKind(BoundKind.SUPER));
1637 nextToken(); 1845 nextToken();
1638 JCExpression bound = parseType(); 1846 JCExpression bound = parseType();
1639 return F.at(pos).Wildcard(t, bound); 1847 result = F.at(pos).Wildcard(t, bound);
1640 } else if (LAX_IDENTIFIER.accepts(token.kind)) { 1848 } else if (LAX_IDENTIFIER.accepts(token.kind)) {
1641 //error recovery 1849 //error recovery
1642 TypeBoundKind t = F.at(Position.NOPOS).TypeBoundKind(BoundKind.UNBOUND); 1850 TypeBoundKind t = F.at(Position.NOPOS).TypeBoundKind(BoundKind.UNBOUND);
1643 JCExpression wc = toP(F.at(pos).Wildcard(t, null)); 1851 JCExpression wc = toP(F.at(pos).Wildcard(t, null));
1644 JCIdent id = toP(F.at(token.pos).Ident(ident())); 1852 JCIdent id = toP(F.at(token.pos).Ident(ident()));
1645 JCErroneous err = F.at(pos).Erroneous(List.<JCTree>of(wc, id)); 1853 JCErroneous err = F.at(pos).Erroneous(List.<JCTree>of(wc, id));
1646 reportSyntaxError(err, "expected3", GT, EXTENDS, SUPER); 1854 reportSyntaxError(err, "expected3", GT, EXTENDS, SUPER);
1647 return err; 1855 result = err;
1648 } else { 1856 } else {
1649 TypeBoundKind t = toP(F.at(pos).TypeBoundKind(BoundKind.UNBOUND)); 1857 TypeBoundKind t = toP(F.at(pos).TypeBoundKind(BoundKind.UNBOUND));
1650 return toP(F.at(pos).Wildcard(t, null)); 1858 result = toP(F.at(pos).Wildcard(t, null));
1651 } 1859 }
1860 if (!annotations.isEmpty()) {
1861 result = toP(F.at(annotations.head.pos).AnnotatedType(annotations,result));
1862 }
1863 return result;
1652 } 1864 }
1653 1865
1654 JCTypeApply typeArguments(JCExpression t, boolean diamondAllowed) { 1866 JCTypeApply typeArguments(JCExpression t, boolean diamondAllowed) {
1655 int pos = token.pos; 1867 int pos = token.pos;
1656 List<JCExpression> args = typeArguments(diamondAllowed); 1868 List<JCExpression> args = typeArguments(diamondAllowed);
1657 return toP(F.at(pos).TypeApply(t, args)); 1869 return toP(F.at(pos).TypeApply(t, args));
1658 } 1870 }
1659 1871
1660 /** BracketsOpt = {"[" "]"} 1872 /**
1661 */ 1873 * BracketsOpt = { [Annotations] "[" "]" }*
1662 private JCExpression bracketsOpt(JCExpression t) { 1874 *
1875 * <p>
1876 *
1877 * <code>annotations</code> is the list of annotations targeting
1878 * the expression <code>t</code>.
1879 */
1880 private JCExpression bracketsOpt(JCExpression t,
1881 List<JCAnnotation> annotations) {
1882 List<JCAnnotation> nextLevelAnnotations = typeAnnotationsOpt();
1883
1663 if (token.kind == LBRACKET) { 1884 if (token.kind == LBRACKET) {
1664 int pos = token.pos; 1885 int pos = token.pos;
1665 nextToken(); 1886 nextToken();
1666 t = bracketsOptCont(t, pos); 1887 t = bracketsOptCont(t, pos, nextLevelAnnotations);
1667 F.at(pos); 1888 } else if (!nextLevelAnnotations.isEmpty()) {
1889 if (permitTypeAnnotationsPushBack) {
1890 this.typeAnnotationsPushedBack = nextLevelAnnotations;
1891 } else {
1892 return illegal(nextLevelAnnotations.head.pos);
1893 }
1894 }
1895
1896 if (!annotations.isEmpty()) {
1897 t = toP(F.at(token.pos).AnnotatedType(annotations, t));
1668 } 1898 }
1669 return t; 1899 return t;
1670 } 1900 }
1671 1901
1672 private JCArrayTypeTree bracketsOptCont(JCExpression t, int pos) { 1902 /** BracketsOpt = [ "[" "]" { [Annotations] "[" "]"} ]
1903 */
1904 private JCExpression bracketsOpt(JCExpression t) {
1905 return bracketsOpt(t, List.<JCAnnotation>nil());
1906 }
1907
1908 private JCExpression bracketsOptCont(JCExpression t, int pos,
1909 List<JCAnnotation> annotations) {
1673 accept(RBRACKET); 1910 accept(RBRACKET);
1674 t = bracketsOpt(t); 1911 t = bracketsOpt(t);
1675 return toP(F.at(pos).TypeArray(t)); 1912 t = toP(F.at(pos).TypeArray(t));
1913 if (annotations.nonEmpty()) {
1914 t = toP(F.at(pos).AnnotatedType(annotations, t));
1915 }
1916 return t;
1676 } 1917 }
1677 1918
1678 /** BracketsSuffixExpr = "." CLASS 1919 /** BracketsSuffixExpr = "." CLASS
1679 * BracketsSuffixType = 1920 * BracketsSuffixType =
1680 */ 1921 */
1684 int pos = token.pos; 1925 int pos = token.pos;
1685 nextToken(); 1926 nextToken();
1686 accept(CLASS); 1927 accept(CLASS);
1687 if (token.pos == endPosTable.errorEndPos) { 1928 if (token.pos == endPosTable.errorEndPos) {
1688 // error recovery 1929 // error recovery
1689 Name name = null; 1930 Name name;
1690 if (LAX_IDENTIFIER.accepts(token.kind)) { 1931 if (LAX_IDENTIFIER.accepts(token.kind)) {
1691 name = token.name(); 1932 name = token.name();
1692 nextToken(); 1933 nextToken();
1693 } else { 1934 } else {
1694 name = names.error; 1935 name = names.error;
1722 mode = EXPR; 1963 mode = EXPR;
1723 List<JCExpression> typeArgs = null; 1964 List<JCExpression> typeArgs = null;
1724 if (token.kind == LT) { 1965 if (token.kind == LT) {
1725 typeArgs = typeArguments(false); 1966 typeArgs = typeArguments(false);
1726 } 1967 }
1727 Name refName = null; 1968 Name refName;
1728 ReferenceMode refMode = null; 1969 ReferenceMode refMode;
1729 if (token.kind == NEW) { 1970 if (token.kind == NEW) {
1730 refMode = ReferenceMode.NEW; 1971 refMode = ReferenceMode.NEW;
1731 refName = names.init; 1972 refName = names.init;
1732 nextToken(); 1973 nextToken();
1733 } else { 1974 } else {
1735 refName = ident(); 1976 refName = ident();
1736 } 1977 }
1737 return toP(F.at(t.getStartPosition()).Reference(refMode, refName, t, typeArgs)); 1978 return toP(F.at(t.getStartPosition()).Reference(refMode, refName, t, typeArgs));
1738 } 1979 }
1739 1980
1740 /** Creator = Qualident [TypeArguments] ( ArrayCreatorRest | ClassCreatorRest ) 1981 /** Creator = [Annotations] Qualident [TypeArguments] ( ArrayCreatorRest | ClassCreatorRest )
1741 */ 1982 */
1742 JCExpression creator(int newpos, List<JCExpression> typeArgs) { 1983 JCExpression creator(int newpos, List<JCExpression> typeArgs) {
1984 List<JCAnnotation> newAnnotations = typeAnnotationsOpt();
1985
1743 switch (token.kind) { 1986 switch (token.kind) {
1744 case BYTE: case SHORT: case CHAR: case INT: case LONG: case FLOAT: 1987 case BYTE: case SHORT: case CHAR: case INT: case LONG: case FLOAT:
1745 case DOUBLE: case BOOLEAN: 1988 case DOUBLE: case BOOLEAN:
1746 if (typeArgs == null) 1989 if (typeArgs == null) {
1747 return arrayCreatorRest(newpos, basicType()); 1990 if (newAnnotations.isEmpty()) {
1991 return arrayCreatorRest(newpos, basicType());
1992 } else {
1993 return arrayCreatorRest(newpos, toP(F.at(newAnnotations.head.pos).AnnotatedType(newAnnotations, basicType())));
1994 }
1995 }
1748 break; 1996 break;
1749 default: 1997 default:
1750 } 1998 }
1751 JCExpression t = qualident(); 1999 JCExpression t = qualident(true);
2000
2001 // handle type annotations for non primitive arrays
2002 if (newAnnotations.nonEmpty()) {
2003 t = insertAnnotationsToMostInner(t, newAnnotations, false);
2004 }
2005
1752 int oldmode = mode; 2006 int oldmode = mode;
1753 mode = TYPE; 2007 mode = TYPE;
1754 boolean diamondFound = false; 2008 boolean diamondFound = false;
1755 int lastTypeargsPos = -1; 2009 int lastTypeargsPos = -1;
1756 if (token.kind == LT) { 2010 if (token.kind == LT) {
1764 //cannot select after a diamond 2018 //cannot select after a diamond
1765 illegal(); 2019 illegal();
1766 } 2020 }
1767 int pos = token.pos; 2021 int pos = token.pos;
1768 nextToken(); 2022 nextToken();
2023 List<JCAnnotation> tyannos = typeAnnotationsOpt();
1769 t = toP(F.at(pos).Select(t, ident())); 2024 t = toP(F.at(pos).Select(t, ident()));
2025
2026 if (tyannos != null && tyannos.nonEmpty()) {
2027 t = toP(F.at(tyannos.head.pos).AnnotatedType(tyannos, t));
2028 }
2029
1770 if (token.kind == LT) { 2030 if (token.kind == LT) {
1771 lastTypeargsPos = token.pos; 2031 lastTypeargsPos = token.pos;
1772 checkGenerics(); 2032 checkGenerics();
1773 t = typeArguments(t, true); 2033 t = typeArguments(t, true);
1774 diamondFound = (mode & DIAMOND) != 0; 2034 diamondFound = (mode & DIAMOND) != 0;
1775 } 2035 }
1776 } 2036 }
1777 mode = oldmode; 2037 mode = oldmode;
1778 if (token.kind == LBRACKET) { 2038 if (token.kind == LBRACKET || token.kind == MONKEYS_AT) {
1779 JCExpression e = arrayCreatorRest(newpos, t); 2039 JCExpression e = arrayCreatorRest(newpos, t);
1780 if (diamondFound) { 2040 if (diamondFound) {
1781 reportSyntaxError(lastTypeargsPos, "cannot.create.array.with.diamond"); 2041 reportSyntaxError(lastTypeargsPos, "cannot.create.array.with.diamond");
1782 return toP(F.at(newpos).Erroneous(List.of(e))); 2042 return toP(F.at(newpos).Erroneous(List.of(e)));
1783 } 2043 }
1794 reportSyntaxError(err, "cannot.create.array.with.type.arguments"); 2054 reportSyntaxError(err, "cannot.create.array.with.type.arguments");
1795 return toP(err); 2055 return toP(err);
1796 } 2056 }
1797 return e; 2057 return e;
1798 } else if (token.kind == LPAREN) { 2058 } else if (token.kind == LPAREN) {
1799 return classCreatorRest(newpos, null, typeArgs, t); 2059 JCNewClass newClass = classCreatorRest(newpos, null, typeArgs, t);
2060 if (newClass.def != null) {
2061 assert newClass.def.mods.annotations.isEmpty();
2062 if (newAnnotations.nonEmpty()) {
2063 newClass.def.mods.pos = earlier(newClass.def.mods.pos, newAnnotations.head.pos);
2064 newClass.def.mods.annotations = List.convert(JCAnnotation.class, newAnnotations);
2065 }
2066 }
2067 return newClass;
1800 } else { 2068 } else {
1801 setErrorEndPos(token.pos); 2069 setErrorEndPos(token.pos);
1802 reportSyntaxError(token.pos, "expected2", LPAREN, LBRACKET); 2070 reportSyntaxError(token.pos, "expected2", LPAREN, LBRACKET);
1803 t = toP(F.at(newpos).NewClass(null, typeArgs, t, List.<JCExpression>nil(), null)); 2071 t = toP(F.at(newpos).NewClass(null, typeArgs, t, List.<JCExpression>nil(), null));
1804 return toP(F.at(newpos).Erroneous(List.<JCTree>of(t))); 2072 return toP(F.at(newpos).Erroneous(List.<JCTree>of(t)));
1805 } 2073 }
1806 } 2074 }
1807 2075
1808 /** InnerCreator = Ident [TypeArguments] ClassCreatorRest 2076 /** InnerCreator = [Annotations] Ident [TypeArguments] ClassCreatorRest
1809 */ 2077 */
1810 JCExpression innerCreator(int newpos, List<JCExpression> typeArgs, JCExpression encl) { 2078 JCExpression innerCreator(int newpos, List<JCExpression> typeArgs, JCExpression encl) {
2079 List<JCAnnotation> newAnnotations = typeAnnotationsOpt();
2080
1811 JCExpression t = toP(F.at(token.pos).Ident(ident())); 2081 JCExpression t = toP(F.at(token.pos).Ident(ident()));
2082
2083 if (newAnnotations.nonEmpty()) {
2084 t = toP(F.at(newAnnotations.head.pos).AnnotatedType(newAnnotations, t));
2085 }
2086
1812 if (token.kind == LT) { 2087 if (token.kind == LT) {
1813 int oldmode = mode; 2088 int oldmode = mode;
1814 checkGenerics(); 2089 checkGenerics();
1815 t = typeArguments(t, true); 2090 t = typeArguments(t, true);
1816 mode = oldmode; 2091 mode = oldmode;
1817 } 2092 }
1818 return classCreatorRest(newpos, encl, typeArgs, t); 2093 return classCreatorRest(newpos, encl, typeArgs, t);
1819 } 2094 }
1820 2095
1821 /** ArrayCreatorRest = "[" ( "]" BracketsOpt ArrayInitializer 2096 /** ArrayCreatorRest = [Annotations] "[" ( "]" BracketsOpt ArrayInitializer
1822 * | Expression "]" {"[" Expression "]"} BracketsOpt ) 2097 * | Expression "]" {[Annotations] "[" Expression "]"} BracketsOpt )
1823 */ 2098 */
1824 JCExpression arrayCreatorRest(int newpos, JCExpression elemtype) { 2099 JCExpression arrayCreatorRest(int newpos, JCExpression elemtype) {
2100 List<JCAnnotation> annos = typeAnnotationsOpt();
2101
1825 accept(LBRACKET); 2102 accept(LBRACKET);
1826 if (token.kind == RBRACKET) { 2103 if (token.kind == RBRACKET) {
1827 accept(RBRACKET); 2104 accept(RBRACKET);
1828 elemtype = bracketsOpt(elemtype); 2105 elemtype = bracketsOpt(elemtype, annos);
1829 if (token.kind == LBRACE) { 2106 if (token.kind == LBRACE) {
1830 return arrayInitializer(newpos, elemtype); 2107 JCNewArray na = (JCNewArray)arrayInitializer(newpos, elemtype);
2108 if (annos.nonEmpty()) {
2109 // when an array initializer is present then
2110 // the parsed annotations should target the
2111 // new array tree
2112 // bracketsOpt inserts the annotation in
2113 // elemtype, and it needs to be corrected
2114 //
2115 JCAnnotatedType annotated = (JCAnnotatedType)elemtype;
2116 assert annotated.annotations == annos;
2117 na.annotations = annotated.annotations;
2118 na.elemtype = annotated.underlyingType;
2119 }
2120 return na;
1831 } else { 2121 } else {
1832 JCExpression t = toP(F.at(newpos).NewArray(elemtype, List.<JCExpression>nil(), null)); 2122 JCExpression t = toP(F.at(newpos).NewArray(elemtype, List.<JCExpression>nil(), null));
1833 return syntaxError(token.pos, List.<JCTree>of(t), "array.dimension.missing"); 2123 return syntaxError(token.pos, List.<JCTree>of(t), "array.dimension.missing");
1834 } 2124 }
1835 } else { 2125 } else {
1836 ListBuffer<JCExpression> dims = new ListBuffer<JCExpression>(); 2126 ListBuffer<JCExpression> dims = new ListBuffer<JCExpression>();
2127
2128 // maintain array dimension type annotations
2129 ListBuffer<List<JCAnnotation>> dimAnnotations = ListBuffer.lb();
2130 dimAnnotations.append(annos);
2131
1837 dims.append(parseExpression()); 2132 dims.append(parseExpression());
1838 accept(RBRACKET); 2133 accept(RBRACKET);
1839 while (token.kind == LBRACKET) { 2134 while (token.kind == LBRACKET
2135 || token.kind == MONKEYS_AT) {
2136 List<JCAnnotation> maybeDimAnnos = typeAnnotationsOpt();
1840 int pos = token.pos; 2137 int pos = token.pos;
1841 nextToken(); 2138 nextToken();
1842 if (token.kind == RBRACKET) { 2139 if (token.kind == RBRACKET) {
1843 elemtype = bracketsOptCont(elemtype, pos); 2140 elemtype = bracketsOptCont(elemtype, pos, maybeDimAnnos);
1844 } else { 2141 } else {
1845 dims.append(parseExpression()); 2142 if (token.kind == RBRACKET) { // no dimension
1846 accept(RBRACKET); 2143 elemtype = bracketsOptCont(elemtype, pos, maybeDimAnnos);
2144 } else {
2145 dimAnnotations.append(maybeDimAnnos);
2146 dims.append(parseExpression());
2147 accept(RBRACKET);
2148 }
1847 } 2149 }
1848 } 2150 }
1849 return toP(F.at(newpos).NewArray(elemtype, dims.toList(), null)); 2151
2152 JCNewArray na = toP(F.at(newpos).NewArray(elemtype, dims.toList(), null));
2153 na.dimAnnotations = dimAnnotations.toList();
2154 return na;
1850 } 2155 }
1851 } 2156 }
1852 2157
1853 /** ClassCreatorRest = Arguments [ClassBody] 2158 /** ClassCreatorRest = Arguments [ClassBody]
1854 */ 2159 */
2252 S.errPos(errPos); 2557 S.errPos(errPos);
2253 return toP(F.Exec(syntaxError(startPos, List.<JCTree>of(stm), key))); 2558 return toP(F.Exec(syntaxError(startPos, List.<JCTree>of(stm), key)));
2254 } 2559 }
2255 2560
2256 /** CatchClause = CATCH "(" FormalParameter ")" Block 2561 /** CatchClause = CATCH "(" FormalParameter ")" Block
2562 * TODO: the "FormalParameter" is not correct, it uses the special "catchTypes" rule below.
2257 */ 2563 */
2258 protected JCCatch catchClause() { 2564 protected JCCatch catchClause() {
2259 int pos = token.pos; 2565 int pos = token.pos;
2260 accept(CATCH); 2566 accept(CATCH);
2261 accept(LPAREN); 2567 accept(LPAREN);
2274 ListBuffer<JCExpression> catchTypes = ListBuffer.lb(); 2580 ListBuffer<JCExpression> catchTypes = ListBuffer.lb();
2275 catchTypes.add(parseType()); 2581 catchTypes.add(parseType());
2276 while (token.kind == BAR) { 2582 while (token.kind == BAR) {
2277 checkMulticatch(); 2583 checkMulticatch();
2278 nextToken(); 2584 nextToken();
2279 catchTypes.add(qualident()); 2585 // Instead of qualident this is now parseType.
2586 // But would that allow too much, e.g. arrays or generics?
2587 catchTypes.add(parseType());
2280 } 2588 }
2281 return catchTypes.toList(); 2589 return catchTypes.toList();
2282 } 2590 }
2283 2591
2284 /** SwitchBlockStatementGroups = { SwitchBlockStatementGroup } 2592 /** SwitchBlockStatementGroups = { SwitchBlockStatementGroup }
2375 parseExpression(), 2683 parseExpression(),
2376 new ListBuffer<JCExpressionStatement>()).toList(); 2684 new ListBuffer<JCExpressionStatement>()).toList();
2377 } 2685 }
2378 2686
2379 /** AnnotationsOpt = { '@' Annotation } 2687 /** AnnotationsOpt = { '@' Annotation }
2380 */ 2688 *
2381 List<JCAnnotation> annotationsOpt() { 2689 * @param kind Whether to parse an ANNOTATION or TYPE_ANNOTATION
2690 */
2691 List<JCAnnotation> annotationsOpt(Tag kind) {
2382 if (token.kind != MONKEYS_AT) return List.nil(); // optimization 2692 if (token.kind != MONKEYS_AT) return List.nil(); // optimization
2383 ListBuffer<JCAnnotation> buf = new ListBuffer<JCAnnotation>(); 2693 ListBuffer<JCAnnotation> buf = new ListBuffer<JCAnnotation>();
2694 int prevmode = mode;
2384 while (token.kind == MONKEYS_AT) { 2695 while (token.kind == MONKEYS_AT) {
2385 int pos = token.pos; 2696 int pos = token.pos;
2386 nextToken(); 2697 nextToken();
2387 buf.append(annotation(pos)); 2698 buf.append(annotation(pos, kind));
2388 } 2699 }
2389 return buf.toList(); 2700 lastmode = mode;
2701 mode = prevmode;
2702 List<JCAnnotation> annotations = buf.toList();
2703
2704 return annotations;
2705 }
2706
2707 List<JCAnnotation> typeAnnotationsOpt() {
2708 List<JCAnnotation> annotations = annotationsOpt(Tag.TYPE_ANNOTATION);
2709 return annotations;
2390 } 2710 }
2391 2711
2392 /** ModifiersOpt = { Modifier } 2712 /** ModifiersOpt = { Modifier }
2393 * Modifier = PUBLIC | PROTECTED | PRIVATE | STATIC | ABSTRACT | FINAL 2713 * Modifier = PUBLIC | PROTECTED | PRIVATE | STATIC | ABSTRACT | FINAL
2394 * | NATIVE | SYNCHRONIZED | TRANSIENT | VOLATILE | "@" 2714 * | NATIVE | SYNCHRONIZED | TRANSIENT | VOLATILE | "@"
2410 pos = partial.pos; 2730 pos = partial.pos;
2411 } 2731 }
2412 if (token.deprecatedFlag()) { 2732 if (token.deprecatedFlag()) {
2413 flags |= Flags.DEPRECATED; 2733 flags |= Flags.DEPRECATED;
2414 } 2734 }
2415 int lastPos = Position.NOPOS; 2735 int lastPos;
2416 loop: 2736 loop:
2417 while (true) { 2737 while (true) {
2418 long flag; 2738 long flag;
2419 switch (token.kind) { 2739 switch (token.kind) {
2420 case PRIVATE : flag = Flags.PRIVATE; break; 2740 case PRIVATE : flag = Flags.PRIVATE; break;
2437 lastPos = token.pos; 2757 lastPos = token.pos;
2438 nextToken(); 2758 nextToken();
2439 if (flag == Flags.ANNOTATION) { 2759 if (flag == Flags.ANNOTATION) {
2440 checkAnnotations(); 2760 checkAnnotations();
2441 if (token.kind != INTERFACE) { 2761 if (token.kind != INTERFACE) {
2442 JCAnnotation ann = annotation(lastPos); 2762 JCAnnotation ann = annotation(lastPos, Tag.ANNOTATION);
2443 // if first modifier is an annotation, set pos to annotation's. 2763 // if first modifier is an annotation, set pos to annotation's.
2444 if (flags == 0 && annotations.isEmpty()) 2764 if (flags == 0 && annotations.isEmpty())
2445 pos = ann.pos; 2765 pos = ann.pos;
2446 annotations.append(ann); 2766 annotations.append(ann);
2447 lastPos = ann.pos;
2448 flag = 0; 2767 flag = 0;
2449 } 2768 }
2450 } 2769 }
2451 flags |= flag; 2770 flags |= flag;
2452 } 2771 }
2466 storeEnd(mods, S.prevToken().endPos); 2785 storeEnd(mods, S.prevToken().endPos);
2467 return mods; 2786 return mods;
2468 } 2787 }
2469 2788
2470 /** Annotation = "@" Qualident [ "(" AnnotationFieldValues ")" ] 2789 /** Annotation = "@" Qualident [ "(" AnnotationFieldValues ")" ]
2790 *
2471 * @param pos position of "@" token 2791 * @param pos position of "@" token
2472 */ 2792 * @param kind Whether to parse an ANNOTATION or TYPE_ANNOTATION
2473 JCAnnotation annotation(int pos) { 2793 */
2794 JCAnnotation annotation(int pos, Tag kind) {
2474 // accept(AT); // AT consumed by caller 2795 // accept(AT); // AT consumed by caller
2475 checkAnnotations(); 2796 checkAnnotations();
2476 JCTree ident = qualident(); 2797 if (kind == Tag.TYPE_ANNOTATION) {
2798 checkTypeAnnotations();
2799 }
2800 JCTree ident = qualident(false);
2477 List<JCExpression> fieldValues = annotationFieldValuesOpt(); 2801 List<JCExpression> fieldValues = annotationFieldValuesOpt();
2478 JCAnnotation ann = F.at(pos).Annotation(ident, fieldValues); 2802 JCAnnotation ann;
2803 if (kind == Tag.ANNOTATION) {
2804 ann = F.at(pos).Annotation(ident, fieldValues);
2805 } else if (kind == Tag.TYPE_ANNOTATION) {
2806 ann = F.at(pos).TypeAnnotation(ident, fieldValues);
2807 } else {
2808 throw new AssertionError("Unhandled annotation kind: " + kind);
2809 }
2810
2479 storeEnd(ann, S.prevToken().endPos); 2811 storeEnd(ann, S.prevToken().endPos);
2480 return ann; 2812 return ann;
2481 } 2813 }
2482 2814
2483 List<JCExpression> annotationFieldValuesOpt() { 2815 List<JCExpression> annotationFieldValuesOpt() {
2526 int pos; 2858 int pos;
2527 switch (token.kind) { 2859 switch (token.kind) {
2528 case MONKEYS_AT: 2860 case MONKEYS_AT:
2529 pos = token.pos; 2861 pos = token.pos;
2530 nextToken(); 2862 nextToken();
2531 return annotation(pos); 2863 return annotation(pos, Tag.ANNOTATION);
2532 case LBRACE: 2864 case LBRACE:
2533 pos = token.pos; 2865 pos = token.pos;
2534 accept(LBRACE); 2866 accept(LBRACE);
2535 ListBuffer<JCExpression> buf = new ListBuffer<JCExpression>(); 2867 ListBuffer<JCExpression> buf = new ListBuffer<JCExpression>();
2536 if (token.kind != RBRACE) { 2868 if (token.kind != RBRACE) {
2681 checkNoMods(mods.flags); 3013 checkNoMods(mods.flags);
2682 packageAnnotations = mods.annotations; 3014 packageAnnotations = mods.annotations;
2683 mods = null; 3015 mods = null;
2684 } 3016 }
2685 nextToken(); 3017 nextToken();
2686 pid = qualident(); 3018 pid = qualident(false);
2687 accept(SEMI); 3019 accept(SEMI);
2688 } 3020 }
2689 ListBuffer<JCTree> defs = new ListBuffer<JCTree>(); 3021 ListBuffer<JCTree> defs = new ListBuffer<JCTree>();
2690 boolean checkForImports = true; 3022 boolean checkForImports = true;
2691 boolean firstTypeDecl = true; 3023 boolean firstTypeDecl = true;
2932 int flags = Flags.PUBLIC|Flags.STATIC|Flags.FINAL|Flags.ENUM; 3264 int flags = Flags.PUBLIC|Flags.STATIC|Flags.FINAL|Flags.ENUM;
2933 if (token.deprecatedFlag()) { 3265 if (token.deprecatedFlag()) {
2934 flags |= Flags.DEPRECATED; 3266 flags |= Flags.DEPRECATED;
2935 } 3267 }
2936 int pos = token.pos; 3268 int pos = token.pos;
2937 List<JCAnnotation> annotations = annotationsOpt(); 3269 List<JCAnnotation> annotations = annotationsOpt(Tag.ANNOTATION);
2938 JCModifiers mods = F.at(annotations.isEmpty() ? Position.NOPOS : pos).Modifiers(flags, annotations); 3270 JCModifiers mods = F.at(annotations.isEmpty() ? Position.NOPOS : pos).Modifiers(flags, annotations);
2939 List<JCExpression> typeArgs = typeArgumentsOpt(); 3271 List<JCExpression> typeArgs = typeArgumentsOpt();
2940 int identPos = token.pos; 3272 int identPos = token.pos;
2941 Name name = ident(); 3273 Name name = ident();
2942 int createPos = token.pos; 3274 int createPos = token.pos;
3035 // position of the method in the modifiers. 3367 // position of the method in the modifiers.
3036 if (typarams.nonEmpty() && mods.pos == Position.NOPOS) { 3368 if (typarams.nonEmpty() && mods.pos == Position.NOPOS) {
3037 mods.pos = pos; 3369 mods.pos = pos;
3038 storeEnd(mods, pos); 3370 storeEnd(mods, pos);
3039 } 3371 }
3372 List<JCAnnotation> annosAfterParams = annotationsOpt(Tag.ANNOTATION);
3373
3040 Token tk = token; 3374 Token tk = token;
3041 pos = token.pos; 3375 pos = token.pos;
3042 JCExpression type; 3376 JCExpression type;
3043 boolean isVoid = token.kind == VOID; 3377 boolean isVoid = token.kind == VOID;
3044 if (isVoid) { 3378 if (isVoid) {
3379 if (annosAfterParams.nonEmpty())
3380 illegal(annosAfterParams.head.pos);
3045 type = to(F.at(pos).TypeIdent(TypeTag.VOID)); 3381 type = to(F.at(pos).TypeIdent(TypeTag.VOID));
3046 nextToken(); 3382 nextToken();
3047 } else { 3383 } else {
3048 type = parseType(); 3384 if (annosAfterParams.nonEmpty()) {
3385 mods.annotations = mods.annotations.appendList(annosAfterParams);
3386 if (mods.pos == Position.NOPOS)
3387 mods.pos = mods.annotations.head.pos;
3388 }
3389 // method returns types are un-annotated types
3390 type = unannotatedType();
3049 } 3391 }
3050 if (token.kind == LPAREN && !isInterface && type.hasTag(IDENT)) { 3392 if (token.kind == LPAREN && !isInterface && type.hasTag(IDENT)) {
3051 if (isInterface || tk.name() != className) 3393 if (isInterface || tk.name() != className)
3052 error(pos, "invalid.meth.decl.ret.type.req"); 3394 error(pos, "invalid.meth.decl.ret.type.req");
3053 return List.of(methodDeclaratorRest( 3395 return List.of(methodDeclaratorRest(
3099 boolean isInterface, boolean isVoid, 3441 boolean isInterface, boolean isVoid,
3100 Comment dc) { 3442 Comment dc) {
3101 if (isInterface && (mods.flags & Flags.STATIC) != 0) { 3443 if (isInterface && (mods.flags & Flags.STATIC) != 0) {
3102 checkStaticInterfaceMethods(); 3444 checkStaticInterfaceMethods();
3103 } 3445 }
3104 List<JCVariableDecl> params = formalParameters(); 3446 JCVariableDecl prevReceiverParam = this.receiverParam;
3105 if (!isVoid) type = bracketsOpt(type); 3447 try {
3106 List<JCExpression> thrown = List.nil(); 3448 this.receiverParam = null;
3107 if (token.kind == THROWS) { 3449 // Parsing formalParameters sets the receiverParam, if present
3108 nextToken(); 3450 List<JCVariableDecl> params = formalParameters();
3109 thrown = qualidentList(); 3451 if (!isVoid) type = bracketsOpt(type);
3110 } 3452 List<JCExpression> thrown = List.nil();
3111 JCBlock body = null; 3453 if (token.kind == THROWS) {
3112 JCExpression defaultValue; 3454 nextToken();
3113 if (token.kind == LBRACE) { 3455 thrown = qualidentList();
3114 body = block(); 3456 }
3115 defaultValue = null; 3457 JCBlock body = null;
3116 } else { 3458 JCExpression defaultValue;
3117 if (token.kind == DEFAULT) { 3459 if (token.kind == LBRACE) {
3118 accept(DEFAULT); 3460 body = block();
3119 defaultValue = annotationValue(); 3461 defaultValue = null;
3120 } else { 3462 } else {
3121 defaultValue = null; 3463 if (token.kind == DEFAULT) {
3122 } 3464 accept(DEFAULT);
3123 accept(SEMI); 3465 defaultValue = annotationValue();
3124 if (token.pos <= endPosTable.errorEndPos) { 3466 } else {
3125 // error recovery 3467 defaultValue = null;
3126 skip(false, true, false, false);
3127 if (token.kind == LBRACE) {
3128 body = block();
3129 } 3468 }
3130 } 3469 accept(SEMI);
3131 } 3470 if (token.pos <= endPosTable.errorEndPos) {
3132 3471 // error recovery
3133 JCMethodDecl result = 3472 skip(false, true, false, false);
3134 toP(F.at(pos).MethodDef(mods, name, type, typarams, 3473 if (token.kind == LBRACE) {
3135 params, thrown, 3474 body = block();
3136 body, defaultValue)); 3475 }
3137 attach(result, dc); 3476 }
3138 return result; 3477 }
3139 } 3478
3140 3479 JCMethodDecl result =
3141 /** QualidentList = Qualident {"," Qualident} 3480 toP(F.at(pos).MethodDef(mods, name, type, typarams,
3481 receiverParam, params, thrown,
3482 body, defaultValue));
3483 attach(result, dc);
3484 return result;
3485 } finally {
3486 this.receiverParam = prevReceiverParam;
3487 }
3488 }
3489
3490 /** QualidentList = [Annotations] Qualident {"," [Annotations] Qualident}
3142 */ 3491 */
3143 List<JCExpression> qualidentList() { 3492 List<JCExpression> qualidentList() {
3144 ListBuffer<JCExpression> ts = new ListBuffer<JCExpression>(); 3493 ListBuffer<JCExpression> ts = new ListBuffer<JCExpression>();
3145 ts.append(qualident()); 3494
3495 List<JCAnnotation> typeAnnos = typeAnnotationsOpt();
3496 if (!typeAnnos.isEmpty())
3497 ts.append(toP(F.at(typeAnnos.head.pos).AnnotatedType(typeAnnos, qualident(true))));
3498 else
3499 ts.append(qualident(true));
3146 while (token.kind == COMMA) { 3500 while (token.kind == COMMA) {
3147 nextToken(); 3501 nextToken();
3148 ts.append(qualident()); 3502
3503 typeAnnos = typeAnnotationsOpt();
3504 if (!typeAnnos.isEmpty())
3505 ts.append(toP(F.at(typeAnnos.head.pos).AnnotatedType(typeAnnos, qualident(true))));
3506 else
3507 ts.append(qualident(true));
3149 } 3508 }
3150 return ts.toList(); 3509 return ts.toList();
3151 } 3510 }
3152 3511
3153 /** 3512 /**
3172 } 3531 }
3173 } 3532 }
3174 3533
3175 /** 3534 /**
3176 * {@literal 3535 * {@literal
3177 * TypeParameter = TypeVariable [TypeParameterBound] 3536 * TypeParameter = [Annotations] TypeVariable [TypeParameterBound]
3178 * TypeParameterBound = EXTENDS Type {"&" Type} 3537 * TypeParameterBound = EXTENDS Type {"&" Type}
3179 * TypeVariable = Ident 3538 * TypeVariable = Ident
3180 * } 3539 * }
3181 */ 3540 */
3182 JCTypeParameter typeParameter() { 3541 JCTypeParameter typeParameter() {
3183 int pos = token.pos; 3542 int pos = token.pos;
3543 List<JCAnnotation> annos = typeAnnotationsOpt();
3184 Name name = ident(); 3544 Name name = ident();
3185 ListBuffer<JCExpression> bounds = new ListBuffer<JCExpression>(); 3545 ListBuffer<JCExpression> bounds = new ListBuffer<JCExpression>();
3186 if (token.kind == EXTENDS) { 3546 if (token.kind == EXTENDS) {
3187 nextToken(); 3547 nextToken();
3188 bounds.append(parseType()); 3548 bounds.append(parseType());
3189 while (token.kind == AMP) { 3549 while (token.kind == AMP) {
3190 nextToken(); 3550 nextToken();
3191 bounds.append(parseType()); 3551 bounds.append(parseType());
3192 } 3552 }
3193 } 3553 }
3194 return toP(F.at(pos).TypeParameter(name, bounds.toList())); 3554 return toP(F.at(pos).TypeParameter(name, bounds.toList(), annos));
3195 } 3555 }
3196 3556
3197 /** FormalParameters = "(" [ FormalParameterList ] ")" 3557 /** FormalParameters = "(" [ FormalParameterList ] ")"
3198 * FormalParameterList = [ FormalParameterListNovarargs , ] LastFormalParameter 3558 * FormalParameterList = [ FormalParameterListNovarargs , ] LastFormalParameter
3199 * FormalParameterListNovarargs = [ FormalParameterListNovarargs , ] FormalParameter 3559 * FormalParameterListNovarargs = [ FormalParameterListNovarargs , ] FormalParameter
3201 List<JCVariableDecl> formalParameters() { 3561 List<JCVariableDecl> formalParameters() {
3202 return formalParameters(false); 3562 return formalParameters(false);
3203 } 3563 }
3204 List<JCVariableDecl> formalParameters(boolean lambdaParameters) { 3564 List<JCVariableDecl> formalParameters(boolean lambdaParameters) {
3205 ListBuffer<JCVariableDecl> params = new ListBuffer<JCVariableDecl>(); 3565 ListBuffer<JCVariableDecl> params = new ListBuffer<JCVariableDecl>();
3206 JCVariableDecl lastParam = null; 3566 JCVariableDecl lastParam;
3207 accept(LPAREN); 3567 accept(LPAREN);
3208 if (token.kind != RPAREN) { 3568 if (token.kind != RPAREN) {
3209 params.append(lastParam = formalParameter(lambdaParameters)); 3569 this.allowThisIdent = true;
3570 lastParam = formalParameter(lambdaParameters);
3571 if (lastParam.name.contentEquals(TokenKind.THIS.name)) {
3572 this.receiverParam = lastParam;
3573 } else {
3574 params.append(lastParam);
3575 }
3576 this.allowThisIdent = false;
3210 while ((lastParam.mods.flags & Flags.VARARGS) == 0 && token.kind == COMMA) { 3577 while ((lastParam.mods.flags & Flags.VARARGS) == 0 && token.kind == COMMA) {
3211 nextToken(); 3578 nextToken();
3212 params.append(lastParam = formalParameter(lambdaParameters)); 3579 params.append(lastParam = formalParameter(lambdaParameters));
3213 } 3580 }
3214 } 3581 }
3239 checkNoMods(mods.flags & ~(Flags.FINAL | Flags.DEPRECATED)); 3606 checkNoMods(mods.flags & ~(Flags.FINAL | Flags.DEPRECATED));
3240 mods.flags |= flags; 3607 mods.flags |= flags;
3241 return mods; 3608 return mods;
3242 } 3609 }
3243 3610
3611 /**
3612 * Inserts the annotations (and possibly a new array level)
3613 * to the left-most type in an array or nested type.
3614 *
3615 * When parsing a type like {@code @B Outer.Inner @A []}, the
3616 * {@code @A} annotation should target the array itself, while
3617 * {@code @B} targets the nested type {@code Outer}.
3618 *
3619 * Currently the parser parses the annotation first, then
3620 * the array, and then inserts the annotation to the left-most
3621 * nested type.
3622 *
3623 * When {@code createNewLevel} is true, then a new array
3624 * level is inserted as the most inner type, and have the
3625 * annotations target it. This is useful in the case of
3626 * varargs, e.g. {@code String @A [] @B ...}, as the parser
3627 * first parses the type {@code String @A []} then inserts
3628 * a new array level with {@code @B} annotation.
3629 */
3630 private JCExpression insertAnnotationsToMostInner(
3631 JCExpression type, List<JCAnnotation> annos,
3632 boolean createNewLevel) {
3633 int origEndPos = getEndPos(type);
3634 JCExpression mostInnerType = type;
3635 JCArrayTypeTree mostInnerArrayType = null;
3636 while (TreeInfo.typeIn(mostInnerType).hasTag(TYPEARRAY)) {
3637 mostInnerArrayType = (JCArrayTypeTree) TreeInfo.typeIn(mostInnerType);
3638 mostInnerType = mostInnerArrayType.elemtype;
3639 }
3640
3641 if (createNewLevel) {
3642 mostInnerType = to(F.at(token.pos).TypeArray(mostInnerType));
3643 }
3644
3645 JCExpression mostInnerTypeToReturn = mostInnerType;
3646 if (annos.nonEmpty()) {
3647 JCExpression lastToModify = mostInnerType;
3648
3649 while (TreeInfo.typeIn(mostInnerType).hasTag(SELECT) ||
3650 TreeInfo.typeIn(mostInnerType).hasTag(TYPEAPPLY)) {
3651 while (TreeInfo.typeIn(mostInnerType).hasTag(SELECT)) {
3652 lastToModify = mostInnerType;
3653 mostInnerType = ((JCFieldAccess) TreeInfo.typeIn(mostInnerType)).getExpression();
3654 }
3655 while (TreeInfo.typeIn(mostInnerType).hasTag(TYPEAPPLY)) {
3656 lastToModify = mostInnerType;
3657 mostInnerType = ((JCTypeApply) TreeInfo.typeIn(mostInnerType)).clazz;
3658 }
3659 }
3660
3661 mostInnerType = F.at(annos.head.pos).AnnotatedType(annos, mostInnerType);
3662
3663 if (TreeInfo.typeIn(lastToModify).hasTag(TYPEAPPLY)) {
3664 ((JCTypeApply) TreeInfo.typeIn(lastToModify)).clazz = mostInnerType;
3665 } else if (TreeInfo.typeIn(lastToModify).hasTag(SELECT)) {
3666 ((JCFieldAccess) TreeInfo.typeIn(lastToModify)).selected = mostInnerType;
3667 } else {
3668 // We never saw a SELECT or TYPEAPPLY, return the annotated type.
3669 mostInnerTypeToReturn = mostInnerType;
3670 }
3671 }
3672
3673 if (mostInnerArrayType == null) {
3674 return mostInnerTypeToReturn;
3675 } else {
3676 mostInnerArrayType.elemtype = mostInnerTypeToReturn;
3677 storeEnd(type, origEndPos);
3678 return type;
3679 }
3680 }
3681
3244 /** FormalParameter = { FINAL | '@' Annotation } Type VariableDeclaratorId 3682 /** FormalParameter = { FINAL | '@' Annotation } Type VariableDeclaratorId
3245 * LastFormalParameter = { FINAL | '@' Annotation } Type '...' Ident | FormalParameter 3683 * LastFormalParameter = { FINAL | '@' Annotation } Type '...' Ident | FormalParameter
3246 */ 3684 */
3247 protected JCVariableDecl formalParameter() { 3685 protected JCVariableDecl formalParameter() {
3248 return formalParameter(false); 3686 return formalParameter(false);
3249 } 3687 }
3250 protected JCVariableDecl formalParameter(boolean lambdaParameter) { 3688 protected JCVariableDecl formalParameter(boolean lambdaParameter) {
3251 JCModifiers mods = optFinal(Flags.PARAMETER); 3689 JCModifiers mods = optFinal(Flags.PARAMETER);
3690 // need to distinguish between vararg annos and array annos
3691 // look at typeAnnotationsPushedBack comment
3692 this.permitTypeAnnotationsPushBack = true;
3252 JCExpression type = parseType(); 3693 JCExpression type = parseType();
3694 this.permitTypeAnnotationsPushBack = false;
3695
3253 if (token.kind == ELLIPSIS) { 3696 if (token.kind == ELLIPSIS) {
3697 List<JCAnnotation> varargsAnnos = typeAnnotationsPushedBack;
3698 typeAnnotationsPushedBack = List.nil();
3254 checkVarargs(); 3699 checkVarargs();
3255 mods.flags |= Flags.VARARGS; 3700 mods.flags |= Flags.VARARGS;
3256 type = to(F.at(token.pos).TypeArray(type)); 3701 // insert var arg type annotations
3257 nextToken(); 3702 type = insertAnnotationsToMostInner(type, varargsAnnos, true);
3703 nextToken();
3704 } else {
3705 // if not a var arg, then typeAnnotationsPushedBack should be null
3706 if (typeAnnotationsPushedBack.nonEmpty()) {
3707 reportSyntaxError(typeAnnotationsPushedBack.head.pos,
3708 "illegal.start.of.type");
3709 }
3710 typeAnnotationsPushedBack = List.nil();
3258 } 3711 }
3259 return variableDeclaratorId(mods, type, lambdaParameter); 3712 return variableDeclaratorId(mods, type, lambdaParameter);
3260 } 3713 }
3261 3714
3262 protected JCVariableDecl implicitParameter() { 3715 protected JCVariableDecl implicitParameter() {
3506 if (!allowStaticInterfaceMethods) { 3959 if (!allowStaticInterfaceMethods) {
3507 log.error(token.pos, "static.intf.methods.not.supported.in.source", source.name); 3960 log.error(token.pos, "static.intf.methods.not.supported.in.source", source.name);
3508 allowStaticInterfaceMethods = true; 3961 allowStaticInterfaceMethods = true;
3509 } 3962 }
3510 } 3963 }
3964 void checkTypeAnnotations() {
3965 if (!allowTypeAnnotations) {
3966 log.error(token.pos, "type.annotations.not.supported.in.source", source.name);
3967 allowTypeAnnotations = true;
3968 }
3969 }
3511 3970
3512 /* 3971 /*
3513 * a functional source tree and end position mappings 3972 * a functional source tree and end position mappings
3514 */ 3973 */
3515 protected class SimpleEndPosTable extends AbstractEndPosTable { 3974 protected class SimpleEndPosTable extends AbstractEndPosTable {

mercurial