Search in sources :

Example 6 with AbstractTypeDeclaration

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

the class ExtractMethodRefactoring method getRefactoringDescriptor.

private ExtractMethodDescriptor getRefactoringDescriptor() {
    final Map<String, String> arguments = new HashMap<String, String>();
    String project = null;
    IJavaProject javaProject = fCUnit.getJavaProject();
    if (javaProject != null)
        project = javaProject.getElementName();
    ITypeBinding type = null;
    if (fDestination instanceof AbstractTypeDeclaration) {
        final AbstractTypeDeclaration decl = (AbstractTypeDeclaration) fDestination;
        type = decl.resolveBinding();
    } else if (fDestination instanceof AnonymousClassDeclaration) {
        final AnonymousClassDeclaration decl = (AnonymousClassDeclaration) fDestination;
        type = decl.resolveBinding();
    }
    IMethodBinding method = null;
    final BodyDeclaration enclosing = fAnalyzer.getEnclosingBodyDeclaration();
    if (enclosing instanceof MethodDeclaration) {
        final MethodDeclaration node = (MethodDeclaration) enclosing;
        method = node.resolveBinding();
    }
    final int flags = RefactoringDescriptor.STRUCTURAL_CHANGE | JavaRefactoringDescriptor.JAR_REFACTORING | JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
    final String description = Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_descriptor_description_short, BasicElementLabels.getJavaElementName(fMethodName));
    final String label = method != null ? BindingLabelProvider.getBindingLabel(method, JavaElementLabels.ALL_FULLY_QUALIFIED) : '{' + JavaElementLabels.ELLIPSIS_STRING + '}';
    final String header = Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_descriptor_description, new String[] { BasicElementLabels.getJavaElementName(getSignature()), label, BindingLabelProvider.getBindingLabel(type, JavaElementLabels.ALL_FULLY_QUALIFIED) });
    final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment(project, this, header);
    comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_name_pattern, BasicElementLabels.getJavaElementName(fMethodName)));
    comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_destination_pattern, BindingLabelProvider.getBindingLabel(type, JavaElementLabels.ALL_FULLY_QUALIFIED)));
    String visibility = JdtFlags.getVisibilityString(fVisibility);
    if (//$NON-NLS-1$
    "".equals(visibility))
        visibility = RefactoringCoreMessages.ExtractMethodRefactoring_default_visibility;
    comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_visibility_pattern, visibility));
    if (fThrowRuntimeExceptions)
        comment.addSetting(RefactoringCoreMessages.ExtractMethodRefactoring_declare_thrown_exceptions);
    if (fReplaceDuplicates)
        comment.addSetting(RefactoringCoreMessages.ExtractMethodRefactoring_replace_occurrences);
    if (fGenerateJavadoc)
        comment.addSetting(RefactoringCoreMessages.ExtractMethodRefactoring_generate_comment);
    final ExtractMethodDescriptor descriptor = RefactoringSignatureDescriptorFactory.createExtractMethodDescriptor(project, description, comment.asString(), arguments, flags);
    arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fCUnit));
    arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME, fMethodName);
    //$NON-NLS-1$
    arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString());
    arguments.put(ATTRIBUTE_VISIBILITY, new Integer(fVisibility).toString());
    arguments.put(ATTRIBUTE_DESTINATION, new Integer(fDestinationIndex).toString());
    arguments.put(ATTRIBUTE_EXCEPTIONS, Boolean.valueOf(fThrowRuntimeExceptions).toString());
    arguments.put(ATTRIBUTE_COMMENTS, Boolean.valueOf(fGenerateJavadoc).toString());
    arguments.put(ATTRIBUTE_REPLACE, Boolean.valueOf(fReplaceDuplicates).toString());
    return descriptor;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) HashMap(java.util.HashMap) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) AnonymousClassDeclaration(org.eclipse.jdt.core.dom.AnonymousClassDeclaration) JDTRefactoringDescriptorComment(org.eclipse.jdt.internal.corext.refactoring.JDTRefactoringDescriptorComment) ExtractMethodDescriptor(org.eclipse.jdt.core.refactoring.descriptors.ExtractMethodDescriptor) IJavaProject(org.eclipse.jdt.core.IJavaProject) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 7 with AbstractTypeDeclaration

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

