< prev index next >

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

Print this page

  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.parser;
  27 
  28 import java.util.*;
  29 import java.util.function.Function;
  30 import java.util.function.Predicate;
  31 import java.util.stream.Collectors;
  32 
  33 import javax.lang.model.SourceVersion;
  34 
  35 import com.sun.source.tree.CaseTree;
  36 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
  37 import com.sun.source.tree.ModuleTree.ModuleKind;
  38 
  39 import com.sun.tools.javac.code.*;

  40 import com.sun.tools.javac.code.Source.Feature;
  41 import com.sun.tools.javac.file.PathFileObject;
  42 import com.sun.tools.javac.parser.Tokens.*;

  43 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  44 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  45 import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
  46 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  47 import com.sun.tools.javac.tree.*;
  48 import com.sun.tools.javac.tree.JCTree.*;
  49 import com.sun.tools.javac.util.*;
  50 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
  51 import com.sun.tools.javac.util.JCDiagnostic.Error;
  52 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
  53 import com.sun.tools.javac.util.List;
  54 

  55 import static com.sun.tools.javac.parser.Tokens.TokenKind.*;
  56 import static com.sun.tools.javac.parser.Tokens.TokenKind.ASSERT;
  57 import static com.sun.tools.javac.parser.Tokens.TokenKind.CASE;
  58 import static com.sun.tools.javac.parser.Tokens.TokenKind.CATCH;
  59 import static com.sun.tools.javac.parser.Tokens.TokenKind.EQ;
  60 import static com.sun.tools.javac.parser.Tokens.TokenKind.GT;
  61 import static com.sun.tools.javac.parser.Tokens.TokenKind.IMPORT;
  62 import static com.sun.tools.javac.parser.Tokens.TokenKind.LT;

  63 import com.sun.tools.javac.parser.VirtualParser.VirtualScanner;
  64 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  65 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.ImplicitAndExplicitNotAllowed;
  66 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.VarAndExplicitNotAllowed;
  67 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.VarAndImplicitNotAllowed;
  68 import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
  69 
  70 /**
  71  * The parser maps a token sequence into an abstract syntax tree.
  72  * The parser is a hand-written recursive-descent parser that
  73  * implements the grammar described in the Java Language Specification.
  74  * For efficiency reasons, an operator precedence scheme is used
  75  * for parsing binary operation expressions.
  76  *
  77  *  <p><b>This is NOT part of any supported API.
  78  *  If you write code that depends on this, you do so at your own risk.
  79  *  This code and its internal interfaces are subject to change or
  80  *  deletion without notice.</b>
  81  */
  82 public class JavacParser implements Parser {

 181                      boolean keepLineMap,
 182                      boolean keepEndPositions,
 183                      boolean parseModuleInfo) {
 184         this.S = S;
 185         nextToken(); // prime the pump
 186         this.F = fac.F;
 187         this.log = fac.log;
 188         this.names = fac.names;
 189         this.source = fac.source;
 190         this.preview = fac.preview;
 191         this.allowStringFolding = fac.options.getBoolean("allowStringFolding", true);
 192         this.keepDocComments = keepDocComments;
 193         this.parseModuleInfo = parseModuleInfo;
 194         this.docComments = newDocCommentTable(keepDocComments, fac);
 195         this.keepLineMap = keepLineMap;
 196         this.errorTree = F.Erroneous();
 197         this.endPosTable = newEndPosTable(keepEndPositions);
 198         this.allowYieldStatement = Feature.SWITCH_EXPRESSION.allowedInSource(source);
 199         this.allowRecords = Feature.RECORDS.allowedInSource(source);
 200         this.allowSealedTypes = Feature.SEALED_CLASSES.allowedInSource(source);


 201         updateUnexpectedTopLevelDefinitionStartError(false);
 202     }
 203 
 204     /** Construct a parser from an existing parser, with minimal overhead.
 205      */
 206     @SuppressWarnings("this-escape")
 207     protected JavacParser(JavacParser parser,
 208                           Lexer S) {
 209         this.S = S;
 210         this.token = parser.token;
 211         this.F = parser.F;
 212         this.log = parser.log;
 213         this.names = parser.names;
 214         this.source = parser.source;
 215         this.preview = parser.preview;
 216         this.allowStringFolding = parser.allowStringFolding;
 217         this.keepDocComments = parser.keepDocComments;
 218         this.parseModuleInfo = false;
 219         this.docComments = parser.docComments;
 220         this.errorTree = F.Erroneous();
 221         this.endPosTable = newEndPosTable(false);
 222         this.allowYieldStatement = Feature.SWITCH_EXPRESSION.allowedInSource(source);
 223         this.allowRecords = Feature.RECORDS.allowedInSource(source);
 224         this.allowSealedTypes = Feature.SEALED_CLASSES.allowedInSource(source);


 225         updateUnexpectedTopLevelDefinitionStartError(false);
 226     }
 227 
 228     protected AbstractEndPosTable newEndPosTable(boolean keepEndPositions) {
 229         return  keepEndPositions
 230                 ? new SimpleEndPosTable()
 231                 : new MinimalEndPosTable();
 232     }
 233 
 234     protected DocCommentTable newDocCommentTable(boolean keepDocComments, ParserFactory fac) {
 235         return keepDocComments ? new LazyDocCommentTable(fac) : null;
 236     }
 237 
 238     /** Switch: should we fold strings?
 239      */
 240     boolean allowStringFolding;
 241 
 242     /** Switch: should we keep docComments?
 243      */
 244     boolean keepDocComments;
 245 
 246     /** Switch: should we keep line table?
 247      */
 248     boolean keepLineMap;
 249 
 250     /** Switch: is "this" allowed as an identifier?
 251      * This is needed to parse receiver types.
 252      */
 253     boolean allowThisIdent;
 254 
 255     /** Switch: is yield statement allowed in this source level?
 256      */
 257     boolean allowYieldStatement;
 258 
 259     /** Switch: are records allowed in this source level?
 260      */
 261     boolean allowRecords;
 262 




 263     /** Switch: are sealed types allowed in this source level?
 264      */
 265     boolean allowSealedTypes;
 266 
 267     /** The type of the method receiver, as specified by a first "this" parameter.
 268      */
 269     JCVariableDecl receiverParam;
 270 
 271     /** When terms are parsed, the mode determines which is expected:
 272      *     mode = EXPR        : an expression
 273      *     mode = TYPE        : a type
 274      *     mode = NOPARAMS    : no parameters allowed for type
 275      *     mode = TYPEARG     : type argument
 276      *     mode |= NOLAMBDA   : lambdas are not allowed
 277      */
 278     protected static final int EXPR          = 1 << 0;
 279     protected static final int TYPE          = 1 << 1;
 280     protected static final int NOPARAMS      = 1 << 2;
 281     protected static final int TYPEARG       = 1 << 3;
 282     protected static final int DIAMOND       = 1 << 4;

