use of org.eclipse.jdt.core.dom.ASTNode in project che by eclipse.
the class ReturnTypeSubProcessor method addMissingReturnTypeProposals.
public static void addMissingReturnTypeProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
ICompilationUnit cu = context.getCompilationUnit();
CompilationUnit astRoot = context.getASTRoot();
ASTNode selectedNode = problem.getCoveringNode(astRoot);
if (selectedNode == null) {
return;
}
BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration = (MethodDeclaration) decl;
ReturnStatementCollector eval = new ReturnStatementCollector();
decl.accept(eval);
AST ast = astRoot.getAST();
ITypeBinding typeBinding = eval.getTypeBinding(decl.getAST());
typeBinding = Bindings.normalizeTypeBinding(typeBinding);
if (typeBinding == null) {
//$NON-NLS-1$
typeBinding = ast.resolveWellKnownType("void");
}
if (typeBinding.isWildcardType()) {
typeBinding = ASTResolving.normalizeWildcardType(typeBinding, true, ast);
}
ASTRewrite rewrite = ASTRewrite.create(ast);
String label = Messages.format(CorrectionMessages.ReturnTypeSubProcessor_missingreturntype_description, BindingLabelProvider.getBindingLabel(typeBinding, BindingLabelProvider.DEFAULT_TEXTFLAGS));
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.MISSING_RETURN_TYPE, image);
ImportRewrite imports = proposal.createImportRewrite(astRoot);
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
Type type = imports.addImport(typeBinding, ast, importRewriteContext);
rewrite.set(methodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, type, null);
rewrite.set(methodDeclaration, MethodDeclaration.CONSTRUCTOR_PROPERTY, Boolean.FALSE, null);
Javadoc javadoc = methodDeclaration.getJavadoc();
if (javadoc != null && typeBinding != null) {
TagElement newTag = ast.newTagElement();
newTag.setTagName(TagElement.TAG_RETURN);
TextElement commentStart = ast.newTextElement();
newTag.fragments().add(commentStart);
JavadocTagsSubProcessor.insertTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), newTag, null);
//$NON-NLS-1$
proposal.addLinkedPosition(rewrite.track(commentStart), false, "comment_start");
}
//$NON-NLS-1$
String key = "return_type";
proposal.addLinkedPosition(rewrite.track(type), true, key);
if (typeBinding != null) {
ITypeBinding[] bindings = ASTResolving.getRelaxingTypes(ast, typeBinding);
for (int i = 0; i < bindings.length; i++) {
proposal.addLinkedPositionProposal(key, bindings[i]);
}
}
proposals.add(proposal);
// change to constructor
ASTNode parentType = ASTResolving.findParentType(decl);
if (parentType instanceof AbstractTypeDeclaration) {
boolean isInterface = parentType instanceof TypeDeclaration && ((TypeDeclaration) parentType).isInterface();
if (!isInterface) {
String constructorName = ((AbstractTypeDeclaration) parentType).getName().getIdentifier();
ASTNode nameNode = methodDeclaration.getName();
label = Messages.format(CorrectionMessages.ReturnTypeSubProcessor_wrongconstructorname_description, BasicElementLabels.getJavaElementName(constructorName));
proposals.add(new ReplaceCorrectionProposal(label, cu, nameNode.getStartPosition(), nameNode.getLength(), constructorName, IProposalRelevance.CHANGE_TO_CONSTRUCTOR));
}
}
}
}
use of org.eclipse.jdt.core.dom.ASTNode in project che by eclipse.
the class SuppressWarningsSubProcessor method addSuppressWarningsProposals.
public static void addSuppressWarningsProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
if (problem.isError() && !JavaCore.ENABLED.equals(context.getCompilationUnit().getJavaProject().getOption(JavaCore.COMPILER_PB_SUPPRESS_OPTIONAL_ERRORS, true))) {
return;
}
if (JavaCore.DISABLED.equals(context.getCompilationUnit().getJavaProject().getOption(JavaCore.COMPILER_PB_SUPPRESS_WARNINGS, true))) {
return;
}
String warningToken = CorrectionEngine.getWarningToken(problem.getProblemId());
if (warningToken == null) {
return;
}
for (Iterator<ICommandAccess> iter = proposals.iterator(); iter.hasNext(); ) {
Object element = iter.next();
if (element instanceof SuppressWarningsProposal && warningToken.equals(((SuppressWarningsProposal) element).getWarningToken())) {
// only one at a time
return;
}
}
ASTNode node = problem.getCoveringNode(context.getASTRoot());
if (node == null) {
return;
}
ASTNode target = node;
int relevance = IProposalRelevance.ADD_SUPPRESSWARNINGS;
do {
relevance = addSuppressWarningsProposalIfPossible(context.getCompilationUnit(), target, warningToken, relevance, proposals);
if (relevance == 0)
return;
target = target.getParent();
} while (target != null);
ASTNode importStatement = ASTNodes.getParent(node, ImportDeclaration.class);
if (importStatement != null && !context.getASTRoot().types().isEmpty()) {
target = (ASTNode) context.getASTRoot().types().get(0);
if (target != null) {
addSuppressWarningsProposalIfPossible(context.getCompilationUnit(), target, warningToken, IProposalRelevance.ADD_SUPPRESSWARNINGS, proposals);
}
}
}
use of org.eclipse.jdt.core.dom.ASTNode in project che by eclipse.
the class SuppressWarningsSubProcessor method addUnknownSuppressWarningProposals.
/**
* Adds a proposal to correct the name of the SuppressWarning annotation
* @param context the context
* @param problem the problem
* @param proposals the resulting proposals
*/
public static void addUnknownSuppressWarningProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
ASTNode coveringNode = context.getCoveringNode();
if (!(coveringNode instanceof StringLiteral))
return;
AST ast = coveringNode.getAST();
StringLiteral literal = (StringLiteral) coveringNode;
String literalValue = literal.getLiteralValue();
String[] allWarningTokens = CorrectionEngine.getAllWarningTokens();
for (int i = 0; i < allWarningTokens.length; i++) {
String curr = allWarningTokens[i];
if (NameMatcher.isSimilarName(literalValue, curr)) {
StringLiteral newLiteral = ast.newStringLiteral();
newLiteral.setLiteralValue(curr);
ASTRewrite rewrite = ASTRewrite.create(ast);
rewrite.replace(literal, newLiteral, null);
String label = Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_fix_suppress_token_label, new String[] { curr });
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.FIX_SUPPRESS_TOKEN, image);
proposals.add(proposal);
}
}
addRemoveUnusedSuppressWarningProposals(context, problem, proposals);
}
use of org.eclipse.jdt.core.dom.ASTNode 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.ASTNode in project che by eclipse.
the class GenerateForLoopAssistProposal method getVariableNameProposals.
/**
* Retrieves name proposals for a fresh local variable.
*
* @param basename the basename of the proposals
* @param excludedName a name that cannot be used for the variable; <code>null</code> if none
* @return an array of proposal strings
*/
private String[] getVariableNameProposals(String basename, String excludedName) {
ASTNode surroundingBlock = fCurrentNode;
while ((surroundingBlock = surroundingBlock.getParent()) != null) {
if (surroundingBlock instanceof Block) {
break;
}
}
Collection<String> localUsedNames = new ScopeAnalyzer((CompilationUnit) fCurrentExpression.getRoot()).getUsedVariableNames(surroundingBlock.getStartPosition(), surroundingBlock.getLength());
if (excludedName != null) {
localUsedNames.add(excludedName);
}
String[] names = StubUtility.getLocalNameSuggestions(getCompilationUnit().getJavaProject(), basename, 0, localUsedNames.toArray(new String[localUsedNames.size()]));
return names;
}
Aggregations