Java Code Examples for org.eclipse.jdt.core.dom.rewrite.ASTRewrite#createStringPlaceholder()

The following examples show how to use org.eclipse.jdt.core.dom.rewrite.ASTRewrite#createStringPlaceholder() . 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: AssociativeInfixExpressionFragment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public Expression createCopyTarget(ASTRewrite rewrite, boolean removeSurroundingParenthesis) throws JavaModelException {
		List<Expression> allOperands= findGroupMembersInOrderFor(fGroupRoot);
		if (allOperands.size() == fOperands.size()) {
			return (Expression) rewrite.createCopyTarget(fGroupRoot);
		}

		CompilationUnit root= (CompilationUnit) fGroupRoot.getRoot();
		ICompilationUnit cu= (ICompilationUnit) root.getJavaElement();
		String source= cu.getBuffer().getText(getStartPosition(), getLength());
		return (Expression) rewrite.createStringPlaceholder(source, ASTNode.INFIX_EXPRESSION);

//		//Todo: see whether we could copy bigger chunks of the original selection
//		// (probably only possible from extendedOperands list or from nested InfixExpressions)
//		InfixExpression result= rewrite.getAST().newInfixExpression();
//		result.setOperator(getOperator());
//		Expression first= (Expression) fOperands.get(0);
//		Expression second= (Expression) fOperands.get(1);
//		result.setLeftOperand((Expression) rewrite.createCopyTarget(first));
//		result.setRightOperand((Expression) rewrite.createCopyTarget(second));
//		for (int i= 2; i < fOperands.size(); i++) {
//			Expression next= (Expression) fOperands.get(i);
//			result.extendedOperands().add(rewrite.createCopyTarget(next));
//		}
//		return result;
	}
 
Example 2
Source File: AssociativeInfixExpressionFragment.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Expression createCopyTarget(ASTRewrite rewrite, boolean removeSurroundingParenthesis) throws JavaModelException {
	List<Expression> allOperands = findGroupMembersInOrderFor(fGroupRoot);
	if (allOperands.size() == fOperands.size()) {
		return (Expression) rewrite.createCopyTarget(fGroupRoot);
	}

	CompilationUnit root = (CompilationUnit) fGroupRoot.getRoot();
	ICompilationUnit cu = (ICompilationUnit) root.getJavaElement();
	String source = cu.getBuffer().getText(getStartPosition(), getLength());
	return (Expression) rewrite.createStringPlaceholder(source, ASTNode.INFIX_EXPRESSION);

	//		//Todo: see whether we could copy bigger chunks of the original selection
	//		// (probably only possible from extendedOperands list or from nested InfixExpressions)
	//		InfixExpression result= rewrite.getAST().newInfixExpression();
	//		result.setOperator(getOperator());
	//		Expression first= (Expression) fOperands.get(0);
	//		Expression second= (Expression) fOperands.get(1);
	//		result.setLeftOperand((Expression) rewrite.createCopyTarget(first));
	//		result.setRightOperand((Expression) rewrite.createCopyTarget(second));
	//		for (int i= 2; i < fOperands.size(); i++) {
	//			Expression next= (Expression) fOperands.get(i);
	//			result.extendedOperands().add(rewrite.createCopyTarget(next));
	//		}
	//		return result;
}
 
Example 3
Source File: LocalCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static void addCasesOmittedProposals(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) {
	ASTNode selectedNode = problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) {
		AST ast = selectedNode.getAST();
		SwitchStatement parent = (SwitchStatement) selectedNode.getParent();

		for (Statement statement : (List<Statement>) parent.statements()) {
			if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) {

				// insert //$CASES-OMITTED$:
				ASTRewrite rewrite = ASTRewrite.create(ast);
				rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
				ListRewrite listRewrite = rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY);
				ASTNode casesOmittedComment = rewrite.createStringPlaceholder("//$CASES-OMITTED$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$
				listRewrite.insertBefore(casesOmittedComment, statement, null);

				String label = CorrectionMessages.LocalCorrectionsSubProcessor_insert_cases_omitted;
				ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_CASES_OMITTED);
				proposals.add(proposal);
				break;
			}
		}
	}
}
 
