Search in sources :

Example 11 with ArrayType

use of org.eclipse.jdt.core.dom.ArrayType in project evosuite by EvoSuite.

the class JUnitCodeGenerator method createArrayInitStmt.

@Override
public void createArrayInitStmt(final CaptureLog log, final int logRecNo) {
    final int oid = log.objectIds.get(logRecNo);
    final Object[] params = log.params.get(logRecNo);
    final String arrTypeName = log.oidClassNames.get(log.oidRecMapping.get(oid));
    final Class<?> arrType = getClassForName(arrTypeName);
    // --- create array instance creation e.g. int[] var = new int[10];
    final ArrayType arrAstType = (ArrayType) createAstArrayType(arrTypeName, ast);
    final ArrayCreation arrCreationExpr = ast.newArrayCreation();
    arrCreationExpr.setType(arrAstType);
    arrCreationExpr.dimensions().add(ast.newNumberLiteral(String.valueOf(params.length)));
    final String arrVarName = this.createNewVarName(oid, arrTypeName);
    final VariableDeclarationFragment vd = ast.newVariableDeclarationFragment();
    final SimpleName arrVarNameExpr = ast.newSimpleName(arrVarName);
    vd.setName(arrVarNameExpr);
    vd.setInitializer(arrCreationExpr);
    final VariableDeclarationStatement varDeclStmt = ast.newVariableDeclarationStatement(vd);
    varDeclStmt.setType(this.createAstType(arrTypeName, ast));
    methodBlock.statements().add(varDeclStmt);
    // create array access statements var[0] = var1;
    Integer paramOID;
    Assignment assign;
    ArrayAccess arrAccessExpr;
    for (int i = 0; i < params.length; i++) {
        assign = ast.newAssignment();
        arrAccessExpr = ast.newArrayAccess();
        arrAccessExpr.setIndex(ast.newNumberLiteral(String.valueOf(i)));
        arrAccessExpr.setArray(arrVarNameExpr);
        assign.setLeftHandSide(arrAccessExpr);
        paramOID = (Integer) params[i];
        if (paramOID == null) {
            assign.setRightHandSide(ast.newNullLiteral());
        } else {
            assign.setRightHandSide(ast.newSimpleName(this.oidToVarMapping.get(paramOID)));
        }
        methodBlock.statements().add(assign);
    }
}
Also used : SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayType(org.eclipse.jdt.core.dom.ArrayType) Assignment(org.eclipse.jdt.core.dom.Assignment) ArrayAccess(org.eclipse.jdt.core.dom.ArrayAccess) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ArrayCreation(org.eclipse.jdt.core.dom.ArrayCreation) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement)

Example 12 with ArrayType

use of org.eclipse.jdt.core.dom.ArrayType in project bndtools by bndtools.

the class AbstractBuildErrorDetailsHandler method createMethodMarkerData.

/**
 * Create a marker on a Java Method
 *
 * @param javaProject
 * @param className - the fully qualified class name (e.g java.lang.String)
 * @param methodName
 * @param methodSignature - signatures are in "internal form" e.g. (Ljava.lang.Integer;[Ljava/lang/String;Z)V
 * @param markerAttributes - attributes that should be included in the marker, typically a message. The start and
 *            end points for the marker are added by this method.
 * @param hasResolutions - true if the marker will have resolutions
 * @return Marker Data that can be used to create an {@link IMarker}, or null if no location can be found
 * @throws JavaModelException
 */
