Java Code Examples for org.eclipse.jdt.core.dom.ThisExpression#setQualifier()

The following examples show how to use org.eclipse.jdt.core.dom.ThisExpression#setQualifier() . 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: 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 2
Source File: GenerateHashCodeEqualsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private MethodDeclaration createGetOuterHelper() {
	String outerTypeName= fType.getDeclaringClass().getTypeDeclaration().getName();

	MethodDeclaration helperMethod= fAst.newMethodDeclaration();
	helperMethod.modifiers().addAll(ASTNodeFactory.newModifiers(fAst, Modifier.PRIVATE));
	helperMethod.setName(fAst.newSimpleName(METHODNAME_OUTER_TYPE));
	helperMethod.setConstructor(false);
	helperMethod.setReturnType2(fAst.newSimpleType(fAst.newSimpleName(outerTypeName)));

	Block body= fAst.newBlock();
	helperMethod.setBody(body);

	ThisExpression thisExpression= fAst.newThisExpression();
	thisExpression.setQualifier(fAst.newSimpleName(outerTypeName));

	ReturnStatement endReturn= fAst.newReturnStatement();
	endReturn.setExpression(thisExpression);
	body.statements().add(endReturn);

	return helperMethod;
}
 
Example 3
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 4
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Expression createEnclosingInstanceCreationString(final ASTNode node, final ICompilationUnit cu) throws JavaModelException {
	Assert.isTrue((node instanceof ClassInstanceCreation) || (node instanceof SuperConstructorInvocation));
	Assert.isNotNull(cu);
	Expression expression= null;
	if (node instanceof ClassInstanceCreation)
		expression= ((ClassInstanceCreation) node).getExpression();
	else
		expression= ((SuperConstructorInvocation) node).getExpression();
	final AST ast= node.getAST();
	if (expression != null)
		return expression;
	else if (JdtFlags.isStatic(fType))
		return null;
	else if (isInsideSubclassOfDeclaringType(node))
		return ast.newThisExpression();
	else if ((node.getStartPosition() >= fType.getSourceRange().getOffset() && ASTNodes.getExclusiveEnd(node) <= fType.getSourceRange().getOffset() + fType.getSourceRange().getLength())) {
		if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
			final FieldAccess access= ast.newFieldAccess();
			access.setExpression(ast.newThisExpression());
			access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
			return access;
		} else
			return ast.newSimpleName(fEnclosingInstanceFieldName);
	} else if (isInsideTypeNestedInDeclaringType(node)) {
		final ThisExpression qualified= ast.newThisExpression();
		qualified.setQualifier(ast.newSimpleName(fType.getDeclaringType().getElementName()));
		return qualified;
	}
	return null;
}
 
Example 5
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 6
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public final boolean visit(final FieldAccess node) {
	Assert.isNotNull(node);
	final Expression expression= node.getExpression();
	final IVariableBinding variable= node.resolveFieldBinding();
	final AST ast= fRewrite.getAST();
	if (expression instanceof ThisExpression) {
		if (Bindings.equals(fTarget, variable)) {
			if (fAnonymousClass > 0) {
				final ThisExpression target= ast.newThisExpression();
				target.setQualifier(ast.newSimpleName(fTargetType.getElementName()));
				fRewrite.replace(node, target, null);
			} else
				fRewrite.replace(node, ast.newThisExpression(), null);
			return false;
		} else {
			expression.accept(this);
			return false;
		}
	} else if (expression instanceof FieldAccess) {
		final FieldAccess access= (FieldAccess) expression;
		final IBinding binding= access.getName().resolveBinding();
		if (access.getExpression() instanceof ThisExpression && Bindings.equals(fTarget, binding)) {
			ASTNode newFieldAccess= getFieldReference(node.getName(), fRewrite);
			fRewrite.replace(node, newFieldAccess, null);
			return false;
		}
	} else if (expression != null) {
		expression.accept(this);
		return false;
	}
	return true;
}
 
Example 7
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 8
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static void addQualifierToOuterProposal(IInvocationContext context, MethodInvocation invocationNode,
		IMethodBinding binding, Collection<ChangeCorrectionProposal> proposals) {
	ITypeBinding declaringType= binding.getDeclaringClass();
	ITypeBinding parentType= Bindings.getBindingOfParentType(invocationNode);
	ITypeBinding currType= parentType;

	boolean isInstanceMethod= !Modifier.isStatic(binding.getModifiers());

	while (currType != null && !Bindings.isSuperType(declaringType, currType)) {
		if (isInstanceMethod && Modifier.isStatic(currType.getModifiers())) {
			return;
		}
		currType= currType.getDeclaringClass();
	}
	if (currType == null || currType == parentType) {
		return;
	}

	ASTRewrite rewrite= ASTRewrite.create(invocationNode.getAST());

	String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetoouter_description,
			org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getTypeSignature(currType));
	ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(),
			rewrite, IProposalRelevance.QUALIFY_WITH_ENCLOSING_TYPE);

	ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot());
	ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(invocationNode, imports);
	AST ast= invocationNode.getAST();

	String qualifier= imports.addImport(currType, importRewriteContext);
	Name name= ASTNodeFactory.newName(ast, qualifier);

	Expression newExpression;
	if (isInstanceMethod) {
		ThisExpression expr= ast.newThisExpression();
		expr.setQualifier(name);
		newExpression= expr;
	} else {
		newExpression= name;
	}

	rewrite.set(invocationNode, MethodInvocation.EXPRESSION_PROPERTY, newExpression, null);

	proposals.add(proposal);
}
 
