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

Mon, 21 Jan 2013 20:13:56 +0000

author
mcimadamore
date
Mon, 21 Jan 2013 20:13:56 +0000
changeset 1510
7873d37f5b37
parent 1455
75ab654b5cd5
child 1521
71f35e4b93a5
permissions
-rw-r--r--

8005244: Implement overload resolution as per latest spec EDR
Summary: Add support for stuck expressions and provisional applicability
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.tree;
    30 import com.sun.source.tree.Tree;
    31 import com.sun.tools.javac.code.*;
    32 import com.sun.tools.javac.comp.AttrContext;
    33 import com.sun.tools.javac.comp.Env;
    34 import com.sun.tools.javac.tree.JCTree.*;
    35 import com.sun.tools.javac.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 NEWCLASS: {
   457                 JCNewClass node = (JCNewClass)tree;
   458                 if (node.encl != null)
   459                     return getStartPos(node.encl);
   460                 break;
   461             }
   462             case VARDEF: {
   463                 JCVariableDecl node = (JCVariableDecl)tree;
   464                 if (node.mods.pos != Position.NOPOS) {
   465                     return node.mods.pos;
   466                 } else if (node.vartype == null) {
   467                     //if there's no type (partially typed lambda parameter)
   468                     //simply return node position
   469                     return node.pos;
   470                 } else {
   471                     return getStartPos(node.vartype);
   472                 }
   473             }
   474             case ERRONEOUS: {
   475                 JCErroneous node = (JCErroneous)tree;
   476                 if (node.errs != null && node.errs.nonEmpty())
   477                     return getStartPos(node.errs.head);
   478             }
   479         }
   480         return tree.pos;
   481     }
   483     /** The end position of given tree, given  a table of end positions generated by the parser
   484      */
   485     public static int getEndPos(JCTree tree, EndPosTable endPosTable) {
   486         if (tree == null)
   487             return Position.NOPOS;
   489         if (endPosTable == null) {
   490             // fall back on limited info in the tree
   491             return endPos(tree);
   492         }
   494         int mapPos = endPosTable.getEndPos(tree);
   495         if (mapPos != Position.NOPOS)
   496             return mapPos;
   498         switch(tree.getTag()) {
   499             case BITOR_ASG: case BITXOR_ASG: case BITAND_ASG:
   500             case SL_ASG: case SR_ASG: case USR_ASG:
   501             case PLUS_ASG: case MINUS_ASG: case MUL_ASG:
   502             case DIV_ASG: case MOD_ASG:
   503                 return getEndPos(((JCAssignOp) tree).rhs, endPosTable);
   504             case OR: case AND: case BITOR:
   505             case BITXOR: case BITAND: case EQ:
   506             case NE: case LT: case GT:
   507             case LE: case GE: case SL:
   508             case SR: case USR: case PLUS:
   509             case MINUS: case MUL: case DIV:
   510             case MOD:
   511                 return getEndPos(((JCBinary) tree).rhs, endPosTable);
   512             case CASE:
   513                 return getEndPos(((JCCase) tree).stats.last(), endPosTable);
   514             case CATCH:
   515                 return getEndPos(((JCCatch) tree).body, endPosTable);
   516             case CONDEXPR:
   517                 return getEndPos(((JCConditional) tree).falsepart, endPosTable);
   518             case FORLOOP:
   519                 return getEndPos(((JCForLoop) tree).body, endPosTable);
   520             case FOREACHLOOP:
   521                 return getEndPos(((JCEnhancedForLoop) tree).body, endPosTable);
   522             case IF: {
   523                 JCIf node = (JCIf)tree;
   524                 if (node.elsepart == null) {
   525                     return getEndPos(node.thenpart, endPosTable);
   526                 } else {
   527                     return getEndPos(node.elsepart, endPosTable);
   528                 }
   529             }
   530             case LABELLED:
   531                 return getEndPos(((JCLabeledStatement) tree).body, endPosTable);
   532             case MODIFIERS:
   533                 return getEndPos(((JCModifiers) tree).annotations.last(), endPosTable);
   534             case SYNCHRONIZED:
   535                 return getEndPos(((JCSynchronized) tree).body, endPosTable);
   536             case TOPLEVEL:
   537                 return getEndPos(((JCCompilationUnit) tree).defs.last(), endPosTable);
   538             case TRY: {
   539                 JCTry node = (JCTry)tree;
   540                 if (node.finalizer != null) {
   541                     return getEndPos(node.finalizer, endPosTable);
   542                 } else if (!node.catchers.isEmpty()) {
   543                     return getEndPos(node.catchers.last(), endPosTable);
   544                 } else {
   545                     return getEndPos(node.body, endPosTable);
   546                 }
   547             }
   548             case WILDCARD:
   549                 return getEndPos(((JCWildcard) tree).inner, endPosTable);
   550             case TYPECAST:
   551                 return getEndPos(((JCTypeCast) tree).expr, endPosTable);
   552             case TYPETEST:
   553                 return getEndPos(((JCInstanceOf) tree).clazz, endPosTable);
   554             case POS:
   555             case NEG:
   556             case NOT:
   557             case COMPL:
   558             case PREINC:
   559             case PREDEC:
   560                 return getEndPos(((JCUnary) tree).arg, endPosTable);
   561             case WHILELOOP:
   562                 return getEndPos(((JCWhileLoop) tree).body, endPosTable);
   563             case ERRONEOUS: {
   564                 JCErroneous node = (JCErroneous)tree;
   565                 if (node.errs != null && node.errs.nonEmpty())
   566                     return getEndPos(node.errs.last(), endPosTable);
   567             }
   568         }
   569         return Position.NOPOS;
   570     }
   573     /** A DiagnosticPosition with the preferred position set to the
   574      *  end position of given tree, if it is a block with
   575      *  defined endpos.
   576      */
   577     public static DiagnosticPosition diagEndPos(final JCTree tree) {
   578         final int endPos = TreeInfo.endPos(tree);
   579         return new DiagnosticPosition() {
   580             public JCTree getTree() { return tree; }
   581             public int getStartPosition() { return TreeInfo.getStartPos(tree); }
   582             public int getPreferredPosition() { return endPos; }
   583             public int getEndPosition(EndPosTable endPosTable) {
   584                 return TreeInfo.getEndPos(tree, endPosTable);
   585             }
   586         };
   587     }
   589     /** The position of the finalizer of given try/synchronized statement.
   590      */
   591     public static int finalizerPos(JCTree tree) {
   592         if (tree.hasTag(TRY)) {
   593             JCTry t = (JCTry) tree;
   594             Assert.checkNonNull(t.finalizer);
   595             return firstStatPos(t.finalizer);
   596         } else if (tree.hasTag(SYNCHRONIZED)) {
   597             return endPos(((JCSynchronized) tree).body);
   598         } else {
   599             throw new AssertionError();
   600         }
   601     }
   603     /** Find the position for reporting an error about a symbol, where
   604      *  that symbol is defined somewhere in the given tree. */
   605     public static int positionFor(final Symbol sym, final JCTree tree) {
   606         JCTree decl = declarationFor(sym, tree);
   607         return ((decl != null) ? decl : tree).pos;
   608     }
   610     /** Find the position for reporting an error about a symbol, where
   611      *  that symbol is defined somewhere in the given tree. */
   612     public static DiagnosticPosition diagnosticPositionFor(final Symbol sym, final JCTree tree) {
   613         JCTree decl = declarationFor(sym, tree);
   614         return ((decl != null) ? decl : tree).pos();
   615     }
   617     /** Find the declaration for a symbol, where
   618      *  that symbol is defined somewhere in the given tree. */
   619     public static JCTree declarationFor(final Symbol sym, final JCTree tree) {
   620         class DeclScanner extends TreeScanner {
   621             JCTree result = null;
   622             public void scan(JCTree tree) {
   623                 if (tree!=null && result==null)
   624                     tree.accept(this);
   625             }
   626             public void visitTopLevel(JCCompilationUnit that) {
   627                 if (that.packge == sym) result = that;
   628                 else super.visitTopLevel(that);
   629             }
   630             public void visitClassDef(JCClassDecl that) {
   631                 if (that.sym == sym) result = that;
   632                 else super.visitClassDef(that);
   633             }
   634             public void visitMethodDef(JCMethodDecl that) {
   635                 if (that.sym == sym) result = that;
   636                 else super.visitMethodDef(that);
   637             }
   638             public void visitVarDef(JCVariableDecl that) {
   639                 if (that.sym == sym) result = that;
   640                 else super.visitVarDef(that);
   641             }
   642             public void visitTypeParameter(JCTypeParameter that) {
   643                 if (that.type != null && that.type.tsym == sym) result = that;
   644                 else super.visitTypeParameter(that);
   645             }
   646         }
   647         DeclScanner s = new DeclScanner();
   648         tree.accept(s);
   649         return s.result;
   650     }
   652     public static Env<AttrContext> scopeFor(JCTree node, JCCompilationUnit unit) {
   653         return scopeFor(pathFor(node, unit));
   654     }
   656     public static Env<AttrContext> scopeFor(List<JCTree> path) {
   657         // TODO: not implemented yet
   658         throw new UnsupportedOperationException("not implemented yet");
   659     }
   661     public static List<JCTree> pathFor(final JCTree node, final JCCompilationUnit unit) {
   662         class Result extends Error {
   663             static final long serialVersionUID = -5942088234594905625L;
   664             List<JCTree> path;
   665             Result(List<JCTree> path) {
   666                 this.path = path;
   667             }
   668         }
   669         class PathFinder extends TreeScanner {
   670             List<JCTree> path = List.nil();
   671             public void scan(JCTree tree) {
   672                 if (tree != null) {
   673                     path = path.prepend(tree);
   674                     if (tree == node)
   675                         throw new Result(path);
   676                     super.scan(tree);
   677                     path = path.tail;
   678                 }
   679             }
   680         }
   681         try {
   682             new PathFinder().scan(unit);
   683         } catch (Result result) {
   684             return result.path;
   685         }
   686         return List.nil();
   687     }
   689     /** Return the statement referenced by a label.
   690      *  If the label refers to a loop or switch, return that switch
   691      *  otherwise return the labelled statement itself
   692      */
   693     public static JCTree referencedStatement(JCLabeledStatement tree) {
   694         JCTree t = tree;
   695         do t = ((JCLabeledStatement) t).body;
   696         while (t.hasTag(LABELLED));
   697         switch (t.getTag()) {
   698         case DOLOOP: case WHILELOOP: case FORLOOP: case FOREACHLOOP: case SWITCH:
   699             return t;
   700         default:
   701             return tree;
   702         }
   703     }
   705     /** Skip parens and return the enclosed expression
   706      */
   707     public static JCExpression skipParens(JCExpression tree) {
   708         while (tree.hasTag(PARENS)) {
   709             tree = ((JCParens) tree).expr;
   710         }
   711         return tree;
   712     }
   714     /** Skip parens and return the enclosed expression
   715      */
   716     public static JCTree skipParens(JCTree tree) {
   717         if (tree.hasTag(PARENS))
   718             return skipParens((JCParens)tree);
   719         else
   720             return tree;
   721     }
   723     /** Return the types of a list of trees.
   724      */
   725     public static List<Type> types(List<? extends JCTree> trees) {
   726         ListBuffer<Type> ts = new ListBuffer<Type>();
   727         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   728             ts.append(l.head.type);
   729         return ts.toList();
   730     }
   732     /** If this tree is an identifier or a field or a parameterized type,
   733      *  return its name, otherwise return null.
   734      */
   735     public static Name name(JCTree tree) {
   736         switch (tree.getTag()) {
   737         case IDENT:
   738             return ((JCIdent) tree).name;
   739         case SELECT:
   740             return ((JCFieldAccess) tree).name;
   741         case TYPEAPPLY:
   742             return name(((JCTypeApply) tree).clazz);
   743         default:
   744             return null;
   745         }
   746     }
   748     /** If this tree is a qualified identifier, its return fully qualified name,
   749      *  otherwise return null.
   750      */
   751     public static Name fullName(JCTree tree) {
   752         tree = skipParens(tree);
   753         switch (tree.getTag()) {
   754         case IDENT:
   755             return ((JCIdent) tree).name;
   756         case SELECT:
   757             Name sname = fullName(((JCFieldAccess) tree).selected);
   758             return sname == null ? null : sname.append('.', name(tree));
   759         default:
   760             return null;
   761         }
   762     }
   764     public static Symbol symbolFor(JCTree node) {
   765         node = skipParens(node);
   766         switch (node.getTag()) {
   767         case CLASSDEF:
   768             return ((JCClassDecl) node).sym;
   769         case METHODDEF:
   770             return ((JCMethodDecl) node).sym;
   771         case VARDEF:
   772             return ((JCVariableDecl) node).sym;
   773         default:
   774             return null;
   775         }
   776     }
   778     public static boolean isDeclaration(JCTree node) {
   779         node = skipParens(node);
   780         switch (node.getTag()) {
   781         case CLASSDEF:
   782         case METHODDEF:
   783         case VARDEF:
   784             return true;
   785         default:
   786             return false;
   787         }
   788     }
   790     /** If this tree is an identifier or a field, return its symbol,
   791      *  otherwise return null.
   792      */
   793     public static Symbol symbol(JCTree tree) {
   794         tree = skipParens(tree);
   795         switch (tree.getTag()) {
   796         case IDENT:
   797             return ((JCIdent) tree).sym;
   798         case SELECT:
   799             return ((JCFieldAccess) tree).sym;
   800         case TYPEAPPLY:
   801             return symbol(((JCTypeApply) tree).clazz);
   802         default:
   803             return null;
   804         }
   805     }
   807     /** Return true if this is a nonstatic selection. */
   808     public static boolean nonstaticSelect(JCTree tree) {
   809         tree = skipParens(tree);
   810         if (!tree.hasTag(SELECT)) return false;
   811         JCFieldAccess s = (JCFieldAccess) tree;
   812         Symbol e = symbol(s.selected);
   813         return e == null || (e.kind != Kinds.PCK && e.kind != Kinds.TYP);
   814     }
   816     /** If this tree is an identifier or a field, set its symbol, otherwise skip.
   817      */
   818     public static void setSymbol(JCTree tree, Symbol sym) {
   819         tree = skipParens(tree);
   820         switch (tree.getTag()) {
   821         case IDENT:
   822             ((JCIdent) tree).sym = sym; break;
   823         case SELECT:
   824             ((JCFieldAccess) tree).sym = sym; break;
   825         default:
   826         }
   827     }
   829     /** If this tree is a declaration or a block, return its flags field,
   830      *  otherwise return 0.
   831      */
   832     public static long flags(JCTree tree) {
   833         switch (tree.getTag()) {
   834         case VARDEF:
   835             return ((JCVariableDecl) tree).mods.flags;
   836         case METHODDEF:
   837             return ((JCMethodDecl) tree).mods.flags;
   838         case CLASSDEF:
   839             return ((JCClassDecl) tree).mods.flags;
   840         case BLOCK:
   841             return ((JCBlock) tree).flags;
   842         default:
   843             return 0;
   844         }
   845     }
   847     /** Return first (smallest) flag in `flags':
   848      *  pre: flags != 0
   849      */
   850     public static long firstFlag(long flags) {
   851         long flag = 1;
   852         while ((flag & flags & ExtendedStandardFlags) == 0)
   853             flag = flag << 1;
   854         return flag;
   855     }
   857     /** Return flags as a string, separated by " ".
   858      */
   859     public static String flagNames(long flags) {
   860         return Flags.toString(flags & ExtendedStandardFlags).trim();
   861     }
   863     /** Operator precedences values.
   864      */
   865     public static final int
   866         notExpression = -1,   // not an expression
   867         noPrec = 0,           // no enclosing expression
   868         assignPrec = 1,
   869         assignopPrec = 2,
   870         condPrec = 3,
   871         orPrec = 4,
   872         andPrec = 5,
   873         bitorPrec = 6,
   874         bitxorPrec = 7,
   875         bitandPrec = 8,
   876         eqPrec = 9,
   877         ordPrec = 10,
   878         shiftPrec = 11,
   879         addPrec = 12,
   880         mulPrec = 13,
   881         prefixPrec = 14,
   882         postfixPrec = 15,
   883         precCount = 16;
   886     /** Map operators to their precedence levels.
   887      */
   888     public static int opPrec(JCTree.Tag op) {
   889         switch(op) {
   890         case POS:
   891         case NEG:
   892         case NOT:
   893         case COMPL:
   894         case PREINC:
   895         case PREDEC: return prefixPrec;
   896         case POSTINC:
   897         case POSTDEC:
   898         case NULLCHK: return postfixPrec;
   899         case ASSIGN: return assignPrec;
   900         case BITOR_ASG:
   901         case BITXOR_ASG:
   902         case BITAND_ASG:
   903         case SL_ASG:
   904         case SR_ASG:
   905         case USR_ASG:
   906         case PLUS_ASG:
   907         case MINUS_ASG:
   908         case MUL_ASG:
   909         case DIV_ASG:
   910         case MOD_ASG: return assignopPrec;
   911         case OR: return orPrec;
   912         case AND: return andPrec;
   913         case EQ:
   914         case NE: return eqPrec;
   915         case LT:
   916         case GT:
   917         case LE:
   918         case GE: return ordPrec;
   919         case BITOR: return bitorPrec;
   920         case BITXOR: return bitxorPrec;
   921         case BITAND: return bitandPrec;
   922         case SL:
   923         case SR:
   924         case USR: return shiftPrec;
   925         case PLUS:
   926         case MINUS: return addPrec;
   927         case MUL:
   928         case DIV:
   929         case MOD: return mulPrec;
   930         case TYPETEST: return ordPrec;
   931         default: throw new AssertionError();
   932         }
   933     }
   935     static Tree.Kind tagToKind(JCTree.Tag tag) {
   936         switch (tag) {
   937         // Postfix expressions
   938         case POSTINC:           // _ ++
   939             return Tree.Kind.POSTFIX_INCREMENT;
   940         case POSTDEC:           // _ --
   941             return Tree.Kind.POSTFIX_DECREMENT;
   943         // Unary operators
   944         case PREINC:            // ++ _
   945             return Tree.Kind.PREFIX_INCREMENT;
   946         case PREDEC:            // -- _
   947             return Tree.Kind.PREFIX_DECREMENT;
   948         case POS:               // +
   949             return Tree.Kind.UNARY_PLUS;
   950         case NEG:               // -
   951             return Tree.Kind.UNARY_MINUS;
   952         case COMPL:             // ~
   953             return Tree.Kind.BITWISE_COMPLEMENT;
   954         case NOT:               // !
   955             return Tree.Kind.LOGICAL_COMPLEMENT;
   957         // Binary operators
   959         // Multiplicative operators
   960         case MUL:               // *
   961             return Tree.Kind.MULTIPLY;
   962         case DIV:               // /
   963             return Tree.Kind.DIVIDE;
   964         case MOD:               // %
   965             return Tree.Kind.REMAINDER;
   967         // Additive operators
   968         case PLUS:              // +
   969             return Tree.Kind.PLUS;
   970         case MINUS:             // -
   971             return Tree.Kind.MINUS;
   973         // Shift operators
   974         case SL:                // <<
   975             return Tree.Kind.LEFT_SHIFT;
   976         case SR:                // >>
   977             return Tree.Kind.RIGHT_SHIFT;
   978         case USR:               // >>>
   979             return Tree.Kind.UNSIGNED_RIGHT_SHIFT;
   981         // Relational operators
   982         case LT:                // <
   983             return Tree.Kind.LESS_THAN;
   984         case GT:                // >
   985             return Tree.Kind.GREATER_THAN;
   986         case LE:                // <=
   987             return Tree.Kind.LESS_THAN_EQUAL;
   988         case GE:                // >=
   989             return Tree.Kind.GREATER_THAN_EQUAL;
   991         // Equality operators
   992         case EQ:                // ==
   993             return Tree.Kind.EQUAL_TO;
   994         case NE:                // !=
   995             return Tree.Kind.NOT_EQUAL_TO;
   997         // Bitwise and logical operators
   998         case BITAND:            // &
   999             return Tree.Kind.AND;
  1000         case BITXOR:            // ^
  1001             return Tree.Kind.XOR;
  1002         case BITOR:             // |
  1003             return Tree.Kind.OR;
  1005         // Conditional operators
  1006         case AND:               // &&
  1007             return Tree.Kind.CONDITIONAL_AND;
  1008         case OR:                // ||
  1009             return Tree.Kind.CONDITIONAL_OR;
  1011         // Assignment operators
  1012         case MUL_ASG:           // *=
  1013             return Tree.Kind.MULTIPLY_ASSIGNMENT;
  1014         case DIV_ASG:           // /=
  1015             return Tree.Kind.DIVIDE_ASSIGNMENT;
  1016         case MOD_ASG:           // %=
  1017             return Tree.Kind.REMAINDER_ASSIGNMENT;
  1018         case PLUS_ASG:          // +=
  1019             return Tree.Kind.PLUS_ASSIGNMENT;
  1020         case MINUS_ASG:         // -=
  1021             return Tree.Kind.MINUS_ASSIGNMENT;
  1022         case SL_ASG:            // <<=
  1023             return Tree.Kind.LEFT_SHIFT_ASSIGNMENT;
  1024         case SR_ASG:            // >>=
  1025             return Tree.Kind.RIGHT_SHIFT_ASSIGNMENT;
  1026         case USR_ASG:           // >>>=
  1027             return Tree.Kind.UNSIGNED_RIGHT_SHIFT_ASSIGNMENT;
  1028         case BITAND_ASG:        // &=
  1029             return Tree.Kind.AND_ASSIGNMENT;
  1030         case BITXOR_ASG:        // ^=
  1031             return Tree.Kind.XOR_ASSIGNMENT;
  1032         case BITOR_ASG:         // |=
  1033             return Tree.Kind.OR_ASSIGNMENT;
  1035         // Null check (implementation detail), for example, __.getClass()
  1036         case NULLCHK:
  1037             return Tree.Kind.OTHER;
  1039         default:
  1040             return null;
  1044     /**
  1045      * Returns the underlying type of the tree if it is annotated type,
  1046      * or the tree itself otherwise
  1047      */
  1048     public static JCExpression typeIn(JCExpression tree) {
  1049         switch (tree.getTag()) {
  1050         case IDENT: /* simple names */
  1051         case TYPEIDENT: /* primitive name */
  1052         case SELECT: /* qualified name */
  1053         case TYPEARRAY: /* array types */
  1054         case WILDCARD: /* wild cards */
  1055         case TYPEPARAMETER: /* type parameters */
  1056         case TYPEAPPLY: /* parameterized types */
  1057             return tree;
  1058         default:
  1059             throw new AssertionError("Unexpected type tree: " + tree);
  1063     public static JCTree innermostType(JCTree type) {
  1064         switch (type.getTag()) {
  1065         case TYPEARRAY:
  1066             return innermostType(((JCArrayTypeTree)type).elemtype);
  1067         case WILDCARD:
  1068             return innermostType(((JCWildcard)type).inner);
  1069         default:
  1070             return type;

mercurial