use of org.eclipse.jdt.core.dom.VariableDeclarationStatement in project che by eclipse.
the class SuppressWarningsSubProcessor method addSuppressWarningsProposalIfPossible.
/**
* Adds a SuppressWarnings proposal if possible and returns whether parent nodes should be processed or not (and with what relevance).
*
* @param cu the compilation unit
* @param node the node on which to add a SuppressWarning token
* @param warningToken the warning token to add
* @param relevance the proposal's relevance
* @param proposals collector to which the proposal should be added
* @return <code>0</code> if no further proposals should be added to parent nodes, or the relevance of the next proposal
*
* @since 3.6
*/
private static int addSuppressWarningsProposalIfPossible(ICompilationUnit cu, ASTNode node, String warningToken, int relevance, Collection<ICommandAccess> proposals) {
ChildListPropertyDescriptor property;
String name;
boolean isLocalVariable = false;
switch(node.getNodeType()) {
case ASTNode.SINGLE_VARIABLE_DECLARATION:
property = SingleVariableDeclaration.MODIFIERS2_PROPERTY;
name = ((SingleVariableDeclaration) node).getName().getIdentifier();
isLocalVariable = true;
break;
case ASTNode.VARIABLE_DECLARATION_STATEMENT:
property = VariableDeclarationStatement.MODIFIERS2_PROPERTY;
name = getFirstFragmentName(((VariableDeclarationStatement) node).fragments());
isLocalVariable = true;
break;
case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
property = VariableDeclarationExpression.MODIFIERS2_PROPERTY;
name = getFirstFragmentName(((VariableDeclarationExpression) node).fragments());
isLocalVariable = true;
break;
case ASTNode.TYPE_DECLARATION:
property = TypeDeclaration.MODIFIERS2_PROPERTY;
name = ((TypeDeclaration) node).getName().getIdentifier();
break;
case ASTNode.ANNOTATION_TYPE_DECLARATION:
property = AnnotationTypeDeclaration.MODIFIERS2_PROPERTY;
name = ((AnnotationTypeDeclaration) node).getName().getIdentifier();
break;
case ASTNode.ENUM_DECLARATION:
property = EnumDeclaration.MODIFIERS2_PROPERTY;
name = ((EnumDeclaration) node).getName().getIdentifier();
break;
case ASTNode.FIELD_DECLARATION:
property = FieldDeclaration.MODIFIERS2_PROPERTY;
name = getFirstFragmentName(((FieldDeclaration) node).fragments());
break;
// case ASTNode.INITIALIZER: not used, because Initializer cannot have annotations
case ASTNode.METHOD_DECLARATION:
property = MethodDeclaration.MODIFIERS2_PROPERTY;
//$NON-NLS-1$
name = ((MethodDeclaration) node).getName().getIdentifier() + "()";
break;
case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION:
property = AnnotationTypeMemberDeclaration.MODIFIERS2_PROPERTY;
//$NON-NLS-1$
name = ((AnnotationTypeMemberDeclaration) node).getName().getIdentifier() + "()";
break;
case ASTNode.ENUM_CONSTANT_DECLARATION:
property = EnumConstantDeclaration.MODIFIERS2_PROPERTY;
name = ((EnumConstantDeclaration) node).getName().getIdentifier();
break;
default:
return relevance;
}
String label = Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_suppress_warnings_label, new String[] { warningToken, BasicElementLabels.getJavaElementName(name) });
ASTRewriteCorrectionProposal proposal = new SuppressWarningsProposal(warningToken, label, cu, node, property, relevance);
proposals.add(proposal);
return isLocalVariable ? relevance - 1 : 0;
}
use of org.eclipse.jdt.core.dom.VariableDeclarationStatement in project che by eclipse.
the class ExtractToNullCheckedLocalProposal method getRewrite.
@Override
protected ASTRewrite getRewrite() throws CoreException {
// infrastructure:
AST ast = this.compilationUnit.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
ImportRewrite imports = ImportRewrite.create(this.compilationUnit, true);
TextEditGroup group = new TextEditGroup(FixMessages.ExtractToNullCheckedLocalProposal_extractCheckedLocal_editName);
LinkedProposalPositionGroup localNameGroup = new LinkedProposalPositionGroup(LOCAL_NAME_POSITION_GROUP);
getLinkedProposalModel().addPositionGroup(localNameGroup);
// AST context:
Statement origStmt = (Statement) ASTNodes.getParent(this.fieldReference, Statement.class);
// determine suitable strategy for rearranging elements towards a new code structure:
RearrangeStrategy rearrangeStrategy = RearrangeStrategy.create(origStmt, rewrite, group);
Expression toReplace;
ASTNode directParent = this.fieldReference.getParent();
if (directParent instanceof FieldAccess) {
toReplace = (Expression) directParent;
} else if (directParent instanceof QualifiedName && this.fieldReference.getLocationInParent() == QualifiedName.NAME_PROPERTY) {
toReplace = (Expression) directParent;
} else {
toReplace = this.fieldReference;
}
// new local declaration initialized from the field reference
VariableDeclarationFragment localFrag = ast.newVariableDeclarationFragment();
VariableDeclarationStatement localDecl = ast.newVariableDeclarationStatement(localFrag);
// ... type
localDecl.setType(newType(toReplace.resolveTypeBinding(), ast, imports));
localDecl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD));
// ... name
String localName = proposeLocalName(this.fieldReference, this.compilationUnit, getCompilationUnit().getJavaProject());
localFrag.setName(ast.newSimpleName(localName));
// ... initialization
localFrag.setInitializer((Expression) ASTNode.copySubtree(ast, toReplace));
rearrangeStrategy.insertLocalDecl(localDecl);
// if statement:
IfStatement ifStmt = ast.newIfStatement();
// condition:
InfixExpression nullCheck = ast.newInfixExpression();
nullCheck.setLeftOperand(ast.newSimpleName(localName));
nullCheck.setRightOperand(ast.newNullLiteral());
nullCheck.setOperator(InfixExpression.Operator.NOT_EQUALS);
ifStmt.setExpression(nullCheck);
// then block: the original statement
Block thenBlock = ast.newBlock();
thenBlock.statements().add(rearrangeStrategy.createMoveTargetForOrigStmt());
ifStmt.setThenStatement(thenBlock);
// ... but with the field reference replaced by the new local:
SimpleName dereferencedName = ast.newSimpleName(localName);
rewrite.replace(toReplace, dereferencedName, group);
// else block: a Todo comment
Block elseBlock = ast.newBlock();
//$NON-NLS-1$
String elseStatement = "// TODO " + FixMessages.ExtractToNullCheckedLocalProposal_todoHandleNullDescription;
if (origStmt instanceof ReturnStatement) {
Type returnType = newType(((ReturnStatement) origStmt).getExpression().resolveTypeBinding(), ast, imports);
ReturnStatement returnStatement = ast.newReturnStatement();
returnStatement.setExpression(ASTNodeFactory.newDefaultExpression(ast, returnType, 0));
elseStatement += '\n' + ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true));
}
EmptyStatement todoNode = (EmptyStatement) rewrite.createStringPlaceholder(elseStatement, ASTNode.EMPTY_STATEMENT);
elseBlock.statements().add(todoNode);
ifStmt.setElseStatement(elseBlock);
// link all three occurrences of the new local variable:
addLinkedPosition(rewrite.track(localFrag.getName()), true, /*first*/
LOCAL_NAME_POSITION_GROUP);
addLinkedPosition(rewrite.track(nullCheck.getLeftOperand()), false, LOCAL_NAME_POSITION_GROUP);
addLinkedPosition(rewrite.track(dereferencedName), false, LOCAL_NAME_POSITION_GROUP);
rearrangeStrategy.insertIfStatement(ifStmt, thenBlock);
return rewrite;
}
use of org.eclipse.jdt.core.dom.VariableDeclarationStatement 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;
}
use of org.eclipse.jdt.core.dom.VariableDeclarationStatement in project che by eclipse.
the class AssignToVariableAssistProposal method doAddLocal.
private ASTRewrite doAddLocal() {
Expression expression = ((ExpressionStatement) fNodeToAssign).getExpression();
AST ast = fNodeToAssign.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
createImportRewrite((CompilationUnit) fNodeToAssign.getRoot());
String[] varNames = suggestLocalVariableNames(fTypeBinding, expression);
for (int i = 0; i < varNames.length; i++) {
addLinkedPositionProposal(KEY_NAME, varNames[i], null);
}
VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
newDeclFrag.setName(ast.newSimpleName(varNames[0]));
newDeclFrag.setInitializer((Expression) rewrite.createCopyTarget(expression));
Type type = evaluateType(ast);
if (ASTNodes.isControlStatementBody(fNodeToAssign.getLocationInParent())) {
Block block = ast.newBlock();
block.statements().add(rewrite.createMoveTarget(fNodeToAssign));
rewrite.replace(fNodeToAssign, block, null);
}
if (needsSemicolon(expression)) {
VariableDeclarationStatement varStatement = ast.newVariableDeclarationStatement(newDeclFrag);
varStatement.setType(type);
rewrite.replace(expression, varStatement, null);
} else {
// trick for bug 43248: use an VariableDeclarationExpression and keep the ExpressionStatement
VariableDeclarationExpression varExpression = ast.newVariableDeclarationExpression(newDeclFrag);
varExpression.setType(type);
rewrite.replace(expression, varExpression, null);
}
addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME);
addLinkedPosition(rewrite.track(type), false, KEY_TYPE);
// set cursor after expression statement
setEndPosition(rewrite.track(fNodeToAssign));
return rewrite;
}
use of org.eclipse.jdt.core.dom.VariableDeclarationStatement in project che by eclipse.
the class ExtractMethodRefactoring method createDeclaration.
private VariableDeclarationStatement createDeclaration(IVariableBinding binding, Expression intilizer) {
VariableDeclaration original = ASTNodes.findVariableDeclaration(binding, fAnalyzer.getEnclosingBodyDeclaration());
VariableDeclarationFragment fragment = fAST.newVariableDeclarationFragment();
fragment.setName((SimpleName) ASTNode.copySubtree(fAST, original.getName()));
fragment.setInitializer(intilizer);
VariableDeclarationStatement result = fAST.newVariableDeclarationStatement(fragment);
result.modifiers().addAll(ASTNode.copySubtrees(fAST, ASTNodes.getModifiers(original)));
result.setType(ASTNodeFactory.newType(fAST, original, fImportRewriter, new ContextSensitiveImportRewriteContext(original, fImportRewriter)));
return result;
}
Aggregations