Search in sources :

Example 1 with ASTParser

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

the class InferTypeArgumentsRefactoring method checkFinalConditions.

/*
	 * @see org.eclipse.ltk.core.refactoring.Refactoring#checkFinalConditions(org.eclipse.core.runtime.IProgressMonitor)
	 */
@Override
public RefactoringStatus checkFinalConditions(final IProgressMonitor pm) throws CoreException, OperationCanceledException {
    HashMap<IJavaProject, ArrayList<IJavaElement>> projectsToElements = getJavaElementsPerProject(fElements);
    //$NON-NLS-1$
    pm.beginTask("", projectsToElements.size() + 2);
    final RefactoringStatus result = new RefactoringStatus();
    try {
        fTCModel = new InferTypeArgumentsTCModel();
        final InferTypeArgumentsConstraintCreator unitCollector = new InferTypeArgumentsConstraintCreator(fTCModel, fAssumeCloneReturnsSameType);
        for (Iterator<Entry<IJavaProject, ArrayList<IJavaElement>>> iter = projectsToElements.entrySet().iterator(); iter.hasNext(); ) {
            Entry<IJavaProject, ArrayList<IJavaElement>> entry = iter.next();
            IJavaProject project = entry.getKey();
            ArrayList<IJavaElement> javaElementsList = entry.getValue();
            IJavaElement[] javaElements = javaElementsList.toArray(new IJavaElement[javaElementsList.size()]);
            List<ICompilationUnit> cus = Arrays.asList(JavaModelUtil.getAllCompilationUnits(javaElements));
            int batchSize = 150;
            int batches = ((cus.size() - 1) / batchSize) + 1;
            SubProgressMonitor projectMonitor = new SubProgressMonitor(pm, 1);
            //$NON-NLS-1$
            projectMonitor.beginTask("", batches);
            projectMonitor.setTaskName(RefactoringCoreMessages.InferTypeArgumentsRefactoring_building);
            for (int i = 0; i < batches; i++) {
                List<ICompilationUnit> batch = cus.subList(i * batchSize, Math.min(cus.size(), (i + 1) * batchSize));
                ICompilationUnit[] batchCus = batch.toArray(new ICompilationUnit[batch.size()]);
                final SubProgressMonitor batchMonitor = new SubProgressMonitor(projectMonitor, 1);
                batchMonitor.subTask(RefactoringCoreMessages.InferTypeArgumentsRefactoring_calculating_dependencies);
                ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
                parser.setProject(project);
                parser.setCompilerOptions(RefactoringASTParser.getCompilerOptions(project));
                parser.setResolveBindings(true);
                parser.createASTs(batchCus, new String[0], new ASTRequestor() {

                    @Override
                    public void acceptAST(final ICompilationUnit source, final CompilationUnit ast) {
                        batchMonitor.subTask(BasicElementLabels.getFileName(source));
                        SafeRunner.run(new ISafeRunnable() {

                            public void run() throws Exception {
                                IProblem[] problems = ast.getProblems();
                                for (int p = 0; p < problems.length; p++) {
                                    if (problems[p].isError()) {
                                        String cuName = JavaElementLabels.getElementLabel(source, JavaElementLabels.CU_QUALIFIED);
                                        String msg = Messages.format(RefactoringCoreMessages.InferTypeArgumentsRefactoring_error_in_cu_skipped, new Object[] { cuName });
                                        result.addError(msg, JavaStatusContext.create(source, SourceRangeFactory.create(problems[p])));
                                        return;
                                    }
                                }
                                ast.accept(unitCollector);
                            }

                            public void handleException(Throwable exception) {
                                String cuName = JavaElementLabels.getElementLabel(source, JavaElementLabels.CU_QUALIFIED);
                                String msg = Messages.format(RefactoringCoreMessages.InferTypeArgumentsRefactoring_internal_error, new Object[] { cuName });
                                JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, msg, null));
                                String msg2 = Messages.format(RefactoringCoreMessages.InferTypeArgumentsRefactoring_error_skipped, new Object[] { cuName });
                                result.addError(msg2, JavaStatusContext.create(source));
                            }
                        });
                        fTCModel.newCu();
                    }

                    @Override
                    public void acceptBinding(String bindingKey, IBinding binding) {
                    //do nothing
                    }
                }, batchMonitor);
            }
            projectMonitor.done();
            fTCModel.newCu();
        }
        //			Display.getDefault().syncExec(new Runnable() {
        //				public void run() {
        //					MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Debugging...", "after constraint gen");
        //				}
        //			});
        pm.setTaskName(RefactoringCoreMessages.InferTypeArgumentsRefactoring_solving);
        InferTypeArgumentsConstraintsSolver solver = new InferTypeArgumentsConstraintsSolver(fTCModel);
        InferTypeArgumentsUpdate updates = solver.solveConstraints(new SubProgressMonitor(pm, 1));
        //free caches
        solver = null;
        fChangeManager = new TextChangeManager();
        rewriteDeclarations(updates, new SubProgressMonitor(pm, 1));
        IFile[] filesToModify = ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits());
        result.merge(Checks.validateModifiesFiles(filesToModify, getValidationContext()));
        return result;
    } finally {
        pm.done();
        clearGlobalState();
    }
}
Also used : IFile(org.eclipse.core.resources.IFile) IBinding(org.eclipse.jdt.core.dom.IBinding) ArrayList(java.util.ArrayList) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) Entry(java.util.Map.Entry) ASTRequestor(org.eclipse.jdt.core.dom.ASTRequestor) ISafeRunnable(org.eclipse.core.runtime.ISafeRunnable) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) ASTParser(org.eclipse.jdt.core.dom.ASTParser) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IJavaElement(org.eclipse.jdt.core.IJavaElement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IProblem(org.eclipse.jdt.core.compiler.IProblem) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) IJavaProject(org.eclipse.jdt.core.IJavaProject) TextChangeManager(org.eclipse.jdt.internal.corext.refactoring.util.TextChangeManager)

