Java Code Examples for org.eclipse.jdt.core.dom.AST#newBlock()

The following examples show how to use org.eclipse.jdt.core.dom.AST#newBlock() . 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: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Helper to generate an index based <code>for</code> loop to iterate over a {@link List}
 * implementation.
 * 
 * @param ast the current {@link AST} instance to generate the {@link ASTRewrite} for
 * @return an applicable {@link ASTRewrite} instance
 */
private ASTRewrite generateIndexBasedForRewrite(AST ast) {
	ASTRewrite rewrite= ASTRewrite.create(ast);

	ForStatement loopStatement= ast.newForStatement();
	SimpleName loopVariableName= resolveLinkedVariableNameWithProposals(rewrite, "int", null, true); //$NON-NLS-1$
	loopStatement.initializers().add(getForInitializer(ast, loopVariableName));

	MethodInvocation listSizeExpression= ast.newMethodInvocation();
	listSizeExpression.setName(ast.newSimpleName("size")); //$NON-NLS-1$
	Expression listExpression= (Expression) rewrite.createCopyTarget(fCurrentExpression);
	listSizeExpression.setExpression(listExpression);

	loopStatement.setExpression(getLinkedInfixExpression(rewrite, loopVariableName.getIdentifier(), listSizeExpression, InfixExpression.Operator.LESS));
	loopStatement.updaters().add(getLinkedIncrementExpression(rewrite, loopVariableName.getIdentifier()));

	Block forLoopBody= ast.newBlock();
	forLoopBody.statements().add(ast.newExpressionStatement(getIndexBasedForBodyAssignment(rewrite, loopVariableName)));
	forLoopBody.statements().add(createBlankLineStatementWithCursorPosition(rewrite));
	loopStatement.setBody(forLoopBody);
	rewrite.replace(fCurrentNode, loopStatement, null);

	return rewrite;
}
 
Example 2
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean getAddElseProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
	if (!(node instanceof IfStatement)) {
		return false;
	}
	IfStatement ifStatement= (IfStatement) node;
	if (ifStatement.getElseStatement() != null) {
		return false;
	}

	if (resultingCollections == null) {
		return true;
	}

	AST ast= node.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	Block body= ast.newBlock();

	rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, body, null);

	String label= CorrectionMessages.QuickAssistProcessor_addelseblock_description;
	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_ELSE_BLOCK, image);
	resultingCollections.add(proposal);
	return true;
}
 
Example 3
Source File: ChangeSignatureProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addNewConstructorToSubclass(AbstractTypeDeclaration subclass, CompilationUnitRewrite cuRewrite) {
	AST ast= subclass.getAST();
	MethodDeclaration newConstructor= ast.newMethodDeclaration();
	newConstructor.setName(ast.newSimpleName(subclass.getName().getIdentifier()));
	newConstructor.setConstructor(true);
	newConstructor.setJavadoc(null);
	newConstructor.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getAccessModifier(subclass)));
	newConstructor.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
	Block body= ast.newBlock();
	newConstructor.setBody(body);
	SuperConstructorInvocation superCall= ast.newSuperConstructorInvocation();
	addArgumentsToNewSuperConstructorCall(superCall, cuRewrite);
	body.statements().add(superCall);

	String msg= RefactoringCoreMessages.ChangeSignatureRefactoring_add_constructor;
	TextEditGroup description= cuRewrite.createGroupDescription(msg);
	cuRewrite.getASTRewrite().getListRewrite(subclass, subclass.getBodyDeclarationsProperty()).insertFirst(newConstructor, description);

	// TODO use AbstractTypeDeclaration
}
 
Example 4
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean getAddFinallyProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
	TryStatement tryStatement= ASTResolving.findParentTryStatement(node);
	if (tryStatement == null || tryStatement.getFinally() != null) {
		return false;
	}
	Statement statement= ASTResolving.findParentStatement(node);
	if (tryStatement != statement && tryStatement.getBody() != statement) {
		return false; // an node inside a catch or finally block
	}

	if (resultingCollections == null) {
		return true;
	}

	AST ast= tryStatement.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	Block finallyBody= ast.newBlock();

	rewrite.set(tryStatement, TryStatement.FINALLY_PROPERTY, finallyBody, null);

	String label= CorrectionMessages.QuickAssistProcessor_addfinallyblock_description;
	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_FINALLY_BLOCK, image);
	resultingCollections.add(proposal);
	return true;
}
 
