Search in sources :

Example 1 with ILocalVariable

use of org.eclipse.jdt.core.ILocalVariable 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 2 with ILocalVariable

use of org.eclipse.jdt.core.ILocalVariable in project che by eclipse.

the class RenameTypeProcessor method initializeReferences.

/**
	 * Initializes the references to the type and the similarly named elements. This
	 * method creates both the fReferences and the fPreloadedElementToName
	 * fields.
	 *
	 * May be called from the UI.
	 * @param monitor progress monitor
	 * @return initialization status
	 * @throws JavaModelException some fundamental error with the underlying model
	 * @throws OperationCanceledException if user canceled the task
	 *
	 */
public RefactoringStatus initializeReferences(IProgressMonitor monitor) throws JavaModelException, OperationCanceledException {
    Assert.isNotNull(fType);
    Assert.isNotNull(getNewElementName());
    if (fReferences != null && (getNewElementName().equals(fCachedNewName)) && (fCachedRenameSimilarElements == getUpdateSimilarDeclarations()) && (fCachedRenamingStrategy == fRenamingStrategy))
        return fCachedRefactoringStatus;
    fCachedNewName = getNewElementName();
    fCachedRenameSimilarElements = fUpdateSimilarElements;
    fCachedRenamingStrategy = fRenamingStrategy;
    fCachedRefactoringStatus = new RefactoringStatus();
    try {
        SearchPattern pattern = SearchPattern.createPattern(fType, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
        String binaryRefsDescription = Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description, BasicElementLabels.getJavaElementName(fType.getElementName()));
        ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription);
        fReferences = RefactoringSearchEngine.search(pattern, RefactoringScopeFactory.create(fType, true, false), new TypeOccurrenceCollector(fType, binaryRefs), monitor, fCachedRefactoringStatus);
        binaryRefs.addErrorIfNecessary(fCachedRefactoringStatus);
        fReferences = Checks.excludeCompilationUnits(fReferences, fCachedRefactoringStatus);
        fPreloadedElementToName = new LinkedHashMap<IJavaElement, String>();
        fPreloadedElementToSelection = new HashMap<IJavaElement, Boolean>();
        final String unQualifiedTypeName = fType.getElementName();
        //$NON-NLS-1$
        monitor.beginTask("", fReferences.length);
        if (getUpdateSimilarDeclarations()) {
            RenamingNameSuggestor sugg = new RenamingNameSuggestor(fRenamingStrategy);
            for (int i = 0; i < fReferences.length; i++) {
                final ICompilationUnit cu = fReferences[i].getCompilationUnit();
                if (cu == null)
                    continue;
                final SearchMatch[] results = fReferences[i].getSearchResults();
                for (int j = 0; j < results.length; j++) {
                    if (!(results[j] instanceof TypeReferenceMatch))
                        continue;
                    final TypeReferenceMatch match = (TypeReferenceMatch) results[j];
                    final List<IJavaElement> matches = new ArrayList<IJavaElement>();
                    if (match.getLocalElement() != null) {
                        if (match.getLocalElement() instanceof ILocalVariable) {
                            matches.add(match.getLocalElement());
                        }
                    // else don't update (e.g. match in type parameter, annotation, ...)
                    } else {
                        matches.add((IJavaElement) match.getElement());
                    }
                    final IJavaElement[] others = match.getOtherElements();
                    if (others != null)
                        matches.addAll(Arrays.asList(others));
                    for (Iterator<IJavaElement> iter = matches.iterator(); iter.hasNext(); ) {
                        final IJavaElement element = iter.next();
                        if (!(element instanceof IMethod) && !(element instanceof IField) && !(element instanceof ILocalVariable))
                            continue;
                        if (!isInDeclaredType(match.getOffset(), element))
                            continue;
                        if (element instanceof IField) {
                            final IField currentField = (IField) element;
                            final String newFieldName = sugg.suggestNewFieldName(currentField.getJavaProject(), currentField.getElementName(), Flags.isStatic(currentField.getFlags()), unQualifiedTypeName, getNewElementName());
                            if (newFieldName != null)
                                fPreloadedElementToName.put(currentField, newFieldName);
                        } else if (element instanceof IMethod) {
                            final IMethod currentMethod = (IMethod) element;
                            addMethodRename(unQualifiedTypeName, sugg, currentMethod);
                        } else if (element instanceof ILocalVariable) {
                            final ILocalVariable currentLocal = (ILocalVariable) element;
                            final boolean isParameter;
                            if (currentLocal.isParameter()) {
                                addMethodRename(unQualifiedTypeName, sugg, (IMethod) currentLocal.getParent());
                                isParameter = true;
                            } else
                                isParameter = false;
                            final String newLocalName = sugg.suggestNewLocalName(currentLocal.getJavaProject(), currentLocal.getElementName(), isParameter, unQualifiedTypeName, getNewElementName());
                            if (newLocalName != null)
                                fPreloadedElementToName.put(currentLocal, newLocalName);
                        }
                    }
                }
                if (monitor.isCanceled())
                    throw new OperationCanceledException();
            }
        }
        for (Iterator<IJavaElement> iter = fPreloadedElementToName.keySet().iterator(); iter.hasNext(); ) {
            IJavaElement element = iter.next();
            fPreloadedElementToSelection.put(element, Boolean.TRUE);
        }
        fPreloadedElementToNameDefault = new LinkedHashMap<IJavaElement, String>(fPreloadedElementToName);
    } catch (OperationCanceledException e) {
        fReferences = null;
        fPreloadedElementToName = null;
        throw new OperationCanceledException();
    }
    return fCachedRefactoringStatus;
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IField(org.eclipse.jdt.core.IField) ILocalVariable(org.eclipse.jdt.core.ILocalVariable) ReferencesInBinaryContext(org.eclipse.jdt.internal.corext.refactoring.base.ReferencesInBinaryContext) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) IMethod(org.eclipse.jdt.core.IMethod) TypeReferenceMatch(org.eclipse.jdt.core.search.TypeReferenceMatch)

