Java Code Examples for org.eclipse.jdt.core.dom.MethodInvocation#setExpression()

The following examples show how to use org.eclipse.jdt.core.dom.MethodInvocation#setExpression() . 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: BaseTranslator.java    From junion with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Expression methodB(String methodName, Type castType, Object... args) {
		MethodInvocation p = ast.newMethodInvocation();
		p.setExpression(name(MEM0_B));
//		p.setName(name(Translator.StringCache.getString(
//				type,
//				t,
//				opsymbol)));
		p.setName(name(methodName));

		for(Object arg : args)
			p.arguments().add(arg);
		
		if(castType != null) {
			CastExpression cast = ast.newCastExpression();			
			cast.setType(castType);
			cast.setExpression(p);
			cast.setProperty(TYPEBIND_PROP, FieldType.OBJECT);
			return cast;
		}
		return p;
	}
 
Example 2
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 3
Source File: GenerateHashCodeEqualsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Statement createOuterComparison() {
	MethodInvocation outer1= fAst.newMethodInvocation();
	outer1.setName(fAst.newSimpleName(METHODNAME_OUTER_TYPE));

	MethodInvocation outer2= fAst.newMethodInvocation();
	outer2.setName(fAst.newSimpleName(METHODNAME_OUTER_TYPE));
	outer2.setExpression(fAst.newSimpleName(VARIABLE_NAME_EQUALS_CASTED));

	MethodInvocation outerEql= fAst.newMethodInvocation();
	outerEql.setName(fAst.newSimpleName(METHODNAME_EQUALS));
	outerEql.setExpression(outer1);
	outerEql.arguments().add(outer2);

	PrefixExpression not= fAst.newPrefixExpression();
	not.setOperand(outerEql);
	not.setOperator(PrefixExpression.Operator.NOT);

	IfStatement notEqNull= fAst.newIfStatement();
	notEqNull.setExpression(not);
	notEqNull.setThenStatement(getThenStatement(getReturnFalse()));
	return notEqNull;
}
 
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: 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 6
Source File: GenStatement.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
private static Statement genPrinter(Expression expression) {
	MethodInvocation methodInvocation = ast.newMethodInvocation();
	methodInvocation.setExpression(ast.newName("System.out"));
	methodInvocation.setName(ast.newSimpleName("println"));
	methodInvocation.arguments().add(expression);
	ExpressionStatement expressionStatement = ast.newExpressionStatement(methodInvocation);
	return expressionStatement;
}
 
Example 7
Source File: AbstractToStringGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates an invocation of a method that takes zero or one argument
 * 
 * @param expression the receiver expression
 * @param methodName the method name
 * @param argument the argument, can be <code>null</code> if the method does not take any arguments
 * @return MethodInvocation in following form: <code>expression.methodName(argument)</code>
 */
protected MethodInvocation createMethodInvocation(Expression expression, String methodName, Expression argument) {
	MethodInvocation invocation= fAst.newMethodInvocation();
	invocation.setExpression(expression);
	invocation.setName(fAst.newSimpleName(methodName));
	if (argument != null)
		invocation.arguments().add(argument);
	return invocation;
}
 
Example 8
Source File: GenerateHashCodeEqualsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Expression createMethodInvocation(Expression access, String qualifiedClassName, String methodName) {
	MethodInvocation invoc= fAst.newMethodInvocation();
	invoc.setExpression(getQualifiedName(qualifiedClassName));
	invoc.setName(fAst.newSimpleName(methodName));
	invoc.arguments().add(access);
	return invoc;
}
 
Example 9
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 10
Source File: AbstractToStringGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected Expression createSubListInvocation(Expression memberAccess, Expression sizeAccess) {
	MethodInvocation subListInvocation= fAst.newMethodInvocation();
	subListInvocation.setExpression(memberAccess);
	subListInvocation.setName(fAst.newSimpleName("subList")); //$NON-NLS-1$
	subListInvocation.arguments().add(fAst.newNumberLiteral(String.valueOf(0)));

	MethodInvocation minInvocation= createMethodInvocation(addImport("java.lang.Math"), "min", sizeAccess); //$NON-NLS-1$ //$NON-NLS-2$
	minInvocation.arguments().add(fAst.newSimpleName(fMaxLenVariableName));
	subListInvocation.arguments().add(minInvocation);
	needMaxLenVariable= true;
	return subListInvocation;
}
 
