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

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

Introduction

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

Prototype

public final int getLength() 

Source Link

Document

Returns the length in characters of the original source file indicating where the source fragment corresponding to this node ends.

Usage

From source file:br.uff.ic.gems.resources.ast.Visitor.java

@Override
public boolean visit(IfStatement node) {
    int beginLine = cu.getLineNumber(node.getStartPosition());
    int endLine = cu.getLineNumber(node.getStartPosition() + node.getLength());
    int beginColumn = cu.getColumnNumber(node.getStartPosition());
    int endColumn = cu.getColumnNumber(node.getStartPosition() + node.getLength());

    int beginLineBlock = 0;
    int beginColumnBlock = 0;

    Expression expression = node.getExpression();

    if (expression != null) {
        beginLineBlock = cu.getLineNumber(expression.getStartPosition() + expression.getLength());
        beginColumnBlock = cu.getColumnNumber(expression.getStartPosition() + expression.getLength());
        languageConstructs.add(new LanguageConstruct(node.getClass().getSimpleName(), beginLine, endLine,
                beginColumn, endColumn, beginLineBlock, endLine, beginColumnBlock, endColumn, null));
    } else {/* ww  w. j a v a 2 s. c om*/
        languageConstructs.add(new LanguageConstruct(node.getClass().getSimpleName(), beginLine, endLine,
                beginColumn, endColumn));
    }

    return true;
}

From source file:br.uff.ic.gems.resources.ast.Visitor.java

public boolean visit(Expression node) {
    int beginLine = cu.getLineNumber(node.getStartPosition());
    int endLine = cu.getLineNumber(node.getStartPosition() + node.getLength());
    int beginColumn = cu.getColumnNumber(node.getStartPosition());
    int endColumn = cu.getColumnNumber(node.getStartPosition() + node.getLength());

    languageConstructs.add(/*  w  w  w. j av a  2s.c om*/
            new LanguageConstruct(node.getClass().getSimpleName(), beginLine, endLine, beginColumn, endColumn));

    return true;
}

From source file:ca.ecliptical.pde.internal.ds.AnnotationProcessor.java

License:Open Source License

private void reportProblem(Annotation annotation, String member, int valueIndex,
        Collection<DSAnnotationProblem> problems, String message, String... args) {
    if (errorLevel.isNone())
        return;/*from   ww w.j  a v  a  2  s .com*/

    Expression memberValue = annotation;
    if (annotation.isNormalAnnotation() && member != null) {
        NormalAnnotation na = (NormalAnnotation) annotation;
        for (Object value : na.values()) {
            MemberValuePair pair = (MemberValuePair) value;
            if (member.equals(pair.getName().getIdentifier())) {
                memberValue = pair.getValue();
                break;
            }
        }
    } else if (annotation.isSingleMemberAnnotation()) {
        SingleMemberAnnotation sma = (SingleMemberAnnotation) annotation;
        memberValue = sma.getValue();
    }

    int start = memberValue.getStartPosition();
    int length = memberValue.getLength();

    if (valueIndex >= 0 && memberValue instanceof ArrayInitializer) {
        ArrayInitializer ai = (ArrayInitializer) memberValue;
        if (valueIndex < ai.expressions().size()) {
            Expression element = (Expression) ai.expressions().get(valueIndex);
            start = element.getStartPosition();
            length = element.getLength();
        }
    }

    if (start >= 0) {
        DSAnnotationProblem problem = new DSAnnotationProblem(errorLevel.isError(), message, args);
        problem.setSourceStart(start);
        problem.setSourceEnd(start + length - 1);
        problems.add(problem);
    }
}

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

License:Apache License

private boolean hasOnlyShortItems(List<Expression> expressions) {
    for (Expression expression : expressions) {
        if (builder.actualSize(expression.getStartPosition(),
                expression.getLength()) >= MAX_ITEM_LENGTH_FOR_FILLING) {
            return false;
        }/*from  w ww . j  av a  2s  .  com*/
    }
    return true;
}

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

License:Apache License

/**
 * Output a "regular" chain of dereferences, possibly in builder-style. Break before every dot.
 *
 * @param items           in the chain/*from  w  ww.  j a  v  a 2 s.  co  m*/
 * @param needDot         whether a leading dot is needed
 */
