Example usage for org.eclipse.jdt.core.dom Expression getNodeType

List of usage examples for org.eclipse.jdt.core.dom Expression getNodeType

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom Expression getNodeType.

Prototype

public final int getNodeType() 

Source Link

Document

Returns an integer value identifying the type of this concrete AST node.

Usage

From source file:ch.acanda.eclipse.pmd.java.resolution.optimization.AddEmptyStringQuickFix.java

License:Open Source License

private boolean isStringLiteral(final Expression expression) {
    return expression.getNodeType() == ASTNode.STRING_LITERAL;
}

From source file:ch.acanda.eclipse.pmd.java.resolution.optimization.AddEmptyStringQuickFix.java

License:Open Source License

private boolean isCharacterLiteral(final Expression expression) {
    return expression.getNodeType() == ASTNode.CHARACTER_LITERAL;
}

From source file:com.google.devtools.j2cpp.gen.CppStatementGenerator.java

License:Open Source License

@Override
public boolean visit(Assignment node) {
    Operator op = node.getOperator();/*from   www .j av a  2 s  .  co m*/
    Expression lhs = node.getLeftHandSide();
    Expression rhs = node.getRightHandSide();
    if (op == Operator.PLUS_ASSIGN && Types.isJavaStringType(lhs.resolveTypeBinding())) {
        boolean needClosingParen = printAssignmentLhs(lhs);
        // Change "str1 += str2" to "str1 = str1 + str2".
        buffer.append(" = ");
        printStringConcatenation(lhs, rhs, Collections.<Expression>emptyList(), needClosingParen);
        if (needClosingParen) {
            buffer.append(")");
        }
    } else if (op == Operator.REMAINDER_ASSIGN && (isFloatingPoint(lhs) || isFloatingPoint(rhs))) {
        lhs.accept(this);
        buffer.append(" = fmod(");
        lhs.accept(this);
        buffer.append(", ");
        rhs.accept(this);
        buffer.append(")");
    } else if (lhs instanceof ArrayAccess) {
        printArrayElementAssignment(lhs, rhs, op);
    } else if (op == Operator.RIGHT_SHIFT_UNSIGNED_ASSIGN) {
        lhs.accept(this);
        buffer.append(" = ");
        printUnsignedRightShift(lhs, rhs);
    } else {
        IVariableBinding var = Types.getVariableBinding(lhs);
        boolean useWriter = false;
        if (var != null && var.getDeclaringClass() != null) {
            // Test with toString, as var may have been have a renamed type.
            String declaringClassName = var.getDeclaringClass().toString();
            String methodsClassName = Types.getTypeBinding(getOwningType(node)).toString();
            useWriter = Types.isStaticVariable(var) && !declaringClassName.equals(methodsClassName);
        }
        if (useWriter) {
            // convert static var assignment to its writer message
            buffer.append('[');
            if (lhs instanceof QualifiedName) {
                QualifiedName qn = (QualifiedName) lhs;
                qn.getQualifier().accept(this);
            } else {
                buffer.append(NameTable.getFullName(var.getDeclaringClass()));
            }
            buffer.append(" set");
            buffer.append(NameTable.capitalize(var.getName()));
            String typeName = NameTable.javaTypeToCpp(var.getType(), false);
            String param = CppSourceFileGenerator.parameterKeyword(typeName, var.getType());
            buffer.append(NameTable.capitalize(param));
            buffer.append(':');
            rhs.accept(this);
            buffer.append(']');
            return false;
        } else {
            boolean needClosingParen = printAssignmentLhs(lhs);
            buffer.append(' ');
            buffer.append(op.toString());
            buffer.append(' ');
            if (Types.isJavaObjectType(Types.getTypeBinding(lhs)) && Types.getTypeBinding(rhs).isInterface()) {
                // The compiler doesn't know that NSObject is the root of all
                // objects used by transpiled code, so add a cast.
                buffer.append("(NSObject *) ");
            }
            if (useReferenceCounting && !isNewAssignment(node) && var != null && Types.isStaticVariable(var)
                    && !var.getType().isPrimitive() && !Types.isWeakReference(var)
                    && rhs.getNodeType() != ASTNode.NULL_LITERAL) {
                buffer.append('[');
                rhs.accept(this);
                buffer.append(" retain]");
            } else {
                boolean needRetainRhs = needClosingParen && !isNewAssignment(node)
                        && !Types.isWeakReference(var);
                if (rhs instanceof NullLiteral) {
                    needRetainRhs = false;
                }
                if (needRetainRhs) {
                    buffer.append("[");
                }
                rhs.accept(this);
                if (needRetainRhs) {
                    buffer.append(" retain]");
                }
                if (needClosingParen) {
                    buffer.append(")");
                }
            }
            return false;
        }
    }
    return false;
}

