Java Code Examples for org.eclipse.jdt.core.dom.rewrite.ListRewrite#replace()

The following examples show how to use org.eclipse.jdt.core.dom.rewrite.ListRewrite#replace() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReplaceRewrite.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
protected void handleManyMany(ASTNode[] replacements, TextEditGroup description) {
	ListRewrite container= fRewrite.getListRewrite(fToReplace[0].getParent(), (ChildListPropertyDescriptor)fDescriptor);
	if (fToReplace.length == replacements.length) {
		for (int i= 0; i < fToReplace.length; i++) {
			container.replace(fToReplace[i], replacements[i], description);
		}
	} else if (fToReplace.length < replacements.length) {
		for (int i= 0; i < fToReplace.length; i++) {
			container.replace(fToReplace[i], replacements[i], description);
		}
		for (int i= fToReplace.length; i < replacements.length; i++) {
			container.insertAfter(replacements[i], replacements[i - 1], description);
		}
	} else if (fToReplace.length > replacements.length) {
		int delta= fToReplace.length - replacements.length;
		for(int i= 0; i < delta; i++) {
			container.remove(fToReplace[i], description);
		}
		for (int i= delta, r= 0; i < fToReplace.length; i++, r++) {
			container.replace(fToReplace[i], replacements[r], description);
		}
	}
}
 
Example 2
Source File: StatementRewrite.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void handleOneMany(ASTNode[] replacements, TextEditGroup description) {
	AST ast= fToReplace[0].getAST();
	// to replace == 1, but more than one replacement. Have to check if we
	// need to insert a block to not change structure
	if (ASTNodes.isControlStatementBody(fDescriptor)) {
		Block block= ast.newBlock();
		ListRewrite statements= fRewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
		for (int i= 0; i < replacements.length; i++) {
			statements.insertLast(replacements[i], description);
		}
		fRewrite.replace(fToReplace[0], block, description);
	} else {
		ListRewrite container= fRewrite.getListRewrite(fToReplace[0].getParent(), (ChildListPropertyDescriptor)fDescriptor);
		container.replace(fToReplace[0], replacements[0], description);
		for (int i= 1; i < replacements.length; i++) {
			container.insertAfter(replacements[i], replacements[i - 1], description);
		}
	}
}
 
