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

The following examples show how to use org.eclipse.jdt.core.dom.AST#newFieldAccess() . 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: RegularBuilderWithMethodAdderFragment.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
private Block createWithMethodBody(AST ast, String originalFieldName, String builderFieldName) {
    Block newBlock = ast.newBlock();
    ReturnStatement builderReturnStatement = ast.newReturnStatement();
    builderReturnStatement.setExpression(ast.newThisExpression());

    Assignment newAssignment = ast.newAssignment();

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

    newBlock.statements().add(ast.newExpressionStatement(newAssignment));
    newBlock.statements().add(builderReturnStatement);
    return newBlock;
}
 
Example 2
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static ASTRewriteCorrectionProposal createNoSideEffectProposal(IInvocationContext context, SimpleName nodeToQualify, IVariableBinding fieldBinding, String label, int relevance) {
	AST ast= nodeToQualify.getAST();

	Expression qualifier;
	if (Modifier.isStatic(fieldBinding.getModifiers())) {
		ITypeBinding declaringClass= fieldBinding.getDeclaringClass();
		qualifier= ast.newSimpleName(declaringClass.getTypeDeclaration().getName());
	} else {
		qualifier= ast.newThisExpression();
	}

	ASTRewrite rewrite= ASTRewrite.create(ast);
	FieldAccess access= ast.newFieldAccess();
	access.setName((SimpleName) rewrite.createCopyTarget(nodeToQualify));
	access.setExpression(qualifier);
	rewrite.replace(nodeToQualify, access, null);


	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
	return new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, relevance, image);
}
 
Example 3
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Expression generateQualifier(String paramName, AST ast, boolean useSuper, Expression qualifier) {
	SimpleName paramSimpleName= ast.newSimpleName(paramName);
	if (useSuper) {
		SuperFieldAccess sf= ast.newSuperFieldAccess();
		sf.setName(paramSimpleName);
		if (qualifier instanceof Name) {
			sf.setQualifier((Name) qualifier);
		}
		return sf;
	}
	if (qualifier != null) {
		FieldAccess parameterAccess= ast.newFieldAccess();
		parameterAccess.setExpression(qualifier);
		parameterAccess.setName(paramSimpleName);
		return parameterAccess;
	}
	return paramSimpleName;
}
 
Example 4
Source File: CodeStyleFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {
	ASTRewrite rewrite= cuRewrite.getASTRewrite();
	TextEditGroup group= createTextEditGroup(getDescription(), cuRewrite);
	AST ast= rewrite.getAST();

	FieldAccess fieldAccess= ast.newFieldAccess();

	ThisExpression thisExpression= ast.newThisExpression();
	if (fQualifier != null)
		thisExpression.setQualifier(ast.newName(fQualifier));

	fieldAccess.setExpression(thisExpression);
	fieldAccess.setName((SimpleName) rewrite.createMoveTarget(fName));

	rewrite.replace(fName, fieldAccess, group);
}
 
Example 5
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean visit(final ThisExpression node) {
	Assert.isNotNull(node);
	Name name= node.getQualifier();
	if (fCreateInstanceField && name != null) {
		ITypeBinding binding= node.resolveTypeBinding();
		if (binding != null && Bindings.equals(binding, fTypeBinding.getDeclaringClass())) {
			AST ast= node.getAST();
			Expression expression= null;
			if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
				FieldAccess access= ast.newFieldAccess();
				access.setExpression(ast.newThisExpression());
				access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
				expression= access;
			} else {
				expression= ast.newSimpleName(fEnclosingInstanceFieldName);
			}
			fSourceRewrite.getASTRewrite().replace(node, expression, null);
		}
	}
	return super.visit(node);
}
 
Example 6
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Helper to generate an index based <code>for</code> loop to iterate over an array.
 * 
 * @param ast the current {@link AST} instance to generate the {@link ASTRewrite} for
 * @return an applicable {@link ASTRewrite} instance
 */
private ASTRewrite generateForRewrite(AST ast) {
	ASTRewrite rewrite= ASTRewrite.create(ast);

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

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

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

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

	return rewrite;
}
 
