Search in sources :

Example 11 with RefactoringASTParser

use of org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser in project che by eclipse.

the class ExtractConstantRefactoring method checkSource.

private void checkSource(SubProgressMonitor monitor, RefactoringStatus result) throws CoreException {
    String newCuSource = fChange.getPreviewContent(new NullProgressMonitor());
    CompilationUnit newCUNode = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(newCuSource, fCu, true, true, monitor);
    IProblem[] newProblems = RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fCuRewrite.getRoot());
    for (int i = 0; i < newProblems.length; i++) {
        IProblem problem = newProblems[i];
        if (problem.isError())
            result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, SourceRangeFactory.create(problem))));
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) RefactoringStatusEntry(org.eclipse.ltk.core.refactoring.RefactoringStatusEntry) JavaStringStatusContext(org.eclipse.jdt.internal.corext.refactoring.base.JavaStringStatusContext) IProblem(org.eclipse.jdt.core.compiler.IProblem)

Example 12 with RefactoringASTParser

use of org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser in project che by eclipse.

the class TypeContextChecker method resolveSuperInterfaces.

public static ITypeBinding[] resolveSuperInterfaces(String[] interfaces, IType typeHandle, StubTypeContext superInterfaceContext) {
    ITypeBinding[] result = new ITypeBinding[interfaces.length];
    int[] interfaceOffsets = new int[interfaces.length];
    StringBuffer cuString = new StringBuffer();
    cuString.append(superInterfaceContext.getBeforeString());
    int last = interfaces.length - 1;
    for (int i = 0; i <= last; i++) {
        interfaceOffsets[i] = cuString.length();
        cuString.append(interfaces[i]);
        if (i != last)
            //$NON-NLS-1$
            cuString.append(", ");
    }
    cuString.append(superInterfaceContext.getAfterString());
    try {
        ICompilationUnit wc = typeHandle.getCompilationUnit().getWorkingCopy(new WorkingCopyOwner() {
        }, new NullProgressMonitor());
        try {
            wc.getBuffer().setContents(cuString.toString());
            CompilationUnit compilationUnit = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(wc, true);
            for (int i = 0; i <= last; i++) {
                ASTNode type = NodeFinder.perform(compilationUnit, interfaceOffsets[i], interfaces[i].length());
                if (type instanceof Type) {
                    result[i] = handleBug84585(((Type) type).resolveBinding());
                } else if (type instanceof Name) {
                    ASTNode parent = type.getParent();
                    if (parent instanceof Type) {
                        result[i] = handleBug84585(((Type) parent).resolveBinding());
                    } else {
                        throw new IllegalStateException();
                    }
                } else {
                    throw new IllegalStateException();
                }
            }
        } finally {
            wc.discardWorkingCopy();
        }
    } catch (JavaModelException e) {
    // won't happen
    }
    return result;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) JavaModelException(org.eclipse.jdt.core.JavaModelException) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) 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) WorkingCopyOwner(org.eclipse.jdt.core.WorkingCopyOwner) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode)

Example 13 with RefactoringASTParser

use of org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser 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 14 with RefactoringASTParser

use of org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser in project che by eclipse.

the class SelfEncapsulateFieldRefactoring method checkFinalConditions.

@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
    pm.beginTask(NO_NAME, 12);
    pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_checking_preconditions);
    RefactoringStatus result = new RefactoringStatus();
    fRewriter = ASTRewrite.create(fRoot.getAST());
    fChangeManager.clear();
    boolean usingLocalGetter = isUsingLocalGetter();
    boolean usingLocalSetter = isUsingLocalSetter();
    result.merge(checkMethodNames(usingLocalGetter, usingLocalSetter));
    pm.worked(1);
    if (result.hasFatalError())
        return result;
    pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_searching_for_cunits);
    final SubProgressMonitor subPm = new SubProgressMonitor(pm, 5);
    ICompilationUnit[] affectedCUs = RefactoringSearchEngine.findAffectedCompilationUnits(SearchPattern.createPattern(fField, IJavaSearchConstants.REFERENCES), RefactoringScopeFactory.create(fField, fConsiderVisibility), subPm, result, true);
    checkInHierarchy(result, usingLocalGetter, usingLocalSetter);
    if (result.hasFatalError())
        return result;
    pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_analyzing);
    IProgressMonitor sub = new SubProgressMonitor(pm, 5);
    sub.beginTask(NO_NAME, affectedCUs.length);
    IVariableBinding fieldIdentifier = fFieldDeclaration.resolveBinding();
    ITypeBinding declaringClass = ((AbstractTypeDeclaration) ASTNodes.getParent(fFieldDeclaration, AbstractTypeDeclaration.class)).resolveBinding();
    List<TextEditGroup> ownerDescriptions = new ArrayList<TextEditGroup>();
    ICompilationUnit owner = fField.getCompilationUnit();
    fImportRewrite = StubUtility.createImportRewrite(fRoot, true);
    for (int i = 0; i < affectedCUs.length; i++) {
        ICompilationUnit unit = affectedCUs[i];
        sub.subTask(BasicElementLabels.getFileName(unit));
        CompilationUnit root = null;
        ASTRewrite rewriter = null;
        ImportRewrite importRewrite;
        List<TextEditGroup> descriptions;
        if (owner.equals(unit)) {
            root = fRoot;
            rewriter = fRewriter;
            importRewrite = fImportRewrite;
            descriptions = ownerDescriptions;
        } else {
            root = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(unit, true);
            rewriter = ASTRewrite.create(root.getAST());
            descriptions = new ArrayList<TextEditGroup>();
            importRewrite = StubUtility.createImportRewrite(root, true);
        }
        checkCompileErrors(result, root, unit);
        AccessAnalyzer analyzer = new AccessAnalyzer(this, unit, fieldIdentifier, declaringClass, rewriter, importRewrite);
        root.accept(analyzer);
        result.merge(analyzer.getStatus());
        if (!fSetterMustReturnValue)
            fSetterMustReturnValue = analyzer.getSetterMustReturnValue();
        if (result.hasFatalError()) {
            fChangeManager.clear();
            return result;
        }
        descriptions.addAll(analyzer.getGroupDescriptions());
        if (!owner.equals(unit))
            createEdits(unit, rewriter, descriptions, importRewrite);
        sub.worked(1);
        if (pm.isCanceled())
            throw new OperationCanceledException();
    }
    ownerDescriptions.addAll(addGetterSetterChanges(fRoot, fRewriter, owner.findRecommendedLineSeparator(), usingLocalSetter, usingLocalGetter));
    createEdits(owner, fRewriter, ownerDescriptions, fImportRewrite);
    sub.done();
    IFile[] filesToBeModified = ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits());
    result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
    if (result.hasFatalError())
        return result;
    ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1));
    return result;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IFile(org.eclipse.core.resources.IFile) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TextEditGroup(org.eclipse.text.edits.TextEditGroup) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 15 with RefactoringASTParser

