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

The following examples show how to use org.eclipse.jdt.core.dom.rewrite.ASTRewrite#getAST() . 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: UseEqualsResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected Expression createEqualsExpression(ASTRewrite rewrite, InfixExpression stringEqualityCheck) {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(stringEqualityCheck);

    final AST ast = rewrite.getAST();
    MethodInvocation equalsInvocation = ast.newMethodInvocation();
    Expression leftOperand = createLeftOperand(rewrite, stringEqualityCheck.getLeftOperand());
    Expression rightOperand = createRightOperand(rewrite, stringEqualityCheck.getRightOperand());

    equalsInvocation.setName(ast.newSimpleName(EQUALS_METHOD_NAME));
    equalsInvocation.setExpression(leftOperand);

    ListRewrite argumentsRewrite = rewrite.getListRewrite(equalsInvocation, MethodInvocation.ARGUMENTS_PROPERTY);
    argumentsRewrite.insertLast(rightOperand, null);

    return equalsInvocation;
}
 
Example 2
Source File: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void addInitializersToConstructors(ASTRewrite rewrite) throws CoreException {
	Assert.isTrue(!isDeclaredInAnonymousClass());
	final AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) getMethodDeclaration().getParent();
	final MethodDeclaration[] constructors = getAllConstructors(declaration);
	if (constructors.length == 0) {
		AST ast = rewrite.getAST();
		MethodDeclaration newConstructor = ast.newMethodDeclaration();
		newConstructor.setConstructor(true);
		newConstructor.modifiers().addAll(ast.newModifiers(declaration.getModifiers() & ModifierRewrite.VISIBILITY_MODIFIERS));
		newConstructor.setName(ast.newSimpleName(declaration.getName().getIdentifier()));
		newConstructor.setBody(ast.newBlock());

		addFieldInitializationToConstructor(rewrite, newConstructor);

		int insertionIndex = computeInsertIndexForNewConstructor(declaration);
		rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertAt(newConstructor, insertionIndex, null);
	} else {
		for (int index = 0; index < constructors.length; index++) {
			if (shouldInsertTempInitialization(constructors[index])) {
				addFieldInitializationToConstructor(rewrite, constructors[index]);
			}
		}
	}
}
 
Example 3
Source File: InvertBooleanUtility.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static Expression combineOperands(ASTRewrite rewrite, Expression existing, Expression originalNode, boolean removeParentheses, Operator operator) {
	if (existing == null && removeParentheses) {
		while (originalNode instanceof ParenthesizedExpression) {
			originalNode = ((ParenthesizedExpression) originalNode).getExpression();
		}
	}
	Expression newRight = (Expression) rewrite.createMoveTarget(originalNode);
	if (originalNode instanceof InfixExpression) {
		((InfixExpression) newRight).setOperator(((InfixExpression) originalNode).getOperator());
	}

	if (existing == null) {
		return newRight;
	}
	AST ast = rewrite.getAST();
	InfixExpression infix = ast.newInfixExpression();
	infix.setOperator(operator);
	infix.setLeftOperand(existing);
	infix.setRightOperand(newRight);
	return infix;
}
 
