Search in sources :

Example 1 with AggregateASTVisitor

use of org.autorefactor.jdt.internal.ui.fix.AggregateASTVisitor in project AutoRefactor by JnRouvignac.

the class AutoRefactorFix method createCleanUp.

/**
 * Create the clean up.
 *
 * @param compilationUnit compilation unit
 * @param enabled         enabled
 * @param fOptions        options
 * @return Clean up fix
 */
public static ICleanUpFix createCleanUp(final CompilationUnit compilationUnit, final boolean enabled, final CleanUpOptions fOptions) {
    boolean hasChanges = false;
    final ICompilationUnit iCompilationUnit = (ICompilationUnit) compilationUnit.getJavaElement();
    // $NON-NLS-1$
    final CleanUpChange cleanUpChange = new CleanUpChange("AutoRefactor", iCompilationUnit);
    TextEdit allEdits = null;
    if (enabled) {
        final IJavaProject javaProject = PrepareApplyRefactoringsJob.getIJavaProject(iCompilationUnit);
        final JavaProjectOptions options = new JavaProjectOptionsImpl(javaProject.getOptions(true));
        final Environment environment = AutoRefactorPlugin.getEnvironment();
        final List<RefactoringRule> refactoringRules = getConfiguredRefactoringRules(fOptions);
        final SubMonitor loopMonitor = SubMonitor.convert(null, 1);
        final Queue<RefactoringUnit> refactoringUnits = new ConcurrentLinkedQueue<>();
        refactoringUnits.add(new RefactoringUnit(iCompilationUnit, options));
        final ApplyRefactoringsJob applyRefactoringsJob = new ApplyRefactoringsJob(refactoringUnits, refactoringRules, environment);
        final AggregateASTVisitor visitor = new AggregateASTVisitor(refactoringRules);
        try {
            List<TextEdit> textEdits = applyRefactoringsJob.applyRefactoring(iCompilationUnit, visitor, options, loopMonitor, false);
            for (TextEdit textEdit : textEdits) {
                if (hasChanges) {
                    allEdits = TextEditUtil.merge(allEdits, textEdit);
                } else {
                    hasChanges = true;
                    allEdits = textEdit;
                }
            }
        } catch (Exception e) {
            if (!hasChanges) {
                return null;
            }
        }
    }
    if (!hasChanges) {
        return null;
    }
    cleanUpChange.setEdit(allEdits);
    AutoRefactorFix autoRefactorFix = new AutoRefactorFix();
    autoRefactorFix.cleanUpChange = cleanUpChange;
    return autoRefactorFix;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) JavaProjectOptions(org.autorefactor.jdt.internal.corext.dom.JavaProjectOptions) SubMonitor(org.eclipse.core.runtime.SubMonitor) RefactoringUnit(org.autorefactor.jdt.internal.corext.dom.RefactoringUnit) CoreException(org.eclipse.core.runtime.CoreException) JavaProjectOptionsImpl(org.autorefactor.jdt.internal.corext.dom.JavaProjectOptionsImpl) ApplyRefactoringsJob(org.autorefactor.jdt.internal.corext.dom.ApplyRefactoringsJob) PrepareApplyRefactoringsJob(org.autorefactor.jdt.internal.corext.dom.PrepareApplyRefactoringsJob) RefactoringRule(org.autorefactor.jdt.internal.corext.dom.RefactoringRule) IJavaProject(org.eclipse.jdt.core.IJavaProject) TextEdit(org.eclipse.text.edits.TextEdit) CleanUpChange(org.eclipse.jdt.internal.corext.fix.CleanUpRefactoring.CleanUpChange) Environment(org.autorefactor.environment.Environment) AggregateASTVisitor(org.autorefactor.jdt.internal.ui.fix.AggregateASTVisitor) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue)

Example 2 with AggregateASTVisitor

use of org.autorefactor.jdt.internal.ui.fix.AggregateASTVisitor in project AutoRefactor by JnRouvignac.

the class CleanUpTest method when.

private IDocument when(final String sampleInSource) throws Exception, JavaModelException {
    final IPackageFragment packageFragment = JavaCoreHelper.getPackageFragment(PACKAGE_NAME);
    final ICompilationUnit cu = packageFragment.createCompilationUnit(sampleName, sampleInSource, true, null);
    cu.getBuffer().setContents(sampleInSource);
    cu.save(null, true);
    final IDocument doc = new Document(sampleInSource);
    new ApplyRefactoringsJob(null, null, TEST_ENVIRONMENT).applyRefactoring(doc, cu, new AggregateASTVisitor(AllCleanUpRules.getAllCleanUpRules()), newJavaProjectOptions(Release.javaSE("1.8.0"), 4), SubMonitor.convert(new NullProgressMonitor()), // $NON-NLS-1$
    true);
    return doc;
}
Also used : ApplyRefactoringsJob(org.autorefactor.jdt.internal.corext.dom.ApplyRefactoringsJob) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) AggregateASTVisitor(org.autorefactor.jdt.internal.ui.fix.AggregateASTVisitor) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) IDocument(org.eclipse.jface.text.IDocument)

