Search in sources :

Example 91 with SingleVariableDeclaration

use of org.eclipse.jdt.core.dom.SingleVariableDeclaration in project che by eclipse.

the class StubUtility2 method createParameters.

private static List<SingleVariableDeclaration> createParameters(IJavaProject project, ImportRewrite imports, ImportRewriteContext context, AST ast, IMethodBinding binding, String[] paramNames, MethodDeclaration decl) {
    boolean is50OrHigher = JavaModelUtil.is50OrHigher(project);
    List<SingleVariableDeclaration> parameters = decl.parameters();
    ITypeBinding[] params = binding.getParameterTypes();
    if (paramNames == null || paramNames.length < params.length) {
        paramNames = StubUtility.suggestArgumentNames(project, binding);
    }
    for (int i = 0; i < params.length; i++) {
        SingleVariableDeclaration var = ast.newSingleVariableDeclaration();
        ITypeBinding type = params[i];
        if (type.isWildcardType()) {
            ITypeBinding bound = type.getBound();
            type = (bound != null) ? bound : type.getErasure();
        }
        if (!is50OrHigher) {
            type = type.getErasure();
            var.setType(imports.addImport(type, ast, context));
        } else if (binding.isVarargs() && type.isArray() && i == params.length - 1) {
            var.setVarargs(true);
            /*
				 * Varargs annotations are special.
				 * Example:
				 *     foo(@O Object @A [] @B ... arg)
				 * => @B is not an annotation on the array dimension that constitutes the vararg.
				 * It's the type annotation of the *innermost* array dimension.
				 */
            int dimensions = type.getDimensions();
            @SuppressWarnings("unchecked") List<Annotation>[] dimensionAnnotations = (List<Annotation>[]) new List<?>[dimensions];
            for (int dim = 0; dim < dimensions; dim++) {
                dimensionAnnotations[dim] = new ArrayList<Annotation>();
                for (IAnnotationBinding annotation : type.getTypeAnnotations()) {
                    dimensionAnnotations[dim].add(imports.addAnnotation(annotation, ast, context));
                }
                type = type.getComponentType();
            }
            Type elementType = imports.addImport(type, ast, context);
            if (dimensions == 1) {
                var.setType(elementType);
            } else {
                ArrayType arrayType = ast.newArrayType(elementType, dimensions - 1);
                List<Dimension> dimensionNodes = arrayType.dimensions();
                for (int dim = 0; dim < dimensions - 1; dim++) {
                    // all except the innermost dimension
                    Dimension dimension = dimensionNodes.get(dim);
                    dimension.annotations().addAll(dimensionAnnotations[dim]);
                }
                var.setType(arrayType);
            }
            List<Annotation> varargTypeAnnotations = dimensionAnnotations[dimensions - 1];
            var.varargsAnnotations().addAll(varargTypeAnnotations);
        } else {
            var.setType(imports.addImport(type, ast, context));
        }
        var.setName(ast.newSimpleName(paramNames[i]));
        IAnnotationBinding[] annotations = binding.getParameterAnnotations(i);
        for (IAnnotationBinding annotation : annotations) {
            if (StubUtility2.isCopyOnInheritAnnotation(annotation.getAnnotationType(), project))
                var.modifiers().add(imports.addAnnotation(annotation, ast, context));
        }
        parameters.add(var);
    }
    return parameters;
}
Also used : SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ArrayList(java.util.ArrayList) Dimension(org.eclipse.jdt.core.dom.Dimension) Annotation(org.eclipse.jdt.core.dom.Annotation) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) IAnnotationBinding(org.eclipse.jdt.core.dom.IAnnotationBinding) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) List(java.util.List) ArrayList(java.util.ArrayList)

Example 92 with SingleVariableDeclaration

use of org.eclipse.jdt.core.dom.SingleVariableDeclaration in project che by eclipse.

the class StubUtility2 method createConstructorStub.

