1 /*
   2  * Copyright (c) 1999, 2022, 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 ERRONEOUS:
 334                 return true;
 335             default:
 336                 return false;
 337         }
 338     }
 339 
 340     /** Return true if the tree corresponds to a statement */
 341     public static boolean isStatement(JCTree tree) {
 342         return (tree instanceof JCStatement) &&
 343                 !tree.hasTag(CLASSDEF) &&
 344                 !tree.hasTag(Tag.BLOCK) &&
 345                 !tree.hasTag(METHODDEF);
 346     }
 347 
 348     /**
 349      * Return true if the AST corresponds to a static select of the kind A.B
 350      */
 351     public static boolean isStaticSelector(JCTree base, Names names) {
 352         if (base == null)
 353             return false;
 354         switch (base.getTag()) {
 355             case IDENT:
 356                 JCIdent id = (JCIdent)base;
 357                 return id.name != names._this &&
 358                         id.name != names._super &&
 359                         isStaticSym(base);
 360             case SELECT:
 361                 return isStaticSym(base) &&
 362                     isStaticSelector(((JCFieldAccess)base).selected, names);
 363             case TYPEAPPLY:
 364             case TYPEARRAY:
 365                 return true;
 366             case ANNOTATED_TYPE:
 367                 return isStaticSelector(((JCAnnotatedType)base).underlyingType, names);
 368             default:
 369                 return false;
 370         }
 371     }
 372     //where
 373         private static boolean isStaticSym(JCTree tree) {
 374             Symbol sym = symbol(tree);
 375             return (sym.kind == TYP || sym.kind == PCK);
 376         }
 377 
 378     /** Return true if a tree represents the null literal. */
 379     public static boolean isNull(JCTree tree) {
 380         if (!tree.hasTag(LITERAL))
 381             return false;
 382         JCLiteral lit = (JCLiteral) tree;
 383         return (lit.typetag == BOT);
 384     }
 385 
 386     /** Return true iff this tree is a child of some annotation. */
 387     public static boolean isInAnnotation(Env<?> env, JCTree tree) {
 388         TreePath tp = TreePath.getPath(env.toplevel, tree);
 389         if (tp != null) {
 390             for (Tree t : tp) {
 391                 if (t.getKind() == Tree.Kind.ANNOTATION)
 392                     return true;
 393             }
 394         }
 395         return false;
 396     }
 397 
 398     public static String getCommentText(Env<?> env, JCTree tree) {
 399         DocCommentTable docComments = (tree.hasTag(JCTree.Tag.TOPLEVEL))
 400                 ? ((JCCompilationUnit) tree).docComments
 401                 : env.toplevel.docComments;
 402         return (docComments == null) ? null : docComments.getCommentText(tree);
 403     }
 404 
 405     public static DCTree.DCDocComment getCommentTree(Env<?> env, JCTree tree) {
 406         DocCommentTable docComments = (tree.hasTag(JCTree.Tag.TOPLEVEL))
 407                 ? ((JCCompilationUnit) tree).docComments
 408                 : env.toplevel.docComments;
 409         return (docComments == null) ? null : docComments.getCommentTree(tree);
 410     }
 411 
 412     /** The position of the first statement in a block, or the position of
 413      *  the block itself if it is empty.
 414      */
 415     public static int firstStatPos(JCTree tree) {
 416         if (tree.hasTag(BLOCK) && ((JCBlock) tree).stats.nonEmpty())
 417             return ((JCBlock) tree).stats.head.pos;
 418         else
 419             return tree.pos;
 420     }
 421 
 422     /** The end position of given tree, if it is a block with
 423      *  defined endpos.
 424      */
 425     public static int endPos(JCTree tree) {
 426         if (tree.hasTag(BLOCK) && ((JCBlock) tree).endpos != Position.NOPOS)
 427             return ((JCBlock) tree).endpos;
 428         else if (tree.hasTag(SYNCHRONIZED))
 429             return endPos(((JCSynchronized) tree).body);
 430         else if (tree.hasTag(TRY)) {
 431             JCTry t = (JCTry) tree;
 432             return endPos((t.finalizer != null) ? t.finalizer
 433                           : (t.catchers.nonEmpty() ? t.catchers.last().body : t.body));
 434         } else if (tree.hasTag(SWITCH) &&
 435                    ((JCSwitch) tree).endpos != Position.NOPOS) {
 436             return ((JCSwitch) tree).endpos;
 437         } else if (tree.hasTag(SWITCH_EXPRESSION) &&
 438                    ((JCSwitchExpression) tree).endpos != Position.NOPOS) {
 439             return ((JCSwitchExpression) tree).endpos;
 440         } else
 441             return tree.pos;
 442     }
 443 
 444 
 445     /** Get the start position for a tree node.  The start position is
 446      * defined to be the position of the first character of the first
 447      * token of the node's source text.
 448      * @param tree  The tree node
 449      */
 450     public static int getStartPos(JCTree tree) {
 451         if (tree == null)
 452             return Position.NOPOS;
 453 
 454         switch(tree.getTag()) {
 455             case MODULEDEF: {
 456                 JCModuleDecl md = (JCModuleDecl)tree;
 457                 return md.mods.annotations.isEmpty() ? md.pos :
 458                        md.mods.annotations.head.pos;
 459             }
 460             case PACKAGEDEF: {
 461                 JCPackageDecl pd = (JCPackageDecl)tree;
 462                 return pd.annotations.isEmpty() ? pd.pos :
 463                        pd.annotations.head.pos;
 464             }
 465             case APPLY:
 466                 return getStartPos(((JCMethodInvocation) tree).meth);
 467             case ASSIGN:
 468                 return getStartPos(((JCAssign) tree).lhs);
 469             case BITOR_ASG: case BITXOR_ASG: case BITAND_ASG:
 470             case SL_ASG: case SR_ASG: case USR_ASG:
 471             case PLUS_ASG: case MINUS_ASG: case MUL_ASG:
 472             case DIV_ASG: case MOD_ASG:
 473             case OR: case AND: case BITOR:
 474             case BITXOR: case BITAND: case EQ:
 475             case NE: case LT: case GT:
 476             case LE: case GE: case SL:
 477             case SR: case USR: case PLUS:
 478             case MINUS: case MUL: case DIV:
 479             case MOD:
 480             case POSTINC:
 481             case POSTDEC:
 482                 return getStartPos(((JCOperatorExpression) tree).getOperand(LEFT));
 483             case CLASSDEF: {
 484                 JCClassDecl node = (JCClassDecl)tree;
 485                 if (node.mods.pos != Position.NOPOS)
 486                     return node.mods.pos;
 487                 break;
 488             }
 489             case CONDEXPR:
 490                 return getStartPos(((JCConditional) tree).cond);
 491             case EXEC:
 492                 return getStartPos(((JCExpressionStatement) tree).expr);
 493             case INDEXED:
 494                 return getStartPos(((JCArrayAccess) tree).indexed);
 495             case METHODDEF: {
 496                 JCMethodDecl node = (JCMethodDecl)tree;
 497                 if (node.mods.pos != Position.NOPOS)
 498                     return node.mods.pos;
 499                 if (node.typarams.nonEmpty()) // List.nil() used for no typarams
 500                     return getStartPos(node.typarams.head);
 501                 return node.restype == null ? node.pos : getStartPos(node.restype);
 502             }
 503             case SELECT:
 504                 return getStartPos(((JCFieldAccess) tree).selected);
 505             case TYPEAPPLY:
 506                 return getStartPos(((JCTypeApply) tree).clazz);
 507             case TYPEARRAY:
 508                 return getStartPos(((JCArrayTypeTree) tree).elemtype);
 509             case TYPETEST:
 510                 return getStartPos(((JCInstanceOf) tree).expr);
 511             case ANNOTATED_TYPE: {
 512                 JCAnnotatedType node = (JCAnnotatedType) tree;
 513                 if (node.annotations.nonEmpty()) {
 514                     if (node.underlyingType.hasTag(TYPEARRAY) ||
 515                             node.underlyingType.hasTag(SELECT)) {
 516                         return getStartPos(node.underlyingType);
 517                     } else {
 518                         return getStartPos(node.annotations.head);
 519                     }
 520                 } else {
 521                     return getStartPos(node.underlyingType);
 522                 }
 523             }
 524             case NEWCLASS: {
 525                 JCNewClass node = (JCNewClass)tree;
 526                 if (node.encl != null)
 527                     return getStartPos(node.encl);
 528                 break;
 529             }
 530             case VARDEF: {
 531                 JCVariableDecl node = (JCVariableDecl)tree;
 532                 if (node.startPos != Position.NOPOS) {
 533                     return node.startPos;
 534                 } else if (node.mods.pos != Position.NOPOS) {
 535                     return node.mods.pos;
 536                 } else if (node.vartype == null || node.vartype.pos == Position.NOPOS) {
 537                     //if there's no type (partially typed lambda parameter)
 538                     //simply return node position
 539                     return node.pos;
 540                 } else {
 541                     return getStartPos(node.vartype);
 542                 }
 543             }
 544             case BINDINGPATTERN: {
 545                 JCBindingPattern node = (JCBindingPattern)tree;
 546                 return getStartPos(node.var);
 547             }
 548             case ERRONEOUS: {
 549                 JCErroneous node = (JCErroneous)tree;
 550                 if (node.errs != null && node.errs.nonEmpty()) {
 551                     int pos = getStartPos(node.errs.head);
 552                     if (pos != Position.NOPOS) {
 553                         return pos;
 554                     }
 555                 }
 556                 break;
 557             }
 558         }
 559         return tree.pos;
 560     }
 561 
 562     /** The end position of given tree, given  a table of end positions generated by the parser
 563      */
 564     public static int getEndPos(JCTree tree, EndPosTable endPosTable) {
 565         if (tree == null)
 566             return Position.NOPOS;
 567 
 568         if (endPosTable == null) {
 569             // fall back on limited info in the tree
 570             return endPos(tree);
 571         }
 572 
 573         int mapPos = endPosTable.getEndPos(tree);
 574         if (mapPos != Position.NOPOS)
 575             return mapPos;
 576 
 577         switch(tree.getTag()) {
 578             case BITOR_ASG: case BITXOR_ASG: case BITAND_ASG:
 579             case SL_ASG: case SR_ASG: case USR_ASG:
 580             case PLUS_ASG: case MINUS_ASG: case MUL_ASG:
 581             case DIV_ASG: case MOD_ASG:
 582             case OR: case AND: case BITOR:
 583             case BITXOR: case BITAND: case EQ:
 584             case NE: case LT: case GT:
 585             case LE: case GE: case SL:
 586             case SR: case USR: case PLUS:
 587             case MINUS: case MUL: case DIV:
 588             case MOD:
 589             case POS:
 590             case NEG:
 591             case NOT:
 592             case COMPL:
 593             case PREINC:
 594             case PREDEC:
 595                 return getEndPos(((JCOperatorExpression) tree).getOperand(RIGHT), endPosTable);
 596             case CASE:
 597                 return getEndPos(((JCCase) tree).stats.last(), endPosTable);
 598             case CATCH:
 599                 return getEndPos(((JCCatch) tree).body, endPosTable);
 600             case CONDEXPR:
 601                 return getEndPos(((JCConditional) tree).falsepart, endPosTable);
 602             case FORLOOP:
 603                 return getEndPos(((JCForLoop) tree).body, endPosTable);
 604             case FOREACHLOOP:
 605                 return getEndPos(((JCEnhancedForLoop) tree).body, endPosTable);
 606             case IF: {
 607                 JCIf node = (JCIf)tree;
 608                 if (node.elsepart == null) {
 609                     return getEndPos(node.thenpart, endPosTable);
 610                 } else {
 611                     return getEndPos(node.elsepart, endPosTable);
 612                 }
 613             }
 614             case LABELLED:
 615                 return getEndPos(((JCLabeledStatement) tree).body, endPosTable);
 616             case MODIFIERS:
 617                 return getEndPos(((JCModifiers) tree).annotations.last(), endPosTable);
 618             case SYNCHRONIZED:
 619                 return getEndPos(((JCSynchronized) tree).body, endPosTable);
 620             case TOPLEVEL:
 621                 return getEndPos(((JCCompilationUnit) tree).defs.last(), endPosTable);
 622             case TRY: {
 623                 JCTry node = (JCTry)tree;
 624                 if (node.finalizer != null) {
 625                     return getEndPos(node.finalizer, endPosTable);
 626                 } else if (!node.catchers.isEmpty()) {
 627                     return getEndPos(node.catchers.last(), endPosTable);
 628                 } else {
 629                     return getEndPos(node.body, endPosTable);
 630                 }
 631             }
 632             case WILDCARD:
 633                 return getEndPos(((JCWildcard) tree).inner, endPosTable);
 634             case TYPECAST:
 635                 return getEndPos(((JCTypeCast) tree).expr, endPosTable);
 636             case TYPETEST:
 637                 return getEndPos(((JCInstanceOf) tree).pattern, endPosTable);
 638             case WHILELOOP:
 639                 return getEndPos(((JCWhileLoop) tree).body, endPosTable);
 640             case ANNOTATED_TYPE:
 641                 return getEndPos(((JCAnnotatedType) tree).underlyingType, endPosTable);
 642             case PARENTHESIZEDPATTERN: {
 643                 JCParenthesizedPattern node = (JCParenthesizedPattern) tree;
 644                 return getEndPos(node.pattern, endPosTable);
 645             }
 646             case ERRONEOUS: {
 647                 JCErroneous node = (JCErroneous)tree;
 648                 if (node.errs != null && node.errs.nonEmpty())
 649                     return getEndPos(node.errs.last(), endPosTable);
 650             }
 651         }
 652         return Position.NOPOS;
 653     }
 654 
 655 
 656     /** A DiagnosticPosition with the preferred position set to the
 657      *  end position of given tree, if it is a block with
 658      *  defined endpos.
 659      */
 660     public static DiagnosticPosition diagEndPos(final JCTree tree) {
 661         final int endPos = TreeInfo.endPos(tree);
 662         return new DiagnosticPosition() {
 663             public JCTree getTree() { return tree; }
 664             public int getStartPosition() { return TreeInfo.getStartPos(tree); }
 665             public int getPreferredPosition() { return endPos; }
 666             public int getEndPosition(EndPosTable endPosTable) {
 667                 return TreeInfo.getEndPos(tree, endPosTable);
 668             }
 669         };
 670     }
 671 
 672     public enum PosKind {
 673         START_POS(TreeInfo::getStartPos),
 674         FIRST_STAT_POS(TreeInfo::firstStatPos),
 675         END_POS(TreeInfo::endPos);
 676 
 677         final ToIntFunction<JCTree> posFunc;
 678 
 679         PosKind(ToIntFunction<JCTree> posFunc) {
 680             this.posFunc = posFunc;
 681         }
 682 
 683         int toPos(JCTree tree) {
 684             return posFunc.applyAsInt(tree);
 685         }
 686     }
 687 
 688     /** The position of the finalizer of given try/synchronized statement.
 689      */
 690     public static int finalizerPos(JCTree tree, PosKind posKind) {
 691         if (tree.hasTag(TRY)) {
 692             JCTry t = (JCTry) tree;
 693             Assert.checkNonNull(t.finalizer);
 694             return posKind.toPos(t.finalizer);
 695         } else if (tree.hasTag(SYNCHRONIZED)) {
 696             return endPos(((JCSynchronized) tree).body);
 697         } else {
 698             throw new AssertionError();
 699         }
 700     }
 701 
 702     /** Find the position for reporting an error about a symbol, where
 703      *  that symbol is defined somewhere in the given tree. */
 704     public static int positionFor(final Symbol sym, final JCTree tree) {
 705         JCTree decl = declarationFor(sym, tree);
 706         return ((decl != null) ? decl : tree).pos;
 707     }
 708 
 709     /** Find the position for reporting an error about a symbol, where
 710      *  that symbol is defined somewhere in the given tree. */
 711     public static DiagnosticPosition diagnosticPositionFor(final Symbol sym, final JCTree tree) {
 712         return diagnosticPositionFor(sym, tree, false);
 713     }
 714 
 715     public static DiagnosticPosition diagnosticPositionFor(final Symbol sym, final JCTree tree, boolean returnNullIfNotFound) {
 716         return diagnosticPositionFor(sym, tree, returnNullIfNotFound, null);
 717     }
 718 
 719     public static DiagnosticPosition diagnosticPositionFor(final Symbol sym, final JCTree tree, boolean returnNullIfNotFound,
 720             Predicate<? super JCTree> filter) {
 721         class DiagScanner extends DeclScanner {
 722             DiagScanner(Symbol sym, Predicate<? super JCTree> filter) {
 723                 super(sym, filter);
 724             }
 725 
 726             public void visitIdent(JCIdent that) {
 727                 if (!checkMatch(that, that.sym))
 728                     super.visitIdent(that);
 729             }
 730             public void visitSelect(JCFieldAccess that) {
 731                 if (!checkMatch(that, that.sym))
 732                     super.visitSelect(that);
 733             }
 734         }
 735         DiagScanner s = new DiagScanner(sym, filter);
 736         tree.accept(s);
 737         JCTree decl = s.result;
 738         if (decl == null && returnNullIfNotFound) { return null; }
 739         return ((decl != null) ? decl : tree).pos();
 740     }
 741 
 742     public static DiagnosticPosition diagnosticPositionFor(final Symbol sym, final List<? extends JCTree> trees) {
 743         return trees.stream().map(t -> TreeInfo.diagnosticPositionFor(sym, t)).filter(t -> t != null).findFirst().get();
 744     }
 745 
 746     private static class DeclScanner extends TreeScanner {
 747         final Symbol sym;
 748         final Predicate<? super JCTree> filter;
 749 
 750         DeclScanner(final Symbol sym) {
 751             this(sym, null);
 752         }
 753         DeclScanner(final Symbol sym, Predicate<? super JCTree> filter) {
 754             this.sym = sym;
 755             this.filter = filter;
 756         }
 757 
 758         JCTree result = null;
 759         public void scan(JCTree tree) {
 760             if (tree!=null && result==null)
 761                 tree.accept(this);
 762         }
 763         public void visitTopLevel(JCCompilationUnit that) {
 764             if (!checkMatch(that, that.packge))
 765                 super.visitTopLevel(that);
 766         }
 767         public void visitModuleDef(JCModuleDecl that) {
 768             checkMatch(that, that.sym);
 769             // no need to scan within module declaration
 770         }
 771         public void visitPackageDef(JCPackageDecl that) {
 772             if (!checkMatch(that, that.packge))
 773                 super.visitPackageDef(that);
 774         }
 775         public void visitClassDef(JCClassDecl that) {
 776             if (!checkMatch(that, that.sym))
 777                 super.visitClassDef(that);
 778         }
 779         public void visitMethodDef(JCMethodDecl that) {
 780             if (!checkMatch(that, that.sym))
 781                 super.visitMethodDef(that);
 782         }
 783         public void visitVarDef(JCVariableDecl that) {
 784             if (!checkMatch(that, that.sym))
 785                 super.visitVarDef(that);
 786         }
 787         public void visitTypeParameter(JCTypeParameter that) {
 788             if (that.type == null || !checkMatch(that, that.type.tsym))
 789                 super.visitTypeParameter(that);
 790         }
 791 
 792         protected boolean checkMatch(JCTree that, Symbol thatSym) {
 793             if (thatSym == this.sym && (filter == null || filter.test(that))) {
 794                 result = that;
 795                 return true;
 796             }
 797             if (this.sym.getKind() == ElementKind.RECORD_COMPONENT) {
 798                 if (thatSym != null && thatSym.getKind() == ElementKind.FIELD && (thatSym.flags_field & RECORD) != 0) {
 799                     RecordComponent rc = thatSym.enclClass().getRecordComponent((VarSymbol)thatSym);
 800                     return checkMatch(rc.declarationFor(), rc);
 801                 }
 802             }
 803             return false;
 804         }
 805     }
 806 
 807     /** Find the declaration for a symbol, where
 808      *  that symbol is defined somewhere in the given tree. */
 809     public static JCTree declarationFor(final Symbol sym, final JCTree tree) {
 810         DeclScanner s = new DeclScanner(sym);
 811         tree.accept(s);
 812         return s.result;
 813     }
 814 
 815     /** Return the statement referenced by a label.
 816      *  If the label refers to a loop or switch, return that switch
 817      *  otherwise return the labelled statement itself
 818      */
 819     public static JCTree referencedStatement(JCLabeledStatement tree) {
 820         JCTree t = tree;
 821         do t = ((JCLabeledStatement) t).body;
 822         while (t.hasTag(LABELLED));
 823         switch (t.getTag()) {
 824         case DOLOOP: case WHILELOOP: case FORLOOP: case FOREACHLOOP: case SWITCH:
 825             return t;
 826         default:
 827             return tree;
 828         }
 829     }
 830 
 831     /** Skip parens and return the enclosed expression
 832      */
 833     public static JCExpression skipParens(JCExpression tree) {
 834         while (tree.hasTag(PARENS)) {
 835             tree = ((JCParens) tree).expr;
 836         }
 837         return tree;
 838     }
 839 
 840     /** Skip parens and return the enclosed expression
 841      */
 842     public static JCTree skipParens(JCTree tree) {
 843         if (tree.hasTag(PARENS))
 844             return skipParens((JCParens)tree);
 845         else
 846             return tree;
 847     }
 848 
 849     /** Skip parens and return the enclosed expression
 850      */
 851     public static JCPattern skipParens(JCPattern tree) {
 852         while (tree.hasTag(PARENTHESIZEDPATTERN)) {
 853             tree = ((JCParenthesizedPattern) tree).pattern;
 854         }
 855         return tree;
 856     }
 857 
 858     /** Return the types of a list of trees.
 859      */
 860     public static List<Type> types(List<? extends JCTree> trees) {
 861         ListBuffer<Type> ts = new ListBuffer<>();
 862         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
 863             ts.append(l.head.type);
 864         return ts.toList();
 865     }
 866 
 867     /** If this tree is an identifier or a field or a parameterized type,
 868      *  return its name, otherwise return null.
 869      */
 870     public static Name name(JCTree tree) {
 871         switch (tree.getTag()) {
 872         case IDENT:
 873             return ((JCIdent) tree).name;
 874         case SELECT:
 875             return ((JCFieldAccess) tree).name;
 876         case TYPEAPPLY:
 877             return name(((JCTypeApply) tree).clazz);
 878         default:
 879             return null;
 880         }
 881     }
 882 
 883     /** If this tree is a qualified identifier, its return fully qualified name,
 884      *  otherwise return null.
 885      */
 886     public static Name fullName(JCTree tree) {
 887         tree = skipParens(tree);
 888         switch (tree.getTag()) {
 889         case IDENT:
 890             return ((JCIdent) tree).name;
 891         case SELECT:
 892             Name sname = fullName(((JCFieldAccess) tree).selected);
 893             return sname == null ? null : sname.append('.', name(tree));
 894         default:
 895             return null;
 896         }
 897     }
 898 
 899     public static Symbol symbolFor(JCTree node) {
 900         Symbol sym = symbolForImpl(node);
 901 
 902         return sym != null ? sym.baseSymbol() : null;
 903     }
 904 
 905     private static Symbol symbolForImpl(JCTree node) {
 906         node = skipParens(node);
 907         switch (node.getTag()) {
 908         case TOPLEVEL:
 909             JCCompilationUnit cut = (JCCompilationUnit) node;
 910             JCModuleDecl moduleDecl = cut.getModuleDecl();
 911             if (isModuleInfo(cut) && moduleDecl != null)
 912                 return symbolFor(moduleDecl);
 913             return cut.packge;
 914         case MODULEDEF:
 915             return ((JCModuleDecl) node).sym;
 916         case PACKAGEDEF:
 917             return ((JCPackageDecl) node).packge;
 918         case CLASSDEF:
 919             return ((JCClassDecl) node).sym;
 920         case METHODDEF:
 921             return ((JCMethodDecl) node).sym;
 922         case VARDEF:
 923             return ((JCVariableDecl) node).sym;
 924         case IDENT:
 925             return ((JCIdent) node).sym;
 926         case SELECT:
 927             return ((JCFieldAccess) node).sym;
 928         case REFERENCE:
 929             return ((JCMemberReference) node).sym;
 930         case NEWCLASS:
 931             return ((JCNewClass) node).constructor;
 932         case APPLY:
 933             return symbolFor(((JCMethodInvocation) node).meth);
 934         case TYPEAPPLY:
 935             return symbolFor(((JCTypeApply) node).clazz);
 936         case ANNOTATION:
 937         case TYPE_ANNOTATION:
 938         case TYPEPARAMETER:
 939             if (node.type != null)
 940                 return node.type.tsym;
 941             return null;
 942         default:
 943             return null;
 944         }
 945     }
 946 
 947     public static boolean isDeclaration(JCTree node) {
 948         node = skipParens(node);
 949         switch (node.getTag()) {
 950         case PACKAGEDEF:
 951         case CLASSDEF:
 952         case METHODDEF:
 953         case VARDEF:
 954             return true;
 955         default:
 956             return false;
 957         }
 958     }
 959 
 960     /** If this tree is an identifier or a field, return its symbol,
 961      *  otherwise return null.
 962      */
 963     public static Symbol symbol(JCTree tree) {
 964         tree = skipParens(tree);
 965         switch (tree.getTag()) {
 966         case IDENT:
 967             return ((JCIdent) tree).sym;
 968         case SELECT:
 969             return ((JCFieldAccess) tree).sym;
 970         case TYPEAPPLY:
 971             return symbol(((JCTypeApply) tree).clazz);
 972         case ANNOTATED_TYPE:
 973             return symbol(((JCAnnotatedType) tree).underlyingType);
 974         case REFERENCE:
 975             return ((JCMemberReference) tree).sym;
 976         default:
 977             return null;
 978         }
 979     }
 980 
 981     /** If this tree has a modifiers field, return it otherwise return null
 982      */
 983     public static JCModifiers getModifiers(JCTree tree) {
 984         tree = skipParens(tree);
 985         switch (tree.getTag()) {
 986             case VARDEF:
 987                 return ((JCVariableDecl) tree).mods;
 988             case METHODDEF:
 989                 return ((JCMethodDecl) tree).mods;
 990             case CLASSDEF:
 991                 return ((JCClassDecl) tree).mods;
 992             case MODULEDEF:
 993                 return ((JCModuleDecl) tree).mods;
 994         default:
 995             return null;
 996         }
 997     }
 998 
 999     /** Return true if this is a nonstatic selection. */
