Search in sources :

Example 41 with BodyDeclaration

use of org.eclipse.jdt.core.dom.BodyDeclaration in project AutoRefactor by JnRouvignac.

the class ASTNodes method getSibling.

private static BodyDeclaration getSibling(final BodyDeclaration node, final List<BodyDeclaration> bodyDeclarations, final boolean lookForPrevious) {
    TreeSet<BodyDeclaration> children = new TreeSet<>(ORDER_NODES_BY_START_POSITION);
    children.addAll(bodyDeclarations);
    BodyDeclaration previous = null;
    boolean returnNext = false;
    for (BodyDeclaration child : children) {
        if (lookForPrevious) {
            if (child.equals(node)) {
                return previous;
            }
        } else if (returnNext) {
            return child;
        }
        previous = child;
        returnNext = child.equals(node);
    }
    return null;
}
Also used : TreeSet(java.util.TreeSet) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration)

Example 42 with BodyDeclaration

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

the class TypeContextChecker method fillWithTypeStubs.

private static void fillWithTypeStubs(final StringBuffer bufBefore, final StringBuffer bufAfter, final int focalPosition, List<? extends BodyDeclaration> types) {
    StringBuffer buf;
    for (Iterator<? extends BodyDeclaration> iter = types.iterator(); iter.hasNext(); ) {
        BodyDeclaration bodyDeclaration = iter.next();
        if (!(bodyDeclaration instanceof AbstractTypeDeclaration)) {
            //account for local classes:
            if (!(bodyDeclaration instanceof MethodDeclaration))
                continue;
            int bodyStart = bodyDeclaration.getStartPosition();
            int bodyEnd = bodyDeclaration.getStartPosition() + bodyDeclaration.getLength();
            if (!(bodyStart < focalPosition && focalPosition < bodyEnd))
                continue;
            MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration;
            buf = bufBefore;
            appendModifiers(buf, methodDeclaration.modifiers());
            appendTypeParameters(buf, methodDeclaration.typeParameters());
            //$NON-NLS-1$
            buf.append(" void ");
            buf.append(methodDeclaration.getName().getIdentifier());
            //$NON-NLS-1$
            buf.append("(){\n");
            Block body = methodDeclaration.getBody();
            body.accept(new HierarchicalASTVisitor() {

                @Override
                public boolean visit(AbstractTypeDeclaration node) {
                    fillWithTypeStubs(bufBefore, bufAfter, focalPosition, Collections.singletonList(node));
                    return false;
                }

                @Override
                public boolean visit(ClassInstanceCreation node) {
                    AnonymousClassDeclaration anonDecl = node.getAnonymousClassDeclaration();
                    if (anonDecl == null)
                        // could be in CIC parameter list
                        return true;
                    int anonStart = anonDecl.getStartPosition();
                    int anonEnd = anonDecl.getStartPosition() + anonDecl.getLength();
                    if (!(anonStart < focalPosition && focalPosition < anonEnd))
                        return false;
                    //$NON-NLS-1$
                    bufBefore.append(" new ");
                    bufBefore.append(node.getType().toString());
                    //$NON-NLS-1$
                    bufBefore.append("(){\n");
                    fillWithTypeStubs(bufBefore, bufAfter, focalPosition, anonDecl.bodyDeclarations());
                    //$NON-NLS-1$
                    bufAfter.append("};\n");
                    return false;
                }
            });
            buf = bufAfter;
            //$NON-NLS-1$
            buf.append("}\n");
            continue;
        }
        AbstractTypeDeclaration decl = (AbstractTypeDeclaration) bodyDeclaration;
        buf = decl.getStartPosition() < focalPosition ? bufBefore : bufAfter;
        appendModifiers(buf, decl.modifiers());
        if (decl instanceof TypeDeclaration) {
            TypeDeclaration type = (TypeDeclaration) decl;
            //$NON-NLS-1$//$NON-NLS-2$
            buf.append(type.isInterface() ? "interface " : "class ");
            buf.append(type.getName().getIdentifier());
            appendTypeParameters(buf, type.typeParameters());
            if (type.getSuperclassType() != null) {
                //$NON-NLS-1$
                buf.append(" extends ");
                buf.append(ASTNodes.asString(type.getSuperclassType()));
            }
            List<Type> superInterfaces = type.superInterfaceTypes();
            appendSuperInterfaces(buf, superInterfaces);
        } else if (decl instanceof AnnotationTypeDeclaration) {
            AnnotationTypeDeclaration annotation = (AnnotationTypeDeclaration) decl;
            //$NON-NLS-1$
            buf.append("@interface ");
            buf.append(annotation.getName().getIdentifier());
        } else if (decl instanceof EnumDeclaration) {
            EnumDeclaration enumDecl = (EnumDeclaration) decl;
            //$NON-NLS-1$
            buf.append("enum ");
            buf.append(enumDecl.getName().getIdentifier());
            List<Type> superInterfaces = enumDecl.superInterfaceTypes();
            appendSuperInterfaces(buf, superInterfaces);
        }
        //$NON-NLS-1$
        buf.append("{\n");
        if (decl instanceof EnumDeclaration)
            //$NON-NLS-1$
            buf.append(";\n");
        fillWithTypeStubs(bufBefore, bufAfter, focalPosition, decl.bodyDeclarations());
        buf = decl.getStartPosition() + decl.getLength() < focalPosition ? bufBefore : bufAfter;
        //$NON-NLS-1$
        buf.append("}\n");
    }
}
Also used : ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) AnonymousClassDeclaration(org.eclipse.jdt.core.dom.AnonymousClassDeclaration) AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) HierarchicalASTVisitor(org.eclipse.jdt.internal.corext.dom.HierarchicalASTVisitor) EnumDeclaration(org.eclipse.jdt.core.dom.EnumDeclaration) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) IType(org.eclipse.jdt.core.IType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) Type(org.eclipse.jdt.core.dom.Type) QualifiedType(org.eclipse.jdt.core.dom.QualifiedType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) Block(org.eclipse.jdt.core.dom.Block) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 43 with BodyDeclaration

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