Example 11
Source File: CreateMutableCloneResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @param workingUnit
 * @param original
 * @return
 */
private MethodInvocation invokeClone(CompilationUnit workingUnit, SimpleName original) {
    MethodInvocation cloneInvoke = workingUnit.getAST().newMethodInvocation();
    Expression cloneField = (SimpleName) ASTNode.copySubtree(cloneInvoke.getAST(), original);
    SimpleName cloneName = workingUnit.getAST().newSimpleName("clone");
    cloneInvoke.setExpression(cloneField);
    cloneInvoke.setName(cloneName);
    return cloneInvoke;
}
 
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: StringBuilderChainGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void appendExpression(Expression expression) {
	MethodInvocation appendInvocation= fAst.newMethodInvocation();
	if (temporaryExpression != null)
		appendInvocation.setExpression(temporaryExpression);
	else
		appendInvocation.setExpression(fAst.newSimpleName(fBuilderVariableName));
	appendInvocation.setName(fAst.newSimpleName(APPEND_METHOD_NAME));
	appendInvocation.arguments().add(expression);
	temporaryExpression= appendInvocation;
}
 
Example 14
Source File: CustomBuilderGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public MethodDeclaration generateToStringMethod() throws CoreException {
	initialize();

	//ToStringBuilder builder= new ToStringBuilder(this);
	String builderVariableName= createNameSuggestion(getContext().getCustomBuilderVariableName(), NamingConventions.VK_LOCAL);
	VariableDeclarationFragment fragment= fAst.newVariableDeclarationFragment();
	fragment.setName(fAst.newSimpleName(builderVariableName));
	ClassInstanceCreation classInstance= fAst.newClassInstanceCreation();
	Name typeName= addImport(getContext().getCustomBuilderClass());
	classInstance.setType(fAst.newSimpleType(typeName));
	classInstance.arguments().add(fAst.newThisExpression());
	fragment.setInitializer(classInstance);
	VariableDeclarationStatement vStatement= fAst.newVariableDeclarationStatement(fragment);
	vStatement.setType(fAst.newSimpleType((Name)ASTNode.copySubtree(fAst, typeName)));
	toStringMethod.getBody().statements().add(vStatement);

	/* expression for accumulating chained calls */
	Expression expression= null;

	for (int i= 0; i < getContext().getSelectedMembers().length; i++) {
		//builder.append("member", member);
		MethodInvocation appendInvocation= createAppendMethodForMember(getContext().getSelectedMembers()[i]);
		if (getContext().isSkipNulls() && !getMemberType(getContext().getSelectedMembers()[i]).isPrimitive()) {
			if (expression != null) {
				toStringMethod.getBody().statements().add(fAst.newExpressionStatement(expression));
				expression= null;
			}
			appendInvocation.setExpression(fAst.newSimpleName(builderVariableName));
			IfStatement ifStatement= fAst.newIfStatement();
			ifStatement.setExpression(createInfixExpression(createMemberAccessExpression(getContext().getSelectedMembers()[i], true, true), Operator.NOT_EQUALS, fAst.newNullLiteral()));
			ifStatement.setThenStatement(createOneStatementBlock(appendInvocation));
			toStringMethod.getBody().statements().add(ifStatement);
		} else {
			if (expression != null) {
				appendInvocation.setExpression(expression);
			} else {
				appendInvocation.setExpression(fAst.newSimpleName(builderVariableName));
			}
			if (getContext().isCustomBuilderChainedCalls() && canChainLastAppendCall) {
				expression= appendInvocation;
			} else {
				expression= null;
				toStringMethod.getBody().statements().add(fAst.newExpressionStatement(appendInvocation));
			}
		}
	}

	if (expression != null) {
		toStringMethod.getBody().statements().add(fAst.newExpressionStatement(expression));
	}
	// return builder.toString();
	ReturnStatement rStatement= fAst.newReturnStatement();
	rStatement.setExpression(createMethodInvocation(builderVariableName, getContext().getCustomBuilderResultMethod(), null));
	toStringMethod.getBody().statements().add(rStatement);

	complete();

	return toStringMethod;
}
 