1000     public static boolean nonstaticSelect(JCTree tree) {
1001         tree = skipParens(tree);
1002         if (!tree.hasTag(SELECT)) return false;
1003         JCFieldAccess s = (JCFieldAccess) tree;
1004         Symbol e = symbol(s.selected);
1005         return e == null || (e.kind != PCK && e.kind != TYP);
1006     }
1007 
1008     /** If this tree is an identifier or a field, set its symbol, otherwise skip.
1009      */
1010     public static void setSymbol(JCTree tree, Symbol sym) {
1011         tree = skipParens(tree);
1012         switch (tree.getTag()) {
1013         case IDENT:
1014             ((JCIdent) tree).sym = sym; break;
1015         case SELECT:
1016             ((JCFieldAccess) tree).sym = sym; break;
1017         default:
1018         }
1019     }
1020 
1021     /** If this tree is a declaration or a block, return its flags field,
1022      *  otherwise return 0.
1023      */
1024     public static long flags(JCTree tree) {
1025         switch (tree.getTag()) {
1026         case VARDEF:
1027             return ((JCVariableDecl) tree).mods.flags;
1028         case METHODDEF:
1029             return ((JCMethodDecl) tree).mods.flags;
1030         case CLASSDEF:
1031             return ((JCClassDecl) tree).mods.flags;
1032         case BLOCK:
1033             return ((JCBlock) tree).flags;
1034         default:
1035             return 0;
1036         }
1037     }
1038 
1039     /** Return first (smallest) flag in `flags':
1040      *  pre: flags != 0
1041      */
1042     public static long firstFlag(long flags) {
1043         long flag = 1;
1044         while ((flag & flags) == 0)
1045             flag = flag << 1;
1046         return flag;
1047     }
1048 
1049     /** Return flags as a string, separated by " ".
1050      */
1051     public static String flagNames(long flags) {
1052         return Flags.toString(flags & ExtendedStandardFlags).trim();
1053     }
1054 
1055     /** Operator precedences values.
1056      */
1057     public static final int
1058         notExpression = -1,   // not an expression
1059         noPrec = 0,           // no enclosing expression
1060         assignPrec = 1,
1061         assignopPrec = 2,
1062         condPrec = 3,
1063         orPrec = 4,
1064         andPrec = 5,
1065         bitorPrec = 6,
1066         bitxorPrec = 7,
1067         bitandPrec = 8,
1068         eqPrec = 9,
1069         ordPrec = 10,
1070         shiftPrec = 11,
1071         addPrec = 12,
1072         mulPrec = 13,
1073         prefixPrec = 14,
1074         postfixPrec = 15,
1075         precCount = 16;
1076 
1077 
1078     /** Map operators to their precedence levels.
1079      */
1080     public static int opPrec(JCTree.Tag op) {
1081         switch(op) {
1082         case POS:
1083         case NEG:
1084         case NOT:
1085         case COMPL:
1086         case PREINC:
1087         case PREDEC: return prefixPrec;
1088         case POSTINC:
1089         case POSTDEC:
1090         case NULLCHK: return postfixPrec;
1091         case ASSIGN: return assignPrec;
1092         case BITOR_ASG:
1093         case BITXOR_ASG:
1094         case BITAND_ASG:
1095         case SL_ASG:
1096         case SR_ASG:
1097         case USR_ASG:
1098         case PLUS_ASG:
1099         case MINUS_ASG:
1100         case MUL_ASG:
1101         case DIV_ASG:
1102         case MOD_ASG: return assignopPrec;
1103         case OR: return orPrec;
1104         case AND: return andPrec;
1105         case EQ:
1106         case NE: return eqPrec;
1107         case LT:
1108         case GT:
1109         case LE:
1110         case GE: return ordPrec;
1111         case BITOR: return bitorPrec;
1112         case BITXOR: return bitxorPrec;
1113         case BITAND: return bitandPrec;
1114         case SL:
1115         case SR:
1116         case USR: return shiftPrec;
1117         case PLUS:
1118         case MINUS: return addPrec;
1119         case MUL:
1120         case DIV:
1121         case MOD: return mulPrec;
1122         case TYPETEST: return ordPrec;
1123         default: throw new AssertionError();
1124         }
1125     }
1126 
1127     static Tree.Kind tagToKind(JCTree.Tag tag) {
1128         switch (tag) {
1129         // Postfix expressions
1130         case POSTINC:           // _ ++
1131             return Tree.Kind.POSTFIX_INCREMENT;
1132         case POSTDEC:           // _ --
1133             return Tree.Kind.POSTFIX_DECREMENT;
1134 
1135         // Unary operators
1136         case PREINC:            // ++ _
1137             return Tree.Kind.PREFIX_INCREMENT;
1138         case PREDEC:            // -- _
1139             return Tree.Kind.PREFIX_DECREMENT;
1140         case POS:               // +
1141             return Tree.Kind.UNARY_PLUS;
1142         case NEG:               // -
1143             return Tree.Kind.UNARY_MINUS;
1144         case COMPL:             // ~
1145             return Tree.Kind.BITWISE_COMPLEMENT;
1146         case NOT:               // !
1147             return Tree.Kind.LOGICAL_COMPLEMENT;
1148 
1149         // Binary operators
1150 
1151         // Multiplicative operators
1152         case MUL:               // *
1153             return Tree.Kind.MULTIPLY;
1154         case DIV:               // /
1155             return Tree.Kind.DIVIDE;
1156         case MOD:               // %
1157             return Tree.Kind.REMAINDER;
1158 
1159         // Additive operators
1160         case PLUS:              // +
1161             return Tree.Kind.PLUS;
1162         case MINUS:             // -
1163             return Tree.Kind.MINUS;
1164 
1165         // Shift operators
1166         case SL:                // <<
1167             return Tree.Kind.LEFT_SHIFT;
1168         case SR:                // >>
1169             return Tree.Kind.RIGHT_SHIFT;
1170         case USR:               // >>>
1171             return Tree.Kind.UNSIGNED_RIGHT_SHIFT;
1172 
1173         // Relational operators
1174         case LT:                // <
1175             return Tree.Kind.LESS_THAN;
1176         case GT:                // >
1177             return Tree.Kind.GREATER_THAN;
1178         case LE:                // <=
1179             return Tree.Kind.LESS_THAN_EQUAL;
1180         case GE:                // >=
1181             return Tree.Kind.GREATER_THAN_EQUAL;
1182 
1183         // Equality operators
1184         case EQ:                // ==
1185             return Tree.Kind.EQUAL_TO;
1186         case NE:                // !=
1187             return Tree.Kind.NOT_EQUAL_TO;
1188 
1189         // Bitwise and logical operators
1190         case BITAND:            // &
1191             return Tree.Kind.AND;
1192         case BITXOR:            // ^
1193             return Tree.Kind.XOR;
1194         case BITOR:             // |
1195             return Tree.Kind.OR;
1196 
1197         // Conditional operators
1198         case AND:               // &&
1199             return Tree.Kind.CONDITIONAL_AND;
1200         case OR:                // ||
1201             return Tree.Kind.CONDITIONAL_OR;
1202 
1203         // Assignment operators
1204         case MUL_ASG:           // *=
1205             return Tree.Kind.MULTIPLY_ASSIGNMENT;
1206         case DIV_ASG:           // /=
1207             return Tree.Kind.DIVIDE_ASSIGNMENT;
1208         case MOD_ASG:           // %=
1209             return Tree.Kind.REMAINDER_ASSIGNMENT;
1210         case PLUS_ASG:          // +=
1211             return Tree.Kind.PLUS_ASSIGNMENT;
1212         case MINUS_ASG:         // -=
1213             return Tree.Kind.MINUS_ASSIGNMENT;
1214         case SL_ASG:            // <<=
1215             return Tree.Kind.LEFT_SHIFT_ASSIGNMENT;
1216         case SR_ASG:            // >>=
1217             return Tree.Kind.RIGHT_SHIFT_ASSIGNMENT;
1218         case USR_ASG:           // >>>=
1219             return Tree.Kind.UNSIGNED_RIGHT_SHIFT_ASSIGNMENT;
1220         case BITAND_ASG:        // &=
1221             return Tree.Kind.AND_ASSIGNMENT;
1222         case BITXOR_ASG:        // ^=
1223             return Tree.Kind.XOR_ASSIGNMENT;
1224         case BITOR_ASG:         // |=
1225             return Tree.Kind.OR_ASSIGNMENT;
1226 
1227         // Null check (implementation detail), for example, __.getClass()
1228         case NULLCHK:
1229             return Tree.Kind.OTHER;
1230 
1231         case ANNOTATION:
1232             return Tree.Kind.ANNOTATION;
1233         case TYPE_ANNOTATION:
1234             return Tree.Kind.TYPE_ANNOTATION;
1235 
1236         case EXPORTS:
1237             return Tree.Kind.EXPORTS;
1238         case OPENS:
1239             return Tree.Kind.OPENS;
1240 
1241         default:
1242             return null;
1243         }
1244     }
1245 
1246     /**
1247      * Returns the underlying type of the tree if it is an annotated type,
1248      * or the tree itself otherwise.
1249      */
1250     public static JCExpression typeIn(JCExpression tree) {
1251         switch (tree.getTag()) {
1252         case ANNOTATED_TYPE:
1253             return ((JCAnnotatedType)tree).underlyingType;
1254         case IDENT: /* simple names */
1255         case TYPEIDENT: /* primitive name */
1256         case SELECT: /* qualified name */
1257         case TYPEARRAY: /* array types */
1258         case WILDCARD: /* wild cards */
1259         case TYPEPARAMETER: /* type parameters */
1260         case TYPEAPPLY: /* parameterized types */
1261         case ERRONEOUS: /* error tree TODO: needed for BadCast JSR308 test case. Better way? */
1262             return tree;
1263         default:
1264             throw new AssertionError("Unexpected type tree: " + tree);
1265         }
1266     }
1267 
1268     /* Return the inner-most type of a type tree.
1269      * For an array that contains an annotated type, return that annotated type.
1270      * TODO: currently only used by Pretty. Describe behavior better.
1271      */
1272     public static JCTree innermostType(JCTree type, boolean skipAnnos) {
1273         JCTree lastAnnotatedType = null;
1274         JCTree cur = type;
1275         loop: while (true) {
1276             switch (cur.getTag()) {
1277             case TYPEARRAY:
1278                 lastAnnotatedType = null;
1279                 cur = ((JCArrayTypeTree)cur).elemtype;
1280                 break;
1281             case WILDCARD:
1282                 lastAnnotatedType = null;
1283                 cur = ((JCWildcard)cur).inner;
1284                 break;
1285             case ANNOTATED_TYPE:
1286                 lastAnnotatedType = cur;
1287                 cur = ((JCAnnotatedType)cur).underlyingType;
1288                 break;
1289             default:
1290                 break loop;
1291             }
1292         }
1293         if (!skipAnnos && lastAnnotatedType!=null) {
1294             return lastAnnotatedType;
1295         } else {
1296             return cur;
1297         }
1298     }
1299 
1300     private static class TypeAnnotationFinder extends TreeScanner {
1301         public boolean foundTypeAnno = false;
1302 
1303         @Override
1304         public void scan(JCTree tree) {
1305             if (foundTypeAnno || tree == null)
1306                 return;
1307             super.scan(tree);
1308         }
1309 
1310         public void visitAnnotation(JCAnnotation tree) {
1311             foundTypeAnno = foundTypeAnno || tree.hasTag(TYPE_ANNOTATION);
1312         }
1313     }
1314 
1315     public static boolean containsTypeAnnotation(JCTree e) {
1316         TypeAnnotationFinder finder = new TypeAnnotationFinder();
1317         finder.scan(e);
1318         return finder.foundTypeAnno;
1319     }
1320 
1321     public static boolean isModuleInfo(JCCompilationUnit tree) {
1322         return tree.sourcefile.isNameCompatible("module-info", JavaFileObject.Kind.SOURCE)
1323                 && tree.getModuleDecl() != null;
1324     }
1325 
1326     public static JCModuleDecl getModule(JCCompilationUnit t) {
1327         if (t.defs.nonEmpty()) {
1328             JCTree def = t.defs.head;
1329             if (def.hasTag(MODULEDEF))
1330                 return (JCModuleDecl) def;
1331         }
1332         return null;
1333     }
1334 
1335     public static boolean isPackageInfo(JCCompilationUnit tree) {
1336         return tree.sourcefile.isNameCompatible("package-info", JavaFileObject.Kind.SOURCE);
1337     }
1338 
1339     public static boolean isErrorEnumSwitch(JCExpression selector, List<JCCase> cases) {
1340         return selector.type.tsym.kind == Kinds.Kind.ERR &&
1341                cases.stream().flatMap(c -> c.labels.stream())
1342                              .filter(l -> l.hasTag(CONSTANTCASELABEL))
1343                              .map(l -> ((JCConstantCaseLabel) l).expr)
1344                              .allMatch(p -> p.hasTag(IDENT));
1345     }
1346 
1347     public static Type primaryPatternType(JCTree pat) {
1348         return switch (pat.getTag()) {
1349             case BINDINGPATTERN -> pat.type;
1350             case PARENTHESIZEDPATTERN -> primaryPatternType(((JCParenthesizedPattern) pat).pattern);
1351             case RECORDPATTERN -> ((JCRecordPattern) pat).type;
1352             default -> throw new AssertionError();
1353         };
1354     }
1355 
1356     public static JCTree primaryPatternTypeTree(JCTree pat) {
1357         return switch (pat.getTag()) {
1358             case BINDINGPATTERN -> ((JCBindingPattern) pat).var.vartype;
1359             case PARENTHESIZEDPATTERN -> primaryPatternTypeTree(((JCParenthesizedPattern) pat).pattern);
1360             case RECORDPATTERN -> ((JCRecordPattern) pat).deconstructor;
1361             default -> throw new AssertionError();
1362         };
1363     }
1364 
1365     public static boolean expectedExhaustive(JCSwitch tree) {
1366         return tree.patternSwitch ||
1367                tree.cases.stream()
1368                          .flatMap(c -> c.labels.stream())
1369                          .anyMatch(l -> TreeInfo.isNullCaseLabel(l));
1370     }
1371 
1372     public static boolean unguardedCaseLabel(JCCaseLabel cse) {
1373         if (!cse.hasTag(PATTERNCASELABEL)) {
1374             return true;
1375         }
1376         JCExpression guard = ((JCPatternCaseLabel) cse).guard;
1377         if (guard == null) {
1378             return true;
1379         }
1380         return isBooleanWithValue(guard, 1);
1381     }
1382 
1383     public static boolean isBooleanWithValue(JCExpression guard, int value) {
1384         var constValue = guard.type.constValue();
1385         return constValue != null &&
1386                 guard.type.hasTag(BOOLEAN) &&
1387                 ((int) constValue) == value;
1388     }
1389 
1390     public static boolean isNullCaseLabel(JCCaseLabel label) {
1391         return label.hasTag(CONSTANTCASELABEL) &&
1392                TreeInfo.isNull(((JCConstantCaseLabel) label).expr);
1393     }
1394 }