Search in sources :

Example 1 with SingleVariableDeclaration

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

the class StubUtility method getMethodComment.

/*
	 * Don't use this method directly, use CodeGeneration.
	 * This method should work with all AST levels.
	 * @see org.eclipse.jdt.ui.CodeGeneration#getMethodComment(ICompilationUnit, String, MethodDeclaration, boolean, String, String[], String)
	 */
public static String getMethodComment(ICompilationUnit cu, String typeName, MethodDeclaration decl, boolean isDeprecated, String targetName, String targetMethodDeclaringTypeName, String[] targetMethodParameterTypeNames, boolean delegate, String lineDelimiter) throws CoreException {
    boolean needsTarget = targetMethodDeclaringTypeName != null && targetMethodParameterTypeNames != null;
    String templateName = CodeTemplateContextType.METHODCOMMENT_ID;
    if (decl.isConstructor()) {
        templateName = CodeTemplateContextType.CONSTRUCTORCOMMENT_ID;
    } else if (needsTarget) {
        if (delegate)
            templateName = CodeTemplateContextType.DELEGATECOMMENT_ID;
        else
            templateName = CodeTemplateContextType.OVERRIDECOMMENT_ID;
    }
    Template template = getCodeTemplate(templateName, cu.getJavaProject());
    if (template == null) {
        return null;
    }
    CodeTemplateContext context = new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter);
    context.setCompilationUnitVariables(cu);
    context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName);
    context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, decl.getName().getIdentifier());
    if (!decl.isConstructor()) {
        context.setVariable(CodeTemplateContextType.RETURN_TYPE, ASTNodes.asString(getReturnType(decl)));
    }
    if (needsTarget) {
        if (delegate)
            context.setVariable(CodeTemplateContextType.SEE_TO_TARGET_TAG, getSeeTag(targetMethodDeclaringTypeName, targetName, targetMethodParameterTypeNames));
        else
            context.setVariable(CodeTemplateContextType.SEE_TO_OVERRIDDEN_TAG, getSeeTag(targetMethodDeclaringTypeName, targetName, targetMethodParameterTypeNames));
    }
    TemplateBuffer buffer;
    try {
        buffer = context.evaluate(template);
    } catch (BadLocationException e) {
        throw new CoreException(Status.CANCEL_STATUS);
    } catch (TemplateException e) {
        throw new CoreException(Status.CANCEL_STATUS);
    }
    if (buffer == null)
        return null;
    String str = buffer.getString();
    if (Strings.containsOnlyWhitespaces(str)) {
        return null;
    }
    // look if Javadoc tags have to be added
    TemplateVariable position = findVariable(buffer, CodeTemplateContextType.TAGS);
    if (position == null) {
        return str;
    }
    IDocument textBuffer = new Document(str);
    List<TypeParameter> typeParams = shouldGenerateMethodTypeParameterTags(cu.getJavaProject()) ? decl.typeParameters() : Collections.emptyList();
    String[] typeParamNames = new String[typeParams.size()];
    for (int i = 0; i < typeParamNames.length; i++) {
        TypeParameter elem = typeParams.get(i);
        typeParamNames[i] = elem.getName().getIdentifier();
    }
    List<SingleVariableDeclaration> params = decl.parameters();
    String[] paramNames = new String[params.size()];
    for (int i = 0; i < paramNames.length; i++) {
        SingleVariableDeclaration elem = params.get(i);
        paramNames[i] = elem.getName().getIdentifier();
    }
    String[] exceptionNames = getExceptionNames(decl);
    String returnType = null;
    if (!decl.isConstructor()) {
        returnType = ASTNodes.asString(getReturnType(decl));
    }
    int[] tagOffsets = position.getOffsets();
    for (int i = tagOffsets.length - 1; i >= 0; i--) {
        // from last to first
        try {
            insertTag(textBuffer, tagOffsets[i], position.getLength(), paramNames, exceptionNames, returnType, typeParamNames, isDeprecated, lineDelimiter);
        } catch (BadLocationException e) {
            throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
        }
    }
    return textBuffer.get();
}
Also used : TypeParameter(org.eclipse.jdt.core.dom.TypeParameter) ITypeParameter(org.eclipse.jdt.core.ITypeParameter) TemplateException(org.eclipse.jface.text.templates.TemplateException) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) TemplateBuffer(org.eclipse.jface.text.templates.TemplateBuffer) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) Template(org.eclipse.jface.text.templates.Template) CodeTemplateContext(org.eclipse.jdt.internal.corext.template.java.CodeTemplateContext) CoreException(org.eclipse.core.runtime.CoreException) TemplateVariable(org.eclipse.jface.text.templates.TemplateVariable) BadLocationException(org.eclipse.jface.text.BadLocationException) IDocument(org.eclipse.jface.text.IDocument)

Example 2 with SingleVariableDeclaration

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

the class StubUtility2 method createConstructorStub.

