Search in sources :

Example 31 with ASTParser

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

the class ASTNodeFactory method newType.

public static Type newType(AST ast, String content) {
    StringBuffer buffer = new StringBuffer(TYPE_HEADER);
    buffer.append(content);
    buffer.append(TYPE_FOOTER);
    ASTParser p = ASTParser.newParser(ast.apiLevel());
    p.setSource(buffer.toString().toCharArray());
    CompilationUnit root = (CompilationUnit) p.createAST(null);
    List<AbstractTypeDeclaration> list = root.types();
    TypeDeclaration typeDecl = (TypeDeclaration) list.get(0);
    MethodDeclaration methodDecl = typeDecl.getMethods()[0];
    ASTNode type = methodDecl.getReturnType2();
    ASTNode result = ASTNode.copySubtree(ast, type);
    result.accept(new PositionClearer());
    return (Type) result;
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) Type(org.eclipse.jdt.core.dom.Type) UnionType(org.eclipse.jdt.core.dom.UnionType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTParser(org.eclipse.jdt.core.dom.ASTParser) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 32 with ASTParser

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

the class StubUtility method getParameterTypeNamesForSeeTag.

/*
	 * Returns the parameters type names used in see tags. Currently, these are always fully qualified.
	 */
private static String[] getParameterTypeNamesForSeeTag(IMethod overridden) {
    try {
        ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
        parser.setProject(overridden.getJavaProject());
        IBinding[] bindings = parser.createBindings(new IJavaElement[] { overridden }, null);
        if (bindings.length == 1 && bindings[0] instanceof IMethodBinding) {
            return getParameterTypeNamesForSeeTag((IMethodBinding) bindings[0]);
        }
    } catch (IllegalStateException e) {
    // method does not exist
    }
    // fall back code. Not good for generic methods!
    String[] paramTypes = overridden.getParameterTypes();
    String[] paramTypeNames = new String[paramTypes.length];
    for (int i = 0; i < paramTypes.length; i++) {
        paramTypeNames[i] = Signature.toString(Signature.getTypeErasure(paramTypes[i]));
    }
    return paramTypeNames;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) IBinding(org.eclipse.jdt.core.dom.IBinding) ASTParser(org.eclipse.jdt.core.dom.ASTParser)

Example 33 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 34 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 35 with ASTParser

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

the class JavaFileParser method makeCompilationUnitFromSource.

private CompilationUnit makeCompilationUnitFromSource(String code) {
    ASTParser parser = ASTParser.newParser(jlsLevel);
    parser.setSource(code.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    Map<String, String> options = JavaCore.getOptions();
    JavaCore.setComplianceOptions(javaVersion, options);
    parser.setCompilerOptions(options);
    return (CompilationUnit) parser.createAST(/* monitor */
    null);
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ASTParser(org.eclipse.jdt.core.dom.ASTParser)

Aggregations

ASTParser (org.eclipse.jdt.core.dom.ASTParser)54 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)43 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)27 ASTNode (org.eclipse.jdt.core.dom.ASTNode)12 RefactoringASTParser (org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser)9 IBinding (org.eclipse.jdt.core.dom.IBinding)7 ArrayList (java.util.ArrayList)6 IProblem (org.eclipse.jdt.core.compiler.IProblem)6 HashMap (java.util.HashMap)5 IType (org.eclipse.jdt.core.IType)5 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)5 SubProgressMonitor (org.eclipse.core.runtime.SubProgressMonitor)4 TypeDeclaration (org.eclipse.jdt.core.dom.TypeDeclaration)4 RefactoringStatus (org.eclipse.ltk.core.refactoring.RefactoringStatus)4 File (java.io.File)3 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)3 ISourceRange (org.eclipse.jdt.core.ISourceRange)3 ASTRequestor (org.eclipse.jdt.core.dom.ASTRequestor)3 ArrayType (org.eclipse.jdt.core.dom.ArrayType)3 PrimitiveType (org.eclipse.jdt.core.dom.PrimitiveType)3