the class IntroduceIndirectionRefactoring method createIntermediaryMethod.

private void createIntermediaryMethod() throws CoreException {
    CompilationUnitRewrite imRewrite = getCachedCURewrite(fIntermediaryType.getCompilationUnit());
    AST ast = imRewrite.getAST();
    MethodDeclaration intermediary = ast.newMethodDeclaration();
    // Intermediary class is non-anonymous
    AbstractTypeDeclaration type = (AbstractTypeDeclaration) typeToDeclaration(fIntermediaryType, imRewrite.getRoot());
    // Name
    intermediary.setName(ast.newSimpleName(fIntermediaryMethodName));
    // Flags
    List<IExtendedModifier> modifiers = intermediary.modifiers();
    if (!fIntermediaryType.isInterface()) {
        modifiers.add(imRewrite.getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD));
    }
    modifiers.add(imRewrite.getAST().newModifier(ModifierKeyword.STATIC_KEYWORD));
    // Parameters
    String targetParameterName = StubUtility.suggestArgumentName(getProject(), fIntermediaryFirstParameterType.getName(), fTargetMethod.getParameterNames());
    ImportRewriteContext context = new ContextSensitiveImportRewriteContext(type, imRewrite.getImportRewrite());
    if (!isStaticTarget()) {
        // Add first param
        SingleVariableDeclaration parameter = imRewrite.getAST().newSingleVariableDeclaration();
        Type t = imRewrite.getImportRewrite().addImport(fIntermediaryFirstParameterType, imRewrite.getAST(), context);
        if (fIntermediaryFirstParameterType.isGenericType()) {
            ParameterizedType parameterized = imRewrite.getAST().newParameterizedType(t);
            ITypeBinding[] typeParameters = fIntermediaryFirstParameterType.getTypeParameters();
            for (int i = 0; i < typeParameters.length; i++) parameterized.typeArguments().add(imRewrite.getImportRewrite().addImport(typeParameters[i], imRewrite.getAST()));
            t = parameterized;
        }
        parameter.setType(t);
        parameter.setName(imRewrite.getAST().newSimpleName(targetParameterName));
        intermediary.parameters().add(parameter);
    }
    // Add other params
    copyArguments(intermediary, imRewrite);
    // Add type parameters of declaring type (and enclosing types)
    if (!isStaticTarget() && fIntermediaryFirstParameterType.isGenericType())
        addTypeParameters(imRewrite, intermediary.typeParameters(), fIntermediaryFirstParameterType);
    // Add type params of method
    copyTypeParameters(intermediary, imRewrite);
    // Return type
    intermediary.setReturnType2(imRewrite.getImportRewrite().addImport(fTargetMethodBinding.getReturnType(), ast, context));
    // Exceptions
    copyExceptions(intermediary, imRewrite);
    // Body
    MethodInvocation invocation = imRewrite.getAST().newMethodInvocation();
    invocation.setName(imRewrite.getAST().newSimpleName(fTargetMethod.getElementName()));
    if (isStaticTarget()) {
        Type importedType = imRewrite.getImportRewrite().addImport(fTargetMethodBinding.getDeclaringClass(), ast, context);
        invocation.setExpression(ASTNodeFactory.newName(ast, ASTNodes.asString(importedType)));
    } else {
        invocation.setExpression(imRewrite.getAST().newSimpleName(targetParameterName));
    }
    copyInvocationParameters(invocation, ast);
    Statement call = encapsulateInvocation(intermediary, invocation);
    final Block body = imRewrite.getAST().newBlock();
    body.statements().add(call);
    intermediary.setBody(body);
    // method comment
    ICompilationUnit targetCU = imRewrite.getCu();
    if (StubUtility.doAddComments(targetCU.getJavaProject())) {
        String comment = CodeGeneration.getMethodComment(targetCU, getIntermediaryTypeName(), intermediary, null, StubUtility.getLineDelimiterUsed(targetCU));
        if (comment != null) {
            Javadoc javadoc = (Javadoc) imRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC);
            intermediary.setJavadoc(javadoc);
        }
    }
    // Add the completed method to the intermediary type:
    ChildListPropertyDescriptor typeBodyDeclarationsProperty = typeToBodyDeclarationProperty(fIntermediaryType, imRewrite.getRoot());
    ListRewrite bodyDeclarationsListRewrite = imRewrite.getASTRewrite().getListRewrite(type, typeBodyDeclarationsProperty);
    bodyDeclarationsListRewrite.insertAt(intermediary, ASTNodes.getInsertionIndex(intermediary, type.bodyDeclarations()), imRewrite.createGroupDescription(RefactoringCoreMessages.IntroduceIndirectionRefactoring_group_description_create_new_method));
}
Also used : CompilationUnitRewrite(org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) 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) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) Javadoc(org.eclipse.jdt.core.dom.Javadoc) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) IType(org.eclipse.jdt.core.IType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) 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) Block(org.eclipse.jdt.core.dom.Block) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 8 with AbstractTypeDeclaration

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