Example 15
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void createIntermediaryMethod() throws CoreException {

		CompilationUnitRewrite imRewrite= getCachedCURewrite(fIntermediaryType.getCompilationUnit());
		AST ast= imRewrite.getAST();
		MethodDeclaration intermediary= ast.newMethodDeclaration();

		// Intermediary class is non-anonymous
		AbstractTypeDeclaration type= (AbstractTypeDeclaration)typeToDeclaration(fIntermediaryType, imRewrite.getRoot());

		// Name
		intermediary.setName(ast.newSimpleName(fIntermediaryMethodName));

		// Flags
		List<IExtendedModifier> modifiers= intermediary.modifiers();
		if (!fIntermediaryType.isInterface()) {
			modifiers.add(imRewrite.getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD));
		}
		modifiers.add(imRewrite.getAST().newModifier(ModifierKeyword.STATIC_KEYWORD));

		// Parameters
		String targetParameterName= StubUtility.suggestArgumentName(getProject(), fIntermediaryFirstParameterType.getName(), fTargetMethod.getParameterNames());

		ImportRewriteContext context= new ContextSensitiveImportRewriteContext(type, imRewrite.getImportRewrite());
		if (!isStaticTarget()) {
			// Add first param
			SingleVariableDeclaration parameter= imRewrite.getAST().newSingleVariableDeclaration();
			Type t= imRewrite.getImportRewrite().addImport(fIntermediaryFirstParameterType, imRewrite.getAST(), context);
			if (fIntermediaryFirstParameterType.isGenericType()) {
				ParameterizedType parameterized= imRewrite.getAST().newParameterizedType(t);
				ITypeBinding[] typeParameters= fIntermediaryFirstParameterType.getTypeParameters();
				for (int i= 0; i < typeParameters.length; i++)
					parameterized.typeArguments().add(imRewrite.getImportRewrite().addImport(typeParameters[i], imRewrite.getAST()));
				t= parameterized;
			}
			parameter.setType(t);
			parameter.setName(imRewrite.getAST().newSimpleName(targetParameterName));
			intermediary.parameters().add(parameter);
		}
		// Add other params
		copyArguments(intermediary, imRewrite);

		// Add type parameters of declaring type (and enclosing types)
		if (!isStaticTarget() && fIntermediaryFirstParameterType.isGenericType())
			addTypeParameters(imRewrite, intermediary.typeParameters(), fIntermediaryFirstParameterType);

		// Add type params of method
		copyTypeParameters(intermediary, imRewrite);

		// Return type
		intermediary.setReturnType2(imRewrite.getImportRewrite().addImport(fTargetMethodBinding.getReturnType(), ast, context));

		// Exceptions
		copyExceptions(intermediary, imRewrite);

		// Body
		MethodInvocation invocation= imRewrite.getAST().newMethodInvocation();
		invocation.setName(imRewrite.getAST().newSimpleName(fTargetMethod.getElementName()));
		if (isStaticTarget()) {
			Type importedType= imRewrite.getImportRewrite().addImport(fTargetMethodBinding.getDeclaringClass(), ast, context);
			invocation.setExpression(ASTNodeFactory.newName(ast, ASTNodes.asString(importedType)));
		} else {
			invocation.setExpression(imRewrite.getAST().newSimpleName(targetParameterName));
		}
		copyInvocationParameters(invocation, ast);
		Statement call= encapsulateInvocation(intermediary, invocation);

		final Block body= imRewrite.getAST().newBlock();
		body.statements().add(call);
		intermediary.setBody(body);

		// method comment
		ICompilationUnit targetCU= imRewrite.getCu();
		if (StubUtility.doAddComments(targetCU.getJavaProject())) {
			String comment= CodeGeneration.getMethodComment(targetCU, getIntermediaryTypeName(), intermediary, null, StubUtility.getLineDelimiterUsed(targetCU));
			if (comment != null) {
				Javadoc javadoc= (Javadoc) imRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC);
				intermediary.setJavadoc(javadoc);
			}
		}

		// Add the completed method to the intermediary type:
		ChildListPropertyDescriptor typeBodyDeclarationsProperty= typeToBodyDeclarationProperty(fIntermediaryType, imRewrite.getRoot());

		ListRewrite bodyDeclarationsListRewrite= imRewrite.getASTRewrite().getListRewrite(type, typeBodyDeclarationsProperty);
		bodyDeclarationsListRewrite.insertAt(intermediary, ASTNodes.getInsertionIndex(intermediary, type.bodyDeclarations()), imRewrite
				.createGroupDescription(RefactoringCoreMessages.IntroduceIndirectionRefactoring_group_description_create_new_method));
	}
 
