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

Mon, 17 Dec 2012 07:47:05 -0800

author
jjg
date
Mon, 17 Dec 2012 07:47:05 -0800
changeset 1455
75ab654b5cd5
parent 1433
4f9853659bf1
child 1510
7873d37f5b37
permissions
-rw-r--r--

8004832: Add new doclint package
Reviewed-by: mcimadamore

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

mercurial