Example 3
Source File: DelegateCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Performs the actual rewriting and adds an edit to the ASTRewrite set with
 * {@link #setSourceRewrite(CompilationUnitRewrite)}.
 *
 * @throws JavaModelException
 */
public void createEdit() throws JavaModelException {
	try {
		IDocument document= new Document(fDelegateRewrite.getCu().getBuffer().getContents());
		TextEdit edit= fDelegateRewrite.getASTRewrite().rewriteAST(document, fDelegateRewrite.getCu().getJavaProject().getOptions(true));
		edit.apply(document, TextEdit.UPDATE_REGIONS);

		String newSource= Strings.trimIndentation(document.get(fTrackedPosition.getStartPosition(), fTrackedPosition.getLength()),
				fPreferences.tabWidth, fPreferences.indentWidth, false);

		ASTNode placeholder= fOriginalRewrite.getASTRewrite().createStringPlaceholder(newSource, fDeclaration.getNodeType());

		CategorizedTextEditGroup groupDescription= fOriginalRewrite.createCategorizedGroupDescription(getTextEditGroupLabel(), CATEGORY_DELEGATE);
		ListRewrite bodyDeclarationsListRewrite= fOriginalRewrite.getASTRewrite().getListRewrite(fDeclaration.getParent(), getTypeBodyDeclarationsProperty());
		if (fCopy)
			if (fInsertBefore)
				bodyDeclarationsListRewrite.insertBefore(placeholder, fDeclaration, groupDescription);
			else
				bodyDeclarationsListRewrite.insertAfter(placeholder, fDeclaration, groupDescription);
		else
			bodyDeclarationsListRewrite.replace(fDeclaration, placeholder, groupDescription);

	} catch (BadLocationException e) {
		JavaPlugin.log(e);
	}
}
 
Example 4
Source File: ReplaceRewrite.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected void handleManyMany(ASTNode[] replacements, TextEditGroup description) {
	ListRewrite container= fRewrite.getListRewrite(fToReplace[0].getParent(), (ChildListPropertyDescriptor)fDescriptor);
	if (fToReplace.length == replacements.length) {
		for (int i= 0; i < fToReplace.length; i++) {
			container.replace(fToReplace[i], replacements[i], description);
		}
	} else if (fToReplace.length < replacements.length) {
		for (int i= 0; i < fToReplace.length; i++) {
			container.replace(fToReplace[i], replacements[i], description);
		}
		for (int i= fToReplace.length; i < replacements.length; i++) {
			container.insertAfter(replacements[i], replacements[i - 1], description);
		}
	} else if (fToReplace.length > replacements.length) {
		int delta= fToReplace.length - replacements.length;
		for(int i= 0; i < delta; i++) {
			container.remove(fToReplace[i], description);
		}
		for (int i= delta, r= 0; i < fToReplace.length; i++, r++) {
			container.replace(fToReplace[i], replacements[r], description);
		}
	}
}
 
Example 5
Source File: StatementRewrite.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void handleOneMany(ASTNode[] replacements, TextEditGroup description) {
	AST ast= fToReplace[0].getAST();
	// to replace == 1, but more than one replacement. Have to check if we
	// need to insert a block to not change structure
	if (ASTNodes.isControlStatementBody(fDescriptor)) {
		Block block= ast.newBlock();
		ListRewrite statements= fRewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
		for (int i= 0; i < replacements.length; i++) {
			statements.insertLast(replacements[i], description);
		}
		fRewrite.replace(fToReplace[0], block, description);
	} else {
		ListRewrite container= fRewrite.getListRewrite(fToReplace[0].getParent(), (ChildListPropertyDescriptor)fDescriptor);
		container.replace(fToReplace[0], replacements[0], description);
		for (int i= 1; i < replacements.length; i++) {
			container.insertAfter(replacements[i], replacements[i - 1], description);
		}
	}
}
 
Example 6
Source File: PolymorphismRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
protected void replaceThisExpressionWithContextParameterInClassInstanceCreationArguments(Statement newStatement, AST subclassAST, ASTRewrite subclassRewriter) {
	ExpressionExtractor expressionExtractor = new ExpressionExtractor();
	List<Expression> classInstanceCreations = expressionExtractor.getClassInstanceCreations(newStatement);
	for(Expression creation : classInstanceCreations) {
		ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation)creation;
		List<Expression> arguments = classInstanceCreation.arguments();
		for(Expression argument : arguments) {
			if(argument instanceof ThisExpression) {
				String parameterName = sourceTypeDeclaration.getName().getIdentifier();
				parameterName = parameterName.substring(0,1).toLowerCase() + parameterName.substring(1,parameterName.length());
				ListRewrite argumentsRewrite = subclassRewriter.getListRewrite(classInstanceCreation, ClassInstanceCreation.ARGUMENTS_PROPERTY);
				argumentsRewrite.replace(argument, subclassAST.newSimpleName(parameterName), null);
			}
		}
	}
}
 
Example 7
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
private void replaceThisExpressionWithSourceClassParameterInMethodInvocationArguments(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter) {
	ExpressionExtractor extractor = new ExpressionExtractor();
	List<Expression> methodInvocations = extractor.getMethodInvocations(newMethodDeclaration.getBody());
	for(Expression invocation : methodInvocations) {
		if(invocation instanceof MethodInvocation) {
			MethodInvocation methodInvocation = (MethodInvocation)invocation;
			List<Expression> arguments = methodInvocation.arguments();
			for(Expression argument : arguments) {
				if(argument instanceof ThisExpression) {
					SimpleName parameterName = null;
					if(!additionalArgumentsAddedToMovedMethod.contains("this")) {
						parameterName = addSourceClassParameterToMovedMethod(newMethodDeclaration, targetRewriter);
					}
					else {
						AST ast = newMethodDeclaration.getAST();
						String sourceTypeName = sourceTypeDeclaration.getName().getIdentifier();
						parameterName = ast.newSimpleName(sourceTypeName.replaceFirst(Character.toString(sourceTypeName.charAt(0)), Character.toString(Character.toLowerCase(sourceTypeName.charAt(0)))));
					}
					ListRewrite argumentRewrite = targetRewriter.getListRewrite(methodInvocation, MethodInvocation.ARGUMENTS_PROPERTY);
					argumentRewrite.replace(argument, parameterName, null);
				}
			}
		}
	}
}
 
