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

The following examples show how to use org.eclipse.jdt.core.dom.AST#newMethodInvocation() . 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: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generates the Assignment in an iterator based for, used in the first statement of an iterator
 * based <code>for</code> loop body, to retrieve the next element of the {@link Iterable}
 * instance.
 * 
 * @param rewrite the current instance of {@link ASTRewrite}
 * @param loopOverType the {@link ITypeBinding} of the loop variable
 * @param loopVariableName the name of the loop variable
 * @return an {@link Assignment}, which retrieves the next element of the {@link Iterable} using
 *         the active {@link Iterator}
 */
private Assignment getIteratorBasedForBodyAssignment(ASTRewrite rewrite, ITypeBinding loopOverType, SimpleName loopVariableName) {
	AST ast= rewrite.getAST();
	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
	MethodInvocation invokeIteratorNextExpression= ast.newMethodInvocation();
	invokeIteratorNextExpression.setName(ast.newSimpleName("next")); //$NON-NLS-1$
	SimpleName currentElementName= ast.newSimpleName(loopVariableName.getIdentifier());
	addLinkedPosition(rewrite.track(currentElementName), LinkedPositionGroup.NO_STOP, currentElementName.getIdentifier());
	invokeIteratorNextExpression.setExpression(currentElementName);
	assignResolvedVariable.setRightHandSide(invokeIteratorNextExpression);

	assignResolvedVariable.setOperator(Assignment.Operator.ASSIGN);

	return assignResolvedVariable;
}
 
Example 3
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 4
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 5
Source File: UseValueOfResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected MethodInvocation createValueOfInvocation(ASTRewrite rewrite, CompilationUnit compilationUnit,
        ClassInstanceCreation primitiveTypeCreation) {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(primitiveTypeCreation);

    final AST ast = rewrite.getAST();
    MethodInvocation valueOfInvocation = ast.newMethodInvocation();
    valueOfInvocation.setName(ast.newSimpleName(VALUE_OF_METHOD_NAME));

    ITypeBinding binding = primitiveTypeCreation.getType().resolveBinding();
    if (isStaticImport()) {
        addStaticImports(rewrite, compilationUnit, binding.getQualifiedName() + "." + VALUE_OF_METHOD_NAME);
    } else {
        valueOfInvocation.setExpression(ast.newSimpleName(binding.getName()));
    }

    List<?> arguments = primitiveTypeCreation.arguments();
    List<Expression> newArguments = valueOfInvocation.arguments();
    for (Object argument : arguments) {
        Expression expression = (Expression) rewrite.createCopyTarget((ASTNode) argument);
        newArguments.add(expression);
    }

    return valueOfInvocation;
}
 
Example 6
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generates the initializer for an iterator based <code>for</code> loop, which declares and
 * initializes the variable to loop over.
 * 
 * @param rewrite the instance of {@link ASTRewrite}
 * @param loopVariableName the proposed name of the loop variable
 * @return a {@link VariableDeclarationExpression} to use as initializer
 */
private VariableDeclarationExpression getIteratorBasedForInitializer(ASTRewrite rewrite, SimpleName loopVariableName) {
	AST ast= rewrite.getAST();
	IMethodBinding iteratorMethodBinding= Bindings.findMethodInHierarchy(fExpressionType, "iterator", new ITypeBinding[] {}); //$NON-NLS-1$
	// initializing fragment
	VariableDeclarationFragment varDeclarationFragment= ast.newVariableDeclarationFragment();
	varDeclarationFragment.setName(loopVariableName);
	MethodInvocation iteratorExpression= ast.newMethodInvocation();
	iteratorExpression.setName(ast.newSimpleName(iteratorMethodBinding.getName()));
	iteratorExpression.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression));
	varDeclarationFragment.setInitializer(iteratorExpression);

	// declaration
	VariableDeclarationExpression varDeclarationExpression= ast.newVariableDeclarationExpression(varDeclarationFragment);
	varDeclarationExpression.setType(getImportRewrite().addImport(iteratorMethodBinding.getReturnType(), ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite())));

	return varDeclarationExpression;
}
 
