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

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

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom Type 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

public boolean visit(Type 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 w ww .j  a v  a2s  .  co m
            new LanguageConstruct(node.getClass().getSimpleName(), beginLine, endLine, beginColumn, endColumn));

    return true;
}

From source file:com.chookapp.org.bracketeer.jdt.ClosingBracketHintVisitor.java

License:Open Source License

private void addBrackets(ParameterizedType node) throws BadLocationException {
    @SuppressWarnings("unchecked")
    List<Type> args = node.typeArguments();
    if (args.isEmpty())
        return;// www  .ja va  2 s. com

    Type type = args.get(0);
    int startLoc = type.getStartPosition() - 1;
    type = args.get(args.size() - 1);
    int endLoc = type.getStartPosition() + type.getLength();
    _container.add(new BracketsPair(startLoc, '<', endLoc, '>'));

}

From source file:com.halware.nakedide.eclipse.ext.annot.utils.AstUtils.java

License:Open Source License

/**
 * Returns the offset and length for the {@link MethodDeclaration}, optionally
 * including any modifiers (including annotations and visibility).
 * /*from w w w  .ja v a  2  s. com*/
 * @param declaration
 * @param includingModifiers - whether to include modifiers in the offset and length.
 */
public final static OffsetAndLength calculateOffset(BodyDeclaration declaration, boolean includingModifiers) {
    if (!(declaration instanceof MethodDeclaration) && !(declaration instanceof TypeDeclaration)) {
        throw new IllegalArgumentException("declaration must be TypeDeclaration or MethodDeclaration");
    }
    SimpleName methodName = nameFor(declaration);
    if (!includingModifiers) {
        return new OffsetAndLength(methodName.getStartPosition(), methodName.getLength());
    } else {
        // including modifiers
        int endOfMethodName = methodName.getStartPosition() + methodName.getLength();
        ChildListPropertyDescriptor modifiersProperty = declaration.getModifiersProperty();
        List<ASTNode> methodModifiers = Generics.asT(declaration.getStructuralProperty(modifiersProperty));
        if (methodModifiers.size() > 0) {
            int startOfModifiers = methodModifiers.get(0).getStartPosition();
            return new OffsetAndLength(startOfModifiers, endOfMethodName - startOfModifiers);
        }
        if (declaration instanceof MethodDeclaration) {
            Type returnType2 = ((MethodDeclaration) declaration).getReturnType2();
            if (returnType2 != null) {
                int startOfReturnType = returnType2.getStartPosition();
                return new OffsetAndLength(startOfReturnType, endOfMethodName - startOfReturnType);
            }
        }
        int startOfMethodName = declaration.getStartPosition();
        return new OffsetAndLength(startOfMethodName, endOfMethodName - startOfMethodName);
    }
}

From source file:com.tsc9526.monalisa.plugin.eclipse.generator.SelectGenerator.java

License:Open Source License

