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