private void visitRegularDot(List<Expression> items, boolean needDot) {
    boolean trailingDereferences = items.size() > 1;
    boolean needDot0 = needDot;
    if (!needDot0) {
        builder.open(plusFour, MAX_LINES_FOR_CHAINED_ACCESSES);
    }
    // don't break after the first element if it is every small, unless the
    // chain starts with another expression
    int minLength = indentMultiplier * 4;
    int length = needDot0 ? minLength : 0;
    for (Expression e : items) {
        if (needDot) {
            if (length > minLength) {
                builder.breakOp(FillMode.UNIFIED, "", ZERO);
            }
            token(".");
            length++;
        }
        BreakTag tyargTag = genSym();
        dotExpressionUpToArgs(e, Optional.of(tyargTag));
        Indent tyargIndent = Indent.If.make(tyargTag, plusFour, ZERO);
        dotExpressionArgsAndParen(e, tyargIndent, (trailingDereferences || needDot) ? plusFour : ZERO);
        length += e.getLength();
        needDot = true;
    }
    if (!needDot0) {
        builder.close();
    }
}

From source file:com.ibm.wala.cast.java.translator.jdt.JDTJava2CAstTranslator.java

License:Open Source License

/**
 * Consider the case:/* w  w w. j  a va  2  s.c o m*/
 * 
 * <pre>
 * String real_oneheyya = (((returnObjectWithSideEffects().y))+=&quot;hey&quot;)+&quot;ya&quot;
 * </pre>
 * 
 * where field 'y' is parameterized to type string. then += is not defined for type 'object'. This function is a hack that expands
 * the code into an assignment and binary operation.
 * 
 * @param leftCast this is the left cast in the original expression. We throw most of it away, although we use the "Cast from" and
 *          "cast to"
 * @param left
 * @param context
 * @return
 */
private CAstNode doFunkyGenericAssignPreOpHack(Assignment assign, WalkContext context) {
    Expression left = assign.getLeftHandSide();
    Expression right = assign.getRightHandSide();

    // consider the case:
    // String real_oneheyya = (((returnObjectWithSideEffects().y))+="hey")+"ya"; // this is going to be a MAJOR pain...
    // where field 'y' is parameterized to type string. then += is not defined for type 'object'. we want to transform
    // it kind of like this, except we have to define temp.
    // String real_oneheyya = (String)((temp=cg2WithSideEffects()).y = (String)temp.y + "hey")+"ya";
    // ----------------------------------------------------------------
    //
    // we are responsible for underlined portion
    // CAST(LOCAL SCOPE(BLOCK EXPR(DECL STMT(temp,
    // left.target),ASSIGN(OBJECT_REF(temp,y),BINARY_EXPR(CAST(OBJECT_REF(Temp,y)),RIGHT)))))
    // yeah, I know, it's cheating, LOCAL SCOPE / DECL STMT inside an expression ... will it work?

    while (left instanceof ParenthesizedExpression)
        left = ((ParenthesizedExpression) left).getExpression();
    assert left instanceof FieldAccess : "Cast in assign pre-op but no field access?!";

    FieldAccess field = (FieldAccess) left;
    InfixExpression.Operator infixop = JDT2CAstUtils.mapAssignOperatorToInfixOperator(assign.getOperator());

    // DECL_STMT: temp = ...;
    final String tmpName = "temp generic preop hack"; // illegal Java identifier
    CAstNode exprNode = visitNode(field.getExpression(), context);
    CAstNode tmpDeclNode = makeNode(context, fFactory, left, CAstNode.DECL_STMT,
            fFactory.makeConstant(new InternalCAstSymbol(tmpName,
                    fTypeDict.getCAstTypeFor(field.getExpression().resolveTypeBinding()), true)),
            exprNode);

    // need two object refndoes "temp.y"
    CAstNode obref1 = createFieldAccess(
            makeNode(context, fFactory, left, CAstNode.VAR, fFactory.makeConstant(tmpName),
                    fFactory.makeConstant(fTypeDict.getCAstTypeFor(field.resolveFieldBinding().getType()))),
            field.getName().getIdentifier(), field.resolveFieldBinding(), left, new AssignmentContext(context));

    CAstNode obref2 = createFieldAccess(
            makeNode(context, fFactory, left, CAstNode.VAR, fFactory.makeConstant(tmpName),
                    fFactory.makeConstant(fTypeDict.getCAstTypeFor(field.resolveFieldBinding().getType()))),
            field.getName().getIdentifier(), field.resolveFieldBinding(), left, context);
    ITypeBinding realtype = JDT2CAstUtils.getErasedType(field.resolveFieldBinding().getType(), ast);
    ITypeBinding fromtype = JDT2CAstUtils
            .getTypesVariablesBase(field.resolveFieldBinding().getVariableDeclaration().getType(), ast);
    CAstNode castedObref = obref2;// createCast(left, obref2, fromtype, realtype, context);

    // put it all together
    // CAST(LOCAL SCOPE(BLOCK EXPR(DECL STMT(temp,
    // left.target),ASSIGN(OBJECT_REF(temp,y),BINARY_EXPR(CAST(OBJECT_REF(Temp,y)),RIGHT)))))
    CAstNode result = makeNode(context, fFactory, assign, CAstNode.LOCAL_SCOPE,
            makeNode(context, fFactory, assign, CAstNode.BLOCK_EXPR, tmpDeclNode,
                    makeNode(context, fFactory, assign, CAstNode.ASSIGN, obref1,
                            createInfixExpression(infixop, realtype, left.getStartPosition(), left.getLength(),
                                    castedObref, right, context))));

    return createCast(assign, result, fromtype, realtype, context);
}

