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