Example 7
Source File: PullUpRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public final boolean visit(final SuperMethodInvocation node) {
	if (!fAnonymousClassDeclaration && !fTypeDeclarationStatement) {
		final IBinding superBinding= node.getName().resolveBinding();
		if (superBinding instanceof IMethodBinding) {
			final IMethodBinding extended= (IMethodBinding) superBinding;
			if (fEnclosingMethod != null && fEnclosingMethod.overrides(extended))
				return true;
			final ITypeBinding declaringBinding= extended.getDeclaringClass();
			if (declaringBinding != null) {
				final IType type= (IType) declaringBinding.getJavaElement();
				if (!fSuperReferenceType.equals(type))
					return true;
			}
		}
		final AST ast= node.getAST();
		final ThisExpression expression= ast.newThisExpression();
		final MethodInvocation invocation= ast.newMethodInvocation();
		final SimpleName simple= ast.newSimpleName(node.getName().getIdentifier());
		invocation.setName(simple);
		invocation.setExpression(expression);
		final List<Expression> arguments= node.arguments();
		if (arguments != null && arguments.size() > 0) {
			final ListRewrite rewriter= fRewrite.getListRewrite(invocation, MethodInvocation.ARGUMENTS_PROPERTY);
			ListRewrite superRewriter= fRewrite.getListRewrite(node, SuperMethodInvocation.ARGUMENTS_PROPERTY);
			ASTNode copyTarget= superRewriter.createCopyTarget(arguments.get(0), arguments.get(arguments.size() - 1));
			rewriter.insertLast(copyTarget, null);
		}
		fRewrite.replace(node, invocation, null);
		if (!fSourceRewriter.getCu().equals(fTargetRewriter.getCu()))
			fSourceRewriter.getImportRemover().registerRemovedNode(node);
		return true;
	}
	return false;
}
 
Example 8
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 an index based
 * <code>for</code> loop's body. This Assignment declares a local variable and initializes it
 * using the {@link List}'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 Expression getIndexBasedForBodyAssignment(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
	MethodInvocation invokeGetExpression= ast.newMethodInvocation();
	invokeGetExpression.setName(ast.newSimpleName("get")); //$NON-NLS-1$
	SimpleName indexVariableName= ast.newSimpleName(loopVariableName.getIdentifier());
	addLinkedPosition(rewrite.track(indexVariableName), LinkedPositionGroup.NO_STOP, indexVariableName.getIdentifier());
	invokeGetExpression.arguments().add(indexVariableName);
	invokeGetExpression.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression));
	assignResolvedVariable.setRightHandSide(invokeGetExpression);

	assignResolvedVariable.setOperator(Assignment.Operator.ASSIGN);

	return assignResolvedVariable;
}
 
Example 9
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Helper to generate an iterator based <code>for</code> loop to iterate over an
 * {@link Iterable}.
 * 
 * @param ast the {@link AST} instance to rewrite the loop to
 * @return the complete {@link ASTRewrite} object
 */
private ASTRewrite generateIteratorBasedForRewrite(AST ast) {
	ASTRewrite rewrite= ASTRewrite.create(ast);
	ForStatement loopStatement= ast.newForStatement();

	ITypeBinding loopOverType= extractElementType(ast);

	SimpleName loopVariableName= resolveLinkedVariableNameWithProposals(rewrite, "iterator", null, true); //$NON-NLS-1$
	loopStatement.initializers().add(getIteratorBasedForInitializer(rewrite, loopVariableName));

	MethodInvocation loopExpression= ast.newMethodInvocation();
	loopExpression.setName(ast.newSimpleName("hasNext")); //$NON-NLS-1$
	SimpleName expressionName= ast.newSimpleName(loopVariableName.getIdentifier());
	addLinkedPosition(rewrite.track(expressionName), LinkedPositionGroup.NO_STOP, expressionName.getIdentifier());
	loopExpression.setExpression(expressionName);

	loopStatement.setExpression(loopExpression);

	Block forLoopBody= ast.newBlock();
	Assignment assignResolvedVariable= getIteratorBasedForBodyAssignment(rewrite, loopOverType, loopVariableName);
	forLoopBody.statements().add(ast.newExpressionStatement(assignResolvedVariable));
	forLoopBody.statements().add(createBlankLineStatementWithCursorPosition(rewrite));

	loopStatement.setBody(forLoopBody);

	rewrite.replace(fCurrentNode, loopStatement, null);

	return rewrite;
}
 
