1 /*
   2  * Copyright (c) 1999, 2023, 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.tree;
  27 
  28 
  29 
  30 import com.sun.source.tree.Tree;
  31 import com.sun.source.util.TreePath;
  32 import com.sun.tools.javac.code.*;
  33 import com.sun.tools.javac.code.Symbol.RecordComponent;
  34 import com.sun.tools.javac.comp.AttrContext;
  35 import com.sun.tools.javac.comp.Env;
  36 import com.sun.tools.javac.tree.JCTree.*;
  37 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
  38 import com.sun.tools.javac.util.*;
  39 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  40 
  41 import static com.sun.tools.javac.code.Flags.*;
  42 import static com.sun.tools.javac.code.Kinds.Kind.*;
  43 import com.sun.tools.javac.code.Symbol.VarSymbol;
  44 import static com.sun.tools.javac.code.TypeTag.BOOLEAN;
  45 import static com.sun.tools.javac.code.TypeTag.BOT;
  46 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  47 import static com.sun.tools.javac.tree.JCTree.Tag.BLOCK;
  48 import static com.sun.tools.javac.tree.JCTree.Tag.SYNCHRONIZED;
  49 
  50 import javax.lang.model.element.ElementKind;
  51 import javax.tools.JavaFileObject;
  52 
  53 import java.util.function.Predicate;
  54 import java.util.function.ToIntFunction;
  55 
  56 import static com.sun.tools.javac.tree.JCTree.JCOperatorExpression.OperandPos.LEFT;
  57 import static com.sun.tools.javac.tree.JCTree.JCOperatorExpression.OperandPos.RIGHT;
  58 
  59 /** Utility class containing inspector methods for trees.
  60  *
  61  *  <p><b>This is NOT part of any supported API.
  62  *  If you write code that depends on this, you do so at your own risk.
  63  *  This code and its internal interfaces are subject to change or
  64  *  deletion without notice.</b>
  65  */
  66 public class TreeInfo {
  67 
  68     public static List<JCExpression> args(JCTree t) {
  69         switch (t.getTag()) {
  70             case APPLY:
  71                 return ((JCMethodInvocation)t).args;
  72             case NEWCLASS:
  73                 return ((JCNewClass)t).args;
  74             default:
  75                 return null;
  76         }
  77     }
  78 
  79     /** Is tree a constructor declaration?
  80      */
  81     public static boolean isConstructor(JCTree tree) {
  82         if (tree.hasTag(METHODDEF)) {
  83             Name name = ((JCMethodDecl) tree).name;
  84             return name == name.table.names.init;
  85         } else {
  86             return false;
  87         }
  88     }
  89 
  90     public static boolean isCanonicalConstructor(JCTree tree) {
  91         // the record flag is only set to the canonical constructor
  92         return isConstructor(tree) && (((JCMethodDecl)tree).sym.flags_field & RECORD) != 0;
  93     }
  94 
  95     public static boolean isCompactConstructor(JCTree tree) {
  96         // the record flag is only set to the canonical constructor
  97         return isCanonicalConstructor(tree) && (((JCMethodDecl)tree).sym.flags_field & COMPACT_RECORD_CONSTRUCTOR) != 0;
  98     }
  99 
 100     public static boolean isReceiverParam(JCTree tree) {
 101         if (tree.hasTag(VARDEF)) {
 102             return ((JCVariableDecl)tree).nameexpr != null;
 103         } else {
 104             return false;
 105         }
 106     }
 107 
 108     /** Is there a constructor declaration in the given list of trees?
 109      */
 110     public static boolean hasConstructors(List<JCTree> trees) {
 111         for (List<JCTree> l = trees; l.nonEmpty(); l = l.tail)
 112             if (isConstructor(l.head)) return true;
 113         return false;
 114     }
 115 
 116     /** Is there a constructor invocation in the given list of trees?
 117      */
 118     public static Name getConstructorInvocationName(List<? extends JCTree> trees, Names names) {
 119         for (JCTree tree : trees) {
 120             if (tree.hasTag(EXEC)) {
 121                 JCExpressionStatement stat = (JCExpressionStatement)tree;
 122                 if (stat.expr.hasTag(APPLY)) {
 123                     JCMethodInvocation apply = (JCMethodInvocation)stat.expr;
 124                     Name methName = TreeInfo.name(apply.meth);
 125                     if (methName == names._this ||
 126                         methName == names._super) {
 127                         return methName;
 128                     }
 129                 }
 130             }
 131         }
 132         return names.empty;
 133     }
 134 
 135     public static boolean isMultiCatch(JCCatch catchClause) {
 136         return catchClause.param.vartype.hasTag(TYPEUNION);
 137     }
 138 
 139     /** Is statement an initializer for a synthetic field?
 140      */
 141     public static boolean isSyntheticInit(JCTree stat) {
 142         if (stat.hasTag(EXEC)) {
 143             JCExpressionStatement exec = (JCExpressionStatement)stat;
 144             if (exec.expr.hasTag(ASSIGN)) {
 145                 JCAssign assign = (JCAssign)exec.expr;
 146                 if (assign.lhs.hasTag(SELECT)) {
 147                     JCFieldAccess select = (JCFieldAccess)assign.lhs;
 148                     if (select.sym != null &&
 149                         (select.sym.flags() & SYNTHETIC) != 0) {
 150                         Name selected = name(select.selected);
 151                         if (selected != null && selected == selected.table.names._this)
 152                             return true;
 153                     }
 154                 }
 155             }
 156         }
 157         return false;
 158     }
 159 
 160     /** If the expression is a method call, return the method name, null
 161      *  otherwise. */
 162     public static Name calledMethodName(JCTree tree) {
 163         if (tree.hasTag(EXEC)) {
 164             JCExpressionStatement exec = (JCExpressionStatement)tree;
 165             if (exec.expr.hasTag(APPLY)) {
 166                 Name mname = TreeInfo.name(((JCMethodInvocation) exec.expr).meth);
 167                 return mname;
 168             }
 169         }
 170         return null;
 171     }
 172 
 173     /** Is this a call to this or super?
 174      */
 175     public static boolean isSelfCall(JCTree tree) {
 176         Name name = calledMethodName(tree);
 177         if (name != null) {
 178             Names names = name.table.names;
 179             return name==names._this || name==names._super;
 180         } else {
 181             return false;
 182         }
 183     }
 184 
 185     /** Is this tree a 'this' identifier?
 186      */
 187     public static boolean isThisQualifier(JCTree tree) {
 188         switch (tree.getTag()) {
 189             case PARENS:
 190                 return isThisQualifier(skipParens(tree));
 191             case IDENT: {
 192                 JCIdent id = (JCIdent)tree;
 193                 return id.name == id.name.table.names._this;
 194             }
 195             default:
 196                 return false;
 197         }
 198     }
 199 
 200     /** Is this tree an identifier, possibly qualified by 'this'?
 201      */
 202     public static boolean isIdentOrThisDotIdent(JCTree tree) {
 203         switch (tree.getTag()) {
 204             case PARENS:
 205                 return isIdentOrThisDotIdent(skipParens(tree));
 206             case IDENT:
 207                 return true;
 208             case SELECT:
 209                 return isThisQualifier(((JCFieldAccess)tree).selected);
 210             default:
 211                 return false;
 212         }
 213     }
 214 
 215     /** Is this a call to super?
 216      */
 217     public static boolean isSuperCall(JCTree tree) {
 218         Name name = calledMethodName(tree);
 219         if (name != null) {
 220             Names names = name.table.names;
 221             return name==names._super;
 222         } else {
 223             return false;
 224         }
 225     }
 226 
 227     public static List<JCVariableDecl> recordFields(JCClassDecl tree) {
 228         return tree.defs.stream()
 229                 .filter(t -> t.hasTag(VARDEF))
 230                 .map(t -> (JCVariableDecl)t)
 231                 .filter(vd -> (vd.getModifiers().flags & (Flags.RECORD)) == RECORD)
 232                 .collect(List.collector());
 233     }
 234 
 235     public static List<Type> recordFieldTypes(JCClassDecl tree) {
 236         return recordFields(tree).stream()
 237                 .map(vd -> vd.type)
 238                 .collect(List.collector());
 239     }
 240 
 241     /** Is this a constructor whose first (non-synthetic) statement is not
 242      *  of the form this(...)?
 243      */
 244     public static boolean isInitialConstructor(JCTree tree) {
 245         JCMethodInvocation app = firstConstructorCall(tree);
 246         if (app == null) return false;
 247         Name meth = name(app.meth);
 248         return meth == null || meth != meth.table.names._this;
 249     }
 250 
 251     /** Return the first call in a constructor definition. */
 252     public static JCMethodInvocation firstConstructorCall(JCTree tree) {
 253         if (!tree.hasTag(METHODDEF)) return null;
 254         JCMethodDecl md = (JCMethodDecl) tree;
 255         Names names = md.name.table.names;
 256         if (md.name != names.init) return null;
 257         if (md.body == null) return null;
 258         List<JCStatement> stats = md.body.stats;
 259         // Synthetic initializations can appear before the super call.
 260         while (stats.nonEmpty() && isSyntheticInit(stats.head))
 261             stats = stats.tail;
 262         if (stats.isEmpty()) return null;
 263         if (!stats.head.hasTag(EXEC)) return null;
 264         JCExpressionStatement exec = (JCExpressionStatement) stats.head;
 265         if (!exec.expr.hasTag(APPLY)) return null;
 266         return (JCMethodInvocation)exec.expr;
 267     }
 268 
 269     /** Return true if a tree represents a diamond new expr. */
 270     public static boolean isDiamond(JCTree tree) {
 271         switch(tree.getTag()) {
 272             case TYPEAPPLY: return ((JCTypeApply)tree).getTypeArguments().isEmpty();
 273             case NEWCLASS: return isDiamond(((JCNewClass)tree).clazz);
 274             case ANNOTATED_TYPE: return isDiamond(((JCAnnotatedType)tree).underlyingType);
 275             default: return false;
 276         }
 277     }
 278 
 279     public static boolean isEnumInit(JCTree tree) {
 280         switch (tree.getTag()) {
 281             case VARDEF:
 282                 return (((JCVariableDecl)tree).mods.flags & ENUM) != 0;
 283             default:
 284                 return false;
 285         }
 286     }
 287 
 288     /** set 'polyKind' on given tree */
 289     public static void setPolyKind(JCTree tree, PolyKind pkind) {
 290         switch (tree.getTag()) {
 291             case APPLY:
 292                 ((JCMethodInvocation)tree).polyKind = pkind;
 293                 break;
 294             case NEWCLASS:
 295                 ((JCNewClass)tree).polyKind = pkind;
 296                 break;
 297             case REFERENCE:
 298                 ((JCMemberReference)tree).refPolyKind = pkind;
 299                 break;
 300             default:
 301                 throw new AssertionError("Unexpected tree: " + tree);
 302         }
 303     }
 304 
 305     /** set 'varargsElement' on given tree */
 306     public static void setVarargsElement(JCTree tree, Type varargsElement) {
 307         switch (tree.getTag()) {
 308             case APPLY:
 309                 ((JCMethodInvocation)tree).varargsElement = varargsElement;
 310                 break;
 311             case NEWCLASS:
 312                 ((JCNewClass)tree).varargsElement = varargsElement;
 313                 break;
 314             case REFERENCE:
 315                 ((JCMemberReference)tree).varargsElement = varargsElement;
 316                 break;
 317             default:
 318                 throw new AssertionError("Unexpected tree: " + tree);
 319         }
 320     }
 321 
 322     /** Return true if the tree corresponds to an expression statement */
 323     public static boolean isExpressionStatement(JCExpression tree) {
 324         switch(tree.getTag()) {
 325             case PREINC: case PREDEC:
 326             case POSTINC: case POSTDEC:
 327             case ASSIGN:
 328             case BITOR_ASG: case BITXOR_ASG: case BITAND_ASG:
 329             case SL_ASG: case SR_ASG: case USR_ASG:
 330             case PLUS_ASG: case MINUS_ASG:
 331             case MUL_ASG: case DIV_ASG: case MOD_ASG:
 332             case APPLY: case NEWCLASS:
 333             case STRING_TEMPLATE:
 334             case ERRONEOUS:
 335                 return true;
 336             default:
 337                 return false;
 338         }
 339     }
 340 
 341     /** Return true if the tree corresponds to a statement */
 342     public static boolean isStatement(JCTree tree) {
 343         return (tree instanceof JCStatement) &&
 344                 !tree.hasTag(CLASSDEF) &&
 345                 !tree.hasTag(Tag.BLOCK) &&
 346                 !tree.hasTag(METHODDEF);
 347     }
 348 
 349     /**
 350      * Return true if the AST corresponds to a static select of the kind A.B
 351      */
 352     public static boolean isStaticSelector(JCTree base, Names names) {
 353         if (base == null)
 354             return false;
 355         switch (base.getTag()) {
 356             case IDENT:
 357                 JCIdent id = (JCIdent)base;
 358                 return id.name != names._this &&
 359                         id.name != names._super &&
 360                         isStaticSym(base);
 361             case SELECT:
 362                 return isStaticSym(base) &&
 363                     isStaticSelector(((JCFieldAccess)base).selected, names);
 364             case TYPEAPPLY:
 365             case TYPEARRAY:
 366                 return true;
 367             case ANNOTATED_TYPE:
 368                 return isStaticSelector(((JCAnnotatedType)base).underlyingType, names);
 369             default:
 370                 return false;
 371         }
 372     }
 373     //where
 374         private static boolean isStaticSym(JCTree tree) {
 375             Symbol sym = symbol(tree);
 376             return (sym.kind == TYP || sym.kind == PCK);
 377         }
 378 
 379     /** Return true if a tree represents the null literal. */
 380     public static boolean isNull(JCTree tree) {
 381         if (!tree.hasTag(LITERAL))
 382             return false;
 383         JCLiteral lit = (JCLiteral) tree;
 384         return (lit.typetag == BOT);
 385     }
 386 
 387     /** Return true iff this tree is a child of some annotation. */
 388     public static boolean isInAnnotation(Env<?> env, JCTree tree) {
 389         TreePath tp = TreePath.getPath(env.toplevel, tree);
 390         if (tp != null) {
 391             for (Tree t : tp) {
 392                 if (t.getKind() == Tree.Kind.ANNOTATION)
 393                     return true;
 394             }
 395         }
 396         return false;
 397     }
 398 
 399     public static String getCommentText(Env<?> env, JCTree tree) {
 400         DocCommentTable docComments = (tree.hasTag(JCTree.Tag.TOPLEVEL))
 401                 ? ((JCCompilationUnit) tree).docComments
 402                 : env.toplevel.docComments;
 403         return (docComments == null) ? null : docComments.getCommentText(tree);
 404     }
 405 
 406     public static DCTree.DCDocComment getCommentTree(Env<?> env, JCTree tree) {
 407         DocCommentTable docComments = (tree.hasTag(JCTree.Tag.TOPLEVEL))
 408                 ? ((JCCompilationUnit) tree).docComments
 409                 : env.toplevel.docComments;
 410         return (docComments == null) ? null : docComments.getCommentTree(tree);
 411     }
 412 
 413     /** The position of the first statement in a block, or the position of
 414      *  the block itself if it is empty.
 415      */
 416     public static int firstStatPos(JCTree tree) {
 417         if (tree.hasTag(BLOCK) && ((JCBlock) tree).stats.nonEmpty())
 418             return ((JCBlock) tree).stats.head.pos;
 419         else
 420             return tree.pos;
 421     }
 422 
 423     /** The end position of given tree, if it is a block with
 424      *  defined endpos.
 425      */
 426     public static int endPos(JCTree tree) {
 427         if (tree.hasTag(BLOCK) && ((JCBlock) tree).endpos != Position.NOPOS)
 428             return ((JCBlock) tree).endpos;
 429         else if (tree.hasTag(SYNCHRONIZED))
 430             return endPos(((JCSynchronized) tree).body);
 431         else if (tree.hasTag(TRY)) {
 432             JCTry t = (JCTry) tree;
 433             return endPos((t.finalizer != null) ? t.finalizer
 434                           : (t.catchers.nonEmpty() ? t.catchers.last().body : t.body));
 435         } else if (tree.hasTag(SWITCH) &&
 436                    ((JCSwitch) tree).endpos != Position.NOPOS) {
 437             return ((JCSwitch) tree).endpos;
 438         } else if (tree.hasTag(SWITCH_EXPRESSION) &&
 439                    ((JCSwitchExpression) tree).endpos != Position.NOPOS) {
 440             return ((JCSwitchExpression) tree).endpos;
 441         } else
 442             return tree.pos;
 443     }
 444 
 445 
 446     /** Get the start position for a tree node.  The start position is
 447      * defined to be the position of the first character of the first
 448      * token of the node's source text.
 449      * @param tree  The tree node
 450      */
 451     public static int getStartPos(JCTree tree) {
 452         if (tree == null)
 453             return Position.NOPOS;
 454 
 455         switch(tree.getTag()) {
 456             case MODULEDEF: {
 457                 JCModuleDecl md = (JCModuleDecl)tree;
 458                 return md.mods.annotations.isEmpty() ? md.pos :
 459                        md.mods.annotations.head.pos;
 460             }
 461             case PACKAGEDEF: {
 462                 JCPackageDecl pd = (JCPackageDecl)tree;
 463                 return pd.annotations.isEmpty() ? pd.pos :
 464                        pd.annotations.head.pos;
 465             }
 466             case APPLY:
 467                 return getStartPos(((JCMethodInvocation) tree).meth);
 468             case ASSIGN:
 469                 return getStartPos(((JCAssign) tree).lhs);
 470             case BITOR_ASG: case BITXOR_ASG: case BITAND_ASG:
 471             case SL_ASG: case SR_ASG: case USR_ASG:
 472             case PLUS_ASG: case MINUS_ASG: case MUL_ASG:
 473             case DIV_ASG: case MOD_ASG:
 474             case OR: case AND: case BITOR:
 475             case BITXOR: case BITAND: case EQ:
 476             case NE: case LT: case GT:
 477             case LE: case GE: case SL:
 478             case SR: case USR: case PLUS:
 479             case MINUS: case MUL: case DIV:
 480             case MOD:
 481             case POSTINC:
 482             case POSTDEC:
 483                 return getStartPos(((JCOperatorExpression) tree).getOperand(LEFT));
 484             case CLASSDEF: {
 485                 JCClassDecl node = (JCClassDecl)tree;
 486                 if (node.mods.pos != Position.NOPOS)
 487                     return node.mods.pos;
 488                 break;
 489             }
 490             case CONDEXPR:
 491                 return getStartPos(((JCConditional) tree).cond);
 492             case EXEC:
 493                 return getStartPos(((JCExpressionStatement) tree).expr);
 494             case INDEXED:
 495                 return getStartPos(((JCArrayAccess) tree).indexed);
 496             case METHODDEF: {
 497                 JCMethodDecl node = (JCMethodDecl)tree;
 498                 if (node.mods.pos != Position.NOPOS)
 499                     return node.mods.pos;
 500                 if (node.typarams.nonEmpty()) // List.nil() used for no typarams
 501                     return getStartPos(node.typarams.head);
 502                 return node.restype == null ? node.pos : getStartPos(node.restype);
 503             }
 504             case SELECT:
 505                 return getStartPos(((JCFieldAccess) tree).selected);
 506             case TYPEAPPLY:
 507                 return getStartPos(((JCTypeApply) tree).clazz);
 508             case TYPEARRAY:
 509                 return getStartPos(((JCArrayTypeTree) tree).elemtype);
 510             case TYPETEST:
 511                 return getStartPos(((JCInstanceOf) tree).expr);
 512             case ANNOTATED_TYPE: {
 513                 JCAnnotatedType node = (JCAnnotatedType) tree;
 514                 if (node.annotations.nonEmpty()) {
 515                     if (node.underlyingType.hasTag(TYPEARRAY) ||
 516                             node.underlyingType.hasTag(SELECT)) {
 517                         return getStartPos(node.underlyingType);
 518                     } else {
 519                         return getStartPos(node.annotations.head);
 520                     }
 521                 } else {
 522                     return getStartPos(node.underlyingType);
 523                 }
 524             }
 525             case NEWCLASS: {
 526                 JCNewClass node = (JCNewClass)tree;
 527                 if (node.encl != null)
 528                     return getStartPos(node.encl);
 529                 break;
 530             }
 531             case VARDEF: {
 532                 JCVariableDecl node = (JCVariableDecl)tree;
 533                 if (node.startPos != Position.NOPOS) {
 534                     return node.startPos;
 535                 } else if (node.mods.pos != Position.NOPOS) {
 536                     return node.mods.pos;
 537                 } else if (node.vartype == null || node.vartype.pos == Position.NOPOS) {
 538                     //if there's no type (partially typed lambda parameter)
 539                     //simply return node position
 540                     return node.pos;
 541                 } else {
 542                     return getStartPos(node.vartype);
 543                 }
 544             }
 545             case BINDINGPATTERN: {
 546                 JCBindingPattern node = (JCBindingPattern)tree;
 547                 return getStartPos(node.var);
 548             }
 549             case STRING_TEMPLATE: {
 550                 JCStringTemplate node = (JCStringTemplate) tree;
 551                 return node.processor == null ? node.pos : getStartPos(node.processor);
 552             }
 553             case ERRONEOUS: {
 554                 JCErroneous node = (JCErroneous)tree;
 555                 if (node.errs != null && node.errs.nonEmpty()) {
 556                     int pos = getStartPos(node.errs.head);
 557                     if (pos != Position.NOPOS) {
 558                         return pos;
 559                     }
 560                 }
 561                 break;
 562             }
 563         }
 564         return tree.pos;
 565     }
 566 
 567     /** The end position of given tree, given  a table of end positions generated by the parser
 568      */
 569     public static int getEndPos(JCTree tree, EndPosTable endPosTable) {
 570         if (tree == null)
 571             return Position.NOPOS;
 572 
 573         if (endPosTable == null) {
 574             // fall back on limited info in the tree
 575             return endPos(tree);
 576         }
 577 
 578         int mapPos = endPosTable.getEndPos(tree);
 579         if (mapPos != Position.NOPOS)
 580             return mapPos;
 581 
 582         switch(tree.getTag()) {
 583             case BITOR_ASG: case BITXOR_ASG: case BITAND_ASG:
 584             case SL_ASG: case SR_ASG: case USR_ASG:
 585             case PLUS_ASG: case MINUS_ASG: case MUL_ASG:
 586             case DIV_ASG: case MOD_ASG:
 587             case OR: case AND: case BITOR:
 588             case BITXOR: case BITAND: case EQ:
 589             case NE: case LT: case GT:
 590             case LE: case GE: case SL:
 591             case SR: case USR: case PLUS:
 592             case MINUS: case MUL: case DIV:
 593             case MOD:
 594             case POS:
 595             case NEG:
 596             case NOT:
 597             case COMPL:
 598             case PREINC:
 599             case PREDEC:
 600                 return getEndPos(((JCOperatorExpression) tree).getOperand(RIGHT), endPosTable);
 601             case CASE:
 602                 return getEndPos(((JCCase) tree).stats.last(), endPosTable);
 603             case CATCH:
 604                 return getEndPos(((JCCatch) tree).body, endPosTable);
 605             case CONDEXPR:
 606                 return getEndPos(((JCConditional) tree).falsepart, endPosTable);
 607             case FORLOOP:
 608                 return getEndPos(((JCForLoop) tree).body, endPosTable);
 609             case FOREACHLOOP:
 610                 return getEndPos(((JCEnhancedForLoop) tree).body, endPosTable);
 611             case IF: {
 612                 JCIf node = (JCIf)tree;
 613                 if (node.elsepart == null) {
 614                     return getEndPos(node.thenpart, endPosTable);
 615                 } else {
 616                     return getEndPos(node.elsepart, endPosTable);
 617                 }
 618             }
 619             case LABELLED:
 620                 return getEndPos(((JCLabeledStatement) tree).body, endPosTable);
 621             case MODIFIERS:
 622                 return getEndPos(((JCModifiers) tree).annotations.last(), endPosTable);
 623             case SYNCHRONIZED:
 624                 return getEndPos(((JCSynchronized) tree).body, endPosTable);
 625             case TOPLEVEL:
 626                 return getEndPos(((JCCompilationUnit) tree).defs.last(), endPosTable);
 627             case TRY: {
 628                 JCTry node = (JCTry)tree;
 629                 if (node.finalizer != null) {
 630                     return getEndPos(node.finalizer, endPosTable);
 631                 } else if (!node.catchers.isEmpty()) {
 632                     return getEndPos(node.catchers.last(), endPosTable);
 633                 } else {
 634                     return getEndPos(node.body, endPosTable);
 635                 }
 636             }
 637             case WILDCARD:
 638                 return getEndPos(((JCWildcard) tree).inner, endPosTable);
 639             case TYPECAST:
 640                 return getEndPos(((JCTypeCast) tree).expr, endPosTable);
 641             case TYPETEST:
 642                 return getEndPos(((JCInstanceOf) tree).pattern, endPosTable);
 643             case WHILELOOP:
 644                 return getEndPos(((JCWhileLoop) tree).body, endPosTable);
 645             case ANNOTATED_TYPE:
 646                 return getEndPos(((JCAnnotatedType) tree).underlyingType, endPosTable);
 647             case ERRONEOUS: {
 648                 JCErroneous node = (JCErroneous)tree;
 649                 if (node.errs != null && node.errs.nonEmpty())
 650                     return getEndPos(node.errs.last(), endPosTable);
 651             }
 652         }
 653         return Position.NOPOS;
 654     }
 655 
 656 
 657     /** A DiagnosticPosition with the preferred position set to the
 658      *  end position of given tree, if it is a block with
 659      *  defined endpos.
 660      */
 661     public static DiagnosticPosition diagEndPos(final JCTree tree) {
 662         final int endPos = TreeInfo.endPos(tree);
 663         return new DiagnosticPosition() {
 664             public JCTree getTree() { return tree; }
 665             public int getStartPosition() { return TreeInfo.getStartPos(tree); }
 666             public int getPreferredPosition() { return endPos; }
 667             public int getEndPosition(EndPosTable endPosTable) {
 668                 return TreeInfo.getEndPos(tree, endPosTable);
 669             }
 670         };
 671     }
 672 
 673     public enum PosKind {
 674         START_POS(TreeInfo::getStartPos),
 675         FIRST_STAT_POS(TreeInfo::firstStatPos),
 676         END_POS(TreeInfo::endPos);
 677 
 678         final ToIntFunction<JCTree> posFunc;
 679 
 680         PosKind(ToIntFunction<JCTree> posFunc) {
 681             this.posFunc = posFunc;
 682         }
 683 
 684         int toPos(JCTree tree) {
 685             return posFunc.applyAsInt(tree);
 686         }
 687     }
 688 
 689     /** The position of the finalizer of given try/synchronized statement.
 690      */
 691     public static int finalizerPos(JCTree tree, PosKind posKind) {
 692         if (tree.hasTag(TRY)) {
 693             JCTry t = (JCTry) tree;
 694             Assert.checkNonNull(t.finalizer);
 695             return posKind.toPos(t.finalizer);
 696         } else if (tree.hasTag(SYNCHRONIZED)) {
 697             return endPos(((JCSynchronized) tree).body);
 698         } else {
 699             throw new AssertionError();
 700         }
 701     }
 702 
 703     /** Find the position for reporting an error about a symbol, where
 704      *  that symbol is defined somewhere in the given tree. */
 705     public static int positionFor(final Symbol sym, final JCTree tree) {
 706         JCTree decl = declarationFor(sym, tree);
 707         return ((decl != null) ? decl : tree).pos;
 708     }
 709 
 710     /** Find the position for reporting an error about a symbol, where
 711      *  that symbol is defined somewhere in the given tree. */
 712     public static DiagnosticPosition diagnosticPositionFor(final Symbol sym, final JCTree tree) {
 713         return diagnosticPositionFor(sym, tree, false);
 714     }
 715 
 716     public static DiagnosticPosition diagnosticPositionFor(final Symbol sym, final JCTree tree, boolean returnNullIfNotFound) {
 717         return diagnosticPositionFor(sym, tree, returnNullIfNotFound, null);
 718     }
 719 
 720     public static DiagnosticPosition diagnosticPositionFor(final Symbol sym, final JCTree tree, boolean returnNullIfNotFound,
 721             Predicate<? super JCTree> filter) {
 722         class DiagScanner extends DeclScanner {
 723             DiagScanner(Symbol sym, Predicate<? super JCTree> filter) {
 724                 super(sym, filter);
 725             }
 726 
 727             public void visitIdent(JCIdent that) {
 728                 if (!checkMatch(that, that.sym))
 729                     super.visitIdent(that);
 730             }
 731             public void visitSelect(JCFieldAccess that) {
 732                 if (!checkMatch(that, that.sym))
 733                     super.visitSelect(that);
 734             }
 735         }
 736         DiagScanner s = new DiagScanner(sym, filter);
 737         tree.accept(s);
 738         JCTree decl = s.result;
 739         if (decl == null && returnNullIfNotFound) { return null; }
 740         return ((decl != null) ? decl : tree).pos();
 741     }
 742 
 743     public static DiagnosticPosition diagnosticPositionFor(final Symbol sym, final List<? extends JCTree> trees) {
 744         return trees.stream().map(t -> TreeInfo.diagnosticPositionFor(sym, t)).filter(t -> t != null).findFirst().get();
 745     }
 746 
 747     private static class DeclScanner extends TreeScanner {
 748         final Symbol sym;
 749         final Predicate<? super JCTree> filter;
 750 
 751         DeclScanner(final Symbol sym) {
 752             this(sym, null);
 753         }
 754         DeclScanner(final Symbol sym, Predicate<? super JCTree> filter) {
 755             this.sym = sym;
 756             this.filter = filter;
 757         }
 758 
 759         JCTree result = null;
 760         public void scan(JCTree tree) {
 761             if (tree!=null && result==null)
 762                 tree.accept(this);
 763         }
 764         public void visitTopLevel(JCCompilationUnit that) {
 765             if (!checkMatch(that, that.packge))
 766                 super.visitTopLevel(that);
 767         }
 768         public void visitModuleDef(JCModuleDecl that) {
 769             checkMatch(that, that.sym);
 770             // no need to scan within module declaration
 771         }
 772         public void visitPackageDef(JCPackageDecl that) {
 773             if (!checkMatch(that, that.packge))
 774                 super.visitPackageDef(that);
 775         }
 776         public void visitClassDef(JCClassDecl that) {
 777             if (!checkMatch(that, that.sym))
 778                 super.visitClassDef(that);
 779         }
 780         public void visitMethodDef(JCMethodDecl that) {
 781             if (!checkMatch(that, that.sym))
 782                 super.visitMethodDef(that);
 783         }
 784         public void visitVarDef(JCVariableDecl that) {
 785             if (!checkMatch(that, that.sym))
 786                 super.visitVarDef(that);
 787         }
 788         public void visitTypeParameter(JCTypeParameter that) {
 789             if (that.type == null || !checkMatch(that, that.type.tsym))
 790                 super.visitTypeParameter(that);
 791         }
 792 
 793         protected boolean checkMatch(JCTree that, Symbol thatSym) {
 794             if (thatSym == this.sym && (filter == null || filter.test(that))) {
 795                 result = that;
 796                 return true;
 797             }
 798             if (this.sym.getKind() == ElementKind.RECORD_COMPONENT) {
 799                 if (thatSym != null && thatSym.getKind() == ElementKind.FIELD && (thatSym.flags_field & RECORD) != 0) {
 800                     RecordComponent rc = thatSym.enclClass().getRecordComponent((VarSymbol)thatSym);
 801                     return checkMatch(rc.declarationFor(), rc);
 802                 }
 803             }
 804             return false;
 805         }
 806     }
 807 
 808     /** Find the declaration for a symbol, where
 809      *  that symbol is defined somewhere in the given tree. */
 810     public static JCTree declarationFor(final Symbol sym, final JCTree tree) {
 811         DeclScanner s = new DeclScanner(sym);
 812         tree.accept(s);
 813         return s.result;
 814     }
 815 
 816     /** Return the statement referenced by a label.
 817      *  If the label refers to a loop or switch, return that switch
 818      *  otherwise return the labelled statement itself
 819      */
 820     public static JCTree referencedStatement(JCLabeledStatement tree) {
 821         JCTree t = tree;
 822         do t = ((JCLabeledStatement) t).body;
 823         while (t.hasTag(LABELLED));
 824         switch (t.getTag()) {
 825         case DOLOOP: case WHILELOOP: case FORLOOP: case FOREACHLOOP: case SWITCH:
 826             return t;
 827         default:
 828             return tree;
 829         }
 830     }
 831 
 832     /** Skip parens and return the enclosed expression
 833      */
 834     public static JCExpression skipParens(JCExpression tree) {
 835         while (tree.hasTag(PARENS)) {
 836             tree = ((JCParens) tree).expr;
 837         }
 838         return tree;
 839     }
 840 
 841     /** Skip parens and return the enclosed expression
 842      */
 843     public static JCTree skipParens(JCTree tree) {
 844         if (tree.hasTag(PARENS))
 845             return skipParens((JCParens)tree);
 846         else
 847             return tree;
 848     }
 849 
 850     /** Return the types of a list of trees.
 851      */
 852     public static List<Type> types(List<? extends JCTree> trees) {
 853         ListBuffer<Type> ts = new ListBuffer<>();
 854         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
 855             ts.append(l.head.type);
 856         return ts.toList();
 857     }
 858 
 859     /** If this tree is an identifier or a field or a parameterized type,
 860      *  return its name, otherwise return null.
 861      */
 862     public static Name name(JCTree tree) {
 863         switch (tree.getTag()) {
 864         case IDENT:
 865             return ((JCIdent) tree).name;
 866         case SELECT:
 867             return ((JCFieldAccess) tree).name;
 868         case TYPEAPPLY:
 869             return name(((JCTypeApply) tree).clazz);
 870         default:
 871             return null;
 872         }
 873     }
 874 
 875     /** If this tree is a qualified identifier, its return fully qualified name,
 876      *  otherwise return null.
 877      */
 878     public static Name fullName(JCTree tree) {
 879         tree = skipParens(tree);
 880         switch (tree.getTag()) {
 881         case IDENT:
 882             return ((JCIdent) tree).name;
 883         case SELECT:
 884             Name sname = fullName(((JCFieldAccess) tree).selected);
 885             return sname == null ? null : sname.append('.', name(tree));
 886         default:
 887             return null;
 888         }
 889     }
 890 
 891     public static Symbol symbolFor(JCTree node) {
 892         Symbol sym = symbolForImpl(node);
 893 
 894         return sym != null ? sym.baseSymbol() : null;
 895     }
 896 
 897     private static Symbol symbolForImpl(JCTree node) {
 898         node = skipParens(node);
 899         switch (node.getTag()) {
 900         case TOPLEVEL:
 901             JCCompilationUnit cut = (JCCompilationUnit) node;
 902             JCModuleDecl moduleDecl = cut.getModuleDecl();
 903             if (isModuleInfo(cut) && moduleDecl != null)
 904                 return symbolFor(moduleDecl);
 905             return cut.packge;
 906         case MODULEDEF:
 907             return ((JCModuleDecl) node).sym;
 908         case PACKAGEDEF:
 909             return ((JCPackageDecl) node).packge;
 910         case CLASSDEF:
 911             return ((JCClassDecl) node).sym;
 912         case METHODDEF:
 913             return ((JCMethodDecl) node).sym;
 914         case VARDEF:
 915             return ((JCVariableDecl) node).sym;
 916         case IDENT:
 917             return ((JCIdent) node).sym;
 918         case SELECT:
 919             return ((JCFieldAccess) node).sym;
 920         case REFERENCE:
 921             return ((JCMemberReference) node).sym;
 922         case NEWCLASS:
 923             return ((JCNewClass) node).constructor;
 924         case APPLY:
 925             return symbolFor(((JCMethodInvocation) node).meth);
 926         case TYPEAPPLY:
 927             return symbolFor(((JCTypeApply) node).clazz);
 928         case ANNOTATION:
 929         case TYPE_ANNOTATION:
 930         case TYPEPARAMETER:
 931             if (node.type != null)
 932                 return node.type.tsym;
 933             return null;
 934         default:
 935             return null;
 936         }
 937     }
 938 
 939     public static boolean isDeclaration(JCTree node) {
 940         node = skipParens(node);
 941         switch (node.getTag()) {
 942         case PACKAGEDEF:
 943         case CLASSDEF:
 944         case METHODDEF:
 945         case VARDEF:
 946             return true;
 947         default:
 948             return false;
 949         }
 950     }
 951 
 952     /** If this tree is an identifier or a field, return its symbol,
 953      *  otherwise return null.
 954      */
 955     public static Symbol symbol(JCTree tree) {
 956         tree = skipParens(tree);
 957         switch (tree.getTag()) {
 958         case IDENT:
 959             return ((JCIdent) tree).sym;
 960         case SELECT:
 961             return ((JCFieldAccess) tree).sym;
 962         case TYPEAPPLY:
 963             return symbol(((JCTypeApply) tree).clazz);
 964         case ANNOTATED_TYPE:
 965             return symbol(((JCAnnotatedType) tree).underlyingType);
 966         case REFERENCE:
 967             return ((JCMemberReference) tree).sym;
 968         case CLASSDEF:
 969             return ((JCClassDecl) tree).sym;
 970         default:
 971             return null;
 972         }
 973     }
 974 
 975     /** If this tree has a modifiers field, return it otherwise return null
 976      */
 977     public static JCModifiers getModifiers(JCTree tree) {
 978         tree = skipParens(tree);
 979         switch (tree.getTag()) {
 980             case VARDEF:
 981                 return ((JCVariableDecl) tree).mods;
 982             case METHODDEF:
 983                 return ((JCMethodDecl) tree).mods;
 984             case CLASSDEF:
 985                 return ((JCClassDecl) tree).mods;
 986             case MODULEDEF:
 987                 return ((JCModuleDecl) tree).mods;
 988         default:
 989             return null;
 990         }
 991     }
 992 
 993     /** Return true if this is a nonstatic selection. */
 994     public static boolean nonstaticSelect(JCTree tree) {
 995         tree = skipParens(tree);
 996         if (!tree.hasTag(SELECT)) return false;
 997         JCFieldAccess s = (JCFieldAccess) tree;
 998         Symbol e = symbol(s.selected);
 999         return e == null || (e.kind != PCK && e.kind != TYP);
1000     }
1001 
1002     /** If this tree is an identifier or a field, set its symbol, otherwise skip.
1003      */
1004     public static void setSymbol(JCTree tree, Symbol sym) {
1005         tree = skipParens(tree);
1006         switch (tree.getTag()) {
1007         case IDENT:
1008             ((JCIdent) tree).sym = sym; break;
1009         case SELECT:
1010             ((JCFieldAccess) tree).sym = sym; break;
1011         default:
1012         }
1013     }
1014 
1015     /** If this tree is a declaration or a block, return its flags field,
1016      *  otherwise return 0.
1017      */
1018     public static long flags(JCTree tree) {
1019         switch (tree.getTag()) {
1020         case VARDEF:
1021             return ((JCVariableDecl) tree).mods.flags;
1022         case METHODDEF:
1023             return ((JCMethodDecl) tree).mods.flags;
1024         case CLASSDEF:
1025             return ((JCClassDecl) tree).mods.flags;
1026         case BLOCK:
1027             return ((JCBlock) tree).flags;
1028         default:
1029             return 0;
1030         }
1031     }
1032 
1033     /** Return first (smallest) flag in `flags':
1034      *  pre: flags != 0
1035      */
1036     public static long firstFlag(long flags) {
1037         long flag = 1;
1038         while ((flag & flags) == 0)
1039             flag = flag << 1;
1040         return flag;
1041     }
1042 
1043     /** Return flags as a string, separated by " ".
1044      */
1045     public static String flagNames(long flags) {
1046         return Flags.toString(flags & ExtendedStandardFlags).trim();
1047     }
1048 
1049     /** Operator precedences values.
1050      */
1051     public static final int
1052         notExpression = -1,   // not an expression
1053         noPrec = 0,           // no enclosing expression
1054         assignPrec = 1,
1055         assignopPrec = 2,
1056         condPrec = 3,
1057         orPrec = 4,
1058         andPrec = 5,
1059         bitorPrec = 6,
1060         bitxorPrec = 7,
1061         bitandPrec = 8,
1062         eqPrec = 9,
1063         ordPrec = 10,
1064         shiftPrec = 11,
1065         addPrec = 12,
1066         mulPrec = 13,
1067         prefixPrec = 14,
1068         postfixPrec = 15,
1069         precCount = 16;
1070 
1071 
1072     /** Map operators to their precedence levels.
1073      */
1074     public static int opPrec(JCTree.Tag op) {
1075         switch(op) {
1076         case POS:
1077         case NEG:
1078         case NOT:
1079         case COMPL:
1080         case PREINC:
1081         case PREDEC: return prefixPrec;
1082         case POSTINC:
1083         case POSTDEC:
1084         case NULLCHK: return postfixPrec;
1085         case ASSIGN: return assignPrec;
1086         case BITOR_ASG:
1087         case BITXOR_ASG:
1088         case BITAND_ASG:
1089         case SL_ASG:
1090         case SR_ASG:
1091         case USR_ASG:
1092         case PLUS_ASG:
1093         case MINUS_ASG:
1094         case MUL_ASG:
1095         case DIV_ASG:
1096         case MOD_ASG: return assignopPrec;
1097         case OR: return orPrec;
1098         case AND: return andPrec;
1099         case EQ:
1100         case NE: return eqPrec;
1101         case LT:
1102         case GT:
1103         case LE:
1104         case GE: return ordPrec;
1105         case BITOR: return bitorPrec;
1106         case BITXOR: return bitxorPrec;
1107         case BITAND: return bitandPrec;
1108         case SL:
1109         case SR:
1110         case USR: return shiftPrec;
1111         case PLUS:
1112         case MINUS: return addPrec;
1113         case MUL:
1114         case DIV:
1115         case MOD: return mulPrec;
1116         case TYPETEST: return ordPrec;
1117         default: throw new AssertionError();
1118         }
1119     }
1120 
1121     static Tree.Kind tagToKind(JCTree.Tag tag) {
1122         switch (tag) {
1123         // Postfix expressions
1124         case POSTINC:           // _ ++
1125             return Tree.Kind.POSTFIX_INCREMENT;
1126         case POSTDEC:           // _ --
1127             return Tree.Kind.POSTFIX_DECREMENT;
1128 
1129         // Unary operators
1130         case PREINC:            // ++ _
1131             return Tree.Kind.PREFIX_INCREMENT;
1132         case PREDEC:            // -- _
1133             return Tree.Kind.PREFIX_DECREMENT;
1134         case POS:               // +
1135             return Tree.Kind.UNARY_PLUS;
1136         case NEG:               // -
1137             return Tree.Kind.UNARY_MINUS;
1138         case COMPL:             // ~
1139             return Tree.Kind.BITWISE_COMPLEMENT;
1140         case NOT:               // !
1141             return Tree.Kind.LOGICAL_COMPLEMENT;
1142 
1143         // Binary operators
1144 
1145         // Multiplicative operators
1146         case MUL:               // *
1147             return Tree.Kind.MULTIPLY;
1148         case DIV:               // /
1149             return Tree.Kind.DIVIDE;
1150         case MOD:               // %
1151             return Tree.Kind.REMAINDER;
1152 
1153         // Additive operators
1154         case PLUS:              // +
1155             return Tree.Kind.PLUS;
1156         case MINUS:             // -
1157             return Tree.Kind.MINUS;
1158 
1159         // Shift operators
1160         case SL:                // <<
1161             return Tree.Kind.LEFT_SHIFT;
1162         case SR:                // >>
1163             return Tree.Kind.RIGHT_SHIFT;
1164         case USR:               // >>>
1165             return Tree.Kind.UNSIGNED_RIGHT_SHIFT;
1166 
1167         // Relational operators
1168         case LT:                // <
1169             return Tree.Kind.LESS_THAN;
1170         case GT:                // >
1171             return Tree.Kind.GREATER_THAN;
1172         case LE:                // <=
1173             return Tree.Kind.LESS_THAN_EQUAL;
1174         case GE:                // >=
1175             return Tree.Kind.GREATER_THAN_EQUAL;
1176 
1177         // Equality operators
1178         case EQ:                // ==
1179             return Tree.Kind.EQUAL_TO;
1180         case NE:                // !=
1181             return Tree.Kind.NOT_EQUAL_TO;
1182 
1183         // Bitwise and logical operators
1184         case BITAND:            // &
1185             return Tree.Kind.AND;
1186         case BITXOR:            // ^
1187             return Tree.Kind.XOR;
1188         case BITOR:             // |
1189             return Tree.Kind.OR;
1190 
1191         // Conditional operators
1192         case AND:               // &&
1193             return Tree.Kind.CONDITIONAL_AND;
1194         case OR:                // ||
1195             return Tree.Kind.CONDITIONAL_OR;
1196 
1197         // Assignment operators
1198         case MUL_ASG:           // *=
1199             return Tree.Kind.MULTIPLY_ASSIGNMENT;
1200         case DIV_ASG:           // /=
1201             return Tree.Kind.DIVIDE_ASSIGNMENT;
1202         case MOD_ASG:           // %=
1203             return Tree.Kind.REMAINDER_ASSIGNMENT;
1204         case PLUS_ASG:          // +=
1205             return Tree.Kind.PLUS_ASSIGNMENT;
1206         case MINUS_ASG:         // -=
1207             return Tree.Kind.MINUS_ASSIGNMENT;
1208         case SL_ASG:            // <<=
1209             return Tree.Kind.LEFT_SHIFT_ASSIGNMENT;
1210         case SR_ASG:            // >>=
1211             return Tree.Kind.RIGHT_SHIFT_ASSIGNMENT;
1212         case USR_ASG:           // >>>=
1213             return Tree.Kind.UNSIGNED_RIGHT_SHIFT_ASSIGNMENT;
1214         case BITAND_ASG:        // &=
1215             return Tree.Kind.AND_ASSIGNMENT;
1216         case BITXOR_ASG:        // ^=
1217             return Tree.Kind.XOR_ASSIGNMENT;
1218         case BITOR_ASG:         // |=
1219             return Tree.Kind.OR_ASSIGNMENT;
1220 
1221         // Null check (implementation detail), for example, __.getClass()
1222         case NULLCHK:
1223             return Tree.Kind.OTHER;
1224 
1225         case ANNOTATION:
1226             return Tree.Kind.ANNOTATION;
1227         case TYPE_ANNOTATION:
1228             return Tree.Kind.TYPE_ANNOTATION;
1229 
1230         case EXPORTS:
1231             return Tree.Kind.EXPORTS;
1232         case OPENS:
1233             return Tree.Kind.OPENS;
1234 
1235         default:
1236             return null;
1237         }
1238     }
1239 
1240     /**
1241      * Returns the underlying type of the tree if it is an annotated type,
1242      * or the tree itself otherwise.
1243      */
1244     public static JCExpression typeIn(JCExpression tree) {
1245         switch (tree.getTag()) {
1246         case ANNOTATED_TYPE:
1247             return ((JCAnnotatedType)tree).underlyingType;
1248         case IDENT: /* simple names */
1249         case TYPEIDENT: /* primitive name */
1250         case SELECT: /* qualified name */
1251         case TYPEARRAY: /* array types */
1252         case WILDCARD: /* wild cards */
1253         case TYPEPARAMETER: /* type parameters */
1254         case TYPEAPPLY: /* parameterized types */
1255         case ERRONEOUS: /* error tree TODO: needed for BadCast JSR308 test case. Better way? */
1256             return tree;
1257         default:
1258             throw new AssertionError("Unexpected type tree: " + tree);
1259         }
1260     }
1261 
1262     /* Return the inner-most type of a type tree.
1263      * For an array that contains an annotated type, return that annotated type.
1264      * TODO: currently only used by Pretty. Describe behavior better.
1265      */
1266     public static JCTree innermostType(JCTree type, boolean skipAnnos) {
1267         JCTree lastAnnotatedType = null;
1268         JCTree cur = type;
1269         loop: while (true) {
1270             switch (cur.getTag()) {
1271             case TYPEARRAY:
1272                 lastAnnotatedType = null;
1273                 cur = ((JCArrayTypeTree)cur).elemtype;
1274                 break;
1275             case WILDCARD:
1276                 lastAnnotatedType = null;
1277                 cur = ((JCWildcard)cur).inner;
1278                 break;
1279             case ANNOTATED_TYPE:
1280                 lastAnnotatedType = cur;
1281                 cur = ((JCAnnotatedType)cur).underlyingType;
1282                 break;
1283             default:
1284                 break loop;
1285             }
1286         }
1287         if (!skipAnnos && lastAnnotatedType!=null) {
1288             return lastAnnotatedType;
1289         } else {
1290             return cur;
1291         }
1292     }
1293 
1294     private static class TypeAnnotationFinder extends TreeScanner {
1295         public boolean foundTypeAnno = false;
1296 
1297         @Override
1298         public void scan(JCTree tree) {
1299             if (foundTypeAnno || tree == null)
1300                 return;
1301             super.scan(tree);
1302         }
1303 
1304         public void visitAnnotation(JCAnnotation tree) {
1305             foundTypeAnno = foundTypeAnno || tree.hasTag(TYPE_ANNOTATION);
1306         }
1307     }
1308 
1309     public static boolean containsTypeAnnotation(JCTree e) {
1310         TypeAnnotationFinder finder = new TypeAnnotationFinder();
1311         finder.scan(e);
1312         return finder.foundTypeAnno;
1313     }
1314 
1315     public static boolean isModuleInfo(JCCompilationUnit tree) {
1316         return tree.sourcefile.isNameCompatible("module-info", JavaFileObject.Kind.SOURCE)
1317                 && tree.getModuleDecl() != null;
1318     }
1319 
1320     public static boolean isPackageInfo(JCCompilationUnit tree) {
1321         return tree.sourcefile.isNameCompatible("package-info", JavaFileObject.Kind.SOURCE);
1322     }
1323 
1324     public static boolean isErrorEnumSwitch(JCExpression selector, List<JCCase> cases) {
1325         return selector.type.tsym.kind == Kinds.Kind.ERR &&
1326                cases.stream().flatMap(c -> c.labels.stream())
1327                              .filter(l -> l.hasTag(CONSTANTCASELABEL))
1328                              .map(l -> ((JCConstantCaseLabel) l).expr)
1329                              .allMatch(p -> p.hasTag(IDENT));
1330     }
1331 
1332     public static Type primaryPatternType(JCTree pat) {
1333         return switch (pat.getTag()) {
1334             case BINDINGPATTERN -> pat.type;
1335             case RECORDPATTERN -> ((JCRecordPattern) pat).type;
1336             case ANYPATTERN -> ((JCAnyPattern) pat).type;
1337             default -> throw new AssertionError();
1338         };
1339     }
1340 
1341     public static JCTree primaryPatternTypeTree(JCTree pat) {
1342         return switch (pat.getTag()) {
1343             case BINDINGPATTERN -> ((JCBindingPattern) pat).var.vartype;
1344             case RECORDPATTERN -> ((JCRecordPattern) pat).deconstructor;
1345             default -> throw new AssertionError();
1346         };
1347     }
1348 
1349     public static boolean expectedExhaustive(JCSwitch tree) {
1350         return tree.patternSwitch ||
1351                tree.cases.stream()
1352                          .flatMap(c -> c.labels.stream())
1353                          .anyMatch(l -> TreeInfo.isNullCaseLabel(l));
1354     }
1355 
1356     public static boolean unguardedCase(JCCase cse) {
1357         JCExpression guard = cse.guard;
1358         if (guard == null) {
1359             return true;
1360         }
1361         return isBooleanWithValue(guard, 1);
1362     }
1363 
1364     public static boolean isBooleanWithValue(JCExpression guard, int value) {
1365         var constValue = guard.type.constValue();
1366         return constValue != null &&
1367                 guard.type.hasTag(BOOLEAN) &&
1368                 ((int) constValue) == value;
1369     }
1370 
1371     public static boolean isNullCaseLabel(JCCaseLabel label) {
1372         return label.hasTag(CONSTANTCASELABEL) &&
1373                TreeInfo.isNull(((JCConstantCaseLabel) label).expr);
1374     }
1375 }