public static final MarkerData createMethodMarkerData(IJavaProject javaProject, final String className, final String methodName, final String methodSignature, final Map<String, Object> markerAttributes, boolean hasResolutions) throws JavaModelException {
    final CompilationUnit ast = createAST(javaProject, className);
    if (ast == null)
        return null;
    ast.accept(new ASTVisitor() {

        @Override
        public boolean visit(MethodDeclaration methodDecl) {
            if (matches(ast, methodDecl, methodName, methodSignature)) {
                // Create the marker attribs here
                markerAttributes.put(IMarker.CHAR_START, methodDecl.getStartPosition());
                markerAttributes.put(IMarker.CHAR_END, methodDecl.getStartPosition() + methodDecl.getLength());
            }
            return false;
        }

        private boolean matches(CompilationUnit ast, MethodDeclaration methodDecl, String methodName, String signature) {
            if ("<init>".equals(methodName)) {
                if (!methodDecl.isConstructor()) {
                    return false;
                }
            } else if (!methodDecl.getName().getIdentifier().equals(methodName)) {
                return false;
            }
            return getSignature(ast, methodDecl).equals(signature);
        }

        private String getSignature(CompilationUnit ast, MethodDeclaration methodDecl) {
            StringBuilder signatureBuilder = new StringBuilder("(");
            for (@SuppressWarnings("unchecked") Iterator<SingleVariableDeclaration> it = methodDecl.parameters().iterator(); it.hasNext(); ) {
                SingleVariableDeclaration decl = it.next();
                appendType(ast, signatureBuilder, decl.getType(), decl.getExtraDimensions());
            }
            signatureBuilder.append(")");
            appendType(ast, signatureBuilder, methodDecl.getReturnType2(), 0);
            return signatureBuilder.toString();
        }

        private void appendType(CompilationUnit ast, StringBuilder signatureBuilder, Type typeToAdd, int extraDimensions) {
            for (int i = 0; i < extraDimensions; i++) {
                signatureBuilder.append('[');
            }
            Type rovingType = typeToAdd;
            if (rovingType == null) {
                // A special return type for constructors, nice one Eclipse...
                signatureBuilder.append("V");
            } else {
                if (rovingType.isArrayType()) {
                    ArrayType type = (ArrayType) rovingType;
                    int depth = type.getDimensions();
                    for (int i = 0; i < depth; i++) {
                        signatureBuilder.append('[');
                    }
                    // We still need to add the array component type, which might be primitive or a reference
                    rovingType = type.getElementType();
                }
                // Type erasure means that we should ignore parameters
                if (rovingType.isParameterizedType()) {
                    rovingType = ((ParameterizedType) rovingType).getType();
                }
                if (rovingType.isPrimitiveType()) {
                    PrimitiveType type = (PrimitiveType) rovingType;
                    signatureBuilder.append(PRIMITIVES_TO_SIGNATURES.get(type.getPrimitiveTypeCode()));
                } else if (rovingType.isSimpleType()) {
                    SimpleType type = (SimpleType) rovingType;
                    String name;
                    if (type.getName().isQualifiedName()) {
                        name = type.getName().getFullyQualifiedName();
                    } else {
                        name = getFullyQualifiedNameForSimpleName(ast, type.getName());
                    }
                    name = name.replace('.', '/');
                    signatureBuilder.append("L").append(name).append(";");
                } else if (rovingType.isQualifiedType()) {
                    QualifiedType type = (QualifiedType) rovingType;
                    String name = type.getQualifier().toString().replace('.', '/') + '/' + type.getName().getFullyQualifiedName().replace('.', '/');
                    signatureBuilder.append("L").append(name).append(";");
                } else {
                    throw new IllegalArgumentException("We hit an unknown type " + rovingType);
                }
            }
        }

        private String getFullyQualifiedNameForSimpleName(CompilationUnit ast, Name typeName) {
            String name = typeName.getFullyQualifiedName();
            @SuppressWarnings("unchecked") List<ImportDeclaration> ids = ast.imports();
            for (ImportDeclaration id : ids) {
                if (id.isStatic())
                    continue;
                if (id.isOnDemand()) {
                    String packageName = id.getName().getFullyQualifiedName();
                    try {
                        if (ast.getJavaElement().getJavaProject().findType(packageName + "." + name) != null) {
                            name = packageName + '.' + name;
                        }
                    } catch (JavaModelException e) {
                    }
                } else {
                    String importName = id.getName().getFullyQualifiedName();
                    if (importName.endsWith("." + name)) {
                        name = importName;
                        break;
                    }
                }
            }
            if (name.indexOf('.') < 0) {
                try {
                    if (ast.getJavaElement().getJavaProject().findType(name) == null) {
                        name = "java.lang." + name;
                    }
                } catch (JavaModelException e) {
                }
            }
            return name;
        }
    });
    if (!markerAttributes.containsKey(IMarker.CHAR_START))
        return null;
    return new MarkerData(ast.getJavaElement().getResource(), markerAttributes, hasResolutions);
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) JavaModelException(org.eclipse.jdt.core.JavaModelException) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) IType(org.eclipse.jdt.core.IType) QualifiedType(org.eclipse.jdt.core.dom.QualifiedType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) QualifiedType(org.eclipse.jdt.core.dom.QualifiedType) Iterator(java.util.Iterator) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) List(java.util.List)

Example 13 with ArrayType

use of org.eclipse.jdt.core.dom.ArrayType in project flux by eclipse.

the class ASTNodes method getTypeName.

/**
 * Returns the simple name of the type, followed by array dimensions.
 * Skips qualifiers, type arguments, and type annotations.
 * <p>
 * Does <b>not</b> work for WildcardTypes, etc.!
 *
 * @param type a type that has a simple name
 * @return the simple name, followed by array dimensions
 * @see #getSimpleNameIdentifier(Name)
 * @since 3.10
 */
