use of org.eclipse.jdt.core.dom.ThisExpression in project eclipse.jdt.ls by eclipse.
the class QuickAssistProcessor method convertMethodRefernceToLambda.
/**
* Converts and replaces the given method reference with corresponding lambda
* expression in the given ASTRewrite.
*
* @param methodReference
* the method reference to convert
* @param functionalMethod
* the non-generic functional interface method to be implemented by
* the lambda expression
* @param astRoot
* the AST root
* @param rewrite
* the ASTRewrite
* @param linkedProposalModel
* to create linked proposals for lambda's parameters or
* <code>null</code> if linked proposals are not required
* @param createBlockBody
* <code>true</code> if lambda expression's body should be a block
*
* @return lambda expression used to replace the method reference in the given
* ASTRewrite
* @throws JavaModelException
* if an exception occurs while accessing the Java element
* corresponding to the <code>functionalMethod</code>
*/
public static LambdaExpression convertMethodRefernceToLambda(MethodReference methodReference, IMethodBinding functionalMethod, CompilationUnit astRoot, ASTRewrite rewrite, LinkedProposalModel linkedProposalModel, boolean createBlockBody) throws JavaModelException {
AST ast = astRoot.getAST();
LambdaExpression lambda = ast.newLambdaExpression();
String[] lambdaParamNames = getUniqueParameterNames(methodReference, functionalMethod);
List<VariableDeclaration> lambdaParameters = lambda.parameters();
for (int i = 0; i < lambdaParamNames.length; i++) {
String paramName = lambdaParamNames[i];
VariableDeclarationFragment lambdaParameter = ast.newVariableDeclarationFragment();
SimpleName name = ast.newSimpleName(paramName);
lambdaParameter.setName(name);
lambdaParameters.add(lambdaParameter);
if (linkedProposalModel != null) {
linkedProposalModel.getPositionGroup(name.getIdentifier(), true).addPosition(rewrite.track(name), i == 0);
}
}
int noOfLambdaParameters = lambdaParamNames.length;
lambda.setParentheses(noOfLambdaParameters != 1);
ITypeBinding returnTypeBinding = functionalMethod.getReturnType();
// too often null, see bug 440000, bug 440344, bug 333665
IMethodBinding referredMethodBinding = methodReference.resolveMethodBinding();
if (methodReference instanceof CreationReference) {
CreationReference creationRef = (CreationReference) methodReference;
Type type = creationRef.getType();
if (type instanceof ArrayType) {
ArrayCreation arrayCreation = ast.newArrayCreation();
if (createBlockBody) {
Block blockBody = getBlockBodyForLambda(arrayCreation, returnTypeBinding, ast);
lambda.setBody(blockBody);
} else {
lambda.setBody(arrayCreation);
}
ArrayType arrayType = (ArrayType) type;
Type copiedElementType = (Type) rewrite.createCopyTarget(arrayType.getElementType());
arrayCreation.setType(ast.newArrayType(copiedElementType, arrayType.getDimensions()));
SimpleName name = ast.newSimpleName(lambdaParamNames[0]);
arrayCreation.dimensions().add(name);
if (linkedProposalModel != null) {
linkedProposalModel.getPositionGroup(name.getIdentifier(), false).addPosition(rewrite.track(name), LinkedPositionGroup.NO_STOP);
}
} else {
ClassInstanceCreation cic = ast.newClassInstanceCreation();
if (createBlockBody) {
Block blockBody = getBlockBodyForLambda(cic, returnTypeBinding, ast);
lambda.setBody(blockBody);
} else {
lambda.setBody(cic);
}
ITypeBinding typeBinding = type.resolveBinding();
if (!(type instanceof ParameterizedType) && typeBinding != null && typeBinding.getTypeDeclaration().isGenericType()) {
cic.setType(ast.newParameterizedType((Type) rewrite.createCopyTarget(type)));
} else {
cic.setType((Type) rewrite.createCopyTarget(type));
}
List<SimpleName> invocationArgs = getInvocationArguments(ast, 0, noOfLambdaParameters, lambdaParamNames);
cic.arguments().addAll(invocationArgs);
if (linkedProposalModel != null) {
for (SimpleName name : invocationArgs) {
linkedProposalModel.getPositionGroup(name.getIdentifier(), false).addPosition(rewrite.track(name), LinkedPositionGroup.NO_STOP);
}
}
cic.typeArguments().addAll(getCopiedTypeArguments(rewrite, methodReference.typeArguments()));
}
} else if (referredMethodBinding != null && Modifier.isStatic(referredMethodBinding.getModifiers())) {
MethodInvocation methodInvocation = ast.newMethodInvocation();
if (createBlockBody) {
Block blockBody = getBlockBodyForLambda(methodInvocation, returnTypeBinding, ast);
lambda.setBody(blockBody);
} else {
lambda.setBody(methodInvocation);
}
Expression expr = null;
boolean hasConflict = hasConflict(methodReference.getStartPosition(), referredMethodBinding, ScopeAnalyzer.METHODS | ScopeAnalyzer.CHECK_VISIBILITY, astRoot);
if (hasConflict || !Bindings.isSuperType(referredMethodBinding.getDeclaringClass(), ASTNodes.getEnclosingType(methodReference)) || methodReference.typeArguments().size() != 0) {
if (methodReference instanceof ExpressionMethodReference) {
ExpressionMethodReference expressionMethodReference = (ExpressionMethodReference) methodReference;
expr = (Expression) rewrite.createCopyTarget(expressionMethodReference.getExpression());
} else if (methodReference instanceof TypeMethodReference) {
Type type = ((TypeMethodReference) methodReference).getType();
ITypeBinding typeBinding = type.resolveBinding();
if (typeBinding != null) {
ImportRewrite importRewrite = CodeStyleConfiguration.createImportRewrite(astRoot, true);
expr = ast.newName(importRewrite.addImport(typeBinding));
}
}
}
methodInvocation.setExpression(expr);
SimpleName methodName = getMethodInvocationName(methodReference);
methodInvocation.setName((SimpleName) rewrite.createCopyTarget(methodName));
List<SimpleName> invocationArgs = getInvocationArguments(ast, 0, noOfLambdaParameters, lambdaParamNames);
methodInvocation.arguments().addAll(invocationArgs);
if (linkedProposalModel != null) {
for (SimpleName name : invocationArgs) {
linkedProposalModel.getPositionGroup(name.getIdentifier(), false).addPosition(rewrite.track(name), LinkedPositionGroup.NO_STOP);
}
}
methodInvocation.typeArguments().addAll(getCopiedTypeArguments(rewrite, methodReference.typeArguments()));
} else if (methodReference instanceof SuperMethodReference) {
SuperMethodInvocation superMethodInvocation = ast.newSuperMethodInvocation();
if (createBlockBody) {
Block blockBody = getBlockBodyForLambda(superMethodInvocation, returnTypeBinding, ast);
lambda.setBody(blockBody);
} else {
lambda.setBody(superMethodInvocation);
}
Name superQualifier = ((SuperMethodReference) methodReference).getQualifier();
if (superQualifier != null) {
superMethodInvocation.setQualifier((Name) rewrite.createCopyTarget(superQualifier));
}
SimpleName methodName = getMethodInvocationName(methodReference);
superMethodInvocation.setName((SimpleName) rewrite.createCopyTarget(methodName));
List<SimpleName> invocationArgs = getInvocationArguments(ast, 0, noOfLambdaParameters, lambdaParamNames);
superMethodInvocation.arguments().addAll(invocationArgs);
if (linkedProposalModel != null) {
for (SimpleName name : invocationArgs) {
linkedProposalModel.getPositionGroup(name.getIdentifier(), false).addPosition(rewrite.track(name), LinkedPositionGroup.NO_STOP);
}
}
superMethodInvocation.typeArguments().addAll(getCopiedTypeArguments(rewrite, methodReference.typeArguments()));
} else {
MethodInvocation methodInvocation = ast.newMethodInvocation();
if (createBlockBody) {
Block blockBody = getBlockBodyForLambda(methodInvocation, returnTypeBinding, ast);
lambda.setBody(blockBody);
} else {
lambda.setBody(methodInvocation);
}
boolean isTypeReference = isTypeReferenceToInstanceMethod(methodReference);
if (isTypeReference) {
SimpleName name = ast.newSimpleName(lambdaParamNames[0]);
methodInvocation.setExpression(name);
if (linkedProposalModel != null) {
linkedProposalModel.getPositionGroup(name.getIdentifier(), false).addPosition(rewrite.track(name), LinkedPositionGroup.NO_STOP);
}
} else {
Expression expr = ((ExpressionMethodReference) methodReference).getExpression();
if (!(expr instanceof ThisExpression && methodReference.typeArguments().size() == 0)) {
methodInvocation.setExpression((Expression) rewrite.createCopyTarget(expr));
}
}
SimpleName methodName = getMethodInvocationName(methodReference);
methodInvocation.setName((SimpleName) rewrite.createCopyTarget(methodName));
List<SimpleName> invocationArgs = getInvocationArguments(ast, isTypeReference ? 1 : 0, noOfLambdaParameters, lambdaParamNames);
methodInvocation.arguments().addAll(invocationArgs);
if (linkedProposalModel != null) {
for (SimpleName name : invocationArgs) {
linkedProposalModel.getPositionGroup(name.getIdentifier(), false).addPosition(rewrite.track(name), LinkedPositionGroup.NO_STOP);
}
}
methodInvocation.typeArguments().addAll(getCopiedTypeArguments(rewrite, methodReference.typeArguments()));
}
rewrite.replace(methodReference, lambda, null);
return lambda;
}
use of org.eclipse.jdt.core.dom.ThisExpression in project eclipse.jdt.ls by eclipse.
the class ExtractMethodAnalyzer method endVisit.
@Override
public void endVisit(CompilationUnit node) {
RefactoringStatus status = getStatus();
superCall: {
if (status.hasFatalError()) {
break superCall;
}
if (!hasSelectedNodes()) {
ASTNode coveringNode = getLastCoveringNode();
if (coveringNode instanceof Block && coveringNode.getParent() instanceof MethodDeclaration) {
MethodDeclaration methodDecl = (MethodDeclaration) coveringNode.getParent();
Message[] messages = ASTNodes.getMessages(methodDecl, ASTNodes.NODE_ONLY);
if (messages.length > 0) {
status.addFatalError(Messages.format(RefactoringCoreMessages.ExtractMethodAnalyzer_compile_errors, BasicElementLabels.getJavaElementName(methodDecl.getName().getIdentifier())), JavaStatusContext.create(fCUnit, methodDecl));
break superCall;
}
}
status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_invalid_selection);
break superCall;
}
fEnclosingBodyDeclaration = (BodyDeclaration) ASTNodes.getParent(getFirstSelectedNode(), BodyDeclaration.class);
if (fEnclosingBodyDeclaration == null || (fEnclosingBodyDeclaration.getNodeType() != ASTNode.METHOD_DECLARATION && fEnclosingBodyDeclaration.getNodeType() != ASTNode.FIELD_DECLARATION && fEnclosingBodyDeclaration.getNodeType() != ASTNode.INITIALIZER)) {
status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_invalid_selection);
break superCall;
} else if (ASTNodes.getEnclosingType(fEnclosingBodyDeclaration) == null) {
status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_compile_errors_no_parent_binding);
break superCall;
} else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) {
fEnclosingMethodBinding = ((MethodDeclaration) fEnclosingBodyDeclaration).resolveBinding();
}
if (!isSingleExpressionOrStatementSet()) {
status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_single_expression_or_set);
break superCall;
}
if (isExpressionSelected()) {
ASTNode expression = getFirstSelectedNode();
if (expression instanceof Name) {
Name name = (Name) expression;
if (name.resolveBinding() instanceof ITypeBinding) {
status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_type_reference);
break superCall;
}
if (name.resolveBinding() instanceof IMethodBinding) {
status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_method_name_reference);
break superCall;
}
if (name.resolveBinding() instanceof IVariableBinding) {
StructuralPropertyDescriptor locationInParent = name.getLocationInParent();
boolean isPartOfQualifiedName = false;
boolean isPartOfQualifier = false;
if (locationInParent == QualifiedName.NAME_PROPERTY) {
isPartOfQualifiedName = true;
QualifiedName qualifiedName = (QualifiedName) name.getParent();
QualifiedName currParent = qualifiedName;
while (true) {
ASTNode parent = currParent.getParent();
if (parent instanceof QualifiedName) {
currParent = (QualifiedName) parent;
} else {
break;
}
}
if (!qualifiedName.equals(currParent)) {
isPartOfQualifier = true;
}
}
if ((isPartOfQualifiedName && !isPartOfQualifier) || (locationInParent == FieldAccess.NAME_PROPERTY && !(((FieldAccess) name.getParent()).getExpression() instanceof ThisExpression))) {
status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_part_of_qualified_name);
break superCall;
}
}
if (name.isSimpleName() && ((SimpleName) name).isDeclaration()) {
status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_name_in_declaration);
break superCall;
}
}
fForceStatic = ASTNodes.getParent(expression, ASTNode.SUPER_CONSTRUCTOR_INVOCATION) != null || ASTNodes.getParent(expression, ASTNode.CONSTRUCTOR_INVOCATION) != null;
}
status.merge(LocalTypeAnalyzer.perform(fEnclosingBodyDeclaration, getSelection()));
computeLastStatementSelected();
}
super.endVisit(node);
}
use of org.eclipse.jdt.core.dom.ThisExpression in project AutoRefactor by JnRouvignac.
the class ObsoleteLambdaCleanUp method visit.
@Override
public boolean visit(final LambdaExpression node) {
if (node.hasParentheses() && node.parameters().size() == 1 && node.parameters().get(0) instanceof VariableDeclarationFragment) {
// TODO it should also be possible to deal with a SingleVariableDeclaration
// when the type matches the expected inferred type
// To do this, we should visit the whole block and check the target type
removeParamParentheses(node);
return false;
}
if (node.getBody() instanceof Block) {
List<Statement> statements = ASTNodes.asList((Block) node.getBody());
if (statements.size() == 1 && statements.get(0) instanceof ReturnStatement) {
removeReturnAndBrackets(node, statements);
return false;
}
} else if (node.getBody() instanceof ClassInstanceCreation) {
ClassInstanceCreation ci = (ClassInstanceCreation) node.getBody();
List<Expression> arguments = ci.arguments();
if (ci.resolveTypeBinding() != null && ci.getAnonymousClassDeclaration() == null && node.parameters().size() == arguments.size() && areSameIdentifiers(node, arguments)) {
replaceByCreationReference(node, ci);
return false;
}
} else if (node.getBody() instanceof SuperMethodInvocation) {
SuperMethodInvocation smi = (SuperMethodInvocation) node.getBody();
List<Expression> arguments = smi.arguments();
if (node.parameters().size() == arguments.size() && areSameIdentifiers(node, arguments)) {
replaceBySuperMethodReference(node, smi);
return false;
}
} else if (node.getBody() instanceof MethodInvocation) {
MethodInvocation methodInvocation = (MethodInvocation) node.getBody();
Expression calledExpression = methodInvocation.getExpression();
ITypeBinding calledType = ASTNodes.getCalledType(methodInvocation);
List<Expression> arguments = methodInvocation.arguments();
if (node.parameters().size() == arguments.size()) {
if (!areSameIdentifiers(node, arguments)) {
return true;
}
if (isStaticMethod(methodInvocation)) {
if (!arguments.isEmpty()) {
String[] remainingParams = new String[arguments.size() - 1];
for (int i = 0; i < arguments.size() - 1; i++) {
ITypeBinding argumentBinding = arguments.get(i + 1).resolveTypeBinding();
if (argumentBinding == null) {
return true;
}
remainingParams[i] = argumentBinding.getQualifiedName();
}
for (IMethodBinding methodBinding : calledType.getDeclaredMethods()) {
if ((methodBinding.getModifiers() & Modifier.STATIC) == 0 && ASTNodes.usesGivenSignature(methodBinding, calledType.getQualifiedName(), methodInvocation.getName().getIdentifier(), remainingParams)) {
return true;
}
}
}
replaceByTypeReference(node, methodInvocation);
return false;
}
if (calledExpression == null || calledExpression instanceof StringLiteral || calledExpression instanceof NumberLiteral || calledExpression instanceof ThisExpression) {
replaceByMethodReference(node, methodInvocation);
return false;
}
if (calledExpression instanceof FieldAccess) {
FieldAccess fieldAccess = (FieldAccess) calledExpression;
if (fieldAccess.resolveFieldBinding().isEffectivelyFinal()) {
replaceByMethodReference(node, methodInvocation);
return false;
}
} else if (calledExpression instanceof SuperFieldAccess) {
SuperFieldAccess fieldAccess = (SuperFieldAccess) calledExpression;
if (fieldAccess.resolveFieldBinding().isEffectivelyFinal()) {
replaceByMethodReference(node, methodInvocation);
return false;
}
}
} else if (calledExpression instanceof SimpleName && node.parameters().size() == arguments.size() + 1) {
SimpleName calledObject = (SimpleName) calledExpression;
if (isSameIdentifier(node, 0, calledObject)) {
for (int i = 0; i < arguments.size(); i++) {
SimpleName expression = ASTNodes.as(arguments.get(i), SimpleName.class);
if (expression == null || !isSameIdentifier(node, i + 1, expression)) {
return true;
}
}
ITypeBinding klass = calledExpression.resolveTypeBinding();
if (klass == null) {
return true;
}
String[] remainingParams = new String[arguments.size() + 1];
remainingParams[0] = klass.getQualifiedName();
for (int i = 0; i < arguments.size(); i++) {
ITypeBinding argumentBinding = arguments.get(i).resolveTypeBinding();
if (argumentBinding == null) {
return true;
}
remainingParams[i + 1] = argumentBinding.getQualifiedName();
}
for (IMethodBinding methodBinding : klass.getDeclaredMethods()) {
if ((methodBinding.getModifiers() & Modifier.STATIC) != 0 && ASTNodes.usesGivenSignature(methodBinding, klass.getQualifiedName(), methodInvocation.getName().getIdentifier(), remainingParams)) {
return true;
}
}
replaceByTypeReference(node, methodInvocation);
return false;
}
}
}
return true;
}
use of org.eclipse.jdt.core.dom.ThisExpression in project AutoRefactor by JnRouvignac.
the class RemoveUnneededThisExpressionCleanUp method visit.
@Override
public boolean visit(final MethodInvocation visited) {
ThisExpression thisExpression = ASTNodes.as(visited.getExpression(), ThisExpression.class);
if (thisExpressionRefersToEnclosingType(thisExpression) && isCallingMethodDeclaredInEnclosingType(visited) && visited.typeArguments().isEmpty()) {
// Remove useless thisExpressions
TextEditGroup group = new TextEditGroup(MultiFixMessages.RemoveUnneededThisExpressionCleanUp_description);
ASTRewrite rewrite = cuRewrite.getASTRewrite();
rewrite.remove(visited.getExpression(), group);
return false;
}
return true;
}
Aggregations