Example 5
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Helper to generate an index based <code>for</code> loop to iterate over an array.
 * 
 * @param ast the current {@link AST} instance to generate the {@link ASTRewrite} for
 * @return an applicable {@link ASTRewrite} instance
 */
private ASTRewrite generateForRewrite(AST ast) {
	ASTRewrite rewrite= ASTRewrite.create(ast);

	ForStatement loopStatement= ast.newForStatement();
	SimpleName loopVariableName= resolveLinkedVariableNameWithProposals(rewrite, "int", null, true); //$NON-NLS-1$
	loopStatement.initializers().add(getForInitializer(ast, loopVariableName));

	FieldAccess getArrayLengthExpression= ast.newFieldAccess();
	getArrayLengthExpression.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression));
	getArrayLengthExpression.setName(ast.newSimpleName("length")); //$NON-NLS-1$

	loopStatement.setExpression(getLinkedInfixExpression(rewrite, loopVariableName.getIdentifier(), getArrayLengthExpression, InfixExpression.Operator.LESS));
	loopStatement.updaters().add(getLinkedIncrementExpression(rewrite, loopVariableName.getIdentifier()));

	Block forLoopBody= ast.newBlock();
	forLoopBody.statements().add(ast.newExpressionStatement(getForBodyAssignment(rewrite, loopVariableName)));
	forLoopBody.statements().add(createBlankLineStatementWithCursorPosition(rewrite));
	loopStatement.setBody(forLoopBody);
	rewrite.replace(fCurrentNode, loopStatement, null);

	return rewrite;
}
 
Example 6
Source File: RegularBuilderWithMethodAdderFragment.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
private Block createWithMethodBody(AST ast, String originalFieldName, String builderFieldName) {
    Block newBlock = ast.newBlock();
    ReturnStatement builderReturnStatement = ast.newReturnStatement();
    builderReturnStatement.setExpression(ast.newThisExpression());

    Assignment newAssignment = ast.newAssignment();

    FieldAccess fieldAccess = ast.newFieldAccess();
    fieldAccess.setExpression(ast.newThisExpression());
    fieldAccess.setName(ast.newSimpleName(originalFieldName));
    newAssignment.setLeftHandSide(fieldAccess);
    newAssignment.setRightHandSide(ast.newSimpleName(builderFieldName));

    newBlock.statements().add(ast.newExpressionStatement(newAssignment));
    newBlock.statements().add(builderReturnStatement);
    return newBlock;
}
 
Example 7
Source File: StagedBuilderWithMethodAdderFragment.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
private Block createWithMethodBody(AST ast, BuilderField builderField) {
    String originalFieldName = builderField.getOriginalFieldName();
    String builderFieldName = builderField.getBuilderFieldName();

    Block newBlock = ast.newBlock();
    ReturnStatement builderReturnStatement = ast.newReturnStatement();
    builderReturnStatement.setExpression(ast.newThisExpression());

    Assignment newAssignment = ast.newAssignment();

    FieldAccess fieldAccess = ast.newFieldAccess();
    fieldAccess.setExpression(ast.newThisExpression());
    fieldAccess.setName(ast.newSimpleName(originalFieldName));
    newAssignment.setLeftHandSide(fieldAccess);
    newAssignment.setRightHandSide(ast.newSimpleName(builderFieldName));

    newBlock.statements().add(ast.newExpressionStatement(newAssignment));
    newBlock.statements().add(builderReturnStatement);
    return newBlock;
}
 
