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 return isTypeSelector(base, names, TreeInfo::isStaticSym);
441 }
442 //where
443 private static boolean isStaticSym(JCTree tree) {
444 Symbol sym = symbol(tree);
445 return (sym.kind == TYP || sym.kind == PCK);
446 }
447
448 public static boolean isType(JCTree base, Names names) {
449 return isTypeSelector(base, names, _ -> true);
450 }
451
452 private static boolean isTypeSelector(JCTree base, Names names, Predicate<JCTree> checkStaticSym) {
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 checkStaticSym.test(base);
461 case SELECT:
462 return checkStaticSym.test(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
474 /** Return true if a tree represents the null literal. */
475 public static boolean isNull(JCTree tree) {
476 if (!tree.hasTag(LITERAL))
477 return false;
478 JCLiteral lit = (JCLiteral) tree;
479 return (lit.typetag == BOT);
480 }
481
482 /** Return true iff this tree is a child of some annotation. */
483 public static boolean isInAnnotation(Env<?> env, JCTree tree) {
484 TreePath tp = TreePath.getPath(env.toplevel, tree);
485 if (tp != null) {
486 for (Tree t : tp) {
487 if (t.getKind() == Tree.Kind.ANNOTATION)
488 return true;
489 }
490 }
491 return false;
492 }
493
494 public static String getCommentText(Env<?> env, JCTree tree) {
495 DocCommentTable docComments = (tree.hasTag(JCTree.Tag.TOPLEVEL))
496 ? ((JCCompilationUnit) tree).docComments
497 : env.toplevel.docComments;
498 return (docComments == null) ? null : docComments.getCommentText(tree);
499 }
500
501 /** The position of the first statement in a block, or the position of
502 * the block itself if it is empty.
503 */
504 public static int firstStatPos(JCTree tree) {
505 if (tree.hasTag(BLOCK) && ((JCBlock) tree).stats.nonEmpty())
506 return ((JCBlock) tree).stats.head.pos;
507 else
508 return tree.pos;
509 }
510
511 /** The closing brace position of given tree, if it is a block with
512 * defined bracePos.
513 */
514 public static int endPos(JCTree tree) {
515 if (tree.hasTag(BLOCK) && ((JCBlock) tree).bracePos != Position.NOPOS)
516 return ((JCBlock) tree).bracePos;
517 else if (tree.hasTag(SYNCHRONIZED))
518 return endPos(((JCSynchronized) tree).body);
519 else if (tree.hasTag(TRY)) {
520 JCTry t = (JCTry) tree;
521 return endPos((t.finalizer != null) ? t.finalizer
522 : (t.catchers.nonEmpty() ? t.catchers.last().body : t.body));
523 } else if (tree.hasTag(SWITCH) &&
524 ((JCSwitch) tree).bracePos != Position.NOPOS) {
525 return ((JCSwitch) tree).bracePos;
526 } else if (tree.hasTag(SWITCH_EXPRESSION) &&
527 ((JCSwitchExpression) tree).bracePos != Position.NOPOS) {
528 return ((JCSwitchExpression) tree).bracePos;
529 } else
530 return tree.pos;
531 }
532
533
534 /** Get the start position for a tree node. The start position is
535 * defined to be the position of the first character of the first
536 * token of the node's source text.
537 * @param tree The tree node
538 */
539 public static int getStartPos(JCTree tree) {
540 if (tree == null)
541 return Position.NOPOS;
542
543 switch(tree.getTag()) {
544 case MODULEDEF: {
545 JCModuleDecl md = (JCModuleDecl)tree;
546 return md.mods.annotations.isEmpty() ? md.pos :
547 md.mods.annotations.head.pos;
548 }
549 case PACKAGEDEF: {
550 JCPackageDecl pd = (JCPackageDecl)tree;
551 return pd.annotations.isEmpty() ? pd.pos :
552 pd.annotations.head.pos;
553 }
554 case APPLY:
555 return getStartPos(((JCMethodInvocation) tree).meth);
556 case ASSIGN:
557 return getStartPos(((JCAssign) tree).lhs);
558 case BITOR_ASG: case BITXOR_ASG: case BITAND_ASG:
559 case SL_ASG: case SR_ASG: case USR_ASG:
560 case PLUS_ASG: case MINUS_ASG: case MUL_ASG:
561 case DIV_ASG: case MOD_ASG:
562 case OR: case AND: case BITOR:
563 case BITXOR: case BITAND: case EQ:
564 case NE: case LT: case GT:
565 case LE: case GE: case SL:
566 case SR: case USR: case PLUS:
567 case MINUS: case MUL: case DIV:
568 case MOD:
569 case POSTINC:
570 case POSTDEC:
571 return getStartPos(((JCOperatorExpression) tree).getOperand(LEFT));
572 case CLASSDEF: {
573 JCClassDecl node = (JCClassDecl)tree;
574 if (node.mods.pos != Position.NOPOS)
575 return node.mods.pos;
576 break;
577 }
578 case CONDEXPR:
579 return getStartPos(((JCConditional) tree).cond);
580 case EXEC:
581 return getStartPos(((JCExpressionStatement) tree).expr);
582 case INDEXED:
583 return getStartPos(((JCArrayAccess) tree).indexed);
584 case METHODDEF: {
585 JCMethodDecl node = (JCMethodDecl)tree;
586 if (node.mods.pos != Position.NOPOS)
587 return node.mods.pos;
588 if (node.typarams.nonEmpty()) // List.nil() used for no typarams
589 return getStartPos(node.typarams.head);
590 return node.restype == null ? node.pos : getStartPos(node.restype);
591 }
592 case SELECT:
593 return getStartPos(((JCFieldAccess) tree).selected);
594 case TYPEAPPLY:
595 return getStartPos(((JCTypeApply) tree).clazz);
596 case TYPEARRAY:
597 return getStartPos(((JCArrayTypeTree) tree).elemtype);
598 case TYPETEST:
599 return getStartPos(((JCInstanceOf) tree).expr);
600 case ANNOTATED_TYPE: {
601 JCAnnotatedType node = (JCAnnotatedType) tree;
602 if (node.annotations.nonEmpty()) {
603 if (node.underlyingType.hasTag(TYPEARRAY) ||
604 node.underlyingType.hasTag(SELECT)) {
605 return getStartPos(node.underlyingType);
606 } else {
607 return getStartPos(node.annotations.head);
608 }
609 } else {
610 return getStartPos(node.underlyingType);
611 }
612 }
613 case NEWCLASS: {
614 JCNewClass node = (JCNewClass)tree;
615 if (node.encl != null)
616 return getStartPos(node.encl);
617 break;
618 }
619 case VARDEF: {
620 JCVariableDecl node = (JCVariableDecl)tree;
621 if (node.mods.pos != Position.NOPOS) {
622 return node.mods.pos;
623 } else if (node.vartype != null) {
624 return getStartPos(node.vartype);
625 } else if (node.typePos != Position.NOPOS) {
626 return node.typePos;
627 }
628 break;
629 }
630 case BINDINGPATTERN: {
631 JCBindingPattern node = (JCBindingPattern)tree;
632 return getStartPos(node.var);
633 }
634 case ERRONEOUS: {
635 JCErroneous node = (JCErroneous)tree;
636 if (node.errs != null && node.errs.nonEmpty()) {
637 int pos = getStartPos(node.errs.head);
638 if (pos != Position.NOPOS) {
639 return pos;
640 }
641 }
642 break;
643 }
644 }
645 return tree.pos;
646 }
647
648 /** The end position of given tree, given a table of end positions generated by the parser
649 */
650 public static int getEndPos(JCTree tree, EndPosTable endPosTable) {
651 if (tree == null)
652 return Position.NOPOS;
653
654 if (endPosTable == null) {
655 // fall back on limited info in the tree
656 return endPos(tree);
657 }
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 }