the class IntroduceFactoryRefactoring method rewriteFactoryMethodCall.

/**
	 * Updates the constructor call.
	 *
	 * @param ctorCall the ClassInstanceCreation to be marked as replaced
	 * @param unitRewriter the AST rewriter
	 * @param gd the edit group to use
	 */
private void rewriteFactoryMethodCall(ClassInstanceCreation ctorCall, ASTRewrite unitRewriter, TextEditGroup gd) {
    AST ast = unitRewriter.getAST();
    MethodInvocation factoryMethodCall = ast.newMethodInvocation();
    ASTNode ctorCallParent = ctorCall.getParent();
    StructuralPropertyDescriptor ctorCallLocation = ctorCall.getLocationInParent();
    if (ctorCallLocation instanceof ChildListPropertyDescriptor) {
        ListRewrite ctorCallParentListRewrite = unitRewriter.getListRewrite(ctorCallParent, (ChildListPropertyDescriptor) ctorCallLocation);
        int index = ctorCallParentListRewrite.getOriginalList().indexOf(ctorCall);
        ctorCall = (ClassInstanceCreation) ctorCallParentListRewrite.getRewrittenList().get(index);
    } else {
        ctorCall = (ClassInstanceCreation) unitRewriter.get(ctorCallParent, ctorCallLocation);
    }
    ListRewrite actualFactoryArgs = unitRewriter.getListRewrite(factoryMethodCall, MethodInvocation.ARGUMENTS_PROPERTY);
    ListRewrite actualCtorArgs = unitRewriter.getListRewrite(ctorCall, ClassInstanceCreation.ARGUMENTS_PROPERTY);
    // Need to use a qualified name for the factory method if we're not
    // in the context of the class holding the factory.
    AbstractTypeDeclaration callOwner = (AbstractTypeDeclaration) ASTNodes.getParent(ctorCall, AbstractTypeDeclaration.class);
    ITypeBinding callOwnerBinding = callOwner.resolveBinding();
    if (callOwnerBinding == null || !Bindings.equals(callOwner.resolveBinding(), fFactoryOwningClass.resolveBinding())) {
        String qualifier = fImportRewriter.addImport(fFactoryOwningClass.resolveBinding());
        factoryMethodCall.setExpression(ASTNodeFactory.newName(ast, qualifier));
    }
    factoryMethodCall.setName(ast.newSimpleName(fNewMethodName));
    List<Expression> actualCtorArgsList = actualCtorArgs.getRewrittenList();
    for (int i = 0; i < actualCtorArgsList.size(); i++) {
        Expression actualCtorArg = actualCtorArgsList.get(i);
        ASTNode movedArg;
        if (ASTNodes.isExistingNode(actualCtorArg)) {
            movedArg = unitRewriter.createMoveTarget(actualCtorArg);
        } else {
            unitRewriter.remove(actualCtorArg, null);
            movedArg = actualCtorArg;
        }
        actualFactoryArgs.insertLast(movedArg, gd);
    }
    unitRewriter.replace(ctorCall, factoryMethodCall, gd);
}
Also used : AST(org.eclipse.jdt.core.dom.AST) Expression(org.eclipse.jdt.core.dom.Expression) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 9 with AbstractTypeDeclaration

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

the class IntroduceFactoryRefactoring method createFactoryChange.