From source file:com.google.gdt.eclipse.core.JavaASTUtils.java

License:Open Source License

@SuppressWarnings("unchecked")
private static boolean containsAnnotationValue(Expression annotationValue, String value) {
    if (annotationValue.getNodeType() == ASTNode.STRING_LITERAL) {
        String valueString = ((StringLiteral) annotationValue).getLiteralValue();
        return value.equals(valueString);
    } else if (annotationValue.getNodeType() == ASTNode.ARRAY_INITIALIZER) {
        // If the annotation value is actually an array, check each element
        List<Expression> warningTypes = ((ArrayInitializer) annotationValue).expressions();
        for (Expression warningType : warningTypes) {
            if (containsAnnotationValue(warningType, value)) {
                return true;
            }//from  w  ww . j a va 2 s  .c o m
        }
    }

    return false;
}

From source file:com.google.googlejavaformat.java.JavaInputAstVisitor.java

License:Apache License

/** Visitor method for {@link PrefixExpression}s. */
@Override// w  w w .j  a v  a 2  s. c  om
public boolean visit(PrefixExpression node) {
    sync(node);
    String op = node.getOperator().toString();
    builder.op(op);
    // Keep prefixes unambiguous.
    Expression operand = node.getOperand();
    if ((op.equals("+") || op.equals("-")) && operand.getNodeType() == ASTNode.PREFIX_EXPRESSION
            && ((PrefixExpression) operand).getOperator().toString().startsWith(op)) {
        builder.space();
    }
    operand.accept(this);
    return false;
}

From source file:com.google.googlejavaformat.java.JavaInputAstVisitor.java

License:Apache License

/** Visitor method for {@link SingleMemberAnnotation}s. */
@Override//w w  w. j  a  va 2  s .  co m
public boolean visit(SingleMemberAnnotation node) {
    sync(node);
    Expression value = node.getValue();
    boolean isArrayInitializer = value.getNodeType() == ASTNode.ARRAY_INITIALIZER;
    builder.open(isArrayInitializer ? ZERO : plusFour);
    token("@");
    node.getTypeName().accept(this);
    token("(");
    if (!isArrayInitializer) {
        builder.breakOp();
    }
    value.accept(this);
    builder.close();
    token(")");
    return false;
}

From source file:com.google.googlejavaformat.java.JavaInputAstVisitor.java

License:Apache License

/**
 * Helper method for {@link InfixExpression}s. Visit this {@link Expression} node, and its
 * children, as long as they are {@link InfixExpression} nodes of the same precedence. Accumulate
 * the operands and operators.//from w  ww  .  j  a v a 2 s.  c  o  m
 * @param precedence the precedence of the operators to collect
 * @param operands the output list of {@code n + 1} operands
 * @param operators the output list of {@code n} operators
 */
private static void walkInfix(int precedence, Expression expression, List<Expression> operands,
        List<String> operators) {
    if (expression.getNodeType() == ASTNode.INFIX_EXPRESSION) {
        InfixExpression infixExpression = (InfixExpression) expression;
        String myOperator = infixExpression.getOperator().toString();
        if (PRECEDENCE.get(myOperator) == precedence) {
            walkInfix(precedence, infixExpression.getLeftOperand(), operands, operators);
            operators.add(myOperator);
            walkInfix(precedence, infixExpression.getRightOperand(), operands, operators);
            if (infixExpression.hasExtendedOperands()) {
                for (Expression extendedOperand : (List<Expression>) infixExpression.extendedOperands()) {
                    operators.add(myOperator);
                    walkInfix(precedence, extendedOperand, operands, operators);
                }
            }
        } else {
            operands.add(expression);
        }
    } else {
        operands.add(expression);
    }
}

From source file:com.google.googlejavaformat.java.JavaInputAstVisitor.java

License:Apache License

/**
 * Output a "." node./* w ww.j  av a2s .c o m*/
 * @param node0 the "." node
 */
