private ICompilationUnit[] getDeclarationCUs() { Set<ICompilationUnit> cus = new HashSet<>(); for (Iterator<IMethod> iter = fMethodsToRename.iterator(); iter.hasNext(); ) { IMethod method = iter.next(); cus.add(method.getCompilationUnit()); } return cus.toArray(new ICompilationUnit[cus.size()]); }
private RefactoringStatus analyzeRenameChanges(IProgressMonitor pm) throws CoreException { ICompilationUnit[] newDeclarationWCs = null; try { pm.beginTask("", 4); // $NON-NLS-1$ RefactoringStatus result = new RefactoringStatus(); ICompilationUnit[] declarationCUs = getDeclarationCUs(); newDeclarationWCs = RenameAnalyzeUtil.createNewWorkingCopies( declarationCUs, fChangeManager, fWorkingCopyOwner, new SubProgressMonitor(pm, 1)); IMethod[] wcOldMethods = new IMethod[fMethodsToRename.size()]; IMethod[] wcNewMethods = new IMethod[fMethodsToRename.size()]; int i = 0; for (Iterator<IMethod> iter = fMethodsToRename.iterator(); iter.hasNext(); i++) { IMethod method = iter.next(); ICompilationUnit newCu = RenameAnalyzeUtil.findWorkingCopyForCu(newDeclarationWCs, method.getCompilationUnit()); IType typeWc = (IType) JavaModelUtil.findInCompilationUnit(newCu, method.getDeclaringType()); if (typeWc == null) { // should not happen i--; wcOldMethods = CollectionsUtil.toArray( Arrays.asList(wcOldMethods).subList(0, wcOldMethods.length - 1), IMethod.class); wcNewMethods = CollectionsUtil.toArray( Arrays.asList(wcNewMethods).subList(0, wcNewMethods.length - 1), IMethod.class); continue; } wcOldMethods[i] = getMethodInWorkingCopy(method, getCurrentElementName(), typeWc); wcNewMethods[i] = getMethodInWorkingCopy(method, getNewElementName(), typeWc); } // SearchResultGroup[] newOccurrences= findNewOccurrences(newMethods, newDeclarationWCs, new // SubProgressMonitor(pm, 3)); SearchResultGroup[] newOccurrences = batchFindNewOccurrences( wcNewMethods, wcOldMethods, newDeclarationWCs, new SubProgressMonitor(pm, 3), result); result.merge( RenameAnalyzeUtil.analyzeRenameChanges2( fChangeManager, fOccurrences, newOccurrences, getNewElementName())); return result; } finally { pm.done(); if (newDeclarationWCs != null) { for (int i = 0; i < newDeclarationWCs.length; i++) { newDeclarationWCs[i].discardWorkingCopy(); } } } }
public RemoveDeprecatedQuickFixProposal( int offset, int length, boolean missingEndQuote, String className, String methodName, IMethod method) { super(offset, length, missingEndQuote); this.className = className; this.methodName = methodName; this.method = method; this.cu = method.getCompilationUnit(); }
public void testParentResourceMapping() throws CoreException { IWorkbenchPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart(); IMethod m1 = type1.createMethod("public void m1() { }", null, true, null); monitor.selectionChanged(part, new StructuredSelection(m1)); IInteractionElement m1Node = ContextCore.getContextManager().getElement(m1.getHandleIdentifier()); assertTrue(m1Node.getInterest().isInteresting()); IResource containingResource = ResourcesUiBridgePlugin.getDefault().getResourceForElement(m1Node, true); assertEquals(m1.getCompilationUnit().getAdapter(IResource.class), containingResource); }
/** * Removes the current variable declaration from the AST and inserts it into the lowest possible * scope where the variable is first used. Returns the modification to the AST within a Change * object. */ private Change recordASTModifications() { AST ast = compilationUnit.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); // duplicate the original variable declaration in lower scope before getting rid of it VariableDeclarationStatement oldDeclaration = (VariableDeclarationStatement) variableVisitor.getDeclaration(); assert variableVisitor.getFirstAssignment() instanceof Assignment; Assignment variableAssignment = (Assignment) variableVisitor.getFirstAssignment(); ASTNode newScopeParent = variableAssignment.getParent().getParent(); String codeString = oldDeclaration.toString(); ASTNode newDeclaration = rewriter.createStringPlaceholder( codeString.substring(0, codeString.length() - 1), ASTNode.VARIABLE_DECLARATION_STATEMENT); ListRewrite listRewrite = rewriter.getListRewrite(newScopeParent, Block.STATEMENTS_PROPERTY); listRewrite.insertAt(newDeclaration, 0, null); // get rid of the higher scope declaration rewriter.remove(oldDeclaration, null); ICompilationUnit iCompUnit = method.getCompilationUnit(); final String description = "ReduceScopeOfVariable"; final String comment = "ReduceScopeOfVariable does blah..."; // record the change CompilationUnitChange change = new CompilationUnitChange("Reduce scope of variable", iCompUnit) { public ChangeDescriptor getDescriptor() { Map<Object, Object> arguments = new HashMap<Object, Object>(); arguments.put("method", method); arguments.put("var", varName); return new RefactoringChangeDescriptor( new ReduceScopeOfVariableDescriptor( method.getJavaProject().getElementName(), description, comment, arguments)); } }; try { change.setEdit(rewriter.rewriteAST()); } catch (Exception e) { } return change; }
@Override public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException { if (!fMethod.exists()) { String message = Messages.format( RefactoringCoreMessages.RenameMethodRefactoring_deleted, BasicElementLabels.getFileName(fMethod.getCompilationUnit())); return RefactoringStatus.createFatalErrorStatus(message); } RefactoringStatus result = Checks.checkAvailability(fMethod); if (result.hasFatalError()) return result; result.merge(Checks.checkIfCuBroken(fMethod)); if (JdtFlags.isNative(fMethod)) result.addError(RefactoringCoreMessages.RenameMethodRefactoring_no_native); return result; }
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; }
/* * Used from www.eclipse.org/articles/article.php?file=Article-Unleashing-the-Power-of-Refactoring/index.html */ @Override public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { RefactoringStatus status = new RefactoringStatus(); try { pm.beginTask("Checking preconditions...", 1); if (method == null) { status.merge(RefactoringStatus.createFatalErrorStatus("Method has not been specified.")); } else if (varName == null) { status.merge(RefactoringStatus.createFatalErrorStatus("Variable has not been specified.")); } else if (!method.exists()) { status.merge(RefactoringStatus.createFatalErrorStatus("Method does not exist.")); } else { if (!method.isBinary() && !method.getCompilationUnit().isStructureKnown()) { status.merge( RefactoringStatus.createFatalErrorStatus( "Compilation unit contains compile errors.")); } } } finally { pm.done(); } return status; }
@Override /** * Checks the final conditions in order to perform the refactoring. Specifically, we check if the * variable is used in only a single lower scope than it is declared in, and if this check fails * for any reason, the appropriate error status is set. */ public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { RefactoringStatus status = new RefactoringStatus(); ICompilationUnit Unit = method.getCompilationUnit(); compilationUnit = parse(Unit, pm); try { pm.beginTask("Checking validity...", 1); // Do the work to check the final conditions variableVisitor = new LocalVarVisitor(this); variableVisitor.visit(compilationUnit); compilationUnit.accept(variableVisitor); // Now check for any errors that may be present ASTNode sp = variableVisitor.getScopeParent(); ASTNode lsp = variableVisitor.getLowerScopeParent(); if (sp == null) { // the variable was never found setRefactoringStatus(VARIABLE_NOT_FOUND); } else if (lsp == null) { setRefactoringStatus(NO_SCOPE_TO_REDUCE_TO); } if (refactoringStatus == VARIABLE_USED_IN_DECLARING_SCOPE) { status.merge( RefactoringStatus.createErrorStatus( varName + " in method " + method.getElementName() + " is used in the same scope it is declared in.")); } else if (refactoringStatus == VARIABLE_IS_FIELD) { status.merge( RefactoringStatus.createErrorStatus( varName + " is a field variable and" + " its scope cannot be reduced.")); } else if (refactoringStatus == NO_SCOPE_TO_REDUCE_TO) { status.merge( RefactoringStatus.createErrorStatus( "No scope to possibly reduce " + varName + " in method " + method.getElementName() + " to.")); } else if (refactoringStatus == VARIABLE_USED_IN_MULTIPLE_LOWER_SCOPES) { status.merge( RefactoringStatus.createErrorStatus( varName + " is used in multiple lower scopes" + " and cannot be reduced in method " + method.getElementName())); } else if (refactoringStatus == VARIABLE_FIRST_INITIALIZED_IN_FOR_DECLARATION) { status.merge( RefactoringStatus.createErrorStatus( varName + " is first initialized in a for loop" + " and cannot be reduced in method " + method.getElementName())); } else if (refactoringStatus == VARIABLE_NOT_FOUND) { status.merge( RefactoringStatus.createErrorStatus(varName + " not found in method " + method)); } } finally { pm.done(); } return status; }
public IDocInfo getBasicDocInfo() { try { IMethod iMethod = (IMethod) tm; ISourceRange javadocRange = iMethod.getJavadocRange(); if (javadocRange != null) { String attachedJavadoc = iMethod .getCompilationUnit() .getSource() .substring( javadocRange.getOffset(), javadocRange.getOffset() + javadocRange.getLength()); attachedJavadoc = attachedJavadoc.substring(3, attachedJavadoc.length() - 2); StringReader rr = new StringReader(attachedJavadoc); BufferedReader mm = new BufferedReader(rr); final StringBuilder bld = new StringBuilder(); final HashMap<String, String> mmq = new HashMap<String, String>(); while (true) { try { String s = mm.readLine(); if (s == null) { break; } int indexOf = s.indexOf('*'); if (indexOf != -1) { s = s.substring(indexOf + 1); } s = s.trim(); if (s.startsWith("@")) { // $NON-NLS-1$ if (s.startsWith(PARAM)) { s = s.substring(PARAM.length()); s = s.trim(); int p = s.indexOf(' '); if (p != -1) { String pName = s.substring(0, p).trim(); String pVal = s.substring(p).trim(); mmq.put(pName, pVal); } } if (s.startsWith(RETURN)) { s = s.substring(RETURN.length()); s = s.trim(); mmq.put(RETURN, s); } continue; } bld.append(s); bld.append('\n'); } catch (IOException e) { break; } } return new IDocInfo() { public String getDocumentation(String pName) { return mmq.get(pName); } public String getDocumentation() { return bld.toString().trim(); } public String getReturnInfo() { return mmq.get(RETURN); } }; } return new IDocInfo() { public String getReturnInfo() { return ""; //$NON-NLS-1$ } public String getDocumentation(String pName) { return ""; //$NON-NLS-1$ } public String getDocumentation() { return ""; //$NON-NLS-1$ } }; } catch (JavaModelException e) { throw new IllegalStateException(); } }