Example 8
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private MethodDeclaration createGetter(ParameterInfo pi, String declaringType, CompilationUnitRewrite cuRewrite) throws CoreException {
	AST ast= cuRewrite.getAST();
	ICompilationUnit cu= cuRewrite.getCu();
	IJavaProject project= cu.getJavaProject();

	MethodDeclaration methodDeclaration= ast.newMethodDeclaration();
	String fieldName= pi.getNewName();
	String getterName= getGetterName(pi, ast, project);
	String lineDelim= StubUtility.getLineDelimiterUsed(cu);
	String bareFieldname= NamingConventions.getBaseName(NamingConventions.VK_INSTANCE_FIELD, fieldName, project);
	if (createComments(project)) {
		String comment= CodeGeneration.getGetterComment(cu, declaringType, getterName, fieldName, pi.getNewTypeName(), bareFieldname, lineDelim);
		if (comment != null)
			methodDeclaration.setJavadoc((Javadoc) cuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC));
	}
	methodDeclaration.setName(ast.newSimpleName(getterName));
	methodDeclaration.setReturnType2(importBinding(pi.getNewTypeBinding(), cuRewrite));
	methodDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
	Block block= ast.newBlock();
	methodDeclaration.setBody(block);
	boolean useThis= StubUtility.useThisForFieldAccess(project);
	if (useThis) {
		fieldName= "this." + fieldName; //$NON-NLS-1$
	}
	String bodyContent= CodeGeneration.getGetterMethodBodyContent(cu, declaringType, getterName, fieldName, lineDelim);
	ASTNode getterBody= cuRewrite.getASTRewrite().createStringPlaceholder(bodyContent, ASTNode.EXPRESSION_STATEMENT);
	block.statements().add(getterBody);
	return methodDeclaration;
}
 
Example 9
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private MethodDeclaration createSetter(ParameterInfo pi, String declaringType, CompilationUnitRewrite cuRewrite) throws CoreException {
	AST ast= cuRewrite.getAST();
	ICompilationUnit cu= cuRewrite.getCu();
	IJavaProject project= cu.getJavaProject();

	MethodDeclaration methodDeclaration= ast.newMethodDeclaration();
	String fieldName= pi.getNewName();
	String setterName= getSetterName(pi, ast, project);
	String lineDelim= StubUtility.getLineDelimiterUsed(cu);
	String bareFieldname= NamingConventions.getBaseName(NamingConventions.VK_INSTANCE_FIELD, fieldName, project);
	String paramName= StubUtility.suggestArgumentName(project, bareFieldname, null);
	if (createComments(project)) {
		String comment= CodeGeneration.getSetterComment(cu, declaringType, setterName, fieldName, pi.getNewTypeName(), paramName, bareFieldname, lineDelim);
		if (comment != null)
			methodDeclaration.setJavadoc((Javadoc) cuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC));
	}
	methodDeclaration.setName(ast.newSimpleName(setterName));
	methodDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
	SingleVariableDeclaration variable= ast.newSingleVariableDeclaration();
	variable.setType(importBinding(pi.getNewTypeBinding(), cuRewrite));
	variable.setName(ast.newSimpleName(paramName));
	methodDeclaration.parameters().add(variable);
	Block block= ast.newBlock();
	methodDeclaration.setBody(block);
	boolean useThis= StubUtility.useThisForFieldAccess(project);
	if (useThis || fieldName.equals(paramName)) {
		fieldName= "this." + fieldName; //$NON-NLS-1$
	}
	String bodyContent= CodeGeneration.getSetterMethodBodyContent(cu, declaringType, setterName, fieldName, paramName, lineDelim);
	ASTNode setterBody= cuRewrite.getASTRewrite().createStringPlaceholder(bodyContent, ASTNode.EXPRESSION_STATEMENT);
	block.statements().add(setterBody);
	return methodDeclaration;
}
 
Example 10
Source File: PrivateConstructorBodyCreationFragment.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public Block createBody(AST ast, TypeDeclaration builderType, List<BuilderField> builderFields) {
    Block body = ast.newBlock();
    String builderName = typeDeclarationToVariableNameConverter.convert(builderType);

    populateBodyWithSuperConstructorCall(ast, builderType, body, getFieldsOfClass(builderFields, ConstructorParameterSetterBuilderField.class));
    fieldSetterAdderFragment.populateBodyWithFieldSetCalls(ast, builderName, body,
            getFieldsOfClass(builderFields, ClassFieldSetterBuilderField.class));
    superFieldSetterMethodAdderFragment.populateBodyWithSuperSetterCalls(ast, builderName, body, getFieldsOfClass(builderFields, SuperSetterBasedBuilderField.class));

    return body;
}
 