Example 4
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void addCasesOmittedProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) {
		AST ast= selectedNode.getAST();
		SwitchStatement parent= (SwitchStatement) selectedNode.getParent();
		
		for (Statement statement : (List<Statement>) parent.statements()) {
			if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) {
				
				// insert //$CASES-OMITTED$:
				ASTRewrite rewrite= ASTRewrite.create(ast);
				rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
				ListRewrite listRewrite= rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY);
				ASTNode casesOmittedComment= rewrite.createStringPlaceholder("//$CASES-OMITTED$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$
				listRewrite.insertBefore(casesOmittedComment, statement, null);
				
				String label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_cases_omitted;
				Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
				ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_CASES_OMITTED, image);
				proposals.add(proposal);
				break;
			}
		}
	}
}
 
Example 5
Source File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void createFieldsForAccessedLocals(CompilationUnitRewrite rewrite, IVariableBinding[] varBindings, String[] fieldNames, List<BodyDeclaration> newBodyDeclarations) throws CoreException {
	final ImportRewrite importRewrite= rewrite.getImportRewrite();
	final ASTRewrite astRewrite= rewrite.getASTRewrite();
	final AST ast= astRewrite.getAST();

	for (int i= 0; i < varBindings.length; i++) {
		VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
		fragment.setInitializer(null);
		fragment.setName(ast.newSimpleName(fieldNames[i]));
		FieldDeclaration field= ast.newFieldDeclaration(fragment);
		ITypeBinding varType= varBindings[i].getType();
		field.setType(importRewrite.addImport(varType, ast));
		field.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.FINAL));
		if (doAddComments()) {
			String string= CodeGeneration.getFieldComment(rewrite.getCu(), varType.getName(), fieldNames[i], StubUtility.getLineDelimiterUsed(fCu));
			if (string != null) {
				Javadoc javadoc= (Javadoc) astRewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
				field.setJavadoc(javadoc);
			}
		}

		newBodyDeclarations.add(field);

		addLinkedPosition(KEY_FIELD_NAME_EXT + i, fragment.getName(), astRewrite, false);
	}
}
 
Example 6
Source File: PullUpRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Javadoc createJavadocForStub(final String enclosingTypeName, final MethodDeclaration oldMethod, final MethodDeclaration newMethodNode, final ICompilationUnit cu, final ASTRewrite rewrite) throws CoreException {
	if (fSettings.createComments) {
		final IMethodBinding binding= oldMethod.resolveBinding();
		if (binding != null) {
			final ITypeBinding[] params= binding.getParameterTypes();
			final String fullTypeName= getDestinationType().getFullyQualifiedName('.');
			final String[] fullParamNames= new String[params.length];
			for (int i= 0; i < fullParamNames.length; i++) {
				fullParamNames[i]= Bindings.getFullyQualifiedName(params[i]);
			}
			final String comment= CodeGeneration.getMethodComment(cu, enclosingTypeName, newMethodNode, false, binding.getName(), fullTypeName, fullParamNames, StubUtility.getLineDelimiterUsed(cu));
			if (comment != null)
				return (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC);
		}
	}
	return null;
}
 
Example 7
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addEnclosingInstanceDeclaration(final AbstractTypeDeclaration declaration, final ASTRewrite rewrite) throws CoreException {
	Assert.isNotNull(declaration);
	Assert.isNotNull(rewrite);
	final AST ast= declaration.getAST();
	final VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
	fragment.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
	final FieldDeclaration newField= ast.newFieldDeclaration(fragment);
	newField.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getEnclosingInstanceAccessModifiers()));
	newField.setType(createEnclosingType(ast));
	final String comment= CodeGeneration.getFieldComment(fType.getCompilationUnit(), declaration.getName().getIdentifier(), fEnclosingInstanceFieldName, StubUtility.getLineDelimiterUsed(fType.getJavaProject()));
	if (comment != null && comment.length() > 0) {
		final Javadoc doc= (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC);
		newField.setJavadoc(doc);
	}
	rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertFirst(newField, null);
}
 
Example 8
Source File: SourceProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void makeNamesUnique(ASTRewrite rewriter, CodeScopeBuilder.Scope scope) {
	Collection<NameData> usedCalleeNames= fAnalyzer.getUsedNames();
	for (Iterator<NameData> iter= usedCalleeNames.iterator(); iter.hasNext();) {
		SourceAnalyzer.NameData nd= iter.next();
		if (scope.isInUse(nd.getName())) {
			String newName= scope.createName(nd.getName(), true);
			List<SimpleName> references= nd.references();
			for (Iterator<SimpleName> refs= references.iterator(); refs.hasNext();) {
				SimpleName element= refs.next();
				ASTNode newNode= rewriter.createStringPlaceholder(newName, ASTNode.SIMPLE_NAME);
				rewriter.replace(element, newNode, null);
			}
		}
	}
}
 
