use of org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal in project flux by eclipse.
the class AdvancedQuickAssistProcessor method getInverseLocalVariableProposals.
private static boolean getInverseLocalVariableProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
final AST ast = covering.getAST();
// cursor should be placed on variable name
if (!(covering instanceof SimpleName)) {
return false;
}
SimpleName coveringName = (SimpleName) covering;
if (!coveringName.isDeclaration()) {
return false;
}
// prepare bindings
final IBinding variableBinding = coveringName.resolveBinding();
if (!(variableBinding instanceof IVariableBinding)) {
return false;
}
IVariableBinding binding = (IVariableBinding) variableBinding;
if (binding.isField()) {
return false;
}
// we operate only on boolean variable
if (!isBoolean(coveringName)) {
return false;
}
// we could produce quick assist
if (resultingCollections == null) {
return true;
}
// find linked nodes
final MethodDeclaration method = ASTResolving.findParentMethodDeclaration(covering);
SimpleName[] linkedNodes = LinkedNodeFinder.findByBinding(method, variableBinding);
//
final ASTRewrite rewrite = ASTRewrite.create(ast);
// create proposal
String label = CorrectionMessages.AdvancedQuickAssistProcessor_inverseBooleanVariable;
// Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
//$NON-NLS-1$
final String KEY_NAME = "name";
final LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERSE_BOOLEAN_VARIABLE);
// prepare new variable identifier
final String oldIdentifier = coveringName.getIdentifier();
//$NON-NLS-1$
final String notString = Messages.format(CorrectionMessages.AdvancedQuickAssistProcessor_negatedVariableName, "");
final String newIdentifier;
if (oldIdentifier.startsWith(notString)) {
int notLength = notString.length();
if (oldIdentifier.length() > notLength) {
newIdentifier = Character.toLowerCase(oldIdentifier.charAt(notLength)) + oldIdentifier.substring(notLength + 1);
} else {
newIdentifier = oldIdentifier;
}
} else {
newIdentifier = Messages.format(CorrectionMessages.AdvancedQuickAssistProcessor_negatedVariableName, Character.toUpperCase(oldIdentifier.charAt(0)) + oldIdentifier.substring(1));
}
//
proposal.addLinkedPositionProposal(KEY_NAME, newIdentifier, null);
proposal.addLinkedPositionProposal(KEY_NAME, oldIdentifier, null);
// iterate over linked nodes and replace variable references with negated reference
final HashSet<SimpleName> renamedNames = new HashSet<SimpleName>();
for (int i = 0; i < linkedNodes.length; i++) {
SimpleName name = linkedNodes[i];
if (renamedNames.contains(name)) {
continue;
}
// prepare new name with new identifier
SimpleName newName = ast.newSimpleName(newIdentifier);
proposal.addLinkedPosition(rewrite.track(newName), name == coveringName, KEY_NAME);
//
StructuralPropertyDescriptor location = name.getLocationInParent();
if (location == SingleVariableDeclaration.NAME_PROPERTY) {
// set new name
rewrite.replace(name, newName, null);
} else if (location == Assignment.LEFT_HAND_SIDE_PROPERTY) {
Assignment assignment = (Assignment) name.getParent();
Expression expression = assignment.getRightHandSide();
int exStart = expression.getStartPosition();
int exEnd = exStart + expression.getLength();
// collect all names that are used in assignments
HashSet<SimpleName> overlapNames = new HashSet<SimpleName>();
for (int j = 0; j < linkedNodes.length; j++) {
SimpleName name2 = linkedNodes[j];
if (name2 == null) {
continue;
}
int name2Start = name2.getStartPosition();
if (exStart <= name2Start && name2Start < exEnd) {
overlapNames.add(name2);
}
}
// prepare inverted expression
SimpleNameRenameProvider provider = new SimpleNameRenameProvider() {
public SimpleName getRenamed(SimpleName simpleName) {
if (simpleName.resolveBinding() == variableBinding) {
renamedNames.add(simpleName);
return ast.newSimpleName(newIdentifier);
}
return null;
}
};
Expression inversedExpression = getInversedExpression(rewrite, expression, provider);
// if any name was not renamed during expression inverting, we can not already rename it, so fail to create assist
for (Iterator<SimpleName> iter = overlapNames.iterator(); iter.hasNext(); ) {
Object o = iter.next();
if (!renamedNames.contains(o)) {
return false;
}
}
// check operator and replace if needed
Assignment.Operator operator = assignment.getOperator();
if (operator == Assignment.Operator.BIT_AND_ASSIGN) {
Assignment newAssignment = ast.newAssignment();
newAssignment.setLeftHandSide(newName);
newAssignment.setRightHandSide(inversedExpression);
newAssignment.setOperator(Assignment.Operator.BIT_OR_ASSIGN);
rewrite.replace(assignment, newAssignment, null);
} else if (operator == Assignment.Operator.BIT_OR_ASSIGN) {
Assignment newAssignment = ast.newAssignment();
newAssignment.setLeftHandSide(newName);
newAssignment.setRightHandSide(inversedExpression);
newAssignment.setOperator(Assignment.Operator.BIT_AND_ASSIGN);
rewrite.replace(assignment, newAssignment, null);
} else {
rewrite.replace(expression, inversedExpression, null);
// set new name
rewrite.replace(name, newName, null);
}
} else if (location == VariableDeclarationFragment.NAME_PROPERTY) {
// replace initializer for variable
VariableDeclarationFragment vdf = (VariableDeclarationFragment) name.getParent();
Expression expression = vdf.getInitializer();
if (expression != null) {
rewrite.replace(expression, getInversedExpression(rewrite, expression), null);
}
// set new name
rewrite.replace(name, newName, null);
} else if (name.getParent() instanceof PrefixExpression && ((PrefixExpression) name.getParent()).getOperator() == PrefixExpression.Operator.NOT) {
rewrite.replace(name.getParent(), newName, null);
} else {
PrefixExpression expression = ast.newPrefixExpression();
expression.setOperator(PrefixExpression.Operator.NOT);
expression.setOperand(newName);
rewrite.replace(name, expression, null);
}
}
// add correction proposal
resultingCollections.add(proposal);
return true;
}
use of org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal in project che by eclipse.
the class LocalCorrectionsSubProcessor method addUninitializedLocalVariableProposal.
public static void addUninitializedLocalVariableProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
ICompilationUnit cu = context.getCompilationUnit();
ASTNode selectedNode = problem.getCoveringNode(context.getASTRoot());
if (!(selectedNode instanceof Name)) {
return;
}
Name name = (Name) selectedNode;
IBinding binding = name.resolveBinding();
if (!(binding instanceof IVariableBinding)) {
return;
}
IVariableBinding varBinding = (IVariableBinding) binding;
CompilationUnit astRoot = context.getASTRoot();
ASTNode node = astRoot.findDeclaringNode(binding);
if (node instanceof VariableDeclarationFragment) {
ASTRewrite rewrite = ASTRewrite.create(node.getAST());
VariableDeclarationFragment fragment = (VariableDeclarationFragment) node;
if (fragment.getInitializer() != null) {
return;
}
Expression expression = ASTNodeFactory.newDefaultExpression(astRoot.getAST(), varBinding.getType());
if (expression == null) {
return;
}
rewrite.set(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, expression, null);
String label = CorrectionMessages.LocalCorrectionsSubProcessor_uninitializedvariable_description;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.INITIALIZE_VARIABLE, image);
//$NON-NLS-1$
proposal.addLinkedPosition(rewrite.track(expression), false, "initializer");
proposals.add(proposal);
}
}
use of org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal in project che by eclipse.
the class LocalCorrectionsSubProcessor method addMissingHashCodeProposals.
public static void addMissingHashCodeProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
final ICompilationUnit cu = context.getCompilationUnit();
CompilationUnit astRoot = context.getASTRoot();
ASTNode selectedNode = problem.getCoveringNode(astRoot);
if (!(selectedNode instanceof Name)) {
return;
}
AbstractTypeDeclaration typeDeclaration = null;
StructuralPropertyDescriptor locationInParent = selectedNode.getLocationInParent();
if (locationInParent != TypeDeclaration.NAME_PROPERTY && locationInParent != EnumDeclaration.NAME_PROPERTY) {
return;
}
typeDeclaration = (AbstractTypeDeclaration) selectedNode.getParent();
ITypeBinding binding = typeDeclaration.resolveBinding();
if (binding == null || binding.getSuperclass() == null) {
return;
}
final IType type = (IType) binding.getJavaElement();
boolean hasInstanceFields = false;
IVariableBinding[] declaredFields = binding.getDeclaredFields();
for (int i = 0; i < declaredFields.length; i++) {
if (!Modifier.isStatic(declaredFields[i].getModifiers())) {
hasInstanceFields = true;
break;
}
}
if (hasInstanceFields) {
//Generate hashCode() and equals()... proposal
String label = CorrectionMessages.LocalCorrectionsSubProcessor_generate_hashCode_equals_description;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ChangeCorrectionProposal proposal = new ChangeCorrectionProposal(label, null, IProposalRelevance.GENERATE_HASHCODE_AND_EQUALS, image) {
@Override
public void apply(IDocument document) {
// should never happened
throw new UnsupportedOperationException();
}
@Override
public Object getAdditionalProposalInfo(IProgressMonitor monitor) {
return CorrectionMessages.LocalCorrectionsSubProcessor_generate_hashCode_equals_additional_info;
}
@Override
public String getActionId() {
return "javaGenerateHashCodeEquals";
}
};
proposals.add(proposal);
}
//Override hashCode() proposal
//$NON-NLS-1$
IMethodBinding superHashCode = Bindings.findMethodInHierarchy(binding, "hashCode", new ITypeBinding[0]);
if (superHashCode == null) {
return;
}
String label = CorrectionMessages.LocalCorrectionsSubProcessor_override_hashCode_description;
Image image = JavaPluginImages.get(JavaPluginImages.DESC_MISC_PUBLIC);
ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
LinkedCorrectionProposal proposal2 = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.OVERRIDE_HASHCODE, image);
ImportRewrite importRewrite = proposal2.createImportRewrite(astRoot);
String typeQualifiedName = type.getTypeQualifiedName('.');
final CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(cu.getJavaProject());
try {
ImportRewriteContext importContext = new ContextSensitiveImportRewriteContext(astRoot, problem.getOffset(), importRewrite);
MethodDeclaration hashCode = StubUtility2.createImplementationStub(cu, rewrite, importRewrite, importContext, superHashCode, typeQualifiedName, settings, false);
BodyDeclarationRewrite.create(rewrite, typeDeclaration).insert(hashCode, null);
proposal2.setEndPosition(rewrite.track(hashCode));
} catch (CoreException e) {
JavaPlugin.log(e);
}
proposals.add(proposal2);
}
use of org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal in project che by eclipse.
the class LocalCorrectionsSubProcessor method getUnusedObjectAllocationProposals.
public static void getUnusedObjectAllocationProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
CompilationUnit root = context.getASTRoot();
AST ast = root.getAST();
ASTNode selectedNode = problem.getCoveringNode(root);
if (selectedNode == null) {
return;
}
ASTNode parent = selectedNode.getParent();
if (parent instanceof ExpressionStatement) {
ExpressionStatement expressionStatement = (ExpressionStatement) parent;
Expression expr = expressionStatement.getExpression();
ITypeBinding exprType = expr.resolveTypeBinding();
if (exprType != null && Bindings.isSuperType(ast.resolveWellKnownType("java.lang.Throwable"), exprType)) {
//$NON-NLS-1$
ASTRewrite rewrite = ASTRewrite.create(ast);
TightSourceRangeComputer sourceRangeComputer = new TightSourceRangeComputer();
rewrite.setTargetSourceRangeComputer(sourceRangeComputer);
ThrowStatement throwStatement = ast.newThrowStatement();
throwStatement.setExpression((Expression) rewrite.createMoveTarget(expr));
sourceRangeComputer.addTightSourceNode(expressionStatement);
rewrite.replace(expressionStatement, throwStatement, null);
String label = CorrectionMessages.LocalCorrectionsSubProcessor_throw_allocated_description;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.THROW_ALLOCATED_OBJECT, image);
proposal.setEndPosition(rewrite.track(throwStatement));
proposals.add(proposal);
}
MethodDeclaration method = ASTResolving.findParentMethodDeclaration(selectedNode);
if (method != null && !method.isConstructor()) {
ASTRewrite rewrite = ASTRewrite.create(ast);
TightSourceRangeComputer sourceRangeComputer = new TightSourceRangeComputer();
rewrite.setTargetSourceRangeComputer(sourceRangeComputer);
ReturnStatement returnStatement = ast.newReturnStatement();
returnStatement.setExpression((Expression) rewrite.createMoveTarget(expr));
sourceRangeComputer.addTightSourceNode(expressionStatement);
rewrite.replace(expressionStatement, returnStatement, null);
String label = CorrectionMessages.LocalCorrectionsSubProcessor_return_allocated_description;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
int relevance;
ITypeBinding returnTypeBinding = method.getReturnType2().resolveBinding();
if (returnTypeBinding != null && exprType != null && exprType.isAssignmentCompatible(returnTypeBinding)) {
relevance = IProposalRelevance.RETURN_ALLOCATED_OBJECT_MATCH;
} else if (method.getReturnType2() instanceof PrimitiveType && ((PrimitiveType) method.getReturnType2()).getPrimitiveTypeCode() == PrimitiveType.VOID) {
relevance = IProposalRelevance.RETURN_ALLOCATED_OBJECT_VOID;
} else {
relevance = IProposalRelevance.RETURN_ALLOCATED_OBJECT;
}
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, relevance, image);
proposal.setEndPosition(rewrite.track(returnStatement));
proposals.add(proposal);
}
{
ASTRewrite rewrite = ASTRewrite.create(ast);
rewrite.remove(parent, null);
String label = CorrectionMessages.LocalCorrectionsSubProcessor_remove_allocated_description;
//JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
Image image = JavaPluginImages.get(JavaPluginImages.IMG_TOOL_DELETE);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_UNUSED_ALLOCATED_OBJECT, image);
proposals.add(proposal);
}
}
QuickAssistProcessor.getAssignToVariableProposals(context, selectedNode, null, proposals);
}
use of org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal in project che by eclipse.
the class AdvancedQuickAssistProcessor method getCombineStringProposals.
private static boolean getCombineStringProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
// we work with InfixExpressions
InfixExpression infixExpression;
if (node instanceof InfixExpression) {
infixExpression = (InfixExpression) node;
} else if (node.getParent() instanceof InfixExpression) {
infixExpression = (InfixExpression) node.getParent();
} else {
return false;
}
// only + is valid for combining strings
if (!(infixExpression.getOperator().equals(InfixExpression.Operator.PLUS))) {
return false;
}
// all expressions must be strings
Expression leftOperand = infixExpression.getLeftOperand();
Expression rightOperand = infixExpression.getRightOperand();
if (!(leftOperand instanceof StringLiteral && rightOperand instanceof StringLiteral)) {
return false;
}
StringLiteral leftString = (StringLiteral) leftOperand;
StringLiteral rightString = (StringLiteral) rightOperand;
if (resultingCollections == null) {
return true;
}
// begin building combined string
StringBuilder stringBuilder = new StringBuilder(leftString.getLiteralValue());
stringBuilder.append(rightString.getLiteralValue());
// append extended string literals
for (Object operand : infixExpression.extendedOperands()) {
if (!(operand instanceof StringLiteral))
return false;
StringLiteral stringLiteral = (StringLiteral) operand;
stringBuilder.append(stringLiteral.getLiteralValue());
}
// prepare new string literal
AST ast = node.getAST();
StringLiteral combinedStringLiteral = ast.newStringLiteral();
combinedStringLiteral.setLiteralValue(stringBuilder.toString());
ASTRewrite rewrite = ASTRewrite.create(ast);
rewrite.replace(infixExpression, combinedStringLiteral, null);
// add correction proposal
String label = CorrectionMessages.AdvancedQuickAssistProcessor_combineSelectedStrings;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.COMBINE_STRINGS, image);
resultingCollections.add(proposal);
return true;
}
Aggregations