Example 16
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private RefactoringStatus updateMethodInvocation(MethodInvocation originalInvocation, IMember enclosing, CompilationUnitRewrite unitRewriter) throws JavaModelException {

		RefactoringStatus status= new RefactoringStatus();

		// If the method invocation utilizes type arguments, skip this
		// call as the new target method may have additional parameters
		if (originalInvocation.typeArguments().size() > 0)
			return createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_type_arguments);

		MethodInvocation newInvocation= unitRewriter.getAST().newMethodInvocation();
		List<Expression> newInvocationArgs= newInvocation.arguments();
		List<Expression> originalInvocationArgs= originalInvocation.arguments();

		// static call => always use a qualifier
		String qualifier= unitRewriter.getImportRewrite().addImport(fIntermediaryTypeBinding);
		newInvocation.setExpression(ASTNodeFactory.newName(unitRewriter.getAST(), qualifier));
		newInvocation.setName(unitRewriter.getAST().newSimpleName(getIntermediaryMethodName()));

		final Expression expression= originalInvocation.getExpression();

		if (!isStaticTarget()) {
			// Add the expression as the first parameter
			if (expression == null) {
				// There is no expression for this call. Use a (possibly qualified) "this" expression.
				ThisExpression expr= unitRewriter.getAST().newThisExpression();
				RefactoringStatus qualifierStatus= qualifyThisExpression(expr, originalInvocation, enclosing, unitRewriter);
				status.merge(qualifierStatus);
				if (qualifierStatus.hasEntries())
					// warning means don't include this invocation
					return status;
				newInvocationArgs.add(expr);
			} else {
				Expression expressionAsParam= (Expression) unitRewriter.getASTRewrite().createMoveTarget(expression);
				newInvocationArgs.add(expressionAsParam);
			}
		} else {
			if (expression != null) {
				// Check if expression is the type name. If not, there may
				// be side effects (e.g. inside methods) -> don't update
				if (! (expression instanceof Name) || ASTNodes.getTypeBinding((Name) expression) == null)
					return createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_static_expression_access);
			}
		}

		for (int i= 0; i < originalInvocationArgs.size(); i++) {
			Expression originalInvocationArg= originalInvocationArgs.get(i);
			Expression movedArg= (Expression) unitRewriter.getASTRewrite().createMoveTarget(originalInvocationArg);
			newInvocationArgs.add(movedArg);
		}

		unitRewriter.getASTRewrite().replace(originalInvocation, newInvocation,
				unitRewriter.createGroupDescription(RefactoringCoreMessages.IntroduceIndirectionRefactoring_group_description_replace_call));

		return status;
	}
 