Example 11
Source File: NewBuilderAndWithMethodCallCreationFragment.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public Block createReturnBlock(AST ast, TypeDeclaration builderType, String withName, String parameterName) {
    Block builderMethodBlock = ast.newBlock();
    ReturnStatement returnStatement = ast.newReturnStatement();
    ClassInstanceCreation newClassInstanceCreation = ast.newClassInstanceCreation();
    newClassInstanceCreation.setType(ast.newSimpleType(ast.newName(builderType.getName().toString())));

    MethodInvocation withMethodInvocation = ast.newMethodInvocation();
    withMethodInvocation.setExpression(newClassInstanceCreation);
    withMethodInvocation.setName(ast.newSimpleName(withName));
    withMethodInvocation.arguments().add(ast.newSimpleName(parameterName));

    returnStatement.setExpression(withMethodInvocation);
    builderMethodBlock.statements().add(returnStatement);
    return builderMethodBlock;
}
 
Example 12
Source File: BuildMethodBodyCreatorFragment.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public Block createBody(AST ast, TypeDeclaration originalType) {
    ClassInstanceCreation newClassInstanceCreation = ast.newClassInstanceCreation();
    newClassInstanceCreation.setType(ast.newSimpleType(ast.newName(originalType.getName().toString())));
    newClassInstanceCreation.arguments().add(ast.newThisExpression());

    ReturnStatement statement = ast.newReturnStatement();
    statement.setExpression(newClassInstanceCreation);

    Block block = ast.newBlock();
    block.statements().add(statement);
    return block;
}
 
Example 13
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 14
Source File: TryPurifyByException.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
private ASTNode tryCatchStmt(AST ast, ASTNode node){
	Block block = ast.newBlock();
	block.statements().add(ASTNode.copySubtree(ast, node));
	TryStatement tryStatement = ast.newTryStatement();
	tryStatement.setBody(block);
	CatchClause catchClause = ast.newCatchClause();
	SingleVariableDeclaration svd = ast.newSingleVariableDeclaration();
	svd.setType(ast.newSimpleType(ast.newSimpleName("Exception")));
	svd.setName(ast.newSimpleName("mException"));
	catchClause.setException(svd);
	tryStatement.catchClauses().add(catchClause);
	return tryStatement;
}
 
Example 15
Source File: BlockWithNewCopyInstanceConstructorCreationFragment.java    From SparkBuilderGenerator with MIT License 4 votes vote down vote up
private Block createBlockWithReturnStatement(AST ast, ReturnStatement returnStatement) {
    Block builderMethodBlock = ast.newBlock();
    builderMethodBlock.statements().add(returnStatement);
    return builderMethodBlock;
}
 
Example 16
Source File: AbstractMethodCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private MethodDeclaration getStub(ASTRewrite rewrite, ASTNode targetTypeDecl) throws CoreException {
	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<String>();
	addNewTypeParameters(rewrite, takenNames, decl.typeParameters());

	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$
	if (!isConstructor()) {
		Type returnType= getNewMethodType(rewrite);
		decl.setReturnType2(returnType);

		boolean isVoid= returnType instanceof PrimitiveType && PrimitiveType.VOID.equals(((PrimitiveType)returnType).getPrimitiveTypeCode());
		if (!fSenderBinding.isInterface() && !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());
	addNewExceptions(rewrite, decl.thrownExceptionTypes());

	Block body= null;
	if (!fSenderBinding.isInterface()) {
		body= ast.newBlock();
		String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), fSenderBinding.getName(), newNameNode.getIdentifier(), isConstructor(), bodyStatement, String.valueOf('\n'));
		if (placeHolder != null) {
			ReturnStatement todoNode= (ReturnStatement)rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
			body.statements().add(todoNode);
		}
	}
	decl.setBody(body);

	CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(getCompilationUnit().getJavaProject());
	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 17