/* This method should work with all AST levels. */
public static MethodDeclaration createConstructorStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, IMethodBinding binding, String type, int modifiers, boolean omitSuperForDefConst, boolean todo, CodeGenerationSettings settings) throws CoreException {
    AST ast = rewrite.getAST();
    MethodDeclaration decl = ast.newMethodDeclaration();
    decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers & ~Modifier.ABSTRACT & ~Modifier.NATIVE));
    decl.setName(ast.newSimpleName(type));
    decl.setConstructor(true);
    createTypeParameters(imports, context, ast, binding, decl);
    List<SingleVariableDeclaration> parameters = createParameters(unit.getJavaProject(), imports, context, ast, binding, null, decl);
    createThrownExceptions(decl, binding, imports, context, ast);
    Block body = ast.newBlock();
    decl.setBody(body);
    String delimiter = StubUtility.getLineDelimiterUsed(unit);
    //$NON-NLS-1$
    String bodyStatement = "";
    if (!omitSuperForDefConst || !parameters.isEmpty()) {
        SuperConstructorInvocation invocation = ast.newSuperConstructorInvocation();
        SingleVariableDeclaration varDecl = null;
        for (Iterator<SingleVariableDeclaration> iterator = parameters.iterator(); iterator.hasNext(); ) {
            varDecl = iterator.next();
            invocation.arguments().add(ast.newSimpleName(varDecl.getName().getIdentifier()));
        }
        bodyStatement = ASTNodes.asFormattedString(invocation, 0, delimiter, unit.getJavaProject().getOptions(true));
    }
    if (todo) {
        String placeHolder = CodeGeneration.getMethodBodyContent(unit, type, binding.getName(), true, bodyStatement, delimiter);
        if (placeHolder != null) {
            ReturnStatement todoNode = (ReturnStatement) rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
            body.statements().add(todoNode);
        }
    } else {
        ReturnStatement statementNode = (ReturnStatement) rewrite.createStringPlaceholder(bodyStatement, ASTNode.RETURN_STATEMENT);
        body.statements().add(statementNode);
    }
    if (settings != null && settings.createComments) {
        String string = CodeGeneration.getMethodComment(unit, type, decl, binding, delimiter);
        if (string != null) {
            Javadoc javadoc = (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
            decl.setJavadoc(javadoc);
        }
    }
    return decl;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) Block(org.eclipse.jdt.core.dom.Block) Javadoc(org.eclipse.jdt.core.dom.Javadoc) SuperConstructorInvocation(org.eclipse.jdt.core.dom.SuperConstructorInvocation)

Example 93 with SingleVariableDeclaration

use of org.eclipse.jdt.core.dom.SingleVariableDeclaration in project che by eclipse.

the class StubUtility2 method createImplementationStub.