1670                             token.kind == MONKEYS_AT) {
1671                             //error recovery, case like:
1672                             //int i = expr.<missing-ident>
1673                             //@Deprecated
1674                             if (typeArgs != null) illegal();
1675                             return toP(t);
1676                         }
1677                         if (tyannos != null && tyannos.nonEmpty()) {
1678                             t = toP(F.at(tyannos.head.pos).AnnotatedType(tyannos, t));
1679                         }
1680                         break;
1681                     case ELLIPSIS:
1682                         if (this.permitTypeAnnotationsPushBack) {
1683                             this.typeAnnotationsPushedBack = annos;
1684                         } else if (annos.nonEmpty()) {
1685                             // Don't return here -- error recovery attempt
1686                             illegal(annos.head.pos);
1687                         }
1688                         break loop;
1689                     case LT:
1690                         if (!isMode(TYPE) && isUnboundMemberRef()) {
1691                             //this is an unbound method reference whose qualifier
1692                             //is a generic type i.e. A<S>::m
1693                             int pos1 = token.pos;
1694                             accept(LT);
1695                             ListBuffer<JCExpression> args = new ListBuffer<>();
1696                             args.append(typeArgument());
1697                             while (token.kind == COMMA) {
1698                                 nextToken();
1699                                 args.append(typeArgument());
1700                             }
1701                             accept(GT);
1702                             t = toP(F.at(pos1).TypeApply(t, args.toList()));
1703                             while (token.kind == DOT) {
1704                                 nextToken();
1705                                 selectTypeMode();
1706                                 t = toP(F.at(token.pos).Select(t, ident()));
1707                                 t = typeArgumentsOpt(t);
1708                             }
1709                             t = bracketsOpt(t);
1710                             if (token.kind != COLCOL) {
1711                                 //method reference expected here

1916                         return illegal(annos.head.pos);
1917                 }
1918                 break;
1919             }
1920         }
1921         while ((token.kind == PLUSPLUS || token.kind == SUBSUB) && isMode(EXPR)) {
1922             selectExprMode();
1923             t = to(F.at(token.pos).Unary(
1924                   token.kind == PLUSPLUS ? POSTINC : POSTDEC, t));
1925             nextToken();
1926         }
1927         return toP(t);
1928     }
1929 
1930     /**
1931      * If we see an identifier followed by a '&lt;' it could be an unbound
1932      * method reference or a binary expression. To disambiguate, look for a
1933      * matching '&gt;' and see if the subsequent terminal is either '.' or '::'.
1934      */
1935     @SuppressWarnings("fallthrough")
1936     boolean isUnboundMemberRef() {
1937         int pos = 0, depth = 0;
1938         outer: for (Token t = S.token(pos) ; ; t = S.token(++pos)) {
1939             switch (t.kind) {
1940                 case IDENTIFIER: case UNDERSCORE: case QUES: case EXTENDS: case SUPER:
1941                 case DOT: case RBRACKET: case LBRACKET: case COMMA:
1942                 case BYTE: case SHORT: case INT: case LONG: case FLOAT:
1943                 case DOUBLE: case BOOLEAN: case CHAR:
1944                 case MONKEYS_AT:
1945                     break;
1946 
1947                 case LPAREN:
1948                     // skip annotation values
1949                     int nesting = 0;
1950                     for (; ; pos++) {
1951                         TokenKind tk2 = S.token(pos).kind;
1952                         switch (tk2) {
1953                             case EOF:
1954                                 return false;
1955                             case LPAREN:
1956                                 nesting++;

3012                     accept(SEMI);
3013                     return List.of(toP(F.at(pos).Yield(t)));
3014                 }
3015 
3016                 //else intentional fall-through
3017             } else {
3018                 if (isNonSealedClassStart(true)) {
3019                     log.error(token.pos, Errors.SealedOrNonSealedLocalClassesNotAllowed);
3020                     nextToken();
3021                     nextToken();
3022                     nextToken();
3023                     return List.of(classOrRecordOrInterfaceOrEnumDeclaration(modifiersOpt(), token.docComment()));
3024                 } else if (isSealedClassStart(true)) {
3025                     checkSourceLevel(Feature.SEALED_CLASSES);
3026                     log.error(token.pos, Errors.SealedOrNonSealedLocalClassesNotAllowed);
3027                     nextToken();
3028                     return List.of(classOrRecordOrInterfaceOrEnumDeclaration(modifiersOpt(), token.docComment()));
3029                 }
3030             }
3031         }





3032         dc = token.docComment();
3033         if (isRecordStart() && allowRecords) {
3034             return List.of(recordDeclaration(F.at(pos).Modifiers(0), dc));
3035         } else {
3036             Token prevToken = token;
3037             JCExpression t = term(EXPR | TYPE);
3038             if (token.kind == COLON && t.hasTag(IDENT)) {
3039                 nextToken();
3040                 JCStatement stat = parseStatementAsBlock();
3041                 return List.of(F.at(pos).Labelled(prevToken.name(), stat));
3042             } else if (wasTypeMode() && LAX_IDENTIFIER.test(token.kind)) {
3043                 pos = token.pos;
3044                 JCModifiers mods = F.at(Position.NOPOS).Modifiers(0);
3045                 F.at(pos);
3046                 return localVariableDeclarations(mods, t, dc);
3047             } else {
3048                 // This Exec is an "ExpressionStatement"; it subsumes the terminating semicolon
3049                 t = checkExprStat(t);
3050                 accept(SEMI);
3051                 JCExpressionStatement expr = toP(F.at(pos).Exec(t));

3617             case ABSTRACT    : flag = Flags.ABSTRACT; break;
3618             case NATIVE      : flag = Flags.NATIVE; break;
3619             case VOLATILE    : flag = Flags.VOLATILE; break;
3620             case SYNCHRONIZED: flag = Flags.SYNCHRONIZED; break;
3621             case STRICTFP    : flag = Flags.STRICTFP; break;
3622             case MONKEYS_AT  : flag = Flags.ANNOTATION; break;
3623             case DEFAULT     : flag = Flags.DEFAULT; break;
3624             case ERROR       : flag = 0; nextToken(); break;
3625             case IDENTIFIER  : {
3626                 if (isNonSealedClassStart(false)) {
3627                     flag = Flags.NON_SEALED;
3628                     nextToken();
3629                     nextToken();
3630                     break;
3631                 }
3632                 if (isSealedClassStart(false)) {
3633                     checkSourceLevel(Feature.SEALED_CLASSES);
3634                     flag = Flags.SEALED;
3635                     break;
3636                 }





3637                 break loop;
3638             }
3639             default: break loop;
3640             }
3641             if ((flags & flag) != 0) log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.RepeatedModifier);
3642             lastPos = token.pos;
3643             nextToken();
3644             if (flag == Flags.ANNOTATION) {
3645                 if (token.kind != INTERFACE) {
3646                     JCAnnotation ann = annotation(lastPos, Tag.ANNOTATION);
3647                     // if first modifier is an annotation, set pos to annotation's.
3648                     if (flags == 0 && annotations.isEmpty())
3649                         pos = ann.pos;
3650                     annotations.append(ann);
3651                     flag = 0;
3652                 }
3653             }
3654             flags |= flag;
3655         }
3656         switch (token.kind) {

3880             if (Feature.LOCAL_VARIABLE_TYPE_INFERENCE.allowedInSource(source)) {
3881                 return Source.JDK10;
3882             } else if (shouldWarn) {
3883                 log.warning(pos, Warnings.RestrictedTypeNotAllowed(name, Source.JDK10));
3884             }
3885         }
3886         if (name == names.yield) {
3887             if (allowYieldStatement) {
3888                 return Source.JDK14;
3889             } else if (shouldWarn) {
3890                 log.warning(pos, Warnings.RestrictedTypeNotAllowed(name, Source.JDK14));
3891             }
3892         }
3893         if (name == names.record) {
3894             if (allowRecords) {
3895                 return Source.JDK14;
3896             } else if (shouldWarn) {
3897                 log.warning(pos, Warnings.RestrictedTypeNotAllowedPreview(name, Source.JDK14));
3898             }
3899         }







3900         if (name == names.sealed) {
3901             if (allowSealedTypes) {
3902                 return Source.JDK15;
3903             } else if (shouldWarn) {
3904                 log.warning(pos, Warnings.RestrictedTypeNotAllowedPreview(name, Source.JDK15));
3905             }
3906         }
3907         if (name == names.permits) {
3908             if (allowSealedTypes) {
3909                 return Source.JDK15;
3910             } else if (shouldWarn) {
3911                 log.warning(pos, Warnings.RestrictedTypeNotAllowedPreview(name, Source.JDK15));
3912             }
3913         }
3914         return null;
3915     }
3916 
3917     /** VariableDeclaratorId = Ident BracketsOpt
3918      */
3919     JCVariableDecl variableDeclaratorId(JCModifiers mods, JCExpression type, boolean catchParameter, boolean lambdaParameter, boolean recordComponent) {

5001             Token next = S.token(3);
5002             return allowedAfterSealedOrNonSealed(next, local, true);
5003         }
5004         return false;
5005     }
5006 
5007     protected boolean isNonSealedIdentifier(Token someToken, int lookAheadOffset) {
5008         if (someToken.name() == names.non && peekToken(lookAheadOffset, TokenKind.SUB, TokenKind.IDENTIFIER)) {
5009             Token tokenSub = S.token(lookAheadOffset + 1);
5010             Token tokenSealed = S.token(lookAheadOffset + 2);
5011             if (someToken.endPos == tokenSub.pos &&
5012                     tokenSub.endPos == tokenSealed.pos &&
5013                     tokenSealed.name() == names.sealed) {
5014                 checkSourceLevel(Feature.SEALED_CLASSES);
5015                 return true;
5016             }
5017         }
5018         return false;
5019     }
5020 


