private void findSelectMethods() {
    Set<String> imps = new HashSet<String>();

    for (MethodDeclaration md : unit.getUnitType().getMethods()) {
        Type rt = md.getReturnType2();

        if (rt == null)
            continue;

        String returnClazz = rt.toString();
        Set<String> returnParameter = new HashSet<String>();

        if (rt.isParameterizedType()) {
            ParameterizedType ptype = (ParameterizedType) rt;
            returnClazz = ptype.getType().toString();
            for (Object arg : ptype.typeArguments()) {
                returnParameter.add(arg.toString());

                referTypes.add(arg.toString());
            }/*from  w w w.j  a va  2  s .  co  m*/
        } else {
            referTypes.add(returnClazz);
        }

        Annotation a = unit.getAnnotation(md, Select.class);
        if (a != null) {
            SelectMethod sm = new SelectMethod(unit, md, a);
            String rcn = sm.getResultClassName();

            String newReturnType = null;
            if (isCollectionType(returnClazz)) {
                String ps = returnParameter.size() > 0 ? returnParameter.iterator().next() : "";
                if (ps.equals("") || isObjectOrDataMap(ps)) {
                    newReturnType = returnClazz + "<" + rcn + ">";
                    imps.add(sm.getResultClassPackage() + "." + rcn);
                } else {
                    if (rcn.equals(ps) == false && sm.isForceRenameResultClass()) {
                        newReturnType = returnClazz + "<" + rcn + ">";
                        imps.add(sm.getResultClassPackage() + "." + rcn);
                    }
                }
            } else if (isObjectOrDataMap(returnClazz)) {
                newReturnType = rcn;
                imps.add(sm.getResultClassPackage() + "." + rcn);
            } else {
                if (rcn.equals(returnClazz) == false && sm.isForceRenameResultClass()) {
                    newReturnType = rcn;
                    imps.add(sm.getResultClassPackage() + "." + rcn);
                }
            }

            if (newReturnType != null) {
                QueryRewriteVisitor rewrite = new QueryRewriteVisitor(rcn);
                md.accept(rewrite);

                List<ReplaceEdit> changes = rewrite.getChanges();
                changes.add(new ReplaceEdit(rt.getStartPosition(), rt.getLength(), newReturnType));

                for (ReplaceEdit re : changes) {
                    edit.addChild(re);
                }
                sm.calculateFingerprint(changes);

                addSelectMethod(sm);
            } else if (sm.isChanged()) {
                addSelectMethod(sm);
            }
        }
    }

    if (imps.size() > 0) {
        TextEdit importEdit = unit.createImports(imps);
        edit.addChild(importEdit);
    }
}

From source file:edu.uci.ics.sourcerer.extractor.ast.ReferenceExtractorVisitor.java

License:Open Source License

/**
 * This method writes:/*from   www  .j  a v  a  2 s  .  c om*/
 * <ul>
 *   <li>Local variable entity to <code>ILocalVariableWriter</code></li>
 *   <li>Uses relation to <code>IRelationWriter</code></li>
 * </ul>
 */
@Override
public boolean visit(SingleVariableDeclaration node) {
    IVariableBinding binding = node.resolveBinding();
    Type type = node.getType();

    if (binding != null) {
        String typeFqn = getTypeFqn(binding.getType());
        if (binding.isParameter()) {
            // Write the parameter
            localVariableWriter.writeParameter(binding.getName(), binding.getModifiers(), typeFqn,
                    type.getStartPosition(), type.getLength(), fqnStack.getFqn(),
                    fqnStack.getNextParameterPos(), getLocation(node.getName()));
        } else {
            // Write the local variable
            localVariableWriter.writeLocalVariable(binding.getName(), binding.getModifiers(), typeFqn,
                    type.getStartPosition(), type.getLength(), fqnStack.getFqn(), getLocation(node.getName()));
        }
    }
    return true;
}

From source file:edu.uci.ics.sourcerer.extractor.ast.ReferenceExtractorVisitor.java

License:Open Source License

/**
 * This method writes://w  ww  .  ja v a2 s.  c o m
 * <ul>
 *   <li>Field entity to <code>IEntityWriter</code>.
 *   <ul>
 *     <li>Inside relation to <code>IRelationWriter</code>.</li>
 *     <li>Holds relation to <code>IRelationWriter</code>.</li>
 *   </ul></li>
 *   <li>Local variable to <code>ILocalVariableWriter</code>.
 *   <ul>
 *     <li>Uses relation to <code>IRelationWriter</codE>.</li>
 *   </ul></li>
 * </ul>
 * 
 * Field fully qualified names (FQNs) adhere to the following format:<br> 
 * parent fqn + . + simple name
 */
