private RefactoringStatus checkRelatedMethods() throws CoreException { RefactoringStatus result = new RefactoringStatus(); for (Iterator<IMethod> iter = fMethodsToRename.iterator(); iter.hasNext(); ) { IMethod method = iter.next(); result.merge( Checks.checkIfConstructorName( method, getNewElementName(), method.getDeclaringType().getElementName())); String[] msgData = new String[] { BasicElementLabels.getJavaElementName(method.getElementName()), BasicElementLabels.getJavaElementName( method.getDeclaringType().getFullyQualifiedName('.')) }; if (!method.exists()) { result.addFatalError( Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_not_in_model, msgData)); continue; } if (method.isBinary()) result.addFatalError( Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_binary, msgData)); if (method.isReadOnly()) result.addFatalError( Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_read_only, msgData)); if (JdtFlags.isNative(method)) result.addError( Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_native_1, msgData)); } return result; }
@Override public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { RefactoringStatus status = new RefactoringStatus(); try { pm.beginTask("Checking preconditions...", 6); if (mSelectionStart == -1 || mSelectionEnd == -1) { status.addFatalError("No selection to convert"); return status; } // Make sure the selection is contiguous if (mTreeSelection != null) { List<CanvasViewInfo> infos = getSelectedViewInfos(); if (!validateNotEmpty(infos, status)) { return status; } } // Ensures that we have a valid DOM model: if (mElements.size() == 0) { status.addFatalError("Nothing to convert"); return status; } pm.worked(1); return status; } finally { pm.done(); } }
protected static void checkExistence(RefactoringStatus status, Object element) { if (element == null) { status.addFatalError("Workspace Changed"); } else if (element instanceof IResource && !((IResource) element).exists()) { status.addFatalError( StringUtils.format( "Resource %s does not exist", ((IResource) element).getFullPath().toString())); } }
public void checkModificationStamp(RefactoringStatus status, long stampToMatch) { if (fKind == DOCUMENT) { if (stampToMatch != IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP && fModificationStamp != stampToMatch) { status.addFatalError( StringUtils.format("Resource %s has modifications", fResource.getFullPath())); } } else { if (stampToMatch != IResource.NULL_STAMP && fModificationStamp != stampToMatch) { status.addFatalError( StringUtils.format("Resource %s has modifications", fResource.getFullPath())); } } }
/* (non-Javadoc) * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#checkFinalConditions(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext) */ public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException, OperationCanceledException { pm.beginTask("", 1); // $NON-NLS-1$ try { RefactoringStatus result = new RefactoringStatus(); for (int i = 0; i < fResources.length; i++) { IResource resource = fResources[i]; if (!resource.isSynchronized(IResource.DEPTH_INFINITE)) { if (resource instanceof IFile) { result.addInfo( Messages.format( RefactoringCoreMessages.DeleteResourcesProcessor_warning_out_of_sync_file, BasicElementLabels.getPathLabel(resource.getFullPath(), false))); } else { result.addInfo( Messages.format( RefactoringCoreMessages.DeleteResourcesProcessor_warning_out_of_sync_container, BasicElementLabels.getPathLabel(resource.getFullPath(), false))); } } } checkDirtyResources(result); ResourceChangeChecker checker = (ResourceChangeChecker) context.getChecker(ResourceChangeChecker.class); IResourceChangeDescriptionFactory deltaFactory = checker.getDeltaFactory(); for (int i = 0; i < fResources.length; i++) { if (fResources[i].isPhantom()) { result.addFatalError( Messages.format( RefactoringCoreMessages.DeleteResourcesProcessor_delete_error_phantom, BasicElementLabels.getPathLabel(fResources[i].getFullPath(), false))); } else if (fDeleteContents && Resources.isReadOnly(fResources[i])) { result.addFatalError( Messages.format( RefactoringCoreMessages.DeleteResourcesProcessor_delete_error_read_only, BasicElementLabels.getPathLabel(fResources[i].getFullPath(), false))); } else { deltaFactory.delete(fResources[i]); } } return result; } finally { pm.done(); } }
@Override public final RefactoringStatus checkNewElementName(String newName) { Assert.isNotNull(newName, "new name"); // $NON-NLS-1$ RefactoringStatus status = Checks.checkName(newName, JavaConventionsUtil.validateMethodName(newName, fMethod)); if (status.isOK() && !Checks.startsWithLowerCase(newName)) status = RefactoringStatus.createWarningStatus( fIsComposite ? Messages.format( RefactoringCoreMessages.Checks_method_names_lowercase2, new String[] { BasicElementLabels.getJavaElementName(newName), getDeclaringTypeLabel() }) : RefactoringCoreMessages.Checks_method_names_lowercase); if (Checks.isAlreadyNamed(fMethod, newName)) status.addFatalError( fIsComposite ? Messages.format( RefactoringCoreMessages.RenameMethodRefactoring_same_name2, new String[] { BasicElementLabels.getJavaElementName(newName), getDeclaringTypeLabel() }) : RefactoringCoreMessages.RenameMethodRefactoring_same_name, JavaStatusContext.create(fMethod)); return status; }
private RefactoringStatus mappingErrorFound(RefactoringStatus result, ASTNode node) { if (node != null && (node.getFlags() & ASTNode.MALFORMED) != 0 && processCompilerError(result, node)) return result; result.addFatalError(getMappingErrorMessage()); return result; }
@Override protected RefactoringStatus checkConditionsAfterNameSetting(IProgressMonitor pm) { RefactoringStatus status = new RefactoringStatus(); ProjectUtil projectUtil = getProjectUtil(); newFileName = projectUtil.appendFileExtension(info.getNewName()); NesCComponentNameCollissionDetector detector = new NesCComponentNameCollissionDetector(); detector.handleCollisions4NewFileName( newFileName, declaringIdentifier, declaringFile, getProjectUtil(), status, pm); try { // Handle Collisions in affected configurations. for (IFile file : affectedIdentifiers.keySet()) { if (!declaringFile.equals(file)) { // The component itself cannot reference itself. AstAnalyzerFactory factory = new AstAnalyzerFactory(file, projectUtil, pm); if (factory .hasConfigurationAnalyzerCreated()) { // Only configurations can reference other // modules. detector.handleCollisions4NewComponentNameWithConfigurationLocalName( factory.getConfigurationAnalyzer(), file, info.getOldName(), info.getNewName(), status); } } } } catch (Exception e) { status.addFatalError( "Exception during condition checking. See project log for more information."); projectUtil.log("Exception during condition checking.", e); } return status; }
private boolean processCompilerError(RefactoringStatus result, ASTNode node) { Message[] messages = ASTNodes.getMessages(node, ASTNodes.INCLUDE_ALL_PARENTS); if (messages.length == 0) return false; result.addFatalError( Messages.format( "Compiler errors with the class to be refactored", new String[] {targetClass.getElementName(), messages[0].getMessage()})); return true; }
private RefactoringStatus validateMethodName() { RefactoringStatus result = new RefactoringStatus(); String text = getText(); if ("".equals(text)) { // $NON-NLS-1$ result.addFatalError(RefactoringMessages.ExtractMethodInputPage_validation_emptyMethodName); return result; } result.merge(fRefactoring.checkMethodName()); return result; }
private void checkExpression(RefactoringStatus status) { ASTNode[] nodes = getSelectedNodes(); if (nodes != null && nodes.length == 1) { ASTNode node = nodes[0]; if (node instanceof Type) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_type_reference, JavaStatusContext.create(fCUnit, node)); } else if (node.getLocationInParent() == SwitchCase.EXPRESSION_PROPERTY) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_switch_case, JavaStatusContext.create(fCUnit, node)); } else if (node instanceof Annotation || ASTNodes.getParent(node, Annotation.class) != null) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_from_annotation, JavaStatusContext.create(fCUnit, node)); } } }
private static SourceProvider resolveSourceProvider( RefactoringStatus status, ITypeRoot typeRoot, ASTNode invocation) { CompilationUnit root = (CompilationUnit) invocation.getRoot(); IMethodBinding methodBinding = Invocations.resolveBinding(invocation); if (methodBinding == null) { status.addFatalError( RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration); return null; } MethodDeclaration declaration = (MethodDeclaration) root.findDeclaringNode(methodBinding); if (declaration != null) { return new SourceProvider(typeRoot, declaration); } IMethod method = (IMethod) methodBinding.getJavaElement(); if (method != null) { CompilationUnit methodDeclarationAstRoot; ICompilationUnit methodCu = method.getCompilationUnit(); if (methodCu != null) { methodDeclarationAstRoot = new RefactoringASTParser(AST.JLS3).parse(methodCu, true); } else { IClassFile classFile = method.getClassFile(); if (!JavaElementUtil.isSourceAvailable(classFile)) { String methodLabel = JavaElementLabels.getTextLabel( method, JavaElementLabels.M_FULLY_QUALIFIED | JavaElementLabels.M_PARAMETER_TYPES); status.addFatalError( Messages.format( RefactoringCoreMessages.InlineMethodRefactoring_error_classFile, methodLabel)); return null; } methodDeclarationAstRoot = new RefactoringASTParser(AST.JLS3).parse(classFile, true); } ASTNode node = methodDeclarationAstRoot.findDeclaringNode(methodBinding.getMethodDeclaration().getKey()); if (node instanceof MethodDeclaration) { return new SourceProvider(methodDeclarationAstRoot.getTypeRoot(), (MethodDeclaration) node); } } status.addFatalError(RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration); return null; }
public RefactoringStatus checkInitialConditions(ImportRewrite rewriter) { RefactoringStatus result = getStatus(); checkExpression(result); if (result.hasFatalError()) return result; List<ASTNode> validDestinations = new ArrayList<>(); ASTNode destination = ASTResolving.findParentType(fEnclosingBodyDeclaration.getParent()); while (destination != null) { if (isValidDestination(destination)) { validDestinations.add(destination); } destination = ASTResolving.findParentType(destination.getParent()); } if (validDestinations.size() == 0) { result.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_no_valid_destination_type); return result; } fReturnKind = UNDEFINED; fMaxVariableId = LocalVariableIndex.perform(fEnclosingBodyDeclaration); if (analyzeSelection(result).hasFatalError()) return result; int returns = fReturnKind == NO ? 0 : 1; if (fReturnValue != null) { fReturnKind = ACCESS_TO_LOCAL; returns++; } if (isExpressionSelected()) { fReturnKind = EXPRESSION; returns++; } if (returns > 1) { result.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_ambiguous_return_value, JavaStatusContext.create(fCUnit, getSelection())); fReturnKind = MULTIPLE; return result; } initReturnType(rewriter); return result; }
@Override public RefactoringStatus initializeRefactoring(IProgressMonitor pm) { RefactoringStatus ret = new RefactoringStatus(); ProjectUtil projectUtil = getProjectUtil(); try { if (!isApplicable()) { ret.addFatalError("The Refactoring is no Accessable"); } if (!findComponentDefinition(ret)) { return ret; } declaringFile = getIFile4ParseFile(componentDefinition.getParseFile()); affectedIdentifiers = gatherAffectedIdentifiers(pm); } catch (Exception e) { ret.addFatalError("Exception during initialization. See project log for more information."); projectUtil.log("Exception during initialization.", e); } return ret; }
public void checkDirty(RefactoringStatus status, long stampToMatch, IProgressMonitor pm) throws CoreException { if (fDirty) { if (fKind == DOCUMENT && fTextFileBuffer != null && stampToMatch == fModificationStamp) { fTextFileBuffer.commit(pm, false); } else { status.addFatalError( StringUtils.format("Resource %s is unsaved", fResource.getFullPath())); } } }
private RefactoringStatus validateParameters() { RefactoringStatus result = new RefactoringStatus(); for (ParameterInfo parameter : fRefactoring.getParameters()) { if ("".equals(parameter.getNewName())) { result.addFatalError( RefactoringMessages.ExtractMethodInputPage_validation_emptyParameterName); return result; } } result.merge(fRefactoring.checkParameterNames()); return result; }
/** * Find the component definition. If couldnt find fatalError is addet to Refactoringstatus. * * @return false if couldnt find definition, true otherwise. * @param ret * @throws CoreException * @throws MissingNatureException */ private boolean findComponentDefinition(RefactoringStatus ret) throws CoreException, MissingNatureException { Identifier selectedIdentifier = getSelectedIdentifier(); ComponentSelectionIdentifier selectionIdentifier = new ComponentSelectionIdentifier(selectedIdentifier); if (!selectionIdentifier.isComponent()) { ret.addFatalError("No Component selected."); return false; } componentDefinition = getProjectUtil().getComponentDefinition(selectedIdentifier.getName()); if (componentDefinition == null) { ret.addFatalError( "Did not find an component Definition, for selection: " + selectedIdentifier.getName() + "!"); return false; } else if (!componentDefinition.getParseFile().isProjectFile()) { ret.addFatalError("Component definition is out of project range!"); return false; } return true; }
private void checkDirtyFile(RefactoringStatus result, IFile file) { if (!file.exists()) return; ITextFileBuffer buffer = FileBuffers.getTextFileBufferManager() .getTextFileBuffer(file.getFullPath(), LocationKind.IFILE); if (buffer != null && buffer.isDirty()) { String message = RefactoringCoreMessages.DeleteResourcesProcessor_warning_unsaved_file; if (buffer.isStateValidated() && buffer.isSynchronized()) { result.addWarning( Messages.format(message, BasicElementLabels.getPathLabel(file.getFullPath(), false))); } else { result.addFatalError( Messages.format(message, BasicElementLabels.getPathLabel(file.getFullPath(), false))); } } }
private RefactoringStatus analyzeSelection(RefactoringStatus status) { fInputFlowContext = new FlowContext(0, fMaxVariableId + 1); fInputFlowContext.setConsiderAccessMode(true); fInputFlowContext.setComputeMode(FlowContext.ARGUMENTS); InOutFlowAnalyzer flowAnalyzer = new InOutFlowAnalyzer(fInputFlowContext); fInputFlowInfo = flowAnalyzer.perform(getSelectedNodes()); if (fInputFlowInfo.branches()) { String canHandleBranchesProblem = canHandleBranches(); if (canHandleBranchesProblem != null) { status.addFatalError( canHandleBranchesProblem, JavaStatusContext.create(fCUnit, getSelection())); fReturnKind = ERROR; return status; } } if (fInputFlowInfo.isValueReturn()) { fReturnKind = RETURN_STATEMENT_VALUE; } else if (fInputFlowInfo.isVoidReturn() || (fInputFlowInfo.isPartialReturn() && isVoidMethod() && isLastStatementSelected())) { fReturnKind = RETURN_STATEMENT_VOID; } else if (fInputFlowInfo.isNoReturn() || fInputFlowInfo.isThrow() || fInputFlowInfo.isUndefined()) { fReturnKind = NO; } if (fReturnKind == UNDEFINED) { status.addError( RefactoringCoreMessages.FlowAnalyzer_execution_flow, JavaStatusContext.create(fCUnit, getSelection())); fReturnKind = NO; } computeInput(); computeExceptions(); computeOutput(status); if (status.hasFatalError()) return status; adjustArgumentsAndMethodLocals(); compressArrays(); return status; }
/* * (non-Javadoc) * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#checkInitialConditions(org.eclipse.core.runtime.IProgressMonitor) */ @Override public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { RefactoringStatus result = new RefactoringStatus(); boolean status = false; component = checkComponent(); if (component == null) { status = checkContextVariable(); } else { setOldName(component.getName()); } if (component == null && !status) result.addFatalError( Messages.format( SeamCoreMessages.RENAME_SEAM_CONTEXT_VARIABLE_PROCESSOR_CAN_NOT_FIND_CONTEXT_VARIABLE, getOldName())); return result; }
@Override RefactoringStatus checkFinalConditions( final IProgressMonitor pm, final CheckConditionsContext ctxt) { RefactoringStatus result = new RefactoringStatus(); try { pm.beginTask(UITexts.refDelegate_checking, 100); if (ctxt != null) { IConditionChecker checker = ctxt.getChecker(ValidateEditChecker.class); ValidateEditChecker editChecker = (ValidateEditChecker) checker; editChecker.addFile(info.getSourceFile()); } change = createRenameChange(pm); if (change == null) { result.addFatalError(UITexts.mkPointFreeDelegate_notApplicable); } } finally { pm.done(); } return result; }
@Override public void endVisit(CompilationUnit node) { RefactoringStatus status = getStatus(); superCall: { if (status.hasFatalError()) break superCall; if (!hasSelectedNodes()) { ASTNode coveringNode = getLastCoveringNode(); if (coveringNode instanceof Block && coveringNode.getParent() instanceof MethodDeclaration) { MethodDeclaration methodDecl = (MethodDeclaration) coveringNode.getParent(); Message[] messages = ASTNodes.getMessages(methodDecl, ASTNodes.NODE_ONLY); if (messages.length > 0) { status.addFatalError( Messages.format( RefactoringCoreMessages.ExtractMethodAnalyzer_compile_errors, BasicElementLabels.getJavaElementName(methodDecl.getName().getIdentifier())), JavaStatusContext.create(fCUnit, methodDecl)); break superCall; } } status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_invalid_selection); break superCall; } fEnclosingBodyDeclaration = (BodyDeclaration) ASTNodes.getParent(getFirstSelectedNode(), BodyDeclaration.class); if (fEnclosingBodyDeclaration == null || (fEnclosingBodyDeclaration.getNodeType() != ASTNode.METHOD_DECLARATION && fEnclosingBodyDeclaration.getNodeType() != ASTNode.FIELD_DECLARATION && fEnclosingBodyDeclaration.getNodeType() != ASTNode.INITIALIZER)) { status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_invalid_selection); break superCall; } else if (ASTNodes.getEnclosingType(fEnclosingBodyDeclaration) == null) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_compile_errors_no_parent_binding); break superCall; } else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) { fEnclosingMethodBinding = ((MethodDeclaration) fEnclosingBodyDeclaration).resolveBinding(); } if (!isSingleExpressionOrStatementSet()) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_single_expression_or_set); break superCall; } if (isExpressionSelected()) { ASTNode expression = getFirstSelectedNode(); if (expression instanceof Name) { Name name = (Name) expression; if (name.resolveBinding() instanceof ITypeBinding) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_type_reference); break superCall; } if (name.resolveBinding() instanceof IMethodBinding) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_method_name_reference); break superCall; } if (name.resolveBinding() instanceof IVariableBinding) { StructuralPropertyDescriptor locationInParent = name.getLocationInParent(); if (locationInParent == QualifiedName.NAME_PROPERTY || (locationInParent == FieldAccess.NAME_PROPERTY && !(((FieldAccess) name.getParent()).getExpression() instanceof ThisExpression))) { status.addFatalError( RefactoringCoreMessages .ExtractMethodAnalyzer_cannot_extract_part_of_qualified_name); break superCall; } } if (name.isSimpleName() && ((SimpleName) name).isDeclaration()) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_name_in_declaration); break superCall; } } fForceStatic = ASTNodes.getParent(expression, ASTNode.SUPER_CONSTRUCTOR_INVOCATION) != null || ASTNodes.getParent(expression, ASTNode.CONSTRUCTOR_INVOCATION) != null; } status.merge(LocalTypeAnalyzer.perform(fEnclosingBodyDeclaration, getSelection())); computeLastStatementSelected(); } super.endVisit(node); }
private void computeOutput(RefactoringStatus status) { // First find all writes inside the selection. FlowContext flowContext = new FlowContext(0, fMaxVariableId + 1); flowContext.setConsiderAccessMode(true); flowContext.setComputeMode(FlowContext.RETURN_VALUES); FlowInfo returnInfo = new InOutFlowAnalyzer(flowContext).perform(getSelectedNodes()); IVariableBinding[] returnValues = returnInfo.get(flowContext, FlowInfo.WRITE | FlowInfo.WRITE_POTENTIAL | FlowInfo.UNKNOWN); // Compute a selection that exactly covers the selected nodes IRegion region = getSelectedNodeRange(); Selection selection = Selection.createFromStartLength(region.getOffset(), region.getLength()); List<IVariableBinding> localReads = new ArrayList<>(); flowContext.setComputeMode(FlowContext.ARGUMENTS); FlowInfo argInfo = new InputFlowAnalyzer(flowContext, selection, true).perform(fEnclosingBodyDeclaration); IVariableBinding[] reads = argInfo.get(flowContext, FlowInfo.READ | FlowInfo.READ_POTENTIAL | FlowInfo.UNKNOWN); outer: for (int i = 0; i < returnValues.length && localReads.size() < returnValues.length; i++) { IVariableBinding binding = returnValues[i]; for (int x = 0; x < reads.length; x++) { if (reads[x] == binding) { localReads.add(binding); fReturnValue = binding; continue outer; } } } switch (localReads.size()) { case 0: fReturnValue = null; break; case 1: break; default: fReturnValue = null; StringBuffer affectedLocals = new StringBuffer(); for (int i = 0; i < localReads.size(); i++) { IVariableBinding binding = localReads.get(i); String bindingName = BindingLabelProvider.getBindingLabel( binding, BindingLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_PRE_TYPE_SIGNATURE); affectedLocals.append(bindingName); if (i != localReads.size() - 1) { affectedLocals.append('\n'); } } String message = MessageFormat.format( RefactoringCoreMessages.ExtractMethodAnalyzer_assignments_to_local, new Object[] {affectedLocals.toString()}); status.addFatalError(message, JavaStatusContext.create(fCUnit, getSelection())); return; } List<IVariableBinding> callerLocals = new ArrayList<>(5); FlowInfo localInfo = new InputFlowAnalyzer(flowContext, selection, false).perform(fEnclosingBodyDeclaration); IVariableBinding[] writes = localInfo.get(flowContext, FlowInfo.WRITE | FlowInfo.WRITE_POTENTIAL | FlowInfo.UNKNOWN); for (int i = 0; i < writes.length; i++) { IVariableBinding write = writes[i]; if (getSelection().covers(ASTNodes.findDeclaration(write, fEnclosingBodyDeclaration))) callerLocals.add(write); } fCallerLocals = callerLocals.toArray(new IVariableBinding[callerLocals.size()]); if (fReturnValue != null && getSelection().covers(ASTNodes.findDeclaration(fReturnValue, fEnclosingBodyDeclaration))) fReturnLocal = fReturnValue; }
@Override protected RefactoringStatus doCheckFinalConditions( IProgressMonitor pm, CheckConditionsContext context) throws CoreException { try { RefactoringStatus result = new RefactoringStatus(); pm.beginTask("", 9); // $NON-NLS-1$ // TODO workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=40367 if (!Checks.isAvailable(fMethod)) { result.addFatalError( RefactoringCoreMessages.RenameMethodProcessor_is_binary, JavaStatusContext.create(fMethod)); return result; } result.merge(Checks.checkIfCuBroken(fMethod)); if (result.hasFatalError()) return result; pm.setTaskName( RefactoringCoreMessages.RenameMethodRefactoring_taskName_checkingPreconditions); result.merge(checkNewElementName(getNewElementName())); if (result.hasFatalError()) return result; boolean mustAnalyzeShadowing; IMethod[] newNameMethods = searchForDeclarationsOfClashingMethods(new SubProgressMonitor(pm, 1)); if (newNameMethods.length == 0) { mustAnalyzeShadowing = false; pm.worked(1); } else { IType[] outerTypes = searchForOuterTypesOfReferences(newNameMethods, new SubProgressMonitor(pm, 1)); if (outerTypes.length > 0) { // There exists a reference to a clashing method, where the reference is in a nested type. // That nested type could be a type in a ripple method's hierarchy, which could // cause the reference to bind to the new ripple method instead of to // its old binding (a method of an enclosing scope). // -> Getting *more* references than before -> Semantics not preserved. // Examples: RenameVirtualMethodInClassTests#testFail39() and #testFail41() // TODO: could pass declaringTypes to the RippleMethodFinder and check whether // a hierarchy contains one of outerTypes (or an outer type of an outerType, recursively). mustAnalyzeShadowing = true; } else { boolean hasOldRefsInInnerTypes = true; // TODO: to implement this optimization: // - move search for references to before this check. // - collect references in inner types. // - for each reference, check for all supertypes and their enclosing types // (recursively), whether they declare a rippleMethod if (hasOldRefsInInnerTypes) { // There exists a reference to a ripple method in a nested type // of a type in the hierarchy of any ripple method. // When that reference is renamed, and one of the supertypes of the // nested type declared a method matching the new name, then // the renamed reference will bind to the method in its supertype, // since inherited methods bind stronger than methods from enclosing scopes. // Getting *less* references than before -> Semantics not preserved. // Examples: RenamePrivateMethodTests#testFail2(), RenamePrivateMethodTests#testFail5() mustAnalyzeShadowing = true; } else { mustAnalyzeShadowing = false; } } } String binaryRefsDescription = Messages.format( RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description, BasicElementLabels.getJavaElementName(getCurrentElementName())); ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription); initializeMethodsToRename(new SubProgressMonitor(pm, 1), binaryRefs); pm.setTaskName( RefactoringCoreMessages.RenameMethodRefactoring_taskName_searchingForReferences); fOccurrences = getOccurrences(new SubProgressMonitor(pm, 3), result, binaryRefs); binaryRefs.addErrorIfNecessary(result); pm.setTaskName( RefactoringCoreMessages.RenameMethodRefactoring_taskName_checkingPreconditions); if (fUpdateReferences) result.merge(checkRelatedMethods()); result.merge(analyzeCompilationUnits()); // removes CUs with syntax errors pm.worked(1); if (result.hasFatalError()) return result; createChanges(new SubProgressMonitor(pm, 1), result); if (fUpdateReferences & mustAnalyzeShadowing) result.merge(analyzeRenameChanges(new SubProgressMonitor(pm, 1))); else pm.worked(1); return result; } finally { pm.done(); } }
/** * Fills {@link #parameters} with information about used variables, which should be turned into * parameters. */ private RefactoringStatus initializeParameters() { RefactoringStatus result = new RefactoringStatus(); final List<VariableElement> assignedUsedVariables = Lists.newArrayList(); unitNode.accept( new ASTVisitor<Void>() { @Override public Void visitIdentifier(DartIdentifier node) { SourceRange nodeRange = SourceRangeFactory.create(node); if (SourceRangeUtils.covers(selectionRange, nodeRange)) { // analyze local variable VariableElement variableElement = ASTNodes.getVariableOrParameterElement(node); if (variableElement != null) { // if declared outside, add parameter if (!isDeclaredInSelection(variableElement)) { String variableName = variableElement.getName(); // add parameter if (!selectionParametersToRanges.containsKey(variableName)) { parameters.add(new ParameterInfo(variableElement)); } // add reference to parameter { List<SourceRange> ranges = selectionParametersToRanges.get(variableName); if (ranges == null) { ranges = Lists.newArrayList(); selectionParametersToRanges.put(variableName, ranges); } ranges.add(nodeRange); } } // remember, if assigned and used after seleciton if (isLeftHandOfAssignment(node) && isUsedAfterSelection(variableElement)) { if (!assignedUsedVariables.contains(variableElement)) { assignedUsedVariables.add(variableElement); } } } // remember declaration names if (ASTNodes.isNameOfDeclaration(node)) { usedNames.add(node.getName()); } } return null; } }); // may be single variable to return if (assignedUsedVariables.size() == 1) { returnVariable = assignedUsedVariables.get(0); } // fatal, if multiple variables assigned and used after selection if (assignedUsedVariables.size() > 1) { StringBuilder sb = new StringBuilder(); for (VariableElement variable : assignedUsedVariables) { sb.append(variable.getName()); sb.append("\n"); } result.addFatalError( Messages.format( RefactoringCoreMessages.ExtractMethodAnalyzer_assignments_to_local, sb.toString().trim())); } // done return result; }
public void checkSameReadOnly(RefactoringStatus status, boolean valueToMatch) { if (fReadOnly != valueToMatch) { status.addFatalError( StringUtils.format("Resource %s (Change_same_read_only)", fResource.getFullPath())); } }
public void checkReadOnly(RefactoringStatus status) { if (fReadOnly) { status.addFatalError( StringUtils.format("Resource %s is read-only", fResource.getFullPath())); } }
public void checkDirty(RefactoringStatus status) { if (fDirty) { status.addFatalError(StringUtils.format("Resource %s is unsaved", fResource.getFullPath())); } }