void visitDot(Expression node0) {
    Expression node = node0;

    // collect a flattened list of "."-separated items
    // e.g. ImmutableList.builder().add(1).build() -> [ImmutableList, builder(), add(1), build()]
    ArrayDeque<Expression> stack = new ArrayDeque<>();
    LOOP: do {
        stack.addFirst(node);
        switch (node.getNodeType()) {
        case ASTNode.FIELD_ACCESS:
            node = ((FieldAccess) node).getExpression();
            break;
        case ASTNode.METHOD_INVOCATION:
            node = ((MethodInvocation) node).getExpression();
            break;
        case ASTNode.QUALIFIED_NAME:
            node = ((QualifiedName) node).getQualifier();
            break;
        case ASTNode.SIMPLE_NAME:
            node = null;
            break LOOP;
        default:
            // If the dot chain starts with a primary expression
            // (e.g. a class instance creation, or a conditional expression)
            // then remove it from the list and deal with it first.
            stack.removeFirst();
            break LOOP;
        }
    } while (node != null);
    List<Expression> items = new ArrayList<>(stack);

    boolean needDot = false;

    // The dot chain started with a primary expression: output it normally, and indent
    // the rest of the chain +4.
    if (node != null) {
        // Exception: if it's an anonymous class declaration, we don't need to
        // break and indent after the trailing '}'.
        if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION
                && ((ClassInstanceCreation) node).getAnonymousClassDeclaration() != null) {
            builder.open(ZERO);
            node.accept(this);
            token(".");
        } else {
            builder.open(plusFour);
            node.accept(this);
            builder.breakOp();
            needDot = true;
        }
    }

    // Check if the dot chain has a prefix that looks like a type name, so we can
    // treat the type name-shaped part as a single syntactic unit.
    int prefixIndex = TypeNameClassifier.typePrefixLength(simpleNames(stack));

    int invocationCount = 0;
    int firstInvocationIndex = -1;
    {
        for (int i = 0; i < items.size(); i++) {
            Expression expression = items.get(i);
            if (expression.getNodeType() == ASTNode.METHOD_INVOCATION) {
                if (i > 0 || node != null) {
                    // we only want dereference invocations
                    invocationCount++;
                }
                if (firstInvocationIndex < 0) {
                    firstInvocationIndex = i;
                }
            }
        }
    }

    // If there's only one invocation, treat leading field accesses as a single
    // unit. In the normal case we want to preserve the alignment of subsequent
    // method calls, and would emit e.g.:
    //
    // myField
    //     .foo()
    //     .bar();
    //
    // But if there's no 'bar()' to worry about the alignment of we prefer:
    //
    // myField.foo();
    //
    // to:
    //
    // myField
    //     .foo();
    //
    if (invocationCount == 1) {
        prefixIndex = firstInvocationIndex;
    }

    if (prefixIndex > 0) {
        visitDotWithPrefix(items, needDot, prefixIndex);
    } else {
        visitRegularDot(items, needDot);
    }

    if (node != null) {
        builder.close();
    }
}

From source file:com.google.googlejavaformat.java.JavaInputAstVisitor.java

License:Apache License

/** Returns the simple names of expressions in a "." chain. */
private List<String> simpleNames(ArrayDeque<Expression> stack) {
    ImmutableList.Builder<String> simpleNames = ImmutableList.builder();
    OUTER: for (Expression expression : stack) {
        switch (expression.getNodeType()) {
        case ASTNode.FIELD_ACCESS:
            simpleNames.add(((FieldAccess) expression).getName().getIdentifier());
            break;
        case ASTNode.QUALIFIED_NAME:
            simpleNames.add(((QualifiedName) expression).getName().getIdentifier());
            break;
        case ASTNode.SIMPLE_NAME:
            simpleNames.add(((SimpleName) expression).getIdentifier());
            break;
        case ASTNode.METHOD_INVOCATION:
            simpleNames.add(((MethodInvocation) expression).getName().getIdentifier());
            break OUTER;
        default:/* w w w  .j a v a2  s  .c  o  m*/
            break OUTER;
        }
    }
    return simpleNames.build();
}

From source file:com.google.googlejavaformat.java.JavaInputAstVisitor.java

License:Apache License

private void dotExpressionUpToArgs(Expression expression, Optional<BreakTag> tyargTag) {
    switch (expression.getNodeType()) {
    case ASTNode.FIELD_ACCESS:
        FieldAccess fieldAccess = (FieldAccess) expression;
        visit(fieldAccess.getName());//from  w w w  . ja v a  2 s.c o  m
        break;
    case ASTNode.METHOD_INVOCATION:
        MethodInvocation methodInvocation = (MethodInvocation) expression;
        if (!methodInvocation.typeArguments().isEmpty()) {
            builder.open(plusFour);
            addTypeArguments(methodInvocation.typeArguments(), ZERO);
            // TODO(jdd): Should indent the name -4.
            builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO, tyargTag);
            builder.close();
        }
        visit(methodInvocation.getName());
        break;
    case ASTNode.QUALIFIED_NAME:
        visit(((QualifiedName) expression).getName());
        break;
    case ASTNode.SIMPLE_NAME:
        visit(((SimpleName) expression));
        break;
    default:
        expression.accept(this);
    }
}