Example 4
Source File: DimensionRewrite.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a {@link ASTRewrite#createCopyTarget(ASTNode) copy} of <code>type</code>
 * and adds <code>extraDimensions</code> to it.
 * 
 * @param type the type to copy
 * @param extraDimensions the dimensions to add
 * @param rewrite the ASTRewrite with which to create new nodes
 * @return the copy target with added dimensions
 */
public static Type copyTypeAndAddDimensions(Type type, List<Dimension> extraDimensions, ASTRewrite rewrite) {
	AST ast= rewrite.getAST();
	if (extraDimensions.isEmpty()) {
		return (Type) rewrite.createCopyTarget(type);
	}
	
	ArrayType result;
	if (type instanceof ArrayType) {
		ArrayType arrayType= (ArrayType) type;
		Type varElementType= (Type) rewrite.createCopyTarget(arrayType.getElementType());
		result= ast.newArrayType(varElementType, 0);
		result.dimensions().addAll(copyDimensions(extraDimensions, rewrite));
		result.dimensions().addAll(copyDimensions(arrayType.dimensions(), rewrite));
	} else {
		Type elementType= (Type) rewrite.createCopyTarget(type);
		result= ast.newArrayType(elementType, 0);
		result.dimensions().addAll(copyDimensions(extraDimensions, rewrite));
	}
	return result;
}
 
Example 5
Source File: CreateDoPrivilegedBlockResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private MethodDeclaration createRunMethodDeclaration(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
    AST ast = rewrite.getAST();

    MethodDeclaration methodDeclaration = ast.newMethodDeclaration();
    SimpleName methodName = ast.newSimpleName("run");
    Type returnType = (Type) rewrite.createCopyTarget(classLoaderCreation.getType());
    Block methodBody = createRunMethodBody(rewrite, classLoaderCreation);
    List<Modifier> modifiers = checkedList(methodDeclaration.modifiers());

    modifiers.add(ast.newModifier(PUBLIC_KEYWORD));
    methodDeclaration.setName(methodName);
    methodDeclaration.setReturnType2(returnType);
    methodDeclaration.setBody(methodBody);

    return methodDeclaration;
}
 
Example 6
Source File: NewAnnotationMemberProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Type getNewType(ASTRewrite rewrite) {
	AST ast= rewrite.getAST();
	Type newTypeNode= null;
	ITypeBinding binding= null;
	if (fInvocationNode.getLocationInParent() == MemberValuePair.NAME_PROPERTY) {
		Expression value= ((MemberValuePair) fInvocationNode.getParent()).getValue();
		binding= value.resolveTypeBinding();
	} else if (fInvocationNode instanceof Expression) {
		binding= ((Expression) fInvocationNode).resolveTypeBinding();
	}
	if (binding != null) {
		ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(fInvocationNode, getImportRewrite());
		newTypeNode= getImportRewrite().addImport(binding, ast, importRewriteContext);
	}
	if (newTypeNode == null) {
		newTypeNode= ast.newSimpleType(ast.newSimpleName("String")); //$NON-NLS-1$
	}
	addLinkedPosition(rewrite.track(newTypeNode), false, KEY_TYPE);
	return newTypeNode;
}
 
Example 7
Source File: CreateDoPrivilegedBlockResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected MethodInvocation createDoPrivilegedInvocation(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
    AST ast = rewrite.getAST();

    MethodInvocation doPrivilegedInvocation = ast.newMethodInvocation();
    ClassInstanceCreation privilegedActionCreation = createPrivilegedActionCreation(rewrite, classLoaderCreation);
    List<Expression> arguments = checkedList(doPrivilegedInvocation.arguments());

    if (!isStaticImport()) {
        Name accessControllerName;
        if (isUpdateImports()) {
            accessControllerName = ast.newSimpleName(AccessController.class.getSimpleName());
        } else {
            accessControllerName = ast.newName(AccessController.class.getName());
        }
        doPrivilegedInvocation.setExpression(accessControllerName);
    }
    doPrivilegedInvocation.setName(ast.newSimpleName(DO_PRIVILEGED_METHOD_NAME));
    arguments.add(privilegedActionCreation);

    return doPrivilegedInvocation;
}
 
Example 8
Source File: CreateAndOddnessCheckResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Creates the new <CODE>InfixExpression</CODE> <CODE>(x &amp; 1) == 1</CODE>.
 */
@Override
protected InfixExpression createCorrectOddnessCheck(ASTRewrite rewrite, Expression numberExpression) {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(numberExpression);

    final AST ast = rewrite.getAST();
    InfixExpression andOddnessCheck = ast.newInfixExpression();
    ParenthesizedExpression parenthesizedExpression = ast.newParenthesizedExpression();
    InfixExpression andExpression = ast.newInfixExpression();

    andExpression.setLeftOperand((Expression) rewrite.createMoveTarget(numberExpression));
    andExpression.setOperator(AND);
    andExpression.setRightOperand(ast.newNumberLiteral("1"));
    parenthesizedExpression.setExpression(andExpression);
    andOddnessCheck.setLeftOperand(parenthesizedExpression);
    andOddnessCheck.setOperator(EQUALS);
    andOddnessCheck.setRightOperand(ast.newNumberLiteral("1"));

    return andOddnessCheck;

}
 
Example 9
Source File: NewMethodCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected SimpleName getNewName(ASTRewrite rewrite) {
	ASTNode invocationNode= getInvocationNode();
	String name;
	if (invocationNode instanceof MethodInvocation) {
		name= ((MethodInvocation)invocationNode).getName().getIdentifier();
	} else if (invocationNode instanceof SuperMethodInvocation) {
		name= ((SuperMethodInvocation)invocationNode).getName().getIdentifier();
	} else {
		name= getSenderBinding().getName(); // name of the class
	}
	AST ast= rewrite.getAST();
	SimpleName newNameNode= ast.newSimpleName(name);
	addLinkedPosition(rewrite.track(newNameNode), false, KEY_NAME);

	ASTNode invocationName= getInvocationNameNode();
	if (invocationName != null && invocationName.getAST() == ast) { // in the same CU
		addLinkedPosition(rewrite.track(invocationName), true, KEY_NAME);
	}
	return newNameNode;
}
 
Example 10
Source File: NewMethodCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params, ImportRewriteContext context) throws CoreException {
	AST ast= rewrite.getAST();

	List<Expression> arguments= fArguments;

	for (int i= 0; i < arguments.size(); i++) {
		Expression elem= arguments.get(i);
		SingleVariableDeclaration param= ast.newSingleVariableDeclaration();

		// argument type
		String argTypeKey= "arg_type_" + i; //$NON-NLS-1$
		Type type= evaluateParameterType(ast, elem, argTypeKey, context);
		param.setType(type);

		// argument name
		String argNameKey= "arg_name_" + i; //$NON-NLS-1$
		String name= evaluateParameterName(takenNames, elem, type, argNameKey);
		param.setName(ast.newSimpleName(name));

		params.add(param);
	}
}
 
