Search in sources :

Example 21 with ASTParser

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

the class ReplaceInvocationsRefactoring method resolveSourceProvider.

private SourceProvider resolveSourceProvider(IMethodBinding methodBinding, RefactoringStatus status) throws JavaModelException {
    final IMethod method = (IMethod) methodBinding.getJavaElement();
    ITypeRoot typeRoot;
    IDocument source;
    CompilationUnit methodDeclarationAstRoot;
    ICompilationUnit methodCu = (method).getCompilationUnit();
    if (methodCu != null) {
        typeRoot = methodCu;
        ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
        parser.setSource(methodCu);
        parser.setFocalPosition(method.getNameRange().getOffset());
        CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
        MethodDeclaration methodDecl = (MethodDeclaration) NodeFinder.perform(compilationUnit, method.getNameRange()).getParent();
        AST ast = compilationUnit.getAST();
        ASTRewrite rewrite = ASTRewrite.create(ast);
        Block newBody = ast.newBlock();
        newBody.statements().add(rewrite.createStringPlaceholder(fBody, ASTNode.EMPTY_STATEMENT));
        rewrite.replace(methodDecl.getBody(), newBody, null);
        List<SingleVariableDeclaration> parameters = methodDecl.parameters();
        for (int i = 0; i < parameters.size(); i++) {
            SingleVariableDeclaration parameter = parameters.get(i);
            rewrite.set(parameter.getName(), SimpleName.IDENTIFIER_PROPERTY, fParameterNames[i], null);
        }
        TextEdit textEdit = rewrite.rewriteAST();
        Document document = new Document(methodCu.getBuffer().getContents());
        try {
            textEdit.apply(document);
        } catch (MalformedTreeException e) {
            JavaPlugin.log(e);
        } catch (BadLocationException e) {
            JavaPlugin.log(e);
        }
        source = document;
        methodDeclarationAstRoot = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(source.get(), methodCu, true, true, null);
    } else {
        IClassFile classFile = method.getClassFile();
        //TODO: use source if available?
        StubCreator stubCreator = new StubCreator(true) {

            @Override
            protected void appendMethodBody(IMethod currentMethod) throws JavaModelException {
                if (currentMethod.equals(method)) {
                    fBuffer.append(fBody);
                } else {
                    super.appendMethodBody(currentMethod);
                }
            }

            /*
				 * @see org.eclipse.jdt.internal.corext.refactoring.binary.StubCreator#appendMethodParameterName(org.eclipse.jdt.core.IMethod, int)
				 */
            @Override
            protected void appendMethodParameterName(IMethod currentMethod, int index) {
                if (currentMethod.equals(method)) {
                    fBuffer.append(fParameterNames[index]);
                } else {
                    super.appendMethodParameterName(currentMethod, index);
                }
            }
        };
        String stub = stubCreator.createStub(classFile.getType(), null);
        source = new Document(stub);
        methodDeclarationAstRoot = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(stub, classFile, true, true, null);
        typeRoot = classFile;
    }
    ASTNode node = methodDeclarationAstRoot.findDeclaringNode(methodBinding.getKey());
    if (node instanceof MethodDeclaration) {
        return new SourceProvider(typeRoot, source, (MethodDeclaration) node);
    } else {
        status.addFatalError(RefactoringCoreMessages.ReplaceInvocationsRefactoring_cannot_find_method_declaration);
        return null;
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) IClassFile(org.eclipse.jdt.core.IClassFile) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ITypeRoot(org.eclipse.jdt.core.ITypeRoot) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) StubCreator(org.eclipse.jdt.internal.corext.refactoring.binary.StubCreator) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Block(org.eclipse.jdt.core.dom.Block) IMethod(org.eclipse.jdt.core.IMethod) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) ASTParser(org.eclipse.jdt.core.dom.ASTParser) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 22 with ASTParser

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

the class IntroduceIndirectionRefactoring method checkInitialConditions.