Example 10
Source File: AccessAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private MethodInvocation createInvocation(AST ast, Expression operand, String operator) {
	Expression receiver= getReceiver(operand);
	MethodInvocation invocation= ast.newMethodInvocation();
	invocation.setName(ast.newSimpleName(fSetter));
	if (receiver != null)
		invocation.setExpression((Expression)fRewriter.createCopyTarget(receiver));
	InfixExpression argument= ast.newInfixExpression();
	invocation.arguments().add(argument);
	if ("++".equals(operator)) { //$NON-NLS-1$
		argument.setOperator(InfixExpression.Operator.PLUS);
	} else if ("--".equals(operator)) { //$NON-NLS-1$
		argument.setOperator(InfixExpression.Operator.MINUS);
	} else {
		Assert.isTrue(false, "Should not happen"); //$NON-NLS-1$
	}
	MethodInvocation getter= ast.newMethodInvocation();
	getter.setName(ast.newSimpleName(fGetter));
	if (receiver != null)
		getter.setExpression((Expression)fRewriter.createCopyTarget(receiver));
	argument.setLeftOperand(getter);
	argument.setRightOperand(ast.newNumberLiteral("1")); //$NON-NLS-1$

	fReferencingGetter= true;
	fReferencingSetter= true;

	return invocation;
}
 
Example 11
Source File: StaticMethodInvocationFragment.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public MethodInvocation createStaticMethodInvocation(AST ast, String className, String methodName) {
    SimpleName typeName = ast.newSimpleName(className);

    MethodInvocation methodInvocation = ast.newMethodInvocation();
    methodInvocation.setName(ast.newSimpleName(methodName));
    methodInvocation.setExpression(typeName);

    return methodInvocation;
}
 
Example 12
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public Expression createFieldWriteAccess(ParameterInfo pi, String paramName, AST ast, IJavaProject project, Expression assignedValue, boolean useSuper, Expression qualifier) {
	Expression completeQualifier= generateQualifier(paramName, ast, useSuper, qualifier);
	if (fCreateSetter) {
		MethodInvocation mi= ast.newMethodInvocation();
		mi.setName(ast.newSimpleName(getSetterName(pi, ast, project)));
		mi.setExpression(completeQualifier);
		mi.arguments().add(assignedValue);
		return mi;
	}
	return createFieldAccess(pi, ast, completeQualifier);
}
 
Example 13
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public Expression createFieldReadAccess(ParameterInfo pi, String paramName, AST ast, IJavaProject project, boolean useSuper, Expression qualifier) {
	Expression completeQualifier= generateQualifier(paramName, ast, useSuper, qualifier);
	if (fCreateGetter) {
		MethodInvocation mi= ast.newMethodInvocation();
		mi.setName(ast.newSimpleName(getGetterName(pi, ast, project)));
		mi.setExpression(completeQualifier);
		return mi;
	}
	return createFieldAccess(pi, ast, completeQualifier);
}
 