Example 3 with ILocalVariable

use of org.eclipse.jdt.core.ILocalVariable in project che by eclipse.

the class RenameLocalVariableProcessor method initialize.

private RefactoringStatus initialize(JavaRefactoringArguments extended) {
    final String handle = extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT);
    if (handle != null) {
        final IJavaElement element = JavaRefactoringDescriptorUtil.handleToElement(extended.getProject(), handle, false);
        if (element != null && element.exists()) {
            if (element.getElementType() == IJavaElement.COMPILATION_UNIT) {
                fCu = (ICompilationUnit) element;
            } else if (element.getElementType() == IJavaElement.LOCAL_VARIABLE) {
                fLocalVariable = (ILocalVariable) element;
                fCu = (ICompilationUnit) fLocalVariable.getAncestor(IJavaElement.COMPILATION_UNIT);
                if (fCu == null)
                    return JavaRefactoringDescriptorUtil.createInputFatalStatus(element, getProcessorName(), IJavaRefactorings.RENAME_LOCAL_VARIABLE);
            } else
                return JavaRefactoringDescriptorUtil.createInputFatalStatus(element, getProcessorName(), IJavaRefactorings.RENAME_LOCAL_VARIABLE);
        } else
            return JavaRefactoringDescriptorUtil.createInputFatalStatus(element, getProcessorName(), IJavaRefactorings.RENAME_LOCAL_VARIABLE);
    } else
        return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT));
    final String name = extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME);
    if (//$NON-NLS-1$
    name != null && !"".equals(name))
        setNewElementName(name);
    else
        return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME));
    if (fCu != null && fLocalVariable == null) {
        final String selection = extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION);
        if (selection != null) {
            int offset = -1;
            int length = -1;
            final StringTokenizer tokenizer = new StringTokenizer(selection);
            if (tokenizer.hasMoreTokens())
                offset = Integer.valueOf(tokenizer.nextToken()).intValue();
            if (tokenizer.hasMoreTokens())
                length = Integer.valueOf(tokenizer.nextToken()).intValue();
            if (offset >= 0 && length >= 0) {
                try {
                    final IJavaElement[] elements = fCu.codeSelect(offset, length);
                    if (elements != null) {
                        for (int index = 0; index < elements.length; index++) {
                            final IJavaElement element = elements[index];
                            if (element instanceof ILocalVariable)
                                fLocalVariable = (ILocalVariable) element;
                        }
                    }
                    if (fLocalVariable == null)
                        return JavaRefactoringDescriptorUtil.createInputFatalStatus(null, getProcessorName(), IJavaRefactorings.RENAME_LOCAL_VARIABLE);
                } catch (JavaModelException exception) {
                    JavaPlugin.log(exception);
                }
            } else
                return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { selection, JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION }));
        } else
            return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION));
    }
    final String references = extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_REFERENCES);
    if (references != null) {
        fUpdateReferences = Boolean.valueOf(references).booleanValue();
    } else
        return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JavaRefactoringDescriptorUtil.ATTRIBUTE_REFERENCES));
    return new RefactoringStatus();
}
Also used : ILocalVariable(org.eclipse.jdt.core.ILocalVariable) IJavaElement(org.eclipse.jdt.core.IJavaElement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) StringTokenizer(java.util.StringTokenizer) JavaModelException(org.eclipse.jdt.core.JavaModelException) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus)

Example 4 with ILocalVariable

use of org.eclipse.jdt.core.ILocalVariable in project che by eclipse.

the class RenameTypeTest method checkMappedSimilarElementsExist.