Source File: AssignToVariableAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private ASTRewrite doAddLocal() {
	Expression expression= ((ExpressionStatement) fNodeToAssign).getExpression();
	AST ast= fNodeToAssign.getAST();

	ASTRewrite rewrite= ASTRewrite.create(ast);

	createImportRewrite((CompilationUnit) fNodeToAssign.getRoot());

	String[] varNames= suggestLocalVariableNames(fTypeBinding, expression);
	for (int i= 0; i < varNames.length; i++) {
		addLinkedPositionProposal(KEY_NAME, varNames[i], null);
	}

	VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment();
	newDeclFrag.setName(ast.newSimpleName(varNames[0]));
	newDeclFrag.setInitializer((Expression) rewrite.createCopyTarget(expression));

	Type type= evaluateType(ast);

	if (ASTNodes.isControlStatementBody(fNodeToAssign.getLocationInParent())) {
		Block block= ast.newBlock();
		block.statements().add(rewrite.createMoveTarget(fNodeToAssign));
		rewrite.replace(fNodeToAssign, block, null);
	}

	if (needsSemicolon(expression)) {
		VariableDeclarationStatement varStatement= ast.newVariableDeclarationStatement(newDeclFrag);
		varStatement.setType(type);
		rewrite.replace(expression, varStatement, null);
	} else {
		// trick for bug 43248: use an VariableDeclarationExpression and keep the ExpressionStatement
		VariableDeclarationExpression varExpression= ast.newVariableDeclarationExpression(newDeclFrag);
		varExpression.setType(type);
		rewrite.replace(expression, varExpression, null);
	}

	addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME);
	addLinkedPosition(rewrite.track(type), false, KEY_TYPE);
	setEndPosition(rewrite.track(fNodeToAssign)); // set cursor after expression statement

	return rewrite;
}
 