public static String getTypeName(Type type) {
    final StringBuffer buffer = new StringBuffer();
    ASTVisitor visitor = new ASTVisitor() {

        @Override
        public boolean visit(PrimitiveType node) {
            buffer.append(node.getPrimitiveTypeCode().toString());
            return false;
        }

        @Override
        public boolean visit(SimpleType node) {
            buffer.append(getSimpleNameIdentifier(node.getName()));
            return false;
        }

        @Override
        public boolean visit(QualifiedType node) {
            buffer.append(node.getName().getIdentifier());
            return false;
        }

        @Override
        public boolean visit(NameQualifiedType node) {
            buffer.append(node.getName().getIdentifier());
            return false;
        }

        @Override
        public boolean visit(ParameterizedType node) {
            node.getType().accept(this);
            return false;
        }

        @Override
        public void endVisit(ArrayType node) {
            for (int i = 0; i < node.dimensions().size(); i++) {
                // $NON-NLS-1$
                buffer.append("[]");
            }
        }
    };
    type.accept(visitor);
    return buffer.toString();
}
Also used : ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) QualifiedType(org.eclipse.jdt.core.dom.QualifiedType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor)

Example 14 with ArrayType

use of org.eclipse.jdt.core.dom.ArrayType in project flux by eclipse.

the class ASTNodes method getDimensions.

public static int getDimensions(VariableDeclaration declaration) {
    int dim = declaration.getExtraDimensions();
    if (declaration instanceof VariableDeclarationFragment && declaration.getParent() instanceof LambdaExpression) {
        LambdaExpression lambda = (LambdaExpression) declaration.getParent();
        IMethodBinding methodBinding = lambda.resolveMethodBinding();
        if (methodBinding != null) {
            ITypeBinding[] parameterTypes = methodBinding.getParameterTypes();
            int index = lambda.parameters().indexOf(declaration);
            ITypeBinding typeBinding = parameterTypes[index];
            return typeBinding.getDimensions();
        }
    } else {
        Type type = getType(declaration);
        if (type instanceof ArrayType) {
            dim += ((ArrayType) type).getDimensions();
        }
    }
    return dim;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ArrayType(org.eclipse.jdt.core.dom.ArrayType) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) IType(org.eclipse.jdt.core.IType) UnionType(org.eclipse.jdt.core.dom.UnionType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) QualifiedType(org.eclipse.jdt.core.dom.QualifiedType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression)

Example 15 with ArrayType

use of org.eclipse.jdt.core.dom.ArrayType in project flux by eclipse.

the class StubUtility method getVariableNameSuggestions.

private static String[] getVariableNameSuggestions(int variableKind, IJavaProject project, Type expectedType, Collection<String> excluded, boolean evaluateDefault) {
    int dim = 0;
    if (expectedType.isArrayType()) {
        ArrayType arrayType = (ArrayType) expectedType;
        dim = arrayType.getDimensions();
        expectedType = arrayType.getElementType();
    }
    if (expectedType.isParameterizedType()) {
        expectedType = ((ParameterizedType) expectedType).getType();
    }
    String typeName = ASTNodes.getTypeName(expectedType);
    if (typeName.length() > 0) {
        return getVariableNameSuggestions(variableKind, project, typeName, dim, excluded, evaluateDefault);
    }
    return EMPTY;
}
Also used : ArrayType(org.eclipse.jdt.core.dom.ArrayType)

Aggregations

ArrayType (org.eclipse.jdt.core.dom.ArrayType)39 Type (org.eclipse.jdt.core.dom.Type)27 ParameterizedType (org.eclipse.jdt.core.dom.ParameterizedType)21 PrimitiveType (org.eclipse.jdt.core.dom.PrimitiveType)18 SimpleType (org.eclipse.jdt.core.dom.SimpleType)18 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)15 Dimension (org.eclipse.jdt.core.dom.Dimension)10 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)10 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)10 QualifiedType (org.eclipse.jdt.core.dom.QualifiedType)8 SimpleName (org.eclipse.jdt.core.dom.SimpleName)8 List (java.util.List)7 ASTNode (org.eclipse.jdt.core.dom.ASTNode)7 NameQualifiedType (org.eclipse.jdt.core.dom.NameQualifiedType)7 UnionType (org.eclipse.jdt.core.dom.UnionType)7 IType (org.eclipse.jdt.core.IType)6 ASTVisitor (org.eclipse.jdt.core.dom.ASTVisitor)6 Expression (org.eclipse.jdt.core.dom.Expression)6 LambdaExpression (org.eclipse.jdt.core.dom.LambdaExpression)6 ArrayList (java.util.ArrayList)5