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