private void replaceExpressionsWithConstant() throws JavaModelException { ASTRewrite astRewrite = fCuRewrite.getASTRewrite(); AST ast = astRewrite.getAST(); IASTFragment[] fragmentsToReplace = getFragmentsToReplace(); for (int i = 0; i < fragmentsToReplace.length; i++) { IASTFragment fragment = fragmentsToReplace[i]; ASTNode node = fragment.getAssociatedNode(); boolean inTypeDeclarationAnnotation = isInTypeDeclarationAnnotation(node); if (inTypeDeclarationAnnotation && JdtFlags.VISIBILITY_STRING_PRIVATE == getVisibility()) continue; SimpleName ref = ast.newSimpleName(fConstantName); Name replacement = ref; boolean qualifyReference = qualifyReferencesWithDeclaringClassName(); if (!qualifyReference) { qualifyReference = inTypeDeclarationAnnotation; } if (qualifyReference) { replacement = ast.newQualifiedName(ast.newSimpleName(getContainingTypeBinding().getName()), ref); } TextEditGroup description = fCuRewrite.createGroupDescription( RefactoringCoreMessages.ExtractConstantRefactoring_replace); fragment.replace(astRewrite, replacement, description); if (fLinkedProposalModel != null) fLinkedProposalModel .getPositionGroup(KEY_NAME, true) .addPosition(astRewrite.track(ref), false); } }
@Override public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException { pm.beginTask(RefactoringCoreMessages.ExtractConstantRefactoring_checking_preconditions, 2); /* Note: some checks are performed on change of input widget * values. (e.g. see ExtractConstantRefactoring.checkConstantNameOnChange()) */ // TODO: possibly add more checking for name conflicts that might // lead to a change in behavior try { RefactoringStatus result = new RefactoringStatus(); createConstantDeclaration(); replaceExpressionsWithConstant(); fChange = fCuRewrite.createChange( RefactoringCoreMessages.ExtractConstantRefactoring_change_name, true, new SubProgressMonitor(pm, 1)); if (fCheckResultForCompileProblems) { checkSource(new SubProgressMonitor(pm, 1), result); } return result; } finally { fConstantTypeCache = null; fCuRewrite.clearASTAndImportRewrites(); pm.done(); } }
@Override protected Statement convert( CompilationUnitRewrite cuRewrite, TextEditGroup group, LinkedProposalModel positionGroups) throws CoreException { ASTRewrite rewrite = cuRewrite.getASTRewrite(); ImportRewrite importRewrite = cuRewrite.getImportRewrite(); ForStatement forStatement = getForStatement(); IJavaProject javaProject = ((CompilationUnit) forStatement.getRoot()).getJavaElement().getJavaProject(); String[] proposals = getVariableNameProposals(fArrayAccess.resolveTypeBinding(), javaProject); String parameterName; if (fElementDeclaration != null) { parameterName = fElementDeclaration.getName().getIdentifier(); } else { parameterName = proposals[0]; } LinkedProposalPositionGroup pg = positionGroups.getPositionGroup(parameterName, true); if (fElementDeclaration != null) pg.addProposal(parameterName, null, 10); for (int i = 0; i < proposals.length; i++) { pg.addProposal(proposals[i], null, 10); } AST ast = forStatement.getAST(); EnhancedForStatement result = ast.newEnhancedForStatement(); SingleVariableDeclaration parameterDeclaration = createParameterDeclaration( parameterName, fElementDeclaration, fArrayAccess, forStatement, importRewrite, rewrite, group, pg, fMakeFinal); result.setParameter(parameterDeclaration); result.setExpression((Expression) rewrite.createCopyTarget(fArrayAccess)); convertBody( forStatement.getBody(), fIndexBinding, fArrayBinding, parameterName, rewrite, group, pg); result.setBody(getBody(cuRewrite, group, positionGroups)); positionGroups.setEndPosition(rewrite.track(result)); return result; }
private RefactoringStatus addDelegates() throws JavaModelException, CoreException { RefactoringStatus status = new RefactoringStatus(); CompilationUnitRewrite rewrite = new CompilationUnitRewrite(fField.getCompilationUnit()); rewrite.setResolveBindings(true); // add delegate for the field if (RefactoringAvailabilityTester.isDelegateCreationAvailable(fField)) { FieldDeclaration fieldDeclaration = ASTNodeSearchUtil.getFieldDeclarationNode(fField, rewrite.getRoot()); if (fieldDeclaration.fragments().size() > 1) { status.addWarning( Messages.format( RefactoringCoreMessages .DelegateCreator_cannot_create_field_delegate_more_than_one_fragment, BasicElementLabels.getJavaElementName(fField.getElementName())), JavaStatusContext.create(fField)); } else if (((VariableDeclarationFragment) fieldDeclaration.fragments().get(0)) .getInitializer() == null) { status.addWarning( Messages.format( RefactoringCoreMessages.DelegateCreator_cannot_create_field_delegate_no_initializer, BasicElementLabels.getJavaElementName(fField.getElementName())), JavaStatusContext.create(fField)); } else { DelegateFieldCreator creator = new DelegateFieldCreator(); creator.setDeclareDeprecated(fDelegateDeprecation); creator.setDeclaration(fieldDeclaration); creator.setNewElementName(getNewElementName()); creator.setSourceRewrite(rewrite); creator.prepareDelegate(); creator.createEdit(); } } // add delegates for getter and setter methods // there may be getters even if the field is static final if (getGetter() != null && fRenameGetter) addMethodDelegate(getGetter(), getNewGetterName(), rewrite); if (getSetter() != null && fRenameSetter) addMethodDelegate(getSetter(), getNewSetterName(), rewrite); final CompilationUnitChange change = rewrite.createChange(true); if (change != null) { change.setKeepPreviewEdits(true); fChangeManager.manage(fField.getCompilationUnit(), change); } return status; }
private Type getConstantType() throws JavaModelException { if (fConstantTypeCache == null) { IExpressionFragment fragment = getSelectedExpression(); ITypeBinding typeBinding = guessBindingForReference(fragment.getAssociatedExpression()); AST ast = fCuRewrite.getAST(); typeBinding = Bindings.normalizeForDeclarationUse(typeBinding, ast); ImportRewrite importRewrite = fCuRewrite.getImportRewrite(); ImportRewriteContext context = new ContextSensitiveImportRewriteContext( fCuRewrite.getRoot(), fSelectionStart, importRewrite); fConstantTypeCache = importRewrite.addImport(typeBinding, ast, context); } return fConstantTypeCache; }
@Override public void run(IProgressMonitor monitor) throws CoreException { if (monitor == null) monitor = new NullProgressMonitor(); try { monitor.beginTask("", 1); // $NON-NLS-1$ monitor.setTaskName(CodeGenerationMessages.GenerateToStringOperation_description); AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) ASTNodes.findDeclaration(fContext.getTypeBinding(), fRewrite.getRoot()); ListRewrite rewriter = fRewrite .getASTRewrite() .getListRewrite(declaration, declaration.getBodyDeclarationsProperty()); if (fContext.getTypeBinding() != null && rewriter != null) { MethodDeclaration toStringMethod = fGenerator.generateToStringMethod(); List<BodyDeclaration> list = declaration.bodyDeclarations(); BodyDeclaration replace = findMethodToReplace(list, toStringMethod); if (replace == null || ((Boolean) toStringMethod.getProperty(AbstractToStringGenerator.OVERWRITE_METHOD_PROPERTY)) .booleanValue()) insertMethod(toStringMethod, rewriter, replace); List<MethodDeclaration> helperMethods = fGenerator.generateHelperMethods(); for (Iterator<MethodDeclaration> iterator = helperMethods.iterator(); iterator.hasNext(); ) { MethodDeclaration method = iterator.next(); replace = findMethodToReplace(list, method); if (replace == null || ((Boolean) method.getProperty(AbstractToStringGenerator.OVERWRITE_METHOD_PROPERTY)) .booleanValue()) { insertMethod(method, rewriter, replace); } } JavaModelUtil.applyEdit( (ICompilationUnit) fUnit.getJavaElement(), fRewrite.createChange(true).getEdit(), false, monitor); } } finally { monitor.done(); } }
/** {@inheritDoc} */ public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { AST ast = cuRewrite.getRoot().getAST(); ListRewrite listRewrite = cuRewrite .getASTRewrite() .getListRewrite(fBodyDeclaration, fBodyDeclaration.getModifiersProperty()); Annotation newAnnotation = ast.newMarkerAnnotation(); newAnnotation.setTypeName(ast.newSimpleName(fAnnotation)); TextEditGroup group = createTextEditGroup( Messages.format( FixMessages.Java50Fix_AddMissingAnnotation_description, BasicElementLabels.getJavaElementName(fAnnotation)), cuRewrite); listRewrite.insertFirst(newAnnotation, group); }
private void addMethodDelegate(IMethod getter, String newName, CompilationUnitRewrite rewrite) throws JavaModelException { MethodDeclaration declaration = ASTNodeSearchUtil.getMethodDeclarationNode(getter, rewrite.getRoot()); DelegateCreator creator = new DelegateMethodCreator(); creator.setDeclareDeprecated(fDelegateDeprecation); creator.setDeclaration(declaration); creator.setNewElementName(newName); creator.setSourceRewrite(rewrite); creator.prepareDelegate(); creator.createEdit(); }
/** {@inheritDoc} */ public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException { InferTypeArgumentsTCModel model = new InferTypeArgumentsTCModel(); InferTypeArgumentsConstraintCreator creator = new InferTypeArgumentsConstraintCreator(model, true); CompilationUnit root = cuRewrite.getRoot(); root.accept(creator); InferTypeArgumentsConstraintsSolver solver = new InferTypeArgumentsConstraintsSolver(model); InferTypeArgumentsUpdate update = solver.solveConstraints(new NullProgressMonitor()); solver = null; // free caches ASTNode[] nodes = InferTypeArgumentsRefactoring.inferArguments(fTypes, update, model, cuRewrite); if (nodes.length == 0) return; ASTRewrite astRewrite = cuRewrite.getASTRewrite(); for (int i = 0; i < nodes.length; i++) { if (nodes[i] instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) nodes[0]; List args = (List) type.getStructuralProperty(ParameterizedType.TYPE_ARGUMENTS_PROPERTY); int j = 0; for (Iterator iter = args.iterator(); iter.hasNext(); ) { LinkedProposalPositionGroup group = new LinkedProposalPositionGroup("G" + i + "_" + j); // $NON-NLS-1$ //$NON-NLS-2$ Type argType = (Type) iter.next(); if (!positionGroups.hasLinkedPositions()) { group.addPosition(astRewrite.track(argType), true); } else { group.addPosition(astRewrite.track(argType), false); } positionGroups.addPositionGroup(group); j++; } } } positionGroups.setEndPosition(astRewrite.track(nodes[0])); }
private String[] getExcludedVariableNames() { if (fExcludedVariableNames == null) { try { IExpressionFragment expr = getSelectedExpression(); Collection<String> takenNames = new ScopeAnalyzer(fCuRewrite.getRoot()) .getUsedVariableNames(expr.getStartPosition(), expr.getLength()); fExcludedVariableNames = takenNames.toArray(new String[takenNames.size()]); } catch (JavaModelException e) { fExcludedVariableNames = new String[0]; } } return fExcludedVariableNames; }
/** {@inheritDoc} */ public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { ASTRewrite rewrite = cuRewrite.getASTRewrite(); TextEditGroup group = createTextEditGroup( FixMessages.VariableDeclarationFix_changeModifierOfUnknownToFinal_description, cuRewrite); if (fDeclaration instanceof VariableDeclarationStatement) { VariableDeclarationFragment[] toChange = (VariableDeclarationFragment[]) fToChange.toArray(new VariableDeclarationFragment[fToChange.size()]); VariableDeclarationRewrite.rewriteModifiers( (VariableDeclarationStatement) fDeclaration, toChange, fIncludedModifiers, fExcludedModifiers, rewrite, group); } else if (fDeclaration instanceof FieldDeclaration) { VariableDeclarationFragment[] toChange = (VariableDeclarationFragment[]) fToChange.toArray(new VariableDeclarationFragment[fToChange.size()]); VariableDeclarationRewrite.rewriteModifiers( (FieldDeclaration) fDeclaration, toChange, fIncludedModifiers, fExcludedModifiers, rewrite, group); } else if (fDeclaration instanceof SingleVariableDeclaration) { VariableDeclarationRewrite.rewriteModifiers( (SingleVariableDeclaration) fDeclaration, fIncludedModifiers, fExcludedModifiers, rewrite, group); } else if (fDeclaration instanceof VariableDeclarationExpression) { VariableDeclarationRewrite.rewriteModifiers( (VariableDeclarationExpression) fDeclaration, fIncludedModifiers, fExcludedModifiers, rewrite, group); } }
private IExpressionFragment getSelectedExpression() throws JavaModelException { if (fSelectedExpression != null) return fSelectedExpression; IASTFragment selectedFragment = ASTFragmentFactory.createFragmentForSourceRange( new SourceRange(fSelectionStart, fSelectionLength), fCuRewrite.getRoot(), fCu); if (selectedFragment instanceof IExpressionFragment && !Checks.isInsideJavadoc(selectedFragment.getAssociatedNode())) { fSelectedExpression = (IExpressionFragment) selectedFragment; } if (fSelectedExpression != null && Checks.isEnumCase(fSelectedExpression.getAssociatedExpression().getParent())) { fSelectedExpression = null; } return fSelectedExpression; }
/** {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException { TextEditGroup group = createTextEditGroup(FixMessages.Java50Fix_ConvertToEnhancedForLoop_description, cuRewrite); ASTRewrite rewrite = cuRewrite.getASTRewrite(); TightSourceRangeComputer rangeComputer; if (rewrite.getExtendedSourceRangeComputer() instanceof TightSourceRangeComputer) { rangeComputer = (TightSourceRangeComputer) rewrite.getExtendedSourceRangeComputer(); } else { rangeComputer = new TightSourceRangeComputer(); } rangeComputer.addTightSourceNode(getForStatement()); rewrite.setTargetSourceRangeComputer(rangeComputer); Statement statement = convert(cuRewrite, group, positionGroups); rewrite.replace(getForStatement(), statement, group); }
private void checkSource(SubProgressMonitor monitor, RefactoringStatus result) throws CoreException { String newCuSource = fChange.getPreviewContent(new NullProgressMonitor()); CompilationUnit newCUNode = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL) .parse(newCuSource, fCu, true, true, monitor); IProblem[] newProblems = RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fCuRewrite.getRoot()); for (int i = 0; i < newProblems.length; i++) { IProblem problem = newProblems[i]; if (problem.isError()) result.addEntry( new RefactoringStatusEntry( (problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, SourceRangeFactory.create(problem)))); } }
private RefactoringStatus checkSelection(IProgressMonitor pm) throws JavaModelException { try { pm.beginTask("", 2); // $NON-NLS-1$ IExpressionFragment selectedExpression = getSelectedExpression(); if (selectedExpression == null) { String message = RefactoringCoreMessages.ExtractConstantRefactoring_select_expression; return CodeRefactoringUtil.checkMethodSyntaxErrors( fSelectionStart, fSelectionLength, fCuRewrite.getRoot(), message); } pm.worked(1); RefactoringStatus result = new RefactoringStatus(); result.merge(checkExpression()); if (result.hasFatalError()) return result; pm.worked(1); return result; } finally { pm.done(); } }
/** * Add occurrences * * @param manager the text change manager * @param pm the progress monitor * @param status the status * @throws CoreException if change creation failed */ protected void addOccurrences( TextChangeManager manager, IProgressMonitor pm, RefactoringStatus status) throws CoreException /*thrown in subtype*/ { pm.beginTask("", fOccurrences.length); // $NON-NLS-1$ for (int i = 0; i < fOccurrences.length; i++) { ICompilationUnit cu = fOccurrences[i].getCompilationUnit(); if (cu == null) continue; SearchMatch[] results = fOccurrences[i].getSearchResults(); // Split matches into declaration and non-declaration matches List<SearchMatch> declarationsInThisCu = new ArrayList<>(); List<SearchMatch> referencesInThisCu = new ArrayList<>(); for (int j = 0; j < results.length; j++) { if (results[j] instanceof MethodDeclarationMatch) declarationsInThisCu.add(results[j]); else referencesInThisCu.add(results[j]); } // First, handle the declarations if (declarationsInThisCu.size() > 0) { if (fDelegateUpdating) { // Update with delegates CompilationUnitRewrite rewrite = new CompilationUnitRewrite(cu); rewrite.setResolveBindings(true); for (Iterator<SearchMatch> iter = declarationsInThisCu.iterator(); iter.hasNext(); ) { SearchMatch element = iter.next(); MethodDeclaration method = ASTNodeSearchUtil.getMethodDeclarationNode( (IMethod) element.getElement(), rewrite.getRoot()); DelegateCreator creator = new DelegateMethodCreator(); creator.setDeclareDeprecated(fDelegateDeprecation); creator.setDeclaration(method); creator.setSourceRewrite(rewrite); creator.setNewElementName(getNewElementName()); creator.prepareDelegate(); creator.createEdit(); } // Need to handle all delegates first as this // creates a completely new change object. TextChange changeForThisCu = rewrite.createChange(true); changeForThisCu.setKeepPreviewEdits(true); manager.manage(cu, changeForThisCu); } // Update the normal methods for (Iterator<SearchMatch> iter = declarationsInThisCu.iterator(); iter.hasNext(); ) { SearchMatch element = iter.next(); simpleUpdate(element, cu, manager.get(cu)); } } // Second, handle references if (fUpdateReferences) { for (Iterator<SearchMatch> iter = referencesInThisCu.iterator(); iter.hasNext(); ) { SearchMatch element = iter.next(); simpleUpdate(element, cu, manager.get(cu)); } } pm.worked(1); if (pm.isCanceled()) throw new OperationCanceledException(); } pm.done(); }
public CompilationUnitChange createTextChange(IProgressMonitor pm) throws CoreException { createConstantDeclaration(); replaceExpressionsWithConstant(); return fCuRewrite.createChange( RefactoringCoreMessages.ExtractConstantRefactoring_change_name, true, pm); }
private void createConstantDeclaration() throws CoreException { Type type = getConstantType(); IExpressionFragment fragment = getSelectedExpression(); Expression initializer = getSelectedExpression().createCopyTarget(fCuRewrite.getASTRewrite(), true); AST ast = fCuRewrite.getAST(); VariableDeclarationFragment variableDeclarationFragment = ast.newVariableDeclarationFragment(); variableDeclarationFragment.setName(ast.newSimpleName(fConstantName)); variableDeclarationFragment.setInitializer(initializer); FieldDeclaration fieldDeclaration = ast.newFieldDeclaration(variableDeclarationFragment); fieldDeclaration.setType(type); Modifier.ModifierKeyword accessModifier = Modifier.ModifierKeyword.toKeyword(fVisibility); if (accessModifier != null) fieldDeclaration.modifiers().add(ast.newModifier(accessModifier)); fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD)); fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD)); boolean createComments = JavaPreferencesSettings.getCodeGenerationSettings(fCu.getJavaProject()).createComments; if (createComments) { String comment = CodeGeneration.getFieldComment( fCu, getConstantTypeName(), fConstantName, StubUtility.getLineDelimiterUsed(fCu)); if (comment != null && comment.length() > 0) { Javadoc doc = (Javadoc) fCuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC); fieldDeclaration.setJavadoc(doc); } } AbstractTypeDeclaration parent = getContainingTypeDeclarationNode(); ListRewrite listRewrite = fCuRewrite.getASTRewrite().getListRewrite(parent, parent.getBodyDeclarationsProperty()); TextEditGroup msg = fCuRewrite.createGroupDescription( RefactoringCoreMessages.ExtractConstantRefactoring_declare_constant); if (insertFirst()) { listRewrite.insertFirst(fieldDeclaration, msg); } else { listRewrite.insertAfter(fieldDeclaration, getNodeToInsertConstantDeclarationAfter(), msg); } if (fLinkedProposalModel != null) { ASTRewrite rewrite = fCuRewrite.getASTRewrite(); LinkedProposalPositionGroup nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true); nameGroup.addPosition(rewrite.track(variableDeclarationFragment.getName()), true); String[] nameSuggestions = guessConstantNames(); if (nameSuggestions.length > 0 && !nameSuggestions[0].equals(fConstantName)) { nameGroup.addProposal(fConstantName, null, nameSuggestions.length + 1); } for (int i = 0; i < nameSuggestions.length; i++) { nameGroup.addProposal(nameSuggestions[i], null, nameSuggestions.length - i); } LinkedProposalPositionGroup typeGroup = fLinkedProposalModel.getPositionGroup(KEY_TYPE, true); typeGroup.addPosition(rewrite.track(type), true); ITypeBinding typeBinding = guessBindingForReference(fragment.getAssociatedExpression()); if (typeBinding != null) { ITypeBinding[] relaxingTypes = ASTResolving.getNarrowingTypes(ast, typeBinding); for (int i = 0; i < relaxingTypes.length; i++) { typeGroup.addProposal(relaxingTypes[i], fCuRewrite.getCu(), relaxingTypes.length - i); } } boolean isInterface = parent.resolveBinding() != null && parent.resolveBinding().isInterface(); ModifierCorrectionSubProcessor.installLinkedVisibilityProposals( fLinkedProposalModel, rewrite, fieldDeclaration.modifiers(), isInterface); } }