Example 8
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
private void replaceThisExpressionWithSourceClassParameterInClassInstanceCreationArguments(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter) {
	ExpressionExtractor extractor = new ExpressionExtractor();
	List<Expression> classInstanceCreations = extractor.getClassInstanceCreations(newMethodDeclaration.getBody());
	for(Expression creation : classInstanceCreations) {
		ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation)creation;
		List<Expression> arguments = classInstanceCreation.arguments();
		for(Expression argument : arguments) {
			if(argument instanceof ThisExpression) {
				SimpleName parameterName = null;
				if(!additionalArgumentsAddedToMovedMethod.contains("this")) {
					parameterName = addSourceClassParameterToMovedMethod(newMethodDeclaration, targetRewriter);
				}
				else {
					AST ast = newMethodDeclaration.getAST();
					String sourceTypeName = sourceTypeDeclaration.getName().getIdentifier();
					parameterName = ast.newSimpleName(sourceTypeName.replaceFirst(Character.toString(sourceTypeName.charAt(0)), Character.toString(Character.toLowerCase(sourceTypeName.charAt(0)))));
				}
				ListRewrite argumentRewrite = targetRewriter.getListRewrite(classInstanceCreation, ClassInstanceCreation.ARGUMENTS_PROPERTY);
				argumentRewrite.replace(argument, parameterName, null);
			}
		}
	}
}
 
Example 9
Source File: DelegateCreator.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Performs the actual rewriting and adds an edit to the ASTRewrite set with
 * {@link #setSourceRewrite(CompilationUnitRewrite)}.
 *
 * @throws JavaModelException
 */
public void createEdit() throws JavaModelException {
	try {
		IDocument document= new Document(fDelegateRewrite.getCu().getBuffer().getContents());
		TextEdit edit= fDelegateRewrite.getASTRewrite().rewriteAST(document, fDelegateRewrite.getCu().getJavaProject().getOptions(true));
		edit.apply(document, TextEdit.UPDATE_REGIONS);

		int tabWidth = CodeFormatterUtil.getTabWidth(fOriginalRewrite.getCu().getJavaProject());
		int identWidth = CodeFormatterUtil.getIndentWidth(fOriginalRewrite.getCu().getJavaProject());

		String newSource= Strings.trimIndentation(document.get(fTrackedPosition.getStartPosition(), fTrackedPosition.getLength()),
				tabWidth, identWidth, false);

		ASTNode placeholder= fOriginalRewrite.getASTRewrite().createStringPlaceholder(newSource, fDeclaration.getNodeType());

		CategorizedTextEditGroup groupDescription= fOriginalRewrite.createCategorizedGroupDescription(getTextEditGroupLabel(), CATEGORY_DELEGATE);
		ListRewrite bodyDeclarationsListRewrite= fOriginalRewrite.getASTRewrite().getListRewrite(fDeclaration.getParent(), getTypeBodyDeclarationsProperty());
		if (fCopy) {
			if (fInsertBefore) {
				bodyDeclarationsListRewrite.insertBefore(placeholder, fDeclaration, groupDescription);
			} else {
				bodyDeclarationsListRewrite.insertAfter(placeholder, fDeclaration, groupDescription);
			}
		} else {
			bodyDeclarationsListRewrite.replace(fDeclaration, placeholder, groupDescription);
		}

	} catch (BadLocationException e) {
		//JavaPlugin.log(e);
	}
}
 
Example 10
Source File: ChangePublicToProtectedResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug) throws BugResolutionException {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(workingUnit);
    Assert.isNotNull(bug);

    TypeDeclaration type = getTypeDeclaration(workingUnit, bug.getPrimaryClass());
    MethodDeclaration method = getMethodDeclaration(type, bug.getPrimaryMethod());
    Modifier originalModifier = getPublicModifier(method);

    ListRewrite listRewrite = rewrite.getListRewrite(method, MethodDeclaration.MODIFIERS2_PROPERTY);
    Modifier protectedModifier = workingUnit.getAST().newModifier(PROTECTED_KEYWORD);
    listRewrite.replace(originalModifier, protectedModifier, null);
}
 