Example 9
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected static ASTNode moveNode(CompilationUnitRewrite cuRewrite, ASTNode node) {
	ASTRewrite rewrite= cuRewrite.getASTRewrite();
	if (rewrite.getAST() != node.getAST()) {
		String str= ASTNodes.getNodeSource(node, true, true);
		if (str != null) {
			return rewrite.createStringPlaceholder(str, node.getNodeType());
		}
		return ASTNode.copySubtree(rewrite.getAST(), node);
	}
	return rewrite.createMoveTarget(node);
}
 
Example 10
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void createConstructor(final AbstractTypeDeclaration declaration, final ASTRewrite rewrite) throws CoreException {
	Assert.isNotNull(declaration);
	Assert.isNotNull(rewrite);
	final AST ast= declaration.getAST();
	final MethodDeclaration constructor= ast.newMethodDeclaration();
	constructor.setConstructor(true);
	constructor.setName(ast.newSimpleName(declaration.getName().getIdentifier()));
	final String comment= CodeGeneration.getMethodComment(fType.getCompilationUnit(), fType.getElementName(), fType.getElementName(), getNewConstructorParameterNames(), new String[0], null, null, StubUtility.getLineDelimiterUsed(fType.getJavaProject()));
	if (comment != null && comment.length() > 0) {
		final Javadoc doc= (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC);
		constructor.setJavadoc(doc);
	}
	if (fCreateInstanceField) {
		final SingleVariableDeclaration variable= ast.newSingleVariableDeclaration();
		final String name= getNameForEnclosingInstanceConstructorParameter();
		variable.setName(ast.newSimpleName(name));
		variable.setType(createEnclosingType(ast));
		constructor.parameters().add(variable);
		final Block body= ast.newBlock();
		final Assignment assignment= ast.newAssignment();
		if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
			final FieldAccess access= ast.newFieldAccess();
			access.setExpression(ast.newThisExpression());
			access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
			assignment.setLeftHandSide(access);
		} else
			assignment.setLeftHandSide(ast.newSimpleName(fEnclosingInstanceFieldName));
		assignment.setRightHandSide(ast.newSimpleName(name));
		final Statement statement= ast.newExpressionStatement(assignment);
		body.statements().add(statement);
		constructor.setBody(body);
	} else
		constructor.setBody(ast.newBlock());
	rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertFirst(constructor, null);
}
 
Example 11
Source File: HierarchyProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected static BodyDeclaration createPlaceholderForProtectedTypeDeclaration(final BodyDeclaration bodyDeclaration, final CompilationUnit declaringCuNode, final ICompilationUnit declaringCu, final ASTRewrite rewrite, final boolean removeIndentation) throws JavaModelException {
	String text= null;
	try {
		final ASTRewrite rewriter= ASTRewrite.create(bodyDeclaration.getAST());
		ModifierRewrite.create(rewriter, bodyDeclaration).setVisibility(Modifier.PROTECTED, null);
		final ITrackedNodePosition position= rewriter.track(bodyDeclaration);
		final IDocument document= new Document(declaringCu.getBuffer().getText(declaringCuNode.getStartPosition(), declaringCuNode.getLength()));
		rewriter.rewriteAST(document, declaringCu.getJavaProject().getOptions(true)).apply(document, TextEdit.UPDATE_REGIONS);
		text= document.get(position.getStartPosition(), position.getLength());
	} catch (BadLocationException exception) {
		text= getNewText(bodyDeclaration, declaringCu, removeIndentation);
	}
	return (BodyDeclaration) rewrite.createStringPlaceholder(text, ASTNode.TYPE_DECLARATION);
}
 