From source file:com.ibm.wala.cast.java.translator.jdt.JDTJava2CAstTranslator.java

License:Open Source License

private CAstNode visit(InfixExpression n, WalkContext context) {
    Expression left = n.getLeftOperand();
    ITypeBinding leftType = left.resolveTypeBinding();
    int leftStartPosition = left.getStartPosition();

    CAstNode leftNode = visitNode(left, context);

    int leftLength = n.getLeftOperand().getLength();
    CAstNode result = createInfixExpression(n.getOperator(), leftType, leftStartPosition, leftLength, leftNode,
            n.getRightOperand(), context);

    if (n.hasExtendedOperands()) {
        // keep on adding operands on the right side

        leftLength = n.getRightOperand().getStartPosition() + n.getRightOperand().getLength()
                - leftStartPosition;// w w  w  .j  a  va 2 s. co  m
        for (Object o : n.extendedOperands()) {
            Expression operand = (Expression) o;
            result = createInfixExpression(n.getOperator(), leftType, leftStartPosition, leftLength, result,
                    operand, context);

            if (leftType.isPrimitive() && operand.resolveTypeBinding().isPrimitive())
                leftType = JDT2CAstUtils.promoteTypes(leftType, operand.resolveTypeBinding(), ast); // TODO: boxing
            else
                leftType = operand.resolveTypeBinding();

            // leftStartPosition doesn't change, beginning is always the first operand
            leftLength = operand.getStartPosition() + operand.getLength() - leftStartPosition;
        }
    }

    return result;
}

From source file:com.ibm.wala.cast.java.translator.jdt.JDTJava2CAstTranslator.java

License:Open Source License

private CAstNode createInfixExpression(InfixExpression.Operator op, ITypeBinding leftType,
        int leftStartPosition, int leftLength, CAstNode leftNode, Expression right, WalkContext context) {
    CAstNode rightNode = visitNode(right, context);

    int start = leftStartPosition;
    int end = right.getStartPosition() + right.getLength();
    T pos = makePosition(start, end);/*from w w  w .  j  av a  2  s.  c  om*/
    T rightPos = makePosition(leftStartPosition, leftStartPosition + leftLength);
    T leftPos = makePosition(right.getStartPosition(), right.getStartPosition() + right.getLength());

    if (op == InfixExpression.Operator.CONDITIONAL_AND) {
        return makeNode(context, fFactory, pos, CAstNode.IF_EXPR, leftNode, rightNode,
                fFactory.makeConstant(false));
    } else if (op == InfixExpression.Operator.CONDITIONAL_OR) {
        return makeNode(context, fFactory, pos, CAstNode.IF_EXPR, leftNode, fFactory.makeConstant(true),
                rightNode);
    } else {
        ITypeBinding rightType = right.resolveTypeBinding();
        if (leftType.isPrimitive() && rightType.isPrimitive()) {
            // TODO: boxing
            ITypeBinding result = JDT2CAstUtils.promoteTypes(leftType, rightType, ast);

            // cast to proper type
            if (!result.isEqualTo(leftType))
                leftNode = makeNode(context, fFactory, leftPos, CAstNode.CAST,
                        fFactory.makeConstant(fTypeDict.getCAstTypeFor(result)), leftNode,
                        fFactory.makeConstant(fTypeDict.getCAstTypeFor(leftType)));
            if (!result.isEqualTo(rightType))
                rightNode = makeNode(context, fFactory, rightPos, CAstNode.CAST,
                        fFactory.makeConstant(fTypeDict.getCAstTypeFor(result)), rightNode,
                        fFactory.makeConstant(fTypeDict.getCAstTypeFor(rightType)));

            CAstNode opNode = makeNode(context, fFactory, pos, CAstNode.BINARY_EXPR,
                    JDT2CAstUtils.mapBinaryOpcode(op), leftNode, rightNode);

            // divide by zero exception implicitly thrown
            if (JDT2CAstUtils.isLongOrLess(leftType) && JDT2CAstUtils.isLongOrLess(rightType)
                    && (JDT2CAstUtils.mapBinaryOpcode(op) == CAstOperator.OP_DIV
                            || JDT2CAstUtils.mapBinaryOpcode(op) == CAstOperator.OP_MOD)) {
                Collection excTargets = context.getCatchTargets(fDivByZeroExcType);
                if (!excTargets.isEmpty()) {
                    for (Iterator iterator = excTargets.iterator(); iterator.hasNext();) {
                        Pair catchPair = (Pair) iterator.next();
                        context.cfg().add(op, catchPair.snd, fDivByZeroExcType);
                    }
                } else {
                    context.cfg().add(op, CAstControlFlowMap.EXCEPTION_TO_EXIT, fDivByZeroExcType);
                }
            }

            return opNode;

        } else {
            return makeNode(context, fFactory, pos, CAstNode.BINARY_EXPR, JDT2CAstUtils.mapBinaryOpcode(op),
                    leftNode, rightNode);
        }
    }
}

