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