Example 2 with ASTParser

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

the class ReplaceInvocationsRefactoring method checkInitialConditions.

@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
    // TargetProvider must get an untampered AST with original invocation node
    // SourceProvider must get a tweaked AST with method body / parameter names replaced
    RefactoringStatus result = new RefactoringStatus();
    if (fMethod == null) {
        if (!(fSelectionTypeRoot instanceof ICompilationUnit))
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReplaceInvocationsRefactoring_cannot_replace_in_binary);
        ICompilationUnit cu = (ICompilationUnit) fSelectionTypeRoot;
        CompilationUnit root = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(cu, true);
        fSelectionNode = getTargetNode(cu, root, fSelectionStart, fSelectionLength);
        if (fSelectionNode == null)
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReplaceInvocationsRefactoring_select_method_to_apply);
        if (fSelectionNode.getNodeType() == ASTNode.METHOD_DECLARATION) {
            MethodDeclaration methodDeclaration = (MethodDeclaration) fSelectionNode;
            fTargetProvider = TargetProvider.create(methodDeclaration);
            fMethodBinding = methodDeclaration.resolveBinding();
        } else {
            MethodInvocation methodInvocation = (MethodInvocation) fSelectionNode;
            fTargetProvider = TargetProvider.create(cu, methodInvocation);
            fMethodBinding = methodInvocation.resolveMethodBinding();
        }
        if (fMethodBinding == null)
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration);
        fMethod = (IMethod) fMethodBinding.getJavaElement();
    } else {
        ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
        parser.setProject(fMethod.getJavaProject());
        IBinding[] bindings = parser.createBindings(new IJavaElement[] { fMethod }, null);
        fMethodBinding = (IMethodBinding) bindings[0];
        if (fMethodBinding == null)
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration);
        fTargetProvider = TargetProvider.create(fMethodBinding);
    }
    result.merge(fTargetProvider.checkActivation());
    return result;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) IBinding(org.eclipse.jdt.core.dom.IBinding) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) ASTParser(org.eclipse.jdt.core.dom.ASTParser)

Example 3 with ASTParser

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

the class ChangeSignatureProcessor method isValidExpression.

public static boolean isValidExpression(String string) {
    String trimmed = string.trim();
    if (//speed up for a common case //$NON-NLS-1$
    "".equals(trimmed))
        return false;
    StringBuffer cuBuff = new StringBuffer();
    cuBuff.append(CONST_CLASS_DECL).append(//$NON-NLS-1$
    "Object").append(CONST_ASSIGN);
    int offset = cuBuff.length();
    cuBuff.append(trimmed).append(CONST_CLOSE);
    ASTParser p = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
    p.setSource(cuBuff.toString().toCharArray());
    CompilationUnit cu = (CompilationUnit) p.createAST(null);
    Selection selection = Selection.createFromStartLength(offset, trimmed.length());
    SelectionAnalyzer analyzer = new SelectionAnalyzer(selection, false);
    cu.accept(analyzer);
    ASTNode selected = analyzer.getFirstSelectedNode();
    return (selected instanceof Expression) && trimmed.equals(cuBuff.substring(cu.getExtendedStartPosition(selected), cu.getExtendedStartPosition(selected) + cu.getExtendedLength(selected)));
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) SelectionAnalyzer(org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer) Expression(org.eclipse.jdt.core.dom.Expression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) Selection(org.eclipse.jdt.internal.corext.dom.Selection) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTParser(org.eclipse.jdt.core.dom.ASTParser) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser)

Example 4 with ASTParser

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

the class ChangeSignatureProcessor method isValidVarargsExpression.

public static boolean isValidVarargsExpression(String string) {
    String trimmed = string.trim();
    if (//speed up for a common case //$NON-NLS-1$
    "".equals(trimmed))
        return true;
    StringBuffer cuBuff = new StringBuffer();
    //$NON-NLS-1$
    cuBuff.append("class A{ {m(");
    int offset = cuBuff.length();
    cuBuff.append(trimmed).append(//$NON-NLS-1$
    ");}}");
    ASTParser p = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
    p.setSource(cuBuff.toString().toCharArray());
    CompilationUnit cu = (CompilationUnit) p.createAST(null);
    Selection selection = Selection.createFromStartLength(offset, trimmed.length());
    SelectionAnalyzer analyzer = new SelectionAnalyzer(selection, false);
    cu.accept(analyzer);
    ASTNode[] selectedNodes = analyzer.getSelectedNodes();
    if (selectedNodes.length == 0)
        return false;
    for (int i = 0; i < selectedNodes.length; i++) {
        if (!(selectedNodes[i] instanceof Expression))
            return false;
    }
    return true;
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) SelectionAnalyzer(org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer) Expression(org.eclipse.jdt.core.dom.Expression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) Selection(org.eclipse.jdt.internal.corext.dom.Selection) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTParser(org.eclipse.jdt.core.dom.ASTParser) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser)

Example 5 with ASTParser

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

the class ASTCreator method getCuNode.

private static CompilationUnit getCuNode(WorkingCopyOwner workingCopyOwner, ICompilationUnit cu) {
    ASTParser p = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
    p.setSource(cu);
    p.setResolveBindings(true);
    p.setWorkingCopyOwner(workingCopyOwner);
    p.setCompilerOptions(RefactoringASTParser.getCompilerOptions(cu));
    return (CompilationUnit) p.createAST(null);
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ASTParser(org.eclipse.jdt.core.dom.ASTParser) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser)

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