Search in sources :

Example 1 with CompilationUnit

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

the class OrganizeImportsOperation method createTextEdit.

public TextEdit createTextEdit(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }
    try {
        fNumberOfImportsAdded = 0;
        fNumberOfImportsRemoved = 0;
        monitor.beginTask(Messages.format(CodeGenerationMessages.OrganizeImportsOperation_description, BasicElementLabels.getFileName(fCompilationUnit)), 9);
        CompilationUnit astRoot = fASTRoot;
        if (astRoot == null) {
            astRoot = SharedASTProvider.getAST(fCompilationUnit, SharedASTProvider.WAIT_YES, new SubProgressMonitor(monitor, 2));
            if (monitor.isCanceled())
                throw new OperationCanceledException();
        } else {
            monitor.worked(2);
        }
        ImportRewrite importsRewrite = StubUtility.createImportRewrite(astRoot, false);
        Set<String> oldSingleImports = new HashSet<>();
        Set<String> oldDemandImports = new HashSet<>();
        List<SimpleName> typeReferences = new ArrayList<>();
        List<SimpleName> staticReferences = new ArrayList<>();
        if (!collectReferences(astRoot, typeReferences, staticReferences, oldSingleImports, oldDemandImports))
            return null;
        monitor.worked(1);
        processor = new TypeReferenceProcessor(oldSingleImports, oldDemandImports, astRoot, importsRewrite, fIgnoreLowerCaseNames);
        Iterator<SimpleName> refIterator = typeReferences.iterator();
        while (refIterator.hasNext()) {
            SimpleName typeRef = refIterator.next();
            processor.add(typeRef);
        }
        hasOpenChoices = processor.process(new SubProgressMonitor(monitor, 3));
        addStaticImports(staticReferences, importsRewrite);
        if (hasOpenChoices) {
            choices = processor.getChoices();
            ISourceRange[] ranges = processor.getChoicesSourceRanges();
            if (fChooseImportQuery != null) {
                TypeNameMatch[] chosen = fChooseImportQuery.chooseImports(choices, ranges);
                for (int i = 0; i < chosen.length; i++) {
                    TypeNameMatch typeInfo = chosen[i];
                    importsRewrite.addImport(typeInfo.getFullyQualifiedName());
                }
            } else if (chosenFQN != null) {
                chosenFQN.forEach(importsRewrite::addImport);
            }
        }
        TextEdit result = importsRewrite.rewriteImports(new SubProgressMonitor(monitor, 3));
        determineImportDifferences(importsRewrite, oldSingleImports, oldDemandImports);
        return result;
    } finally {
        monitor.done();
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayList(java.util.ArrayList) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) TypeNameMatch(org.eclipse.jdt.core.search.TypeNameMatch) TextEdit(org.eclipse.text.edits.TextEdit) HashSet(java.util.HashSet) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 2 with CompilationUnit

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

the class LinkedNodeFinder method findByProblems.

public static SimpleName[] findByProblems(ASTNode parent, SimpleName nameNode) {
    ArrayList<SimpleName> res = new ArrayList<SimpleName>();
    ASTNode astRoot = parent.getRoot();
    if (!(astRoot instanceof CompilationUnit)) {
        return null;
    }
    IProblem[] problems = ((CompilationUnit) astRoot).getProblems();
    int nameNodeKind = getNameNodeProblemKind(problems, nameNode);
    if (nameNodeKind == 0) {
        // no problem on node
        return null;
    }
    int bodyStart = parent.getStartPosition();
    int bodyEnd = bodyStart + parent.getLength();
    String name = nameNode.getIdentifier();
    for (int i = 0; i < problems.length; i++) {
        IProblem curr = problems[i];
        int probStart = curr.getSourceStart();
        int probEnd = curr.getSourceEnd() + 1;
        if (probStart > bodyStart && probEnd < bodyEnd) {
            int currKind = getProblemKind(curr);
            if ((nameNodeKind & currKind) != 0) {
                ASTNode node = NodeFinder.perform(parent, probStart, (probEnd - probStart));
                if (node instanceof SimpleName && name.equals(((SimpleName) node).getIdentifier())) {
                    res.add((SimpleName) node);
                }
            }
        }
    }
    return res.toArray(new SimpleName[res.size()]);
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayList(java.util.ArrayList) ASTNode(org.eclipse.jdt.core.dom.ASTNode) IProblem(org.eclipse.jdt.core.compiler.IProblem)

Example 3 with CompilationUnit

use of org.eclipse.jdt.core.dom.CompilationUnit in project che 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);
    CheASTParser p = CheASTParser.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) CheASTParser(org.eclipse.jdt.core.dom.CheASTParser) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 4 with CompilationUnit

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

