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

Wed, 23 Jan 2013 13:27:24 -0800

author
jjg
date
Wed, 23 Jan 2013 13:27:24 -0800
changeset 1521
71f35e4b93a5
parent 1510
7873d37f5b37
child 1563
bc456436c613
permissions
-rw-r--r--

8006775: JSR 308: Compiler changes in JDK8
Reviewed-by: jjg
Contributed-by: mernst@cs.washington.edu, wmdietl@cs.washington.edu, mpapi@csail.mit.edu, mahmood@notnoop.com

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

mercurial