@Override
public boolean visit(VariableDeclarationFragment node) {
    if (node.getParent() instanceof FieldDeclaration) {
        FieldDeclaration parent = (FieldDeclaration) node.getParent();

        // Get the fqn
        String fqn = fqnStack.getTypeFqn(node.getName().getIdentifier());

        // Write the entity
        entityWriter.writeField(fqn, parent.getModifiers(),
                MetricsCalculator.computeLinesOfCode(getSource(node)), getLocation(node));

        // Write the inside relation
        relationWriter.writeInside(fqn, fqnStack.getFqn(), getUnknownLocation());

        Type type = parent.getType();
        String typeFqn = getTypeFqn(type);

        // Write the holds relation
        relationWriter.writeHolds(fqn, typeFqn, getLocation(type));

        // Add the field to the fqnstack
        fqnStack.push(fqn, Entity.FIELD);

        // Write the uses relation
        accept(parent.getType());

        // Write the javadoc comment
        accept(parent.getJavadoc());
    } else if (node.getParent() instanceof VariableDeclarationStatement) {
        VariableDeclarationStatement parent = (VariableDeclarationStatement) node.getParent();

        Type type = parent.getType();
        String typeFqn = getTypeFqn(type);

        // Write the local variable
        localVariableWriter.writeLocalVariable(node.getName().getIdentifier(), parent.getModifiers(), typeFqn,
                type.getStartPosition(), type.getLength(), fqnStack.getFqn(), getLocation(node));
    } else if (node.getParent() instanceof VariableDeclarationExpression) {
        VariableDeclarationExpression parent = (VariableDeclarationExpression) node.getParent();

        Type type = parent.getType();
        String typeFqn = getTypeFqn(type);

        // Write the local variable
        localVariableWriter.writeLocalVariable(node.getName().getIdentifier(), parent.getModifiers(), typeFqn,
                type.getStartPosition(), type.getLength(), fqnStack.getFqn(), getLocation(node));
    } else {
        logger.log(Level.SEVERE, "Unknown parent for variable declaration fragment.");
    }

    IVariableBinding binding = node.resolveBinding();
    if (binding != null && binding.isField() && !(node.getParent() instanceof FieldDeclaration)) {
        logger.log(Level.SEVERE, "It's a field but it shouldn't be!");
    }

    if (node.getInitializer() != null) {
        inLhsAssignment = true;
        accept(node.getName());
        inLhsAssignment = false;
        accept(node.getInitializer());
    }

    return false;
}

From source file:org.bundlemaker.core.ui.editor.sourceviewer.referencedetail.JdtAstVisitor.java

License:Open Source License

/***************/
private void resolveType(Type type) {

    // return null if type == null
    if (type == null) {
        return;/*  w  w  w  .j  av  a 2 s .c  o m*/
    }

    if (type.resolveBinding() != null && !type.resolveBinding().isRecovered()) {
        // resolve the type binding
        resolveTypeBinding(type.resolveBinding(), type.getStartPosition(), type.getLength());
    } else {
        //
        System.out.println("Resolve Type " + type.toString());
    }
}

From source file:org.codehaus.groovy.eclipse.dsl.inferencing.suggestions.JavaValidParameterizedTypeRule.java

License:Apache License

protected String getTypeName(Type type, StringBuffer source) {
    String name = null;/*  w ww  .j a v  a  2  s . c o m*/
    name = source.substring(type.getStartPosition(), ASTNodes.getExclusiveEnd(type));
    if (type instanceof ParameterizedType) {

        // Strip everything after the first <
        int index = name.indexOf('<');
        if (index >= 0) {
            name = name.substring(0, index);
        }
    }
    return name;
}

From source file:org.eclipse.jdt.core.dom.ASTConverter.java

License:Open Source License