Example 17
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 18
Source File: ExtractMethodRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private ASTNode[] createCallNodes(SnippetFinder.Match duplicate, int modifiers) {
	List<ASTNode> result = new ArrayList<>(2);

	IVariableBinding[] locals = fAnalyzer.getCallerLocals();
	for (int i = 0; i < locals.length; i++) {
		result.add(createDeclaration(locals[i], null));
	}

	MethodInvocation invocation = fAST.newMethodInvocation();
	invocation.setName(fAST.newSimpleName(fMethodName));
	ASTNode typeNode = ASTResolving.findParentType(fAnalyzer.getEnclosingBodyDeclaration());
	RefactoringStatus status = new RefactoringStatus();
	while (fDestination != typeNode) {
		fAnalyzer.checkInput(status, fMethodName, typeNode);
		if (!status.isOK()) {
			SimpleName destinationTypeName = fAST.newSimpleName(ASTNodes.getEnclosingType(fDestination).getName());
			if ((modifiers & Modifier.STATIC) == 0) {
				ThisExpression thisExpression = fAST.newThisExpression();
				thisExpression.setQualifier(destinationTypeName);
				invocation.setExpression(thisExpression);
			} else {
				invocation.setExpression(destinationTypeName);
			}
			break;
		}
		typeNode = typeNode.getParent();
	}

	List<Expression> arguments = invocation.arguments();
	for (int i = 0; i < fParameterInfos.size(); i++) {
		ParameterInfo parameter = fParameterInfos.get(i);
		arguments.add(ASTNodeFactory.newName(fAST, getMappedName(duplicate, parameter)));
	}
	if (fLinkedProposalModel != null) {
		LinkedProposalPositionGroupCore nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
		nameGroup.addPosition(fRewriter.track(invocation.getName()), true);
	}

	ASTNode call;
	int returnKind = fAnalyzer.getReturnKind();
	switch (returnKind) {
		case ExtractMethodAnalyzer.ACCESS_TO_LOCAL:
			IVariableBinding binding = fAnalyzer.getReturnLocal();
			if (binding != null) {
				VariableDeclarationStatement decl = createDeclaration(getMappedBinding(duplicate, binding), invocation);
				call = decl;
			} else {
				Assignment assignment = fAST.newAssignment();
				assignment.setLeftHandSide(ASTNodeFactory.newName(fAST, getMappedBinding(duplicate, fAnalyzer.getReturnValue()).getName()));
				assignment.setRightHandSide(invocation);
				call = assignment;
			}
			break;
		case ExtractMethodAnalyzer.RETURN_STATEMENT_VALUE:
			ReturnStatement rs = fAST.newReturnStatement();
			rs.setExpression(invocation);
			call = rs;
			break;
		default:
			call = invocation;
	}

	if (call instanceof Expression && !fAnalyzer.isExpressionSelected()) {
		call = fAST.newExpressionStatement((Expression) call);
	}
	result.add(call);

	// We have a void return statement. The code looks like
	// extracted();
	// return;
	if (returnKind == ExtractMethodAnalyzer.RETURN_STATEMENT_VOID && !fAnalyzer.isLastStatementSelected()) {
		result.add(fAST.newReturnStatement());
	}
	return result.toArray(new ASTNode[result.size()]);
}
 
Example 19
Source File: GenerateHashCodeEqualsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates a comparison of reference types.
 *
 * <pre>
 * if (this.a == null) {
 * 	if (other.a != null)
 * 		return false;
 * } else {
 * 	if (!this.a.equals(other.a))
 * 		return false;
 * }
 * </pre>
 * @param name the field name
 * @return the comparison statement
 */