use of org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser in project eclipse.platform.runtime by eclipse.

the class RemoveUnusedMessages method checkFinalConditions.

@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
    if (monitor == null)
        monitor = new NullProgressMonitor();
    change = new CompositeChange("Accessor Class Changes");
    RefactoringStatus result = new RefactoringStatus();
    ICompilationUnit unit = JavaCore.createCompilationUnitFrom((IFile) accessorClass.getResource());
    CompilationUnit root = new RefactoringASTParser(AST.JLS3).parse(unit, true, null);
    ASTRewrite rewriter = ASTRewrite.create(root.getAST());
    // Search for references
    IField[] fields = accessorClass.getFields();
    ArrayList toDelete = new ArrayList();
    // 10 units of work for modifying the properties file and AST
    monitor.beginTask("Searching for references.", fields.length + 10);
    try {
        for (IField field : fields) {
            if (monitor.isCanceled())
                throw new OperationCanceledException();
            String fieldName = field.getElementName();
            monitor.subTask("Searching for references to: " + fieldName);
            int flags = field.getFlags();
            // only want to look at the public static String fields
            if (!(Flags.isPublic(flags) && Flags.isStatic(flags)))
                continue;
            // search for references
            ICompilationUnit[] affectedUnits = RefactoringSearchEngine.findAffectedCompilationUnits(SearchPattern.createPattern(field, IJavaSearchConstants.REFERENCES), RefactoringScopeFactory.create(accessorClass), new SubProgressMonitor(monitor, 1), result);
            // there are references so go to the next field
            if (affectedUnits.length > 0)
                continue;
            System.out.println("Found unused field: " + fieldName);
            toDelete.add(fieldName);
        }
        System.out.println("Analysis of " + fields.length + " messages found " + toDelete.size() + " unused messages");
        // any work to do?
        if (toDelete.isEmpty())
            return result;
        if (monitor.isCanceled())
            throw new OperationCanceledException();
        // remove the field and its corresponding entry in the messages.properties file
        processAST(root, rewriter, toDelete);
        monitor.worked(5);
        processPropertiesFile(toDelete);
        monitor.worked(5);
        TextFileChange cuChange = new TextFileChange(unit.getElementName(), (IFile) unit.getResource());
        try {
            ITextFileBuffer buffer = RefactoringFileBuffers.acquire(unit);
            IDocument document = buffer.getDocument();
            cuChange.setEdit(rewriter.rewriteAST(document, null));
        } finally {
            RefactoringFileBuffers.release(unit);
        }
        change.add(cuChange);
    } finally {
        monitor.done();
    }
    // return the result
    return result;
}
Also used : ArrayList(java.util.ArrayList) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) IDocument(org.eclipse.jface.text.IDocument)

Aggregations

RefactoringASTParser (org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser)15 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)12 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)12 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)7 ASTNode (org.eclipse.jdt.core.dom.ASTNode)6 RefactoringStatus (org.eclipse.ltk.core.refactoring.RefactoringStatus)6 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)4 ArrayList (java.util.ArrayList)3 IMethod (org.eclipse.jdt.core.IMethod)3 IType (org.eclipse.jdt.core.IType)3 IProblem (org.eclipse.jdt.core.compiler.IProblem)3 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)3 Name (org.eclipse.jdt.core.dom.Name)3 SimpleName (org.eclipse.jdt.core.dom.SimpleName)3 JavaStringStatusContext (org.eclipse.jdt.internal.corext.refactoring.base.JavaStringStatusContext)3 IDocument (org.eclipse.jface.text.IDocument)3 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)2 IClassFile (org.eclipse.jdt.core.IClassFile)2 ISourceRange (org.eclipse.jdt.core.ISourceRange)2 JavaModelException (org.eclipse.jdt.core.JavaModelException)2