Example 11
Source File: CastCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Type getNewCastTypeNode(ASTRewrite rewrite, ImportRewrite importRewrite) {
	AST ast= rewrite.getAST();

	ImportRewriteContext context= new ContextSensitiveImportRewriteContext((CompilationUnit) fNodeToCast.getRoot(), fNodeToCast.getStartPosition(), importRewrite);

	if (fCastType != null) {
		return importRewrite.addImport(fCastType, ast,context);
	}

	ASTNode node= fNodeToCast;
	ASTNode parent= node.getParent();
	if (parent instanceof CastExpression) {
		node= parent;
		parent= parent.getParent();
	}
	while (parent instanceof ParenthesizedExpression) {
		node= parent;
		parent= parent.getParent();
	}
	if (parent instanceof MethodInvocation) {
		MethodInvocation invocation= (MethodInvocation) node.getParent();
		if (invocation.getExpression() == node) {
			IBinding targetContext= ASTResolving.getParentMethodOrTypeBinding(node);
			ITypeBinding[] bindings= ASTResolving.getQualifierGuess(node.getRoot(), invocation.getName().getIdentifier(), invocation.arguments(), targetContext);
			if (bindings.length > 0) {
				ITypeBinding first= getCastFavorite(bindings, fNodeToCast.resolveTypeBinding());

				Type newTypeNode= importRewrite.addImport(first, ast, context);
				addLinkedPosition(rewrite.track(newTypeNode), true, "casttype"); //$NON-NLS-1$
				for (int i= 0; i < bindings.length; i++) {
					addLinkedPositionProposal("casttype", bindings[i]); //$NON-NLS-1$
				}
				return newTypeNode;
			}
		}
	}
	Type newCastType= ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
	addLinkedPosition(rewrite.track(newCastType), true, "casttype"); //$NON-NLS-1$
	return newCastType;
}
 