Example 12
Source File: SelfEncapsulateFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private MethodDeclaration createGetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
	FieldDeclaration field = ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
	Type type = field.getType();
	MethodDeclaration result = ast.newMethodDeclaration();
	result.setName(ast.newSimpleName(fGetterName));
	result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
	Type returnType = DimensionRewrite.copyTypeAndAddDimensions(type, fFieldDeclaration.extraDimensions(), rewriter);
	result.setReturnType2(returnType);

	Block block = ast.newBlock();
	result.setBody(block);

	String body = CodeGeneration.getGetterMethodBodyContent(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), lineDelimiter);
	if (body != null) {
		body = body.substring(0, body.lastIndexOf(lineDelimiter));
		ASTNode getterNode = rewriter.createStringPlaceholder(body, ASTNode.BLOCK);
		block.statements().add(getterNode);
	} else {
		ReturnStatement rs = ast.newReturnStatement();
		rs.setExpression(ast.newSimpleName(fField.getElementName()));
		block.statements().add(rs);
	}
	if (fGenerateJavadoc) {
		String string = CodeGeneration.getGetterComment(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), ASTNodes.asString(type), StubUtility.getBaseName(fField), lineDelimiter);
		if (string != null) {
			Javadoc javadoc = (Javadoc) fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
			result.setJavadoc(javadoc);
		}
	}
	return result;
}
 
Example 13
Source File: HierarchyProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected static Type createPlaceholderForType(final Type type, final ICompilationUnit declaringCu, final ASTRewrite rewrite) throws JavaModelException {
	return (Type) rewrite.createStringPlaceholder(declaringCu.getBuffer().getText(type.getStartPosition(), type.getLength()), ASTNode.SIMPLE_TYPE);
}
 