Example 14
Source File: AccessAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private MethodInvocation createInvocation(AST ast, Expression operand, String operator) {
	Expression receiver = getReceiver(operand);
	MethodInvocation invocation = ast.newMethodInvocation();
	invocation.setName(ast.newSimpleName(fSetter));
	if (receiver != null) {
		invocation.setExpression((Expression) fRewriter.createCopyTarget(receiver));
	}
	InfixExpression argument = ast.newInfixExpression();
	invocation.arguments().add(argument);
	if ("++".equals(operator)) { //$NON-NLS-1$
		argument.setOperator(InfixExpression.Operator.PLUS);
	} else if ("--".equals(operator)) { //$NON-NLS-1$
		argument.setOperator(InfixExpression.Operator.MINUS);
	} else {
		Assert.isTrue(false, "Should not happen"); //$NON-NLS-1$
	}
	MethodInvocation getter = ast.newMethodInvocation();
	getter.setName(ast.newSimpleName(fGetter));
	if (receiver != null) {
		getter.setExpression((Expression) fRewriter.createCopyTarget(receiver));
	}
	argument.setLeftOperand(getter);
	argument.setRightOperand(ast.newNumberLiteral("1")); //$NON-NLS-1$

	fReferencingGetter = true;
	fReferencingSetter = true;

	return invocation;
}
 
Example 15
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 16
Source File: AccessAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public boolean visit(Assignment node) {
	Expression leftHandSide= node.getLeftHandSide();
	if (!considerBinding(resolveBinding(leftHandSide), leftHandSide))
		return true;

	checkParent(node);
	Expression rightHandSide= node.getRightHandSide();
	if (!fIsFieldFinal) {
		// Write access.
		AST ast= node.getAST();
		MethodInvocation invocation= ast.newMethodInvocation();
		invocation.setName(ast.newSimpleName(fSetter));
		fReferencingSetter= true;
		Expression receiver= getReceiver(leftHandSide);
		if (receiver != null)
			invocation.setExpression((Expression)fRewriter.createCopyTarget(receiver));
		List<Expression> arguments= invocation.arguments();
		if (node.getOperator() == Assignment.Operator.ASSIGN) {
			arguments.add((Expression)fRewriter.createCopyTarget(rightHandSide));
		} else {
			// This is the compound assignment case: field+= 10;
			InfixExpression exp= ast.newInfixExpression();
			exp.setOperator(ASTNodes.convertToInfixOperator(node.getOperator()));
			MethodInvocation getter= ast.newMethodInvocation();
			getter.setName(ast.newSimpleName(fGetter));
			fReferencingGetter= true;
			if (receiver != null)
				getter.setExpression((Expression)fRewriter.createCopyTarget(receiver));
			exp.setLeftOperand(getter);
			Expression rhs= (Expression)fRewriter.createCopyTarget(rightHandSide);
			if (NecessaryParenthesesChecker.needsParenthesesForRightOperand(rightHandSide, exp, leftHandSide.resolveTypeBinding())) {
				ParenthesizedExpression p= ast.newParenthesizedExpression();
				p.setExpression(rhs);
				rhs= p;
			}
			exp.setRightOperand(rhs);
			arguments.add(exp);
		}
		fRewriter.replace(node, invocation, createGroupDescription(WRITE_ACCESS));
	}
	rightHandSide.accept(this);
	return false;
}
 