public static MethodDeclaration createConstructorStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, ITypeBinding typeBinding, IMethodBinding superConstructor, IVariableBinding[] variableBindings, int modifiers, 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(typeBinding.getName()));
    decl.setConstructor(true);
    List<SingleVariableDeclaration> parameters = decl.parameters();
    if (superConstructor != null) {
        createTypeParameters(imports, context, ast, superConstructor, decl);
        createParameters(unit.getJavaProject(), imports, context, ast, superConstructor, null, decl);
        createThrownExceptions(decl, superConstructor, imports, context, ast);
    }
    Block body = ast.newBlock();
    decl.setBody(body);
    String delimiter = StubUtility.getLineDelimiterUsed(unit);
    if (superConstructor != null) {
        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()));
        }
        body.statements().add(invocation);
    }
    List<String> prohibited = new ArrayList<String>();
    for (final Iterator<SingleVariableDeclaration> iterator = parameters.iterator(); iterator.hasNext(); ) prohibited.add(iterator.next().getName().getIdentifier());
    String param = null;
    List<String> list = new ArrayList<String>(prohibited);
    String[] excluded = null;
    for (int i = 0; i < variableBindings.length; i++) {
        SingleVariableDeclaration var = ast.newSingleVariableDeclaration();
        var.setType(imports.addImport(variableBindings[i].getType(), ast, context));
        excluded = new String[list.size()];
        list.toArray(excluded);
        param = suggestParameterName(unit, variableBindings[i], excluded);
        list.add(param);
        var.setName(ast.newSimpleName(param));
        parameters.add(var);
    }
    list = new ArrayList<String>(prohibited);
    for (int i = 0; i < variableBindings.length; i++) {
        excluded = new String[list.size()];
        list.toArray(excluded);
        final String paramName = suggestParameterName(unit, variableBindings[i], excluded);
        list.add(paramName);
        final String fieldName = variableBindings[i].getName();
        Expression expression = null;
        if (paramName.equals(fieldName) || settings.useKeywordThis) {
            FieldAccess access = ast.newFieldAccess();
            access.setExpression(ast.newThisExpression());
            access.setName(ast.newSimpleName(fieldName));
            expression = access;
        } else
            expression = ast.newSimpleName(fieldName);
        Assignment assignment = ast.newAssignment();
        assignment.setLeftHandSide(expression);
        assignment.setRightHandSide(ast.newSimpleName(paramName));
        assignment.setOperator(Assignment.Operator.ASSIGN);
        body.statements().add(ast.newExpressionStatement(assignment));
    }
    if (settings != null && settings.createComments) {
        String string = CodeGeneration.getMethodComment(unit, typeBinding.getName(), decl, superConstructor, 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) ArrayList(java.util.ArrayList) Javadoc(org.eclipse.jdt.core.dom.Javadoc) Assignment(org.eclipse.jdt.core.dom.Assignment) Expression(org.eclipse.jdt.core.dom.Expression) Block(org.eclipse.jdt.core.dom.Block) SuperConstructorInvocation(org.eclipse.jdt.core.dom.SuperConstructorInvocation) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess)

Example 3 with SingleVariableDeclaration

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

the class UnresolvedElementsSubProcessor method addEnhancedForWithoutTypeProposals.

private static void addEnhancedForWithoutTypeProposals(ICompilationUnit cu, ASTNode selectedNode, Collection<ICommandAccess> proposals) {
    if (selectedNode instanceof SimpleName && (selectedNode.getLocationInParent() == SimpleType.NAME_PROPERTY || selectedNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY)) {
        ASTNode type = selectedNode.getParent();
        if (type.getLocationInParent() == SingleVariableDeclaration.TYPE_PROPERTY) {
            SingleVariableDeclaration svd = (SingleVariableDeclaration) type.getParent();
            if (svd.getLocationInParent() == EnhancedForStatement.PARAMETER_PROPERTY) {
                if (svd.getName().getLength() == 0) {
                    SimpleName simpleName = (SimpleName) selectedNode;
                    String name = simpleName.getIdentifier();
                    int relevance = StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7;
                    String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_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));
                }
            }
        }
    }
}
Also used : SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ASTNode(org.eclipse.jdt.core.dom.ASTNode) NewVariableCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.NewVariableCorrectionProposal) Image(org.eclipse.swt.graphics.Image)

Example 4 with SingleVariableDeclaration

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

the class SuppressWarningsSubProcessor method addSuppressWarningsProposalIfPossible.

/**
	 * Adds a SuppressWarnings proposal if possible and returns whether parent nodes should be processed or not (and with what relevance).
	 *
	 * @param cu the compilation unit
	 * @param node the node on which to add a SuppressWarning token
	 * @param warningToken the warning token to add
	 * @param relevance the proposal's relevance
	 * @param proposals collector to which the proposal should be added
	 * @return <code>0</code> if no further proposals should be added to parent nodes, or the relevance of the next proposal
	 *
	 * @since 3.6
	 */