the class RenameTypeProcessor method initializeSimilarElementsRenameProcessors.

// --------- Similar names
/**
	 * Creates and initializes the refactoring processors for similarly named elements
	 * @param progressMonitor progress monitor
	 * @param context context
	 * @return status
	 * @throws CoreException should not happen
	 */
private RefactoringStatus initializeSimilarElementsRenameProcessors(IProgressMonitor progressMonitor, CheckConditionsContext context) throws CoreException {
    Assert.isNotNull(fPreloadedElementToName);
    Assert.isNotNull(fPreloadedElementToSelection);
    final RefactoringStatus status = new RefactoringStatus();
    final Set<IMethod> handledTopLevelMethods = new HashSet<IMethod>();
    final Set<Warning> warnings = new HashSet<Warning>();
    final List<RefactoringProcessor> processors = new ArrayList<RefactoringProcessor>();
    fFinalSimilarElementToName = new HashMap<IJavaElement, String>();
    CompilationUnit currentResolvedCU = null;
    ICompilationUnit currentCU = null;
    int current = 0;
    final int max = fPreloadedElementToName.size();
    //$NON-NLS-1$
    progressMonitor.beginTask("", max * 3);
    progressMonitor.setTaskName(RefactoringCoreMessages.RenameTypeProcessor_checking_similarly_named_declarations_refactoring_conditions);
    for (Iterator<IJavaElement> iter = fPreloadedElementToName.keySet().iterator(); iter.hasNext(); ) {
        final IJavaElement element = iter.next();
        current++;
        progressMonitor.worked(3);
        // not selected? -> skip
        if (!(fPreloadedElementToSelection.get(element)).booleanValue())
            continue;
        // already registered? (may happen with overridden methods) -> skip
        if (fFinalSimilarElementToName.containsKey(element))
            continue;
        // CompilationUnit changed? (note: fPreloadedElementToName is sorted by CompilationUnit)
        ICompilationUnit newCU = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
        if (!newCU.equals(currentCU)) {
            checkCUCompleteConditions(status, currentResolvedCU, currentCU, processors);
            if (status.hasFatalError())
                return status;
            // reset values
            currentResolvedCU = null;
            currentCU = newCU;
            processors.clear();
        }
        final String newName = fPreloadedElementToName.get(element);
        RefactoringProcessor processor = null;
        if (element instanceof ILocalVariable) {
            final ILocalVariable currentLocal = (ILocalVariable) element;
            if (currentResolvedCU == null)
                currentResolvedCU = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(currentCU, true);
            processor = createLocalRenameProcessor(currentLocal, newName, currentResolvedCU);
            if (status.hasFatalError())
                return status;
            fFinalSimilarElementToName.put(currentLocal, newName);
        }
        if (element instanceof IField) {
            final IField currentField = (IField) element;
            processor = createFieldRenameProcessor(currentField, newName);
            status.merge(checkForConflictingRename(currentField, newName));
            if (status.hasFatalError())
                return status;
            fFinalSimilarElementToName.put(currentField, newName);
        }
        if (element instanceof IMethod) {
            IMethod currentMethod = (IMethod) element;
            if (MethodChecks.isVirtual(currentMethod)) {
                final IType declaringType = currentMethod.getDeclaringType();
                ITypeHierarchy hierarchy = null;
                if (!declaringType.isInterface())
                    hierarchy = declaringType.newTypeHierarchy(new NullProgressMonitor());
                final IMethod topmost = MethodChecks.getTopmostMethod(currentMethod, hierarchy, new NullProgressMonitor());
                if (topmost != null)
                    currentMethod = topmost;
                if (handledTopLevelMethods.contains(currentMethod))
                    continue;
                handledTopLevelMethods.add(currentMethod);
                final IMethod[] ripples = RippleMethodFinder2.getRelatedMethods(currentMethod, new NullProgressMonitor(), null);
                if (checkForWarnings(warnings, newName, ripples))
                    continue;
                status.merge(checkForConflictingRename(ripples, newName));
                if (status.hasFatalError())
                    return status;
                processor = createVirtualMethodRenameProcessor(currentMethod, newName, ripples, hierarchy);
                fFinalSimilarElementToName.put(currentMethod, newName);
                for (int i = 0; i < ripples.length; i++) {
                    fFinalSimilarElementToName.put(ripples[i], newName);
                }
            } else {
                status.merge(checkForConflictingRename(new IMethod[] { currentMethod }, newName));
                if (status.hasFatalError())
                    break;
                fFinalSimilarElementToName.put(currentMethod, newName);
                processor = createNonVirtualMethodRenameProcessor(currentMethod, newName);
            }
        }
        progressMonitor.subTask(Messages.format(RefactoringCoreMessages.RenameTypeProcessor_progress_current_total, new Object[] { String.valueOf(current), String.valueOf(max) }));
        status.merge(processor.checkInitialConditions(new NoOverrideProgressMonitor(progressMonitor, 1)));
        if (status.hasFatalError())
            return status;
        status.merge(processor.checkFinalConditions(new NoOverrideProgressMonitor(progressMonitor, 1), context));
        if (status.hasFatalError())
            return status;
        processors.add(processor);
        progressMonitor.worked(1);
        if (progressMonitor.isCanceled())
            throw new OperationCanceledException();
    }
    // check last CU
    checkCUCompleteConditions(status, currentResolvedCU, currentCU, processors);
    status.merge(addWarnings(warnings));
    progressMonitor.done();
    return status;
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IType(org.eclipse.jdt.core.IType) ILocalVariable(org.eclipse.jdt.core.ILocalVariable) ITypeHierarchy(org.eclipse.jdt.core.ITypeHierarchy) IMethod(org.eclipse.jdt.core.IMethod) HashSet(java.util.HashSet) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IField(org.eclipse.jdt.core.IField) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) RefactoringProcessor(org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor)