Example 3 with AggregateASTVisitor

use of org.autorefactor.jdt.internal.ui.fix.AggregateASTVisitor in project AutoRefactor by JnRouvignac.

the class RefactoringRulesTest method when.

private IDocument when(final String sampleName, final RefactoringRule refactoring, final String sampleInSource) throws Exception {
    IPackageFragment packageFragment = JavaCoreHelper.getPackageFragment(PACKAGE_NAME);
    ICompilationUnit cu = packageFragment.createCompilationUnit(sampleName, sampleInSource, true, null);
    cu.getBuffer().setContents(sampleInSource);
    cu.save(null, true);
    IDocument doc = new Document(sampleInSource);
    new ApplyRefactoringsJob(null, null, TEST_ENVIRONMENT).applyRefactoring(doc, cu, // $NON-NLS-1$
    new AggregateASTVisitor(Arrays.asList(refactoring)), // $NON-NLS-1$
    newJavaProjectOptions(Release.javaSE("1.8.0"), 4), SubMonitor.convert(new NullProgressMonitor()), true);
    return doc;
}
Also used : ApplyRefactoringsJob(org.autorefactor.jdt.internal.corext.dom.ApplyRefactoringsJob) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) AggregateASTVisitor(org.autorefactor.jdt.internal.ui.fix.AggregateASTVisitor) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) IDocument(org.eclipse.jface.text.IDocument)

Example 4 with AggregateASTVisitor

use of org.autorefactor.jdt.internal.ui.fix.AggregateASTVisitor in project AutoRefactor by JnRouvignac.

the class ApplyRefactoringsJob method run0.

private IStatus run0(final IProgressMonitor monitor) throws Exception {
    if (refactoringUnits.isEmpty()) {
        // No java project exists.
        return Status.OK_STATUS;
    }
    SubMonitor loopMonitor = SubMonitor.convert(monitor, refactoringUnits.size());
    try {
        RefactoringUnit toRefactor;
        while ((toRefactor = refactoringUnits.poll()) != null && !loopMonitor.isCanceled()) {
            ICompilationUnit compilationUnit = toRefactor.getCompilationUnit();
            JavaProjectOptions options = toRefactor.getOptions();
            try {
                // $NON-NLS-1$
                loopMonitor.subTask("Applying refactorings to " + getClassName(compilationUnit));
                AggregateASTVisitor refactoring = new AggregateASTVisitor(refactoringRulesToApply);
                applyRefactoring(compilationUnit, refactoring, options, loopMonitor.newChild(1), true);
            } catch (OperationCanceledException e) {
                throw e;
            } catch (Exception e) {
                String msg = // $NON-NLS-1$
                "Exception when applying refactorings to file \"" + compilationUnit.getPath() + "\": " + // $NON-NLS-1$
                e.getMessage();
                throw new UnhandledException(null, msg, e);
            }
        }
    } finally {
        loopMonitor.done();
    }
    return Status.OK_STATUS;
}
Also used : UnhandledException(org.autorefactor.util.UnhandledException) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) SubMonitor(org.eclipse.core.runtime.SubMonitor) AggregateASTVisitor(org.autorefactor.jdt.internal.ui.fix.AggregateASTVisitor) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) IllegalStateException(org.autorefactor.util.IllegalStateException) UnhandledException(org.autorefactor.util.UnhandledException)

Example 5 with AggregateASTVisitor

use of org.autorefactor.jdt.internal.ui.fix.AggregateASTVisitor in project AutoRefactor by JnRouvignac.

the class ApplyRefactoringsJob method applyRefactoring.

/**
 * Applies the cleanups provided inside the {@link AggregateASTVisitor} to
 * the provided {@link ICompilationUnit}.
 *
 * @param document        the document where the compilation unit comes from
 * @param compilationUnit the compilation unit to refactor
 * @param refactoring     the {@link AggregateASTVisitor} to apply to the
 *                        compilation unit
 * @param options         the Java project options used to compile the project
 * @param monitor         the progress monitor of the current job
 * @param hasToSave       hasToSave
 * @return TextEdit
 * @throws Exception if any problem occurs
 *
 * @see <a href=
 *      "http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Fguide%2Fjdt_api_manip.htm"
 *      >Eclipse JDT core - Manipulating Java code</a>
 * @see <a href=
 *      "http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.platform.doc.isv/guide/workbench_cmd_menus.htm"
 *      > Eclipse Platform Plug-in Developer Guide > Plugging into the workbench
 *      > Basic workbench extension points using commands >
 *      org.eclipse.ui.menus</a>
 * @see <a href=
 *      "http://www.eclipse.org/articles/article.php?file=Article-JavaCodeManipulation_AST/index.html"
 *      >Abstract Syntax Tree > Write it down</a>
 */