// ********** CONDITION CHECKING **********
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException {
    try {
        pm.beginTask(RefactoringCoreMessages.IntroduceIndirectionRefactoring_checking_activation, 1);
        fRewrites = new HashMap<ICompilationUnit, CompilationUnitRewrite>();
        if (fTargetMethod == null) {
            if (fSelectionStart == 0)
                return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_on_this_selection);
            // if a text selection exists, source is available.
            CompilationUnit selectionCURoot;
            ASTNode selectionNode;
            if (fSelectionCompilationUnit != null) {
                // compilation unit - could use CuRewrite later on
                selectionCURoot = getCachedCURewrite(fSelectionCompilationUnit).getRoot();
                selectionNode = getSelectedNode(fSelectionCompilationUnit, selectionCURoot, fSelectionStart, fSelectionLength);
            } else {
                // binary class file - no cu rewrite
                ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
                parser.setResolveBindings(true);
                parser.setSource(fSelectionClassFile);
                selectionCURoot = (CompilationUnit) parser.createAST(null);
                selectionNode = getSelectedNode(null, selectionCURoot, fSelectionStart, fSelectionLength);
            }
            if (selectionNode == null)
                return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_on_this_selection);
            IMethodBinding targetMethodBinding = null;
            if (selectionNode.getNodeType() == ASTNode.METHOD_INVOCATION) {
                targetMethodBinding = ((MethodInvocation) selectionNode).resolveMethodBinding();
            } else if (selectionNode.getNodeType() == ASTNode.METHOD_DECLARATION) {
                targetMethodBinding = ((MethodDeclaration) selectionNode).resolveBinding();
            } else if (selectionNode.getNodeType() == ASTNode.SUPER_METHOD_INVOCATION) {
                // Allow invocation on super methods calls. makes sense as other
                // calls or even only the declaration can be updated.
                targetMethodBinding = ((SuperMethodInvocation) selectionNode).resolveMethodBinding();
            } else {
                return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_on_this_selection);
            }
            // resolve generics
            fTargetMethodBinding = targetMethodBinding.getMethodDeclaration();
            fTargetMethod = (IMethod) fTargetMethodBinding.getJavaElement();
            //allow single updating mode if an invocation was selected and the invocation can be updated
            if (selectionNode instanceof MethodInvocation && fSelectionCompilationUnit != null)
                fSelectionMethodInvocation = (MethodInvocation) selectionNode;
        } else {
            if (fTargetMethod.getDeclaringType().isAnnotation())
                return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_on_annotation);
            if (fTargetMethod.getCompilationUnit() != null) {
                // source method
                CompilationUnit selectionCURoot = getCachedCURewrite(fTargetMethod.getCompilationUnit()).getRoot();
                MethodDeclaration declaration = ASTNodeSearchUtil.getMethodDeclarationNode(fTargetMethod, selectionCURoot);
                fTargetMethodBinding = declaration.resolveBinding().getMethodDeclaration();
            } else {
                // binary method - no CURewrite available (and none needed as we cannot update the method anyway)
                ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
                parser.setProject(fTargetMethod.getJavaProject());
                IBinding[] bindings = parser.createBindings(new IJavaElement[] { fTargetMethod }, null);
                fTargetMethodBinding = ((IMethodBinding) bindings[0]).getMethodDeclaration();
            }
        }
        if (fTargetMethod == null || fTargetMethodBinding == null || (!RefactoringAvailabilityTester.isIntroduceIndirectionAvailable(fTargetMethod)))
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_on_this_selection);
        if (fTargetMethod.getDeclaringType().isLocal() || fTargetMethod.getDeclaringType().isAnonymous())
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_for_local_or_anonymous_types);
        if (fTargetMethod.isConstructor())
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_for_constructors);
        if (fIntermediaryMethodName == null)
            fIntermediaryMethodName = fTargetMethod.getElementName();
        if (fIntermediaryType == null) {
            if (fSelectionCompilationUnit != null && !fSelectionCompilationUnit.isReadOnly())
                fIntermediaryType = getEnclosingInitialSelectionMember().getDeclaringType();
            else if (!fTargetMethod.isBinary() && !fTargetMethod.isReadOnly())
                fIntermediaryType = fTargetMethod.getDeclaringType();
        }
        return new RefactoringStatus();
    } finally {
        pm.done();
    }
}
Also used : CompilationUnitRewrite(org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) IBinding(org.eclipse.jdt.core.dom.IBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) ASTParser(org.eclipse.jdt.core.dom.ASTParser)

Example 23 with ASTParser

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

the class ASTBatchParser method createParser.

/**
	 * Creates a new parser which can be used to create ASTs
	 * for compilation units in <code>project</code>
	 * <p>
	 * Subclasses may override
	 * </p>
	 *
	 * @param project the project for which ASTs are been generated
	 * @return an AST parser capable of creating ASTs of compilation units in project
	 */
protected ASTParser createParser(IJavaProject project) {
    ASTParser result = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
    result.setResolveBindings(true);
    result.setProject(project);
    return result;
}
Also used : ASTParser(org.eclipse.jdt.core.dom.ASTParser)

Example 24 with ASTParser

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

