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

Fri, 30 Nov 2012 15:14:12 +0000

author
mcimadamore
date
Fri, 30 Nov 2012 15:14:12 +0000
changeset 1433
4f9853659bf1
parent 1374
c002fdee76fd
child 1455
75ab654b5cd5
permissions
-rw-r--r--

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

mercurial