Example 5 with CompilationUnit

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

the class RenameTypeProcessor method analyseEnclosedTypes.

private RefactoringStatus analyseEnclosedTypes() throws CoreException {
    final ISourceRange typeRange = fType.getSourceRange();
    final RefactoringStatus result = new RefactoringStatus();
    CompilationUnit cuNode = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(fType.getCompilationUnit(), false);
    cuNode.accept(new ASTVisitor() {

        @Override
        public boolean visit(TypeDeclaration node) {
            // enums and annotations can't be local
            if (node.getStartPosition() <= typeRange.getOffset())
                return true;
            if (node.getStartPosition() > typeRange.getOffset() + typeRange.getLength())
                return true;
            if (getNewElementName().equals(node.getName().getIdentifier())) {
                RefactoringStatusContext context = JavaStatusContext.create(fType.getCompilationUnit(), node);
                String msg = null;
                if (node.isLocalTypeDeclaration()) {
                    msg = Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_local_type, new String[] { JavaElementUtil.createSignature(fType), getNewElementLabel() });
                } else if (node.isMemberTypeDeclaration()) {
                    msg = Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_member_type, new String[] { JavaElementUtil.createSignature(fType), getNewElementLabel() });
                }
                if (msg != null)
                    result.addError(msg, context);
            }
            MethodDeclaration[] methods = node.getMethods();
            for (int i = 0; i < methods.length; i++) {
                if (Modifier.isNative(methods[i].getModifiers())) {
                    RefactoringStatusContext context = JavaStatusContext.create(fType.getCompilationUnit(), methods[i]);
                    String msg = Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_enclosed_type_native, BasicElementLabels.getJavaElementName(node.getName().getIdentifier()));
                    result.addWarning(msg, context);
                }
            }
            return true;
        }
    });
    return result;
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) RefactoringStatusContext(org.eclipse.ltk.core.refactoring.RefactoringStatusContext) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) ISourceRange(org.eclipse.jdt.core.ISourceRange) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor)

Aggregations

CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)610 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)555 ArrayList (java.util.ArrayList)450 Test (org.junit.Test)438 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)435 CUCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal)228 Hashtable (java.util.Hashtable)137 ASTNode (org.eclipse.jdt.core.dom.ASTNode)80 SimpleName (org.eclipse.jdt.core.dom.SimpleName)36 ASTParser (org.eclipse.jdt.core.dom.ASTParser)35 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)35 ASTRewriteCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal)35 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)34 Ignore (org.junit.Ignore)34 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)28 Type (org.eclipse.jdt.core.dom.Type)26 AST (org.eclipse.jdt.core.dom.AST)21 Expression (org.eclipse.jdt.core.dom.Expression)20 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)19 RefactoringASTParser (org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser)19