the class TypeContextChecker method parseSuperType.

private static Type parseSuperType(String superType, boolean isInterface) {
    if (!superType.trim().equals(superType)) {
        return null;
    }
    StringBuffer cuBuff = new StringBuffer();
    if (isInterface)
        //$NON-NLS-1$
        cuBuff.append("class __X__ implements ");
    else
        //$NON-NLS-1$
        cuBuff.append("class __X__ extends ");
    int offset = cuBuff.length();
    //$NON-NLS-1$
    cuBuff.append(superType).append(" {}");
    ASTParser p = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
    p.setSource(cuBuff.toString().toCharArray());
    Map<String, String> options = new HashMap<String, String>();
    JavaModelUtil.setComplianceOptions(options, JavaModelUtil.VERSION_LATEST);
    p.setCompilerOptions(options);
    CompilationUnit cu = (CompilationUnit) p.createAST(null);
    ASTNode selected = NodeFinder.perform(cu, offset, superType.length());
    if (selected instanceof Name)
        selected = selected.getParent();
    if (selected.getStartPosition() != offset || selected.getLength() != superType.length() || !(selected instanceof Type) || selected instanceof PrimitiveType) {
        return null;
    }
    Type type = (Type) selected;
    String typeNodeRange = cuBuff.substring(type.getStartPosition(), ASTNodes.getExclusiveEnd(type));
    if (!superType.equals(typeNodeRange)) {
        return null;
    }
    return type;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) 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) HashMap(java.util.HashMap) ASTNode(org.eclipse.jdt.core.dom.ASTNode) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) ASTParser(org.eclipse.jdt.core.dom.ASTParser) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name)

Example 25 with ASTParser

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

the class TypeContextChecker method createSupertypeStubTypeContext.

private static StubTypeContext createSupertypeStubTypeContext(String typeName, boolean isInterface, IType enclosingType, IPackageFragment packageFragment) {
    StubTypeContext stubTypeContext;
    //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    String prolog = "class " + typeName + (isInterface ? " implements " : " extends ");
    //$NON-NLS-1$
    String epilog = " {} ";
    if (enclosingType != null) {
        try {
            ICompilationUnit cu = enclosingType.getCompilationUnit();
            ISourceRange typeSourceRange = enclosingType.getSourceRange();
            // before closing brace
            int focalPosition = typeSourceRange.getOffset() + typeSourceRange.getLength() - 1;
            ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
            parser.setSource(cu);
            parser.setFocalPosition(focalPosition);
            CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
            stubTypeContext = createStubTypeContext(cu, compilationUnit, focalPosition);
            stubTypeContext = new StubTypeContext(stubTypeContext.getCuHandle(), stubTypeContext.getBeforeString() + prolog, epilog + stubTypeContext.getAfterString());
        } catch (CoreException e) {
            JavaPlugin.log(e);
            stubTypeContext = new StubTypeContext(null, null, null);
        }
    } else if (packageFragment != null) {
        ICompilationUnit cu = packageFragment.getCompilationUnit(JavaTypeCompletionProcessor.DUMMY_CU_NAME);
        stubTypeContext = new StubTypeContext(cu, "package " + packageFragment.getElementName() + ";" + prolog, //$NON-NLS-1$//$NON-NLS-2$
        epilog);
    } else {
        stubTypeContext = new StubTypeContext(null, null, null);
    }
    return stubTypeContext;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CoreException(org.eclipse.core.runtime.CoreException) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) ASTParser(org.eclipse.jdt.core.dom.ASTParser) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Aggregations

ASTParser (org.eclipse.jdt.core.dom.ASTParser)42 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)34 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)24 ASTNode (org.eclipse.jdt.core.dom.ASTNode)11 RefactoringASTParser (org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser)9 IBinding (org.eclipse.jdt.core.dom.IBinding)7 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 IType (org.eclipse.jdt.core.IType)5 IProblem (org.eclipse.jdt.core.compiler.IProblem)5 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)5 ASTRequestor (org.eclipse.jdt.core.dom.ASTRequestor)4 RefactoringStatus (org.eclipse.ltk.core.refactoring.RefactoringStatus)4 SubProgressMonitor (org.eclipse.core.runtime.SubProgressMonitor)3 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)3 ISourceRange (org.eclipse.jdt.core.ISourceRange)3 ArrayType (org.eclipse.jdt.core.dom.ArrayType)3 PrimitiveType (org.eclipse.jdt.core.dom.PrimitiveType)3 Type (org.eclipse.jdt.core.dom.Type)3 Map (java.util.Map)2