Example 12
Source File: NewDefiningMethodProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void addNewExceptions(ASTRewrite rewrite, List<Type> exceptions) throws CoreException {
	AST ast= rewrite.getAST();
	ImportRewrite importRewrite= getImportRewrite();
	ITypeBinding[] bindings= fMethod.getExceptionTypes();
	for (int i= 0; i < bindings.length; i++) {
		Type newType= importRewrite.addImport(bindings[i], ast);
		exceptions.add(newType);

		addLinkedPosition(rewrite.track(newType), false, "exc_type_" + i); //$NON-NLS-1$
	}
}
 
Example 13
Source File: ChangeMethodSignatureProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void fixupNames(ASTRewrite rewrite, ArrayList<String> usedNames) {
	AST ast= rewrite.getAST();
	// set names for new parameters
	for (int i= 0; i < fParameterChanges.length; i++) {
		ChangeDescription curr= fParameterChanges[i];
		if (curr instanceof ModifyDescription) {
			ModifyDescription desc= (ModifyDescription) curr;

			String typeKey= getParamTypeGroupId(i);
			String nameKey= getParamNameGroupId(i);

			// collect name suggestions
			String favourite= null;
			String[] excludedNames= usedNames.toArray(new String[usedNames.size()]);

			String suggestedName= desc.name;
			if (suggestedName != null) {
				favourite= StubUtility.suggestArgumentName(getCompilationUnit().getJavaProject(), suggestedName, excludedNames);
			}

			Type type= desc.resultingParamType;
			String[] suggestedNames= StubUtility.getArgumentNameSuggestions(getCompilationUnit().getJavaProject(), type, excludedNames);
			if (favourite == null) {
				favourite= suggestedNames[0];
			}
			usedNames.add(favourite);

			SimpleName[] names= desc.resultingParamName;
			for (int j= 0; j < names.length; j++) {
				names[j].setIdentifier(favourite);
			}

			SimpleName tagArg= desc.resultingTagArg;
			if (tagArg != null) {
				tagArg.setIdentifier(favourite);
			}
		}
	}
}
 
Example 14
Source File: ExtractConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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);
	}
}
 
Example 15
Source File: CastCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private Type getNewCastTypeNode(ASTRewrite rewrite, ImportRewrite importRewrite) {
	AST ast= rewrite.getAST();

	ImportRewriteContext context= new ContextSensitiveImportRewriteContext((CompilationUnit) fNodeToCast.getRoot(), fNodeToCast.getStartPosition(), importRewrite);

	if (fCastType != null) {
		return importRewrite.addImport(fCastType, ast,context, TypeLocation.CAST);
	}

	ASTNode node= fNodeToCast;
	ASTNode parent= node.getParent();
	if (parent instanceof CastExpression) {
		node= parent;
		parent= parent.getParent();
	}
	while (parent instanceof ParenthesizedExpression) {
		node= parent;
		parent= parent.getParent();
	}
	if (parent instanceof MethodInvocation) {
		MethodInvocation invocation= (MethodInvocation) node.getParent();
		if (invocation.getExpression() == node) {
			IBinding targetContext= ASTResolving.getParentMethodOrTypeBinding(node);
			ITypeBinding[] bindings= ASTResolving.getQualifierGuess(node.getRoot(), invocation.getName().getIdentifier(), invocation.arguments(), targetContext);
			if (bindings.length > 0) {
				ITypeBinding first= getCastFavorite(bindings, fNodeToCast.resolveTypeBinding());

				Type newTypeNode= importRewrite.addImport(first, ast, context, TypeLocation.CAST);
				return newTypeNode;
			}
		}
	}
	Type newCastType= ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
	return newCastType;
}
 