private Statement createQualifiedComparison(String name) {
	InfixExpression newCondition= fAst.newInfixExpression();
	newCondition.setOperator(Operator.EQUALS);
	newCondition.setLeftOperand(getThisAccessForEquals(name));
	newCondition.setRightOperand(fAst.newNullLiteral());

	// THEN
	InfixExpression notEqNull= fAst.newInfixExpression();
	notEqNull.setOperator(Operator.NOT_EQUALS);
	notEqNull.setLeftOperand(getOtherAccess(name));
	notEqNull.setRightOperand(fAst.newNullLiteral());

	IfStatement thenPart= fAst.newIfStatement();
	thenPart.setExpression(notEqNull);
	thenPart.setThenStatement(getThenStatement(getReturnFalse()));

	Block thenPart2= fAst.newBlock();
	thenPart2.statements().add(thenPart);

	// ELSE
	MethodInvocation invoc= fAst.newMethodInvocation();
	invoc.setName(fAst.newSimpleName(METHODNAME_EQUALS));
	invoc.setExpression(getThisAccessForEquals(name));
	invoc.arguments().add(getOtherAccess(name));

	PrefixExpression pe= fAst.newPrefixExpression();
	pe.setOperator(PrefixExpression.Operator.NOT);
	pe.setOperand(invoc);

	IfStatement elsePart= fAst.newIfStatement();
	elsePart.setExpression(pe);
	elsePart.setThenStatement(getThenStatement(getReturnFalse()));

	// ALL
	IfStatement isNull= fAst.newIfStatement();
	isNull.setExpression(newCondition);
	isNull.setThenStatement(thenPart2);
	isNull.setElseStatement(elsePart);

	return isNull;
}
 
Example 20
Source File: AbstractToStringGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * 
 * @param templateElement the template element, see constants in {@link ToStringTemplateParser}
 * @param member the member
 * @return <code>String</code> or <code>Expression</code> switching
 */
protected Object processElement(String templateElement, Object member) {
	Object result= templateElement;
	if (templateElement == ToStringTemplateParser.OBJECT_NAME_VARIABLE) {
		result= fContext.getTypeBinding().getName();
	}
	if (templateElement == ToStringTemplateParser.OBJECT_GET_NAME_VARIABLE) {
		//this.getClass().getName()
		MethodInvocation getClassInvocation= fAst.newMethodInvocation();
		if (fContext.isKeywordThis())
			getClassInvocation.setExpression(fAst.newThisExpression());
		getClassInvocation.setName(fAst.newSimpleName("getClass")); //$NON-NLS-1$
		MethodInvocation getNameInvocation= fAst.newMethodInvocation();
		getNameInvocation.setExpression(getClassInvocation);
		getNameInvocation.setName(fAst.newSimpleName("getName")); //$NON-NLS-1$
		result= getNameInvocation;
	}
	if (templateElement == ToStringTemplateParser.OBJECT_SUPER_TOSTRING_VARIABLE) {
		//super.toString()
		SuperMethodInvocation superToStringInvocation= fAst.newSuperMethodInvocation();
		superToStringInvocation.setName(fAst.newSimpleName(METHODNAME_TO_STRING));
		result= superToStringInvocation;
	}
	if (templateElement == ToStringTemplateParser.OBJECT_HASHCODE_VARIABLE) {
		//this.hashCode()
		MethodInvocation hashCodeInvocation= fAst.newMethodInvocation();
		if (fContext.isKeywordThis())
			hashCodeInvocation.setExpression(fAst.newThisExpression());
		hashCodeInvocation.setName(fAst.newSimpleName("hashCode")); //$NON-NLS-1$
		result= hashCodeInvocation;
	}
	if (templateElement == ToStringTemplateParser.OBJECT_SYSTEM_HASHCODE_VARIABLE) {
		//system.identityHashCode(this)
		result= createMethodInvocation(addImport("java.lang.System"), "identityHashCode", fAst.newThisExpression()); //$NON-NLS-1$ //$NON-NLS-2$
	}
	if (templateElement == ToStringTemplateParser.MEMBER_NAME_VARIABLE || templateElement == ToStringTemplateParser.MEMBER_NAME_PARENTHESIS_VARIABLE) {
		result= getMemberName(member, templateElement);
	}
	if (templateElement == ToStringTemplateParser.MEMBER_VALUE_VARIABLE) {
		result= createMemberAccessExpression(member, false, fContext.isSkipNulls());
	}
	if (result instanceof StringLiteral)
		return ((StringLiteral)result).getLiteralValue();
	else
		return result;
}