Example 14
Source File: StubUtility2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static MethodDeclaration createConstructorStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, ITypeBinding typeBinding, IMethodBinding superConstructor, IVariableBinding[] variableBindings, int modifiers, CodeGenerationSettings settings) throws CoreException {
	AST ast= rewrite.getAST();

	MethodDeclaration decl= ast.newMethodDeclaration();
	decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers & ~Modifier.ABSTRACT & ~Modifier.NATIVE));
	decl.setName(ast.newSimpleName(typeBinding.getName()));
	decl.setConstructor(true);

	List<SingleVariableDeclaration> parameters= decl.parameters();
	if (superConstructor != null) {
		createTypeParameters(imports, context, ast, superConstructor, decl);

		createParameters(unit.getJavaProject(), imports, context, ast, superConstructor, null, decl);

		createThrownExceptions(decl, superConstructor, imports, context, ast);
	}

	Block body= ast.newBlock();
	decl.setBody(body);

	String delimiter= StubUtility.getLineDelimiterUsed(unit);

	if (superConstructor != null) {
		SuperConstructorInvocation invocation= ast.newSuperConstructorInvocation();
		SingleVariableDeclaration varDecl= null;
		for (Iterator<SingleVariableDeclaration> iterator= parameters.iterator(); iterator.hasNext();) {
			varDecl= iterator.next();
			invocation.arguments().add(ast.newSimpleName(varDecl.getName().getIdentifier()));
		}
		body.statements().add(invocation);
	}

	List<String> prohibited= new ArrayList<String>();
	for (final Iterator<SingleVariableDeclaration> iterator= parameters.iterator(); iterator.hasNext();)
		prohibited.add(iterator.next().getName().getIdentifier());
	String param= null;
	List<String> list= new ArrayList<String>(prohibited);
	String[] excluded= null;
	for (int i= 0; i < variableBindings.length; i++) {
		SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
		var.setType(imports.addImport(variableBindings[i].getType(), ast, context));
		excluded= new String[list.size()];
		list.toArray(excluded);
		param= suggestParameterName(unit, variableBindings[i], excluded);
		list.add(param);
		var.setName(ast.newSimpleName(param));
		parameters.add(var);
	}

	list= new ArrayList<String>(prohibited);
	for (int i= 0; i < variableBindings.length; i++) {
		excluded= new String[list.size()];
		list.toArray(excluded);
		final String paramName= suggestParameterName(unit, variableBindings[i], excluded);
		list.add(paramName);
		final String fieldName= variableBindings[i].getName();
		Expression expression= null;
		if (paramName.equals(fieldName) || settings.useKeywordThis) {
			FieldAccess access= ast.newFieldAccess();
			access.setExpression(ast.newThisExpression());
			access.setName(ast.newSimpleName(fieldName));
			expression= access;
		} else
			expression= ast.newSimpleName(fieldName);
		Assignment assignment= ast.newAssignment();
		assignment.setLeftHandSide(expression);
		assignment.setRightHandSide(ast.newSimpleName(paramName));
		assignment.setOperator(Assignment.Operator.ASSIGN);
		body.statements().add(ast.newExpressionStatement(assignment));
	}

	if (settings != null && settings.createComments) {
		String string= CodeGeneration.getMethodComment(unit, typeBinding.getName(), decl, superConstructor, delimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 15
Source File: CreateTypeMemberOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected ASTNode generateElementAST(ASTRewrite rewriter, ICompilationUnit cu) throws JavaModelException {
	if (this.createdNode == null) {
		this.source = removeIndentAndNewLines(this.source, cu);
		ASTParser parser = ASTParser.newParser(AST.JLS8);
		parser.setSource(this.source.toCharArray());
		parser.setProject(getCompilationUnit().getJavaProject());
		parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
		ASTNode node = parser.createAST(this.progressMonitor);
		String createdNodeSource;
		if (node.getNodeType() != ASTNode.TYPE_DECLARATION) {
			createdNodeSource = generateSyntaxIncorrectAST();
			if (this.createdNode == null)
				throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
		} else {
			TypeDeclaration typeDeclaration = (TypeDeclaration) node;
			if ((typeDeclaration.getFlags() & ASTNode.MALFORMED) != 0) {
				createdNodeSource = generateSyntaxIncorrectAST();
				if (this.createdNode == null)
					throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
			} else {
				List bodyDeclarations = typeDeclaration.bodyDeclarations();
				if (bodyDeclarations.size() == 0) {
					throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
				}
				this.createdNode = (ASTNode) bodyDeclarations.iterator().next();
				createdNodeSource = this.source;
			}
		}
		if (this.alteredName != null) {
			SimpleName newName = this.createdNode.getAST().newSimpleName(this.alteredName);
			SimpleName oldName = rename(this.createdNode, newName);
			int nameStart = oldName.getStartPosition();
			int nameEnd = nameStart + oldName.getLength();
			StringBuffer newSource = new StringBuffer();
			if (this.source.equals(createdNodeSource)) {
				newSource.append(createdNodeSource.substring(0, nameStart));
				newSource.append(this.alteredName);
				newSource.append(createdNodeSource.substring(nameEnd));
			} else {
				// syntactically incorrect source
				int createdNodeStart = this.createdNode.getStartPosition();
				int createdNodeEnd = createdNodeStart + this.createdNode.getLength();
				newSource.append(createdNodeSource.substring(createdNodeStart, nameStart));
				newSource.append(this.alteredName);
				newSource.append(createdNodeSource.substring(nameEnd, createdNodeEnd));

			}
			this.source = newSource.toString();
		}
	}
	if (rewriter == null) return this.createdNode;
	// return a string place holder (instead of the created node) so has to not lose comments and formatting
	return rewriter.createStringPlaceholder(this.source, this.createdNode.getNodeType());
}
 
Example 16
Source File: HierarchyProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected static Expression createPlaceholderForExpression(final Expression expression, final ICompilationUnit declaringCu, final ASTRewrite rewrite) throws JavaModelException {
	return (Expression) rewrite.createStringPlaceholder(declaringCu.getBuffer().getText(expression.getStartPosition(), expression.getLength()), ASTNode.METHOD_INVOCATION);
}
 
Example 17
Source File: SourceProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private Expression createReceiver(ASTRewrite rewriter, CallContext context, IVariableBinding field, ImportRewriteContext importRewriteContext) {
	String receiver= getReceiver(context, field.getModifiers(), importRewriteContext);
	if (receiver == null)
		return null;
	return (Expression)rewriter.createStringPlaceholder(receiver, ASTNode.SIMPLE_NAME);
}
 
Example 18
Source File: AbstractMethodCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private MethodDeclaration getStub(ASTRewrite rewrite, ASTNode targetTypeDecl) throws CoreException {
	ImportRewriteContext context=new ContextSensitiveImportRewriteContext(targetTypeDecl, getImportRewrite());

	AST ast= targetTypeDecl.getAST();
	MethodDeclaration decl= ast.newMethodDeclaration();

	SimpleName newNameNode= getNewName(rewrite);

	decl.setConstructor(isConstructor());

	addNewModifiers(rewrite, targetTypeDecl, decl.modifiers());

	ArrayList<String> takenNames= new ArrayList<>();
	addNewTypeParameters(rewrite, takenNames, decl.typeParameters(), context);

	decl.setName(newNameNode);

	IVariableBinding[] declaredFields= fSenderBinding.getDeclaredFields();
	for (int i= 0; i < declaredFields.length; i++) { // avoid to take parameter names that are equal to field names
		takenNames.add(declaredFields[i].getName());
	}

	String bodyStatement= ""; //$NON-NLS-1$
	boolean isAbstractMethod= Modifier.isAbstract(decl.getModifiers()) || (fSenderBinding.isInterface() && !Modifier.isStatic(decl.getModifiers()) && !Modifier.isDefault(decl.getModifiers()));
	if (!isConstructor()) {
		Type returnType= getNewMethodType(rewrite, context);
		decl.setReturnType2(returnType);

		boolean isVoid= returnType instanceof PrimitiveType && PrimitiveType.VOID.equals(((PrimitiveType)returnType).getPrimitiveTypeCode());
		if (!isAbstractMethod && !isVoid) {
			ReturnStatement returnStatement= ast.newReturnStatement();
			returnStatement.setExpression(ASTNodeFactory.newDefaultExpression(ast, returnType, 0));
			bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true));
		}
	}

	addNewParameters(rewrite, takenNames, decl.parameters(), context);
	addNewExceptions(rewrite, decl.thrownExceptionTypes(), context);

	Block body= null;
	if (!isAbstractMethod && !Flags.isAbstract(decl.getModifiers())) {
		body= ast.newBlock();
		if (bodyStatement.length() > 0) {
			ReturnStatement todoNode = (ReturnStatement) rewrite.createStringPlaceholder(bodyStatement,
					ASTNode.RETURN_STATEMENT);
			body.statements().add(todoNode);
		}
	}
	decl.setBody(body);

	CodeGenerationSettings settings = PreferenceManager.getCodeGenerationSettings(getCompilationUnit().getResource());
	if (settings.createComments && !fSenderBinding.isAnonymous()) {
		String string = CodeGeneration.getMethodComment(getCompilationUnit(), fSenderBinding.getName(), decl, null,
				String.valueOf('\n'));
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 19
Source File: SourceProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void replaceParameterWithExpression(ASTRewrite rewriter, CallContext context, ImportRewrite importRewrite) throws CoreException {
	Expression[] arguments= context.arguments;
	try {
		ITextFileBuffer buffer= RefactoringFileBuffers.acquire(context.compilationUnit);
		for (int i= 0; i < arguments.length; i++) {
			Expression expression= arguments[i];
			String expressionString= null;
			if (expression instanceof SimpleName) {
				expressionString= ((SimpleName)expression).getIdentifier();
			} else {
				try {
					expressionString= buffer.getDocument().get(expression.getStartPosition(), expression.getLength());
				} catch (BadLocationException exception) {
					JavaPlugin.log(exception);
					continue;
				}
			}
			ParameterData parameter= getParameterData(i);
			List<SimpleName> references= parameter.references();
			for (Iterator<SimpleName> iter= references.iterator(); iter.hasNext();) {
				ASTNode element= iter.next();
				Expression newExpression= (Expression)rewriter.createStringPlaceholder(expressionString, expression.getNodeType());
				AST ast= rewriter.getAST();
				ITypeBinding explicitCast= ASTNodes.getExplicitCast(expression, (Expression)element);
				if (explicitCast != null) {
					CastExpression cast= ast.newCastExpression();
					if (NecessaryParenthesesChecker.needsParentheses(expression, cast, CastExpression.EXPRESSION_PROPERTY)) {
						newExpression= createParenthesizedExpression(newExpression, ast);
					}
					cast.setExpression(newExpression);
					ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(expression, importRewrite);
					cast.setType(importRewrite.addImport(explicitCast, ast, importRewriteContext));
					expression= newExpression= cast;
				}
				if (NecessaryParenthesesChecker.needsParentheses(expression, element.getParent(), element.getLocationInParent())) {
					newExpression= createParenthesizedExpression(newExpression, ast);
				}
				rewriter.replace(element, newExpression, null);
			}
		}
	} finally {
		RefactoringFileBuffers.release(context.compilationUnit);
	}
}
 
Example 20
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Generates an empty statement, which is shown as blank line and is set as end position for the
 * cursor.
 * 
 * @param rewrite the current {@link ASTRewrite} instance
 * @return an empty statement, shown as blank line
 */
private Statement createBlankLineStatementWithCursorPosition(ASTRewrite rewrite) {
	Statement blankLineStatement= (Statement) rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$
	setEndPosition(rewrite.track(blankLineStatement));
	return blankLineStatement;
}