1 /*
   2  * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  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 com.sun.source.tree.CaseTree;
  34 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
  35 import com.sun.source.tree.ModuleTree.ModuleKind;
  36 
  37 import com.sun.tools.javac.code.*;
  38 import com.sun.tools.javac.code.Source.Feature;
  39 import com.sun.tools.javac.parser.Tokens.*;
  40 import com.sun.tools.javac.parser.Tokens.Comment.CommentStyle;
  41 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  42 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  43 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  44 import com.sun.tools.javac.tree.*;
  45 import com.sun.tools.javac.tree.JCTree.*;
  46 import com.sun.tools.javac.util.*;
  47 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
  48 import com.sun.tools.javac.util.JCDiagnostic.Error;
  49 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
  50 import com.sun.tools.javac.util.List;
  51 
  52 import static com.sun.tools.javac.parser.Tokens.TokenKind.*;
  53 import static com.sun.tools.javac.parser.Tokens.TokenKind.ASSERT;
  54 import static com.sun.tools.javac.parser.Tokens.TokenKind.CASE;
  55 import static com.sun.tools.javac.parser.Tokens.TokenKind.CATCH;
  56 import static com.sun.tools.javac.parser.Tokens.TokenKind.EQ;
  57 import static com.sun.tools.javac.parser.Tokens.TokenKind.GT;
  58 import static com.sun.tools.javac.parser.Tokens.TokenKind.IMPORT;
  59 import static com.sun.tools.javac.parser.Tokens.TokenKind.LT;
  60 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  61 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.ImplicitAndExplicitNotAllowed;
  62 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.VarAndExplicitNotAllowed;
  63 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.VarAndImplicitNotAllowed;
  64 import java.util.function.BiFunction;
  65 
  66 /**
  67  * The parser maps a token sequence into an abstract syntax tree.
  68  * The parser is a hand-written recursive-descent parser that
  69  * implements the grammar described in the Java Language Specification.
  70  * For efficiency reasons, an operator precedence scheme is used
  71  * for parsing binary operation expressions.
  72  *
  73  *  <p><b>This is NOT part of any supported API.
  74  *  If you write code that depends on this, you do so at your own risk.
  75  *  This code and its internal interfaces are subject to change or
  76  *  deletion without notice.</b>
  77  */
  78 public class JavacParser implements Parser {
  79 
  80     /** The number of precedence levels of infix operators.
  81      */
  82     private static final int infixPrecedenceLevels = 10;
  83 
  84     /** Is the parser instantiated to parse a module-info file ?
  85      */
  86     private final boolean parseModuleInfo;
  87 
  88     /** The scanner used for lexical analysis.
  89      */
  90     protected Lexer S;
  91 
  92     /** The factory to be used for abstract syntax tree construction.
  93      */
  94     protected TreeMaker F;
  95 
  96     /** The log to be used for error diagnostics.
  97      */
  98     private Log log;
  99 
 100     /** The Source language setting. */
 101     private Source source;
 102 
 103     /** The Preview language setting. */
 104     private Preview preview;
 105 
 106     /** The name table. */
 107     private Names names;
 108 
 109     /** End position mappings container */
 110     protected final AbstractEndPosTable endPosTable;
 111 
 112     // Because of javac's limited lookahead, some contexts are ambiguous in
 113     // the presence of type annotations even though they are not ambiguous
 114     // in the absence of type annotations.  Consider this code:
 115     //   void m(String [] m) { }
 116     //   void m(String ... m) { }
 117     // After parsing "String", javac calls bracketsOpt which immediately
 118     // returns if the next character is not '['.  Similarly, javac can see
 119     // if the next token is ... and in that case parse an ellipsis.  But in
 120     // the presence of type annotations:
 121     //   void m(String @A [] m) { }
 122     //   void m(String @A ... m) { }
 123     // no finite lookahead is enough to determine whether to read array
 124     // levels or an ellipsis.  Furthermore, if you call bracketsOpt, then
 125     // bracketsOpt first reads all the leading annotations and only then
 126     // discovers that it needs to fail.  bracketsOpt needs a way to push
 127     // back the extra annotations that it read.  (But, bracketsOpt should
 128     // not *always* be allowed to push back extra annotations that it finds
 129     // -- in most contexts, any such extra annotation is an error.
 130     //
 131     // The following two variables permit type annotations that have
 132     // already been read to be stored for later use.  Alternate
 133     // implementations are possible but would cause much larger changes to
 134     // the parser.
 135 
 136     /** Type annotations that have already been read but have not yet been used. **/
 137     private List<JCAnnotation> typeAnnotationsPushedBack = List.nil();
 138 
 139     /**
 140      * If the parser notices extra annotations, then it either immediately
 141      * issues an error (if this variable is false) or places the extra
 142      * annotations in variable typeAnnotationsPushedBack (if this variable
 143      * is true).
 144      */
 145     private boolean permitTypeAnnotationsPushBack = false;
 146 
 147     interface ErrorRecoveryAction {
 148         JCTree doRecover(JavacParser parser);
 149     }
 150 
 151     enum BasicErrorRecoveryAction implements ErrorRecoveryAction {
 152         BLOCK_STMT {public JCTree doRecover(JavacParser parser) { return parser.parseStatementAsBlock(); }},
 153         CATCH_CLAUSE {public JCTree doRecover(JavacParser parser) { return parser.catchClause(); }}
 154     }
 155 
 156     /** Construct a parser from a given scanner, tree factory and log.
 157      */
 158     protected JavacParser(ParserFactory fac,
 159                           Lexer S,
 160                           boolean keepDocComments,
 161                           boolean keepLineMap,
 162                           boolean keepEndPositions) {
 163         this(fac, S, keepDocComments, keepLineMap, keepEndPositions, false);
 164 
 165     }
 166     /** Construct a parser from a given scanner, tree factory and log.
 167      */
 168     protected JavacParser(ParserFactory fac,
 169                      Lexer S,
 170                      boolean keepDocComments,
 171                      boolean keepLineMap,
 172                      boolean keepEndPositions,
 173                      boolean parseModuleInfo) {
 174         this.S = S;
 175         nextToken(); // prime the pump
 176         this.F = fac.F;
 177         this.log = fac.log;
 178         this.names = fac.names;
 179         this.source = fac.source;
 180         this.preview = fac.preview;
 181         this.allowStringFolding = fac.options.getBoolean("allowStringFolding", true);
 182         this.keepDocComments = keepDocComments;
 183         this.parseModuleInfo = parseModuleInfo;
 184         docComments = newDocCommentTable(keepDocComments, fac);
 185         this.keepLineMap = keepLineMap;
 186         this.errorTree = F.Erroneous();
 187         endPosTable = newEndPosTable(keepEndPositions);
 188         this.allowYieldStatement = Feature.SWITCH_EXPRESSION.allowedInSource(source);
 189         this.allowRecords = Feature.RECORDS.allowedInSource(source);
 190         this.allowSealedTypes = Feature.SEALED_CLASSES.allowedInSource(source);
 191     }
 192 
 193     protected AbstractEndPosTable newEndPosTable(boolean keepEndPositions) {
 194         return  keepEndPositions
 195                 ? new SimpleEndPosTable(this)
 196                 : new EmptyEndPosTable(this);
 197     }
 198 
 199     protected DocCommentTable newDocCommentTable(boolean keepDocComments, ParserFactory fac) {
 200         return keepDocComments ? new LazyDocCommentTable(fac) : null;
 201     }
 202 
 203     /** Switch: should we fold strings?
 204      */
 205     boolean allowStringFolding;
 206 
 207     /** Switch: should we keep docComments?
 208      */
 209     boolean keepDocComments;
 210 
 211     /** Switch: should we keep line table?
 212      */
 213     boolean keepLineMap;
 214 
 215     /** Switch: is "this" allowed as an identifier?
 216      * This is needed to parse receiver types.
 217      */
 218     boolean allowThisIdent;
 219 
 220     /** Switch: is yield statement allowed in this source level?
 221      */
 222     boolean allowYieldStatement;
 223 
 224     /** Switch: are records allowed in this source level?
 225      */
 226     boolean allowRecords;
 227 
 228     /** Switch: are sealed types allowed in this source level?
 229      */
 230     boolean allowSealedTypes;
 231 
 232     /** The type of the method receiver, as specified by a first "this" parameter.
 233      */
 234     JCVariableDecl receiverParam;
 235 
 236     /** When terms are parsed, the mode determines which is expected:
 237      *     mode = EXPR        : an expression
 238      *     mode = TYPE        : a type
 239      *     mode = NOPARAMS    : no parameters allowed for type
 240      *     mode = TYPEARG     : type argument
 241      *     mode |= NOLAMBDA   : lambdas are not allowed
 242      */
 243     protected static final int EXPR = 0x1;
 244     protected static final int TYPE = 0x2;
 245     protected static final int NOPARAMS = 0x4;
 246     protected static final int TYPEARG = 0x8;
 247     protected static final int DIAMOND = 0x10;
 248     protected static final int NOLAMBDA = 0x20;
 249 
 250     protected void selectExprMode() {
 251         mode = (mode & NOLAMBDA) | EXPR;
 252     }
 253 
 254     protected void selectTypeMode() {
 255         mode = (mode & NOLAMBDA) | TYPE;
 256     }
 257 
 258     /** The current mode.
 259      */
 260     protected int mode = 0;
 261 
 262     /** The mode of the term that was parsed last.
 263      */
 264     protected int lastmode = 0;
 265 
 266     /* ---------- token management -------------- */
 267 
 268     protected Token token;
 269 
 270     public Token token() {
 271         return token;
 272     }
 273 
 274     public void nextToken() {
 275         S.nextToken();
 276         token = S.token();
 277     }
 278 
 279     protected boolean peekToken(Predicate<TokenKind> tk) {
 280         return peekToken(0, tk);
 281     }
 282 
 283     protected boolean peekToken(int lookahead, Predicate<TokenKind> tk) {
 284         return tk.test(S.token(lookahead + 1).kind);
 285     }
 286 
 287     protected boolean peekToken(Predicate<TokenKind> tk1, Predicate<TokenKind> tk2) {
 288         return peekToken(0, tk1, tk2);
 289     }
 290 
 291     protected boolean peekToken(int lookahead, Predicate<TokenKind> tk1, Predicate<TokenKind> tk2) {
 292         return tk1.test(S.token(lookahead + 1).kind) &&
 293                 tk2.test(S.token(lookahead + 2).kind);
 294     }
 295 
 296     protected boolean peekToken(Predicate<TokenKind> tk1, Predicate<TokenKind> tk2, Predicate<TokenKind> tk3) {
 297         return peekToken(0, tk1, tk2, tk3);
 298     }
 299 
 300     protected boolean peekToken(int lookahead, Predicate<TokenKind> tk1, Predicate<TokenKind> tk2, Predicate<TokenKind> tk3) {
 301         return tk1.test(S.token(lookahead + 1).kind) &&
 302                 tk2.test(S.token(lookahead + 2).kind) &&
 303                 tk3.test(S.token(lookahead + 3).kind);
 304     }
 305 
 306     @SuppressWarnings("unchecked")
 307     protected boolean peekToken(Predicate<TokenKind>... kinds) {
 308         return peekToken(0, kinds);
 309     }
 310 
 311     @SuppressWarnings("unchecked")
 312     protected boolean peekToken(int lookahead, Predicate<TokenKind>... kinds) {
 313         for (Predicate<TokenKind> kind : kinds) {
 314             if (!kind.test(S.token(++lookahead).kind)) {
 315                 return false;
 316             }
 317         }
 318         return true;
 319     }
 320 
 321     /* ---------- error recovery -------------- */
 322 
 323     private JCErroneous errorTree;
 324 
 325     /** Skip forward until a suitable stop token is found.
 326      */
 327     protected void skip(boolean stopAtImport, boolean stopAtMemberDecl, boolean stopAtIdentifier, boolean stopAtStatement) {
 328          while (true) {
 329              switch (token.kind) {
 330                 case SEMI:
 331                     nextToken();
 332                     return;
 333                 case PUBLIC:
 334                 case FINAL:
 335                 case ABSTRACT:
 336                 case MONKEYS_AT:
 337                 case EOF:
 338                 case CLASS:
 339                 case INTERFACE:
 340                 case ENUM:
 341                     return;
 342                 case IMPORT:
 343                     if (stopAtImport)
 344                         return;
 345                     break;
 346                 case LBRACE:
 347                 case RBRACE:
 348                 case PRIVATE:
 349                 case PROTECTED:
 350                 case STATIC:
 351                 case TRANSIENT:
 352                 case NATIVE:
 353                 case VOLATILE:
 354                 case SYNCHRONIZED:
 355                 case STRICTFP:
 356                 case LT:
 357                 case BYTE:
 358                 case SHORT:
 359                 case CHAR:
 360                 case INT:
 361                 case LONG:
 362                 case FLOAT:
 363                 case DOUBLE:
 364                 case BOOLEAN:
 365                 case VOID:
 366                     if (stopAtMemberDecl)
 367                         return;
 368                     break;
 369                 case UNDERSCORE:
 370                 case IDENTIFIER:
 371                    if (stopAtIdentifier)
 372                         return;
 373                     break;
 374                 case CASE:
 375                 case DEFAULT:
 376                 case IF:
 377                 case FOR:
 378                 case WHILE:
 379                 case DO:
 380                 case TRY:
 381                 case SWITCH:
 382                 case RETURN:
 383                 case THROW:
 384                 case BREAK:
 385                 case CONTINUE:
 386                 case ELSE:
 387                 case FINALLY:
 388                 case CATCH:
 389                 case THIS:
 390                 case SUPER:
 391                 case NEW:
 392                     if (stopAtStatement)
 393                         return;
 394                     break;
 395                 case ASSERT:
 396                     if (stopAtStatement)
 397                         return;
 398                     break;
 399             }
 400             nextToken();
 401         }
 402     }
 403 
 404     protected JCErroneous syntaxError(int pos, Error errorKey) {
 405         return syntaxError(pos, List.nil(), errorKey);
 406     }
 407 
 408     protected JCErroneous syntaxError(int pos, List<JCTree> errs, Error errorKey) {
 409         setErrorEndPos(pos);
 410         JCErroneous err = F.at(pos).Erroneous(errs);
 411         reportSyntaxError(err, errorKey);
 412         if (errs != null) {
 413             JCTree last = errs.last();
 414             if (last != null)
 415                 storeEnd(last, pos);
 416         }
 417         return toP(err);
 418     }
 419 
 420     private static final int RECOVERY_THRESHOLD = 50;
 421     private int errorPos = Position.NOPOS;
 422     private int count = 0;
 423 
 424     /**
 425      * Report a syntax using the given the position parameter and arguments,
 426      * unless one was already reported at the same position.
 427      */
 428     protected void reportSyntaxError(int pos, Error errorKey) {
 429         JCDiagnostic.DiagnosticPosition diag = new JCDiagnostic.SimpleDiagnosticPosition(pos);
 430         reportSyntaxError(diag, errorKey);
 431     }
 432 
 433     /**
 434      * Report a syntax error using the given DiagnosticPosition object and
 435      * arguments, unless one was already reported at the same position.
 436      */
 437     protected void reportSyntaxError(JCDiagnostic.DiagnosticPosition diagPos, Error errorKey) {
 438         int pos = diagPos.getPreferredPosition();
 439         if (pos > S.errPos() || pos == Position.NOPOS) {
 440             if (token.kind == EOF) {
 441                 log.error(DiagnosticFlag.SYNTAX, diagPos, Errors.PrematureEof);
 442             } else {
 443                 log.error(DiagnosticFlag.SYNTAX, diagPos, errorKey);
 444             }
 445         }
 446         S.errPos(pos);
 447         if (token.pos == errorPos && token.kind != EOF) {
 448             //check for a possible infinite loop in parsing:
 449             Assert.check(count++ < RECOVERY_THRESHOLD);
 450         } else {
 451             count = 0;
 452             errorPos = token.pos;
 453         }
 454     }
 455 
 456     /** If next input token matches given token, skip it, otherwise report
 457      *  an error.
 458      */
 459     public void accept(TokenKind tk) {
 460         accept(tk, Errors::Expected);
 461     }
 462 
 463     /** If next input token matches given token, skip it, otherwise report
 464      *  an error.
 465      */
 466     public void accept(TokenKind tk, Function<TokenKind, Error> errorProvider) {
 467         if (token.kind == tk) {
 468             nextToken();
 469         } else {
 470             setErrorEndPos(token.pos);
 471             reportSyntaxError(S.prevToken().endPos, errorProvider.apply(tk));
 472         }
 473     }
 474 
 475     /** Report an illegal start of expression/type error at given position.
 476      */
 477     JCExpression illegal(int pos) {
 478         setErrorEndPos(pos);
 479         if ((mode & EXPR) != 0)
 480             return syntaxError(pos, Errors.IllegalStartOfExpr);
 481         else
 482             return syntaxError(pos, Errors.IllegalStartOfType);
 483 
 484     }
 485 
 486     /** Report an illegal start of expression/type error at current position.
 487      */
 488     JCExpression illegal() {
 489         return illegal(token.pos);
 490     }
 491 
 492     /** Diagnose a modifier flag from the set, if any. */
 493     protected void checkNoMods(long mods) {
 494         checkNoMods(token.pos, mods);
 495     }
 496 
 497     protected void checkNoMods(int pos, long mods) {
 498         if (mods != 0) {
 499             long lowestMod = mods & -mods;
 500             log.error(DiagnosticFlag.SYNTAX, pos, Errors.ModNotAllowedHere(Flags.asFlagSet(lowestMod)));
 501         }
 502     }
 503 
 504 /* ---------- doc comments --------- */
 505 
 506     /** A table to store all documentation comments
 507      *  indexed by the tree nodes they refer to.
 508      *  defined only if option flag keepDocComment is set.
 509      */
 510     private final DocCommentTable docComments;
 511 
 512     /** Make an entry into docComments hashtable,
 513      *  provided flag keepDocComments is set and given doc comment is non-null.
 514      *  @param tree   The tree to be used as index in the hashtable
 515      *  @param dc     The doc comment to associate with the tree, or null.
 516      */
 517     protected void attach(JCTree tree, Comment dc) {
 518         if (keepDocComments && dc != null) {
 519 //          System.out.println("doc comment = ");System.out.println(dc);//DEBUG
 520             docComments.putComment(tree, dc);
 521         }
 522     }
 523 
 524 /* -------- source positions ------- */
 525 
 526     protected void setErrorEndPos(int errPos) {
 527         endPosTable.setErrorEndPos(errPos);
 528     }
 529 
 530     protected void storeEnd(JCTree tree, int endpos) {
 531         endPosTable.storeEnd(tree, endpos);
 532     }
 533 
 534     protected <T extends JCTree> T to(T t) {
 535         return endPosTable.to(t);
 536     }
 537 
 538     protected <T extends JCTree> T toP(T t) {
 539         return endPosTable.toP(t);
 540     }
 541 
 542     /** Get the start position for a tree node.  The start position is
 543      * defined to be the position of the first character of the first
 544      * token of the node's source text.
 545      * @param tree  The tree node
 546      */
 547     public int getStartPos(JCTree tree) {
 548         return TreeInfo.getStartPos(tree);
 549     }
 550 
 551     /**
 552      * Get the end position for a tree node.  The end position is
 553      * defined to be the position of the last character of the last
 554      * token of the node's source text.  Returns Position.NOPOS if end
 555      * positions are not generated or the position is otherwise not
 556      * found.
 557      * @param tree  The tree node
 558      */
 559     public int getEndPos(JCTree tree) {
 560         return endPosTable.getEndPos(tree);
 561     }
 562 
 563 
 564 
 565 /* ---------- parsing -------------- */
 566 
 567     /**
 568      * Ident = IDENTIFIER
 569      */
 570     public Name ident() {
 571         return ident(false);
 572     }
 573 
 574     protected Name ident(boolean allowClass) {
 575         if (token.kind == IDENTIFIER) {
 576             Name name = token.name();
 577             nextToken();
 578             return name;
 579         } else if (token.kind == ASSERT) {
 580             log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.AssertAsIdentifier);
 581             nextToken();
 582             return names.error;
 583         } else if (token.kind == ENUM) {
 584             log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.EnumAsIdentifier);
 585             nextToken();
 586             return names.error;
 587         } else if (token.kind == THIS) {
 588             if (allowThisIdent) {
 589                 // Make sure we're using a supported source version.
 590                 checkSourceLevel(Feature.TYPE_ANNOTATIONS);
 591                 Name name = token.name();
 592                 nextToken();
 593                 return name;
 594             } else {
 595                 log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.ThisAsIdentifier);
 596                 nextToken();
 597                 return names.error;
 598             }
 599         } else if (token.kind == UNDERSCORE) {
 600             if (Feature.UNDERSCORE_IDENTIFIER.allowedInSource(source)) {
 601                 log.warning(token.pos, Warnings.UnderscoreAsIdentifier);
 602             } else {
 603                 log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.UnderscoreAsIdentifier);
 604             }
 605             Name name = token.name();
 606             nextToken();
 607             return name;
 608         } else {
 609             accept(IDENTIFIER);
 610             if (allowClass && token.kind == CLASS) {
 611                 nextToken();
 612                 return names._class;
 613             }
 614             return names.error;
 615         }
 616     }
 617 
 618     /**
 619      * Qualident = Ident { DOT [Annotations] Ident }
 620      */
 621     public JCExpression qualident(boolean allowAnnos) {
 622         JCExpression t = toP(F.at(token.pos).Ident(ident()));
 623         while (token.kind == DOT) {
 624             int pos = token.pos;
 625             nextToken();
 626             List<JCAnnotation> tyannos = null;
 627             if (allowAnnos) {
 628                 tyannos = typeAnnotationsOpt();
 629             }
 630             t = toP(F.at(pos).Select(t, ident()));
 631             if (tyannos != null && tyannos.nonEmpty()) {
 632                 t = toP(F.at(tyannos.head.pos).AnnotatedType(tyannos, t));
 633             }
 634         }
 635         return t;
 636     }
 637 
 638     JCExpression literal(Name prefix) {
 639         return literal(prefix, token.pos);
 640     }
 641 
 642     /**
 643      * Literal =
 644      *     INTLITERAL
 645      *   | LONGLITERAL
 646      *   | FLOATLITERAL
 647      *   | DOUBLELITERAL
 648      *   | CHARLITERAL
 649      *   | STRINGLITERAL
 650      *   | TRUE
 651      *   | FALSE
 652      *   | NULL
 653      */
 654     JCExpression literal(Name prefix, int pos) {
 655         JCExpression t = errorTree;
 656         switch (token.kind) {
 657         case INTLITERAL:
 658             try {
 659                 t = F.at(pos).Literal(
 660                     TypeTag.INT,
 661                     Convert.string2int(strval(prefix), token.radix()));
 662             } catch (NumberFormatException ex) {
 663                 log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.IntNumberTooLarge(strval(prefix)));
 664             }
 665             break;
 666         case LONGLITERAL:
 667             try {
 668                 t = F.at(pos).Literal(
 669                     TypeTag.LONG,
 670                     Long.valueOf(Convert.string2long(strval(prefix), token.radix())));
 671             } catch (NumberFormatException ex) {
 672                 log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.IntNumberTooLarge(strval(prefix)));
 673             }
 674             break;
 675         case FLOATLITERAL: {
 676             String proper = token.radix() == 16 ?
 677                     ("0x"+ token.stringVal()) :
 678                     token.stringVal();
 679             Float n;
 680             try {
 681                 n = Float.valueOf(proper);
 682             } catch (NumberFormatException ex) {
 683                 // error already reported in scanner
 684                 n = Float.NaN;
 685             }
 686             if (n.floatValue() == 0.0f && !isZero(proper))
 687                 log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.FpNumberTooSmall);
 688             else if (n.floatValue() == Float.POSITIVE_INFINITY)
 689                 log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.FpNumberTooLarge);
 690             else
 691                 t = F.at(pos).Literal(TypeTag.FLOAT, n);
 692             break;
 693         }
 694         case DOUBLELITERAL: {
 695             String proper = token.radix() == 16 ?
 696                     ("0x"+ token.stringVal()) :
 697                     token.stringVal();
 698             Double n;
 699             try {
 700                 n = Double.valueOf(proper);
 701             } catch (NumberFormatException ex) {
 702                 // error already reported in scanner
 703                 n = Double.NaN;
 704             }
 705             if (n.doubleValue() == 0.0d && !isZero(proper))
 706                 log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.FpNumberTooSmall);
 707             else if (n.doubleValue() == Double.POSITIVE_INFINITY)
 708                 log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.FpNumberTooLarge);
 709             else
 710                 t = F.at(pos).Literal(TypeTag.DOUBLE, n);
 711             break;
 712         }
 713         case CHARLITERAL:
 714             t = F.at(pos).Literal(
 715                 TypeTag.CHAR,
 716                 token.stringVal().charAt(0) + 0);
 717             break;
 718         case STRINGLITERAL:
 719             t = F.at(pos).Literal(
 720                 TypeTag.CLASS,
 721                 token.stringVal());
 722             break;
 723         case TRUE: case FALSE:
 724             t = F.at(pos).Literal(
 725                 TypeTag.BOOLEAN,
 726                 (token.kind == TRUE ? 1 : 0));
 727             break;
 728         case NULL:
 729             t = F.at(pos).Literal(
 730                 TypeTag.BOT,
 731                 null);
 732             break;
 733         default:
 734             Assert.error();
 735         }
 736         if (t == errorTree)
 737             t = F.at(pos).Erroneous();
 738         storeEnd(t, token.endPos);
 739         nextToken();
 740         return t;
 741     }
 742     //where
 743         boolean isZero(String s) {
 744             char[] cs = s.toCharArray();
 745             int base = ((cs.length > 1 && Character.toLowerCase(cs[1]) == 'x') ? 16 : 10);
 746             int i = ((base==16) ? 2 : 0);
 747             while (i < cs.length && (cs[i] == '0' || cs[i] == '.')) i++;
 748             return !(i < cs.length && (Character.digit(cs[i], base) > 0));
 749         }
 750 
 751         String strval(Name prefix) {
 752             String s = token.stringVal();
 753             return prefix.isEmpty() ? s : prefix + s;
 754         }
 755 
 756     /** terms can be either expressions or types.
 757      */
 758     public JCExpression parseExpression() {
 759         return term(EXPR);
 760     }
 761 
 762 
 763     /** parses patterns.
 764      */
 765 
 766     public JCPattern parsePattern(int pos, JCModifiers mods, JCExpression parsedType, boolean inInstanceOf) {
 767         JCPattern pattern;
 768         if (token.kind == LPAREN && parsedType == null) {
 769             int startPos = token.pos;
 770             accept(LPAREN);
 771             JCPattern p = parsePattern(token.pos, null, null, false);
 772             accept(RPAREN);
 773             pattern = toP(F.at(startPos).ParenthesizedPattern(p));
 774         } else {
 775             mods = mods != null ? mods : optFinal(0);
 776             JCExpression e = parsedType == null ? term(TYPE | NOLAMBDA) : parsedType;
 777             JCVariableDecl var = toP(F.at(token.pos).VarDef(mods, ident(), e, null));
 778             pattern = toP(F.at(pos).BindingPattern(var));
 779         }
 780         if (!inInstanceOf && token.kind == AMPAMP) {
 781             checkSourceLevel(Feature.PATTERN_SWITCH);
 782             nextToken();
 783             JCExpression guard = term(EXPR | NOLAMBDA);
 784             pattern = F.at(pos).GuardPattern(pattern, guard);
 785         }
 786         return pattern;
 787     }
 788 
 789     /**
 790      * parses (optional) type annotations followed by a type. If the
 791      * annotations are present before the type and are not consumed during array
 792      * parsing, this method returns a {@link JCAnnotatedType} consisting of
 793      * these annotations and the underlying type. Otherwise, it returns the
 794      * underlying type.
 795      *
 796      * <p>
 797      *
 798      * Note that this method sets {@code mode} to {@code TYPE} first, before
 799      * parsing annotations.
 800      */
 801     public JCExpression parseType() {
 802         return parseType(false);
 803     }
 804 
 805     public JCExpression parseType(boolean allowVar) {
 806         List<JCAnnotation> annotations = typeAnnotationsOpt();
 807         return parseType(allowVar, annotations);
 808     }
 809 
 810     public JCExpression parseType(boolean allowVar, List<JCAnnotation> annotations) {
 811         JCExpression result = unannotatedType(allowVar);
 812 
 813         if (annotations.nonEmpty()) {
 814             result = insertAnnotationsToMostInner(result, annotations, false);
 815         }
 816 
 817         return result;
 818     }
 819 
 820     public JCExpression unannotatedType(boolean allowVar) {
 821         JCExpression result = term(TYPE);
 822         Name restrictedTypeName = restrictedTypeName(result, !allowVar);
 823 
 824         if (restrictedTypeName != null && (!allowVar || restrictedTypeName != names.var)) {
 825             syntaxError(result.pos, Errors.RestrictedTypeNotAllowedHere(restrictedTypeName));
 826         }
 827 
 828         return result;
 829     }
 830 
 831 
 832 
 833     protected JCExpression term(int newmode) {
 834         int prevmode = mode;
 835         mode = newmode;
 836         JCExpression t = term();
 837         lastmode = mode;
 838         mode = prevmode;
 839         return t;
 840     }
 841 
 842     /**
 843      *  {@literal
 844      *  Expression = Expression1 [ExpressionRest]
 845      *  ExpressionRest = [AssignmentOperator Expression1]
 846      *  AssignmentOperator = "=" | "+=" | "-=" | "*=" | "/=" |
 847      *                       "&=" | "|=" | "^=" |
 848      *                       "%=" | "<<=" | ">>=" | ">>>="
 849      *  Type = Type1
 850      *  TypeNoParams = TypeNoParams1
 851      *  StatementExpression = Expression
 852      *  ConstantExpression = Expression
 853      *  }
 854      */
 855     JCExpression term() {
 856         JCExpression t = term1();
 857         if ((mode & EXPR) != 0 &&
 858             (token.kind == EQ || PLUSEQ.compareTo(token.kind) <= 0 && token.kind.compareTo(GTGTGTEQ) <= 0))
 859             return termRest(t);
 860         else
 861             return t;
 862     }
 863 
 864     JCExpression termRest(JCExpression t) {
 865         switch (token.kind) {
 866         case EQ: {
 867             int pos = token.pos;
 868             nextToken();
 869             selectExprMode();
 870             JCExpression t1 = term();
 871             return toP(F.at(pos).Assign(t, t1));
 872         }
 873         case PLUSEQ:
 874         case SUBEQ:
 875         case STAREQ:
 876         case SLASHEQ:
 877         case PERCENTEQ:
 878         case AMPEQ:
 879         case BAREQ:
 880         case CARETEQ:
 881         case LTLTEQ:
 882         case GTGTEQ:
 883         case GTGTGTEQ:
 884             int pos = token.pos;
 885             TokenKind tk = token.kind;
 886             nextToken();
 887             selectExprMode();
 888             JCExpression t1 = term();
 889             return F.at(pos).Assignop(optag(tk), t, t1);
 890         default:
 891             return t;
 892         }
 893     }
 894 
 895     /** Expression1   = Expression2 [Expression1Rest]
 896      *  Type1         = Type2
 897      *  TypeNoParams1 = TypeNoParams2
 898      */
 899     JCExpression term1() {
 900         JCExpression t = term2();
 901         if ((mode & EXPR) != 0 && token.kind == QUES) {
 902             selectExprMode();
 903             return term1Rest(t);
 904         } else {
 905             return t;
 906         }
 907     }
 908 
 909     /** Expression1Rest = ["?" Expression ":" Expression1]
 910      */
 911     JCExpression term1Rest(JCExpression t) {
 912         if (token.kind == QUES) {
 913             int pos = token.pos;
 914             nextToken();
 915             JCExpression t1 = term();
 916             accept(COLON);
 917             JCExpression t2 = term1();
 918             return F.at(pos).Conditional(t, t1, t2);
 919         } else {
 920             return t;
 921         }
 922     }
 923 
 924     /** Expression2   = Expression3 [Expression2Rest]
 925      *  Type2         = Type3
 926      *  TypeNoParams2 = TypeNoParams3
 927      */
 928     JCExpression term2() {
 929         JCExpression t = term3();
 930         if ((mode & EXPR) != 0 && prec(token.kind) >= TreeInfo.orPrec) {
 931             selectExprMode();
 932             return term2Rest(t, TreeInfo.orPrec);
 933         } else {
 934             return t;
 935         }
 936     }
 937 
 938     /*  Expression2Rest = {infixop Expression3}
 939      *                  | Expression3 instanceof Type
 940      *                  | Expression3 instanceof Pattern
 941      *  infixop         = "||"
 942      *                  | "&&"
 943      *                  | "|"
 944      *                  | "^"
 945      *                  | "&"
 946      *                  | "==" | "!="
 947      *                  | "<" | ">" | "<=" | ">="
 948      *                  | "<<" | ">>" | ">>>"
 949      *                  | "+" | "-"
 950      *                  | "*" | "/" | "%"
 951      */
 952     JCExpression term2Rest(JCExpression t, int minprec) {
 953         JCExpression[] odStack = newOdStack();
 954         Token[] opStack = newOpStack();
 955 
 956         // optimization, was odStack = new Tree[...]; opStack = new Tree[...];
 957         int top = 0;
 958         odStack[0] = t;
 959         int startPos = token.pos;
 960         Token topOp = Tokens.DUMMY;
 961         while (prec(token.kind) >= minprec) {
 962             opStack[top] = topOp;
 963 
 964             if (token.kind == INSTANCEOF) {
 965                 int pos = token.pos;
 966                 nextToken();
 967                 JCTree pattern;
 968                 if (token.kind == LPAREN) {
 969                     checkSourceLevel(token.pos, Feature.PATTERN_SWITCH);
 970                     pattern = parsePattern(token.pos, null, null, true);
 971                 } else {
 972                     int patternPos = token.pos;
 973                     JCModifiers mods = optFinal(0);
 974                     int typePos = token.pos;
 975                     JCExpression type = unannotatedType(false);
 976                     if (token.kind == IDENTIFIER) {
 977                         checkSourceLevel(token.pos, Feature.PATTERN_MATCHING_IN_INSTANCEOF);
 978                         pattern = parsePattern(patternPos, mods, type, true);
 979                     } else {
 980                         checkNoMods(typePos, mods.flags & ~Flags.DEPRECATED);
 981                         if (mods.annotations.nonEmpty()) {
 982                             checkSourceLevel(mods.annotations.head.pos, Feature.TYPE_ANNOTATIONS);
 983                             List<JCAnnotation> typeAnnos =
 984                                     mods.annotations
 985                                         .map(decl -> {
 986                                             JCAnnotation typeAnno = F.at(decl.pos)
 987                                                                      .TypeAnnotation(decl.annotationType,
 988                                                                                       decl.args);
 989                                             endPosTable.replaceTree(decl, typeAnno);
 990                                             return typeAnno;
 991                                         });
 992                             type = insertAnnotationsToMostInner(type, typeAnnos, false);
 993                         }
 994                         pattern = type;
 995                     }
 996                 }
 997                 odStack[top] = F.at(pos).TypeTest(odStack[top], pattern);
 998             } else {
 999                 topOp = token;
1000                 nextToken();
1001                 top++;
1002                 odStack[top] = term3();
1003             }
1004             while (top > 0 && prec(topOp.kind) >= prec(token.kind)) {
1005                 odStack[top - 1] = F.at(topOp.pos).Binary(optag(topOp.kind), odStack[top - 1], odStack[top]);
1006                 top--;
1007                 topOp = opStack[top];
1008             }
1009         }
1010         Assert.check(top == 0);
1011         t = odStack[0];
1012 
1013         if (t.hasTag(JCTree.Tag.PLUS)) {
1014             t = foldStrings(t);
1015         }
1016 
1017         odStackSupply.add(odStack);
1018         opStackSupply.add(opStack);
1019         return t;
1020     }
1021     //where
1022         /** If tree is a concatenation of string literals, replace it
1023          *  by a single literal representing the concatenated string.
1024          */
1025         protected JCExpression foldStrings(JCExpression tree) {
1026             if (!allowStringFolding)
1027                 return tree;
1028             ListBuffer<JCExpression> opStack = new ListBuffer<>();
1029             ListBuffer<JCLiteral> litBuf = new ListBuffer<>();
1030             boolean needsFolding = false;
1031             JCExpression curr = tree;
1032             while (true) {
1033                 if (curr.hasTag(JCTree.Tag.PLUS)) {
1034                     JCBinary op = (JCBinary)curr;
1035                     needsFolding |= foldIfNeeded(op.rhs, litBuf, opStack, false);
1036                     curr = op.lhs;
1037                 } else {
1038                     needsFolding |= foldIfNeeded(curr, litBuf, opStack, true);
1039                     break; //last one!
1040                 }
1041             }
1042             if (needsFolding) {
1043                 List<JCExpression> ops = opStack.toList();
1044                 JCExpression res = ops.head;
1045                 for (JCExpression op : ops.tail) {
1046                     res = F.at(op.getStartPosition()).Binary(optag(TokenKind.PLUS), res, op);
1047                     storeEnd(res, getEndPos(op));
1048                 }
1049                 return res;
1050             } else {
1051                 return tree;
1052             }
1053         }
1054 
1055         private boolean foldIfNeeded(JCExpression tree, ListBuffer<JCLiteral> litBuf,
1056                                                 ListBuffer<JCExpression> opStack, boolean last) {
1057             JCLiteral str = stringLiteral(tree);
1058             if (str != null) {
1059                 litBuf.prepend(str);
1060                 return last && merge(litBuf, opStack);
1061             } else {
1062                 boolean res = merge(litBuf, opStack);
1063                 litBuf.clear();
1064                 opStack.prepend(tree);
1065                 return res;
1066             }
1067         }
1068 
1069         boolean merge(ListBuffer<JCLiteral> litBuf, ListBuffer<JCExpression> opStack) {
1070             if (litBuf.isEmpty()) {
1071                 return false;
1072             } else if (litBuf.size() == 1) {
1073                 opStack.prepend(litBuf.first());
1074                 return false;
1075             } else {
1076                 JCExpression t = F.at(litBuf.first().getStartPosition()).Literal(TypeTag.CLASS,
1077                         litBuf.stream().map(lit -> (String)lit.getValue()).collect(Collectors.joining()));
1078                 storeEnd(t, litBuf.last().getEndPosition(endPosTable));
1079                 opStack.prepend(t);
1080                 return true;
1081             }
1082         }
1083 
1084         private JCLiteral stringLiteral(JCTree tree) {
1085             if (tree.hasTag(LITERAL)) {
1086                 JCLiteral lit = (JCLiteral)tree;
1087                 if (lit.typetag == TypeTag.CLASS) {
1088                     return lit;
1089                 }
1090             }
1091             return null;
1092         }
1093 
1094 
1095         /** optimization: To save allocating a new operand/operator stack
1096          *  for every binary operation, we use supplys.
1097          */
1098         ArrayList<JCExpression[]> odStackSupply = new ArrayList<>();
1099         ArrayList<Token[]> opStackSupply = new ArrayList<>();
1100 
1101         private JCExpression[] newOdStack() {
1102             if (odStackSupply.isEmpty())
1103                 return new JCExpression[infixPrecedenceLevels + 1];
1104             return odStackSupply.remove(odStackSupply.size() - 1);
1105         }
1106 
1107         private Token[] newOpStack() {
1108             if (opStackSupply.isEmpty())
1109                 return new Token[infixPrecedenceLevels + 1];
1110             return opStackSupply.remove(opStackSupply.size() - 1);
1111         }
1112 
1113     /**
1114      *  Expression3    = PrefixOp Expression3
1115      *                 | "(" Expr | TypeNoParams ")" Expression3
1116      *                 | Primary {Selector} {PostfixOp}
1117      *
1118      *  {@literal
1119      *  Primary        = "(" Expression ")"
1120      *                 | Literal
1121      *                 | [TypeArguments] THIS [Arguments]
1122      *                 | [TypeArguments] SUPER SuperSuffix
1123      *                 | NEW [TypeArguments] Creator
1124      *                 | "(" Arguments ")" "->" ( Expression | Block )
1125      *                 | Ident "->" ( Expression | Block )
1126      *                 | [Annotations] Ident { "." [Annotations] Ident }
1127      *                 | Expression3 MemberReferenceSuffix
1128      *                   [ [Annotations] "[" ( "]" BracketsOpt "." CLASS | Expression "]" )
1129      *                   | Arguments
1130      *                   | "." ( CLASS | THIS | [TypeArguments] SUPER Arguments | NEW [TypeArguments] InnerCreator )
1131      *                   ]
1132      *                 | BasicType BracketsOpt "." CLASS
1133      *  }
1134      *
1135      *  PrefixOp       = "++" | "--" | "!" | "~" | "+" | "-"
1136      *  PostfixOp      = "++" | "--"
1137      *  Type3          = Ident { "." Ident } [TypeArguments] {TypeSelector} BracketsOpt
1138      *                 | BasicType
1139      *  TypeNoParams3  = Ident { "." Ident } BracketsOpt
1140      *  Selector       = "." [TypeArguments] Ident [Arguments]
1141      *                 | "." THIS
1142      *                 | "." [TypeArguments] SUPER SuperSuffix
1143      *                 | "." NEW [TypeArguments] InnerCreator
1144      *                 | "[" Expression "]"
1145      *  TypeSelector   = "." Ident [TypeArguments]
1146      *  SuperSuffix    = Arguments | "." Ident [Arguments]
1147      */
1148     protected JCExpression term3() {
1149         int pos = token.pos;
1150         JCExpression t;
1151         List<JCExpression> typeArgs = typeArgumentsOpt(EXPR);
1152         switch (token.kind) {
1153         case QUES:
1154             if ((mode & TYPE) != 0 && (mode & (TYPEARG|NOPARAMS)) == TYPEARG) {
1155                 selectTypeMode();
1156                 return typeArgument();
1157             } else
1158                 return illegal();
1159         case PLUSPLUS: case SUBSUB: case BANG: case TILDE: case PLUS: case SUB:
1160             if (typeArgs == null && (mode & EXPR) != 0) {
1161                 TokenKind tk = token.kind;
1162                 nextToken();
1163                 selectExprMode();
1164                 if (tk == SUB &&
1165                     (token.kind == INTLITERAL || token.kind == LONGLITERAL) &&
1166                     token.radix() == 10) {
1167                     selectExprMode();
1168                     t = literal(names.hyphen, pos);
1169                 } else {
1170                     t = term3();
1171                     return F.at(pos).Unary(unoptag(tk), t);
1172                 }
1173             } else return illegal();
1174             break;
1175         case LPAREN:
1176             if (typeArgs == null && (mode & EXPR) != 0) {
1177                 ParensResult pres = analyzeParens();
1178                 switch (pres) {
1179                     case CAST:
1180                        accept(LPAREN);
1181                        selectTypeMode();
1182                        int pos1 = pos;
1183                        List<JCExpression> targets = List.of(t = parseType());
1184                        while (token.kind == AMP) {
1185                            checkSourceLevel(Feature.INTERSECTION_TYPES_IN_CAST);
1186                            accept(AMP);
1187                            targets = targets.prepend(parseType());
1188                        }
1189                        if (targets.length() > 1) {
1190                            t = toP(F.at(pos1).TypeIntersection(targets.reverse()));
1191                        }
1192                        accept(RPAREN);
1193                        selectExprMode();
1194                        JCExpression t1 = term3();
1195                        return F.at(pos).TypeCast(t, t1);
1196                     case IMPLICIT_LAMBDA:
1197                     case EXPLICIT_LAMBDA:
1198                         t = lambdaExpressionOrStatement(true, pres == ParensResult.EXPLICIT_LAMBDA, pos);
1199                         break;
1200                     default: //PARENS
1201                         accept(LPAREN);
1202                         selectExprMode();
1203                         t = termRest(term1Rest(term2Rest(term3(), TreeInfo.orPrec)));
1204                         accept(RPAREN);
1205                         t = toP(F.at(pos).Parens(t));
1206                         break;
1207                 }
1208             } else {
1209                 return illegal();
1210             }
1211             break;
1212         case THIS:
1213             if ((mode & EXPR) != 0) {
1214                 selectExprMode();
1215                 t = to(F.at(pos).Ident(names._this));
1216                 nextToken();
1217                 if (typeArgs == null)
1218                     t = argumentsOpt(null, t);
1219                 else
1220                     t = arguments(typeArgs, t);
1221                 typeArgs = null;
1222             } else return illegal();
1223             break;
1224         case SUPER:
1225             if ((mode & EXPR) != 0) {
1226                 selectExprMode();
1227                 t = to(F.at(pos).Ident(names._super));
1228                 t = superSuffix(typeArgs, t);
1229                 typeArgs = null;
1230             } else return illegal();
1231             break;
1232         case INTLITERAL: case LONGLITERAL: case FLOATLITERAL: case DOUBLELITERAL:
1233         case CHARLITERAL: case STRINGLITERAL:
1234         case TRUE: case FALSE: case NULL:
1235             if (typeArgs == null && (mode & EXPR) != 0) {
1236                 selectExprMode();
1237                 t = literal(names.empty);
1238             } else return illegal();
1239             break;
1240         case NEW:
1241             if (typeArgs != null) return illegal();
1242             if ((mode & EXPR) != 0) {
1243                 selectExprMode();
1244                 nextToken();
1245                 if (token.kind == LT) typeArgs = typeArguments(false);
1246                 t = creator(pos, typeArgs);
1247                 typeArgs = null;
1248             } else return illegal();
1249             break;
1250         case MONKEYS_AT:
1251             // Only annotated cast types and method references are valid
1252             List<JCAnnotation> typeAnnos = typeAnnotationsOpt();
1253             if (typeAnnos.isEmpty()) {
1254                 // else there would be no '@'
1255                 throw new AssertionError("Expected type annotations, but found none!");
1256             }
1257 
1258             JCExpression expr = term3();
1259 
1260             if ((mode & TYPE) == 0) {
1261                 // Type annotations on class literals no longer legal
1262                 switch (expr.getTag()) {
1263                 case REFERENCE: {
1264                     JCMemberReference mref = (JCMemberReference) expr;
1265                     mref.expr = toP(F.at(pos).AnnotatedType(typeAnnos, mref.expr));
1266                     t = mref;
1267                     break;
1268                 }
1269                 case SELECT: {
1270                     JCFieldAccess sel = (JCFieldAccess) expr;
1271 
1272                     if (sel.name != names._class) {
1273                         return illegal();
1274                     } else {
1275                         log.error(token.pos, Errors.NoAnnotationsOnDotClass);
1276                         return expr;
1277                     }
1278                 }
1279                 default:
1280                     return illegal(typeAnnos.head.pos);
1281                 }
1282 
1283             } else {
1284                 // Type annotations targeting a cast
1285                 t = insertAnnotationsToMostInner(expr, typeAnnos, false);
1286             }
1287             break;
1288         case UNDERSCORE: case IDENTIFIER: case ASSERT: case ENUM:
1289             if (typeArgs != null) return illegal();
1290             if ((mode & EXPR) != 0 && (mode & NOLAMBDA) == 0 && peekToken(ARROW)) {
1291                 t = lambdaExpressionOrStatement(false, false, pos);
1292             } else {
1293                 t = toP(F.at(token.pos).Ident(ident()));
1294                 loop: while (true) {
1295                     pos = token.pos;
1296                     final List<JCAnnotation> annos = typeAnnotationsOpt();
1297 
1298                     // need to report an error later if LBRACKET is for array
1299                     // index access rather than array creation level
1300                     if (!annos.isEmpty() && token.kind != LBRACKET && token.kind != ELLIPSIS)
1301                         return illegal(annos.head.pos);
1302 
1303                     switch (token.kind) {
1304                     case LBRACKET:
1305                         nextToken();
1306                         if (token.kind == RBRACKET) {
1307                             nextToken();
1308                             t = bracketsOpt(t);
1309                             t = toP(F.at(pos).TypeArray(t));
1310                             if (annos.nonEmpty()) {
1311                                 t = toP(F.at(pos).AnnotatedType(annos, t));
1312                             }
1313                             t = bracketsSuffix(t);
1314                         } else {
1315                             if ((mode & EXPR) != 0) {
1316                                 selectExprMode();
1317                                 JCExpression t1 = term();
1318                                 if (!annos.isEmpty()) t = illegal(annos.head.pos);
1319                                 t = to(F.at(pos).Indexed(t, t1));
1320                             }
1321                             accept(RBRACKET);
1322                         }
1323                         break loop;
1324                     case LPAREN:
1325                         if ((mode & EXPR) != 0) {
1326                             selectExprMode();
1327                             t = arguments(typeArgs, t);
1328                             if (!annos.isEmpty()) t = illegal(annos.head.pos);
1329                             typeArgs = null;
1330                         }
1331                         break loop;
1332                     case DOT:
1333                         nextToken();
1334                         if (token.kind == TokenKind.IDENTIFIER && typeArgs != null) {
1335                             return illegal();
1336                         }
1337                         int oldmode = mode;
1338                         mode &= ~NOPARAMS;
1339                         typeArgs = typeArgumentsOpt(EXPR);
1340                         mode = oldmode;
1341                         if ((mode & EXPR) != 0) {
1342                             switch (token.kind) {
1343                             case CLASS:
1344                                 if (typeArgs != null) return illegal();
1345                                 selectExprMode();
1346                                 t = to(F.at(pos).Select(t, names._class));
1347                                 nextToken();
1348                                 break loop;
1349                             case THIS:
1350                                 if (typeArgs != null) return illegal();
1351                                 selectExprMode();
1352                                 t = to(F.at(pos).Select(t, names._this));
1353                                 nextToken();
1354                                 break loop;
1355                             case SUPER:
1356                                 selectExprMode();
1357                                 t = to(F.at(pos).Select(t, names._super));
1358                                 t = superSuffix(typeArgs, t);
1359                                 typeArgs = null;
1360                                 break loop;
1361                             case NEW:
1362                                 if (typeArgs != null) return illegal();
1363                                 selectExprMode();
1364                                 int pos1 = token.pos;
1365                                 nextToken();
1366                                 if (token.kind == LT) typeArgs = typeArguments(false);
1367                                 t = innerCreator(pos1, typeArgs, t);
1368                                 typeArgs = null;
1369                                 break loop;
1370                             }
1371                         }
1372 
1373                         List<JCAnnotation> tyannos = null;
1374                         if ((mode & TYPE) != 0 && token.kind == MONKEYS_AT) {
1375                             tyannos = typeAnnotationsOpt();
1376                         }
1377                         // typeArgs saved for next loop iteration.
1378                         t = toP(F.at(pos).Select(t, ident()));
1379                         if (token.pos <= endPosTable.errorEndPos &&
1380                             token.kind == MONKEYS_AT) {
1381                             //error recovery, case like:
1382                             //int i = expr.<missing-ident>
1383                             //@Deprecated
1384                             if (typeArgs != null) illegal();
1385                             return toP(t);
1386                         }
1387                         if (tyannos != null && tyannos.nonEmpty()) {
1388                             t = toP(F.at(tyannos.head.pos).AnnotatedType(tyannos, t));
1389                         }
1390                         break;
1391                     case ELLIPSIS:
1392                         if (this.permitTypeAnnotationsPushBack) {
1393                             this.typeAnnotationsPushedBack = annos;
1394                         } else if (annos.nonEmpty()) {
1395                             // Don't return here -- error recovery attempt
1396                             illegal(annos.head.pos);
1397                         }
1398                         break loop;
1399                     case LT:
1400                         if ((mode & TYPE) == 0 && isUnboundMemberRef()) {
1401                             //this is an unbound method reference whose qualifier
1402                             //is a generic type i.e. A<S>::m
1403                             int pos1 = token.pos;
1404                             accept(LT);
1405                             ListBuffer<JCExpression> args = new ListBuffer<>();
1406                             args.append(typeArgument());
1407                             while (token.kind == COMMA) {
1408                                 nextToken();
1409                                 args.append(typeArgument());
1410                             }
1411                             accept(GT);
1412                             t = toP(F.at(pos1).TypeApply(t, args.toList()));
1413                             while (token.kind == DOT) {
1414                                 nextToken();
1415                                 selectTypeMode();
1416                                 t = toP(F.at(token.pos).Select(t, ident()));
1417                                 t = typeArgumentsOpt(t);
1418                             }
1419                             t = bracketsOpt(t);
1420                             if (token.kind != COLCOL) {
1421                                 //method reference expected here
1422                                 t = illegal();
1423                             }
1424                             selectExprMode();
1425                             return term3Rest(t, typeArgs);
1426                         }
1427                         break loop;
1428                     default:
1429                         break loop;
1430                     }
1431                 }
1432             }
1433             if (typeArgs != null) illegal();
1434             t = typeArgumentsOpt(t);
1435             break;
1436         case BYTE: case SHORT: case CHAR: case INT: case LONG: case FLOAT:
1437         case DOUBLE: case BOOLEAN:
1438             if (typeArgs != null) illegal();
1439             t = bracketsSuffix(bracketsOpt(basicType()));
1440             break;
1441         case VOID:
1442             if (typeArgs != null) illegal();
1443             if ((mode & EXPR) != 0) {
1444                 nextToken();
1445                 if (token.kind == DOT) {
1446                     JCPrimitiveTypeTree ti = toP(F.at(pos).TypeIdent(TypeTag.VOID));
1447                     t = bracketsSuffix(ti);
1448                 } else {
1449                     return illegal(pos);
1450                 }
1451             } else {
1452                 // Support the corner case of myMethodHandle.<void>invoke() by passing
1453                 // a void type (like other primitive types) to the next phase.
1454                 // The error will be reported in Attr.attribTypes or Attr.visitApply.
1455                 JCPrimitiveTypeTree ti = to(F.at(pos).TypeIdent(TypeTag.VOID));
1456                 nextToken();
1457                 return ti;
1458                 //return illegal();
1459             }
1460             break;
1461         case SWITCH:
1462             checkSourceLevel(Feature.SWITCH_EXPRESSION);
1463             allowYieldStatement = true;
1464             int switchPos = token.pos;
1465             nextToken();
1466             JCExpression selector = parExpression();
1467             accept(LBRACE);
1468             ListBuffer<JCCase> cases = new ListBuffer<>();
1469             while (true) {
1470                 pos = token.pos;
1471                 switch (token.kind) {
1472                 case CASE:
1473                 case DEFAULT:
1474                     cases.appendList(switchExpressionStatementGroup());
1475                     break;
1476                 case RBRACE: case EOF:
1477                     JCSwitchExpression e = to(F.at(switchPos).SwitchExpression(selector,
1478                                                                                cases.toList()));
1479                     e.endpos = token.pos;
1480                     accept(RBRACE);
1481                     return e;
1482                 default:
1483                     nextToken(); // to ensure progress
1484                     syntaxError(pos, Errors.Expected3(CASE, DEFAULT, RBRACE));
1485                 }
1486             }
1487         default:
1488             return illegal();
1489         }
1490         return term3Rest(t, typeArgs);
1491     }
1492 
1493     private List<JCCase> switchExpressionStatementGroup() {
1494         ListBuffer<JCCase> caseExprs = new ListBuffer<>();
1495         int casePos = token.pos;
1496         ListBuffer<JCCaseLabel> pats = new ListBuffer<>();
1497 
1498         if (token.kind == DEFAULT) {
1499             nextToken();
1500             pats.append(toP(F.at(casePos).DefaultCaseLabel()));
1501         } else {
1502             accept(CASE);
1503             while (true) {
1504                 JCCaseLabel label = parseCaseLabel();
1505                 pats.append(label);
1506                 if (token.kind != COMMA) break;
1507                 checkSourceLevel(Feature.SWITCH_MULTIPLE_CASE_LABELS);
1508                 nextToken();
1509             };
1510         }
1511         List<JCStatement> stats = null;
1512         JCTree body = null;
1513         CaseTree.CaseKind kind;
1514         switch (token.kind) {
1515             case ARROW:
1516                 checkSourceLevel(Feature.SWITCH_RULE);
1517                 nextToken();
1518                 if (token.kind == TokenKind.THROW || token.kind == TokenKind.LBRACE) {
1519                     stats = List.of(parseStatement());
1520                     body = stats.head;
1521                     kind = JCCase.RULE;
1522                 } else {
1523                     JCExpression value = parseExpression();
1524                     stats = List.of(to(F.at(value).Yield(value)));
1525                     body = value;
1526                     kind = JCCase.RULE;
1527                     accept(SEMI);
1528                 }
1529                 break;
1530             default:
1531                 accept(COLON, tk -> Errors.Expected2(COLON, ARROW));
1532                 stats = blockStatements();
1533                 kind = JCCase.STATEMENT;
1534                 break;
1535         }
1536         caseExprs.append(toP(F.at(casePos).Case(kind, pats.toList(), stats, body)));
1537         return caseExprs.toList();
1538     }
1539 
1540     JCExpression term3Rest(JCExpression t, List<JCExpression> typeArgs) {
1541         if (typeArgs != null) illegal();
1542         while (true) {
1543             int pos1 = token.pos;
1544             final List<JCAnnotation> annos = typeAnnotationsOpt();
1545 
1546             if (token.kind == LBRACKET) {
1547                 nextToken();
1548                 if ((mode & TYPE) != 0) {
1549                     int oldmode = mode;
1550                     selectTypeMode();
1551                     if (token.kind == RBRACKET) {
1552                         nextToken();
1553                         t = bracketsOpt(t);
1554                         t = toP(F.at(pos1).TypeArray(t));
1555                         if (token.kind == COLCOL) {
1556                             selectExprMode();
1557                             continue;
1558                         }
1559                         if (annos.nonEmpty()) {
1560                             t = toP(F.at(pos1).AnnotatedType(annos, t));
1561                         }
1562                         return t;
1563                     }
1564                     mode = oldmode;
1565                 }
1566                 if ((mode & EXPR) != 0) {
1567                     selectExprMode();
1568                     JCExpression t1 = term();
1569                     t = to(F.at(pos1).Indexed(t, t1));
1570                 }
1571                 accept(RBRACKET);
1572             } else if (token.kind == DOT) {
1573                 nextToken();
1574                 typeArgs = typeArgumentsOpt(EXPR);
1575                 if (token.kind == SUPER && (mode & EXPR) != 0) {
1576                     selectExprMode();
1577                     t = to(F.at(pos1).Select(t, names._super));
1578                     nextToken();
1579                     t = arguments(typeArgs, t);
1580                     typeArgs = null;
1581                 } else if (token.kind == NEW && (mode & EXPR) != 0) {
1582                     if (typeArgs != null) return illegal();
1583                     selectExprMode();
1584                     int pos2 = token.pos;
1585                     nextToken();
1586                     if (token.kind == LT) typeArgs = typeArguments(false);
1587                     t = innerCreator(pos2, typeArgs, t);
1588                     typeArgs = null;
1589                 } else {
1590                     List<JCAnnotation> tyannos = null;
1591                     if ((mode & TYPE) != 0 && token.kind == MONKEYS_AT) {
1592                         // is the mode check needed?
1593                         tyannos = typeAnnotationsOpt();
1594                     }
1595                     t = toP(F.at(pos1).Select(t, ident(true)));
1596                     if (token.pos <= endPosTable.errorEndPos &&
1597                         token.kind == MONKEYS_AT) {
1598                         //error recovery, case like:
1599                         //int i = expr.<missing-ident>
1600                         //@Deprecated
1601                         break;
1602                     }
1603                     if (tyannos != null && tyannos.nonEmpty()) {
1604                         t = toP(F.at(tyannos.head.pos).AnnotatedType(tyannos, t));
1605                     }
1606                     t = argumentsOpt(typeArgs, typeArgumentsOpt(t));
1607                     typeArgs = null;
1608                 }
1609             } else if ((mode & EXPR) != 0 && token.kind == COLCOL) {
1610                 selectExprMode();
1611                 if (typeArgs != null) return illegal();
1612                 accept(COLCOL);
1613                 t = memberReferenceSuffix(pos1, t);
1614             } else {
1615                 if (!annos.isEmpty()) {
1616                     if (permitTypeAnnotationsPushBack)
1617                         typeAnnotationsPushedBack = annos;
1618                     else
1619                         return illegal(annos.head.pos);
1620                 }
1621                 break;
1622             }
1623         }
1624         while ((token.kind == PLUSPLUS || token.kind == SUBSUB) && (mode & EXPR) != 0) {
1625             selectExprMode();
1626             t = to(F.at(token.pos).Unary(
1627                   token.kind == PLUSPLUS ? POSTINC : POSTDEC, t));
1628             nextToken();
1629         }
1630         return toP(t);
1631     }
1632 
1633     /**
1634      * If we see an identifier followed by a '&lt;' it could be an unbound
1635      * method reference or a binary expression. To disambiguate, look for a
1636      * matching '&gt;' and see if the subsequent terminal is either '.' or '::'.
1637      */
1638     @SuppressWarnings("fallthrough")
1639     boolean isUnboundMemberRef() {
1640         int pos = 0, depth = 0;
1641         outer: for (Token t = S.token(pos) ; ; t = S.token(++pos)) {
1642             switch (t.kind) {
1643                 case IDENTIFIER: case UNDERSCORE: case QUES: case EXTENDS: case SUPER:
1644                 case DOT: case RBRACKET: case LBRACKET: case COMMA:
1645                 case BYTE: case SHORT: case INT: case LONG: case FLOAT:
1646                 case DOUBLE: case BOOLEAN: case CHAR:
1647                 case MONKEYS_AT:
1648                     break;
1649 
1650                 case LPAREN:
1651                     // skip annotation values
1652                     int nesting = 0;
1653                     for (; ; pos++) {
1654                         TokenKind tk2 = S.token(pos).kind;
1655                         switch (tk2) {
1656                             case EOF:
1657                                 return false;
1658                             case LPAREN:
1659                                 nesting++;
1660                                 break;
1661                             case RPAREN:
1662                                 nesting--;
1663                                 if (nesting == 0) {
1664                                     continue outer;
1665                                 }
1666                                 break;
1667                         }
1668                     }
1669 
1670                 case LT:
1671                     depth++; break;
1672                 case GTGTGT:
1673                     depth--;
1674                 case GTGT:
1675                     depth--;
1676                 case GT:
1677                     depth--;
1678                     if (depth == 0) {
1679                         TokenKind nextKind = S.token(pos + 1).kind;
1680                         return
1681                             nextKind == TokenKind.DOT ||
1682                             nextKind == TokenKind.LBRACKET ||
1683                             nextKind == TokenKind.COLCOL;
1684                     }
1685                     break;
1686                 default:
1687                     return false;
1688             }
1689         }
1690     }
1691 
1692     /**
1693      * If we see an identifier followed by a '&lt;' it could be an unbound
1694      * method reference or a binary expression. To disambiguate, look for a
1695      * matching '&gt;' and see if the subsequent terminal is either '.' or '::'.
1696      */
1697     @SuppressWarnings("fallthrough")
1698     ParensResult analyzeParens() {
1699         int depth = 0;
1700         boolean type = false;
1701         ParensResult defaultResult = ParensResult.PARENS;
1702         outer: for (int lookahead = 0; ; lookahead++) {
1703             TokenKind tk = S.token(lookahead).kind;
1704             switch (tk) {
1705                 case COMMA:
1706                     type = true;
1707                 case EXTENDS: case SUPER: case DOT: case AMP:
1708                     //skip
1709                     break;
1710                 case QUES:
1711                     if (peekToken(lookahead, EXTENDS) ||
1712                             peekToken(lookahead, SUPER)) {
1713                         //wildcards
1714                         type = true;
1715                     }
1716                     break;
1717                 case BYTE: case SHORT: case INT: case LONG: case FLOAT:
1718                 case DOUBLE: case BOOLEAN: case CHAR: case VOID:
1719                     if (peekToken(lookahead, RPAREN)) {
1720                         //Type, ')' -> cast
1721                         return ParensResult.CAST;
1722                     } else if (peekToken(lookahead, LAX_IDENTIFIER)) {
1723                         //Type, Identifier/'_'/'assert'/'enum' -> explicit lambda
1724                         return ParensResult.EXPLICIT_LAMBDA;
1725                     }
1726                     break;
1727                 case LPAREN:
1728                     if (lookahead != 0) {
1729                         // '(' in a non-starting position -> parens
1730                         return ParensResult.PARENS;
1731                     } else if (peekToken(lookahead, RPAREN)) {
1732                         // '(', ')' -> explicit lambda
1733                         return ParensResult.EXPLICIT_LAMBDA;
1734                     }
1735                     break;
1736                 case RPAREN:
1737                     // if we have seen something that looks like a type,
1738                     // then it's a cast expression
1739                     if (type) return ParensResult.CAST;
1740                     // otherwise, disambiguate cast vs. parenthesized expression
1741                     // based on subsequent token.
1742                     switch (S.token(lookahead + 1).kind) {
1743                         /*case PLUSPLUS: case SUBSUB: */
1744                         case BANG: case TILDE:
1745                         case LPAREN: case THIS: case SUPER:
1746                         case INTLITERAL: case LONGLITERAL: case FLOATLITERAL:
1747                         case DOUBLELITERAL: case CHARLITERAL: case STRINGLITERAL:
1748                         case TRUE: case FALSE: case NULL:
1749                         case NEW: case IDENTIFIER: case ASSERT: case ENUM: case UNDERSCORE:
1750                         case SWITCH:
1751                         case BYTE: case SHORT: case CHAR: case INT:
1752                         case LONG: case FLOAT: case DOUBLE: case BOOLEAN: case VOID:
1753                             return ParensResult.CAST;
1754                         default:
1755                             return defaultResult;
1756                     }
1757                 case UNDERSCORE:
1758                 case ASSERT:
1759                 case ENUM:
1760                 case IDENTIFIER:
1761                     if (peekToken(lookahead, LAX_IDENTIFIER)) {
1762                         // Identifier, Identifier/'_'/'assert'/'enum' -> explicit lambda
1763                         return ParensResult.EXPLICIT_LAMBDA;
1764                     } else if (peekToken(lookahead, RPAREN, ARROW)) {
1765                         // Identifier, ')' '->' -> implicit lambda
1766                         return (mode & NOLAMBDA) == 0 ? ParensResult.IMPLICIT_LAMBDA
1767                                                       : ParensResult.PARENS;
1768                     } else if (depth == 0 && peekToken(lookahead, COMMA)) {
1769                         defaultResult = ParensResult.IMPLICIT_LAMBDA;
1770                     }
1771                     type = false;
1772                     break;
1773                 case FINAL:
1774                 case ELLIPSIS:
1775                     //those can only appear in explicit lambdas
1776                     return ParensResult.EXPLICIT_LAMBDA;
1777                 case MONKEYS_AT:
1778                     type = true;
1779                     lookahead = skipAnnotation(lookahead);
1780                     break;
1781                 case LBRACKET:
1782                     if (peekToken(lookahead, RBRACKET, LAX_IDENTIFIER)) {
1783                         // '[', ']', Identifier/'_'/'assert'/'enum' -> explicit lambda
1784                         return ParensResult.EXPLICIT_LAMBDA;
1785                     } else if (peekToken(lookahead, RBRACKET, RPAREN) ||
1786                             peekToken(lookahead, RBRACKET, AMP)) {
1787                         // '[', ']', ')' -> cast
1788                         // '[', ']', '&' -> cast (intersection type)
1789                         return ParensResult.CAST;
1790                     } else if (peekToken(lookahead, RBRACKET)) {
1791                         //consume the ']' and skip
1792                         type = true;
1793                         lookahead++;
1794                         break;
1795                     } else {
1796                         return ParensResult.PARENS;
1797                     }
1798                 case LT:
1799                     depth++; break;
1800                 case GTGTGT:
1801                     depth--;
1802                 case GTGT:
1803                     depth--;
1804                 case GT:
1805                     depth--;
1806                     if (depth == 0) {
1807                         if (peekToken(lookahead, RPAREN) ||
1808                                 peekToken(lookahead, AMP)) {
1809                             // '>', ')' -> cast
1810                             // '>', '&' -> cast
1811                             return ParensResult.CAST;
1812                         } else if (peekToken(lookahead, LAX_IDENTIFIER, COMMA) ||
1813                                 peekToken(lookahead, LAX_IDENTIFIER, RPAREN, ARROW) ||
1814                                 peekToken(lookahead, ELLIPSIS)) {
1815                             // '>', Identifier/'_'/'assert'/'enum', ',' -> explicit lambda
1816                             // '>', Identifier/'_'/'assert'/'enum', ')', '->' -> explicit lambda
1817                             // '>', '...' -> explicit lambda
1818                             return ParensResult.EXPLICIT_LAMBDA;
1819                         }
1820                         //it looks a type, but could still be (i) a cast to generic type,
1821                         //(ii) an unbound method reference or (iii) an explicit lambda
1822                         type = true;
1823                         break;
1824                     } else if (depth < 0) {
1825                         //unbalanced '<', '>' - not a generic type
1826                         return ParensResult.PARENS;
1827                     }
1828                     break;
1829                 default:
1830                     //this includes EOF
1831                     return defaultResult;
1832             }
1833         }
1834     }
1835 
1836     private int skipAnnotation(int lookahead) {
1837         lookahead += 1; //skip '@'
1838         while (peekToken(lookahead, DOT)) {
1839             lookahead += 2;
1840         }
1841         if (peekToken(lookahead, LPAREN)) {
1842             lookahead++;
1843             //skip annotation values
1844             int nesting = 0;
1845             for (; ; lookahead++) {
1846                 TokenKind tk2 = S.token(lookahead).kind;
1847                 switch (tk2) {
1848                     case EOF:
1849                         return lookahead;
1850                     case LPAREN:
1851                         nesting++;
1852                         break;
1853                     case RPAREN:
1854                         nesting--;
1855                         if (nesting == 0) {
1856                             return lookahead;
1857                         }
1858                     break;
1859                 }
1860             }
1861         }
1862         return lookahead;
1863     }
1864 
1865     /** Accepts all identifier-like tokens */
1866     protected Predicate<TokenKind> LAX_IDENTIFIER = t -> t == IDENTIFIER || t == UNDERSCORE || t == ASSERT || t == ENUM;
1867 
1868     enum ParensResult {
1869         CAST,
1870         EXPLICIT_LAMBDA,
1871         IMPLICIT_LAMBDA,
1872         PARENS
1873     }
1874 
1875     JCExpression lambdaExpressionOrStatement(boolean hasParens, boolean explicitParams, int pos) {
1876         List<JCVariableDecl> params = explicitParams ?
1877                 formalParameters(true, false) :
1878                 implicitParameters(hasParens);
1879         if (explicitParams) {
1880             LambdaClassifier lambdaClassifier = new LambdaClassifier();
1881             for (JCVariableDecl param: params) {
1882                 Name restrictedTypeName;
1883                 if (param.vartype != null &&
1884                         (restrictedTypeName = restrictedTypeName(param.vartype, false)) != null &&
1885                         param.vartype.hasTag(TYPEARRAY)) {
1886                     log.error(DiagnosticFlag.SYNTAX, param.pos,
1887                         Feature.VAR_SYNTAX_IMPLICIT_LAMBDAS.allowedInSource(source)
1888                             ? Errors.RestrictedTypeNotAllowedArray(restrictedTypeName) : Errors.RestrictedTypeNotAllowedHere(restrictedTypeName));
1889                 }
1890                 lambdaClassifier.addParameter(param);
1891                 if (lambdaClassifier.result() == LambdaParameterKind.ERROR) {
1892                     break;
1893                 }
1894             }
1895             if (lambdaClassifier.diagFragment != null) {
1896                 log.error(DiagnosticFlag.SYNTAX, pos, Errors.InvalidLambdaParameterDeclaration(lambdaClassifier.diagFragment));
1897             }
1898             for (JCVariableDecl param: params) {
1899                 if (param.vartype != null
1900                         && restrictedTypeName(param.vartype, true) != null) {
1901                     checkSourceLevel(param.pos, Feature.VAR_SYNTAX_IMPLICIT_LAMBDAS);
1902                     param.startPos = TreeInfo.getStartPos(param.vartype);
1903                     param.vartype = null;
1904                 }
1905             }
1906         }
1907         return lambdaExpressionOrStatementRest(params, pos);
1908     }
1909 
1910     enum LambdaParameterKind {
1911         VAR(0),
1912         EXPLICIT(1),
1913         IMPLICIT(2),
1914         ERROR(-1);
1915 
1916         private final int index;
1917 
1918         LambdaParameterKind(int index) {
1919             this.index = index;
1920         }
1921     }
1922 
1923     private static final Fragment[][] decisionTable = new Fragment[][] {
1924         /*              VAR                              EXPLICIT                         IMPLICIT  */
1925         /* VAR      */ {null,                            VarAndExplicitNotAllowed,        VarAndImplicitNotAllowed},
1926         /* EXPLICIT */ {VarAndExplicitNotAllowed,        null,                            ImplicitAndExplicitNotAllowed},
1927         /* IMPLICIT */ {VarAndImplicitNotAllowed,        ImplicitAndExplicitNotAllowed,   null},
1928     };
1929 
1930     class LambdaClassifier {
1931 
1932         LambdaParameterKind kind;
1933         Fragment diagFragment;
1934         List<JCVariableDecl> params;
1935 
1936         void addParameter(JCVariableDecl param) {
1937             if (param.vartype != null && param.name != names.empty) {
1938                 if (restrictedTypeName(param.vartype, false) != null) {
1939                     reduce(LambdaParameterKind.VAR);
1940                 } else {
1941                     reduce(LambdaParameterKind.EXPLICIT);
1942                 }
1943             }
1944             if (param.vartype == null && param.name != names.empty ||
1945                 param.vartype != null && param.name == names.empty) {
1946                 reduce(LambdaParameterKind.IMPLICIT);
1947             }
1948         }
1949 
1950         private void reduce(LambdaParameterKind newKind) {
1951             if (kind == null) {
1952                 kind = newKind;
1953             } else if (kind != newKind && kind != LambdaParameterKind.ERROR) {
1954                 LambdaParameterKind currentKind = kind;
1955                 kind = LambdaParameterKind.ERROR;
1956                 boolean varIndex = currentKind.index == LambdaParameterKind.VAR.index ||
1957                         newKind.index == LambdaParameterKind.VAR.index;
1958                 diagFragment = Feature.VAR_SYNTAX_IMPLICIT_LAMBDAS.allowedInSource(source) || !varIndex ?
1959                         decisionTable[currentKind.index][newKind.index] : null;
1960             }
1961         }
1962 
1963         LambdaParameterKind result() {
1964             return kind;
1965         }
1966     }
1967 
1968     JCExpression lambdaExpressionOrStatementRest(List<JCVariableDecl> args, int pos) {
1969         checkSourceLevel(Feature.LAMBDA);
1970         accept(ARROW);
1971 
1972         return token.kind == LBRACE ?
1973             lambdaStatement(args, pos, token.pos) :
1974             lambdaExpression(args, pos);
1975     }
1976 
1977     JCExpression lambdaStatement(List<JCVariableDecl> args, int pos, int pos2) {
1978         JCBlock block = block(pos2, 0);
1979         return toP(F.at(pos).Lambda(args, block));
1980     }
1981 
1982     JCExpression lambdaExpression(List<JCVariableDecl> args, int pos) {
1983         JCTree expr = parseExpression();
1984         return toP(F.at(pos).Lambda(args, expr));
1985     }
1986 
1987     /** SuperSuffix = Arguments | "." [TypeArguments] Ident [Arguments]
1988      */
1989     JCExpression superSuffix(List<JCExpression> typeArgs, JCExpression t) {
1990         nextToken();
1991         if (token.kind == LPAREN || typeArgs != null) {
1992             t = arguments(typeArgs, t);
1993         } else if (token.kind == COLCOL) {
1994             if (typeArgs != null) return illegal();
1995             t = memberReferenceSuffix(t);
1996         } else {
1997             int pos = token.pos;
1998             accept(DOT);
1999             typeArgs = (token.kind == LT) ? typeArguments(false) : null;
2000             t = toP(F.at(pos).Select(t, ident()));
2001             t = argumentsOpt(typeArgs, t);
2002         }
2003         return t;
2004     }
2005 
2006     /** BasicType = BYTE | SHORT | CHAR | INT | LONG | FLOAT | DOUBLE | BOOLEAN
2007      */
2008     JCPrimitiveTypeTree basicType() {
2009         JCPrimitiveTypeTree t = to(F.at(token.pos).TypeIdent(typetag(token.kind)));
2010         nextToken();
2011         return t;
2012     }
2013 
2014     /** ArgumentsOpt = [ Arguments ]
2015      */
2016     JCExpression argumentsOpt(List<JCExpression> typeArgs, JCExpression t) {
2017         if ((mode & EXPR) != 0 && token.kind == LPAREN || typeArgs != null) {
2018             selectExprMode();
2019             return arguments(typeArgs, t);
2020         } else {
2021             return t;
2022         }
2023     }
2024 
2025     /** Arguments = "(" [Expression { COMMA Expression }] ")"
2026      */
2027     List<JCExpression> arguments() {
2028         ListBuffer<JCExpression> args = new ListBuffer<>();
2029         if (token.kind == LPAREN) {
2030             nextToken();
2031             if (token.kind != RPAREN) {
2032                 args.append(parseExpression());
2033                 while (token.kind == COMMA) {
2034                     nextToken();
2035                     args.append(parseExpression());
2036                 }
2037             }
2038             accept(RPAREN);
2039         } else {
2040             syntaxError(token.pos, Errors.Expected(LPAREN));
2041         }
2042         return args.toList();
2043     }
2044 
2045     JCExpression arguments(List<JCExpression> typeArgs, JCExpression t) {
2046         int pos = token.pos;
2047         List<JCExpression> args = arguments();
2048         JCExpression mi = F.at(pos).Apply(typeArgs, t, args);
2049         if (t.hasTag(IDENT) && isInvalidUnqualifiedMethodIdentifier(((JCIdent) t).pos,
2050                                                                     ((JCIdent) t).name)) {
2051             log.error(DiagnosticFlag.SYNTAX, t, Errors.InvalidYield);
2052             mi = F.Erroneous(List.of(mi));
2053         }
2054         return toP(mi);
2055     }
2056 
2057     boolean isInvalidUnqualifiedMethodIdentifier(int pos, Name name) {
2058         if (name == names.yield) {
2059             if (allowYieldStatement) {
2060                 return true;
2061             } else {
2062                 log.warning(pos, Warnings.InvalidYield);
2063             }
2064         }
2065         return false;
2066     }
2067 
2068     /**  TypeArgumentsOpt = [ TypeArguments ]
2069      */
2070     JCExpression typeArgumentsOpt(JCExpression t) {
2071         if (token.kind == LT &&
2072             (mode & TYPE) != 0 &&
2073             (mode & NOPARAMS) == 0) {
2074             selectTypeMode();
2075             return typeArguments(t, false);
2076         } else {
2077             return t;
2078         }
2079     }
2080     List<JCExpression> typeArgumentsOpt() {
2081         return typeArgumentsOpt(TYPE);
2082     }
2083 
2084     List<JCExpression> typeArgumentsOpt(int useMode) {
2085         if (token.kind == LT) {
2086             if ((mode & useMode) == 0 ||
2087                 (mode & NOPARAMS) != 0) {
2088                 illegal();
2089             }
2090             mode = useMode;
2091             return typeArguments(false);
2092         }
2093         return null;
2094     }
2095 
2096     /**
2097      *  {@literal
2098      *  TypeArguments  = "<" TypeArgument {"," TypeArgument} ">"
2099      *  }
2100      */
2101     List<JCExpression> typeArguments(boolean diamondAllowed) {
2102         if (token.kind == LT) {
2103             nextToken();
2104             if (token.kind == GT && diamondAllowed) {
2105                 checkSourceLevel(Feature.DIAMOND);
2106                 mode |= DIAMOND;
2107                 nextToken();
2108                 return List.nil();
2109             } else {
2110                 ListBuffer<JCExpression> args = new ListBuffer<>();
2111                 args.append(((mode & EXPR) == 0) ? typeArgument() : parseType());
2112                 while (token.kind == COMMA) {
2113                     nextToken();
2114                     args.append(((mode & EXPR) == 0) ? typeArgument() : parseType());
2115                 }
2116                 switch (token.kind) {
2117 
2118                 case GTGTGTEQ: case GTGTEQ: case GTEQ:
2119                 case GTGTGT: case GTGT:
2120                     token = S.split();
2121                     break;
2122                 case GT:
2123                     nextToken();
2124                     break;
2125                 default:
2126                     args.append(syntaxError(token.pos, Errors.Expected(GT)));
2127                     break;
2128                 }
2129                 return args.toList();
2130             }
2131         } else {
2132             return List.of(syntaxError(token.pos, Errors.Expected(LT)));
2133         }
2134     }
2135 
2136     /**
2137      *  {@literal
2138      *  TypeArgument = Type
2139      *               | [Annotations] "?"
2140      *               | [Annotations] "?" EXTENDS Type {"&" Type}
2141      *               | [Annotations] "?" SUPER Type
2142      *  }
2143      */
2144     JCExpression typeArgument() {
2145         List<JCAnnotation> annotations = typeAnnotationsOpt();
2146         if (token.kind != QUES) return parseType(false, annotations);
2147         int pos = token.pos;
2148         nextToken();
2149         JCExpression result;
2150         if (token.kind == EXTENDS) {
2151             TypeBoundKind t = to(F.at(pos).TypeBoundKind(BoundKind.EXTENDS));
2152             nextToken();
2153             JCExpression bound = parseType();
2154             result = F.at(pos).Wildcard(t, bound);
2155         } else if (token.kind == SUPER) {
2156             TypeBoundKind t = to(F.at(pos).TypeBoundKind(BoundKind.SUPER));
2157             nextToken();
2158             JCExpression bound = parseType();
2159             result = F.at(pos).Wildcard(t, bound);
2160         } else if (LAX_IDENTIFIER.test(token.kind)) {
2161             //error recovery
2162             TypeBoundKind t = F.at(Position.NOPOS).TypeBoundKind(BoundKind.UNBOUND);
2163             JCExpression wc = toP(F.at(pos).Wildcard(t, null));
2164             JCIdent id = toP(F.at(token.pos).Ident(ident()));
2165             JCErroneous err = F.at(pos).Erroneous(List.<JCTree>of(wc, id));
2166             reportSyntaxError(err, Errors.Expected3(GT, EXTENDS, SUPER));
2167             result = err;
2168         } else {
2169             TypeBoundKind t = toP(F.at(pos).TypeBoundKind(BoundKind.UNBOUND));
2170             result = toP(F.at(pos).Wildcard(t, null));
2171         }
2172         if (!annotations.isEmpty()) {
2173             result = toP(F.at(annotations.head.pos).AnnotatedType(annotations,result));
2174         }
2175         return result;
2176     }
2177 
2178     JCTypeApply typeArguments(JCExpression t, boolean diamondAllowed) {
2179         int pos = token.pos;
2180         List<JCExpression> args = typeArguments(diamondAllowed);
2181         return toP(F.at(pos).TypeApply(t, args));
2182     }
2183 
2184     /**
2185      * BracketsOpt = { [Annotations] "[" "]" }*
2186      *
2187      * <p>
2188      *
2189      * <code>annotations</code> is the list of annotations targeting
2190      * the expression <code>t</code>.
2191      */
2192     private JCExpression bracketsOpt(JCExpression t,
2193             List<JCAnnotation> annotations) {
2194         List<JCAnnotation> nextLevelAnnotations = typeAnnotationsOpt();
2195 
2196         if (token.kind == LBRACKET) {
2197             int pos = token.pos;
2198             nextToken();
2199             t = bracketsOptCont(t, pos, nextLevelAnnotations);
2200         } else if (!nextLevelAnnotations.isEmpty()) {
2201             if (permitTypeAnnotationsPushBack) {
2202                 this.typeAnnotationsPushedBack = nextLevelAnnotations;
2203             } else {
2204                 return illegal(nextLevelAnnotations.head.pos);
2205             }
2206         }
2207 
2208         if (!annotations.isEmpty()) {
2209             t = toP(F.at(token.pos).AnnotatedType(annotations, t));
2210         }
2211         return t;
2212     }
2213 
2214     /** BracketsOpt = [ "[" "]" { [Annotations] "[" "]"} ]
2215      */
2216     private JCExpression bracketsOpt(JCExpression t) {
2217         return bracketsOpt(t, List.nil());
2218     }
2219 
2220     private JCExpression bracketsOptCont(JCExpression t, int pos,
2221             List<JCAnnotation> annotations) {
2222         accept(RBRACKET);
2223         t = bracketsOpt(t);
2224         t = toP(F.at(pos).TypeArray(t));
2225         if (annotations.nonEmpty()) {
2226             t = toP(F.at(pos).AnnotatedType(annotations, t));
2227         }
2228         return t;
2229     }
2230 
2231     /** BracketsSuffixExpr = "." CLASS
2232      *  BracketsSuffixType =
2233      */
2234     JCExpression bracketsSuffix(JCExpression t) {
2235         if ((mode & EXPR) != 0 && token.kind == DOT) {
2236             selectExprMode();
2237             int pos = token.pos;
2238             nextToken();
2239             accept(CLASS);
2240             if (token.pos == endPosTable.errorEndPos) {
2241                 // error recovery
2242                 Name name;
2243                 if (LAX_IDENTIFIER.test(token.kind)) {
2244                     name = token.name();
2245                     nextToken();
2246                 } else {
2247                     name = names.error;
2248                 }
2249                 t = F.at(pos).Erroneous(List.<JCTree>of(toP(F.at(pos).Select(t, name))));
2250             } else {
2251                 Tag tag = t.getTag();
2252                 // Type annotations are illegal on class literals. Annotated non array class literals
2253                 // are complained about directly in term3(), Here check for type annotations on dimensions
2254                 // taking care to handle some interior dimension(s) being annotated.
2255                 if ((tag == TYPEARRAY && TreeInfo.containsTypeAnnotation(t)) || tag == ANNOTATED_TYPE)
2256                     syntaxError(token.pos, Errors.NoAnnotationsOnDotClass);
2257                 t = toP(F.at(pos).Select(t, names._class));
2258             }
2259         } else if ((mode & TYPE) != 0) {
2260             if (token.kind != COLCOL) {
2261                 selectTypeMode();
2262             }
2263         } else if (token.kind != COLCOL) {
2264             syntaxError(token.pos, Errors.DotClassExpected);
2265         }
2266         return t;
2267     }
2268 
2269     /**
2270      * MemberReferenceSuffix = "::" [TypeArguments] Ident
2271      *                       | "::" [TypeArguments] "new"
2272      */
2273     JCExpression memberReferenceSuffix(JCExpression t) {
2274         int pos1 = token.pos;
2275         accept(COLCOL);
2276         return memberReferenceSuffix(pos1, t);
2277     }
2278 
2279     JCExpression memberReferenceSuffix(int pos1, JCExpression t) {
2280         checkSourceLevel(Feature.METHOD_REFERENCES);
2281         selectExprMode();
2282         List<JCExpression> typeArgs = null;
2283         if (token.kind == LT) {
2284             typeArgs = typeArguments(false);
2285         }
2286         Name refName;
2287         ReferenceMode refMode;
2288         if (token.kind == NEW) {
2289             refMode = ReferenceMode.NEW;
2290             refName = names.init;
2291             nextToken();
2292         } else {
2293             refMode = ReferenceMode.INVOKE;
2294             refName = ident();
2295         }
2296         return toP(F.at(t.getStartPosition()).Reference(refMode, refName, t, typeArgs));
2297     }
2298 
2299     /** Creator = [Annotations] Qualident [TypeArguments] ( ArrayCreatorRest | ClassCreatorRest )
2300      */
2301     JCExpression creator(int newpos, List<JCExpression> typeArgs) {
2302         List<JCAnnotation> newAnnotations = typeAnnotationsOpt();
2303 
2304         switch (token.kind) {
2305         case BYTE: case SHORT: case CHAR: case INT: case LONG: case FLOAT:
2306         case DOUBLE: case BOOLEAN:
2307             if (typeArgs == null) {
2308                 if (newAnnotations.isEmpty()) {
2309                     return arrayCreatorRest(newpos, basicType());
2310                 } else {
2311                     return arrayCreatorRest(newpos, toP(F.at(newAnnotations.head.pos).AnnotatedType(newAnnotations, basicType())));
2312                 }
2313             }
2314             break;
2315         default:
2316         }
2317         JCExpression t = qualident(true);
2318 
2319         int oldmode = mode;
2320         selectTypeMode();
2321         boolean diamondFound = false;
2322         int lastTypeargsPos = -1;
2323         if (token.kind == LT) {
2324             lastTypeargsPos = token.pos;
2325             t = typeArguments(t, true);
2326             diamondFound = (mode & DIAMOND) != 0;
2327         }
2328         while (token.kind == DOT) {
2329             if (diamondFound) {
2330                 //cannot select after a diamond
2331                 illegal();
2332             }
2333             int pos = token.pos;
2334             nextToken();
2335             List<JCAnnotation> tyannos = typeAnnotationsOpt();
2336             t = toP(F.at(pos).Select(t, ident()));
2337 
2338             if (tyannos != null && tyannos.nonEmpty()) {
2339                 t = toP(F.at(tyannos.head.pos).AnnotatedType(tyannos, t));
2340             }
2341 
2342             if (token.kind == LT) {
2343                 lastTypeargsPos = token.pos;
2344                 t = typeArguments(t, true);
2345                 diamondFound = (mode & DIAMOND) != 0;
2346             }
2347         }
2348         mode = oldmode;
2349         if (token.kind == LBRACKET || token.kind == MONKEYS_AT) {
2350             // handle type annotations for non primitive arrays
2351             if (newAnnotations.nonEmpty()) {
2352                 t = insertAnnotationsToMostInner(t, newAnnotations, false);
2353             }
2354 
2355             JCExpression e = arrayCreatorRest(newpos, t);
2356             if (diamondFound) {
2357                 reportSyntaxError(lastTypeargsPos, Errors.CannotCreateArrayWithDiamond);
2358                 return toP(F.at(newpos).Erroneous(List.of(e)));
2359             }
2360             else if (typeArgs != null) {
2361                 int pos = newpos;
2362                 if (!typeArgs.isEmpty() && typeArgs.head.pos != Position.NOPOS) {
2363                     // note: this should always happen but we should
2364                     // not rely on this as the parser is continuously
2365                     // modified to improve error recovery.
2366                     pos = typeArgs.head.pos;
2367                 }
2368                 setErrorEndPos(S.prevToken().endPos);
2369                 JCErroneous err = F.at(pos).Erroneous(typeArgs.prepend(e));
2370                 reportSyntaxError(err, Errors.CannotCreateArrayWithTypeArguments);
2371                 return toP(err);
2372             }
2373             return e;
2374         } else if (token.kind == LPAREN) {
2375             // handle type annotations for instantiations and anonymous classes
2376             if (newAnnotations.nonEmpty()) {
2377                 t = insertAnnotationsToMostInner(t, newAnnotations, false);
2378             }
2379             return classCreatorRest(newpos, null, typeArgs, t);
2380         } else {
2381             setErrorEndPos(token.pos);
2382             reportSyntaxError(token.pos, Errors.Expected2(LPAREN, LBRACKET));
2383             t = toP(F.at(newpos).NewClass(null, typeArgs, t, List.nil(), null));
2384             return toP(F.at(newpos).Erroneous(List.<JCTree>of(t)));
2385         }
2386     }
2387 
2388     /** InnerCreator = [Annotations] Ident [TypeArguments] ClassCreatorRest
2389      */
2390     JCExpression innerCreator(int newpos, List<JCExpression> typeArgs, JCExpression encl) {
2391         List<JCAnnotation> newAnnotations = typeAnnotationsOpt();
2392 
2393         JCExpression t = toP(F.at(token.pos).Ident(ident()));
2394 
2395         if (newAnnotations.nonEmpty()) {
2396             t = toP(F.at(newAnnotations.head.pos).AnnotatedType(newAnnotations, t));
2397         }
2398 
2399         if (token.kind == LT) {
2400             int oldmode = mode;
2401             t = typeArguments(t, true);
2402             mode = oldmode;
2403         }
2404         return classCreatorRest(newpos, encl, typeArgs, t);
2405     }
2406 
2407     /** ArrayCreatorRest = [Annotations] "[" ( "]" BracketsOpt ArrayInitializer
2408      *                         | Expression "]" {[Annotations]  "[" Expression "]"} BracketsOpt )
2409      */
2410     JCExpression arrayCreatorRest(int newpos, JCExpression elemtype) {
2411         List<JCAnnotation> annos = typeAnnotationsOpt();
2412 
2413         accept(LBRACKET);
2414         if (token.kind == RBRACKET) {
2415             accept(RBRACKET);
2416             elemtype = bracketsOpt(elemtype, annos);
2417             if (token.kind == LBRACE) {
2418                 JCNewArray na = (JCNewArray)arrayInitializer(newpos, elemtype);
2419                 if (annos.nonEmpty()) {
2420                     // when an array initializer is present then
2421                     // the parsed annotations should target the
2422                     // new array tree
2423                     // bracketsOpt inserts the annotation in
2424                     // elemtype, and it needs to be corrected
2425                     //
2426                     JCAnnotatedType annotated = (JCAnnotatedType)elemtype;
2427                     assert annotated.annotations == annos;
2428                     na.annotations = annotated.annotations;
2429                     na.elemtype = annotated.underlyingType;
2430                 }
2431                 return na;
2432             } else {
2433                 JCExpression t = toP(F.at(newpos).NewArray(elemtype, List.nil(), null));
2434                 return syntaxError(token.pos, List.of(t), Errors.ArrayDimensionMissing);
2435             }
2436         } else {
2437             ListBuffer<JCExpression> dims = new ListBuffer<>();
2438 
2439             // maintain array dimension type annotations
2440             ListBuffer<List<JCAnnotation>> dimAnnotations = new ListBuffer<>();
2441             dimAnnotations.append(annos);
2442 
2443             dims.append(parseExpression());
2444             accept(RBRACKET);
2445             while (token.kind == LBRACKET
2446                     || token.kind == MONKEYS_AT) {
2447                 List<JCAnnotation> maybeDimAnnos = typeAnnotationsOpt();
2448                 int pos = token.pos;
2449                 nextToken();
2450                 if (token.kind == RBRACKET) { // no dimension
2451                     elemtype = bracketsOptCont(elemtype, pos, maybeDimAnnos);
2452                 } else {
2453                     dimAnnotations.append(maybeDimAnnos);
2454                     dims.append(parseExpression());
2455                     accept(RBRACKET);
2456                 }
2457             }
2458 
2459             List<JCExpression> elems = null;
2460             int errpos = token.pos;
2461 
2462             if (token.kind == LBRACE) {
2463                 elems = arrayInitializerElements(newpos, elemtype);
2464             }
2465 
2466             JCNewArray na = toP(F.at(newpos).NewArray(elemtype, dims.toList(), elems));
2467             na.dimAnnotations = dimAnnotations.toList();
2468 
2469             if (elems != null) {
2470                 return syntaxError(errpos, List.of(na), Errors.IllegalArrayCreationBothDimensionAndInitialization);
2471             }
2472 
2473             return na;
2474         }
2475     }
2476 
2477     /** ClassCreatorRest = Arguments [ClassBody]
2478      */
2479     JCNewClass classCreatorRest(int newpos,
2480                                   JCExpression encl,
2481                                   List<JCExpression> typeArgs,
2482                                   JCExpression t)
2483     {
2484         List<JCExpression> args = arguments();
2485         JCClassDecl body = null;
2486         if (token.kind == LBRACE) {
2487             int pos = token.pos;
2488             List<JCTree> defs = classInterfaceOrRecordBody(names.empty, false, false);
2489             JCModifiers mods = F.at(Position.NOPOS).Modifiers(0);
2490             body = toP(F.at(pos).AnonymousClassDef(mods, defs));
2491         }
2492         return toP(F.at(newpos).NewClass(encl, typeArgs, t, args, body));
2493     }
2494 
2495     /** ArrayInitializer = "{" [VariableInitializer {"," VariableInitializer}] [","] "}"
2496      */
2497     JCExpression arrayInitializer(int newpos, JCExpression t) {
2498         List<JCExpression> elems = arrayInitializerElements(newpos, t);
2499         return toP(F.at(newpos).NewArray(t, List.nil(), elems));
2500     }
2501 
2502     List<JCExpression> arrayInitializerElements(int newpos, JCExpression t) {
2503         accept(LBRACE);
2504         ListBuffer<JCExpression> elems = new ListBuffer<>();
2505         if (token.kind == COMMA) {
2506             nextToken();
2507         } else if (token.kind != RBRACE) {
2508             elems.append(variableInitializer());
2509             while (token.kind == COMMA) {
2510                 nextToken();
2511                 if (token.kind == RBRACE) break;
2512                 elems.append(variableInitializer());
2513             }
2514         }
2515         accept(RBRACE);
2516         return elems.toList();
2517     }
2518 
2519     /** VariableInitializer = ArrayInitializer | Expression
2520      */
2521     public JCExpression variableInitializer() {
2522         return token.kind == LBRACE ? arrayInitializer(token.pos, null) : parseExpression();
2523     }
2524 
2525     /** ParExpression = "(" Expression ")"
2526      */
2527     JCExpression parExpression() {
2528         int pos = token.pos;
2529         accept(LPAREN);
2530         JCExpression t = parseExpression();
2531         accept(RPAREN);
2532         return toP(F.at(pos).Parens(t));
2533     }
2534 
2535     /** Block = "{" BlockStatements "}"
2536      */
2537     JCBlock block(int pos, long flags) {
2538         accept(LBRACE);
2539         List<JCStatement> stats = blockStatements();
2540         JCBlock t = F.at(pos).Block(flags, stats);
2541         while (token.kind == CASE || token.kind == DEFAULT) {
2542             syntaxError(token.pos, Errors.Orphaned(token.kind));
2543             switchBlockStatementGroups();
2544         }
2545         // the Block node has a field "endpos" for first char of last token, which is
2546         // usually but not necessarily the last char of the last token.
2547         t.endpos = token.pos;
2548         accept(RBRACE);
2549         return toP(t);
2550     }
2551 
2552     public JCBlock block() {
2553         return block(token.pos, 0);
2554     }
2555 
2556     /** BlockStatements = { BlockStatement }
2557      *  BlockStatement  = LocalVariableDeclarationStatement
2558      *                  | ClassOrInterfaceOrEnumDeclaration
2559      *                  | [Ident ":"] Statement
2560      *  LocalVariableDeclarationStatement
2561      *                  = { FINAL | '@' Annotation } Type VariableDeclarators ";"
2562      */
2563     @SuppressWarnings("fallthrough")
2564     List<JCStatement> blockStatements() {
2565         //todo: skip to anchor on error(?)
2566         int lastErrPos = -1;
2567         ListBuffer<JCStatement> stats = new ListBuffer<>();
2568         while (true) {
2569             List<JCStatement> stat = blockStatement();
2570             if (stat.isEmpty()) {
2571                 return stats.toList();
2572             } else {
2573                 // error recovery
2574                 if (token.pos == lastErrPos)
2575                     return stats.toList();
2576                 if (token.pos <= endPosTable.errorEndPos) {
2577                     skip(false, true, true, true);
2578                     lastErrPos = token.pos;
2579                 }
2580                 stats.addAll(stat);
2581             }
2582         }
2583     }
2584 
2585     /*
2586      * Parse a Statement (JLS 14.5). As an enhancement to improve error recovery,
2587      * this method will also recognize variable and class declarations (which are
2588      * not legal for a Statement) by delegating the parsing to BlockStatement (JLS 14.2).
2589      * If any illegal declarations are found, they will be wrapped in an erroneous tree,
2590      * and an error will be produced by this method.
2591      */
2592     JCStatement parseStatementAsBlock() {
2593         int pos = token.pos;
2594         List<JCStatement> stats = blockStatement();
2595         if (stats.isEmpty()) {
2596             JCErroneous e = syntaxError(pos, Errors.IllegalStartOfStmt);
2597             return toP(F.at(pos).Exec(e));
2598         } else {
2599             JCStatement first = stats.head;
2600             Error error = null;
2601             switch (first.getTag()) {
2602             case CLASSDEF:
2603                 error = Errors.ClassNotAllowed;
2604                 break;
2605             case VARDEF:
2606                 error = Errors.VariableNotAllowed;
2607                 break;
2608             }
2609             if (error != null) {
2610                 log.error(DiagnosticFlag.SYNTAX, first, error);
2611                 List<JCBlock> blist = List.of(F.at(first.pos).Block(0, stats));
2612                 return toP(F.at(pos).Exec(F.at(first.pos).Erroneous(blist)));
2613             }
2614             return first;
2615         }
2616     }
2617 
2618     /**This method parses a statement appearing inside a block.
2619      */
2620     @SuppressWarnings("fallthrough")
2621     List<JCStatement> blockStatement() {
2622         //todo: skip to anchor on error(?)
2623         Comment dc;
2624         int pos = token.pos;
2625         switch (token.kind) {
2626         case RBRACE: case CASE: case DEFAULT: case EOF:
2627             return List.nil();
2628         case LBRACE: case IF: case FOR: case WHILE: case DO: case TRY:
2629         case SWITCH: case SYNCHRONIZED: case RETURN: case THROW: case BREAK:
2630         case CONTINUE: case SEMI: case ELSE: case FINALLY: case CATCH:
2631         case ASSERT:
2632             return List.of(parseSimpleStatement());
2633         case MONKEYS_AT:
2634         case FINAL: {
2635             dc = token.comment(CommentStyle.JAVADOC);
2636             JCModifiers mods = modifiersOpt();
2637             if (token.kind == INTERFACE ||
2638                 token.kind == CLASS ||
2639                 token.kind == ENUM ||
2640                 isRecordStart()) {
2641                 return List.of(classOrRecordOrInterfaceOrEnumDeclaration(mods, dc));
2642             } else {
2643                 JCExpression t = parseType(true);
2644                 return localVariableDeclarations(mods, t);
2645             }
2646         }
2647         case ABSTRACT: case STRICTFP: {
2648             dc = token.comment(CommentStyle.JAVADOC);
2649             JCModifiers mods = modifiersOpt();
2650             return List.of(classOrRecordOrInterfaceOrEnumDeclaration(mods, dc));
2651         }
2652         case INTERFACE:
2653         case CLASS:
2654             dc = token.comment(CommentStyle.JAVADOC);
2655             return List.of(classOrRecordOrInterfaceOrEnumDeclaration(modifiersOpt(), dc));
2656         case ENUM:
2657             if (!allowRecords) {
2658                 log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.LocalEnum);
2659             }
2660             dc = token.comment(CommentStyle.JAVADOC);
2661             return List.of(classOrRecordOrInterfaceOrEnumDeclaration(modifiersOpt(), dc));
2662         case IDENTIFIER:
2663             if (token.name() == names.yield && allowYieldStatement) {
2664                 Token next = S.token(1);
2665                 boolean isYieldStatement;
2666                 switch (next.kind) {
2667                     case PLUS: case SUB: case STRINGLITERAL: case CHARLITERAL:
2668                     case INTLITERAL: case LONGLITERAL: case FLOATLITERAL: case DOUBLELITERAL:
2669                     case NULL: case IDENTIFIER: case TRUE: case FALSE:
2670                     case NEW: case SWITCH: case THIS: case SUPER:
2671                         isYieldStatement = true;
2672                         break;
2673                     case PLUSPLUS: case SUBSUB:
2674                         isYieldStatement = S.token(2).kind != SEMI;
2675                         break;
2676                     case BANG: case TILDE:
2677                         isYieldStatement = S.token(1).kind != SEMI;
2678                         break;
2679                     case LPAREN:
2680                         int lookahead = 2;
2681                         int balance = 1;
2682                         boolean hasComma = false;
2683                         Token l;
2684                         while ((l = S.token(lookahead)).kind != EOF && balance != 0) {
2685                             switch (l.kind) {
2686                                 case LPAREN: balance++; break;
2687                                 case RPAREN: balance--; break;
2688                                 case COMMA: if (balance == 1) hasComma = true; break;
2689                             }
2690                             lookahead++;
2691                         }
2692                         isYieldStatement = (!hasComma && lookahead != 3) || l.kind == ARROW;
2693                         break;
2694                     case SEMI: //error recovery - this is not a valid statement:
2695                         isYieldStatement = true;
2696                         break;
2697                     default:
2698                         isYieldStatement = false;
2699                         break;
2700                 }
2701 
2702                 if (isYieldStatement) {
2703                     nextToken();
2704                     JCExpression t = term(EXPR);
2705                     accept(SEMI);
2706                     return List.of(toP(F.at(pos).Yield(t)));
2707                 }
2708 
2709                 //else intentional fall-through
2710             } else {
2711                 if (isNonSealedClassStart(true)) {
2712                     log.error(token.pos, Errors.SealedOrNonSealedLocalClassesNotAllowed);
2713                     nextToken();
2714                     nextToken();
2715                     nextToken();
2716                     return List.of(classOrRecordOrInterfaceOrEnumDeclaration(modifiersOpt(), token.comment(CommentStyle.JAVADOC)));
2717                 } else if (isSealedClassStart(true)) {
2718                     checkSourceLevel(Feature.SEALED_CLASSES);
2719                     log.error(token.pos, Errors.SealedOrNonSealedLocalClassesNotAllowed);
2720                     nextToken();
2721                     return List.of(classOrRecordOrInterfaceOrEnumDeclaration(modifiersOpt(), token.comment(CommentStyle.JAVADOC)));
2722                 }
2723             }
2724         }
2725         if (isRecordStart() && allowRecords) {
2726             dc = token.comment(CommentStyle.JAVADOC);
2727             return List.of(recordDeclaration(F.at(pos).Modifiers(0), dc));
2728         } else {
2729             Token prevToken = token;
2730             JCExpression t = term(EXPR | TYPE);
2731             if (token.kind == COLON && t.hasTag(IDENT)) {
2732                 nextToken();
2733                 JCStatement stat = parseStatementAsBlock();
2734                 return List.of(F.at(pos).Labelled(prevToken.name(), stat));
2735             } else if ((lastmode & TYPE) != 0 && LAX_IDENTIFIER.test(token.kind)) {
2736                 pos = token.pos;
2737                 JCModifiers mods = F.at(Position.NOPOS).Modifiers(0);
2738                 F.at(pos);
2739                 return localVariableDeclarations(mods, t);
2740             } else {
2741                 // This Exec is an "ExpressionStatement"; it subsumes the terminating semicolon
2742                 t = checkExprStat(t);
2743                 accept(SEMI);
2744                 JCExpressionStatement expr = toP(F.at(pos).Exec(t));
2745                 return List.of(expr);
2746             }
2747         }
2748     }
2749     //where
2750         private List<JCStatement> localVariableDeclarations(JCModifiers mods, JCExpression type) {
2751             ListBuffer<JCStatement> stats =
2752                     variableDeclarators(mods, type, new ListBuffer<>(), true);
2753             // A "LocalVariableDeclarationStatement" subsumes the terminating semicolon
2754             accept(SEMI);
2755             storeEnd(stats.last(), S.prevToken().endPos);
2756             return stats.toList();
2757         }
2758 
2759     /** Statement =
2760      *       Block
2761      *     | IF ParExpression Statement [ELSE Statement]
2762      *     | FOR "(" ForInitOpt ";" [Expression] ";" ForUpdateOpt ")" Statement
2763      *     | FOR "(" FormalParameter : Expression ")" Statement
2764      *     | WHILE ParExpression Statement
2765      *     | DO Statement WHILE ParExpression ";"
2766      *     | TRY Block ( Catches | [Catches] FinallyPart )
2767      *     | TRY "(" ResourceSpecification ";"opt ")" Block [Catches] [FinallyPart]
2768      *     | SWITCH ParExpression "{" SwitchBlockStatementGroups "}"
2769      *     | SYNCHRONIZED ParExpression Block
2770      *     | RETURN [Expression] ";"
2771      *     | THROW Expression ";"
2772      *     | BREAK [Ident] ";"
2773      *     | CONTINUE [Ident] ";"
2774      *     | ASSERT Expression [ ":" Expression ] ";"
2775      *     | ";"
2776      */
2777     public JCStatement parseSimpleStatement() {
2778         int pos = token.pos;
2779         switch (token.kind) {
2780         case LBRACE:
2781             return block();
2782         case IF: {
2783             nextToken();
2784             JCExpression cond = parExpression();
2785             JCStatement thenpart = parseStatementAsBlock();
2786             JCStatement elsepart = null;
2787             if (token.kind == ELSE) {
2788                 nextToken();
2789                 elsepart = parseStatementAsBlock();
2790             }
2791             return F.at(pos).If(cond, thenpart, elsepart);
2792         }
2793         case FOR: {
2794             nextToken();
2795             accept(LPAREN);
2796             List<JCStatement> inits = token.kind == SEMI ? List.nil() : forInit();
2797             if (inits.length() == 1 &&
2798                 inits.head.hasTag(VARDEF) &&
2799                 ((JCVariableDecl) inits.head).init == null &&
2800                 token.kind == COLON) {
2801                 JCVariableDecl var = (JCVariableDecl)inits.head;
2802                 accept(COLON);
2803                 JCExpression expr = parseExpression();
2804                 accept(RPAREN);
2805                 JCStatement body = parseStatementAsBlock();
2806                 return F.at(pos).ForeachLoop(var, expr, body);
2807             } else {
2808                 accept(SEMI);
2809                 JCExpression cond = token.kind == SEMI ? null : parseExpression();
2810                 accept(SEMI);
2811                 List<JCExpressionStatement> steps = token.kind == RPAREN ? List.nil() : forUpdate();
2812                 accept(RPAREN);
2813                 JCStatement body = parseStatementAsBlock();
2814                 return F.at(pos).ForLoop(inits, cond, steps, body);
2815             }
2816         }
2817         case WHILE: {
2818             nextToken();
2819             JCExpression cond = parExpression();
2820             JCStatement body = parseStatementAsBlock();
2821             return F.at(pos).WhileLoop(cond, body);
2822         }
2823         case DO: {
2824             nextToken();
2825             JCStatement body = parseStatementAsBlock();
2826             accept(WHILE);
2827             JCExpression cond = parExpression();
2828             accept(SEMI);
2829             JCDoWhileLoop t = toP(F.at(pos).DoLoop(body, cond));
2830             return t;
2831         }
2832         case TRY: {
2833             nextToken();
2834             List<JCTree> resources = List.nil();
2835             if (token.kind == LPAREN) {
2836                 nextToken();
2837                 resources = resources();
2838                 accept(RPAREN);
2839             }
2840             JCBlock body = block();
2841             ListBuffer<JCCatch> catchers = new ListBuffer<>();
2842             JCBlock finalizer = null;
2843             if (token.kind == CATCH || token.kind == FINALLY) {
2844                 while (token.kind == CATCH) catchers.append(catchClause());
2845                 if (token.kind == FINALLY) {
2846                     nextToken();
2847                     finalizer = block();
2848                 }
2849             } else {
2850                 if (resources.isEmpty()) {
2851                     log.error(DiagnosticFlag.SYNTAX, pos, Errors.TryWithoutCatchFinallyOrResourceDecls);
2852                 }
2853             }
2854             return F.at(pos).Try(resources, body, catchers.toList(), finalizer);
2855         }
2856         case SWITCH: {
2857             nextToken();
2858             JCExpression selector = parExpression();
2859             accept(LBRACE);
2860             List<JCCase> cases = switchBlockStatementGroups();
2861             JCSwitch t = to(F.at(pos).Switch(selector, cases));
2862             t.endpos = token.endPos;
2863             accept(RBRACE);
2864             return t;
2865         }
2866         case SYNCHRONIZED: {
2867             nextToken();
2868             JCExpression lock = parExpression();
2869             JCBlock body = block();
2870             return F.at(pos).Synchronized(lock, body);
2871         }
2872         case RETURN: {
2873             nextToken();
2874             JCExpression result = token.kind == SEMI ? null : parseExpression();
2875             accept(SEMI);
2876             JCReturn t = toP(F.at(pos).Return(result));
2877             return t;
2878         }
2879         case THROW: {
2880             nextToken();
2881             JCExpression exc = parseExpression();
2882             accept(SEMI);
2883             JCThrow t = toP(F.at(pos).Throw(exc));
2884             return t;
2885         }
2886         case BREAK: {
2887             nextToken();
2888             Name label = LAX_IDENTIFIER.test(token.kind) ? ident() : null;
2889             accept(SEMI);
2890             JCBreak t = toP(F.at(pos).Break(label));
2891             return t;
2892         }
2893         case CONTINUE: {
2894             nextToken();
2895             Name label = LAX_IDENTIFIER.test(token.kind) ? ident() : null;
2896             accept(SEMI);
2897             JCContinue t =  toP(F.at(pos).Continue(label));
2898             return t;
2899         }
2900         case SEMI:
2901             nextToken();
2902             return toP(F.at(pos).Skip());
2903         case ELSE:
2904             int elsePos = token.pos;
2905             nextToken();
2906             return doRecover(elsePos, BasicErrorRecoveryAction.BLOCK_STMT, Errors.ElseWithoutIf);
2907         case FINALLY:
2908             int finallyPos = token.pos;
2909             nextToken();
2910             return doRecover(finallyPos, BasicErrorRecoveryAction.BLOCK_STMT, Errors.FinallyWithoutTry);
2911         case CATCH:
2912             return doRecover(token.pos, BasicErrorRecoveryAction.CATCH_CLAUSE, Errors.CatchWithoutTry);
2913         case ASSERT: {
2914             nextToken();
2915             JCExpression assertion = parseExpression();
2916             JCExpression message = null;
2917             if (token.kind == COLON) {
2918                 nextToken();
2919                 message = parseExpression();
2920             }
2921             accept(SEMI);
2922             JCAssert t = toP(F.at(pos).Assert(assertion, message));
2923             return t;
2924         }
2925         default:
2926             Assert.error();
2927             return null;
2928         }
2929     }
2930 
2931     @Override
2932     public JCStatement parseStatement() {
2933         return parseStatementAsBlock();
2934     }
2935 
2936     private JCStatement doRecover(int startPos, ErrorRecoveryAction action, Error errorKey) {
2937         int errPos = S.errPos();
2938         JCTree stm = action.doRecover(this);
2939         S.errPos(errPos);
2940         return toP(F.Exec(syntaxError(startPos, List.of(stm), errorKey)));
2941     }
2942 
2943     /** CatchClause     = CATCH "(" FormalParameter ")" Block
2944      * TODO: the "FormalParameter" is not correct, it uses the special "catchTypes" rule below.
2945      */
2946     protected JCCatch catchClause() {
2947         int pos = token.pos;
2948         accept(CATCH);
2949         accept(LPAREN);
2950         JCModifiers mods = optFinal(Flags.PARAMETER);
2951         List<JCExpression> catchTypes = catchTypes();
2952         JCExpression paramType = catchTypes.size() > 1 ?
2953                 toP(F.at(catchTypes.head.getStartPosition()).TypeUnion(catchTypes)) :
2954                 catchTypes.head;
2955         JCVariableDecl formal = variableDeclaratorId(mods, paramType);
2956         accept(RPAREN);
2957         JCBlock body = block();
2958         return F.at(pos).Catch(formal, body);
2959     }
2960 
2961     List<JCExpression> catchTypes() {
2962         ListBuffer<JCExpression> catchTypes = new ListBuffer<>();
2963         catchTypes.add(parseType());
2964         while (token.kind == BAR) {
2965             nextToken();
2966             // Instead of qualident this is now parseType.
2967             // But would that allow too much, e.g. arrays or generics?
2968             catchTypes.add(parseType());
2969         }
2970         return catchTypes.toList();
2971     }
2972 
2973     /** SwitchBlockStatementGroups = { SwitchBlockStatementGroup }
2974      *  SwitchBlockStatementGroup = SwitchLabel BlockStatements
2975      *  SwitchLabel = CASE ConstantExpression ":" | DEFAULT ":"
2976      */
2977     List<JCCase> switchBlockStatementGroups() {
2978         ListBuffer<JCCase> cases = new ListBuffer<>();
2979         while (true) {
2980             int pos = token.pos;
2981             switch (token.kind) {
2982             case CASE:
2983             case DEFAULT:
2984                 cases.appendList(switchBlockStatementGroup());
2985                 break;
2986             case RBRACE: case EOF:
2987                 return cases.toList();
2988             default:
2989                 nextToken(); // to ensure progress
2990                 syntaxError(pos, Errors.Expected3(CASE, DEFAULT, RBRACE));
2991             }
2992         }
2993     }
2994 
2995     protected List<JCCase> switchBlockStatementGroup() {
2996         int pos = token.pos;
2997         List<JCStatement> stats;
2998         JCCase c;
2999         ListBuffer<JCCase> cases = new ListBuffer<JCCase>();
3000         switch (token.kind) {
3001         case CASE: {
3002             nextToken();
3003             ListBuffer<JCCaseLabel> pats = new ListBuffer<>();
3004             while (true) {
3005                 pats.append(parseCaseLabel());
3006                 if (token.kind != COMMA) break;
3007                 nextToken();
3008                 checkSourceLevel(Feature.SWITCH_MULTIPLE_CASE_LABELS);
3009             };
3010             CaseTree.CaseKind caseKind;
3011             JCTree body = null;
3012             if (token.kind == ARROW) {
3013                 checkSourceLevel(Feature.SWITCH_RULE);
3014                 accept(ARROW);
3015                 caseKind = JCCase.RULE;
3016                 JCStatement statement = parseStatementAsBlock();
3017                 if (!statement.hasTag(EXEC) && !statement.hasTag(BLOCK) && !statement.hasTag(Tag.THROW)) {
3018                     log.error(statement.pos(), Errors.SwitchCaseUnexpectedStatement);
3019                 }
3020                 stats = List.of(statement);
3021                 body = stats.head;
3022             } else {
3023                 accept(COLON, tk -> Errors.Expected2(COLON, ARROW));
3024                 caseKind = JCCase.STATEMENT;
3025                 stats = blockStatements();
3026             }
3027             c = F.at(pos).Case(caseKind, pats.toList(), stats, body);
3028             if (stats.isEmpty())
3029                 storeEnd(c, S.prevToken().endPos);
3030             return cases.append(c).toList();
3031         }
3032         case DEFAULT: {
3033             nextToken();
3034             CaseTree.CaseKind caseKind;
3035             JCTree body = null;
3036             int patternPos = token.pos;
3037             if (token.kind == ARROW) {
3038                 checkSourceLevel(Feature.SWITCH_RULE);
3039                 accept(ARROW);
3040                 caseKind = JCCase.RULE;
3041                 JCStatement statement = parseStatementAsBlock();
3042                 if (!statement.hasTag(EXEC) && !statement.hasTag(BLOCK) && !statement.hasTag(Tag.THROW)) {
3043                     log.error(statement.pos(), Errors.SwitchCaseUnexpectedStatement);
3044                 }
3045                 stats = List.of(statement);
3046                 body = stats.head;
3047             } else {
3048                 accept(COLON, tk -> Errors.Expected2(COLON, ARROW));
3049                 caseKind = JCCase.STATEMENT;
3050                 stats = blockStatements();
3051             }
3052             JCCaseLabel defaultPattern = toP(F.at(patternPos).DefaultCaseLabel());
3053             c = F.at(pos).Case(caseKind, List.of(defaultPattern), stats, body);
3054             if (stats.isEmpty())
3055                 storeEnd(c, S.prevToken().endPos);
3056             return cases.append(c).toList();
3057         }
3058         }
3059         throw new AssertionError("should not reach here");
3060     }
3061 
3062     private JCCaseLabel parseCaseLabel() {
3063         int patternPos = token.pos;
3064         JCCaseLabel label;
3065 
3066         if (token.kind == DEFAULT) {
3067             checkSourceLevel(token.pos, Feature.PATTERN_SWITCH);
3068             nextToken();
3069             label = toP(F.at(patternPos).DefaultCaseLabel());
3070         } else {
3071             int lookahead = 0;
3072             while (S.token(lookahead).kind == LPAREN) {
3073                 lookahead++;
3074             }
3075             JCModifiers mods = optFinal(0);
3076             boolean pattern = mods.flags != 0 || mods.annotations.nonEmpty() ||
3077                               analyzePattern(lookahead) == PatternResult.PATTERN;
3078             if (pattern) {
3079                 checkSourceLevel(token.pos, Feature.PATTERN_SWITCH);
3080                 return parsePattern(patternPos, mods, null, false);
3081             } else {
3082                 return term(EXPR | NOLAMBDA);
3083             }
3084         }
3085 
3086         return label;
3087     }
3088 
3089     @SuppressWarnings("fallthrough")
3090     PatternResult analyzePattern(int lookahead) {
3091         int depth = 0;
3092         while (true) {
3093             TokenKind token = S.token(lookahead).kind;
3094             switch (token) {
3095                 case BYTE: case SHORT: case INT: case LONG: case FLOAT:
3096                 case DOUBLE: case BOOLEAN: case CHAR: case VOID:
3097                 case ASSERT, ENUM, IDENTIFIER, UNDERSCORE:
3098                     if (depth == 0 && peekToken(lookahead, LAX_IDENTIFIER)) return PatternResult.PATTERN;
3099                     break;
3100                 case DOT, QUES, EXTENDS, SUPER, COMMA: break;
3101                 case LT: depth++; break;
3102                 case GTGTGT: depth--;
3103                 case GTGT: depth--;
3104                 case GT:
3105                     depth--;
3106                     if (depth == 0) {
3107                          return peekToken(lookahead, LAX_IDENTIFIER) ? PatternResult.PATTERN
3108                                                           : PatternResult.EXPRESSION;
3109                     } else if (depth < 0) return PatternResult.EXPRESSION;
3110                     break;
3111                 case MONKEYS_AT:
3112                     lookahead = skipAnnotation(lookahead);
3113                     break;
3114                 case LBRACKET:
3115                     if (peekToken(lookahead, RBRACKET, LAX_IDENTIFIER)) {
3116                         return PatternResult.PATTERN;
3117                     } else if (peekToken(lookahead, RBRACKET)) {
3118                         lookahead++;
3119                         break;
3120                     } else {
3121                         return PatternResult.EXPRESSION;
3122                     }
3123                 default: return PatternResult.EXPRESSION;
3124             }
3125             lookahead++;
3126         }
3127     }
3128 
3129     private enum PatternResult {
3130         EXPRESSION,
3131         PATTERN;
3132     }
3133 
3134     /** MoreStatementExpressions = { COMMA StatementExpression }
3135      */
3136     <T extends ListBuffer<? super JCExpressionStatement>> T moreStatementExpressions(int pos,
3137                                                                     JCExpression first,
3138                                                                     T stats) {
3139         // This Exec is a "StatementExpression"; it subsumes no terminating token
3140         stats.append(toP(F.at(pos).Exec(checkExprStat(first))));
3141         while (token.kind == COMMA) {
3142             nextToken();
3143             pos = token.pos;
3144             JCExpression t = parseExpression();
3145             // This Exec is a "StatementExpression"; it subsumes no terminating token
3146             stats.append(toP(F.at(pos).Exec(checkExprStat(t))));
3147         }
3148         return stats;
3149     }
3150 
3151     /** ForInit = StatementExpression MoreStatementExpressions
3152      *           |  { FINAL | '@' Annotation } Type VariableDeclarators
3153      */
3154     List<JCStatement> forInit() {
3155         ListBuffer<JCStatement> stats = new ListBuffer<>();
3156         int pos = token.pos;
3157         if (token.kind == FINAL || token.kind == MONKEYS_AT) {
3158             return variableDeclarators(optFinal(0), parseType(true), stats, true).toList();
3159         } else {
3160             JCExpression t = term(EXPR | TYPE);
3161             if ((lastmode & TYPE) != 0 && LAX_IDENTIFIER.test(token.kind)) {
3162                 return variableDeclarators(modifiersOpt(), t, stats, true).toList();
3163             } else if ((lastmode & TYPE) != 0 && token.kind == COLON) {
3164                 log.error(DiagnosticFlag.SYNTAX, pos, Errors.BadInitializer("for-loop"));
3165                 return List.of((JCStatement)F.at(pos).VarDef(modifiersOpt(), names.error, t, null));
3166             } else {
3167                 return moreStatementExpressions(pos, t, stats).toList();
3168             }
3169         }
3170     }
3171 
3172     /** ForUpdate = StatementExpression MoreStatementExpressions
3173      */
3174     List<JCExpressionStatement> forUpdate() {
3175         return moreStatementExpressions(token.pos,
3176                                         parseExpression(),
3177                                         new ListBuffer<JCExpressionStatement>()).toList();
3178     }
3179 
3180     /** AnnotationsOpt = { '@' Annotation }
3181      *
3182      * @param kind Whether to parse an ANNOTATION or TYPE_ANNOTATION
3183      */
3184     protected List<JCAnnotation> annotationsOpt(Tag kind) {
3185         if (token.kind != MONKEYS_AT) return List.nil(); // optimization
3186         ListBuffer<JCAnnotation> buf = new ListBuffer<>();
3187         int prevmode = mode;
3188         while (token.kind == MONKEYS_AT) {
3189             int pos = token.pos;
3190             nextToken();
3191             buf.append(annotation(pos, kind));
3192         }
3193         lastmode = mode;
3194         mode = prevmode;
3195         List<JCAnnotation> annotations = buf.toList();
3196 
3197         return annotations;
3198     }
3199 
3200     List<JCAnnotation> typeAnnotationsOpt() {
3201         List<JCAnnotation> annotations = annotationsOpt(Tag.TYPE_ANNOTATION);
3202         return annotations;
3203     }
3204 
3205     /** ModifiersOpt = { Modifier }
3206      *  Modifier = PUBLIC | PROTECTED | PRIVATE | STATIC | ABSTRACT | FINAL
3207      *           | NATIVE | SYNCHRONIZED | TRANSIENT | VOLATILE | "@"
3208      *           | "@" Annotation
3209      */
3210     protected JCModifiers modifiersOpt() {
3211         return modifiersOpt(null);
3212     }
3213     protected JCModifiers modifiersOpt(JCModifiers partial) {
3214         long flags;
3215         ListBuffer<JCAnnotation> annotations = new ListBuffer<>();
3216         int pos;
3217         if (partial == null) {
3218             flags = 0;
3219             pos = token.pos;
3220         } else {
3221             flags = partial.flags;
3222             annotations.appendList(partial.annotations);
3223             pos = partial.pos;
3224         }
3225         if (token.deprecatedFlag()) {
3226             flags |= Flags.DEPRECATED;
3227         }
3228         int lastPos;
3229     loop:
3230         while (true) {
3231             long flag;
3232             switch (token.kind) {
3233             case PRIVATE     : flag = Flags.PRIVATE; break;
3234             case PROTECTED   : flag = Flags.PROTECTED; break;
3235             case PUBLIC      : flag = Flags.PUBLIC; break;
3236             case STATIC      : flag = Flags.STATIC; break;
3237             case TRANSIENT   : flag = Flags.TRANSIENT; break;
3238             case FINAL       : flag = Flags.FINAL; break;
3239             case ABSTRACT    : flag = Flags.ABSTRACT; break;
3240             case NATIVE      : flag = Flags.NATIVE; break;
3241             case VOLATILE    : flag = Flags.VOLATILE; break;
3242             case SYNCHRONIZED: flag = Flags.SYNCHRONIZED; break;
3243             case STRICTFP    : flag = Flags.STRICTFP; break;
3244             case MONKEYS_AT  : flag = Flags.ANNOTATION; break;
3245             case DEFAULT     : checkSourceLevel(Feature.DEFAULT_METHODS); flag = Flags.DEFAULT; break;
3246             case ERROR       : flag = 0; nextToken(); break;
3247             case IDENTIFIER  : {
3248                 if (isNonSealedClassStart(false)) {
3249                     flag = Flags.NON_SEALED;
3250                     nextToken();
3251                     nextToken();
3252                     break;
3253                 }
3254                 if (isSealedClassStart(false)) {
3255                     checkSourceLevel(Feature.SEALED_CLASSES);
3256                     flag = Flags.SEALED;
3257                     break;
3258                 }
3259                 break loop;
3260             }
3261             default: break loop;
3262             }
3263             if ((flags & flag) != 0) log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.RepeatedModifier);
3264             lastPos = token.pos;
3265             nextToken();
3266             if (flag == Flags.ANNOTATION) {
3267                 if (token.kind != INTERFACE) {
3268                     JCAnnotation ann = annotation(lastPos, Tag.ANNOTATION);
3269                     // if first modifier is an annotation, set pos to annotation's.
3270                     if (flags == 0 && annotations.isEmpty())
3271                         pos = ann.pos;
3272                     annotations.append(ann);
3273                     flag = 0;
3274                 }
3275             }
3276             flags |= flag;
3277         }
3278         switch (token.kind) {
3279         case ENUM: flags |= Flags.ENUM; break;
3280         case INTERFACE: flags |= Flags.INTERFACE; break;
3281         default: break;
3282         }
3283 
3284         /* A modifiers tree with no modifier tokens or annotations
3285          * has no text position. */
3286         if ((flags & (Flags.ModifierFlags | Flags.ANNOTATION)) == 0 && annotations.isEmpty())
3287             pos = Position.NOPOS;
3288 
3289         JCModifiers mods = F.at(pos).Modifiers(flags, annotations.toList());
3290         if (pos != Position.NOPOS)
3291             storeEnd(mods, S.prevToken().endPos);
3292         return mods;
3293     }
3294 
3295     /** Annotation              = "@" Qualident [ "(" AnnotationFieldValues ")" ]
3296      *
3297      * @param pos position of "@" token
3298      * @param kind Whether to parse an ANNOTATION or TYPE_ANNOTATION
3299      */
3300     JCAnnotation annotation(int pos, Tag kind) {
3301         // accept(AT); // AT consumed by caller
3302         if (kind == Tag.TYPE_ANNOTATION) {
3303             checkSourceLevel(Feature.TYPE_ANNOTATIONS);
3304         }
3305         JCTree ident = qualident(false);
3306         List<JCExpression> fieldValues = annotationFieldValuesOpt();
3307         JCAnnotation ann;
3308         if (kind == Tag.ANNOTATION) {
3309             ann = F.at(pos).Annotation(ident, fieldValues);
3310         } else if (kind == Tag.TYPE_ANNOTATION) {
3311             ann = F.at(pos).TypeAnnotation(ident, fieldValues);
3312         } else {
3313             throw new AssertionError("Unhandled annotation kind: " + kind);
3314         }
3315 
3316         storeEnd(ann, S.prevToken().endPos);
3317         return ann;
3318     }
3319 
3320     List<JCExpression> annotationFieldValuesOpt() {
3321         return (token.kind == LPAREN) ? annotationFieldValues() : List.nil();
3322     }
3323 
3324     /** AnnotationFieldValues   = "(" [ AnnotationFieldValue { "," AnnotationFieldValue } ] ")" */
3325     List<JCExpression> annotationFieldValues() {
3326         accept(LPAREN);
3327         ListBuffer<JCExpression> buf = new ListBuffer<>();
3328         if (token.kind != RPAREN) {
3329             buf.append(annotationFieldValue());
3330             while (token.kind == COMMA) {
3331                 nextToken();
3332                 buf.append(annotationFieldValue());
3333             }
3334         }
3335         accept(RPAREN);
3336         return buf.toList();
3337     }
3338 
3339     /** AnnotationFieldValue    = AnnotationValue
3340      *                          | Identifier "=" AnnotationValue
3341      */
3342     JCExpression annotationFieldValue() {
3343         if (LAX_IDENTIFIER.test(token.kind)) {
3344             selectExprMode();
3345             JCExpression t1 = term1();
3346             if (t1.hasTag(IDENT) && token.kind == EQ) {
3347                 int pos = token.pos;
3348                 accept(EQ);
3349                 JCExpression v = annotationValue();
3350                 return toP(F.at(pos).Assign(t1, v));
3351             } else {
3352                 return t1;
3353             }
3354         }
3355         return annotationValue();
3356     }
3357 
3358     /* AnnotationValue          = ConditionalExpression
3359      *                          | Annotation
3360      *                          | "{" [ AnnotationValue { "," AnnotationValue } ] [","] "}"
3361      */
3362     JCExpression annotationValue() {
3363         int pos;
3364         switch (token.kind) {
3365         case MONKEYS_AT:
3366             pos = token.pos;
3367             nextToken();
3368             return annotation(pos, Tag.ANNOTATION);
3369         case LBRACE:
3370             pos = token.pos;
3371             accept(LBRACE);
3372             ListBuffer<JCExpression> buf = new ListBuffer<>();
3373             if (token.kind == COMMA) {
3374                 nextToken();
3375             } else if (token.kind != RBRACE) {
3376                 buf.append(annotationValue());
3377                 while (token.kind == COMMA) {
3378                     nextToken();
3379                     if (token.kind == RBRACE) break;
3380                     buf.append(annotationValue());
3381                 }
3382             }
3383             accept(RBRACE);
3384             return toP(F.at(pos).NewArray(null, List.nil(), buf.toList()));
3385         default:
3386             selectExprMode();
3387             return term1();
3388         }
3389     }
3390 
3391     /** VariableDeclarators = VariableDeclarator { "," VariableDeclarator }
3392      */
3393     public <T extends ListBuffer<? super JCVariableDecl>> T variableDeclarators(JCModifiers mods,
3394                                                                          JCExpression type,
3395                                                                          T vdefs,
3396                                                                          boolean localDecl)
3397     {
3398         return variableDeclaratorsRest(token.pos, mods, type, ident(), false, null, vdefs, localDecl);
3399     }
3400 
3401     /** VariableDeclaratorsRest = VariableDeclaratorRest { "," VariableDeclarator }
3402      *  ConstantDeclaratorsRest = ConstantDeclaratorRest { "," ConstantDeclarator }
3403      *
3404      *  @param reqInit  Is an initializer always required?
3405      *  @param dc       The documentation comment for the variable declarations, or null.
3406      */
3407     protected <T extends ListBuffer<? super JCVariableDecl>> T variableDeclaratorsRest(int pos,
3408                                                                      JCModifiers mods,
3409                                                                      JCExpression type,
3410                                                                      Name name,
3411                                                                      boolean reqInit,
3412                                                                      Comment dc,
3413                                                                      T vdefs,
3414                                                                      boolean localDecl)
3415     {
3416         JCVariableDecl head = variableDeclaratorRest(pos, mods, type, name, reqInit, dc, localDecl, false);
3417         vdefs.append(head);
3418         while (token.kind == COMMA) {
3419             // All but last of multiple declarators subsume a comma
3420             storeEnd((JCTree)vdefs.last(), token.endPos);
3421             nextToken();
3422             vdefs.append(variableDeclarator(mods, type, reqInit, dc, localDecl));
3423         }
3424         return vdefs;
3425     }
3426 
3427     /** VariableDeclarator = Ident VariableDeclaratorRest
3428      *  ConstantDeclarator = Ident ConstantDeclaratorRest
3429      */
3430     JCVariableDecl variableDeclarator(JCModifiers mods, JCExpression type, boolean reqInit, Comment dc, boolean localDecl) {
3431         return variableDeclaratorRest(token.pos, mods, type, ident(), reqInit, dc, localDecl, true);
3432     }
3433 
3434     /** VariableDeclaratorRest = BracketsOpt ["=" VariableInitializer]
3435      *  ConstantDeclaratorRest = BracketsOpt "=" VariableInitializer
3436      *
3437      *  @param reqInit  Is an initializer always required?
3438      *  @param dc       The documentation comment for the variable declarations, or null.
3439      */
3440     JCVariableDecl variableDeclaratorRest(int pos, JCModifiers mods, JCExpression type, Name name,
3441                                   boolean reqInit, Comment dc, boolean localDecl, boolean compound) {
3442         boolean declaredUsingVar = false;
3443         type = bracketsOpt(type);
3444         JCExpression init = null;
3445         if (token.kind == EQ) {
3446             nextToken();
3447             init = variableInitializer();
3448         }
3449         else if (reqInit) syntaxError(token.pos, Errors.Expected(EQ));
3450         JCTree elemType = TreeInfo.innermostType(type, true);
3451         int startPos = Position.NOPOS;
3452         if (elemType.hasTag(IDENT)) {
3453             Name typeName = ((JCIdent)elemType).name;
3454             if (restrictedTypeNameStartingAtSource(typeName, pos, !compound && localDecl) != null) {
3455                 if (typeName != names.var) {
3456                     reportSyntaxError(elemType.pos, Errors.RestrictedTypeNotAllowedHere(typeName));
3457                 } else if (type.hasTag(TYPEARRAY) && !compound) {
3458                     //error - 'var' and arrays
3459                     reportSyntaxError(elemType.pos, Errors.RestrictedTypeNotAllowedArray(typeName));
3460                 } else {
3461                     declaredUsingVar = true;
3462                     if(compound)
3463                         //error - 'var' in compound local var decl
3464                         reportSyntaxError(elemType.pos, Errors.RestrictedTypeNotAllowedCompound(typeName));
3465                     startPos = TreeInfo.getStartPos(mods);
3466                     if (startPos == Position.NOPOS)
3467                         startPos = TreeInfo.getStartPos(type);
3468                     //implicit type
3469                     type = null;
3470                 }
3471             }
3472         }
3473         JCVariableDecl result =
3474             toP(F.at(pos).VarDef(mods, name, type, init, declaredUsingVar));
3475         attach(result, dc);
3476         result.startPos = startPos;
3477         return result;
3478     }
3479 
3480     Name restrictedTypeName(JCExpression e, boolean shouldWarn) {
3481         switch (e.getTag()) {
3482             case IDENT:
3483                 return restrictedTypeNameStartingAtSource(((JCIdent)e).name, e.pos, shouldWarn) != null ? ((JCIdent)e).name : null;
3484             case TYPEARRAY:
3485                 return restrictedTypeName(((JCArrayTypeTree)e).elemtype, shouldWarn);
3486             default:
3487                 return null;
3488         }
3489     }
3490 
3491     Source restrictedTypeNameStartingAtSource(Name name, int pos, boolean shouldWarn) {
3492         if (name == names.var) {
3493             if (Feature.LOCAL_VARIABLE_TYPE_INFERENCE.allowedInSource(source)) {
3494                 return Source.JDK10;
3495             } else if (shouldWarn) {
3496                 log.warning(pos, Warnings.RestrictedTypeNotAllowed(name, Source.JDK10));
3497             }
3498         }
3499         if (name == names.yield) {
3500             if (allowYieldStatement) {
3501                 return Source.JDK14;
3502             } else if (shouldWarn) {
3503                 log.warning(pos, Warnings.RestrictedTypeNotAllowed(name, Source.JDK14));
3504             }
3505         }
3506         if (name == names.record) {
3507             if (allowRecords) {
3508                 return Source.JDK14;
3509             } else if (shouldWarn) {
3510                 log.warning(pos, Warnings.RestrictedTypeNotAllowedPreview(name, Source.JDK14));
3511             }
3512         }
3513         if (name == names.sealed) {
3514             if (allowSealedTypes) {
3515                 return Source.JDK15;
3516             } else if (shouldWarn) {
3517                 log.warning(pos, Warnings.RestrictedTypeNotAllowedPreview(name, Source.JDK15));
3518             }
3519         }
3520         if (name == names.permits) {
3521             if (allowSealedTypes) {
3522                 return Source.JDK15;
3523             } else if (shouldWarn) {
3524                 log.warning(pos, Warnings.RestrictedTypeNotAllowedPreview(name, Source.JDK15));
3525             }
3526         }
3527         return null;
3528     }
3529 
3530     /** VariableDeclaratorId = Ident BracketsOpt
3531      */
3532     JCVariableDecl variableDeclaratorId(JCModifiers mods, JCExpression type) {
3533         return variableDeclaratorId(mods, type, false, false);
3534     }
3535     //where
3536     JCVariableDecl variableDeclaratorId(JCModifiers mods, JCExpression type, boolean lambdaParameter, boolean recordComponent) {
3537         int pos = token.pos;
3538         Name name;
3539         if (lambdaParameter && token.kind == UNDERSCORE) {
3540             log.error(pos, Errors.UnderscoreAsIdentifierInLambda);
3541             name = token.name();
3542             nextToken();
3543         } else {
3544             if (allowThisIdent ||
3545                 !lambdaParameter ||
3546                 LAX_IDENTIFIER.test(token.kind) ||
3547                 mods.flags != Flags.PARAMETER ||
3548                 mods.annotations.nonEmpty()) {
3549                 JCExpression pn = qualident(false);
3550                 if (pn.hasTag(Tag.IDENT) && ((JCIdent)pn).name != names._this) {
3551                     name = ((JCIdent)pn).name;
3552                 } else {
3553                     if (allowThisIdent) {
3554                         if ((mods.flags & Flags.VARARGS) != 0) {
3555                             log.error(token.pos, Errors.VarargsAndReceiver);
3556                         }
3557                         if (token.kind == LBRACKET) {
3558                             log.error(token.pos, Errors.ArrayAndReceiver);
3559                         }
3560                         if (pn.hasTag(Tag.SELECT) && ((JCFieldAccess)pn).name != names._this) {
3561                             log.error(token.pos, Errors.WrongReceiver);
3562                         }
3563                     }
3564                     return toP(F.at(pos).ReceiverVarDef(mods, pn, type));
3565                 }
3566             } else {
3567                 /** if it is a lambda parameter and the token kind is not an identifier,
3568                  *  and there are no modifiers or annotations, then this means that the compiler
3569                  *  supposed the lambda to be explicit but it can contain a mix of implicit,
3570                  *  var or explicit parameters. So we assign the error name to the parameter name
3571                  *  instead of issuing an error and analyze the lambda parameters as a whole at
3572                  *  a higher level.
3573                  */
3574                 name = names.empty;
3575             }
3576         }
3577         if ((mods.flags & Flags.VARARGS) != 0 &&
3578                 token.kind == LBRACKET) {
3579             log.error(token.pos, Errors.VarargsAndOldArraySyntax);
3580         }
3581         if (recordComponent && token.kind == LBRACKET) {
3582             log.error(token.pos, Errors.RecordComponentAndOldArraySyntax);
3583         }
3584         type = bracketsOpt(type);
3585 
3586         return toP(F.at(pos).VarDef(mods, name, type, null,
3587                 type != null && type.hasTag(IDENT) && ((JCIdent)type).name == names.var));
3588     }
3589 
3590     /** Resources = Resource { ";" Resources }
3591      */
3592     List<JCTree> resources() {
3593         ListBuffer<JCTree> defs = new ListBuffer<>();
3594         defs.append(resource());
3595         while (token.kind == SEMI) {
3596             // All but last of multiple declarators must subsume a semicolon
3597             storeEnd(defs.last(), token.endPos);
3598             int semiColonPos = token.pos;
3599             nextToken();
3600             if (token.kind == RPAREN) { // Optional trailing semicolon
3601                                        // after last resource
3602                 break;
3603             }
3604             defs.append(resource());
3605         }
3606         return defs.toList();
3607     }
3608 
3609     /** Resource = VariableModifiersOpt Type VariableDeclaratorId "=" Expression
3610      *           | Expression
3611      */
3612     protected JCTree resource() {
3613         int startPos = token.pos;
3614         if (token.kind == FINAL || token.kind == MONKEYS_AT) {
3615             JCModifiers mods = optFinal(Flags.FINAL);
3616             JCExpression t = parseType(true);
3617             return variableDeclaratorRest(token.pos, mods, t, ident(), true, null, true, false);
3618         }
3619         JCExpression t = term(EXPR | TYPE);
3620         if ((lastmode & TYPE) != 0 && LAX_IDENTIFIER.test(token.kind)) {
3621             JCModifiers mods = toP(F.at(startPos).Modifiers(Flags.FINAL));
3622             return variableDeclaratorRest(token.pos, mods, t, ident(), true, null, true, false);
3623         } else {
3624             checkSourceLevel(Feature.EFFECTIVELY_FINAL_VARIABLES_IN_TRY_WITH_RESOURCES);
3625             if (!t.hasTag(IDENT) && !t.hasTag(SELECT)) {
3626                 log.error(t.pos(), Errors.TryWithResourcesExprNeedsVar);
3627             }
3628 
3629             return t;
3630         }
3631     }
3632 
3633     /** CompilationUnit = [ { "@" Annotation } PACKAGE Qualident ";"] {ImportDeclaration} {TypeDeclaration}
3634      */
3635     public JCTree.JCCompilationUnit parseCompilationUnit() {
3636         Token firstToken = token;
3637         JCModifiers mods = null;
3638         boolean consumedToplevelDoc = false;
3639         boolean seenImport = false;
3640         boolean seenPackage = false;
3641         ListBuffer<JCTree> defs = new ListBuffer<>();
3642         if (token.kind == MONKEYS_AT)
3643             mods = modifiersOpt();
3644 
3645         if (token.kind == PACKAGE) {
3646             int packagePos = token.pos;
3647             List<JCAnnotation> annotations = List.nil();
3648             seenPackage = true;
3649             if (mods != null) {
3650                 checkNoMods(mods.flags & ~Flags.DEPRECATED);
3651                 annotations = mods.annotations;
3652                 mods = null;
3653             }
3654             nextToken();
3655             JCExpression pid = qualident(false);
3656             accept(SEMI);
3657             JCPackageDecl pd = toP(F.at(packagePos).PackageDecl(annotations, pid));
3658             attach(pd, firstToken.comment(CommentStyle.JAVADOC));
3659             consumedToplevelDoc = true;
3660             defs.append(pd);
3661         }
3662 
3663         boolean checkForImports = true;
3664         boolean firstTypeDecl = true;
3665         while (token.kind != EOF) {
3666             if (token.pos <= endPosTable.errorEndPos) {
3667                 // error recovery
3668                 skip(checkForImports, false, false, false);
3669                 if (token.kind == EOF)
3670                     break;
3671             }
3672             if (checkForImports && mods == null && token.kind == IMPORT) {
3673                 seenImport = true;
3674                 defs.append(importDeclaration());
3675             } else {
3676                 Comment docComment = token.comment(CommentStyle.JAVADOC);
3677                 if (firstTypeDecl && !seenImport && !seenPackage) {
3678                     docComment = firstToken.comment(CommentStyle.JAVADOC);
3679                     consumedToplevelDoc = true;
3680                 }
3681                 if (mods != null || token.kind != SEMI)
3682                     mods = modifiersOpt(mods);
3683                 if (firstTypeDecl && token.kind == IDENTIFIER) {
3684                     ModuleKind kind = ModuleKind.STRONG;
3685                     if (token.name() == names.open) {
3686                         kind = ModuleKind.OPEN;
3687                         nextToken();
3688                     }
3689                     if (token.kind == IDENTIFIER && token.name() == names.module) {
3690                         if (mods != null) {
3691                             checkNoMods(mods.flags & ~Flags.DEPRECATED);
3692                         }
3693                         defs.append(moduleDecl(mods, kind, docComment));
3694                         consumedToplevelDoc = true;
3695                         break;
3696                     } else if (kind != ModuleKind.STRONG) {
3697                         reportSyntaxError(token.pos, Errors.ExpectedModule);
3698                     }
3699                 }
3700                 JCTree def = typeDeclaration(mods, docComment);
3701                 if (def instanceof JCExpressionStatement statement)
3702                     def = statement.expr;
3703                 defs.append(def);
3704                 if (def instanceof JCClassDecl)
3705                     checkForImports = false;
3706                 mods = null;
3707                 firstTypeDecl = false;
3708             }
3709         }
3710         JCTree.JCCompilationUnit toplevel = F.at(firstToken.pos).TopLevel(defs.toList());
3711         if (!consumedToplevelDoc)
3712             attach(toplevel, firstToken.comment(CommentStyle.JAVADOC));
3713         if (defs.isEmpty())
3714             storeEnd(toplevel, S.prevToken().endPos);
3715         if (keepDocComments)
3716             toplevel.docComments = docComments;
3717         if (keepLineMap)
3718             toplevel.lineMap = S.getLineMap();
3719         this.endPosTable.setParser(null); // remove reference to parser
3720         toplevel.endPositions = this.endPosTable;
3721         return toplevel;
3722     }
3723 
3724     JCModuleDecl moduleDecl(JCModifiers mods, ModuleKind kind, Comment dc) {
3725         int pos = token.pos;
3726         checkSourceLevel(Feature.MODULES);
3727 
3728         nextToken();
3729         JCExpression name = qualident(false);
3730         List<JCDirective> directives = null;
3731 
3732         accept(LBRACE);
3733         directives = moduleDirectiveList();
3734         accept(RBRACE);
3735         accept(EOF);
3736 
3737         JCModuleDecl result = toP(F.at(pos).ModuleDef(mods, kind, name, directives));
3738         attach(result, dc);
3739         return result;
3740     }
3741 
3742     List<JCDirective> moduleDirectiveList() {
3743         ListBuffer<JCDirective> defs = new ListBuffer<>();
3744         while (token.kind == IDENTIFIER) {
3745             int pos = token.pos;
3746             if (token.name() == names.requires) {
3747                 nextToken();
3748                 boolean isTransitive = false;
3749                 boolean isStaticPhase = false;
3750             loop:
3751                 while (true) {
3752                     switch (token.kind) {
3753                         case IDENTIFIER:
3754                             if (token.name() == names.transitive && !isTransitive) {
3755                                 Token t1 = S.token(1);
3756                                 if (t1.kind == SEMI || t1.kind == DOT) {
3757                                     break loop;
3758                                 }
3759                                 isTransitive = true;
3760                                 break;
3761                             } else {
3762                                 break loop;
3763                             }
3764                         case STATIC:
3765                             if (isStaticPhase) {
3766                                 log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.RepeatedModifier);
3767                             }
3768                             isStaticPhase = true;
3769                             break;
3770                         default:
3771                             break loop;
3772                     }
3773                     nextToken();
3774                 }
3775                 JCExpression moduleName = qualident(false);
3776                 accept(SEMI);
3777                 defs.append(toP(F.at(pos).Requires(isTransitive, isStaticPhase, moduleName)));
3778             } else if (token.name() == names.exports || token.name() == names.opens) {
3779                 boolean exports = token.name() == names.exports;
3780                 nextToken();
3781                 JCExpression pkgName = qualident(false);
3782                 List<JCExpression> moduleNames = null;
3783                 if (token.kind == IDENTIFIER && token.name() == names.to) {
3784                     nextToken();
3785                     moduleNames = qualidentList(false);
3786                 }
3787                 accept(SEMI);
3788                 JCDirective d;
3789                 if (exports) {
3790                     d = F.at(pos).Exports(pkgName, moduleNames);
3791                 } else {
3792                     d = F.at(pos).Opens(pkgName, moduleNames);
3793                 }
3794                 defs.append(toP(d));
3795             } else if (token.name() == names.provides) {
3796                 nextToken();
3797                 JCExpression serviceName = qualident(false);
3798                 if (token.kind == IDENTIFIER && token.name() == names.with) {
3799                     nextToken();
3800                     List<JCExpression> implNames = qualidentList(false);
3801                     accept(SEMI);
3802                     defs.append(toP(F.at(pos).Provides(serviceName, implNames)));
3803                 } else {
3804                     log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.ExpectedStr("'" + names.with + "'"));
3805                     skip(false, false, false, false);
3806                 }
3807             } else if (token.name() == names.uses) {
3808                 nextToken();
3809                 JCExpression service = qualident(false);
3810                 accept(SEMI);
3811                 defs.append(toP(F.at(pos).Uses(service)));
3812             } else {
3813                 setErrorEndPos(pos);
3814                 reportSyntaxError(pos, Errors.InvalidModuleDirective);
3815                 break;
3816             }
3817         }
3818         return defs.toList();
3819     }
3820 
3821     /** ImportDeclaration = IMPORT [ STATIC ] Ident { "." Ident } [ "." "*" ] ";"
3822      */
3823     protected JCTree importDeclaration() {
3824         int pos = token.pos;
3825         nextToken();
3826         boolean importStatic = false;
3827         if (token.kind == STATIC) {
3828             importStatic = true;
3829             nextToken();
3830         }
3831         JCExpression pid = toP(F.at(token.pos).Ident(ident()));
3832         do {
3833             int pos1 = token.pos;
3834             accept(DOT);
3835             if (token.kind == STAR) {
3836                 pid = to(F.at(pos1).Select(pid, names.asterisk));
3837                 nextToken();
3838                 break;
3839             } else {
3840                 pid = toP(F.at(pos1).Select(pid, ident()));
3841             }
3842         } while (token.kind == DOT);
3843         accept(SEMI);
3844         return toP(F.at(pos).Import(pid, importStatic));
3845     }
3846 
3847     /** TypeDeclaration = ClassOrInterfaceOrEnumDeclaration
3848      *                  | ";"
3849      */
3850     JCTree typeDeclaration(JCModifiers mods, Comment docComment) {
3851         int pos = token.pos;
3852         if (mods == null && token.kind == SEMI) {
3853             nextToken();
3854             return toP(F.at(pos).Skip());
3855         } else {
3856             return classOrRecordOrInterfaceOrEnumDeclaration(modifiersOpt(mods), docComment);
3857         }
3858     }
3859 
3860     /** ClassOrInterfaceOrEnumDeclaration = ModifiersOpt
3861      *           (ClassDeclaration | InterfaceDeclaration | EnumDeclaration)
3862      *  @param mods     Any modifiers starting the class or interface declaration
3863      *  @param dc       The documentation comment for the class, or null.
3864      */
3865     protected JCStatement classOrRecordOrInterfaceOrEnumDeclaration(JCModifiers mods, Comment dc) {
3866         if (token.kind == CLASS) {
3867             return classDeclaration(mods, dc);
3868         } if (isRecordStart()) {
3869             return recordDeclaration(mods, dc);
3870         } else if (token.kind == INTERFACE) {
3871             return interfaceDeclaration(mods, dc);
3872         } else if (token.kind == ENUM) {
3873             return enumDeclaration(mods, dc);
3874         } else {
3875             int pos = token.pos;
3876             List<JCTree> errs;
3877             if (token.kind == IDENTIFIER && token.name() == names.record) {
3878                 checkSourceLevel(Feature.RECORDS);
3879                 JCErroneous erroneousTree = syntaxError(token.pos, List.of(mods), Errors.RecordHeaderExpected);
3880                 return toP(F.Exec(erroneousTree));
3881             } else {
3882                 if (LAX_IDENTIFIER.test(token.kind)) {
3883                     errs = List.of(mods, toP(F.at(pos).Ident(ident())));
3884                     setErrorEndPos(token.pos);
3885                 } else {
3886                     errs = List.of(mods);
3887                 }
3888                 final JCErroneous erroneousTree;
3889                 if (parseModuleInfo) {
3890                     erroneousTree = syntaxError(pos, errs, Errors.ExpectedModuleOrOpen);
3891                 } else {
3892                     if (allowRecords) {
3893                         erroneousTree = syntaxError(pos, errs, Errors.Expected4(CLASS, INTERFACE, ENUM, "record"));
3894                     } else {
3895                         erroneousTree = syntaxError(pos, errs, Errors.Expected3(CLASS, INTERFACE, ENUM));
3896                     }
3897                 }
3898                 return toP(F.Exec(erroneousTree));
3899             }
3900         }
3901     }
3902 
3903     /** ClassDeclaration = CLASS Ident TypeParametersOpt [EXTENDS Type]
3904      *                     [IMPLEMENTS TypeList] ClassBody
3905      *  @param mods    The modifiers starting the class declaration
3906      *  @param dc       The documentation comment for the class, or null.
3907      */
3908     protected JCClassDecl classDeclaration(JCModifiers mods, Comment dc) {
3909         int pos = token.pos;
3910         accept(CLASS);
3911         Name name = typeName();
3912 
3913         List<JCTypeParameter> typarams = typeParametersOpt();
3914 
3915         JCExpression extending = null;
3916         if (token.kind == EXTENDS) {
3917             nextToken();
3918             extending = parseType();
3919         }
3920         List<JCExpression> implementing = List.nil();
3921         if (token.kind == IMPLEMENTS) {
3922             nextToken();
3923             implementing = typeList();
3924         }
3925         List<JCExpression> permitting = permitsClause(mods, "class");
3926         List<JCTree> defs = classInterfaceOrRecordBody(name, false, false);
3927         JCClassDecl result = toP(F.at(pos).ClassDef(
3928             mods, name, typarams, extending, implementing, permitting, defs));
3929         attach(result, dc);
3930         return result;
3931     }
3932 
3933     protected JCClassDecl recordDeclaration(JCModifiers mods, Comment dc) {
3934         int pos = token.pos;
3935         nextToken();
3936         mods.flags |= Flags.RECORD;
3937         Name name = typeName();
3938 
3939         List<JCTypeParameter> typarams = typeParametersOpt();
3940 
3941         List<JCVariableDecl> headerFields = formalParameters(false, true);
3942 
3943         List<JCExpression> implementing = List.nil();
3944         if (token.kind == IMPLEMENTS) {
3945             nextToken();
3946             implementing = typeList();
3947         }
3948         List<JCTree> defs = classInterfaceOrRecordBody(name, false, true);
3949         java.util.List<JCVariableDecl> fields = new ArrayList<>();
3950         for (JCVariableDecl field : headerFields) {
3951             fields.add(field);
3952         }
3953         for (JCTree def : defs) {
3954             if (def.hasTag(METHODDEF)) {
3955                 JCMethodDecl methDef = (JCMethodDecl) def;
3956                 if (methDef.name == names.init && methDef.params.isEmpty() && (methDef.mods.flags & Flags.COMPACT_RECORD_CONSTRUCTOR) != 0) {
3957                     ListBuffer<JCVariableDecl> tmpParams = new ListBuffer<>();
3958                     for (JCVariableDecl param : headerFields) {
3959                         tmpParams.add(F.at(param)
3960                                 // we will get flags plus annotations from the record component
3961                                 .VarDef(F.Modifiers(Flags.PARAMETER | Flags.GENERATED_MEMBER | param.mods.flags & Flags.VARARGS,
3962                                         param.mods.annotations),
3963                                 param.name, param.vartype, null));
3964                     }
3965                     methDef.params = tmpParams.toList();
3966                 }
3967             }
3968         }
3969         for (int i = fields.size() - 1; i >= 0; i--) {
3970             JCVariableDecl field = fields.get(i);
3971             defs = defs.prepend(field);
3972         }
3973         JCClassDecl result = toP(F.at(pos).ClassDef(mods, name, typarams, null, implementing, defs));
3974         attach(result, dc);
3975         return result;
3976     }
3977 
3978     Name typeName() {
3979         int pos = token.pos;
3980         Name name = ident();
3981         Source source = restrictedTypeNameStartingAtSource(name, pos, true);
3982         if (source != null) {
3983             reportSyntaxError(pos, Errors.RestrictedTypeNotAllowed(name, source));
3984         }
3985         return name;
3986     }
3987 
3988     /** InterfaceDeclaration = INTERFACE Ident TypeParametersOpt
3989      *                         [EXTENDS TypeList] InterfaceBody
3990      *  @param mods    The modifiers starting the interface declaration
3991      *  @param dc       The documentation comment for the interface, or null.
3992      */
3993     protected JCClassDecl interfaceDeclaration(JCModifiers mods, Comment dc) {
3994         int pos = token.pos;
3995         accept(INTERFACE);
3996 
3997         Name name = typeName();
3998 
3999         List<JCTypeParameter> typarams = typeParametersOpt();
4000 
4001         List<JCExpression> extending = List.nil();
4002         if (token.kind == EXTENDS) {
4003             nextToken();
4004             extending = typeList();
4005         }
4006         List<JCExpression> permitting = permitsClause(mods, "interface");
4007         List<JCTree> defs;
4008         defs = classInterfaceOrRecordBody(name, true, false);
4009         JCClassDecl result = toP(F.at(pos).ClassDef(
4010             mods, name, typarams, null, extending, permitting, defs));
4011         attach(result, dc);
4012         return result;
4013     }
4014 
4015     List<JCExpression> permitsClause(JCModifiers mods, String classOrInterface) {
4016         if (allowSealedTypes && token.kind == IDENTIFIER && token.name() == names.permits) {
4017             checkSourceLevel(Feature.SEALED_CLASSES);
4018             if ((mods.flags & Flags.SEALED) == 0) {
4019                 log.error(token.pos, Errors.InvalidPermitsClause(Fragments.ClassIsNotSealed(classOrInterface)));
4020             }
4021             nextToken();
4022             return qualidentList(false);
4023         }
4024         return List.nil();
4025     }
4026 
4027     /** EnumDeclaration = ENUM Ident [IMPLEMENTS TypeList] EnumBody
4028      *  @param mods    The modifiers starting the enum declaration
4029      *  @param dc       The documentation comment for the enum, or null.
4030      */
4031     protected JCClassDecl enumDeclaration(JCModifiers mods, Comment dc) {
4032         int pos = token.pos;
4033         accept(ENUM);
4034 
4035         Name name = typeName();
4036 
4037         List<JCExpression> implementing = List.nil();
4038         if (token.kind == IMPLEMENTS) {
4039             nextToken();
4040             implementing = typeList();
4041         }
4042 
4043         List<JCTree> defs = enumBody(name);
4044         mods.flags |= Flags.ENUM;
4045         JCClassDecl result = toP(F.at(pos).
4046             ClassDef(mods, name, List.nil(),
4047                      null, implementing, defs));
4048         attach(result, dc);
4049         return result;
4050     }
4051 
4052     /** EnumBody = "{" { EnumeratorDeclarationList } [","]
4053      *                  [ ";" {ClassBodyDeclaration} ] "}"
4054      */
4055     List<JCTree> enumBody(Name enumName) {
4056         accept(LBRACE);
4057         ListBuffer<JCTree> defs = new ListBuffer<>();
4058         boolean wasSemi = false;
4059         boolean hasStructuralErrors = false;
4060         boolean wasError = false;
4061         if (token.kind == COMMA) {
4062             nextToken();
4063             if (token.kind == SEMI) {
4064                 wasSemi = true;
4065                 nextToken();
4066             } else if (token.kind != RBRACE) {
4067                 reportSyntaxError(S.prevToken().endPos,
4068                                   Errors.Expected2(RBRACE, SEMI));
4069                 wasError = true;
4070             }
4071         }
4072         while (token.kind != RBRACE && token.kind != EOF) {
4073             if (token.kind == SEMI) {
4074                 accept(SEMI);
4075                 wasSemi = true;
4076                 if (token.kind == RBRACE || token.kind == EOF) break;
4077             }
4078             EnumeratorEstimate memberType = estimateEnumeratorOrMember(enumName);
4079             if (memberType == EnumeratorEstimate.UNKNOWN) {
4080                 memberType = wasSemi ? EnumeratorEstimate.MEMBER
4081                                      : EnumeratorEstimate.ENUMERATOR;
4082             }
4083             if (memberType == EnumeratorEstimate.ENUMERATOR) {
4084                 wasError = false;
4085                 if (wasSemi && !hasStructuralErrors) {
4086                     reportSyntaxError(token.pos, Errors.EnumConstantNotExpected);
4087                     hasStructuralErrors = true;
4088                 }
4089                 defs.append(enumeratorDeclaration(enumName));
4090                 if (token.pos <= endPosTable.errorEndPos) {
4091                     // error recovery
4092                    skip(false, true, true, false);
4093                 } else {
4094                     if (token.kind != RBRACE && token.kind != SEMI && token.kind != EOF) {
4095                         if (token.kind == COMMA) {
4096                             nextToken();
4097                         } else {
4098                             setErrorEndPos(token.pos);
4099                             reportSyntaxError(S.prevToken().endPos,
4100                                               Errors.Expected3(COMMA, RBRACE, SEMI));
4101                             wasError = true;
4102                         }
4103                     }
4104                 }
4105             } else {
4106                 if (!wasSemi && !hasStructuralErrors && !wasError) {
4107                     reportSyntaxError(token.pos, Errors.EnumConstantExpected);
4108                     hasStructuralErrors = true;
4109                 }
4110                 wasError = false;
4111                 defs.appendList(classOrInterfaceOrRecordBodyDeclaration(enumName,
4112                                                                 false, false));
4113                 if (token.pos <= endPosTable.errorEndPos) {
4114                     // error recovery
4115                    skip(false, true, true, false);
4116                 }
4117             }
4118         }
4119         accept(RBRACE);
4120         return defs.toList();
4121     }
4122 
4123     private EnumeratorEstimate estimateEnumeratorOrMember(Name enumName) {
4124         // if we are seeing a record declaration inside of an enum we want the same error message as expected for a
4125         // let's say an interface declaration inside an enum
4126         if (token.kind == TokenKind.IDENTIFIER && token.name() != enumName &&
4127                 (!allowRecords || !isRecordStart())) {
4128             Token next = S.token(1);
4129             switch (next.kind) {
4130                 case LPAREN: case LBRACE: case COMMA: case SEMI:
4131                     return EnumeratorEstimate.ENUMERATOR;
4132             }
4133         }
4134         switch (token.kind) {
4135             case IDENTIFIER: case MONKEYS_AT: case LT:
4136                 if (token.kind == IDENTIFIER) {
4137                     if (allowRecords && isRecordStart()) {
4138                         return EnumeratorEstimate.MEMBER;
4139                     }
4140                 }
4141                 return EnumeratorEstimate.UNKNOWN;
4142             default:
4143                 return EnumeratorEstimate.MEMBER;
4144         }
4145     }
4146 
4147     private enum EnumeratorEstimate {
4148         ENUMERATOR,
4149         MEMBER,
4150         UNKNOWN;
4151     }
4152 
4153     /** EnumeratorDeclaration = AnnotationsOpt [TypeArguments] IDENTIFIER [ Arguments ] [ "{" ClassBody "}" ]
4154      */
4155     JCTree enumeratorDeclaration(Name enumName) {
4156         Comment dc = token.comment(CommentStyle.JAVADOC);
4157         int flags = Flags.PUBLIC|Flags.STATIC|Flags.FINAL|Flags.ENUM;
4158         if (token.deprecatedFlag()) {
4159             flags |= Flags.DEPRECATED;
4160         }
4161         int pos = token.pos;
4162         List<JCAnnotation> annotations = annotationsOpt(Tag.ANNOTATION);
4163         JCModifiers mods = F.at(annotations.isEmpty() ? Position.NOPOS : pos).Modifiers(flags, annotations);
4164         List<JCExpression> typeArgs = typeArgumentsOpt();
4165         int identPos = token.pos;
4166         Name name = ident();
4167         int createPos = token.pos;
4168         List<JCExpression> args = (token.kind == LPAREN)
4169             ? arguments() : List.nil();
4170         JCClassDecl body = null;
4171         if (token.kind == LBRACE) {
4172             JCModifiers mods1 = F.at(Position.NOPOS).Modifiers(Flags.ENUM);
4173             List<JCTree> defs = classInterfaceOrRecordBody(names.empty, false, false);
4174             body = toP(F.at(identPos).AnonymousClassDef(mods1, defs));
4175         }
4176         if (args.isEmpty() && body == null)
4177             createPos = identPos;
4178         JCIdent ident = F.at(identPos).Ident(enumName);
4179         JCNewClass create = F.at(createPos).NewClass(null, typeArgs, ident, args, body);
4180         if (createPos != identPos)
4181             storeEnd(create, S.prevToken().endPos);
4182         ident = F.at(identPos).Ident(enumName);
4183         JCTree result = toP(F.at(pos).VarDef(mods, name, ident, create));
4184         attach(result, dc);
4185         return result;
4186     }
4187 
4188     /** TypeList = Type {"," Type}
4189      */
4190     List<JCExpression> typeList() {
4191         ListBuffer<JCExpression> ts = new ListBuffer<>();
4192         ts.append(parseType());
4193         while (token.kind == COMMA) {
4194             nextToken();
4195             ts.append(parseType());
4196         }
4197         return ts.toList();
4198     }
4199 
4200     /** ClassBody     = "{" {ClassBodyDeclaration} "}"
4201      *  InterfaceBody = "{" {InterfaceBodyDeclaration} "}"
4202      */
4203     List<JCTree> classInterfaceOrRecordBody(Name className, boolean isInterface, boolean isRecord) {
4204         accept(LBRACE);
4205         if (token.pos <= endPosTable.errorEndPos) {
4206             // error recovery
4207             skip(false, true, false, false);
4208             if (token.kind == LBRACE)
4209                 nextToken();
4210             else
4211                 return List.nil();
4212         }
4213         ListBuffer<JCTree> defs = new ListBuffer<>();
4214         while (token.kind != RBRACE && token.kind != EOF) {
4215             defs.appendList(classOrInterfaceOrRecordBodyDeclaration(className, isInterface, isRecord));
4216             if (token.pos <= endPosTable.errorEndPos) {
4217                // error recovery
4218                skip(false, true, true, false);
4219            }
4220         }
4221         accept(RBRACE);
4222         return defs.toList();
4223     }
4224 
4225     /** ClassBodyDeclaration =
4226      *      ";"
4227      *    | [STATIC] Block
4228      *    | ModifiersOpt
4229      *      ( Type Ident
4230      *        ( VariableDeclaratorsRest ";" | MethodDeclaratorRest )
4231      *      | VOID Ident VoidMethodDeclaratorRest
4232      *      | TypeParameters [Annotations]
4233      *        ( Type Ident MethodDeclaratorRest
4234      *        | VOID Ident VoidMethodDeclaratorRest
4235      *        )
4236      *      | Ident ConstructorDeclaratorRest
4237      *      | TypeParameters Ident ConstructorDeclaratorRest
4238      *      | ClassOrInterfaceOrEnumDeclaration
4239      *      )
4240      *  InterfaceBodyDeclaration =
4241      *      ";"
4242      *    | ModifiersOpt
4243      *      ( Type Ident
4244      *        ( ConstantDeclaratorsRest ";" | MethodDeclaratorRest )
4245      *      | VOID Ident MethodDeclaratorRest
4246      *      | TypeParameters [Annotations]
4247      *        ( Type Ident MethodDeclaratorRest
4248      *        | VOID Ident VoidMethodDeclaratorRest
4249      *        )
4250      *      | ClassOrInterfaceOrEnumDeclaration
4251      *      )
4252      *
4253      */
4254     protected List<JCTree> classOrInterfaceOrRecordBodyDeclaration(Name className, boolean isInterface, boolean isRecord) {
4255         if (token.kind == SEMI) {
4256             nextToken();
4257             return List.nil();
4258         } else {
4259             Comment dc = token.comment(CommentStyle.JAVADOC);
4260             int pos = token.pos;
4261             JCModifiers mods = modifiersOpt();
4262             if (token.kind == CLASS ||
4263                 allowRecords && isRecordStart() ||
4264                 token.kind == INTERFACE ||
4265                 token.kind == ENUM) {
4266                 return List.of(classOrRecordOrInterfaceOrEnumDeclaration(mods, dc));
4267             } else if (token.kind == LBRACE &&
4268                        (mods.flags & Flags.StandardFlags & ~Flags.STATIC) == 0 &&
4269                        mods.annotations.isEmpty()) {
4270                 if (isInterface) {
4271                     log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.InitializerNotAllowed);
4272                 } else if (isRecord && (mods.flags & Flags.STATIC) == 0) {
4273                     log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.InstanceInitializerNotAllowedInRecords);
4274                 }
4275                 return List.of(block(pos, mods.flags));
4276             } else {
4277                 pos = token.pos;
4278                 List<JCTypeParameter> typarams = typeParametersOpt();
4279                 // if there are type parameters but no modifiers, save the start
4280                 // position of the method in the modifiers.
4281                 if (typarams.nonEmpty() && mods.pos == Position.NOPOS) {
4282                     mods.pos = pos;
4283                     storeEnd(mods, pos);
4284                 }
4285                 List<JCAnnotation> annosAfterParams = annotationsOpt(Tag.ANNOTATION);
4286 
4287                 if (annosAfterParams.nonEmpty()) {
4288                     checkSourceLevel(annosAfterParams.head.pos, Feature.ANNOTATIONS_AFTER_TYPE_PARAMS);
4289                     mods.annotations = mods.annotations.appendList(annosAfterParams);
4290                     if (mods.pos == Position.NOPOS)
4291                         mods.pos = mods.annotations.head.pos;
4292                 }
4293 
4294                 Token tk = token;
4295                 pos = token.pos;
4296                 JCExpression type;
4297                 boolean isVoid = token.kind == VOID;
4298                 if (isVoid) {
4299                     type = to(F.at(pos).TypeIdent(TypeTag.VOID));
4300                     nextToken();
4301                 } else {
4302                     // method returns types are un-annotated types
4303                     type = unannotatedType(false);
4304                 }
4305                 if ((token.kind == LPAREN && !isInterface ||
4306                         isRecord && token.kind == LBRACE) && type.hasTag(IDENT)) {
4307                     if (isInterface || tk.name() != className)
4308                         log.error(DiagnosticFlag.SYNTAX, pos, Errors.InvalidMethDeclRetTypeReq);
4309                     else if (annosAfterParams.nonEmpty())
4310                         illegal(annosAfterParams.head.pos);
4311                     if (isRecord && token.kind == LBRACE) {
4312                         mods.flags |= Flags.COMPACT_RECORD_CONSTRUCTOR;
4313                     }
4314                     return List.of(methodDeclaratorRest(
4315                         pos, mods, null, names.init, typarams,
4316                         isInterface, true, isRecord, dc));
4317                 } else if (isRecord && type.hasTag(IDENT) && token.kind == THROWS) {
4318                     // trying to define a compact constructor with a throws clause
4319                     log.error(DiagnosticFlag.SYNTAX, token.pos,
4320                             Errors.InvalidCanonicalConstructorInRecord(
4321                                     Fragments.Compact,
4322                                     className,
4323                                     Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(Fragments.Compact)));
4324                     skip(false, true, false, false);
4325                     return List.of(methodDeclaratorRest(
4326                             pos, mods, null, names.init, typarams,
4327                             isInterface, true, isRecord, dc));
4328                 } else {
4329                     pos = token.pos;
4330                     Name name = ident();
4331                     if (token.kind == LPAREN) {
4332                         return List.of(methodDeclaratorRest(
4333                             pos, mods, type, name, typarams,
4334                             isInterface, isVoid, false, dc));
4335                     } else if (!isVoid && typarams.isEmpty()) {
4336                         if (!isRecord || (isRecord && (mods.flags & Flags.STATIC) != 0)) {
4337                         List<JCTree> defs =
4338                             variableDeclaratorsRest(pos, mods, type, name, isInterface, dc,
4339                                                     new ListBuffer<JCTree>(), false).toList();
4340                         accept(SEMI);
4341                         storeEnd(defs.last(), S.prevToken().endPos);
4342                         return defs;
4343                     } else {
4344                             int errPos = pos;
4345                             variableDeclaratorsRest(pos, mods, type, name, isInterface, dc,
4346                                     new ListBuffer<JCTree>(), false).toList();
4347                             accept(SEMI);
4348                             return List.of(syntaxError(errPos, null, Errors.RecordCannotDeclareInstanceFields));
4349                         }
4350                     } else {
4351                         pos = token.pos;
4352                         List<JCTree> err;
4353                         if (isVoid || typarams.nonEmpty()) {
4354                             JCMethodDecl m =
4355                                     toP(F.at(pos).MethodDef(mods, name, type, typarams,
4356                                                             List.nil(), List.nil(), null, null));
4357                             attach(m, dc);
4358                             err = List.of(m);
4359                         } else {
4360                             err = List.nil();
4361                         }
4362                         return List.of(syntaxError(token.pos, err, Errors.Expected(LPAREN)));
4363                     }
4364                 }
4365             }
4366         }
4367     }
4368 
4369     protected boolean isRecordStart() {
4370         if (token.kind == IDENTIFIER && token.name() == names.record &&
4371             (peekToken(TokenKind.IDENTIFIER, TokenKind.LPAREN) ||
4372              peekToken(TokenKind.IDENTIFIER, TokenKind.EOF) ||
4373              peekToken(TokenKind.IDENTIFIER, TokenKind.LT))) {
4374             checkSourceLevel(Feature.RECORDS);
4375             return true;
4376         } else {
4377             return false;
4378         }
4379     }
4380 
4381     protected boolean isNonSealedClassStart(boolean local) {
4382         if (isNonSealedIdentifier(token, 0)) {
4383             Token next = S.token(3);
4384             return allowedAfterSealedOrNonSealed(next, local, true);
4385         }
4386         return false;
4387     }
4388 
4389     protected boolean isNonSealedIdentifier(Token someToken, int lookAheadOffset) {
4390         if (someToken.name() == names.non && peekToken(lookAheadOffset, TokenKind.SUB, TokenKind.IDENTIFIER)) {
4391             Token tokenSub = S.token(lookAheadOffset + 1);
4392             Token tokenSealed = S.token(lookAheadOffset + 2);
4393             if (someToken.endPos == tokenSub.pos &&
4394                     tokenSub.endPos == tokenSealed.pos &&
4395                     tokenSealed.name() == names.sealed) {
4396                 checkSourceLevel(Feature.SEALED_CLASSES);
4397                 return true;
4398             }
4399         }
4400         return false;
4401     }
4402 
4403     protected boolean isSealedClassStart(boolean local) {
4404         if (token.name() == names.sealed) {
4405             Token next = S.token(1);
4406             if (allowedAfterSealedOrNonSealed(next, local, false)) {
4407                 checkSourceLevel(Feature.SEALED_CLASSES);
4408                 return true;
4409             }
4410         }
4411         return false;
4412     }
4413 
4414     private boolean allowedAfterSealedOrNonSealed(Token next, boolean local, boolean currentIsNonSealed) {
4415         return local ?
4416             switch (next.kind) {
4417                 case MONKEYS_AT -> {
4418                     Token afterNext = S.token(2);
4419                     yield afterNext.kind != INTERFACE || currentIsNonSealed;
4420                 }
4421                 case ABSTRACT, FINAL, STRICTFP, CLASS, INTERFACE, ENUM -> true;
4422                 default -> false;
4423             } :
4424             switch (next.kind) {
4425                 case MONKEYS_AT -> {
4426                     Token afterNext = S.token(2);
4427                     yield afterNext.kind != INTERFACE || currentIsNonSealed;
4428                 }
4429                 case PUBLIC, PROTECTED, PRIVATE, ABSTRACT, STATIC, FINAL, STRICTFP, CLASS, INTERFACE, ENUM -> true;
4430                 case IDENTIFIER -> isNonSealedIdentifier(next, currentIsNonSealed ? 3 : 1) || next.name() == names.sealed;
4431                 default -> false;
4432             };
4433     }
4434 
4435     /** MethodDeclaratorRest =
4436      *      FormalParameters BracketsOpt [THROWS TypeList] ( MethodBody | [DEFAULT AnnotationValue] ";")
4437      *  VoidMethodDeclaratorRest =
4438      *      FormalParameters [THROWS TypeList] ( MethodBody | ";")
4439      *  ConstructorDeclaratorRest =
4440      *      "(" FormalParameterListOpt ")" [THROWS TypeList] MethodBody
4441      */
4442     protected JCTree methodDeclaratorRest(int pos,
4443                               JCModifiers mods,
4444                               JCExpression type,
4445                               Name name,
4446                               List<JCTypeParameter> typarams,
4447                               boolean isInterface, boolean isVoid,
4448                               boolean isRecord,
4449                               Comment dc) {
4450         if (isInterface) {
4451             if ((mods.flags & Flags.STATIC) != 0) {
4452                 checkSourceLevel(Feature.STATIC_INTERFACE_METHODS);
4453             }
4454             if ((mods.flags & Flags.PRIVATE) != 0) {
4455                 checkSourceLevel(Feature.PRIVATE_INTERFACE_METHODS);
4456             }
4457         }
4458         JCVariableDecl prevReceiverParam = this.receiverParam;
4459         try {
4460             this.receiverParam = null;
4461             // Parsing formalParameters sets the receiverParam, if present
4462             List<JCVariableDecl> params = List.nil();
4463             List<JCExpression> thrown = List.nil();
4464             if (!isRecord || name != names.init || token.kind == LPAREN) {
4465                 params = formalParameters();
4466                 if (!isVoid) type = bracketsOpt(type);
4467                 if (token.kind == THROWS) {
4468                     nextToken();
4469                     thrown = qualidentList(true);
4470                 }
4471             }
4472             JCBlock body = null;
4473             JCExpression defaultValue;
4474             if (token.kind == LBRACE) {
4475                 body = block();
4476                 defaultValue = null;
4477             } else {
4478                 if (token.kind == DEFAULT) {
4479                     accept(DEFAULT);
4480                     defaultValue = annotationValue();
4481                 } else {
4482                     defaultValue = null;
4483                 }
4484                 accept(SEMI);
4485                 if (token.pos <= endPosTable.errorEndPos) {
4486                     // error recovery
4487                     skip(false, true, false, false);
4488                     if (token.kind == LBRACE) {
4489                         body = block();
4490                     }
4491                 }
4492             }
4493 
4494             JCMethodDecl result =
4495                     toP(F.at(pos).MethodDef(mods, name, type, typarams,
4496                                             receiverParam, params, thrown,
4497                                             body, defaultValue));
4498             attach(result, dc);
4499             return result;
4500         } finally {
4501             this.receiverParam = prevReceiverParam;
4502         }
4503     }
4504 
4505     /** QualidentList = [Annotations] Qualident {"," [Annotations] Qualident}
4506      */
4507     List<JCExpression> qualidentList(boolean allowAnnos) {
4508         ListBuffer<JCExpression> ts = new ListBuffer<>();
4509 
4510         List<JCAnnotation> typeAnnos = allowAnnos ? typeAnnotationsOpt() : List.nil();
4511         JCExpression qi = qualident(allowAnnos);
4512         if (!typeAnnos.isEmpty()) {
4513             JCExpression at = insertAnnotationsToMostInner(qi, typeAnnos, false);
4514             ts.append(at);
4515         } else {
4516             ts.append(qi);
4517         }
4518         while (token.kind == COMMA) {
4519             nextToken();
4520 
4521             typeAnnos = allowAnnos ? typeAnnotationsOpt() : List.nil();
4522             qi = qualident(allowAnnos);
4523             if (!typeAnnos.isEmpty()) {
4524                 JCExpression at = insertAnnotationsToMostInner(qi, typeAnnos, false);
4525                 ts.append(at);
4526             } else {
4527                 ts.append(qi);
4528             }
4529         }
4530         return ts.toList();
4531     }
4532 
4533     /**
4534      *  {@literal
4535      *  TypeParametersOpt = ["<" TypeParameter {"," TypeParameter} ">"]
4536      *  }
4537      */
4538     protected List<JCTypeParameter> typeParametersOpt() {
4539         if (token.kind == LT) {
4540             ListBuffer<JCTypeParameter> typarams = new ListBuffer<>();
4541             nextToken();
4542             typarams.append(typeParameter());
4543             while (token.kind == COMMA) {
4544                 nextToken();
4545                 typarams.append(typeParameter());
4546             }
4547             accept(GT);
4548             return typarams.toList();
4549         } else {
4550             return List.nil();
4551         }
4552     }
4553 
4554     /**
4555      *  {@literal
4556      *  TypeParameter = [Annotations] TypeVariable [TypeParameterBound]
4557      *  TypeParameterBound = EXTENDS Type {"&" Type}
4558      *  TypeVariable = Ident
4559      *  }
4560      */
4561     JCTypeParameter typeParameter() {
4562         int pos = token.pos;
4563         List<JCAnnotation> annos = typeAnnotationsOpt();
4564         Name name = typeName();
4565         ListBuffer<JCExpression> bounds = new ListBuffer<>();
4566         if (token.kind == EXTENDS) {
4567             nextToken();
4568             bounds.append(parseType());
4569             while (token.kind == AMP) {
4570                 nextToken();
4571                 bounds.append(parseType());
4572             }
4573         }
4574         return toP(F.at(pos).TypeParameter(name, bounds.toList(), annos));
4575     }
4576 
4577     /** FormalParameters = "(" [ FormalParameterList ] ")"
4578      *  FormalParameterList = [ FormalParameterListNovarargs , ] LastFormalParameter
4579      *  FormalParameterListNovarargs = [ FormalParameterListNovarargs , ] FormalParameter
4580      */
4581     List<JCVariableDecl> formalParameters() {
4582         return formalParameters(false, false);
4583     }
4584     List<JCVariableDecl> formalParameters(boolean lambdaParameters, boolean recordComponents) {
4585         ListBuffer<JCVariableDecl> params = new ListBuffer<>();
4586         JCVariableDecl lastParam;
4587         accept(LPAREN);
4588         if (token.kind != RPAREN) {
4589             this.allowThisIdent = !lambdaParameters && !recordComponents;
4590             lastParam = formalParameter(lambdaParameters, recordComponents);
4591             if (lastParam.nameexpr != null) {
4592                 this.receiverParam = lastParam;
4593             } else {
4594                 params.append(lastParam);
4595             }
4596             this.allowThisIdent = false;
4597             while (token.kind == COMMA) {
4598                 if ((lastParam.mods.flags & Flags.VARARGS) != 0) {
4599                     log.error(DiagnosticFlag.SYNTAX, lastParam, Errors.VarargsMustBeLast);
4600                 }
4601                 nextToken();
4602                 params.append(lastParam = formalParameter(lambdaParameters, recordComponents));
4603             }
4604         }
4605         if (token.kind == RPAREN) {
4606             nextToken();
4607         } else {
4608             setErrorEndPos(token.pos);
4609             reportSyntaxError(S.prevToken().endPos, Errors.Expected3(COMMA, RPAREN, LBRACKET));
4610         }
4611         return params.toList();
4612     }
4613 
4614     List<JCVariableDecl> implicitParameters(boolean hasParens) {
4615         if (hasParens) {
4616             accept(LPAREN);
4617         }
4618         ListBuffer<JCVariableDecl> params = new ListBuffer<>();
4619         if (token.kind != RPAREN && token.kind != ARROW) {
4620             params.append(implicitParameter());
4621             while (token.kind == COMMA) {
4622                 nextToken();
4623                 params.append(implicitParameter());
4624             }
4625         }
4626         if (hasParens) {
4627             accept(RPAREN);
4628         }
4629         return params.toList();
4630     }
4631 
4632     JCModifiers optFinal(long flags) {
4633         JCModifiers mods = modifiersOpt();
4634         checkNoMods(mods.flags & ~(Flags.FINAL | Flags.DEPRECATED));
4635         mods.flags |= flags;
4636         return mods;
4637     }
4638 
4639     /**
4640      * Inserts the annotations (and possibly a new array level)
4641      * to the left-most type in an array or nested type.
4642      *
4643      * When parsing a type like {@code @B Outer.Inner @A []}, the
4644      * {@code @A} annotation should target the array itself, while
4645      * {@code @B} targets the nested type {@code Outer}.
4646      *
4647      * Currently the parser parses the annotation first, then
4648      * the array, and then inserts the annotation to the left-most
4649      * nested type.
4650      *
4651      * When {@code createNewLevel} is true, then a new array
4652      * level is inserted as the most inner type, and have the
4653      * annotations target it.  This is useful in the case of
4654      * varargs, e.g. {@code String @A [] @B ...}, as the parser
4655      * first parses the type {@code String @A []} then inserts
4656      * a new array level with {@code @B} annotation.
4657      */
4658     private JCExpression insertAnnotationsToMostInner(
4659             JCExpression type, List<JCAnnotation> annos,
4660             boolean createNewLevel) {
4661         int origEndPos = getEndPos(type);
4662         JCExpression mostInnerType = type;
4663         JCArrayTypeTree mostInnerArrayType = null;
4664         while (TreeInfo.typeIn(mostInnerType).hasTag(TYPEARRAY)) {
4665             mostInnerArrayType = (JCArrayTypeTree) TreeInfo.typeIn(mostInnerType);
4666             mostInnerType = mostInnerArrayType.elemtype;
4667         }
4668 
4669         if (createNewLevel) {
4670             mostInnerType = to(F.at(token.pos).TypeArray(mostInnerType));
4671             origEndPos = getEndPos(mostInnerType);
4672         }
4673 
4674         JCExpression mostInnerTypeToReturn = mostInnerType;
4675         if (annos.nonEmpty()) {
4676             JCExpression lastToModify = mostInnerType;
4677 
4678             while (TreeInfo.typeIn(mostInnerType).hasTag(SELECT) ||
4679                     TreeInfo.typeIn(mostInnerType).hasTag(TYPEAPPLY)) {
4680                 while (TreeInfo.typeIn(mostInnerType).hasTag(SELECT)) {
4681                     lastToModify = mostInnerType;
4682                     mostInnerType = ((JCFieldAccess) TreeInfo.typeIn(mostInnerType)).getExpression();
4683                 }
4684                 while (TreeInfo.typeIn(mostInnerType).hasTag(TYPEAPPLY)) {
4685                     lastToModify = mostInnerType;
4686                     mostInnerType = ((JCTypeApply) TreeInfo.typeIn(mostInnerType)).clazz;
4687                 }
4688             }
4689 
4690             mostInnerType = F.at(annos.head.pos).AnnotatedType(annos, mostInnerType);
4691 
4692             if (TreeInfo.typeIn(lastToModify).hasTag(TYPEAPPLY)) {
4693                 ((JCTypeApply) TreeInfo.typeIn(lastToModify)).clazz = mostInnerType;
4694             } else if (TreeInfo.typeIn(lastToModify).hasTag(SELECT)) {
4695                 ((JCFieldAccess) TreeInfo.typeIn(lastToModify)).selected = mostInnerType;
4696             } else {
4697                 // We never saw a SELECT or TYPEAPPLY, return the annotated type.
4698                 mostInnerTypeToReturn = mostInnerType;
4699             }
4700         }
4701 
4702         if (mostInnerArrayType == null) {
4703             return mostInnerTypeToReturn;
4704         } else {
4705             mostInnerArrayType.elemtype = mostInnerTypeToReturn;
4706             storeEnd(type, origEndPos);
4707             return type;
4708         }
4709     }
4710 
4711     /** FormalParameter = { FINAL | '@' Annotation } Type VariableDeclaratorId
4712      *  LastFormalParameter = { FINAL | '@' Annotation } Type '...' Ident | FormalParameter
4713      */
4714     protected JCVariableDecl formalParameter(boolean lambdaParameter, boolean recordComponent) {
4715         JCModifiers mods = !recordComponent ? optFinal(Flags.PARAMETER) : modifiersOpt();
4716         if (recordComponent && mods.flags != 0) {
4717             log.error(mods.pos, Errors.RecordCantDeclareFieldModifiers);
4718         }
4719         if (recordComponent) {
4720             mods.flags |= Flags.RECORD | Flags.FINAL | Flags.PRIVATE | Flags.GENERATED_MEMBER;
4721         }
4722         // need to distinguish between vararg annos and array annos
4723         // look at typeAnnotationsPushedBack comment
4724         this.permitTypeAnnotationsPushBack = true;
4725         JCExpression type = parseType(lambdaParameter);
4726         this.permitTypeAnnotationsPushBack = false;
4727 
4728         if (token.kind == ELLIPSIS) {
4729             List<JCAnnotation> varargsAnnos = typeAnnotationsPushedBack;
4730             typeAnnotationsPushedBack = List.nil();
4731             mods.flags |= Flags.VARARGS;
4732             // insert var arg type annotations
4733             type = insertAnnotationsToMostInner(type, varargsAnnos, true);
4734             nextToken();
4735         } else {
4736             // if not a var arg, then typeAnnotationsPushedBack should be null
4737             if (typeAnnotationsPushedBack.nonEmpty()) {
4738                 reportSyntaxError(typeAnnotationsPushedBack.head.pos, Errors.IllegalStartOfType);
4739             }
4740             typeAnnotationsPushedBack = List.nil();
4741         }
4742         return variableDeclaratorId(mods, type, lambdaParameter, recordComponent);
4743     }
4744 
4745     protected JCVariableDecl implicitParameter() {
4746         JCModifiers mods = F.at(token.pos).Modifiers(Flags.PARAMETER);
4747         return variableDeclaratorId(mods, null, true, false);
4748     }
4749 
4750 /* ---------- auxiliary methods -------------- */
4751     /** Check that given tree is a legal expression statement.
4752      */
4753     protected JCExpression checkExprStat(JCExpression t) {
4754         if (!TreeInfo.isExpressionStatement(t)) {
4755             JCExpression ret = F.at(t.pos).Erroneous(List.<JCTree>of(t));
4756             log.error(DiagnosticFlag.SYNTAX, ret, Errors.NotStmt);
4757             return ret;
4758         } else {
4759             return t;
4760         }
4761     }
4762 
4763     /** Return precedence of operator represented by token,
4764      *  -1 if token is not a binary operator. @see TreeInfo.opPrec
4765      */
4766     static int prec(TokenKind token) {
4767         JCTree.Tag oc = optag(token);
4768         return (oc != NO_TAG) ? TreeInfo.opPrec(oc) : -1;
4769     }
4770 
4771     /**
4772      * Return the lesser of two positions, making allowance for either one
4773      * being unset.
4774      */
4775     static int earlier(int pos1, int pos2) {
4776         if (pos1 == Position.NOPOS)
4777             return pos2;
4778         if (pos2 == Position.NOPOS)
4779             return pos1;
4780         return (pos1 < pos2 ? pos1 : pos2);
4781     }
4782 
4783     /** Return operation tag of binary operator represented by token,
4784      *  No_TAG if token is not a binary operator.
4785      */
4786     static JCTree.Tag optag(TokenKind token) {
4787         switch (token) {
4788         case BARBAR:
4789             return OR;
4790         case AMPAMP:
4791             return AND;
4792         case BAR:
4793             return BITOR;
4794         case BAREQ:
4795             return BITOR_ASG;
4796         case CARET:
4797             return BITXOR;
4798         case CARETEQ:
4799             return BITXOR_ASG;
4800         case AMP:
4801             return BITAND;
4802         case AMPEQ:
4803             return BITAND_ASG;
4804         case EQEQ:
4805             return JCTree.Tag.EQ;
4806         case BANGEQ:
4807             return NE;
4808         case LT:
4809             return JCTree.Tag.LT;
4810         case GT:
4811             return JCTree.Tag.GT;
4812         case LTEQ:
4813             return LE;
4814         case GTEQ:
4815             return GE;
4816         case LTLT:
4817             return SL;
4818         case LTLTEQ:
4819             return SL_ASG;
4820         case GTGT:
4821             return SR;
4822         case GTGTEQ:
4823             return SR_ASG;
4824         case GTGTGT:
4825             return USR;
4826         case GTGTGTEQ:
4827             return USR_ASG;
4828         case PLUS:
4829             return JCTree.Tag.PLUS;
4830         case PLUSEQ:
4831             return PLUS_ASG;
4832         case SUB:
4833             return MINUS;
4834         case SUBEQ:
4835             return MINUS_ASG;
4836         case STAR:
4837             return MUL;
4838         case STAREQ:
4839             return MUL_ASG;
4840         case SLASH:
4841             return DIV;
4842         case SLASHEQ:
4843             return DIV_ASG;
4844         case PERCENT:
4845             return MOD;
4846         case PERCENTEQ:
4847             return MOD_ASG;
4848         case INSTANCEOF:
4849             return TYPETEST;
4850         default:
4851             return NO_TAG;
4852         }
4853     }
4854 
4855     /** Return operation tag of unary operator represented by token,
4856      *  No_TAG if token is not a binary operator.
4857      */
4858     static JCTree.Tag unoptag(TokenKind token) {
4859         switch (token) {
4860         case PLUS:
4861             return POS;
4862         case SUB:
4863             return NEG;
4864         case BANG:
4865             return NOT;
4866         case TILDE:
4867             return COMPL;
4868         case PLUSPLUS:
4869             return PREINC;
4870         case SUBSUB:
4871             return PREDEC;
4872         default:
4873             return NO_TAG;
4874         }
4875     }
4876 
4877     /** Return type tag of basic type represented by token,
4878      *  NONE if token is not a basic type identifier.
4879      */
4880     static TypeTag typetag(TokenKind token) {
4881         switch (token) {
4882         case BYTE:
4883             return TypeTag.BYTE;
4884         case CHAR:
4885             return TypeTag.CHAR;
4886         case SHORT:
4887             return TypeTag.SHORT;
4888         case INT:
4889             return TypeTag.INT;
4890         case LONG:
4891             return TypeTag.LONG;
4892         case FLOAT:
4893             return TypeTag.FLOAT;
4894         case DOUBLE:
4895             return TypeTag.DOUBLE;
4896         case BOOLEAN:
4897             return TypeTag.BOOLEAN;
4898         default:
4899             return TypeTag.NONE;
4900         }
4901     }
4902 
4903     void checkSourceLevel(Feature feature) {
4904         checkSourceLevel(token.pos, feature);
4905     }
4906 
4907     protected void checkSourceLevel(int pos, Feature feature) {
4908         if (preview.isPreview(feature) && !preview.isEnabled()) {
4909             //preview feature without --preview flag, error
4910             log.error(DiagnosticFlag.SOURCE_LEVEL, pos, preview.disabledError(feature));
4911         } else if (!feature.allowedInSource(source)) {
4912             //incompatible source level, error
4913             log.error(DiagnosticFlag.SOURCE_LEVEL, pos, feature.error(source.name));
4914         } else if (preview.isPreview(feature)) {
4915             //use of preview feature, warn
4916             preview.warnPreview(pos, feature);
4917         }
4918     }
4919 
4920     /*
4921      * a functional source tree and end position mappings
4922      */
4923     protected static class SimpleEndPosTable extends AbstractEndPosTable {
4924 
4925         private final IntHashTable endPosMap;
4926 
4927         SimpleEndPosTable(JavacParser parser) {
4928             super(parser);
4929             endPosMap = new IntHashTable();
4930         }
4931 
4932         public void storeEnd(JCTree tree, int endpos) {
4933             endPosMap.put(tree, errorEndPos > endpos ? errorEndPos : endpos);
4934         }
4935 
4936         protected <T extends JCTree> T to(T t) {
4937             storeEnd(t, parser.token.endPos);
4938             return t;
4939         }
4940 
4941         protected <T extends JCTree> T toP(T t) {
4942             storeEnd(t, parser.S.prevToken().endPos);
4943             return t;
4944         }
4945 
4946         public int getEndPos(JCTree tree) {
4947             int value = endPosMap.get(tree);
4948             // As long as Position.NOPOS==-1, this just returns value.
4949             return (value == -1) ? Position.NOPOS : value;
4950         }
4951 
4952         public int replaceTree(JCTree oldTree, JCTree newTree) {
4953             int pos = endPosMap.remove(oldTree);
4954             if (pos != -1) {
4955                 storeEnd(newTree, pos);
4956                 return pos;
4957             }
4958             return Position.NOPOS;
4959         }
4960     }
4961 
4962     /*
4963      * a default skeletal implementation without any mapping overhead.
4964      */
4965     protected static class EmptyEndPosTable extends AbstractEndPosTable {
4966 
4967         EmptyEndPosTable(JavacParser parser) {
4968             super(parser);
4969         }
4970 
4971         public void storeEnd(JCTree tree, int endpos) { /* empty */ }
4972 
4973         protected <T extends JCTree> T to(T t) {
4974             return t;
4975         }
4976 
4977         protected <T extends JCTree> T toP(T t) {
4978             return t;
4979         }
4980 
4981         public int getEndPos(JCTree tree) {
4982             return Position.NOPOS;
4983         }
4984 
4985         public int replaceTree(JCTree oldTree, JCTree newTree) {
4986             return Position.NOPOS;
4987         }
4988 
4989     }
4990 
4991     protected static abstract class AbstractEndPosTable implements EndPosTable {
4992         /**
4993          * The current parser.
4994          */
4995         protected JavacParser parser;
4996 
4997         /**
4998          * Store the last error position.
4999          */
5000         public int errorEndPos = Position.NOPOS;
5001 
5002         public AbstractEndPosTable(JavacParser parser) {
5003             this.parser = parser;
5004         }
5005 
5006         /**
5007          * Store current token's ending position for a tree, the value of which
5008          * will be the greater of last error position and the ending position of
5009          * the current token.
5010          * @param t The tree.
5011          */
5012         protected abstract <T extends JCTree> T to(T t);
5013 
5014         /**
5015          * Store current token's ending position for a tree, the value of which
5016          * will be the greater of last error position and the ending position of
5017          * the previous token.
5018          * @param t The tree.
5019          */
5020         protected abstract <T extends JCTree> T toP(T t);
5021 
5022         /**
5023          * Set the error position during the parsing phases, the value of which
5024          * will be set only if it is greater than the last stored error position.
5025          * @param errPos The error position
5026          */
5027         public void setErrorEndPos(int errPos) {
5028             if (errPos > errorEndPos) {
5029                 errorEndPos = errPos;
5030             }
5031         }
5032 
5033         public void setParser(JavacParser parser) {
5034             this.parser = parser;
5035         }
5036     }
5037 }