public List<TextEdit> applyRefactoring(final IDocument document, final ICompilationUnit compilationUnit, final AggregateASTVisitor refactoring, final JavaProjectOptions options, final SubMonitor monitor, final boolean hasToSave) throws Exception {
    // Creation of DOM/AST from a ICompilationUnit
    @SuppressWarnings("deprecation") ASTParser parser = ASTParser.newParser(AST.JLS8);
    int maxIterations = 100;
    int iterationCount = 0;
    Set<ASTVisitor> lastLoopVisitors = Collections.emptySet();
    int nbLoopsWithSameVisitors = 0;
    List<TextEdit> textEdits = new ArrayList<>();
    monitor.setWorkRemaining(maxIterations);
    CompilationUnit astRoot;
    do {
        // I did not find any other way to directly modify the AST
        // while still keeping the resolved type bindings working.
        // Using astRoot.recordModifications() did not work:
        // type bindings were lost. Is there a way to recover them?
        // FIXME we should find a way to apply all the changes at
        // the AST level and refresh the bindings
        resetParser(compilationUnit, parser, options);
        astRoot = (CompilationUnit) parser.createAST(null);
        if (iterationCount > maxIterations) {
            // Oops! Something went wrong.
            String errorMsg = // $NON-NLS-1$ //$NON-NLS-2$
            "An infinite loop has been detected for file " + ASTNodes.getFileName(astRoot) + "." + // $NON-NLS-1$
            " A possible cause is that code is being incorrectly" + " refactored one way then refactored back to what it was." + // $NON-NLS-1$ //$NON-NLS-2$
            " Fix the code before pursuing." + getPossibleCulprits(nbLoopsWithSameVisitors, lastLoopVisitors);
            environment.getLogger().error(errorMsg, new IllegalStateException(astRoot, errorMsg));
            break;
        }
        CompilationUnitRewrite cuRewrite = new CompilationUnitRewrite(compilationUnit, astRoot, options, monitor, environment);
        refactoring.setRefactoringContext(cuRewrite);
        ASTRewrite refactorings = refactoring.getRefactorings(astRoot);
        if (!refactorings.hasRefactorings()) {
            // We are done with applying the cleanups.
            break;
        }
        // Apply the cleanups and save the compilation unit
        refactorings.applyTo(document, hasToSave);
        textEdits.add(refactorings.getEdits());
        if (!hasToSave) {
            return textEdits;
        }
        boolean hadUnsavedChanges = compilationUnit.hasUnsavedChanges();
        compilationUnit.getBuffer().setContents(document.get());
        // , null, null);
        if (!hadUnsavedChanges && hasToSave) {
            compilationUnit.save(null, true);
        }
        iterationCount++;
        Set<ASTVisitor> thisLoopVisitors = refactoring.getVisitorsContributingRefactoring();
        if (thisLoopVisitors.equals(lastLoopVisitors)) {
            nbLoopsWithSameVisitors++;
        } else {
            lastLoopVisitors = new HashSet<>(thisLoopVisitors);
            nbLoopsWithSameVisitors = 0;
        }
    } while (true);
    return textEdits;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) CompilationUnitRewrite(org.autorefactor.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite) IllegalStateException(org.autorefactor.util.IllegalStateException) ArrayList(java.util.ArrayList) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) AggregateASTVisitor(org.autorefactor.jdt.internal.ui.fix.AggregateASTVisitor) TextEdit(org.eclipse.text.edits.TextEdit) ASTRewrite(org.autorefactor.jdt.core.dom.ASTRewrite) ASTParser(org.eclipse.jdt.core.dom.ASTParser)

Aggregations

AggregateASTVisitor (org.autorefactor.jdt.internal.ui.fix.AggregateASTVisitor)5 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)5 ApplyRefactoringsJob (org.autorefactor.jdt.internal.corext.dom.ApplyRefactoringsJob)3 IllegalStateException (org.autorefactor.util.IllegalStateException)2 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)2 SubMonitor (org.eclipse.core.runtime.SubMonitor)2 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)2 Document (org.eclipse.jface.text.Document)2 IDocument (org.eclipse.jface.text.IDocument)2 TextEdit (org.eclipse.text.edits.TextEdit)2 ArrayList (java.util.ArrayList)1 ConcurrentLinkedQueue (java.util.concurrent.ConcurrentLinkedQueue)1 Environment (org.autorefactor.environment.Environment)1 ASTRewrite (org.autorefactor.jdt.core.dom.ASTRewrite)1 JavaProjectOptions (org.autorefactor.jdt.internal.corext.dom.JavaProjectOptions)1 JavaProjectOptionsImpl (org.autorefactor.jdt.internal.corext.dom.JavaProjectOptionsImpl)1 PrepareApplyRefactoringsJob (org.autorefactor.jdt.internal.corext.dom.PrepareApplyRefactoringsJob)1 RefactoringRule (org.autorefactor.jdt.internal.corext.dom.RefactoringRule)1 RefactoringUnit (org.autorefactor.jdt.internal.corext.dom.RefactoringUnit)1 CompilationUnitRewrite (org.autorefactor.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite)1