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