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

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

Introduction

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

Prototype

public final int getStartPosition() 

Source Link

Document

Returns the character index into the original source file indicating where the source fragment corresponding to this node begins.

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 {/*  w  w  w .  j a  va  2 s . co  m*/
        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(/*from  ww w .j a v  a  2 s . c  o m*/
            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   w w w . j a va 2  s.c om*/

    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  ww w  .  j a  v  a2  s. co m*/
    }
    return true;
}

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

License:Apache License

private Integer actualColumn(Expression expression) {
    Map<Integer, Integer> positionToColumnMap = builder.getInput().getPositionToColumnMap();
    return positionToColumnMap.get(builder.actualStartColumn(expression.getStartPosition()));
}

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

License:Open Source License

/**
 * Consider the case://from ww  w  .j ava 2s.co 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;//from  w w  w.j  a  v  a 2  s  .  c o  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  .ja  v  a 2 s .c o  m*/
    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.liferay.blade.eclipse.provider.JavaFileJDT.java

License:Open Source License

/**
 * find the method invocations for a particular method on a given type or expression
 *
 * @param typeHint the type hint to use when matching expressions
 * @param expressionValue    the expression only value (no type hint)
 * @param methodName     the method name
 * @return    search results/*  ww w  .  j  a  v  a2s  . c  o  m*/
 */
@Override
@SuppressWarnings("unchecked")
public List<SearchResult> findMethodInvocations(final String typeHint, final String expressionValue,
        final String methodName, final String[] methodParamTypes) {
    final List<SearchResult> searchResults = new ArrayList<>();

    _ast.accept(new ASTVisitor() {

        @Override
        public boolean visit(MethodInvocation node) {
            final String methodNameValue = node.getName().toString();
            final Expression expression = node.getExpression();

            ITypeBinding type = null;

            if (expression != null) {
                type = expression.resolveTypeBinding();
            }

            if (((methodName.equals(methodNameValue)) || ("*".equals(methodName))) &&
            // if typeHint is not null it must match the type hint and ignore the expression
            // not strictly check the type and will check equals later
            ((typeHint != null && type != null && type.getName().endsWith(typeHint)) ||
            // with no typeHint then expressions can be used to match Static invocation
            (typeHint == null && expression != null && expression.toString().equals(expressionValue)))) {

                boolean argumentsMatch = false;

                if (methodParamTypes != null) {
                    Expression[] argExpressions = ((List<Expression>) node.arguments())
                            .toArray(new Expression[0]);

                    if (argExpressions.length == methodParamTypes.length) {
                        //args number matched
                        boolean possibleMatch = true;
                        // assume all types will match until we find otherwise
                        boolean typeMatched = true;
                        boolean typeUnresolved = false;

                        for (int i = 0; i < argExpressions.length; i++) {
                            Expression arg = argExpressions[i];
                            ITypeBinding argType = arg.resolveTypeBinding();

                            if (argType != null) {
                                //can resolve the type
                                if (argType.getName().equals(methodParamTypes[i])) {
                                    //type matched
                                    continue;
                                } else {
                                    //type unmatched
                                    possibleMatch = false;
                                    typeMatched = false;
                                    break;
                                }
                            } else {
                                possibleMatch = false;
                                //there are two cases :
                                //typeUnresolved : means that  all resolved type is matched and there is unsolved type , need to set fullMatch false
                                //typeUnmatched : means that some resolved type is unmatched , no need to add SearchResult

                                //do not add searchResults now , just record the state and continue
                                //because there maybe unmatched type later which will  break this case
                                typeUnresolved = true;
                            }
                        }

                        if (typeMatched && typeUnresolved) {
                            final int startOffset = expression.getStartPosition();
                            final int startLine = _ast.getLineNumber(startOffset);
                            final int endOffset = node.getStartPosition() + node.getLength();
                            final int endLine = _ast.getLineNumber(endOffset);
                            //can't resolve the type but  args number matched  ,  note that the last param is false
                            searchResults.add(createSearchResult(null, startOffset, endOffset, startLine,
                                    endLine, false));
                        }

                        if (possibleMatch) {
                            argumentsMatch = true;
                        }
                    }
                }
                //any method args types is OK without setting methodParamTypes
                else {
                    argumentsMatch = true;
                }

                if (argumentsMatch) {
                    final int startOffset = expression.getStartPosition();
                    final int startLine = _ast.getLineNumber(startOffset);
                    final int endOffset = node.getStartPosition() + node.getLength();
                    final int endLine = _ast.getLineNumber(endOffset);
                    boolean isFullMatch = true;

                    //endsWith but not equals
                    if (typeHint != null && type != null && type.getName().endsWith(typeHint)
                            && !type.getName().equals(typeHint)) {
                        isFullMatch = false;
                    }

                    searchResults.add(
                            createSearchResult(null, startOffset, endOffset, startLine, endLine, isFullMatch));
                }
            }

            return true;
        }
    });

    return searchResults;
}

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

License:Apache License

/**
 * {@inheritDoc}/*from  w  w w  .j a v a 2 s  . com*/
 */
@Override
public int getStartPosition() {
    final Expression expression = classInstanceCreation.getExpression();
    return expression != null ? expression.getStartPosition() + expression.getLength() + 1
            : classInstanceCreation.getType().getStartPosition();
}