use of org.eclipse.jdt.core.dom.Assignment in project che by eclipse.
the class GetterSetterUtil method getAssignedValue.
/**
* Converts an assignment, postfix expression or prefix expression into an assignable equivalent expression using the getter.
*
* @param node the assignment/prefix/postfix node
* @param astRewrite the astRewrite to use
* @param getterExpression the expression to insert for read accesses or <code>null</code> if such an expression does not exist
* @param variableType the type of the variable that the result will be assigned to
* @param is50OrHigher <code>true</code> if a 5.0 or higher environment can be used
* @return an expression that can be assigned to the type variableType with node being replaced by a equivalent expression using the getter
*/
public static Expression getAssignedValue(ASTNode node, ASTRewrite astRewrite, Expression getterExpression, ITypeBinding variableType, boolean is50OrHigher) {
InfixExpression.Operator op = null;
AST ast = astRewrite.getAST();
if (isNotInBlock(node))
return null;
if (node.getNodeType() == ASTNode.ASSIGNMENT) {
Assignment assignment = ((Assignment) node);
Expression rightHandSide = assignment.getRightHandSide();
Expression copiedRightOp = (Expression) astRewrite.createCopyTarget(rightHandSide);
if (assignment.getOperator() == Operator.ASSIGN) {
ITypeBinding rightHandSideType = rightHandSide.resolveTypeBinding();
copiedRightOp = createNarrowCastIfNessecary(copiedRightOp, rightHandSideType, ast, variableType, is50OrHigher);
return copiedRightOp;
}
if (getterExpression != null) {
InfixExpression infix = ast.newInfixExpression();
infix.setLeftOperand(getterExpression);
infix.setOperator(ASTNodes.convertToInfixOperator(assignment.getOperator()));
ITypeBinding infixType = infix.resolveTypeBinding();
if (NecessaryParenthesesChecker.needsParenthesesForRightOperand(rightHandSide, infix, variableType)) {
ParenthesizedExpression p = ast.newParenthesizedExpression();
p.setExpression(copiedRightOp);
copiedRightOp = p;
}
infix.setRightOperand(copiedRightOp);
return createNarrowCastIfNessecary(infix, infixType, ast, variableType, is50OrHigher);
}
} else if (node.getNodeType() == ASTNode.POSTFIX_EXPRESSION) {
PostfixExpression po = (PostfixExpression) node;
if (po.getOperator() == PostfixExpression.Operator.INCREMENT)
op = InfixExpression.Operator.PLUS;
if (po.getOperator() == PostfixExpression.Operator.DECREMENT)
op = InfixExpression.Operator.MINUS;
} else if (node.getNodeType() == ASTNode.PREFIX_EXPRESSION) {
PrefixExpression pe = (PrefixExpression) node;
if (pe.getOperator() == PrefixExpression.Operator.INCREMENT)
op = InfixExpression.Operator.PLUS;
if (pe.getOperator() == PrefixExpression.Operator.DECREMENT)
op = InfixExpression.Operator.MINUS;
}
if (op != null && getterExpression != null) {
return createInfixInvocationFromPostPrefixExpression(op, getterExpression, ast, variableType, is50OrHigher);
}
return null;
}
use of org.eclipse.jdt.core.dom.Assignment in project che by eclipse.
the class StubUtility2 method createConstructorStub.
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;
}
use of org.eclipse.jdt.core.dom.Assignment in project che by eclipse.
the class UnresolvedElementsSubProcessor method addNewVariableProposals.
private static void addNewVariableProposals(ICompilationUnit cu, Name node, SimpleName simpleName, Collection<ICommandAccess> proposals) {
String name = simpleName.getIdentifier();
BodyDeclaration bodyDeclaration = ASTResolving.findParentBodyDeclaration(node, true);
int type = bodyDeclaration.getNodeType();
if (type == ASTNode.METHOD_DECLARATION) {
int relevance = StubUtility.hasParameterName(cu.getJavaProject(), name) ? IProposalRelevance.CREATE_PARAMETER_PREFIX_OR_SUFFIX_MATCH : IProposalRelevance.CREATE_PARAMETER;
String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createparameter_description, BasicElementLabels.getJavaElementName(name));
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.PARAM, simpleName, null, relevance, image));
}
if (type == ASTNode.INITIALIZER || type == ASTNode.METHOD_DECLARATION && !ASTResolving.isInsideConstructorInvocation((MethodDeclaration) bodyDeclaration, node)) {
int relevance = StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? IProposalRelevance.CREATE_LOCAL_PREFIX_OR_SUFFIX_MATCH : IProposalRelevance.CREATE_LOCAL;
String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createlocal_description, BasicElementLabels.getJavaElementName(name));
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL, simpleName, null, relevance, image));
}
if (node.getParent().getNodeType() == ASTNode.ASSIGNMENT) {
Assignment assignment = (Assignment) node.getParent();
if (assignment.getLeftHandSide() == node && assignment.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
ASTNode statement = assignment.getParent();
ASTRewrite rewrite = ASTRewrite.create(statement.getAST());
if (ASTNodes.isControlStatementBody(assignment.getParent().getLocationInParent())) {
rewrite.replace(statement, rewrite.getAST().newBlock(), null);
} else {
rewrite.remove(statement, null);
}
String label = CorrectionMessages.UnresolvedElementsSubProcessor_removestatement_description;
//JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
Image image = JavaPluginImages.get(JavaPluginImages.IMG_TOOL_DELETE);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.REMOVE_ASSIGNMENT, image);
proposals.add(proposal);
}
}
}
use of org.eclipse.jdt.core.dom.Assignment in project che by eclipse.
the class GenerateForLoopAssistProposal method getIndexBasedForBodyAssignment.
/**
* 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();
//$NON-NLS-1$
invokeGetExpression.setName(ast.newSimpleName("get"));
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;
}
use of org.eclipse.jdt.core.dom.Assignment in project che by eclipse.
the class NewVariableCorrectionProposal method doAddLocal.
private ASTRewrite doAddLocal(CompilationUnit cu) {
AST ast = cu.getAST();
Block body;
BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(fOriginalNode);
IBinding targetContext = null;
if (decl instanceof MethodDeclaration) {
body = (((MethodDeclaration) decl).getBody());
targetContext = ((MethodDeclaration) decl).resolveBinding();
} else if (decl instanceof Initializer) {
body = (((Initializer) decl).getBody());
targetContext = Bindings.getBindingOfParentType(decl);
} else {
return null;
}
ASTRewrite rewrite = ASTRewrite.create(ast);
ImportRewrite imports = createImportRewrite((CompilationUnit) decl.getRoot());
SimpleName[] names = getAllReferences(body);
ASTNode dominant = getDominantNode(names);
Statement dominantStatement = ASTResolving.findParentStatement(dominant);
if (ASTNodes.isControlStatementBody(dominantStatement.getLocationInParent())) {
dominantStatement = (Statement) dominantStatement.getParent();
}
SimpleName node = names[0];
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, imports);
if (isAssigned(dominantStatement, node)) {
// x = 1; -> int x = 1;
Assignment assignment = (Assignment) node.getParent();
// trick to avoid comment removal around the statement: keep the expression statement
// and replace the assignment with an VariableDeclarationExpression
VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
VariableDeclarationExpression newDecl = ast.newVariableDeclarationExpression(newDeclFrag);
newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext));
Expression placeholder = (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
newDeclFrag.setInitializer(placeholder);
newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
rewrite.replace(assignment, newDecl, null);
addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME);
setEndPosition(rewrite.track(assignment.getParent()));
return rewrite;
} else if ((dominant != dominantStatement) && isForStatementInit(dominantStatement, node)) {
// for (x = 1;;) ->for (int x = 1;;)
Assignment assignment = (Assignment) node.getParent();
VariableDeclarationFragment frag = ast.newVariableDeclarationFragment();
VariableDeclarationExpression expression = ast.newVariableDeclarationExpression(frag);
frag.setName(ast.newSimpleName(node.getIdentifier()));
Expression placeholder = (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
frag.setInitializer(placeholder);
expression.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext));
rewrite.replace(assignment, expression, null);
addLinkedPosition(rewrite.track(expression.getType()), false, KEY_TYPE);
addLinkedPosition(rewrite.track(frag.getName()), true, KEY_NAME);
setEndPosition(rewrite.track(expression));
return rewrite;
} else if ((dominant != dominantStatement) && isEnhancedForStatementVariable(dominantStatement, node)) {
// for (x: collectionOfT) -> for (T x: collectionOfT)
EnhancedForStatement enhancedForStatement = (EnhancedForStatement) dominantStatement;
SingleVariableDeclaration parameter = enhancedForStatement.getParameter();
Expression expression = enhancedForStatement.getExpression();
SimpleName newName = (SimpleName) rewrite.createMoveTarget(node);
rewrite.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, newName, null);
ITypeBinding elementBinding = null;
ITypeBinding typeBinding = expression.resolveTypeBinding();
if (typeBinding != null) {
if (typeBinding.isArray()) {
elementBinding = typeBinding.getElementType();
} else {
//$NON-NLS-1$
ITypeBinding iterable = Bindings.findTypeInHierarchy(typeBinding, "java.lang.Iterable");
if (iterable != null) {
ITypeBinding[] typeArguments = iterable.getTypeArguments();
if (typeArguments.length == 1) {
elementBinding = typeArguments[0];
elementBinding = Bindings.normalizeForDeclarationUse(elementBinding, ast);
}
}
}
}
Type type;
if (elementBinding != null) {
type = imports.addImport(elementBinding, ast, importRewriteContext);
} else {
//$NON-NLS-1$
type = ast.newSimpleType(ast.newSimpleName("Object"));
}
rewrite.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, type, null);
addLinkedPosition(rewrite.track(type), false, KEY_TYPE);
addLinkedPosition(rewrite.track(newName), true, KEY_NAME);
setEndPosition(rewrite.track(expression));
return rewrite;
}
// foo(x) -> int x; foo(x)
VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
VariableDeclarationStatement newDecl = ast.newVariableDeclarationStatement(newDeclFrag);
newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext));
// newDeclFrag.setInitializer(ASTNodeFactory.newDefaultExpression(ast, newDecl.getType(), 0));
addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
addLinkedPosition(rewrite.track(node), true, KEY_NAME);
addLinkedPosition(rewrite.track(newDeclFrag.getName()), false, KEY_NAME);
Statement statement = dominantStatement;
List<? extends ASTNode> list = ASTNodes.getContainingList(statement);
while (list == null && statement.getParent() instanceof Statement) {
// parent must be if, for or while
statement = (Statement) statement.getParent();
list = ASTNodes.getContainingList(statement);
}
if (list != null) {
ASTNode parent = statement.getParent();
StructuralPropertyDescriptor childProperty = statement.getLocationInParent();
if (childProperty.isChildListProperty()) {
rewrite.getListRewrite(parent, (ChildListPropertyDescriptor) childProperty).insertBefore(newDecl, statement, null);
return rewrite;
} else {
return null;
}
}
return rewrite;
}
Aggregations