Example 18
Source File: ConstructorFromSuperclassProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private MethodDeclaration createNewMethodDeclaration(AST ast, IMethodBinding binding, ASTRewrite rewrite, ImportRewriteContext importRewriteContext, CodeGenerationSettings commentSettings) throws CoreException {
	String name= fTypeNode.getName().getIdentifier();
	MethodDeclaration decl= ast.newMethodDeclaration();
	decl.setConstructor(true);
	decl.setName(ast.newSimpleName(name));
	Block body= ast.newBlock();
	decl.setBody(body);

	SuperConstructorInvocation invocation= null;

	List<SingleVariableDeclaration> parameters= decl.parameters();
	String[] paramNames= getArgumentNames(binding);

	ITypeBinding enclosingInstance= getEnclosingInstance();
	if (enclosingInstance != null) {
		invocation= addEnclosingInstanceAccess(rewrite, importRewriteContext, parameters, paramNames, enclosingInstance);
	}

	if (binding == null) {
		decl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
	} else {
		decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, binding.getModifiers()));

		ITypeBinding[] params= binding.getParameterTypes();
		for (int i= 0; i < params.length; i++) {
			SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
			var.setType(getImportRewrite().addImport(params[i], ast, importRewriteContext));
			var.setName(ast.newSimpleName(paramNames[i]));
			parameters.add(var);
		}

		List<Type> thrownExceptions= decl.thrownExceptionTypes();
		ITypeBinding[] excTypes= binding.getExceptionTypes();
		for (int i= 0; i < excTypes.length; i++) {
			Type excType= getImportRewrite().addImport(excTypes[i], ast, importRewriteContext);
			thrownExceptions.add(excType);
		}

		if (invocation == null) {
			invocation= ast.newSuperConstructorInvocation();
		}

		List<Expression> arguments= invocation.arguments();
		for (int i= 0; i < paramNames.length; i++) {
			Name argument= ast.newSimpleName(paramNames[i]);
			arguments.add(argument);
			addLinkedPosition(rewrite.track(argument), false, "arg_name_" + paramNames[i]); //$NON-NLS-1$
		}
	}

	String bodyStatement= (invocation == null) ? "" : ASTNodes.asFormattedString(invocation, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true)); //$NON-NLS-1$
	String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), name, name, true, bodyStatement, String.valueOf('\n'));
	if (placeHolder != null) {
		ASTNode todoNode= rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
		body.statements().add(todoNode);
	}
	if (commentSettings != null) {
		String string= CodeGeneration.getMethodComment(getCompilationUnit(), name, 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: ConstructorFromSuperclassProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private MethodDeclaration createNewMethodDeclaration(AST ast, IMethodBinding binding, ASTRewrite rewrite, ImportRewriteContext importRewriteContext, CodeGenerationSettings commentSettings) throws CoreException {
	String name= fTypeNode.getName().getIdentifier();
	MethodDeclaration decl= ast.newMethodDeclaration();
	decl.setConstructor(true);
	decl.setName(ast.newSimpleName(name));
	Block body= ast.newBlock();
	decl.setBody(body);

	SuperConstructorInvocation invocation= null;

	List<SingleVariableDeclaration> parameters= decl.parameters();
	String[] paramNames= getArgumentNames(binding);

	ITypeBinding enclosingInstance= getEnclosingInstance();
	if (enclosingInstance != null) {
		invocation= addEnclosingInstanceAccess(rewrite, importRewriteContext, parameters, paramNames, enclosingInstance);
	}

	if (binding == null) {
		decl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
	} else {
		decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, binding.getModifiers()));

		ITypeBinding[] params= binding.getParameterTypes();
		for (int i= 0; i < params.length; i++) {
			SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
			var.setType(getImportRewrite().addImport(params[i], ast, importRewriteContext, TypeLocation.LOCAL_VARIABLE));
			var.setName(ast.newSimpleName(paramNames[i]));
			parameters.add(var);
		}

		List<Type> thrownExceptions= decl.thrownExceptionTypes();
		ITypeBinding[] excTypes= binding.getExceptionTypes();
		for (int i= 0; i < excTypes.length; i++) {
			Type excType= getImportRewrite().addImport(excTypes[i], ast, importRewriteContext, TypeLocation.EXCEPTION);
			thrownExceptions.add(excType);
		}

		if (invocation == null) {
			invocation= ast.newSuperConstructorInvocation();
		}

		List<Expression> arguments= invocation.arguments();
		for (int i= 0; i < paramNames.length; i++) {
			Name argument= ast.newSimpleName(paramNames[i]);
			arguments.add(argument);
			addLinkedPosition(rewrite.track(argument), false, "arg_name_" + paramNames[i]); //$NON-NLS-1$
		}
	}

	String bodyStatement = (invocation == null) ? "" : ASTNodes.asFormattedString(invocation, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true)); //$NON-NLS-1$
	String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), name, name, true, bodyStatement, String.valueOf('\n'));
	if (placeHolder != null) {
		ASTNode todoNode= rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
		body.statements().add(todoNode);
	}
	if (commentSettings != null) {
		String string= CodeGeneration.getMethodComment(getCompilationUnit(), name, decl, null, String.valueOf('\n'));
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 20
Source File: AssignToVariableAssistProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private ASTRewrite doAddLocal() {
	ASTNode nodeToAssign= fNodesToAssign.get(0);
	Expression expression= ((ExpressionStatement) nodeToAssign).getExpression();
	AST ast= nodeToAssign.getAST();

	ASTRewrite rewrite= ASTRewrite.create(ast);

	createImportRewrite((CompilationUnit) nodeToAssign.getRoot());

	String[] varNames= suggestLocalVariableNames(fTypeBinding, expression);
	for (int i= 0; i < varNames.length; i++) {
		addLinkedPositionProposal(KEY_NAME, varNames[i]);
	}

	VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment();
	newDeclFrag.setName(ast.newSimpleName(varNames[0]));
	newDeclFrag.setInitializer((Expression) rewrite.createCopyTarget(expression));

	Type type= evaluateType(ast, nodeToAssign, fTypeBinding, KEY_TYPE, TypeLocation.LOCAL_VARIABLE);

	if (ASTNodes.isControlStatementBody(nodeToAssign.getLocationInParent())) {
		Block block= ast.newBlock();
		block.statements().add(rewrite.createMoveTarget(nodeToAssign));
		rewrite.replace(nodeToAssign, block, null);
	}

	if (needsSemicolon(expression)) {
		VariableDeclarationStatement varStatement= ast.newVariableDeclarationStatement(newDeclFrag);
		varStatement.setType(type);
		rewrite.replace(expression, varStatement, null);
	} else {
		// trick for bug 43248: use an VariableDeclarationExpression and keep the ExpressionStatement
		VariableDeclarationExpression varExpression= ast.newVariableDeclarationExpression(newDeclFrag);
		varExpression.setType(type);
		rewrite.replace(expression, varExpression, null);
	}

	addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME);
	addLinkedPosition(rewrite.track(type), false, KEY_TYPE);
	setEndPosition(rewrite.track(nodeToAssign)); // set cursor after expression statement

	return rewrite;
}