public SingleVariableDeclaration convert(org.eclipse.jdt.internal.compiler.ast.Argument argument) {
    SingleVariableDeclaration variableDecl = new SingleVariableDeclaration(this.ast);
    setModifiers(variableDecl, argument);
    final SimpleName name = new SimpleName(this.ast);
    name.internalSetIdentifier(new String(argument.name));
    int start = argument.sourceStart;
    int nameEnd = argument.sourceEnd;
    name.setSourceRange(start, nameEnd - start + 1);
    variableDecl.setName(name);/*from  w w  w.  ja  v  a2  s.  co m*/
    final int typeSourceEnd = argument.type.sourceEnd;
    final int extraDimensions = retrieveExtraDimension(nameEnd + 1, typeSourceEnd);
    variableDecl.setExtraDimensions(extraDimensions);
    final boolean isVarArgs = argument.isVarArgs();
    // GROOVY start
    // Do not try to change source ends for var args.  Groovy assumes that
    // all methods that have an array as the last param are varargs
    /* old {
    if (isVarArgs && extraDimensions == 0) {
    } new */
    if (argument.binding != null && scannerAvailable(argument.binding.declaringScope) && isVarArgs
            && extraDimensions == 0) {
        // GROOVY end
        // remove the ellipsis from the type source end
        argument.type.sourceEnd = retrieveEllipsisStartPosition(argument.type.sourceStart, typeSourceEnd);
    }
    Type type = convertType(argument.type);
    int typeEnd = type.getStartPosition() + type.getLength() - 1;
    int rightEnd = Math.max(typeEnd, argument.declarationSourceEnd);
    /*
     * There is extra work to do to set the proper type positions
     * See PR http://bugs.eclipse.org/bugs/show_bug.cgi?id=23284
     */
    if (isVarArgs) {
        setTypeForSingleVariableDeclaration(variableDecl, type, extraDimensions + 1);
        if (extraDimensions != 0) {
            variableDecl.setFlags(variableDecl.getFlags() | ASTNode.MALFORMED);
        }
    } else {
        setTypeForSingleVariableDeclaration(variableDecl, type, extraDimensions);
    }
    variableDecl.setSourceRange(argument.declarationSourceStart,
            rightEnd - argument.declarationSourceStart + 1);

    if (isVarArgs) {
        switch (this.ast.apiLevel) {
        case AST.JLS2_INTERNAL:
            variableDecl.setFlags(variableDecl.getFlags() | ASTNode.MALFORMED);
            break;
        default:
            variableDecl.setVarargs(true);
        }
    }
    if (this.resolveBindings) {
        recordNodes(name, argument);
        recordNodes(variableDecl, argument);
        variableDecl.resolveBinding();
    }
    return variableDecl;
}

From source file:org.eclipse.jdt.core.dom.ASTConverter.java

License:Open Source License

public ArrayCreation convert(org.eclipse.jdt.internal.compiler.ast.ArrayAllocationExpression expression) {
    ArrayCreation arrayCreation = new ArrayCreation(this.ast);
    if (this.resolveBindings) {
        recordNodes(arrayCreation, expression);
    }/* w  w w .jav a  2s .  co m*/
    arrayCreation.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
    org.eclipse.jdt.internal.compiler.ast.Expression[] dimensions = expression.dimensions;

    int dimensionsLength = dimensions.length;
    for (int i = 0; i < dimensionsLength; i++) {
        if (dimensions[i] != null) {
            Expression dimension = convert(dimensions[i]);
            if (this.resolveBindings) {
                recordNodes(dimension, dimensions[i]);
            }
            arrayCreation.dimensions().add(dimension);
        }
    }
    Type type = convertType(expression.type);
    if (this.resolveBindings) {
        recordNodes(type, expression.type);
    }
    ArrayType arrayType = null;
    if (type.isArrayType()) {
        arrayType = (ArrayType) type;
    } else {
        arrayType = this.ast.newArrayType(type, dimensionsLength);
        if (this.resolveBindings) {
            completeRecord(arrayType, expression);
        }
        int start = type.getStartPosition();
        int end = type.getStartPosition() + type.getLength();
        int previousSearchStart = end - 1;
        ArrayType componentType = (ArrayType) type.getParent();
        for (int i = 0; i < dimensionsLength; i++) {
            previousSearchStart = retrieveRightBracketPosition(previousSearchStart + 1,
                    this.compilationUnitSourceLength);
            componentType.setSourceRange(start, previousSearchStart - start + 1);
            componentType = (ArrayType) componentType.getParent();
        }
    }
    arrayCreation.setType(arrayType);
    if (this.resolveBindings) {
        recordNodes(arrayType, expression);
    }
    if (expression.initializer != null) {
        arrayCreation.setInitializer(convert(expression.initializer));
    }
    return arrayCreation;
}