src/share/classes/com/sun/tools/javac/tree/TreeInfo.java

Wed, 07 Jun 2017 00:04:12 -0700

author
shshahma
date
Wed, 07 Jun 2017 00:04:12 -0700
changeset 3497
08a21473de54
parent 3371
7220be8747f0
child 3446
e468915bad3a
permissions
-rw-r--r--

8180660: missing LNT entry for finally block
Reviewed-by: mcimadamore, vromero
Contributed-by: maurizio.cimadamore@oracle.com, vicente.romero@oracle.com

     1 /*
     2  * Copyright (c) 1999, 2017, 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  */
    26 package com.sun.tools.javac.tree;
    30 import com.sun.source.tree.Tree;
    31 import com.sun.source.util.TreePath;
    32 import com.sun.tools.javac.code.*;
    33 import com.sun.tools.javac.comp.AttrContext;
    34 import com.sun.tools.javac.comp.Env;
    35 import com.sun.tools.javac.tree.JCTree.*;
    36 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
    37 import com.sun.tools.javac.util.*;
    39 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    40 import static com.sun.tools.javac.code.Flags.*;
    41 import static com.sun.tools.javac.code.TypeTag.BOT;
    42 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    43 import static com.sun.tools.javac.tree.JCTree.Tag.BLOCK;
    44 import static com.sun.tools.javac.tree.JCTree.Tag.SYNCHRONIZED;
    46 /** Utility class containing inspector methods for trees.
    47  *
    48  *  <p><b>This is NOT part of any supported API.
    49  *  If you write code that depends on this, you do so at your own risk.
    50  *  This code and its internal interfaces are subject to change or
    51  *  deletion without notice.</b>
    52  */
    53 public class TreeInfo {
    54     protected static final Context.Key<TreeInfo> treeInfoKey =
    55         new Context.Key<TreeInfo>();
    57     public static TreeInfo instance(Context context) {
    58         TreeInfo instance = context.get(treeInfoKey);
    59         if (instance == null)
    60             instance = new TreeInfo(context);
    61         return instance;
    62     }
    64     /** The names of all operators.
    65      */
    66     private Name[] opname = new Name[Tag.getNumberOfOperators()];
    68     private void setOpname(Tag tag, String name, Names names) {
    69          setOpname(tag, names.fromString(name));
    70      }
    71      private void setOpname(Tag tag, Name name) {
    72          opname[tag.operatorIndex()] = name;
    73      }
    75     private TreeInfo(Context context) {
    76         context.put(treeInfoKey, this);
    78         Names names = Names.instance(context);
    79         /*  Internally we use +++, --- for unary +, - to reduce +, - operators
    80          *  overloading
    81          */
    82         setOpname(POS, "+++", names);
    83         setOpname(NEG, "---", names);
    84         setOpname(NOT, "!", names);
    85         setOpname(COMPL, "~", names);
    86         setOpname(PREINC, "++", names);
    87         setOpname(PREDEC, "--", names);
    88         setOpname(POSTINC, "++", names);
    89         setOpname(POSTDEC, "--", names);
    90         setOpname(NULLCHK, "<*nullchk*>", names);
    91         setOpname(OR, "||", names);
    92         setOpname(AND, "&&", names);
    93         setOpname(EQ, "==", names);
    94         setOpname(NE, "!=", names);
    95         setOpname(LT, "<", names);
    96         setOpname(GT, ">", names);
    97         setOpname(LE, "<=", names);
    98         setOpname(GE, ">=", names);
    99         setOpname(BITOR, "|", names);
   100         setOpname(BITXOR, "^", names);
   101         setOpname(BITAND, "&", names);
   102         setOpname(SL, "<<", names);
   103         setOpname(SR, ">>", names);
   104         setOpname(USR, ">>>", names);
   105         setOpname(PLUS, "+", names);
   106         setOpname(MINUS, names.hyphen);
   107         setOpname(MUL, names.asterisk);
   108         setOpname(DIV, names.slash);
   109         setOpname(MOD, "%", names);
   110     }
   112     public static List<JCExpression> args(JCTree t) {
   113         switch (t.getTag()) {
   114             case APPLY:
   115                 return ((JCMethodInvocation)t).args;
   116             case NEWCLASS:
   117                 return ((JCNewClass)t).args;
   118             default:
   119                 return null;
   120         }
   121     }
   123     /** Return name of operator with given tree tag.
   124      */
   125     public Name operatorName(JCTree.Tag tag) {
   126         return opname[tag.operatorIndex()];
   127     }
   129     /** Is tree a constructor declaration?
   130      */
   131     public static boolean isConstructor(JCTree tree) {
   132         if (tree.hasTag(METHODDEF)) {
   133             Name name = ((JCMethodDecl) tree).name;
   134             return name == name.table.names.init;
   135         } else {
   136             return false;
   137         }
   138     }
   140     public static boolean isReceiverParam(JCTree tree) {
   141         if (tree.hasTag(VARDEF)) {
   142             return ((JCVariableDecl)tree).nameexpr != null;
   143         } else {
   144             return false;
   145         }
   146     }
   148     /** Is there a constructor declaration in the given list of trees?
   149      */
   150     public static boolean hasConstructors(List<JCTree> trees) {
   151         for (List<JCTree> l = trees; l.nonEmpty(); l = l.tail)
   152             if (isConstructor(l.head)) return true;
   153         return false;
   154     }
   156     public static boolean isMultiCatch(JCCatch catchClause) {
   157         return catchClause.param.vartype.hasTag(TYPEUNION);
   158     }
   160     /** Is statement an initializer for a synthetic field?
   161      */
   162     public static boolean isSyntheticInit(JCTree stat) {
   163         if (stat.hasTag(EXEC)) {
   164             JCExpressionStatement exec = (JCExpressionStatement)stat;
   165             if (exec.expr.hasTag(ASSIGN)) {
   166                 JCAssign assign = (JCAssign)exec.expr;
   167                 if (assign.lhs.hasTag(SELECT)) {
   168                     JCFieldAccess select = (JCFieldAccess)assign.lhs;
   169                     if (select.sym != null &&
   170                         (select.sym.flags() & SYNTHETIC) != 0) {
   171                         Name selected = name(select.selected);
   172                         if (selected != null && selected == selected.table.names._this)
   173                             return true;
   174                     }
   175                 }
   176             }
   177         }
   178         return false;
   179     }
   181     /** If the expression is a method call, return the method name, null
   182      *  otherwise. */
   183     public static Name calledMethodName(JCTree tree) {
   184         if (tree.hasTag(EXEC)) {
   185             JCExpressionStatement exec = (JCExpressionStatement)tree;
   186             if (exec.expr.hasTag(APPLY)) {
   187                 Name mname = TreeInfo.name(((JCMethodInvocation) exec.expr).meth);
   188                 return mname;
   189             }
   190         }
   191         return null;
   192     }
   194     /** Is this a call to this or super?
   195      */
   196     public static boolean isSelfCall(JCTree tree) {
   197         Name name = calledMethodName(tree);
   198         if (name != null) {
   199             Names names = name.table.names;
   200             return name==names._this || name==names._super;
   201         } else {
   202             return false;
   203         }
   204     }
   206     /** Is this a call to super?
   207      */
   208     public static boolean isSuperCall(JCTree tree) {
   209         Name name = calledMethodName(tree);
   210         if (name != null) {
   211             Names names = name.table.names;
   212             return name==names._super;
   213         } else {
   214             return false;
   215         }
   216     }
   218     /** Is this a constructor whose first (non-synthetic) statement is not
   219      *  of the form this(...)?
   220      */
   221     public static boolean isInitialConstructor(JCTree tree) {
   222         JCMethodInvocation app = firstConstructorCall(tree);
   223         if (app == null) return false;
   224         Name meth = name(app.meth);
   225         return meth == null || meth != meth.table.names._this;
   226     }
   228     /** Return the first call in a constructor definition. */
   229     public static JCMethodInvocation firstConstructorCall(JCTree tree) {
   230         if (!tree.hasTag(METHODDEF)) return null;
   231         JCMethodDecl md = (JCMethodDecl) tree;
   232         Names names = md.name.table.names;
   233         if (md.name != names.init) return null;
   234         if (md.body == null) return null;
   235         List<JCStatement> stats = md.body.stats;
   236         // Synthetic initializations can appear before the super call.
   237         while (stats.nonEmpty() && isSyntheticInit(stats.head))
   238             stats = stats.tail;
   239         if (stats.isEmpty()) return null;
   240         if (!stats.head.hasTag(EXEC)) return null;
   241         JCExpressionStatement exec = (JCExpressionStatement) stats.head;
   242         if (!exec.expr.hasTag(APPLY)) return null;
   243         return (JCMethodInvocation)exec.expr;
   244     }
   246     /** Return true if a tree represents a diamond new expr. */
   247     public static boolean isDiamond(JCTree tree) {
   248         switch(tree.getTag()) {
   249             case TYPEAPPLY: return ((JCTypeApply)tree).getTypeArguments().isEmpty();
   250             case NEWCLASS: return isDiamond(((JCNewClass)tree).clazz);
   251             case ANNOTATED_TYPE: return isDiamond(((JCAnnotatedType)tree).underlyingType);
   252             default: return false;
   253         }
   254     }
   256     public static boolean isEnumInit(JCTree tree) {
   257         switch (tree.getTag()) {
   258             case VARDEF:
   259                 return (((JCVariableDecl)tree).mods.flags & ENUM) != 0;
   260             default:
   261                 return false;
   262         }
   263     }
   265     /** set 'polyKind' on given tree */
   266     public static void setPolyKind(JCTree tree, PolyKind pkind) {
   267         switch (tree.getTag()) {
   268             case APPLY:
   269                 ((JCMethodInvocation)tree).polyKind = pkind;
   270                 break;
   271             case NEWCLASS:
   272                 ((JCNewClass)tree).polyKind = pkind;
   273                 break;
   274             case REFERENCE:
   275                 ((JCMemberReference)tree).refPolyKind = pkind;
   276                 break;
   277             default:
   278                 throw new AssertionError("Unexpected tree: " + tree);
   279         }
   280     }
   282     /** set 'varargsElement' on given tree */
   283     public static void setVarargsElement(JCTree tree, Type varargsElement) {
   284         switch (tree.getTag()) {
   285             case APPLY:
   286                 ((JCMethodInvocation)tree).varargsElement = varargsElement;
   287                 break;
   288             case NEWCLASS:
   289                 ((JCNewClass)tree).varargsElement = varargsElement;
   290                 break;
   291             case REFERENCE:
   292                 ((JCMemberReference)tree).varargsElement = varargsElement;
   293                 break;
   294             default:
   295                 throw new AssertionError("Unexpected tree: " + tree);
   296         }
   297     }
   299     /** Return true if the tree corresponds to an expression statement */
   300     public static boolean isExpressionStatement(JCExpression tree) {
   301         switch(tree.getTag()) {
   302             case PREINC: case PREDEC:
   303             case POSTINC: case POSTDEC:
   304             case ASSIGN:
   305             case BITOR_ASG: case BITXOR_ASG: case BITAND_ASG:
   306             case SL_ASG: case SR_ASG: case USR_ASG:
   307             case PLUS_ASG: case MINUS_ASG:
   308             case MUL_ASG: case DIV_ASG: case MOD_ASG:
   309             case APPLY: case NEWCLASS:
   310             case ERRONEOUS:
   311                 return true;
   312             default:
   313                 return false;
   314         }
   315     }
   317     /**
   318      * Return true if the AST corresponds to a static select of the kind A.B
   319      */
   320     public static boolean isStaticSelector(JCTree base, Names names) {
   321         if (base == null)
   322             return false;
   323         switch (base.getTag()) {
   324             case IDENT:
   325                 JCIdent id = (JCIdent)base;
   326                 return id.name != names._this &&
   327                         id.name != names._super &&
   328                         isStaticSym(base);
   329             case SELECT:
   330                 return isStaticSym(base) &&
   331                     isStaticSelector(((JCFieldAccess)base).selected, names);
   332             case TYPEAPPLY:
   333             case TYPEARRAY:
   334                 return true;
   335             case ANNOTATED_TYPE:
   336                 return isStaticSelector(((JCAnnotatedType)base).underlyingType, names);
   337             default:
   338                 return false;
   339         }
   340     }
   341     //where
   342         private static boolean isStaticSym(JCTree tree) {
   343             Symbol sym = symbol(tree);
   344             return (sym.kind == Kinds.TYP ||
   345                     sym.kind == Kinds.PCK);
   346         }
   348     /** Return true if a tree represents the null literal. */
   349     public static boolean isNull(JCTree tree) {
   350         if (!tree.hasTag(LITERAL))
   351             return false;
   352         JCLiteral lit = (JCLiteral) tree;
   353         return (lit.typetag == BOT);
   354     }
   356     /** Return true iff this tree is a child of some annotation. */
   357     public static boolean isInAnnotation(Env<?> env, JCTree tree) {
   358         TreePath tp = TreePath.getPath(env.toplevel, tree);
   359         if (tp != null) {
   360             for (Tree t : tp) {
   361                 if (t.getKind() == Tree.Kind.ANNOTATION)
   362                     return true;
   363             }
   364         }
   365         return false;
   366     }
   368     public static String getCommentText(Env<?> env, JCTree tree) {
   369         DocCommentTable docComments = (tree.hasTag(JCTree.Tag.TOPLEVEL))
   370                 ? ((JCCompilationUnit) tree).docComments
   371                 : env.toplevel.docComments;
   372         return (docComments == null) ? null : docComments.getCommentText(tree);
   373     }
   375     public static DCTree.DCDocComment getCommentTree(Env<?> env, JCTree tree) {
   376         DocCommentTable docComments = (tree.hasTag(JCTree.Tag.TOPLEVEL))
   377                 ? ((JCCompilationUnit) tree).docComments
   378                 : env.toplevel.docComments;
   379         return (docComments == null) ? null : docComments.getCommentTree(tree);
   380     }
   382     /** The position of the first statement in a block, or the position of
   383      *  the block itself if it is empty.
   384      */
   385     public static int firstStatPos(JCTree tree) {
   386         if (tree.hasTag(BLOCK) && ((JCBlock) tree).stats.nonEmpty())
   387             return ((JCBlock) tree).stats.head.pos;
   388         else
   389             return tree.pos;
   390     }
   392     /** The end position of given tree, if it is a block with
   393      *  defined endpos.
   394      */
   395     public static int endPos(JCTree tree) {
   396         if (tree.hasTag(BLOCK) && ((JCBlock) tree).endpos != Position.NOPOS)
   397             return ((JCBlock) tree).endpos;
   398         else if (tree.hasTag(SYNCHRONIZED))
   399             return endPos(((JCSynchronized) tree).body);
   400         else if (tree.hasTag(TRY)) {
   401             JCTry t = (JCTry) tree;
   402             return endPos((t.finalizer != null) ? t.finalizer
   403                           : (t.catchers.nonEmpty() ? t.catchers.last().body : t.body));
   404         } else
   405             return tree.pos;
   406     }
   409     /** Get the start position for a tree node.  The start position is
   410      * defined to be the position of the first character of the first
   411      * token of the node's source text.
   412      * @param tree  The tree node
   413      */
   414     public static int getStartPos(JCTree tree) {
   415         if (tree == null)
   416             return Position.NOPOS;
   418         switch(tree.getTag()) {
   419             case APPLY:
   420                 return getStartPos(((JCMethodInvocation) tree).meth);
   421             case ASSIGN:
   422                 return getStartPos(((JCAssign) tree).lhs);
   423             case BITOR_ASG: case BITXOR_ASG: case BITAND_ASG:
   424             case SL_ASG: case SR_ASG: case USR_ASG:
   425             case PLUS_ASG: case MINUS_ASG: case MUL_ASG:
   426             case DIV_ASG: case MOD_ASG:
   427                 return getStartPos(((JCAssignOp) tree).lhs);
   428             case OR: case AND: case BITOR:
   429             case BITXOR: case BITAND: case EQ:
   430             case NE: case LT: case GT:
   431             case LE: case GE: case SL:
   432             case SR: case USR: case PLUS:
   433             case MINUS: case MUL: case DIV:
   434             case MOD:
   435                 return getStartPos(((JCBinary) tree).lhs);
   436             case CLASSDEF: {
   437                 JCClassDecl node = (JCClassDecl)tree;
   438                 if (node.mods.pos != Position.NOPOS)
   439                     return node.mods.pos;
   440                 break;
   441             }
   442             case CONDEXPR:
   443                 return getStartPos(((JCConditional) tree).cond);
   444             case EXEC:
   445                 return getStartPos(((JCExpressionStatement) tree).expr);
   446             case INDEXED:
   447                 return getStartPos(((JCArrayAccess) tree).indexed);
   448             case METHODDEF: {
   449                 JCMethodDecl node = (JCMethodDecl)tree;
   450                 if (node.mods.pos != Position.NOPOS)
   451                     return node.mods.pos;
   452                 if (node.typarams.nonEmpty()) // List.nil() used for no typarams
   453                     return getStartPos(node.typarams.head);
   454                 return node.restype == null ? node.pos : getStartPos(node.restype);
   455             }
   456             case SELECT:
   457                 return getStartPos(((JCFieldAccess) tree).selected);
   458             case TYPEAPPLY:
   459                 return getStartPos(((JCTypeApply) tree).clazz);
   460             case TYPEARRAY:
   461                 return getStartPos(((JCArrayTypeTree) tree).elemtype);
   462             case TYPETEST:
   463                 return getStartPos(((JCInstanceOf) tree).expr);
   464             case POSTINC:
   465             case POSTDEC:
   466                 return getStartPos(((JCUnary) tree).arg);
   467             case ANNOTATED_TYPE: {
   468                 JCAnnotatedType node = (JCAnnotatedType) tree;
   469                 if (node.annotations.nonEmpty()) {
   470                     if (node.underlyingType.hasTag(TYPEARRAY) ||
   471                             node.underlyingType.hasTag(SELECT)) {
   472                         return getStartPos(node.underlyingType);
   473                     } else {
   474                         return getStartPos(node.annotations.head);
   475                     }
   476                 } else {
   477                     return getStartPos(node.underlyingType);
   478                 }
   479             }
   480             case NEWCLASS: {
   481                 JCNewClass node = (JCNewClass)tree;
   482                 if (node.encl != null)
   483                     return getStartPos(node.encl);
   484                 break;
   485             }
   486             case VARDEF: {
   487                 JCVariableDecl node = (JCVariableDecl)tree;
   488                 if (node.mods.pos != Position.NOPOS) {
   489                     return node.mods.pos;
   490                 } else if (node.vartype == null) {
   491                     //if there's no type (partially typed lambda parameter)
   492                     //simply return node position
   493                     return node.pos;
   494                 } else {
   495                     return getStartPos(node.vartype);
   496                 }
   497             }
   498             case ERRONEOUS: {
   499                 JCErroneous node = (JCErroneous)tree;
   500                 if (node.errs != null && node.errs.nonEmpty())
   501                     return getStartPos(node.errs.head);
   502             }
   503         }
   504         return tree.pos;
   505     }
   507     /** The end position of given tree, given  a table of end positions generated by the parser
   508      */
   509     public static int getEndPos(JCTree tree, EndPosTable endPosTable) {
   510         if (tree == null)
   511             return Position.NOPOS;
   513         if (endPosTable == null) {
   514             // fall back on limited info in the tree
   515             return endPos(tree);
   516         }
   518         int mapPos = endPosTable.getEndPos(tree);
   519         if (mapPos != Position.NOPOS)
   520             return mapPos;
   522         switch(tree.getTag()) {
   523             case BITOR_ASG: case BITXOR_ASG: case BITAND_ASG:
   524             case SL_ASG: case SR_ASG: case USR_ASG:
   525             case PLUS_ASG: case MINUS_ASG: case MUL_ASG:
   526             case DIV_ASG: case MOD_ASG:
   527                 return getEndPos(((JCAssignOp) tree).rhs, endPosTable);
   528             case OR: case AND: case BITOR:
   529             case BITXOR: case BITAND: case EQ:
   530             case NE: case LT: case GT:
   531             case LE: case GE: case SL:
   532             case SR: case USR: case PLUS:
   533             case MINUS: case MUL: case DIV:
   534             case MOD:
   535                 return getEndPos(((JCBinary) tree).rhs, endPosTable);
   536             case CASE:
   537                 return getEndPos(((JCCase) tree).stats.last(), endPosTable);
   538             case CATCH:
   539                 return getEndPos(((JCCatch) tree).body, endPosTable);
   540             case CONDEXPR:
   541                 return getEndPos(((JCConditional) tree).falsepart, endPosTable);
   542             case FORLOOP:
   543                 return getEndPos(((JCForLoop) tree).body, endPosTable);
   544             case FOREACHLOOP:
   545                 return getEndPos(((JCEnhancedForLoop) tree).body, endPosTable);
   546             case IF: {
   547                 JCIf node = (JCIf)tree;
   548                 if (node.elsepart == null) {
   549                     return getEndPos(node.thenpart, endPosTable);
   550                 } else {
   551                     return getEndPos(node.elsepart, endPosTable);
   552                 }
   553             }
   554             case LABELLED:
   555                 return getEndPos(((JCLabeledStatement) tree).body, endPosTable);
   556             case MODIFIERS:
   557                 return getEndPos(((JCModifiers) tree).annotations.last(), endPosTable);
   558             case SYNCHRONIZED:
   559                 return getEndPos(((JCSynchronized) tree).body, endPosTable);
   560             case TOPLEVEL:
   561                 return getEndPos(((JCCompilationUnit) tree).defs.last(), endPosTable);
   562             case TRY: {
   563                 JCTry node = (JCTry)tree;
   564                 if (node.finalizer != null) {
   565                     return getEndPos(node.finalizer, endPosTable);
   566                 } else if (!node.catchers.isEmpty()) {
   567                     return getEndPos(node.catchers.last(), endPosTable);
   568                 } else {
   569                     return getEndPos(node.body, endPosTable);
   570                 }
   571             }
   572             case WILDCARD:
   573                 return getEndPos(((JCWildcard) tree).inner, endPosTable);
   574             case TYPECAST:
   575                 return getEndPos(((JCTypeCast) tree).expr, endPosTable);
   576             case TYPETEST:
   577                 return getEndPos(((JCInstanceOf) tree).clazz, endPosTable);
   578             case POS:
   579             case NEG:
   580             case NOT:
   581             case COMPL:
   582             case PREINC:
   583             case PREDEC:
   584                 return getEndPos(((JCUnary) tree).arg, endPosTable);
   585             case WHILELOOP:
   586                 return getEndPos(((JCWhileLoop) tree).body, endPosTable);
   587             case ANNOTATED_TYPE:
   588                 return getEndPos(((JCAnnotatedType) tree).underlyingType, endPosTable);
   589             case ERRONEOUS: {
   590                 JCErroneous node = (JCErroneous)tree;
   591                 if (node.errs != null && node.errs.nonEmpty())
   592                     return getEndPos(node.errs.last(), endPosTable);
   593             }
   594         }
   595         return Position.NOPOS;
   596     }
   599     /** A DiagnosticPosition with the preferred position set to the
   600      *  end position of given tree, if it is a block with
   601      *  defined endpos.
   602      */
   603     public static DiagnosticPosition diagEndPos(final JCTree tree) {
   604         final int endPos = TreeInfo.endPos(tree);
   605         return new DiagnosticPosition() {
   606             public JCTree getTree() { return tree; }
   607             public int getStartPosition() { return TreeInfo.getStartPos(tree); }
   608             public int getPreferredPosition() { return endPos; }
   609             public int getEndPosition(EndPosTable endPosTable) {
   610                 return TreeInfo.getEndPos(tree, endPosTable);
   611             }
   612         };
   613     }
   615     public enum PosKind {
   616         START_POS() { int  toPos(JCTree tree) { return TreeInfo.getStartPos(tree); } },
   617         FIRST_STAT_POS() { int  toPos(JCTree tree) { return firstStatPos(tree); } },
   618         END_POS() { int  toPos(JCTree tree) { return endPos(tree); } };
   620         abstract int toPos(JCTree tree);
   621     }
   623     /** The position of the finalizer of given try/synchronized statement.
   624      */
   625     public static int finalizerPos(JCTree tree, PosKind posKind) {
   626         if (tree.hasTag(TRY)) {
   627             JCTry t = (JCTry) tree;
   628             Assert.checkNonNull(t.finalizer);
   629             return posKind.toPos(t.finalizer);
   630         } else if (tree.hasTag(SYNCHRONIZED)) {
   631             return endPos(((JCSynchronized) tree).body);
   632         } else {
   633             throw new AssertionError();
   634         }
   635     }
   637     /** Find the position for reporting an error about a symbol, where
   638      *  that symbol is defined somewhere in the given tree. */
   639     public static int positionFor(final Symbol sym, final JCTree tree) {
   640         JCTree decl = declarationFor(sym, tree);
   641         return ((decl != null) ? decl : tree).pos;
   642     }
   644     /** Find the position for reporting an error about a symbol, where
   645      *  that symbol is defined somewhere in the given tree. */
   646     public static DiagnosticPosition diagnosticPositionFor(final Symbol sym, final JCTree tree) {
   647         JCTree decl = declarationFor(sym, tree);
   648         return ((decl != null) ? decl : tree).pos();
   649     }
   651     /** Find the declaration for a symbol, where
   652      *  that symbol is defined somewhere in the given tree. */
   653     public static JCTree declarationFor(final Symbol sym, final JCTree tree) {
   654         class DeclScanner extends TreeScanner {
   655             JCTree result = null;
   656             public void scan(JCTree tree) {
   657                 if (tree!=null && result==null)
   658                     tree.accept(this);
   659             }
   660             public void visitTopLevel(JCCompilationUnit that) {
   661                 if (that.packge == sym) result = that;
   662                 else super.visitTopLevel(that);
   663             }
   664             public void visitClassDef(JCClassDecl that) {
   665                 if (that.sym == sym) result = that;
   666                 else super.visitClassDef(that);
   667             }
   668             public void visitMethodDef(JCMethodDecl that) {
   669                 if (that.sym == sym) result = that;
   670                 else super.visitMethodDef(that);
   671             }
   672             public void visitVarDef(JCVariableDecl that) {
   673                 if (that.sym == sym) result = that;
   674                 else super.visitVarDef(that);
   675             }
   676             public void visitTypeParameter(JCTypeParameter that) {
   677                 if (that.type != null && that.type.tsym == sym) result = that;
   678                 else super.visitTypeParameter(that);
   679             }
   680         }
   681         DeclScanner s = new DeclScanner();
   682         tree.accept(s);
   683         return s.result;
   684     }
   686     public static Env<AttrContext> scopeFor(JCTree node, JCCompilationUnit unit) {
   687         return scopeFor(pathFor(node, unit));
   688     }
   690     public static Env<AttrContext> scopeFor(List<JCTree> path) {
   691         // TODO: not implemented yet
   692         throw new UnsupportedOperationException("not implemented yet");
   693     }
   695     public static List<JCTree> pathFor(final JCTree node, final JCCompilationUnit unit) {
   696         class Result extends Error {
   697             static final long serialVersionUID = -5942088234594905625L;
   698             List<JCTree> path;
   699             Result(List<JCTree> path) {
   700                 this.path = path;
   701             }
   702         }
   703         class PathFinder extends TreeScanner {
   704             List<JCTree> path = List.nil();
   705             public void scan(JCTree tree) {
   706                 if (tree != null) {
   707                     path = path.prepend(tree);
   708                     if (tree == node)
   709                         throw new Result(path);
   710                     super.scan(tree);
   711                     path = path.tail;
   712                 }
   713             }
   714         }
   715         try {
   716             new PathFinder().scan(unit);
   717         } catch (Result result) {
   718             return result.path;
   719         }
   720         return List.nil();
   721     }
   723     /** Return the statement referenced by a label.
   724      *  If the label refers to a loop or switch, return that switch
   725      *  otherwise return the labelled statement itself
   726      */
   727     public static JCTree referencedStatement(JCLabeledStatement tree) {
   728         JCTree t = tree;
   729         do t = ((JCLabeledStatement) t).body;
   730         while (t.hasTag(LABELLED));
   731         switch (t.getTag()) {
   732         case DOLOOP: case WHILELOOP: case FORLOOP: case FOREACHLOOP: case SWITCH:
   733             return t;
   734         default:
   735             return tree;
   736         }
   737     }
   739     /** Skip parens and return the enclosed expression
   740      */
   741     public static JCExpression skipParens(JCExpression tree) {
   742         while (tree.hasTag(PARENS)) {
   743             tree = ((JCParens) tree).expr;
   744         }
   745         return tree;
   746     }
   748     /** Skip parens and return the enclosed expression
   749      */
   750     public static JCTree skipParens(JCTree tree) {
   751         if (tree.hasTag(PARENS))
   752             return skipParens((JCParens)tree);
   753         else
   754             return tree;
   755     }
   757     /** Return the types of a list of trees.
   758      */
   759     public static List<Type> types(List<? extends JCTree> trees) {
   760         ListBuffer<Type> ts = new ListBuffer<Type>();
   761         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   762             ts.append(l.head.type);
   763         return ts.toList();
   764     }
   766     /** If this tree is an identifier or a field or a parameterized type,
   767      *  return its name, otherwise return null.
   768      */
   769     public static Name name(JCTree tree) {
   770         switch (tree.getTag()) {
   771         case IDENT:
   772             return ((JCIdent) tree).name;
   773         case SELECT:
   774             return ((JCFieldAccess) tree).name;
   775         case TYPEAPPLY:
   776             return name(((JCTypeApply) tree).clazz);
   777         default:
   778             return null;
   779         }
   780     }
   782     /** If this tree is a qualified identifier, its return fully qualified name,
   783      *  otherwise return null.
   784      */
   785     public static Name fullName(JCTree tree) {
   786         tree = skipParens(tree);
   787         switch (tree.getTag()) {
   788         case IDENT:
   789             return ((JCIdent) tree).name;
   790         case SELECT:
   791             Name sname = fullName(((JCFieldAccess) tree).selected);
   792             return sname == null ? null : sname.append('.', name(tree));
   793         default:
   794             return null;
   795         }
   796     }
   798     public static Symbol symbolFor(JCTree node) {
   799         Symbol sym = symbolForImpl(node);
   801         return sym != null ? sym.baseSymbol() : null;
   802     }
   804     private static Symbol symbolForImpl(JCTree node) {
   805         node = skipParens(node);
   806         switch (node.getTag()) {
   807         case TOPLEVEL:
   808             return ((JCCompilationUnit) node).packge;
   809         case CLASSDEF:
   810             return ((JCClassDecl) node).sym;
   811         case METHODDEF:
   812             return ((JCMethodDecl) node).sym;
   813         case VARDEF:
   814             return ((JCVariableDecl) node).sym;
   815         case IDENT:
   816             return ((JCIdent) node).sym;
   817         case SELECT:
   818             return ((JCFieldAccess) node).sym;
   819         case REFERENCE:
   820             return ((JCMemberReference) node).sym;
   821         case NEWCLASS:
   822             return ((JCNewClass) node).constructor;
   823         case APPLY:
   824             return symbolFor(((JCMethodInvocation) node).meth);
   825         case TYPEAPPLY:
   826             return symbolFor(((JCTypeApply) node).clazz);
   827         case ANNOTATION:
   828         case TYPE_ANNOTATION:
   829         case TYPEPARAMETER:
   830             if (node.type != null)
   831                 return node.type.tsym;
   832             return null;
   833         default:
   834             return null;
   835         }
   836     }
   838     public static boolean isDeclaration(JCTree node) {
   839         node = skipParens(node);
   840         switch (node.getTag()) {
   841         case CLASSDEF:
   842         case METHODDEF:
   843         case VARDEF:
   844             return true;
   845         default:
   846             return false;
   847         }
   848     }
   850     /** If this tree is an identifier or a field, return its symbol,
   851      *  otherwise return null.
   852      */
   853     public static Symbol symbol(JCTree tree) {
   854         tree = skipParens(tree);
   855         switch (tree.getTag()) {
   856         case IDENT:
   857             return ((JCIdent) tree).sym;
   858         case SELECT:
   859             return ((JCFieldAccess) tree).sym;
   860         case TYPEAPPLY:
   861             return symbol(((JCTypeApply) tree).clazz);
   862         case ANNOTATED_TYPE:
   863             return symbol(((JCAnnotatedType) tree).underlyingType);
   864         case REFERENCE:
   865             return ((JCMemberReference) tree).sym;
   866         default:
   867             return null;
   868         }
   869     }
   871     /** Return true if this is a nonstatic selection. */
   872     public static boolean nonstaticSelect(JCTree tree) {
   873         tree = skipParens(tree);
   874         if (!tree.hasTag(SELECT)) return false;
   875         JCFieldAccess s = (JCFieldAccess) tree;
   876         Symbol e = symbol(s.selected);
   877         return e == null || (e.kind != Kinds.PCK && e.kind != Kinds.TYP);
   878     }
   880     /** If this tree is an identifier or a field, set its symbol, otherwise skip.
   881      */
   882     public static void setSymbol(JCTree tree, Symbol sym) {
   883         tree = skipParens(tree);
   884         switch (tree.getTag()) {
   885         case IDENT:
   886             ((JCIdent) tree).sym = sym; break;
   887         case SELECT:
   888             ((JCFieldAccess) tree).sym = sym; break;
   889         default:
   890         }
   891     }
   893     /** If this tree is a declaration or a block, return its flags field,
   894      *  otherwise return 0.
   895      */
   896     public static long flags(JCTree tree) {
   897         switch (tree.getTag()) {
   898         case VARDEF:
   899             return ((JCVariableDecl) tree).mods.flags;
   900         case METHODDEF:
   901             return ((JCMethodDecl) tree).mods.flags;
   902         case CLASSDEF:
   903             return ((JCClassDecl) tree).mods.flags;
   904         case BLOCK:
   905             return ((JCBlock) tree).flags;
   906         default:
   907             return 0;
   908         }
   909     }
   911     /** Return first (smallest) flag in `flags':
   912      *  pre: flags != 0
   913      */
   914     public static long firstFlag(long flags) {
   915         long flag = 1;
   916         while ((flag & flags & ExtendedStandardFlags) == 0)
   917             flag = flag << 1;
   918         return flag;
   919     }
   921     /** Return flags as a string, separated by " ".
   922      */
   923     public static String flagNames(long flags) {
   924         return Flags.toString(flags & ExtendedStandardFlags).trim();
   925     }
   927     /** Operator precedences values.
   928      */
   929     public static final int
   930         notExpression = -1,   // not an expression
   931         noPrec = 0,           // no enclosing expression
   932         assignPrec = 1,
   933         assignopPrec = 2,
   934         condPrec = 3,
   935         orPrec = 4,
   936         andPrec = 5,
   937         bitorPrec = 6,
   938         bitxorPrec = 7,
   939         bitandPrec = 8,
   940         eqPrec = 9,
   941         ordPrec = 10,
   942         shiftPrec = 11,
   943         addPrec = 12,
   944         mulPrec = 13,
   945         prefixPrec = 14,
   946         postfixPrec = 15,
   947         precCount = 16;
   950     /** Map operators to their precedence levels.
   951      */
   952     public static int opPrec(JCTree.Tag op) {
   953         switch(op) {
   954         case POS:
   955         case NEG:
   956         case NOT:
   957         case COMPL:
   958         case PREINC:
   959         case PREDEC: return prefixPrec;
   960         case POSTINC:
   961         case POSTDEC:
   962         case NULLCHK: return postfixPrec;
   963         case ASSIGN: return assignPrec;
   964         case BITOR_ASG:
   965         case BITXOR_ASG:
   966         case BITAND_ASG:
   967         case SL_ASG:
   968         case SR_ASG:
   969         case USR_ASG:
   970         case PLUS_ASG:
   971         case MINUS_ASG:
   972         case MUL_ASG:
   973         case DIV_ASG:
   974         case MOD_ASG: return assignopPrec;
   975         case OR: return orPrec;
   976         case AND: return andPrec;
   977         case EQ:
   978         case NE: return eqPrec;
   979         case LT:
   980         case GT:
   981         case LE:
   982         case GE: return ordPrec;
   983         case BITOR: return bitorPrec;
   984         case BITXOR: return bitxorPrec;
   985         case BITAND: return bitandPrec;
   986         case SL:
   987         case SR:
   988         case USR: return shiftPrec;
   989         case PLUS:
   990         case MINUS: return addPrec;
   991         case MUL:
   992         case DIV:
   993         case MOD: return mulPrec;
   994         case TYPETEST: return ordPrec;
   995         default: throw new AssertionError();
   996         }
   997     }
   999     static Tree.Kind tagToKind(JCTree.Tag tag) {
  1000         switch (tag) {
  1001         // Postfix expressions
  1002         case POSTINC:           // _ ++
  1003             return Tree.Kind.POSTFIX_INCREMENT;
  1004         case POSTDEC:           // _ --
  1005             return Tree.Kind.POSTFIX_DECREMENT;
  1007         // Unary operators
  1008         case PREINC:            // ++ _
  1009             return Tree.Kind.PREFIX_INCREMENT;
  1010         case PREDEC:            // -- _
  1011             return Tree.Kind.PREFIX_DECREMENT;
  1012         case POS:               // +
  1013             return Tree.Kind.UNARY_PLUS;
  1014         case NEG:               // -
  1015             return Tree.Kind.UNARY_MINUS;
  1016         case COMPL:             // ~
  1017             return Tree.Kind.BITWISE_COMPLEMENT;
  1018         case NOT:               // !
  1019             return Tree.Kind.LOGICAL_COMPLEMENT;
  1021         // Binary operators
  1023         // Multiplicative operators
  1024         case MUL:               // *
  1025             return Tree.Kind.MULTIPLY;
  1026         case DIV:               // /
  1027             return Tree.Kind.DIVIDE;
  1028         case MOD:               // %
  1029             return Tree.Kind.REMAINDER;
  1031         // Additive operators
  1032         case PLUS:              // +
  1033             return Tree.Kind.PLUS;
  1034         case MINUS:             // -
  1035             return Tree.Kind.MINUS;
  1037         // Shift operators
  1038         case SL:                // <<
  1039             return Tree.Kind.LEFT_SHIFT;
  1040         case SR:                // >>
  1041             return Tree.Kind.RIGHT_SHIFT;
  1042         case USR:               // >>>
  1043             return Tree.Kind.UNSIGNED_RIGHT_SHIFT;
  1045         // Relational operators
  1046         case LT:                // <
  1047             return Tree.Kind.LESS_THAN;
  1048         case GT:                // >
  1049             return Tree.Kind.GREATER_THAN;
  1050         case LE:                // <=
  1051             return Tree.Kind.LESS_THAN_EQUAL;
  1052         case GE:                // >=
  1053             return Tree.Kind.GREATER_THAN_EQUAL;
  1055         // Equality operators
  1056         case EQ:                // ==
  1057             return Tree.Kind.EQUAL_TO;
  1058         case NE:                // !=
  1059             return Tree.Kind.NOT_EQUAL_TO;
  1061         // Bitwise and logical operators
  1062         case BITAND:            // &
  1063             return Tree.Kind.AND;
  1064         case BITXOR:            // ^
  1065             return Tree.Kind.XOR;
  1066         case BITOR:             // |
  1067             return Tree.Kind.OR;
  1069         // Conditional operators
  1070         case AND:               // &&
  1071             return Tree.Kind.CONDITIONAL_AND;
  1072         case OR:                // ||
  1073             return Tree.Kind.CONDITIONAL_OR;
  1075         // Assignment operators
  1076         case MUL_ASG:           // *=
  1077             return Tree.Kind.MULTIPLY_ASSIGNMENT;
  1078         case DIV_ASG:           // /=
  1079             return Tree.Kind.DIVIDE_ASSIGNMENT;
  1080         case MOD_ASG:           // %=
  1081             return Tree.Kind.REMAINDER_ASSIGNMENT;
  1082         case PLUS_ASG:          // +=
  1083             return Tree.Kind.PLUS_ASSIGNMENT;
  1084         case MINUS_ASG:         // -=
  1085             return Tree.Kind.MINUS_ASSIGNMENT;
  1086         case SL_ASG:            // <<=
  1087             return Tree.Kind.LEFT_SHIFT_ASSIGNMENT;
  1088         case SR_ASG:            // >>=
  1089             return Tree.Kind.RIGHT_SHIFT_ASSIGNMENT;
  1090         case USR_ASG:           // >>>=
  1091             return Tree.Kind.UNSIGNED_RIGHT_SHIFT_ASSIGNMENT;
  1092         case BITAND_ASG:        // &=
  1093             return Tree.Kind.AND_ASSIGNMENT;
  1094         case BITXOR_ASG:        // ^=
  1095             return Tree.Kind.XOR_ASSIGNMENT;
  1096         case BITOR_ASG:         // |=
  1097             return Tree.Kind.OR_ASSIGNMENT;
  1099         // Null check (implementation detail), for example, __.getClass()
  1100         case NULLCHK:
  1101             return Tree.Kind.OTHER;
  1103         case ANNOTATION:
  1104             return Tree.Kind.ANNOTATION;
  1105         case TYPE_ANNOTATION:
  1106             return Tree.Kind.TYPE_ANNOTATION;
  1108         default:
  1109             return null;
  1113     /**
  1114      * Returns the underlying type of the tree if it is an annotated type,
  1115      * or the tree itself otherwise.
  1116      */
  1117     public static JCExpression typeIn(JCExpression tree) {
  1118         switch (tree.getTag()) {
  1119         case ANNOTATED_TYPE:
  1120             return ((JCAnnotatedType)tree).underlyingType;
  1121         case IDENT: /* simple names */
  1122         case TYPEIDENT: /* primitive name */
  1123         case SELECT: /* qualified name */
  1124         case TYPEARRAY: /* array types */
  1125         case WILDCARD: /* wild cards */
  1126         case TYPEPARAMETER: /* type parameters */
  1127         case TYPEAPPLY: /* parameterized types */
  1128         case ERRONEOUS: /* error tree TODO: needed for BadCast JSR308 test case. Better way? */
  1129             return tree;
  1130         default:
  1131             throw new AssertionError("Unexpected type tree: " + tree);
  1135     /* Return the inner-most type of a type tree.
  1136      * For an array that contains an annotated type, return that annotated type.
  1137      * TODO: currently only used by Pretty. Describe behavior better.
  1138      */
  1139     public static JCTree innermostType(JCTree type) {
  1140         JCTree lastAnnotatedType = null;
  1141         JCTree cur = type;
  1142         loop: while (true) {
  1143             switch (cur.getTag()) {
  1144             case TYPEARRAY:
  1145                 lastAnnotatedType = null;
  1146                 cur = ((JCArrayTypeTree)cur).elemtype;
  1147                 break;
  1148             case WILDCARD:
  1149                 lastAnnotatedType = null;
  1150                 cur = ((JCWildcard)cur).inner;
  1151                 break;
  1152             case ANNOTATED_TYPE:
  1153                 lastAnnotatedType = cur;
  1154                 cur = ((JCAnnotatedType)cur).underlyingType;
  1155                 break;
  1156             default:
  1157                 break loop;
  1160         if (lastAnnotatedType!=null) {
  1161             return lastAnnotatedType;
  1162         } else {
  1163             return cur;
  1167     private static class TypeAnnotationFinder extends TreeScanner {
  1168         public boolean foundTypeAnno = false;
  1170         @Override
  1171         public void scan(JCTree tree) {
  1172             if (foundTypeAnno || tree == null)
  1173                 return;
  1174             super.scan(tree);
  1177         public void visitAnnotation(JCAnnotation tree) {
  1178             foundTypeAnno = foundTypeAnno || tree.hasTag(TYPE_ANNOTATION);
  1182     public static boolean containsTypeAnnotation(JCTree e) {
  1183         TypeAnnotationFinder finder = new TypeAnnotationFinder();
  1184         finder.scan(e);
  1185         return finder.foundTypeAnno;

mercurial