Example 7
Source File: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private FieldAccess wrapAsFieldAccess(SimpleName fieldName, AST ast) {
	Name qualifierName = null;
	try {
		if (isDeclaredInLambdaExpression()) {
			String enclosingTypeName = getEnclosingTypeName();
			qualifierName = ast.newSimpleName(enclosingTypeName);
		}
	} catch (JavaModelException e) {
		// do nothing.
	}

	FieldAccess fieldAccess = ast.newFieldAccess();
	ThisExpression thisExpression = ast.newThisExpression();
	if (qualifierName != null) {
		thisExpression.setQualifier(qualifierName);
	}
	fieldAccess.setExpression(thisExpression);
	fieldAccess.setName(fieldName);
	return fieldAccess;
}
 
Example 8
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void createConstructor(final AbstractTypeDeclaration declaration, final ASTRewrite rewrite) throws CoreException {
	Assert.isNotNull(declaration);
	Assert.isNotNull(rewrite);
	final AST ast= declaration.getAST();
	final MethodDeclaration constructor= ast.newMethodDeclaration();
	constructor.setConstructor(true);
	constructor.setName(ast.newSimpleName(declaration.getName().getIdentifier()));
	final String comment= CodeGeneration.getMethodComment(fType.getCompilationUnit(), fType.getElementName(), fType.getElementName(), getNewConstructorParameterNames(), new String[0], null, null, StubUtility.getLineDelimiterUsed(fType.getJavaProject()));
	if (comment != null && comment.length() > 0) {
		final Javadoc doc= (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC);
		constructor.setJavadoc(doc);
	}
	if (fCreateInstanceField) {
		final SingleVariableDeclaration variable= ast.newSingleVariableDeclaration();
		final String name= getNameForEnclosingInstanceConstructorParameter();
		variable.setName(ast.newSimpleName(name));
		variable.setType(createEnclosingType(ast));
		constructor.parameters().add(variable);
		final Block body= ast.newBlock();
		final Assignment assignment= ast.newAssignment();
		if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
			final FieldAccess access= ast.newFieldAccess();
			access.setExpression(ast.newThisExpression());
			access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
			assignment.setLeftHandSide(access);
		} else
			assignment.setLeftHandSide(ast.newSimpleName(fEnclosingInstanceFieldName));
		assignment.setRightHandSide(ast.newSimpleName(name));
		final Statement statement= ast.newExpressionStatement(assignment);
		body.statements().add(statement);
		constructor.setBody(body);
	} else
		constructor.setBody(ast.newBlock());
	rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertFirst(constructor, null);
}
 
Example 9
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Expression createQualifiedReadAccessExpressionForEnclosingInstance(AST ast) {
	ThisExpression expression= ast.newThisExpression();
	expression.setQualifier(ast.newName(new String[] { fType.getElementName()}));
	FieldAccess access= ast.newFieldAccess();
	access.setExpression(expression);
	access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
	return access;
}
 
Example 10
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Expression createReadAccessExpressionForEnclosingInstance(AST ast) {
	if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
		final FieldAccess access= ast.newFieldAccess();
		access.setExpression(ast.newThisExpression());
		access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
		return access;
	}
	return ast.newSimpleName(fEnclosingInstanceFieldName);
}
 
Example 11
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Expression createFieldAccess(ParameterInfo pi, AST ast, Expression qualifier) {
	if (qualifier instanceof Name) {
		Name name= (Name) qualifier; //create FQN for IPOR
		return ast.newName(JavaModelUtil.concatenateName(name.getFullyQualifiedName(), pi.getNewName()));
	}
	FieldAccess fa= ast.newFieldAccess();
	fa.setName(ast.newSimpleName(pi.getNewName()));
	fa.setExpression(qualifier);
	return fa;
}
 
Example 12
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 SuperFieldAccess node) {
	if (!fAnonymousClassDeclaration && !fTypeDeclarationStatement) {
		final AST ast= node.getAST();
		final FieldAccess access= ast.newFieldAccess();
		access.setExpression(ast.newThisExpression());
		access.setName(ast.newSimpleName(node.getName().getIdentifier()));
		fRewrite.replace(node, access, null);
		if (!fSourceRewriter.getCu().equals(fTargetRewriter.getCu()))
			fSourceRewriter.getImportRemover().registerRemovedNode(node);
		return true;
	}
	return false;
}
 
Example 13
Source File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Statement newFieldAssignment(AST ast, SimpleName fieldNameNode, Expression initializer, boolean useThisAccess) {
Assignment assignment= ast.newAssignment();
if (useThisAccess) {
	FieldAccess access= ast.newFieldAccess();
	access.setExpression(ast.newThisExpression());
	access.setName(fieldNameNode);
	assignment.setLeftHandSide(access);
} else {
	assignment.setLeftHandSide(fieldNameNode);
}
assignment.setOperator(Assignment.Operator.ASSIGN);
assignment.setRightHandSide(initializer);

return ast.newExpressionStatement(assignment);
   }
 