From source file:com.intel.ide.eclipse.mpt.ast.UnresolvedElementsSubProcessor.java

License:Open Source License

private static void addMissingCastParentsProposal(ICompilationUnit cu, MethodInvocation invocationNode,
        Collection<LinkedCorrectionProposal> proposals) {
    Expression sender = invocationNode.getExpression();
    if (sender instanceof ThisExpression) {
        return;//from   ww w.j a va2 s  .c  o m
    }

    ITypeBinding senderBinding = sender.resolveTypeBinding();
    if (senderBinding == null || Modifier.isFinal(senderBinding.getModifiers())) {
        return;
    }

    if (sender instanceof Name && ((Name) sender).resolveBinding() instanceof ITypeBinding) {
        return; // static access
    }

    ASTNode parent = invocationNode.getParent();
    while (parent instanceof Expression && parent.getNodeType() != ASTNode.CAST_EXPRESSION) {
        parent = parent.getParent();
    }
    boolean hasCastProposal = false;
    if (parent instanceof CastExpression) {
        //   (TestCase) x.getName() -> ((TestCase) x).getName
        //         hasCastProposal= useExistingParentCastProposal(cu, (CastExpression) parent, sender, invocationNode.getName(), getArgumentTypes(invocationNode.arguments()), proposals);
    }
    if (!hasCastProposal) {
        // x.getName() -> ((TestCase) x).getName

        Expression target = sender;
        while (target instanceof ParenthesizedExpression) {
            target = ((ParenthesizedExpression) target).getExpression();
        }

        String label;
        if (target.getNodeType() != ASTNode.CAST_EXPRESSION) {
            String targetName = null;
            if (target.getLength() <= 18) {
                targetName = ASTNodes.asString(target);
            }
            if (targetName == null) {
                label = CorrectionMessages.UnresolvedElementsSubProcessor_methodtargetcast_description;
            } else {
                label = Messages.format(
                        CorrectionMessages.UnresolvedElementsSubProcessor_methodtargetcast2_description,
                        BasicElementLabels.getJavaCodeString(targetName));
            }
        } else {
            String targetName = null;
            if (target.getLength() <= 18) {
                targetName = ASTNodes.asString(((CastExpression) target).getExpression());
            }
            if (targetName == null) {
                label = CorrectionMessages.UnresolvedElementsSubProcessor_changemethodtargetcast_description;
            } else {
                label = Messages.format(
                        CorrectionMessages.UnresolvedElementsSubProcessor_changemethodtargetcast2_description,
                        BasicElementLabels.getJavaCodeString(targetName));
            }
        }
        proposals.add(new CastCorrectionProposal(label, cu, target, (ITypeBinding) null,
                IProposalRelevance.CHANGE_CAST));
    }
}

From source file:eu.cloudwave.wp5.feedback.eclipse.performance.core.ast.extensions.ClassInstanceCreationExtension.java

License:Apache License

/**
 * {@inheritDoc}// w ww . j ava 2s.  c o  m
 */
@Override
public int getStartPosition() {
    final Expression expression = classInstanceCreation.getExpression();
    return expression != null ? expression.getStartPosition() + expression.getLength() + 1
            : classInstanceCreation.getType().getStartPosition();
}