Example 11
Source File: GenerateToStringOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void insertMethod(MethodDeclaration method, ListRewrite rewriter, BodyDeclaration replace) throws JavaModelException {
	if (replace != null) {
		rewriter.replace(replace, method, null);
	} else {
		ASTNode insertion= StubUtility2.getNodeToInsertBefore(rewriter, fInsert);
		if (insertion != null)
			rewriter.insertBefore(method, insertion, null);
		else
			rewriter.insertLast(method, null);
	}
}
 
Example 12
Source File: GenerateHashCodeEqualsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addMethod(ListRewrite rewriter, ASTNode insertion, MethodDeclaration stub, BodyDeclaration replace) {
	if (replace != null) {
		rewriter.replace(replace, stub, null);
	} else {
	if (insertion != null)
		rewriter.insertBefore(stub, insertion, null);
	else
		rewriter.insertLast(stub, null);
	}
}
 
Example 13
Source File: PolymorphismRefactoring.java    From JDeodorant with MIT License 5 votes vote down vote up
protected void replaceThisExpressionWithContextParameterInMethodInvocationArguments(List<Expression> newMethodInvocations, AST subclassAST, ASTRewrite subclassRewriter) {
	for(Expression expression : newMethodInvocations) {
		if(expression instanceof MethodInvocation) {
			MethodInvocation newMethodInvocation = (MethodInvocation)expression;
			List<Expression> arguments = newMethodInvocation.arguments();
			for(Expression argument : arguments) {
				if(argument instanceof ThisExpression) {
					String parameterName = sourceTypeDeclaration.getName().getIdentifier();
					parameterName = parameterName.substring(0,1).toLowerCase() + parameterName.substring(1,parameterName.length());
					ListRewrite argumentsRewrite = subclassRewriter.getListRewrite(newMethodInvocation, MethodInvocation.ARGUMENTS_PROPERTY);
					argumentsRewrite.replace(argument, subclassAST.newSimpleName(parameterName), null);
				}
			}
		}
	}
}
 
Example 14
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 5 votes vote down vote up
private void setPublicModifierToSourceMethod(IMethodBinding methodBinding, TypeDeclaration sourceTypeDeclaration) {
	MethodDeclaration[] methodDeclarations = sourceTypeDeclaration.getMethods();
	for(MethodDeclaration methodDeclaration : methodDeclarations) {
		if(methodDeclaration.resolveBinding().isEqualTo(methodBinding)) {
			CompilationUnit sourceCompilationUnit = RefactoringUtility.findCompilationUnit(methodDeclaration);
			ASTRewrite sourceRewriter = ASTRewrite.create(sourceCompilationUnit.getAST());
			ListRewrite modifierRewrite = sourceRewriter.getListRewrite(methodDeclaration, MethodDeclaration.MODIFIERS2_PROPERTY);
			Modifier publicModifier = methodDeclaration.getAST().newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
			boolean modifierFound = false;
			List<IExtendedModifier> modifiers = methodDeclaration.modifiers();
			for(IExtendedModifier extendedModifier : modifiers) {
				if(extendedModifier.isModifier()) {
					Modifier modifier = (Modifier)extendedModifier;
					if(modifier.getKeyword().equals(Modifier.ModifierKeyword.PUBLIC_KEYWORD)) {
						modifierFound = true;
					}
					else if(modifier.getKeyword().equals(Modifier.ModifierKeyword.PRIVATE_KEYWORD)) {
						modifierFound = true;
						modifierRewrite.replace(modifier, publicModifier, null);
						updateAccessModifier(sourceRewriter, sourceCompilationUnit);
					}
					else if(modifier.getKeyword().equals(Modifier.ModifierKeyword.PROTECTED_KEYWORD)) {
						modifierFound = true;
						IPackageBinding targetTypeDeclarationPackageBinding = this.targetTypeDeclaration.resolveBinding().getPackage();
						IPackageBinding typeDeclarationPackageBinding = sourceTypeDeclaration.resolveBinding().getPackage();
						if(targetTypeDeclarationPackageBinding != null && typeDeclarationPackageBinding != null &&
								!targetTypeDeclarationPackageBinding.isEqualTo(typeDeclarationPackageBinding)) {
							modifierRewrite.replace(modifier, publicModifier, null);
							updateAccessModifier(sourceRewriter, sourceCompilationUnit);
						}
					}
				}
			}
			if(!modifierFound) {
				modifierRewrite.insertFirst(publicModifier, null);
				updateAccessModifier(sourceRewriter, sourceCompilationUnit);
			}
		}
	}
}
 