Example 14
Source File: StubUtility2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static MethodDeclaration createConstructorStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, ITypeBinding typeBinding, IMethodBinding superConstructor, IVariableBinding[] variableBindings, int modifiers, CodeGenerationSettings settings) throws CoreException {
	AST ast= rewrite.getAST();

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

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

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

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

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

	String delimiter= StubUtility.getLineDelimiterUsed(unit);

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

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

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

	if (settings != null && settings.createComments) {
		String string= CodeGeneration.getMethodComment(unit, typeBinding.getName(), decl, superConstructor, delimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 15
Source File: BuilderFieldAccessCreatorFragment.java    From SparkBuilderGenerator with MIT License 4 votes vote down vote up
public FieldAccess createBuilderFieldAccess(AST ast, String builderName, BuilderField field) {
    FieldAccess builderFieldAccess = ast.newFieldAccess();
    builderFieldAccess.setExpression(ast.newSimpleName(builderName));
    builderFieldAccess.setName(ast.newSimpleName(field.getOriginalFieldName()));
    return builderFieldAccess;
}
 
Example 16
Source File: FieldSetterAdderFragment.java    From SparkBuilderGenerator with MIT License 4 votes vote down vote up
private FieldAccess createThisFieldAccess(AST ast, BuilderField field) {
    FieldAccess fieldAccess = ast.newFieldAccess();
    fieldAccess.setExpression(ast.newThisExpression());
    fieldAccess.setName(ast.newSimpleName(field.getOriginalFieldName()));
    return fieldAccess;
}
 
Example 17
Source File: PublicConstructorWithMandatoryFieldsAdderFragment.java    From SparkBuilderGenerator with MIT License 4 votes vote down vote up
private FieldAccess createThisFieldAccess(AST ast, BuilderField field) {
    FieldAccess fieldAccess = ast.newFieldAccess();
    fieldAccess.setExpression(ast.newThisExpression());
    fieldAccess.setName(ast.newSimpleName(field.getOriginalFieldName()));
    return fieldAccess;
}
 
Example 18
Source File: PolymorphismRefactoring.java    From JDeodorant with MIT License 4 votes vote down vote up
protected void generateSettersForAssignedFields() {
	AST contextAST = sourceTypeDeclaration.getAST();
	Set<VariableDeclarationFragment> assignedFields = new LinkedHashSet<VariableDeclarationFragment>();
	assignedFields.addAll(typeCheckElimination.getAssignedFields());
	assignedFields.addAll(typeCheckElimination.getSuperAssignedFields());
	for(VariableDeclarationFragment fragment : assignedFields) {
		IMethodBinding setterMethodBinding = null;
		if(typeCheckElimination.getSuperAssignedFields().contains(fragment)) {
			for(IVariableBinding fieldBinding : typeCheckElimination.getSuperAssignedFieldBindings()) {
				if(fieldBinding.isEqualTo(fragment.resolveBinding())) {
					setterMethodBinding = typeCheckElimination.getSetterMethodBindingOfSuperAssignedField(fieldBinding);
					break;
				}
			}
		}
		else {
			setterMethodBinding = findSetterMethodInContext(fragment.resolveBinding());
		}
		if(setterMethodBinding == null) {
			FieldDeclaration fieldDeclaration = (FieldDeclaration)fragment.getParent();
			if(!fragment.equals(typeCheckElimination.getTypeField())) {
				ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST());
				MethodDeclaration newMethodDeclaration = contextAST.newMethodDeclaration();
				sourceRewriter.set(newMethodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, contextAST.newPrimitiveType(PrimitiveType.VOID), null);
				ListRewrite methodDeclarationModifiersRewrite = sourceRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.MODIFIERS2_PROPERTY);
				methodDeclarationModifiersRewrite.insertLast(contextAST.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD), null);
				String methodName = fragment.getName().getIdentifier();
				methodName = "set" + methodName.substring(0,1).toUpperCase() + methodName.substring(1,methodName.length());
				sourceRewriter.set(newMethodDeclaration, MethodDeclaration.NAME_PROPERTY, contextAST.newSimpleName(methodName), null);
				ListRewrite methodDeclarationParametersRewrite = sourceRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.PARAMETERS_PROPERTY);
				SingleVariableDeclaration parameter = contextAST.newSingleVariableDeclaration();
				sourceRewriter.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, fieldDeclaration.getType(), null);
				sourceRewriter.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, fragment.getName(), null);
				methodDeclarationParametersRewrite.insertLast(parameter, null);
				Block methodDeclarationBody = contextAST.newBlock();
				ListRewrite methodDeclarationBodyStatementsRewrite = sourceRewriter.getListRewrite(methodDeclarationBody, Block.STATEMENTS_PROPERTY);
				Assignment assignment = contextAST.newAssignment();
				sourceRewriter.set(assignment, Assignment.RIGHT_HAND_SIDE_PROPERTY, fragment.getName(), null);
				sourceRewriter.set(assignment, Assignment.OPERATOR_PROPERTY, Assignment.Operator.ASSIGN, null);
				FieldAccess fieldAccess = contextAST.newFieldAccess();
				sourceRewriter.set(fieldAccess, FieldAccess.EXPRESSION_PROPERTY, contextAST.newThisExpression(), null);
				sourceRewriter.set(fieldAccess, FieldAccess.NAME_PROPERTY, fragment.getName(), null);
				sourceRewriter.set(assignment, Assignment.LEFT_HAND_SIDE_PROPERTY, fieldAccess, null);
				ExpressionStatement expressionStatement = contextAST.newExpressionStatement(assignment);
				methodDeclarationBodyStatementsRewrite.insertLast(expressionStatement, null);
				sourceRewriter.set(newMethodDeclaration, MethodDeclaration.BODY_PROPERTY, methodDeclarationBody, null);
				ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
				contextBodyRewrite.insertLast(newMethodDeclaration, null);
				try {
					TextEdit sourceEdit = sourceRewriter.rewriteAST();
					ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
					CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit);
					change.getEdit().addChild(sourceEdit);
					change.addTextEditGroup(new TextEditGroup("Create setter method for assigned field", new TextEdit[] {sourceEdit}));
				} catch (JavaModelException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
 
Example 19
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public final boolean visit(final SimpleName node) {
	Assert.isNotNull(node);
	final AST ast= node.getAST();
	final ASTRewrite rewrite= fRewrite;
	final IBinding binding= node.resolveBinding();
	if (binding instanceof ITypeBinding) {
		ITypeBinding type= (ITypeBinding) binding;
		String name= fTargetRewrite.getImportRewrite().addImport(type.getTypeDeclaration());
		if (name != null && name.indexOf('.') != -1) {
			fRewrite.replace(node, ASTNodeFactory.newName(ast, name), null);
			return false;
		}
	}
	if (Bindings.equals(fTarget, binding))
		if (fAnonymousClass > 0) {
			final ThisExpression target= ast.newThisExpression();
			target.setQualifier(ast.newSimpleName(fTargetType.getElementName()));
			fRewrite.replace(node, target, null);
		} else
			rewrite.replace(node, ast.newThisExpression(), null);
	else if (binding instanceof IVariableBinding) {
		final IVariableBinding variable= (IVariableBinding) binding;
		final IMethodBinding method= fDeclaration.resolveBinding();
		ITypeBinding declaring= variable.getDeclaringClass();
		if (method != null) {
			if (declaring != null && Bindings.isSuperType(declaring, method.getDeclaringClass(), false)) {
				declaring= declaring.getTypeDeclaration();
				if (JdtFlags.isStatic(variable))
					rewrite.replace(node, ast.newQualifiedName(ASTNodeFactory.newName(ast, fTargetRewrite.getImportRewrite().addImport(declaring)), ast.newSimpleName(node.getFullyQualifiedName())), null);
				else {
					final FieldAccess access= ast.newFieldAccess();
					access.setExpression(ast.newSimpleName(fTargetName));
					access.setName(ast.newSimpleName(node.getFullyQualifiedName()));
					rewrite.replace(node, access, null);
				}
			} else if (!(node.getParent() instanceof QualifiedName) && JdtFlags.isStatic(variable) && !fStaticImports.contains(variable) && !Checks.isEnumCase(node.getParent())) {
				rewrite.replace(node, ast.newQualifiedName(ASTNodeFactory.newName(ast, fTargetRewrite.getImportRewrite().addImport(declaring)), ast.newSimpleName(node.getFullyQualifiedName())), null);
			}
		}
	}
	return false;
}
 
Example 20
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;
}