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

Wed, 14 Nov 2012 17:23:10 -0800

author
jjg
date
Wed, 14 Nov 2012 17:23:10 -0800
changeset 1409
33abf479f202
parent 1374
c002fdee76fd
child 1433
4f9853659bf1
permissions
-rw-r--r--

7021614: extend com.sun.source API to support parsing javadoc comments
Reviewed-by: ksrini, strarup

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

mercurial