public static MethodDeclaration createImplementationStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, IMethodBinding binding, String[] parameterNames, String type, CodeGenerationSettings settings, boolean inInterface) throws CoreException {
    Assert.isNotNull(imports);
    Assert.isNotNull(rewrite);
    AST ast = rewrite.getAST();
    MethodDeclaration decl = ast.newMethodDeclaration();
    decl.modifiers().addAll(getImplementationModifiers(ast, binding, inInterface, imports, context));
    decl.setName(ast.newSimpleName(binding.getName()));
    decl.setConstructor(false);
    ITypeBinding bindingReturnType = binding.getReturnType();
    if (bindingReturnType.isWildcardType()) {
        ITypeBinding bound = bindingReturnType.getBound();
        bindingReturnType = (bound != null) ? bound : bindingReturnType.getErasure();
    }
    IJavaProject javaProject = unit.getJavaProject();
    if (JavaModelUtil.is50OrHigher(javaProject)) {
        createTypeParameters(imports, context, ast, binding, decl);
    } else {
        bindingReturnType = bindingReturnType.getErasure();
    }
    decl.setReturnType2(imports.addImport(bindingReturnType, ast, context));
    List<SingleVariableDeclaration> parameters = createParameters(javaProject, imports, context, ast, binding, parameterNames, decl);
    createThrownExceptions(decl, binding, imports, context, ast);
    String delimiter = unit.findRecommendedLineSeparator();
    int modifiers = binding.getModifiers();
    if (!(inInterface && Modifier.isAbstract(modifiers))) {
        // generate a method body
        Map<String, String> options = javaProject.getOptions(true);
        Block body = ast.newBlock();
        decl.setBody(body);
        //$NON-NLS-1$
        String bodyStatement = "";
        if (Modifier.isAbstract(modifiers)) {
            Expression expression = ASTNodeFactory.newDefaultExpression(ast, decl.getReturnType2(), decl.getExtraDimensions());
            if (expression != null) {
                ReturnStatement returnStatement = ast.newReturnStatement();
                returnStatement.setExpression(expression);
                bodyStatement = ASTNodes.asFormattedString(returnStatement, 0, delimiter, options);
            }
        } else {
            SuperMethodInvocation invocation = ast.newSuperMethodInvocation();
            ITypeBinding declaringType = binding.getDeclaringClass();
            if (declaringType.isInterface()) {
                String qualifier = imports.addImport(declaringType.getErasure(), context);
                Name name = ASTNodeFactory.newName(ast, qualifier);
                invocation.setQualifier(name);
            }
            invocation.setName(ast.newSimpleName(binding.getName()));
            SingleVariableDeclaration varDecl = null;
            for (Iterator<SingleVariableDeclaration> iterator = parameters.iterator(); iterator.hasNext(); ) {
                varDecl = iterator.next();
                invocation.arguments().add(ast.newSimpleName(varDecl.getName().getIdentifier()));
            }
            Expression expression = invocation;
            Type returnType = decl.getReturnType2();
            if (returnType instanceof PrimitiveType && ((PrimitiveType) returnType).getPrimitiveTypeCode().equals(PrimitiveType.VOID)) {
                bodyStatement = ASTNodes.asFormattedString(ast.newExpressionStatement(expression), 0, delimiter, options);
            } else {
                ReturnStatement returnStatement = ast.newReturnStatement();
                returnStatement.setExpression(expression);
                bodyStatement = ASTNodes.asFormattedString(returnStatement, 0, delimiter, options);
            }
        }
        String placeHolder = CodeGeneration.getMethodBodyContent(unit, type, binding.getName(), false, bodyStatement, delimiter);
        if (placeHolder != null) {
            ReturnStatement todoNode = (ReturnStatement) rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
            body.statements().add(todoNode);
        }
    }
    if (settings != null && settings.createComments) {
        String string = CodeGeneration.getMethodComment(unit, type, decl, binding, delimiter);
        if (string != null) {
            Javadoc javadoc = (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
            decl.setJavadoc(javadoc);
        }
    }
    if (settings != null && settings.overrideAnnotation && JavaModelUtil.is50OrHigher(javaProject)) {
        addOverrideAnnotation(javaProject, rewrite, decl, binding);
    }
    return decl;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) Javadoc(org.eclipse.jdt.core.dom.Javadoc) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) Name(org.eclipse.jdt.core.dom.Name) ArrayType(org.eclipse.jdt.core.dom.ArrayType) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) IJavaProject(org.eclipse.jdt.core.IJavaProject) Expression(org.eclipse.jdt.core.dom.Expression) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) Block(org.eclipse.jdt.core.dom.Block) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType)

Example 94 with SingleVariableDeclaration

use of org.eclipse.jdt.core.dom.SingleVariableDeclaration in project che by eclipse.

the class TypeMismatchSubProcessor method addTypeMismatchInForEachProposals.

public static void addTypeMismatchInForEachProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    if (selectedNode == null || selectedNode.getLocationInParent() != EnhancedForStatement.EXPRESSION_PROPERTY) {
        return;
    }
    EnhancedForStatement forStatement = (EnhancedForStatement) selectedNode.getParent();
    ITypeBinding expressionBinding = forStatement.getExpression().resolveTypeBinding();
    if (expressionBinding == null) {
        return;
    }
    ITypeBinding expectedBinding;
    if (expressionBinding.isArray()) {
        expectedBinding = expressionBinding.getComponentType();
    } else {
        //$NON-NLS-1$
        IMethodBinding iteratorMethod = Bindings.findMethodInHierarchy(expressionBinding, "iterator", new String[0]);
        if (iteratorMethod == null) {
            return;
        }
        ITypeBinding[] typeArguments = iteratorMethod.getReturnType().getTypeArguments();
        if (typeArguments.length != 1) {
            return;
        }
        expectedBinding = typeArguments[0];
    }
    AST ast = astRoot.getAST();
    expectedBinding = Bindings.normalizeForDeclarationUse(expectedBinding, ast);
    SingleVariableDeclaration parameter = forStatement.getParameter();
    ICompilationUnit cu = context.getCompilationUnit();
    if (parameter.getName().getLength() == 0) {
        SimpleName simpleName = null;
        if (parameter.getType() instanceof SimpleType) {
            SimpleType type = (SimpleType) parameter.getType();
            if (type.getName() instanceof SimpleName) {
                simpleName = (SimpleName) type.getName();
            }
        } else if (parameter.getType() instanceof NameQualifiedType) {
            simpleName = ((NameQualifiedType) parameter.getType()).getName();
        }
        if (simpleName != null) {
            String name = simpleName.getIdentifier();
            int relevance = StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7;
            String label = Messages.format(CorrectionMessages.TypeMismatchSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name));
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
            proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL, simpleName, null, relevance, image));
            return;
        }
    }
    String label = Messages.format(CorrectionMessages.TypeMismatchSubProcessor_incompatible_for_each_type_description, new String[] { BasicElementLabels.getJavaElementName(parameter.getName().getIdentifier()), BindingLabelProvider.getBindingLabel(expectedBinding, BindingLabelProvider.DEFAULT_TEXTFLAGS) });
    Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
    ASTRewrite rewrite = ASTRewrite.create(ast);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.INCOMPATIBLE_FOREACH_TYPE, image);
    ImportRewrite importRewrite = proposal.createImportRewrite(astRoot);
    ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(selectedNode), importRewrite);
    Type newType = importRewrite.addImport(expectedBinding, ast, importRewriteContext);
    rewrite.replace(parameter.getType(), newType, null);
    proposals.add(proposal);
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Image(org.eclipse.swt.graphics.Image) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) SimpleType(org.eclipse.jdt.core.dom.SimpleType) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) NewVariableCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.NewVariableCorrectionProposal) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType)

Example 95 with SingleVariableDeclaration

use of org.eclipse.jdt.core.dom.SingleVariableDeclaration in project che by eclipse.

the class AssignToVariableAssistProposal method findAssignmentInsertIndex.

private int findAssignmentInsertIndex(List<Statement> statements) {
    HashSet<String> paramsBefore = new HashSet<String>();
    List<SingleVariableDeclaration> params = ((MethodDeclaration) fNodeToAssign.getParent()).parameters();
    for (int i = 0; i < params.size() && (params.get(i) != fNodeToAssign); i++) {
        SingleVariableDeclaration decl = params.get(i);
        paramsBefore.add(decl.getName().getIdentifier());
    }
    int i = 0;
    for (i = 0; i < statements.size(); i++) {
        Statement curr = statements.get(i);
        switch(curr.getNodeType()) {
            case ASTNode.CONSTRUCTOR_INVOCATION:
            case ASTNode.SUPER_CONSTRUCTOR_INVOCATION:
                break;
            case ASTNode.EXPRESSION_STATEMENT:
                Expression expr = ((ExpressionStatement) curr).getExpression();
                if (expr instanceof Assignment) {
                    Assignment assignment = (Assignment) expr;
                    Expression rightHand = assignment.getRightHandSide();
                    if (rightHand instanceof SimpleName && paramsBefore.contains(((SimpleName) rightHand).getIdentifier())) {
                        IVariableBinding binding = Bindings.getAssignedVariable(assignment);
                        if (binding == null || binding.isField()) {
                            break;
                        }
                    }
                }
                return i;
            default:
                return i;
        }
    }
    return i;
}
Also used : MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) Statement(org.eclipse.jdt.core.dom.Statement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) Assignment(org.eclipse.jdt.core.dom.Assignment) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) HashSet(java.util.HashSet)

Aggregations

SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)124 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)41 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)39 Type (org.eclipse.jdt.core.dom.Type)37 Block (org.eclipse.jdt.core.dom.Block)35 ASTNode (org.eclipse.jdt.core.dom.ASTNode)33 AST (org.eclipse.jdt.core.dom.AST)32 ArrayList (java.util.ArrayList)29 List (java.util.List)27 SimpleName (org.eclipse.jdt.core.dom.SimpleName)27 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)27 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)26 Expression (org.eclipse.jdt.core.dom.Expression)22 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)20 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)18 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)18 PrimitiveType (org.eclipse.jdt.core.dom.PrimitiveType)17 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)16 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)16 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)16