Example 9
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 10
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Attempts to qualify a "this" expression for a method invocation with an appropriate qualifier.
 * The invoked method is analyzed according to the following specs:
 *
 * 'this' must be qualified iff method is declared in an enclosing type or a supertype of an enclosing type
 *
 * 1) The method is declared somewhere outside of the cu of the invocation
 *      1a) inside a supertype of the current type
 *      1b) inside a supertype of an enclosing type
 * 2) The method is declared inside of the cu of the invocation
 * 		2a) inside the type of the invocation
 * 		2b) outside the type of the invocation
 *
 * In case of 1a) and 2b), qualify with the enclosing type.
 * @param expr a {@link ThisExpression}
 * @param originalInvocation the original method invocation
 * @param enclosing the enclosing member of the original method invocation
 * @param unitRewriter the rewrite
 * @return resulting status
 *
 */
private RefactoringStatus qualifyThisExpression(ThisExpression expr, MethodInvocation originalInvocation, IMember enclosing, CompilationUnitRewrite unitRewriter) {

	RefactoringStatus status= new RefactoringStatus();

	IMethodBinding methodBinding= originalInvocation.resolveMethodBinding();
	MethodDeclaration methodDeclaration= (MethodDeclaration) ASTNodes.findDeclaration(methodBinding, originalInvocation.getRoot());

	ITypeBinding currentTypeBinding= null;
	if (methodDeclaration != null) {
		// Case 1) : Declaring type is inside this cu => use its name if it's declared in an enclosing type
		if (ASTNodes.isParent(originalInvocation, methodDeclaration.getParent()))
			currentTypeBinding= methodBinding.getDeclaringClass();
		else
			currentTypeBinding= ASTNodes.getEnclosingType(originalInvocation);
	} else {
		// Case 2) : Declaring type is outside of this cu => find subclass in this cu
		ASTNode currentTypeDeclaration= getEnclosingTypeDeclaration(originalInvocation);
		currentTypeBinding= ASTNodes.getEnclosingType(currentTypeDeclaration);
		while (currentTypeDeclaration != null && (Bindings.findMethodInHierarchy(currentTypeBinding, methodBinding.getName(), methodBinding.getParameterTypes()) == null)) {
			currentTypeDeclaration= getEnclosingTypeDeclaration(currentTypeDeclaration.getParent());
			currentTypeBinding= ASTNodes.getEnclosingType(currentTypeDeclaration);
		}
	}

	if (currentTypeBinding == null) {
		status.merge(createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_declaring_type_not_found));
		return status;
	}

	currentTypeBinding= currentTypeBinding.getTypeDeclaration();

	ITypeBinding typeOfCall= ASTNodes.getEnclosingType(originalInvocation);
	if (!typeOfCall.equals(currentTypeBinding)) {
		if (currentTypeBinding.isAnonymous()) {
			// Cannot qualify, see bug 115277
			status.merge(createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_anonymous_cannot_qualify));
		} else {
			expr.setQualifier(unitRewriter.getAST().newSimpleName(currentTypeBinding.getName()));
		}
	} else {
		// do not qualify, only use "this.".
	}

	return status;
}
 
Example 11
Source File: ExtractMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private ASTNode[] createCallNodes(SnippetFinder.Match duplicate, int modifiers) {
	List<ASTNode> result= new ArrayList<ASTNode>(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) {
		LinkedProposalPositionGroup nameGroup= fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
		nameGroup.addPosition(fRewriter.track(invocation.getName()), false);
	}

	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 12
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static void addQualifierToOuterProposal(IInvocationContext context, MethodInvocation invocationNode, IMethodBinding binding, Collection<ICommandAccess> proposals) {
	ITypeBinding declaringType= binding.getDeclaringClass();
	ITypeBinding parentType= Bindings.getBindingOfParentType(invocationNode);
	ITypeBinding currType= parentType;

	boolean isInstanceMethod= !Modifier.isStatic(binding.getModifiers());

	while (currType != null && !Bindings.isSuperType(declaringType, currType)) {
		if (isInstanceMethod && Modifier.isStatic(currType.getModifiers())) {
			return;
		}
		currType= currType.getDeclaringClass();
	}
	if (currType == null || currType == parentType) {
		return;
	}

	ASTRewrite rewrite= ASTRewrite.create(invocationNode.getAST());

	String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetoouter_description, ASTResolving.getTypeSignature(currType));
	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.QUALIFY_WITH_ENCLOSING_TYPE, image);

	ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot());
	ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(invocationNode, imports);
	AST ast= invocationNode.getAST();

	String qualifier= imports.addImport(currType, importRewriteContext);
	Name name= ASTNodeFactory.newName(ast, qualifier);

	Expression newExpression;
	if (isInstanceMethod) {
		ThisExpression expr= ast.newThisExpression();
		expr.setQualifier(name);
		newExpression= expr;
	} else {
		newExpression= name;
	}

	rewrite.set(invocationNode, MethodInvocation.EXPRESSION_PROPERTY, newExpression, null);

	proposals.add(proposal);
}