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

Sat, 10 Aug 2013 16:29:26 +0100

author
vromero
date
Sat, 10 Aug 2013 16:29:26 +0100
changeset 1944
aa6c6f8b5622
parent 1845
be10ac0081b2
child 2390
b06c2db45ddb
permissions
-rw-r--r--

6983297: methods missing from NewArrayTree
Reviewed-by: jjg

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

mercurial