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