Example 17
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 18
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void addDeprecatedFieldsToMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof Name) {
		IBinding binding= ((Name) selectedNode).resolveBinding();
		if (binding instanceof IVariableBinding) {
			IVariableBinding variableBinding= (IVariableBinding) binding;
			if (variableBinding.isField()) {
				String qualifiedName= variableBinding.getDeclaringClass().getTypeDeclaration().getQualifiedName();
				String fieldName= variableBinding.getName();
				String[] methodName= getMethod(JavaModelUtil.concatenateName(qualifiedName, fieldName));
				if (methodName != null) {
					AST ast= selectedNode.getAST();
					ASTRewrite astRewrite= ASTRewrite.create(ast);
					ImportRewrite importRewrite= StubUtility.createImportRewrite(context.getASTRoot(), true);

					MethodInvocation method= ast.newMethodInvocation();
					String qfn= importRewrite.addImport(methodName[0]);
					method.setExpression(ast.newName(qfn));
					method.setName(ast.newSimpleName(methodName[1]));
					ASTNode parent= selectedNode.getParent();
					ICompilationUnit cu= context.getCompilationUnit();
					// add explicit type arguments if necessary (for 1.8 and later, we're optimistic that inference just works):
					if (Invocations.isInvocationWithArguments(parent) && !JavaModelUtil.is18OrHigher(cu.getJavaProject())) {
						IMethodBinding methodBinding= Invocations.resolveBinding(parent);
						if (methodBinding != null) {
							ITypeBinding[] parameterTypes= methodBinding.getParameterTypes();
							int i= Invocations.getArguments(parent).indexOf(selectedNode);
							if (parameterTypes.length >= i && parameterTypes[i].isParameterizedType()) {
								ITypeBinding[] typeArguments= parameterTypes[i].getTypeArguments();
								for (int j= 0; j < typeArguments.length; j++) {
									ITypeBinding typeArgument= typeArguments[j];
									typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast);
									if (! TypeRules.isJavaLangObject(typeArgument)) {
										// add all type arguments if at least one is found to be necessary:
										List<Type> typeArgumentsList= method.typeArguments();
										for (int k= 0; k < typeArguments.length; k++) {
											typeArgument= typeArguments[k];
											typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast);
											typeArgumentsList.add(importRewrite.addImport(typeArgument, ast));
										}
										break;
									}
								}
							}
						}
					}
					
					astRewrite.replace(selectedNode, method, null);

					String label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_replacefieldaccesswithmethod_description, BasicElementLabels.getJavaElementName(ASTNodes.asString(method)));
					Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
					ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, astRewrite, IProposalRelevance.REPLACE_FIELD_ACCESS_WITH_METHOD, image);
					proposal.setImportRewrite(importRewrite);
					proposals.add(proposal);
				}
			}
		}
	}
}
 
Example 19
Source File: AccessAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public boolean visit(Assignment node) {
	Expression leftHandSide = node.getLeftHandSide();
	if (!considerBinding(resolveBinding(leftHandSide), leftHandSide)) {
		return true;
	}

	checkParent(node);
	Expression rightHandSide = node.getRightHandSide();
	if (!fIsFieldFinal) {
		// Write access.
		AST ast = node.getAST();
		MethodInvocation invocation = ast.newMethodInvocation();
		invocation.setName(ast.newSimpleName(fSetter));
		fReferencingSetter = true;
		Expression receiver = getReceiver(leftHandSide);
		if (receiver != null) {
			invocation.setExpression((Expression) fRewriter.createCopyTarget(receiver));
		}
		List<Expression> arguments = invocation.arguments();
		if (node.getOperator() == Assignment.Operator.ASSIGN) {
			arguments.add((Expression) fRewriter.createCopyTarget(rightHandSide));
		} else {
			// This is the compound assignment case: field+= 10;
			InfixExpression exp = ast.newInfixExpression();
			exp.setOperator(ASTNodes.convertToInfixOperator(node.getOperator()));
			MethodInvocation getter = ast.newMethodInvocation();
			getter.setName(ast.newSimpleName(fGetter));
			fReferencingGetter = true;
			if (receiver != null) {
				getter.setExpression((Expression) fRewriter.createCopyTarget(receiver));
			}
			exp.setLeftOperand(getter);
			Expression rhs = (Expression) fRewriter.createCopyTarget(rightHandSide);
			if (NecessaryParenthesesChecker.needsParenthesesForRightOperand(rightHandSide, exp, leftHandSide.resolveTypeBinding())) {
				ParenthesizedExpression p = ast.newParenthesizedExpression();
				p.setExpression(rhs);
				rhs = p;
			}
			exp.setRightOperand(rhs);
			arguments.add(exp);
		}
		fRewriter.replace(node, invocation, createGroupDescription(WRITE_ACCESS));
	}
	rightHandSide.accept(this);
	return false;
}