5021     protected boolean isSealedClassStart(boolean local) {
5022         if (token.name() == names.sealed) {
5023             Token next = S.token(1);
5024             if (allowedAfterSealedOrNonSealed(next, local, false)) {
5025                 checkSourceLevel(Feature.SEALED_CLASSES);
5026                 return true;
5027             }
5028         }
5029         return false;
5030     }
5031 
5032     private boolean allowedAfterSealedOrNonSealed(Token next, boolean local, boolean currentIsNonSealed) {
5033         return local ?
5034             switch (next.kind) {
5035                 case MONKEYS_AT -> {
5036                     Token afterNext = S.token(2);
5037                     yield afterNext.kind != INTERFACE || currentIsNonSealed;
5038                 }
5039                 case ABSTRACT, FINAL, STRICTFP, CLASS, INTERFACE, ENUM -> true;
5040                 default -> false;
5041             } :
5042             switch (next.kind) {
5043                 case MONKEYS_AT -> {
5044                     Token afterNext = S.token(2);
5045                     yield afterNext.kind != INTERFACE || currentIsNonSealed;
5046                 }
5047                 case PUBLIC, PROTECTED, PRIVATE, ABSTRACT, STATIC, FINAL, STRICTFP, CLASS, INTERFACE, ENUM -> true;
5048                 case IDENTIFIER -> isNonSealedIdentifier(next, currentIsNonSealed ? 3 : 1) || next.name() == names.sealed;


5049                 default -> false;
5050             };
5051     }
5052 
5053     /** MethodDeclaratorRest =
5054      *      FormalParameters BracketsOpt [THROWS TypeList] ( MethodBody | [DEFAULT AnnotationValue] ";")
5055      *  VoidMethodDeclaratorRest =
5056      *      FormalParameters [THROWS TypeList] ( MethodBody | ";")
5057      *  ConstructorDeclaratorRest =
5058      *      "(" FormalParameterListOpt ")" [THROWS TypeList] MethodBody
5059      */
5060     protected JCTree methodDeclaratorRest(int pos,
5061                               JCModifiers mods,
5062                               JCExpression type,
5063                               Name name,
5064                               List<JCTypeParameter> typarams,
5065                               boolean isInterface, boolean isVoid,
5066                               boolean isRecord,
5067                               Comment dc) {
5068         if (isInterface) {

  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.parser;
  27 
  28 import java.util.*;
  29 import java.util.function.Function;
  30 import java.util.function.Predicate;
  31 import java.util.stream.Collectors;
  32 
  33 import javax.lang.model.SourceVersion;
  34 
  35 import com.sun.source.tree.CaseTree;
  36 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
  37 import com.sun.source.tree.ModuleTree.ModuleKind;
  38 
  39 import com.sun.tools.javac.code.*;
  40 import com.sun.tools.javac.code.FlagsEnum;
  41 import com.sun.tools.javac.code.Source.Feature;
  42 import com.sun.tools.javac.file.PathFileObject;
  43 import com.sun.tools.javac.parser.Tokens.*;
  44 import com.sun.tools.javac.parser.Tokens.Comment.CommentStyle;
  45 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  46 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  47 import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
  48 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  49 import com.sun.tools.javac.tree.*;
  50 import com.sun.tools.javac.tree.JCTree.*;
  51 import com.sun.tools.javac.util.*;
  52 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
  53 import com.sun.tools.javac.util.JCDiagnostic.Error;
  54 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
  55 import com.sun.tools.javac.util.List;
  56 
  57 import static com.sun.tools.javac.code.Flags.asFlagSet;
  58 import static com.sun.tools.javac.parser.Tokens.TokenKind.*;
  59 import static com.sun.tools.javac.parser.Tokens.TokenKind.ASSERT;
  60 import static com.sun.tools.javac.parser.Tokens.TokenKind.CASE;
  61 import static com.sun.tools.javac.parser.Tokens.TokenKind.CATCH;
  62 import static com.sun.tools.javac.parser.Tokens.TokenKind.EQ;
  63 import static com.sun.tools.javac.parser.Tokens.TokenKind.GT;
  64 import static com.sun.tools.javac.parser.Tokens.TokenKind.IMPORT;
  65 import static com.sun.tools.javac.parser.Tokens.TokenKind.LT;
  66 import static com.sun.tools.javac.parser.Tokens.TokenKind.SYNCHRONIZED;
  67 import com.sun.tools.javac.parser.VirtualParser.VirtualScanner;
  68 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  69 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.ImplicitAndExplicitNotAllowed;
  70 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.VarAndExplicitNotAllowed;
  71 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.VarAndImplicitNotAllowed;
  72 import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
  73 
  74 /**
  75  * The parser maps a token sequence into an abstract syntax tree.
  76  * The parser is a hand-written recursive-descent parser that
  77  * implements the grammar described in the Java Language Specification.
  78  * For efficiency reasons, an operator precedence scheme is used
  79  * for parsing binary operation expressions.
  80  *
  81  *  <p><b>This is NOT part of any supported API.
  82  *  If you write code that depends on this, you do so at your own risk.
  83  *  This code and its internal interfaces are subject to change or
  84  *  deletion without notice.</b>
  85  */
  86 public class JavacParser implements Parser {

 185                      boolean keepLineMap,
 186                      boolean keepEndPositions,
 187                      boolean parseModuleInfo) {
 188         this.S = S;
 189         nextToken(); // prime the pump
 190         this.F = fac.F;
 191         this.log = fac.log;
 192         this.names = fac.names;
 193         this.source = fac.source;
 194         this.preview = fac.preview;
 195         this.allowStringFolding = fac.options.getBoolean("allowStringFolding", true);
 196         this.keepDocComments = keepDocComments;
 197         this.parseModuleInfo = parseModuleInfo;
 198         this.docComments = newDocCommentTable(keepDocComments, fac);
 199         this.keepLineMap = keepLineMap;
 200         this.errorTree = F.Erroneous();
 201         this.endPosTable = newEndPosTable(keepEndPositions);
 202         this.allowYieldStatement = Feature.SWITCH_EXPRESSION.allowedInSource(source);
 203         this.allowRecords = Feature.RECORDS.allowedInSource(source);
 204         this.allowSealedTypes = Feature.SEALED_CLASSES.allowedInSource(source);
 205         this.allowValueClasses = (!preview.isPreview(Feature.VALUE_CLASSES) || preview.isEnabled()) &&
 206                 Feature.VALUE_CLASSES.allowedInSource(source);
 207         updateUnexpectedTopLevelDefinitionStartError(false);
 208     }
 209 
 210     /** Construct a parser from an existing parser, with minimal overhead.
 211      */
 212     @SuppressWarnings("this-escape")
 213     protected JavacParser(JavacParser parser,
 214                           Lexer S) {
 215         this.S = S;
 216         this.token = parser.token;
 217         this.F = parser.F;
 218         this.log = parser.log;
 219         this.names = parser.names;
 220         this.source = parser.source;
 221         this.preview = parser.preview;
 222         this.allowStringFolding = parser.allowStringFolding;
 223         this.keepDocComments = parser.keepDocComments;
 224         this.parseModuleInfo = false;
 225         this.docComments = parser.docComments;
 226         this.errorTree = F.Erroneous();
 227         this.endPosTable = newEndPosTable(false);
 228         this.allowYieldStatement = Feature.SWITCH_EXPRESSION.allowedInSource(source);
 229         this.allowRecords = Feature.RECORDS.allowedInSource(source);
 230         this.allowSealedTypes = Feature.SEALED_CLASSES.allowedInSource(source);
 231         this.allowValueClasses = (!preview.isPreview(Feature.VALUE_CLASSES) || preview.isEnabled()) &&
 232                 Feature.VALUE_CLASSES.allowedInSource(source);
 233         updateUnexpectedTopLevelDefinitionStartError(false);
 234     }
 235 
 236     protected AbstractEndPosTable newEndPosTable(boolean keepEndPositions) {
 237         return  keepEndPositions
 238                 ? new SimpleEndPosTable()
 239                 : new MinimalEndPosTable();
 240     }
 241 
 242     protected DocCommentTable newDocCommentTable(boolean keepDocComments, ParserFactory fac) {
 243         return keepDocComments ? new LazyDocCommentTable(fac) : null;
 244     }
 245 
 246     /** Switch: should we fold strings?
 247      */
 248     boolean allowStringFolding;
 249 
 250     /** Switch: should we keep docComments?
 251      */
 252     boolean keepDocComments;
 253 
 254     /** Switch: should we keep line table?
 255      */
 256     boolean keepLineMap;
 257 
 258     /** Switch: is "this" allowed as an identifier?
 259      * This is needed to parse receiver types.
 260      */
 261     boolean allowThisIdent;
 262 
 263     /** Switch: is yield statement allowed in this source level?
 264      */
 265     boolean allowYieldStatement;
 266 
 267     /** Switch: are records allowed in this source level?
 268      */
 269     boolean allowRecords;
 270 
 271     /** Switch: are value classes allowed in this source level?
 272      */
 273     boolean allowValueClasses;
 274 
 275     /** Switch: are sealed types allowed in this source level?
 276      */
 277     boolean allowSealedTypes;
 278 
 279     /** The type of the method receiver, as specified by a first "this" parameter.
 280      */
 281     JCVariableDecl receiverParam;
 282 
 283     /** When terms are parsed, the mode determines which is expected:
 284      *     mode = EXPR        : an expression
 285      *     mode = TYPE        : a type
 286      *     mode = NOPARAMS    : no parameters allowed for type
 287      *     mode = TYPEARG     : type argument
 288      *     mode |= NOLAMBDA   : lambdas are not allowed
 289      */
 290     protected static final int EXPR          = 1 << 0;
 291     protected static final int TYPE          = 1 << 1;
 292     protected static final int NOPARAMS      = 1 << 2;
 293     protected static final int TYPEARG       = 1 << 3;
 294     protected static final int DIAMOND       = 1 << 4;

1682                             token.kind == MONKEYS_AT) {
1683                             //error recovery, case like:
1684                             //int i = expr.<missing-ident>
1685                             //@Deprecated
1686                             if (typeArgs != null) illegal();
1687                             return toP(t);
1688                         }
1689                         if (tyannos != null && tyannos.nonEmpty()) {
1690                             t = toP(F.at(tyannos.head.pos).AnnotatedType(tyannos, t));
1691                         }
1692                         break;
1693                     case ELLIPSIS:
1694                         if (this.permitTypeAnnotationsPushBack) {
1695                             this.typeAnnotationsPushedBack = annos;
1696                         } else if (annos.nonEmpty()) {
1697                             // Don't return here -- error recovery attempt
1698                             illegal(annos.head.pos);
1699                         }
1700                         break loop;
1701                     case LT:
1702                         if (!isMode(TYPE) && isParameterizedTypePrefix()) {
1703                             //this is either an unbound method reference whose qualifier
1704                             //is a generic type i.e. A<S>::m
1705                             int pos1 = token.pos;
1706                             accept(LT);
1707                             ListBuffer<JCExpression> args = new ListBuffer<>();
1708                             args.append(typeArgument());
1709                             while (token.kind == COMMA) {
1710                                 nextToken();
1711                                 args.append(typeArgument());
1712                             }
1713                             accept(GT);
1714                             t = toP(F.at(pos1).TypeApply(t, args.toList()));
1715                             while (token.kind == DOT) {
1716                                 nextToken();
1717                                 selectTypeMode();
1718                                 t = toP(F.at(token.pos).Select(t, ident()));
1719                                 t = typeArgumentsOpt(t);
1720                             }
1721                             t = bracketsOpt(t);
1722                             if (token.kind != COLCOL) {
1723                                 //method reference expected here

1928                         return illegal(annos.head.pos);
1929                 }
1930                 break;
1931             }
1932         }
1933         while ((token.kind == PLUSPLUS || token.kind == SUBSUB) && isMode(EXPR)) {
1934             selectExprMode();
1935             t = to(F.at(token.pos).Unary(
1936                   token.kind == PLUSPLUS ? POSTINC : POSTDEC, t));
1937             nextToken();
1938         }
1939         return toP(t);
1940     }
1941 
1942     /**
1943      * If we see an identifier followed by a '&lt;' it could be an unbound
1944      * method reference or a binary expression. To disambiguate, look for a
1945      * matching '&gt;' and see if the subsequent terminal is either '.' or '::'.
1946      */
1947     @SuppressWarnings("fallthrough")
1948     boolean isParameterizedTypePrefix() {
1949         int pos = 0, depth = 0;
1950         outer: for (Token t = S.token(pos) ; ; t = S.token(++pos)) {
1951             switch (t.kind) {
1952                 case IDENTIFIER: case UNDERSCORE: case QUES: case EXTENDS: case SUPER:
1953                 case DOT: case RBRACKET: case LBRACKET: case COMMA:
1954                 case BYTE: case SHORT: case INT: case LONG: case FLOAT:
1955                 case DOUBLE: case BOOLEAN: case CHAR:
1956                 case MONKEYS_AT:
1957                     break;
1958 
1959                 case LPAREN:
1960                     // skip annotation values
1961                     int nesting = 0;
1962                     for (; ; pos++) {
1963                         TokenKind tk2 = S.token(pos).kind;
1964                         switch (tk2) {
1965                             case EOF:
1966                                 return false;
1967                             case LPAREN:
1968                                 nesting++;

3024                     accept(SEMI);
3025                     return List.of(toP(F.at(pos).Yield(t)));
3026                 }
3027 
3028                 //else intentional fall-through
3029             } else {
3030                 if (isNonSealedClassStart(true)) {
3031                     log.error(token.pos, Errors.SealedOrNonSealedLocalClassesNotAllowed);
3032                     nextToken();
3033                     nextToken();
3034                     nextToken();
3035                     return List.of(classOrRecordOrInterfaceOrEnumDeclaration(modifiersOpt(), token.docComment()));
3036                 } else if (isSealedClassStart(true)) {
3037                     checkSourceLevel(Feature.SEALED_CLASSES);
3038                     log.error(token.pos, Errors.SealedOrNonSealedLocalClassesNotAllowed);
3039                     nextToken();
3040                     return List.of(classOrRecordOrInterfaceOrEnumDeclaration(modifiersOpt(), token.docComment()));
3041                 }
3042             }
3043         }
3044         if ((isValueModifier()) && allowValueClasses) {
3045             checkSourceLevel(Feature.VALUE_CLASSES);
3046             dc = token.docComment();
3047             return List.of(classOrRecordOrInterfaceOrEnumDeclaration(modifiersOpt(), dc));
3048         }
3049         dc = token.docComment();
3050         if (isRecordStart() && allowRecords) {
3051             return List.of(recordDeclaration(F.at(pos).Modifiers(0), dc));
3052         } else {
3053             Token prevToken = token;
3054             JCExpression t = term(EXPR | TYPE);
3055             if (token.kind == COLON && t.hasTag(IDENT)) {
3056                 nextToken();
3057                 JCStatement stat = parseStatementAsBlock();
3058                 return List.of(F.at(pos).Labelled(prevToken.name(), stat));
3059             } else if (wasTypeMode() && LAX_IDENTIFIER.test(token.kind)) {
3060                 pos = token.pos;
3061                 JCModifiers mods = F.at(Position.NOPOS).Modifiers(0);
3062                 F.at(pos);
3063                 return localVariableDeclarations(mods, t, dc);
3064             } else {
3065                 // This Exec is an "ExpressionStatement"; it subsumes the terminating semicolon
3066                 t = checkExprStat(t);
3067                 accept(SEMI);
3068                 JCExpressionStatement expr = toP(F.at(pos).Exec(t));

3634             case ABSTRACT    : flag = Flags.ABSTRACT; break;
3635             case NATIVE      : flag = Flags.NATIVE; break;
3636             case VOLATILE    : flag = Flags.VOLATILE; break;
3637             case SYNCHRONIZED: flag = Flags.SYNCHRONIZED; break;
3638             case STRICTFP    : flag = Flags.STRICTFP; break;
3639             case MONKEYS_AT  : flag = Flags.ANNOTATION; break;
3640             case DEFAULT     : flag = Flags.DEFAULT; break;
3641             case ERROR       : flag = 0; nextToken(); break;
3642             case IDENTIFIER  : {
3643                 if (isNonSealedClassStart(false)) {
3644                     flag = Flags.NON_SEALED;
3645                     nextToken();
3646                     nextToken();
3647                     break;
3648                 }
3649                 if (isSealedClassStart(false)) {
3650                     checkSourceLevel(Feature.SEALED_CLASSES);
3651                     flag = Flags.SEALED;
3652                     break;
3653                 }
3654                 if (isValueModifier()) {
3655                     checkSourceLevel(Feature.VALUE_CLASSES);
3656                     flag = Flags.VALUE_CLASS;
3657                     break;
3658                 }
3659                 break loop;
3660             }
3661             default: break loop;
3662             }
3663             if ((flags & flag) != 0) log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.RepeatedModifier);
3664             lastPos = token.pos;
3665             nextToken();
3666             if (flag == Flags.ANNOTATION) {
3667                 if (token.kind != INTERFACE) {
3668                     JCAnnotation ann = annotation(lastPos, Tag.ANNOTATION);
3669                     // if first modifier is an annotation, set pos to annotation's.
3670                     if (flags == 0 && annotations.isEmpty())
3671                         pos = ann.pos;
3672                     annotations.append(ann);
3673                     flag = 0;
3674                 }
3675             }
3676             flags |= flag;
3677         }
3678         switch (token.kind) {

3902             if (Feature.LOCAL_VARIABLE_TYPE_INFERENCE.allowedInSource(source)) {
3903                 return Source.JDK10;
3904             } else if (shouldWarn) {
3905                 log.warning(pos, Warnings.RestrictedTypeNotAllowed(name, Source.JDK10));
3906             }
3907         }
3908         if (name == names.yield) {
3909             if (allowYieldStatement) {
3910                 return Source.JDK14;
3911             } else if (shouldWarn) {
3912                 log.warning(pos, Warnings.RestrictedTypeNotAllowed(name, Source.JDK14));
3913             }
3914         }
3915         if (name == names.record) {
3916             if (allowRecords) {
3917                 return Source.JDK14;
3918             } else if (shouldWarn) {
3919                 log.warning(pos, Warnings.RestrictedTypeNotAllowedPreview(name, Source.JDK14));
3920             }
3921         }
3922         if (name == names.value) {
3923             if (allowValueClasses) {
3924                 return Source.JDK23;
3925             } else if (shouldWarn) {
3926                 log.warning(pos, Warnings.RestrictedTypeNotAllowedPreview(name, Source.JDK23));
3927             }
3928         }
3929         if (name == names.sealed) {
3930             if (allowSealedTypes) {
3931                 return Source.JDK15;
3932             } else if (shouldWarn) {
3933                 log.warning(pos, Warnings.RestrictedTypeNotAllowedPreview(name, Source.JDK15));
3934             }
3935         }
3936         if (name == names.permits) {
3937             if (allowSealedTypes) {
3938                 return Source.JDK15;
3939             } else if (shouldWarn) {
3940                 log.warning(pos, Warnings.RestrictedTypeNotAllowedPreview(name, Source.JDK15));
3941             }
3942         }
3943         return null;
3944     }
3945 
3946     /** VariableDeclaratorId = Ident BracketsOpt
3947      */
3948     JCVariableDecl variableDeclaratorId(JCModifiers mods, JCExpression type, boolean catchParameter, boolean lambdaParameter, boolean recordComponent) {

5030             Token next = S.token(3);
5031             return allowedAfterSealedOrNonSealed(next, local, true);
5032         }
5033         return false;
5034     }
5035 
5036     protected boolean isNonSealedIdentifier(Token someToken, int lookAheadOffset) {
5037         if (someToken.name() == names.non && peekToken(lookAheadOffset, TokenKind.SUB, TokenKind.IDENTIFIER)) {
5038             Token tokenSub = S.token(lookAheadOffset + 1);
5039             Token tokenSealed = S.token(lookAheadOffset + 2);
5040             if (someToken.endPos == tokenSub.pos &&
5041                     tokenSub.endPos == tokenSealed.pos &&
5042                     tokenSealed.name() == names.sealed) {
5043                 checkSourceLevel(Feature.SEALED_CLASSES);
5044                 return true;
5045             }
5046         }
5047         return false;
5048     }
5049 
5050     protected boolean isValueModifier() {
5051         if (token.kind == IDENTIFIER && token.name() == names.value) {
5052             boolean isValueModifier = false;
5053             Token next = S.token(1);
5054             switch (next.kind) {
5055                 case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: case TRANSIENT:
5056                 case FINAL: case ABSTRACT: case NATIVE: case VOLATILE: case SYNCHRONIZED:
5057                 case STRICTFP: case MONKEYS_AT: case DEFAULT: case BYTE: case SHORT:
5058                 case CHAR: case INT: case LONG: case FLOAT: case DOUBLE: case BOOLEAN: case VOID:
5059                 case CLASS: case INTERFACE: case ENUM:
5060                     isValueModifier = true;
5061                     break;
5062                 case IDENTIFIER: // value record R || value value || new value Comparable() {} ??
5063                     if (next.name() == names.record || next.name() == names.value
5064                             || (mode & EXPR) != 0)
5065                         isValueModifier = true;
5066                     break;
5067             }
5068             if (isValueModifier) {
5069                 checkSourceLevel(Feature.VALUE_CLASSES);
5070                 return true;
5071             }
5072         }
5073         return false;
5074     }
5075 
5076     protected boolean isSealedClassStart(boolean local) {
5077         if (token.name() == names.sealed) {
5078             Token next = S.token(1);
5079             if (allowedAfterSealedOrNonSealed(next, local, false)) {
5080                 checkSourceLevel(Feature.SEALED_CLASSES);
5081                 return true;
5082             }
5083         }
5084         return false;
5085     }
5086 
5087     private boolean allowedAfterSealedOrNonSealed(Token next, boolean local, boolean currentIsNonSealed) {
5088         return local ?
5089             switch (next.kind) {
5090                 case MONKEYS_AT -> {
5091                     Token afterNext = S.token(2);
5092                     yield afterNext.kind != INTERFACE || currentIsNonSealed;
5093                 }
5094                 case ABSTRACT, FINAL, STRICTFP, CLASS, INTERFACE, ENUM -> true;
5095                 default -> false;
5096             } :
5097             switch (next.kind) {
5098                 case MONKEYS_AT -> {
5099                     Token afterNext = S.token(2);
5100                     yield afterNext.kind != INTERFACE || currentIsNonSealed;
5101                 }
5102                 case PUBLIC, PROTECTED, PRIVATE, ABSTRACT, STATIC, FINAL, STRICTFP, CLASS, INTERFACE, ENUM -> true;
5103                 case IDENTIFIER -> isNonSealedIdentifier(next, currentIsNonSealed ? 3 : 1) ||
5104                         next.name() == names.sealed ||
5105                         allowValueClasses && next.name() == names.value;
5106                 default -> false;
5107             };
5108     }
5109 
5110     /** MethodDeclaratorRest =
5111      *      FormalParameters BracketsOpt [THROWS TypeList] ( MethodBody | [DEFAULT AnnotationValue] ";")
5112      *  VoidMethodDeclaratorRest =
5113      *      FormalParameters [THROWS TypeList] ( MethodBody | ";")
5114      *  ConstructorDeclaratorRest =
5115      *      "(" FormalParameterListOpt ")" [THROWS TypeList] MethodBody
5116      */
5117     protected JCTree methodDeclaratorRest(int pos,
5118                               JCModifiers mods,
5119                               JCExpression type,
5120                               Name name,
5121                               List<JCTypeParameter> typarams,
5122                               boolean isInterface, boolean isVoid,
5123                               boolean isRecord,
5124                               Comment dc) {
5125         if (isInterface) {
< prev index next >