private static int getPrecedence ( JCTree leaf , Context context ) { JCCompilationUnit comp = context . get ( JCCompilationUnit . class ) ; JCTree parent = TreeInfo . pathFor ( leaf , comp ) . get ( 1 ) ; // In general, this should match the logic in com.sun.tools.javac.tree.Pretty. // // TODO(mdempsky): There are probably cases where we could omit parentheses // by tweaking the returned precedence, but they need careful review. // For example, consider a template to replace "add(a, b)" with "a + b", // which applied to "x + add(y, z)" would result in "x + (y + z)". // In most cases, we'd likely prefer "x + y + z" instead, but those aren't // always equivalent: "0L + (Integer.MIN_VALUE + Integer.MIN_VALUE)" yields // a different value than "0L + Integer.MIN_VALUE + Integer.MIN_VALUE" due // to integer promotion rules. if ( parent instanceof JCConditional ) { // This intentionally differs from Pretty, because Pretty appears buggy: // http://mail.openjdk.java.net/pipermail/compiler-dev/2013-September/007303.html JCConditional conditional = ( JCConditional ) parent ; return TreeInfo . condPrec + ( ( conditional . cond == leaf ) ? 1 : 0 ) ; } else if ( parent instanceof JCAssign ) { JCAssign assign = ( JCAssign ) parent ; return TreeInfo . assignPrec + ( ( assign . lhs == leaf ) ? 1 : 0 ) ; } else if ( parent instanceof JCAssignOp ) { JCAssignOp assignOp = ( JCAssignOp ) parent ; return TreeInfo . assignopPrec + ( ( assignOp . lhs == leaf ) ? 1 : 0 ) ; } else if ( parent instanceof JCUnary ) { return TreeInfo . opPrec ( parent . getTag ( ) ) ; } else if ( parent instanceof JCBinary ) { JCBinary binary = ( JCBinary ) parent ; return TreeInfo . opPrec ( parent . getTag ( ) ) + ( ( binary . rhs == leaf ) ? 1 : 0 ) ; } else if ( parent instanceof JCTypeCast ) { JCTypeCast typeCast = ( JCTypeCast ) parent ; return ( typeCast . expr == leaf ) ? TreeInfo . prefixPrec : TreeInfo . noPrec ; } else if ( parent instanceof JCInstanceOf ) { JCInstanceOf instanceOf = ( JCInstanceOf ) parent ; return TreeInfo . ordPrec + ( ( instanceOf . clazz == leaf ) ? 1 : 0 ) ; } else if ( parent instanceof JCArrayAccess ) { JCArrayAccess arrayAccess = ( JCArrayAccess ) parent ; return ( arrayAccess . indexed == leaf ) ? TreeInfo . postfixPrec : TreeInfo . noPrec ; } else if ( parent instanceof JCFieldAccess ) { JCFieldAccess fieldAccess = ( JCFieldAccess ) parent ; return ( fieldAccess . selected == leaf ) ? TreeInfo . postfixPrec : TreeInfo . noPrec ; } else { return TreeInfo . noPrec ; } }
Returns the precedence level appropriate for unambiguously printing leaf as a subexpression of its parent .