the class ExtractTempRefactoring method createRefactoringDescriptor.

private final ExtractLocalDescriptor createRefactoringDescriptor() {
    final Map<String, String> arguments = new HashMap<String, String>();
    String project = null;
    IJavaProject javaProject = fCu.getJavaProject();
    if (javaProject != null)
        project = javaProject.getElementName();
    final String description = Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_descriptor_description_short, BasicElementLabels.getJavaElementName(fTempName));
    final String expression = ASTNodes.asString(fSelectedExpression.getAssociatedExpression());
    final String header = Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_descriptor_description, new String[] { BasicElementLabels.getJavaElementName(fTempName), BasicElementLabels.getJavaCodeString(expression) });
    final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment(project, this, header);
    comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_name_pattern, BasicElementLabels.getJavaElementName(fTempName)));
    final BodyDeclaration decl = (BodyDeclaration) ASTNodes.getParent(fSelectedExpression.getAssociatedExpression(), BodyDeclaration.class);
    if (decl instanceof MethodDeclaration) {
        final IMethodBinding method = ((MethodDeclaration) decl).resolveBinding();
        final String label = method != null ? BindingLabelProvider.getBindingLabel(method, JavaElementLabels.ALL_FULLY_QUALIFIED) : BasicElementLabels.getJavaElementName('{' + JavaElementLabels.ELLIPSIS_STRING + '}');
        comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_destination_pattern, label));
    }
    comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_expression_pattern, BasicElementLabels.getJavaCodeString(expression)));
    if (fReplaceAllOccurrences)
        comment.addSetting(RefactoringCoreMessages.ExtractTempRefactoring_replace_occurrences);
    if (fDeclareFinal)
        comment.addSetting(RefactoringCoreMessages.ExtractTempRefactoring_declare_final);
    final ExtractLocalDescriptor descriptor = RefactoringSignatureDescriptorFactory.createExtractLocalDescriptor(project, description, comment.asString(), arguments, RefactoringDescriptor.NONE);
    arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fCu));
    arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME, fTempName);
    arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION, //$NON-NLS-1$
    new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString());
    arguments.put(ATTRIBUTE_REPLACE, Boolean.valueOf(fReplaceAllOccurrences).toString());
    arguments.put(ATTRIBUTE_FINAL, Boolean.valueOf(fDeclareFinal).toString());
    return descriptor;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) IJavaProject(org.eclipse.jdt.core.IJavaProject) HashMap(java.util.HashMap) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ExtractLocalDescriptor(org.eclipse.jdt.core.refactoring.descriptors.ExtractLocalDescriptor) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) JDTRefactoringDescriptorComment(org.eclipse.jdt.internal.corext.refactoring.JDTRefactoringDescriptorComment)

Example 44 with BodyDeclaration

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

the class ExtractMethodRefactoring method createNewMethodDeclaration.