private void checkMappedSimilarElementsExist(Refactoring ref) {
    RenameTypeProcessor rtp = (RenameTypeProcessor) ((RenameRefactoring) ref).getProcessor();
    IJavaElementMapper mapper = (IJavaElementMapper) rtp.getAdapter(IJavaElementMapper.class);
    IJavaElement[] similarElements = rtp.getSimilarElements();
    if (similarElements == null)
        return;
    for (int i = 0; i < similarElements.length; i++) {
        IJavaElement element = similarElements[i];
        if (!(element instanceof ILocalVariable)) {
            IJavaElement newElement = mapper.getRefactoredJavaElement(element);
            TestCase.assertTrue(newElement.exists());
            Assert.assertFalse(element.exists());
        }
    }
}
Also used : ILocalVariable(org.eclipse.jdt.core.ILocalVariable) IJavaElement(org.eclipse.jdt.core.IJavaElement) RenameTypeProcessor(org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor) IJavaElementMapper(org.eclipse.jdt.core.refactoring.IJavaElementMapper)

Example 5 with ILocalVariable

use of org.eclipse.jdt.core.ILocalVariable in project che by eclipse.

the class JavaElementImageProvider method computeJavaAdornmentFlags.

// ---- Methods to compute the adornments flags ---------------------------------
private int computeJavaAdornmentFlags(IJavaElement element, int renderFlags) {
    int flags = 0;
    if (showOverlayIcons(renderFlags)) {
        try {
            if (element instanceof IMember) {
                IMember member = (IMember) element;
                int modifiers = member.getFlags();
                if (confirmAbstract(member) && JdtFlags.isAbstract(member))
                    flags |= JavaElementImageDescriptor.ABSTRACT;
                if (Flags.isFinal(modifiers) || isInterfaceOrAnnotationField(member) || isEnumConstant(member, modifiers))
                    flags |= JavaElementImageDescriptor.FINAL;
                if (Flags.isStatic(modifiers) || isInterfaceOrAnnotationFieldOrType(member) || isEnumConstant(member, modifiers))
                    flags |= JavaElementImageDescriptor.STATIC;
                if (Flags.isDeprecated(modifiers))
                    flags |= JavaElementImageDescriptor.DEPRECATED;
                int elementType = element.getElementType();
                if (elementType == IJavaElement.METHOD) {
                    if (((IMethod) element).isConstructor())
                        flags |= JavaElementImageDescriptor.CONSTRUCTOR;
                    if (// collides with 'super' flag
                    Flags.isSynchronized(modifiers))
                        flags |= JavaElementImageDescriptor.SYNCHRONIZED;
                    if (Flags.isNative(modifiers))
                        flags |= JavaElementImageDescriptor.NATIVE;
                    if (Flags.isDefaultMethod(modifiers))
                        flags |= JavaElementImageDescriptor.DEFAULT_METHOD;
                    if (Flags.isAnnnotationDefault(modifiers))
                        flags |= JavaElementImageDescriptor.ANNOTATION_DEFAULT;
                }
                if (member.getElementType() == IJavaElement.TYPE) {
                    if (JavaModelUtil.hasMainMethod((IType) member)) {
                        flags |= JavaElementImageDescriptor.RUNNABLE;
                    }
                }
                if (member.getElementType() == IJavaElement.FIELD) {
                    if (Flags.isVolatile(modifiers))
                        flags |= JavaElementImageDescriptor.VOLATILE;
                    if (Flags.isTransient(modifiers))
                        flags |= JavaElementImageDescriptor.TRANSIENT;
                }
            } else if (element instanceof ILocalVariable && Flags.isFinal(((ILocalVariable) element).getFlags())) {
                flags |= JavaElementImageDescriptor.FINAL;
            }
        } catch (JavaModelException e) {
        // do nothing. Can't compute runnable adornment or get flags
        }
    }
    return flags;
}
Also used : ILocalVariable(org.eclipse.jdt.core.ILocalVariable) JavaModelException(org.eclipse.jdt.core.JavaModelException) IMethod(org.eclipse.jdt.core.IMethod) IMember(org.eclipse.jdt.core.IMember) Point(org.eclipse.swt.graphics.Point)

Aggregations

ILocalVariable (org.eclipse.jdt.core.ILocalVariable)11 IJavaElement (org.eclipse.jdt.core.IJavaElement)6 IMethod (org.eclipse.jdt.core.IMethod)6 IField (org.eclipse.jdt.core.IField)5 JavaModelException (org.eclipse.jdt.core.JavaModelException)4 ArrayList (java.util.ArrayList)3 BindingKey (org.eclipse.jdt.core.BindingKey)3 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)3 IType (org.eclipse.jdt.core.IType)3 RefactoringStatus (org.eclipse.ltk.core.refactoring.RefactoringStatus)3 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)2 IMember (org.eclipse.jdt.core.IMember)2 HashSet (java.util.HashSet)1 StringTokenizer (java.util.StringTokenizer)1 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)1 IAnnotation (org.eclipse.jdt.core.IAnnotation)1 IJavaProject (org.eclipse.jdt.core.IJavaProject)1 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)1 ITypeHierarchy (org.eclipse.jdt.core.ITypeHierarchy)1 ITypeParameter (org.eclipse.jdt.core.ITypeParameter)1