use of org.eclipse.jdt.core.dom.Expression in project che by eclipse.
the class InlineTempRefactoring method getModifiedInitializerSource.
private Expression getModifiedInitializerSource(CompilationUnitRewrite rewrite, SimpleName reference) throws JavaModelException {
VariableDeclaration varDecl = getVariableDeclaration();
Expression initializer = varDecl.getInitializer();
ASTNode referenceContext = reference.getParent();
if (Invocations.isResolvedTypeInferredFromExpectedType(initializer)) {
if (!(referenceContext instanceof VariableDeclarationFragment || referenceContext instanceof SingleVariableDeclaration || referenceContext instanceof Assignment)) {
ITypeBinding[] typeArguments = Invocations.getInferredTypeArguments(initializer);
if (typeArguments != null) {
String newSource = createParameterizedInvocation(initializer, typeArguments, rewrite);
return (Expression) rewrite.getASTRewrite().createStringPlaceholder(newSource, initializer.getNodeType());
}
}
}
Expression copy = (Expression) rewrite.getASTRewrite().createCopyTarget(initializer);
AST ast = rewrite.getAST();
if (NecessaryParenthesesChecker.needsParentheses(initializer, reference.getParent(), reference.getLocationInParent())) {
ParenthesizedExpression parenthesized = ast.newParenthesizedExpression();
parenthesized.setExpression(copy);
copy = parenthesized;
}
ITypeBinding explicitCast = ASTNodes.getExplicitCast(initializer, reference);
if (explicitCast != null) {
CastExpression cast = ast.newCastExpression();
if (NecessaryParenthesesChecker.needsParentheses(copy, cast, CastExpression.EXPRESSION_PROPERTY)) {
ParenthesizedExpression parenthesized = ast.newParenthesizedExpression();
parenthesized.setExpression(copy);
copy = parenthesized;
}
cast.setExpression(copy);
ImportRewriteContext context = new ContextSensitiveImportRewriteContext(reference, rewrite.getImportRewrite());
cast.setType(rewrite.getImportRewrite().addImport(explicitCast, ast, context));
copy = cast;
} else if (initializer instanceof ArrayInitializer && ASTNodes.getDimensions(varDecl) > 0) {
ArrayType newType = (ArrayType) ASTNodeFactory.newType(ast, varDecl);
ArrayCreation newArrayCreation = ast.newArrayCreation();
newArrayCreation.setType(newType);
newArrayCreation.setInitializer((ArrayInitializer) copy);
return newArrayCreation;
}
return copy;
}
use of org.eclipse.jdt.core.dom.Expression in project che by eclipse.
the class IntroduceFactoryRefactoring method getCtorCallAt.
/**
* Look "in the vicinity" of the given range to find the <code>ClassInstanceCreation</code>
* node that this search hit identified. Necessary because the <code>SearchEngine</code>
* doesn't always cough up text extents that <code>NodeFinder.perform()</code> agrees with.
* @param start
* @param length
* @param unitAST
* @return return a {@link ClassInstanceCreation} or a {@link MethodRef} or <code>null</code> if this is really a constructor->constructor call (e.g. "this(...)")
* @throws CoreException
*/
private ASTNode getCtorCallAt(int start, int length, CompilationUnit unitAST) throws CoreException {
ICompilationUnit unitHandle = ASTCreator.getCu(unitAST);
ASTNode node = NodeFinder.perform(unitAST, start, length);
if (node == null)
throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, Messages.format(RefactoringCoreMessages.IntroduceFactory_noASTNodeForConstructorSearchHit, new Object[] { Integer.toString(start), Integer.toString(start + length), BasicElementLabels.getJavaCodeString(unitHandle.getSource().substring(start, start + length)), BasicElementLabels.getFileName(unitHandle) }), null));
if (node instanceof ClassInstanceCreation) {
if (((ClassInstanceCreation) node).getAnonymousClassDeclaration() != null) {
// Cannot replace anonymous inner class, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=250660
fConstructorVisibility = Modifier.PROTECTED;
return null;
}
return node;
} else if (node instanceof VariableDeclaration) {
Expression init = ((VariableDeclaration) node).getInitializer();
if (init instanceof ClassInstanceCreation) {
return init;
} else if (init != null)
throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, Messages.format(RefactoringCoreMessages.IntroduceFactory_unexpectedInitializerNodeType, new Object[] { BasicElementLabels.getJavaCodeString(init.toString()), BasicElementLabels.getFileName(unitHandle) }), null));
else
throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, Messages.format(RefactoringCoreMessages.IntroduceFactory_noConstructorCallNodeInsideFoundVarbleDecl, BasicElementLabels.getJavaCodeString(node.toString())), null));
} else if (node instanceof ConstructorInvocation) {
// to another flavor on the same class.
return null;
} else if (node instanceof SuperConstructorInvocation) {
// This is a call we can bypass; it's from one constructor flavor
// to another flavor on the same class.
fConstructorVisibility = Modifier.PROTECTED;
return null;
} else if (node instanceof ExpressionStatement) {
Expression expr = ((ExpressionStatement) node).getExpression();
if (expr instanceof ClassInstanceCreation)
return expr;
else
throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, Messages.format(RefactoringCoreMessages.IntroduceFactory_unexpectedASTNodeTypeForConstructorSearchHit, new Object[] { BasicElementLabels.getJavaCodeString(expr.toString()), BasicElementLabels.getFileName(unitHandle) }), null));
} else if (node instanceof SimpleName && (node.getParent() instanceof MethodDeclaration || node.getParent() instanceof AbstractTypeDeclaration)) {
// We seem to have been given a hit for an implicit call to the base-class constructor.
// Do nothing with this (implicit) call, but have to make sure we make the derived class
// doesn't lose access to the base-class constructor (so make it 'protected', not 'private').
fConstructorVisibility = Modifier.PROTECTED;
return null;
} else if (node instanceof MethodRef) {
return node;
} else
throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, Messages.format(RefactoringCoreMessages.IntroduceFactory_unexpectedASTNodeTypeForConstructorSearchHit, new Object[] { BasicElementLabels.getJavaElementName(node.getClass().getName() + "('" + node.toString() + "')"), BasicElementLabels.getFileName(unitHandle) }), //$NON-NLS-1$ //$NON-NLS-2$
null));
}
use of org.eclipse.jdt.core.dom.Expression in project che by eclipse.
the class ExtractMethodAnalyzer method visit.
@Override
public boolean visit(LambdaExpression node) {
Selection selection = getSelection();
int selectionStart = selection.getOffset();
int selectionExclusiveEnd = selection.getExclusiveEnd();
int lambdaStart = node.getStartPosition();
int lambdaExclusiveEnd = lambdaStart + node.getLength();
ASTNode body = node.getBody();
int bodyStart = body.getStartPosition();
int bodyExclusiveEnd = bodyStart + body.getLength();
boolean isValidSelection = false;
if ((body instanceof Block) && (bodyStart < selectionStart && selectionExclusiveEnd <= bodyExclusiveEnd)) {
// if selection is inside lambda body's block
isValidSelection = true;
} else if (body instanceof Expression) {
try {
TokenScanner scanner = new TokenScanner(fCUnit);
int arrowExclusiveEnd = scanner.getTokenEndOffset(ITerminalSymbols.TokenNameARROW, lambdaStart);
if (selectionStart >= arrowExclusiveEnd) {
isValidSelection = true;
}
} catch (CoreException e) {
// ignore
}
}
if (selectionStart <= lambdaStart && selectionExclusiveEnd >= lambdaExclusiveEnd) {
// if selection covers the lambda node
isValidSelection = true;
}
if (!isValidSelection) {
return false;
}
return super.visit(node);
}
use of org.eclipse.jdt.core.dom.Expression in project che by eclipse.
the class ExtractMethodRefactoring method createCallNodes.
//---- Code generation -----------------------------------------------------------------------
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);
// return;
if (returnKind == ExtractMethodAnalyzer.RETURN_STATEMENT_VOID && !fAnalyzer.isLastStatementSelected()) {
result.add(fAST.newReturnStatement());
}
return result.toArray(new ASTNode[result.size()]);
}
use of org.eclipse.jdt.core.dom.Expression in project che by eclipse.
the class IntroduceIndirectionRefactoring method updateMethodInvocation.
// ******************* UPDATE CALLS **********************
private RefactoringStatus updateMethodInvocation(MethodInvocation originalInvocation, IMember enclosing, CompilationUnitRewrite unitRewriter) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
// 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) {
// 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;
}
Aggregations