Example 16
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates an {@link Assignment} as first expression appearing in a <code>for</code> loop's
 * body. This Assignment declares a local variable and initializes it using the array's current
 * element identified by the loop index.
 * 
 * @param rewrite the current {@link ASTRewrite} instance
 * @param loopVariableName the name of the index variable in String representation
 * @return a completed {@link Assignment} containing the mentioned declaration and
 *         initialization
 */
private Assignment getForBodyAssignment(ASTRewrite rewrite, SimpleName loopVariableName) {
	AST ast= rewrite.getAST();
	ITypeBinding loopOverType= extractElementType(ast);

	Assignment assignResolvedVariable= ast.newAssignment();

	// left hand side
	SimpleName resolvedVariableName= resolveLinkedVariableNameWithProposals(rewrite, loopOverType.getName(), loopVariableName.getIdentifier(), false);
	VariableDeclarationFragment resolvedVariableDeclarationFragment= ast.newVariableDeclarationFragment();
	resolvedVariableDeclarationFragment.setName(resolvedVariableName);
	VariableDeclarationExpression resolvedVariableDeclaration= ast.newVariableDeclarationExpression(resolvedVariableDeclarationFragment);
	resolvedVariableDeclaration.setType(getImportRewrite().addImport(loopOverType, ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite())));
	assignResolvedVariable.setLeftHandSide(resolvedVariableDeclaration);

	// right hand side
	ArrayAccess access= ast.newArrayAccess();
	access.setArray((Expression) rewrite.createCopyTarget(fCurrentExpression));
	SimpleName indexName= ast.newSimpleName(loopVariableName.getIdentifier());
	addLinkedPosition(rewrite.track(indexName), LinkedPositionGroup.NO_STOP, indexName.getIdentifier());
	access.setIndex(indexName);
	assignResolvedVariable.setRightHandSide(access);

	assignResolvedVariable.setOperator(Assignment.Operator.ASSIGN);

	return assignResolvedVariable;
}
 
Example 17
Source File: NewMethodCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params) throws CoreException {
	AST ast= rewrite.getAST();

	List<Expression> arguments= fArguments;
	ImportRewriteContext context= new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(getInvocationNode()), getImportRewrite());

	for (int i= 0; i < arguments.size(); i++) {
		Expression elem= arguments.get(i);
		SingleVariableDeclaration param= ast.newSingleVariableDeclaration();

		// argument type
		String argTypeKey= "arg_type_" + i; //$NON-NLS-1$
		Type type= evaluateParameterType(ast, elem, argTypeKey, context);
		param.setType(type);

		// argument name
		String argNameKey= "arg_name_" + i; //$NON-NLS-1$
		String name= evaluateParameterName(takenNames, elem, type, argNameKey);
		param.setName(ast.newSimpleName(name));

		params.add(param);

		addLinkedPosition(rewrite.track(param.getType()), false, argTypeKey);
		addLinkedPosition(rewrite.track(param.getName()), false, argNameKey);
	}
}
 