private MethodDeclaration createNewMethodDeclaration() {
    MethodDeclaration result = fAST.newMethodDeclaration();
    int modifiers = fVisibility;
    BodyDeclaration enclosingBodyDeclaration = fAnalyzer.getEnclosingBodyDeclaration();
    boolean isDestinationInterface = isDestinationInterface();
    if (isDestinationInterface && !(enclosingBodyDeclaration instanceof MethodDeclaration && enclosingBodyDeclaration.getParent() == fDestination && Modifier.isPublic(enclosingBodyDeclaration.getModifiers()))) {
        modifiers = Modifier.NONE;
    }
    boolean shouldBeStatic = false;
    ASTNode currentParent = enclosingBodyDeclaration;
    do {
        if (currentParent instanceof BodyDeclaration) {
            shouldBeStatic = shouldBeStatic || JdtFlags.isStatic((BodyDeclaration) currentParent);
        }
        currentParent = currentParent.getParent();
    } while (!shouldBeStatic && currentParent != null && currentParent != fDestination);
    if (shouldBeStatic || fAnalyzer.getForceStatic() || forceStatic()) {
        modifiers |= Modifier.STATIC;
    } else if (isDestinationInterface) {
        modifiers |= Modifier.DEFAULT;
    }
    ITypeBinding[] typeVariables = computeLocalTypeVariables(modifiers);
    List<TypeParameter> typeParameters = result.typeParameters();
    for (int i = 0; i < typeVariables.length; i++) {
        TypeParameter parameter = fAST.newTypeParameter();
        parameter.setName(fAST.newSimpleName(typeVariables[i].getName()));
        ITypeBinding[] bounds = typeVariables[i].getTypeBounds();
        for (int j = 0; j < bounds.length; j++) if (//$NON-NLS-1$
        !"java.lang.Object".equals(bounds[j].getQualifiedName()))
            parameter.typeBounds().add(fImportRewriter.addImport(bounds[j], fAST));
        typeParameters.add(parameter);
    }
    result.modifiers().addAll(ASTNodeFactory.newModifiers(fAST, modifiers));
    result.setReturnType2((Type) ASTNode.copySubtree(fAST, fAnalyzer.getReturnType()));
    result.setName(fAST.newSimpleName(fMethodName));
    ImportRewriteContext context = new ContextSensitiveImportRewriteContext(enclosingBodyDeclaration, fImportRewriter);
    List<SingleVariableDeclaration> parameters = result.parameters();
    for (int i = 0; i < fParameterInfos.size(); i++) {
        ParameterInfo info = fParameterInfos.get(i);
        VariableDeclaration infoDecl = getVariableDeclaration(info);
        SingleVariableDeclaration parameter = fAST.newSingleVariableDeclaration();
        parameter.modifiers().addAll(ASTNodeFactory.newModifiers(fAST, ASTNodes.getModifiers(infoDecl)));
        parameter.setType(ASTNodeFactory.newType(fAST, infoDecl, fImportRewriter, context));
        parameter.setName(fAST.newSimpleName(info.getNewName()));
        parameter.setVarargs(info.isNewVarargs());
        parameters.add(parameter);
    }
    List<Type> exceptions = result.thrownExceptionTypes();
    ITypeBinding[] exceptionTypes = fAnalyzer.getExceptions(fThrowRuntimeExceptions);
    for (int i = 0; i < exceptionTypes.length; i++) {
        ITypeBinding exceptionType = exceptionTypes[i];
        exceptions.add(fImportRewriter.addImport(exceptionType, fAST, context));
    }
    return result;
}
Also used : TypeParameter(org.eclipse.jdt.core.dom.TypeParameter) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ParameterInfo(org.eclipse.jdt.internal.corext.refactoring.ParameterInfo) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) 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) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) VariableDeclaration(org.eclipse.jdt.core.dom.VariableDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration)

Example 45 with BodyDeclaration

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

the class ExtractMethodRefactoring method initializeDestinations.

private void initializeDestinations() {
    List<ASTNode> result = new ArrayList<ASTNode>();
    BodyDeclaration decl = fAnalyzer.getEnclosingBodyDeclaration();
    ASTNode current = ASTResolving.findParentType(decl.getParent());
    if (fAnalyzer.isValidDestination(current)) {
        result.add(current);
    }
    if (current != null && (decl instanceof MethodDeclaration || decl instanceof Initializer || decl instanceof FieldDeclaration)) {
        ITypeBinding binding = ASTNodes.getEnclosingType(current);
        ASTNode next = ASTResolving.findParentType(current.getParent());
        while (next != null && binding != null && binding.isNested()) {
            if (fAnalyzer.isValidDestination(next)) {
                result.add(next);
            }
            current = next;
            binding = ASTNodes.getEnclosingType(current);
            next = ASTResolving.findParentType(next.getParent());
        }
    }
    fDestinations = result.toArray(new ASTNode[result.size()]);
    fDestination = fDestinations[fDestinationIndex];
}
Also used : Initializer(org.eclipse.jdt.core.dom.Initializer) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ArrayList(java.util.ArrayList) ASTNode(org.eclipse.jdt.core.dom.ASTNode) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration)

Aggregations

BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)98 ASTNode (org.eclipse.jdt.core.dom.ASTNode)61 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)53 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)28 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)27 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)26 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)26 Type (org.eclipse.jdt.core.dom.Type)25 AST (org.eclipse.jdt.core.dom.AST)23 FieldDeclaration (org.eclipse.jdt.core.dom.FieldDeclaration)18 ImportRewrite (org.eclipse.jdt.core.dom.rewrite.ImportRewrite)17 Expression (org.eclipse.jdt.core.dom.Expression)16 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)15 Initializer (org.eclipse.jdt.core.dom.Initializer)15 SimpleName (org.eclipse.jdt.core.dom.SimpleName)15 TypeDeclaration (org.eclipse.jdt.core.dom.TypeDeclaration)15 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)14 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)14 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)13 ArrayList (java.util.ArrayList)12