private static int addSuppressWarningsProposalIfPossible(ICompilationUnit cu, ASTNode node, String warningToken, int relevance, Collection<ICommandAccess> proposals) {
    ChildListPropertyDescriptor property;
    String name;
    boolean isLocalVariable = false;
    switch(node.getNodeType()) {
        case ASTNode.SINGLE_VARIABLE_DECLARATION:
            property = SingleVariableDeclaration.MODIFIERS2_PROPERTY;
            name = ((SingleVariableDeclaration) node).getName().getIdentifier();
            isLocalVariable = true;
            break;
        case ASTNode.VARIABLE_DECLARATION_STATEMENT:
            property = VariableDeclarationStatement.MODIFIERS2_PROPERTY;
            name = getFirstFragmentName(((VariableDeclarationStatement) node).fragments());
            isLocalVariable = true;
            break;
        case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
            property = VariableDeclarationExpression.MODIFIERS2_PROPERTY;
            name = getFirstFragmentName(((VariableDeclarationExpression) node).fragments());
            isLocalVariable = true;
            break;
        case ASTNode.TYPE_DECLARATION:
            property = TypeDeclaration.MODIFIERS2_PROPERTY;
            name = ((TypeDeclaration) node).getName().getIdentifier();
            break;
        case ASTNode.ANNOTATION_TYPE_DECLARATION:
            property = AnnotationTypeDeclaration.MODIFIERS2_PROPERTY;
            name = ((AnnotationTypeDeclaration) node).getName().getIdentifier();
            break;
        case ASTNode.ENUM_DECLARATION:
            property = EnumDeclaration.MODIFIERS2_PROPERTY;
            name = ((EnumDeclaration) node).getName().getIdentifier();
            break;
        case ASTNode.FIELD_DECLARATION:
            property = FieldDeclaration.MODIFIERS2_PROPERTY;
            name = getFirstFragmentName(((FieldDeclaration) node).fragments());
            break;
        // case ASTNode.INITIALIZER: not used, because Initializer cannot have annotations
        case ASTNode.METHOD_DECLARATION:
            property = MethodDeclaration.MODIFIERS2_PROPERTY;
            //$NON-NLS-1$
            name = ((MethodDeclaration) node).getName().getIdentifier() + "()";
            break;
        case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION:
            property = AnnotationTypeMemberDeclaration.MODIFIERS2_PROPERTY;
            //$NON-NLS-1$
            name = ((AnnotationTypeMemberDeclaration) node).getName().getIdentifier() + "()";
            break;
        case ASTNode.ENUM_CONSTANT_DECLARATION:
            property = EnumConstantDeclaration.MODIFIERS2_PROPERTY;
            name = ((EnumConstantDeclaration) node).getName().getIdentifier();
            break;
        default:
            return relevance;
    }
    String label = Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_suppress_warnings_label, new String[] { warningToken, BasicElementLabels.getJavaElementName(name) });
    ASTRewriteCorrectionProposal proposal = new SuppressWarningsProposal(warningToken, label, cu, node, property, relevance);
    proposals.add(proposal);
    return isLocalVariable ? relevance - 1 : 0;
}
Also used : SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) EnumDeclaration(org.eclipse.jdt.core.dom.EnumDeclaration) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) EnumConstantDeclaration(org.eclipse.jdt.core.dom.EnumConstantDeclaration) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration)

Example 5 with SingleVariableDeclaration

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

the class NewDefiningMethodProposal method addNewParameters.

/* (non-Javadoc)
	 * @see org.eclipse.jdt.internal.ui.text.correction.proposals.AbstractMethodCorrectionProposal#addNewParameters(org.eclipse.jdt.core
	 * .dom.rewrite.ASTRewrite, java.util.List, java.util.List)
	 */
@Override
protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params) throws CoreException {
    AST ast = rewrite.getAST();
    ImportRewrite importRewrite = getImportRewrite();
    ITypeBinding[] bindings = fMethod.getParameterTypes();
    IJavaProject project = getCompilationUnit().getJavaProject();
    String[][] paramNames = StubUtility.suggestArgumentNamesWithProposals(project, fParamNames);
    for (int i = 0; i < bindings.length; i++) {
        ITypeBinding curr = bindings[i];
        String[] proposedNames = paramNames[i];
        SingleVariableDeclaration newParam = ast.newSingleVariableDeclaration();
        newParam.setType(importRewrite.addImport(curr, ast));
        newParam.setName(ast.newSimpleName(proposedNames[0]));
        params.add(newParam);
        //$NON-NLS-1$
        String groupId = "arg_name_" + i;
        addLinkedPosition(rewrite.track(newParam.getName()), false, groupId);
        for (int k = 0; k < proposedNames.length; k++) {
            addLinkedPositionProposal(groupId, proposedNames[k], null);
        }
    }
}
Also used : AST(org.eclipse.jdt.core.dom.AST) IJavaProject(org.eclipse.jdt.core.IJavaProject) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding)

Aggregations

SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)121 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)41 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)37 Type (org.eclipse.jdt.core.dom.Type)37 ASTNode (org.eclipse.jdt.core.dom.ASTNode)33 Block (org.eclipse.jdt.core.dom.Block)33 AST (org.eclipse.jdt.core.dom.AST)32 SimpleName (org.eclipse.jdt.core.dom.SimpleName)27 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)27 ArrayList (java.util.ArrayList)26 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)25 List (java.util.List)24 Expression (org.eclipse.jdt.core.dom.Expression)22 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)18 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)18 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)17 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