Example 18
Source File: StubUtility2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static MethodDeclaration createDelegationStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, IMethodBinding delegate, IVariableBinding delegatingField, CodeGenerationSettings settings) throws CoreException {
	Assert.isNotNull(delegate);
	Assert.isNotNull(delegatingField);
	Assert.isNotNull(settings);

	AST ast= rewrite.getAST();

	MethodDeclaration decl= ast.newMethodDeclaration();
	decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, delegate.getModifiers() & ~Modifier.SYNCHRONIZED & ~Modifier.ABSTRACT & ~Modifier.NATIVE));

	decl.setName(ast.newSimpleName(delegate.getName()));
	decl.setConstructor(false);

	createTypeParameters(imports, context, ast, delegate, decl);

	decl.setReturnType2(imports.addImport(delegate.getReturnType(), ast, context));

	List<SingleVariableDeclaration> params= createParameters(unit.getJavaProject(), imports, context, ast, delegate, null, decl);

	createThrownExceptions(decl, delegate, imports, context, ast);

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

	String delimiter= StubUtility.getLineDelimiterUsed(unit);

	Statement statement= null;
	MethodInvocation invocation= ast.newMethodInvocation();
	invocation.setName(ast.newSimpleName(delegate.getName()));
	List<Expression> arguments= invocation.arguments();
	for (int i= 0; i < params.size(); i++)
		arguments.add(ast.newSimpleName(params.get(i).getName().getIdentifier()));
	if (settings.useKeywordThis) {
		FieldAccess access= ast.newFieldAccess();
		access.setExpression(ast.newThisExpression());
		access.setName(ast.newSimpleName(delegatingField.getName()));
		invocation.setExpression(access);
	} else
		invocation.setExpression(ast.newSimpleName(delegatingField.getName()));
	if (delegate.getReturnType().isPrimitive() && delegate.getReturnType().getName().equals("void")) {//$NON-NLS-1$
		statement= ast.newExpressionStatement(invocation);
	} else {
		ReturnStatement returnStatement= ast.newReturnStatement();
		returnStatement.setExpression(invocation);
		statement= returnStatement;
	}
	body.statements().add(statement);

	ITypeBinding declaringType= delegatingField.getDeclaringClass();
	if (declaringType == null) { // can be null for
		return decl;
	}

	String qualifiedName= declaringType.getQualifiedName();
	IPackageBinding packageBinding= declaringType.getPackage();
	if (packageBinding != null) {
		if (packageBinding.getName().length() > 0 && qualifiedName.startsWith(packageBinding.getName()))
			qualifiedName= qualifiedName.substring(packageBinding.getName().length());
	}

	if (settings.createComments) {
		/*
		 * TODO: have API for delegate method comments This is an inlined
		 * version of
		 * {@link CodeGeneration#getMethodComment(ICompilationUnit, String, MethodDeclaration, IMethodBinding, String)}
		 */
		delegate= delegate.getMethodDeclaration();
		String declaringClassQualifiedName= delegate.getDeclaringClass().getQualifiedName();
		String linkToMethodName= delegate.getName();
		String[] parameterTypesQualifiedNames= StubUtility.getParameterTypeNamesForSeeTag(delegate);
		String string= StubUtility.getMethodComment(unit, qualifiedName, decl, delegate.isDeprecated(), linkToMethodName, declaringClassQualifiedName, parameterTypesQualifiedNames, true, delimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 19
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, IMethodBinding binding, String type, int modifiers, boolean omitSuperForDefConst, boolean todo, 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(type));
	decl.setConstructor(true);

	createTypeParameters(imports, context, ast, binding, decl);

	List<SingleVariableDeclaration> parameters= createParameters(unit.getJavaProject(), imports, context, ast, binding, null, decl);

	createThrownExceptions(decl, binding, imports, context, ast);

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

	String delimiter= StubUtility.getLineDelimiterUsed(unit);
	String bodyStatement= ""; //$NON-NLS-1$
	if (!omitSuperForDefConst || !parameters.isEmpty()) {
		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()));
		}
		bodyStatement= ASTNodes.asFormattedString(invocation, 0, delimiter, unit.getJavaProject().getOptions(true));
	}

	if (todo) {
		String placeHolder= CodeGeneration.getMethodBodyContent(unit, type, binding.getName(), true, bodyStatement, delimiter);
		if (placeHolder != null) {
			ReturnStatement todoNode= (ReturnStatement) rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
			body.statements().add(todoNode);
		}
	} else {
		ReturnStatement statementNode= (ReturnStatement) rewrite.createStringPlaceholder(bodyStatement, ASTNode.RETURN_STATEMENT);
		body.statements().add(statementNode);
	}

	if (settings != null && settings.createComments) {
		String string= CodeGeneration.getMethodComment(unit, type, decl, binding, delimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 20
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);
	}
}