Example 15
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public List<ResourceChange> createTopLevelParameterObject(IPackageFragmentRoot packageFragmentRoot, CreationListener listener) throws CoreException {
	List<ResourceChange> changes= new ArrayList<ResourceChange>();
	IPackageFragment packageFragment= packageFragmentRoot.getPackageFragment(getPackage());
	if (!packageFragment.exists()) {
		changes.add(new CreatePackageChange(packageFragment));
	}
	ICompilationUnit unit= packageFragment.getCompilationUnit(getClassName() + JavaModelUtil.DEFAULT_CU_SUFFIX);
	Assert.isTrue(!unit.exists());
	IJavaProject javaProject= unit.getJavaProject();
	ICompilationUnit workingCopy= unit.getWorkingCopy(null);

	try {
		// create stub with comments and dummy type
		String lineDelimiter= StubUtility.getLineDelimiterUsed(javaProject);
		String fileComment= getFileComment(workingCopy, lineDelimiter);
		String typeComment= getTypeComment(workingCopy, lineDelimiter);
		String content= CodeGeneration.getCompilationUnitContent(workingCopy, fileComment, typeComment, "class " + getClassName() + "{}", lineDelimiter); //$NON-NLS-1$ //$NON-NLS-2$
		workingCopy.getBuffer().setContents(content);

		CompilationUnitRewrite cuRewrite= new CompilationUnitRewrite(workingCopy);
		ASTRewrite rewriter= cuRewrite.getASTRewrite();
		CompilationUnit root= cuRewrite.getRoot();
		AST ast= cuRewrite.getAST();
		ImportRewrite importRewrite= cuRewrite.getImportRewrite();

		// retrieve&replace dummy type with real class
		ListRewrite types= rewriter.getListRewrite(root, CompilationUnit.TYPES_PROPERTY);
		ASTNode dummyType= (ASTNode) types.getOriginalList().get(0);
		String newTypeName= JavaModelUtil.concatenateName(getPackage(), getClassName());
		TypeDeclaration classDeclaration= createClassDeclaration(newTypeName, cuRewrite, listener);
		classDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
		Javadoc javadoc= (Javadoc) dummyType.getStructuralProperty(TypeDeclaration.JAVADOC_PROPERTY);
		rewriter.set(classDeclaration, TypeDeclaration.JAVADOC_PROPERTY, javadoc, null);
		types.replace(dummyType, classDeclaration, null);

		// Apply rewrites and discard workingcopy
		// Using CompilationUnitRewrite.createChange() leads to strange
		// results
		String charset= ResourceUtil.getFile(unit).getCharset(false);
		Document document= new Document(content);
		try {
			rewriter.rewriteAST().apply(document);
			TextEdit rewriteImports= importRewrite.rewriteImports(null);
			rewriteImports.apply(document);
		} catch (BadLocationException e) {
			throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), RefactoringCoreMessages.IntroduceParameterObjectRefactoring_parameter_object_creation_error, e));
		}
		String docContent= document.get();
		CreateCompilationUnitChange compilationUnitChange= new CreateCompilationUnitChange(unit, docContent, charset);
		changes.add(compilationUnitChange);
	} finally {
		workingCopy.discardWorkingCopy();
	}
	return changes;
}