/**
	 * Perform the AST rewriting necessary on the given <code>CompilationUnit</code> to create the
	 * factory method. The method will reside on the type identified by
	 * <code>fFactoryOwningClass</code>.
	 * 
	 * @param unitRewriter the ASTRewrite to be used
	 * @param unit the <code>CompilationUnit</code> where factory method will be created
	 * @param gd the <code>GroupDescription</code> to associate with the changes made
	 * @throws CoreException if an exception occurs while accessing its corresponding resource
	 */
private void createFactoryChange(ASTRewrite unitRewriter, CompilationUnit unit, TextEditGroup gd) throws CoreException {
    // ================================================================================
    // First add the factory itself (method, class, and interface as needed/directed by user)
    AST ast = unit.getAST();
    fFactoryMethod = createFactoryMethod(ast, fCtorBinding, unitRewriter);
    AbstractTypeDeclaration factoryOwner = (AbstractTypeDeclaration) unit.findDeclaringNode(fFactoryOwningClass.resolveBinding().getKey());
    fImportRewriter.addImport(fCtorOwningClass.resolveBinding());
    int idx = ASTNodes.getInsertionIndex(fFactoryMethod, factoryOwner.bodyDeclarations());
    // Guard against bug in getInsertionIndex()
    if (idx < 0)
        idx = 0;
    unitRewriter.getListRewrite(factoryOwner, factoryOwner.getBodyDeclarationsProperty()).insertAt(fFactoryMethod, idx, gd);
}
Also used : AST(org.eclipse.jdt.core.dom.AST) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 10 with AbstractTypeDeclaration

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

the class ExtractConstantRefactoring method getReplacementScope.

/*
	 * Elements returned by next() are BodyDeclaration or Annotation instances.
	 */
private Iterator<ASTNode> getReplacementScope() throws JavaModelException {
    boolean declPredecessorReached = false;
    Collection<ASTNode> scope = new ArrayList<ASTNode>();
    AbstractTypeDeclaration containingType = getContainingTypeDeclarationNode();
    if (containingType instanceof EnumDeclaration) {
        // replace in all enum constants bodies
        EnumDeclaration enumDeclaration = (EnumDeclaration) containingType;
        scope.addAll(enumDeclaration.enumConstants());
    }
    for (Iterator<IExtendedModifier> iter = containingType.modifiers().iterator(); iter.hasNext(); ) {
        IExtendedModifier modifier = iter.next();
        if (modifier instanceof Annotation) {
            scope.add((ASTNode) modifier);
        }
    }
    for (Iterator<BodyDeclaration> bodyDeclarations = containingType.bodyDeclarations().iterator(); bodyDeclarations.hasNext(); ) {
        BodyDeclaration bodyDeclaration = bodyDeclarations.next();
        if (bodyDeclaration == getNodeToInsertConstantDeclarationAfter())
            declPredecessorReached = true;
        if (insertFirst() || declPredecessorReached || !isStaticFieldOrStaticInitializer(bodyDeclaration))
            scope.add(bodyDeclaration);
    }
    return scope.iterator();
}
Also used : ArrayList(java.util.ArrayList) ASTNode(org.eclipse.jdt.core.dom.ASTNode) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) Annotation(org.eclipse.jdt.core.dom.Annotation) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) EnumDeclaration(org.eclipse.jdt.core.dom.EnumDeclaration) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier)

Aggregations

AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)61 ASTNode (org.eclipse.jdt.core.dom.ASTNode)36 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)25 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)17 AnonymousClassDeclaration (org.eclipse.jdt.core.dom.AnonymousClassDeclaration)17 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)17 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)17 AST (org.eclipse.jdt.core.dom.AST)15 TypeDeclaration (org.eclipse.jdt.core.dom.TypeDeclaration)12 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)12 FieldDeclaration (org.eclipse.jdt.core.dom.FieldDeclaration)11 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)11 Type (org.eclipse.jdt.core.dom.Type)10 ArrayList (java.util.ArrayList)9 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)9 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)9 IType (org.eclipse.jdt.core.IType)8 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)8 Expression (org.eclipse.jdt.core.dom.Expression)7 Javadoc (org.eclipse.jdt.core.dom.Javadoc)7