use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite 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.core.dom.rewrite.ImportRewrite in project che by eclipse.
the class LocalCorrectionsSubProcessor method addDeprecatedFieldsToMethodsProposals.
public static void addDeprecatedFieldsToMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
ASTNode selectedNode = problem.getCoveringNode(context.getASTRoot());
if (selectedNode instanceof Name) {
IBinding binding = ((Name) selectedNode).resolveBinding();
if (binding instanceof IVariableBinding) {
IVariableBinding variableBinding = (IVariableBinding) binding;
if (variableBinding.isField()) {
String qualifiedName = variableBinding.getDeclaringClass().getTypeDeclaration().getQualifiedName();
String fieldName = variableBinding.getName();
String[] methodName = getMethod(JavaModelUtil.concatenateName(qualifiedName, fieldName));
if (methodName != null) {
AST ast = selectedNode.getAST();
ASTRewrite astRewrite = ASTRewrite.create(ast);
ImportRewrite importRewrite = StubUtility.createImportRewrite(context.getASTRoot(), true);
MethodInvocation method = ast.newMethodInvocation();
String qfn = importRewrite.addImport(methodName[0]);
method.setExpression(ast.newName(qfn));
method.setName(ast.newSimpleName(methodName[1]));
ASTNode parent = selectedNode.getParent();
ICompilationUnit cu = context.getCompilationUnit();
// add explicit type arguments if necessary (for 1.8 and later, we're optimistic that inference just works):
if (Invocations.isInvocationWithArguments(parent) && !JavaModelUtil.is18OrHigher(cu.getJavaProject())) {
IMethodBinding methodBinding = Invocations.resolveBinding(parent);
if (methodBinding != null) {
ITypeBinding[] parameterTypes = methodBinding.getParameterTypes();
int i = Invocations.getArguments(parent).indexOf(selectedNode);
if (parameterTypes.length >= i && parameterTypes[i].isParameterizedType()) {
ITypeBinding[] typeArguments = parameterTypes[i].getTypeArguments();
for (int j = 0; j < typeArguments.length; j++) {
ITypeBinding typeArgument = typeArguments[j];
typeArgument = Bindings.normalizeForDeclarationUse(typeArgument, ast);
if (!TypeRules.isJavaLangObject(typeArgument)) {
// add all type arguments if at least one is found to be necessary:
List<Type> typeArgumentsList = method.typeArguments();
for (int k = 0; k < typeArguments.length; k++) {
typeArgument = typeArguments[k];
typeArgument = Bindings.normalizeForDeclarationUse(typeArgument, ast);
typeArgumentsList.add(importRewrite.addImport(typeArgument, ast));
}
break;
}
}
}
}
}
astRewrite.replace(selectedNode, method, null);
String label = Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_replacefieldaccesswithmethod_description, BasicElementLabels.getJavaElementName(ASTNodes.asString(method)));
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, astRewrite, IProposalRelevance.REPLACE_FIELD_ACCESS_WITH_METHOD, image);
proposal.setImportRewrite(importRewrite);
proposals.add(proposal);
}
}
}
}
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project che by eclipse.
the class AdvancedQuickAssistProcessor method getConvertIfElseToSwitchProposals.
private static boolean getConvertIfElseToSwitchProposals(IInvocationContext context, ASTNode coveringNode, ArrayList<ICommandAccess> resultingCollections, boolean handleNullArg) {
final AST ast = coveringNode.getAST();
final ASTRewrite rewrite = ASTRewrite.create(ast);
final ImportRewrite importRewrite = StubUtility.createImportRewrite(context.getASTRoot(), true);
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(coveringNode), importRewrite);
IfStatement ifStatement = (IfStatement) coveringNode;
IfStatement currentIf = ifStatement;
Statement currentStatement = ifStatement;
Expression currentExpression = currentIf.getExpression();
SwitchStatement switchStatement = ast.newSwitchStatement();
Expression switchExpression = null;
boolean executeDefaultOnNullExpression = false;
Statement defaultStatement = null;
while (currentStatement != null) {
Expression expression = null;
List<Expression> caseExpressions = new ArrayList<Expression>();
if (currentIf != null) {
while (currentExpression != null) {
// loop for fall through cases - multiple expressions with || operator
Expression leftOperand;
Expression rightOperand;
boolean isMethodInvocationCase = false;
if (currentExpression instanceof MethodInvocation) {
isMethodInvocationCase = true;
if (//$NON-NLS-1$
!(((MethodInvocation) currentExpression).getName().getIdentifier()).equals("equals"))
return false;
MethodInvocation invocation = (MethodInvocation) currentExpression;
leftOperand = invocation.getExpression();
if (leftOperand == null)
return false;
ITypeBinding leftBinding = leftOperand.resolveTypeBinding();
if (leftBinding != null) {
if (leftBinding.getQualifiedName().equals("java.lang.String")) {
//$NON-NLS-1$
if (!JavaModelUtil.is17OrHigher(context.getCompilationUnit().getJavaProject()))
return false;
} else if (!leftBinding.isEnum()) {
return false;
}
}
List<Expression> arguments = invocation.arguments();
if (arguments.size() != 1)
return false;
rightOperand = arguments.get(0);
ITypeBinding rightBinding = leftOperand.resolveTypeBinding();
if (rightBinding != null) {
if (rightBinding.getQualifiedName().equals("java.lang.String")) {
//$NON-NLS-1$
if (!JavaModelUtil.is17OrHigher(context.getCompilationUnit().getJavaProject()))
return false;
} else if (!rightBinding.isEnum()) {
return false;
}
}
} else if (currentExpression instanceof InfixExpression) {
InfixExpression infixExpression = (InfixExpression) currentExpression;
Operator operator = infixExpression.getOperator();
if (!(operator.equals(InfixExpression.Operator.CONDITIONAL_OR) || operator.equals(InfixExpression.Operator.EQUALS)))
return false;
leftOperand = infixExpression.getLeftOperand();
rightOperand = infixExpression.getRightOperand();
if (operator.equals(InfixExpression.Operator.EQUALS)) {
ITypeBinding typeBinding = leftOperand.resolveTypeBinding();
if (typeBinding != null && typeBinding.getQualifiedName().equals("java.lang.String")) {
// don't propose quick assist when == is used to compare strings, since switch will use equals()
return false;
}
} else if (operator.equals(InfixExpression.Operator.CONDITIONAL_OR)) {
currentExpression = leftOperand;
continue;
}
} else {
return false;
}
if (leftOperand.resolveConstantExpressionValue() != null) {
caseExpressions.add(leftOperand);
expression = rightOperand;
executeDefaultOnNullExpression |= isMethodInvocationCase;
} else if (rightOperand.resolveConstantExpressionValue() != null) {
caseExpressions.add(rightOperand);
expression = leftOperand;
} else if (leftOperand instanceof QualifiedName) {
QualifiedName qualifiedName = (QualifiedName) leftOperand;
IVariableBinding binding = (IVariableBinding) qualifiedName.resolveBinding();
if (binding == null || !binding.isEnumConstant())
return false;
importRewrite.addImport(binding.getDeclaringClass(), importRewriteContext);
caseExpressions.add(qualifiedName.getName());
expression = rightOperand;
executeDefaultOnNullExpression |= isMethodInvocationCase;
} else if (rightOperand instanceof QualifiedName) {
QualifiedName qualifiedName = (QualifiedName) rightOperand;
IVariableBinding binding = (IVariableBinding) qualifiedName.resolveBinding();
if (binding == null || !binding.isEnumConstant())
return false;
importRewrite.addImport(binding.getDeclaringClass(), importRewriteContext);
caseExpressions.add(qualifiedName.getName());
expression = leftOperand;
} else {
return false;
}
if (expression == null) {
// paranoidal check: this condition should never be true
return false;
}
if (currentExpression.getParent() instanceof InfixExpression) {
currentExpression = getNextSiblingExpression(currentExpression);
} else {
currentExpression = null;
}
if (switchExpression == null) {
switchExpression = expression;
}
if (!switchExpression.subtreeMatch(new ASTMatcher(), expression)) {
return false;
}
}
}
Statement thenStatement;
if (currentIf == null) {
//currentStatement has the default else block
thenStatement = currentStatement;
defaultStatement = currentStatement;
} else {
thenStatement = currentIf.getThenStatement();
}
SwitchCase[] switchCaseStatements = createSwitchCaseStatements(ast, rewrite, caseExpressions);
for (int i = 0; i < switchCaseStatements.length; i++) {
switchStatement.statements().add(switchCaseStatements[i]);
}
boolean isBreakRequired = true;
if (thenStatement instanceof Block) {
Statement statement = null;
for (Iterator<Statement> iter = ((Block) thenStatement).statements().iterator(); iter.hasNext(); ) {
statement = iter.next();
switchStatement.statements().add(rewrite.createCopyTarget(statement));
}
if (statement instanceof ReturnStatement || statement instanceof ThrowStatement)
isBreakRequired = false;
} else {
if (thenStatement instanceof ReturnStatement || thenStatement instanceof ThrowStatement)
isBreakRequired = false;
switchStatement.statements().add(rewrite.createCopyTarget(thenStatement));
}
if (isBreakRequired)
switchStatement.statements().add(ast.newBreakStatement());
// advance currentStatement to the next "else if" or "else":
if (currentIf != null && currentIf.getElseStatement() != null) {
Statement elseStatement = currentIf.getElseStatement();
if (elseStatement instanceof IfStatement) {
currentIf = (IfStatement) elseStatement;
currentStatement = currentIf;
currentExpression = currentIf.getExpression();
} else {
currentIf = null;
currentStatement = elseStatement;
currentExpression = null;
}
} else {
currentStatement = null;
}
}
if (switchExpression == null)
return false;
switchStatement.setExpression((Expression) rewrite.createCopyTarget(switchExpression));
if (handleNullArg) {
if (executeDefaultOnNullExpression) {
IfStatement newIfStatement = ast.newIfStatement();
InfixExpression infixExpression = ast.newInfixExpression();
infixExpression.setLeftOperand((Expression) rewrite.createCopyTarget(switchExpression));
infixExpression.setRightOperand(ast.newNullLiteral());
infixExpression.setOperator(InfixExpression.Operator.EQUALS);
newIfStatement.setExpression(infixExpression);
if (defaultStatement == null) {
Block block = ast.newBlock();
newIfStatement.setThenStatement(block);
} else if (defaultStatement instanceof Block) {
Block block = ast.newBlock();
for (Iterator<Statement> iter = ((Block) defaultStatement).statements().iterator(); iter.hasNext(); ) {
block.statements().add(rewrite.createCopyTarget(iter.next()));
}
newIfStatement.setThenStatement(block);
} else {
newIfStatement.setThenStatement((Statement) rewrite.createCopyTarget(defaultStatement));
}
Block block = ast.newBlock();
block.statements().add(switchStatement);
newIfStatement.setElseStatement(block);
rewrite.replace(ifStatement, newIfStatement, null);
//$NON-NLS-1$ //$NON-NLS-2$
String source = ASTNodes.asString(switchExpression).replaceAll("\r\n?|\n", " ");
String label = Messages.format(CorrectionMessages.AdvancedQuickAssistProcessor_convertIfElseToSwitch_handleNullArg, source);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_IF_ELSE_TO_SWITCH);
proposal.setImportRewrite(importRewrite);
resultingCollections.add(proposal);
}
} else {
rewrite.replace(ifStatement, switchStatement, null);
String label = CorrectionMessages.AdvancedQuickAssistProcessor_convertIfElseToSwitch;
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_IF_ELSE_TO_SWITCH);
proposal.setImportRewrite(importRewrite);
resultingCollections.add(proposal);
}
return true;
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project che by eclipse.
the class MoveCuUpdateCreator method getImportRewrite.
private ImportRewrite getImportRewrite(ICompilationUnit cu) throws CoreException {
if (fImportRewrites.containsKey(cu))
return fImportRewrites.get(cu);
ImportRewrite importEdit = StubUtility.createImportRewrite(cu, true);
fImportRewrites.put(cu, importEdit);
return importEdit;
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project che by eclipse.
the class SourceProvider method updateTypeReferences.
private void updateTypeReferences(ASTRewrite rewriter, CallContext context) {
ImportRewrite importer = context.importer;
for (Iterator<SimpleName> iter = fAnalyzer.getTypesToImport().iterator(); iter.hasNext(); ) {
Name element = iter.next();
ITypeBinding binding = ASTNodes.getTypeBinding(element);
if (binding != null && !binding.isLocal()) {
// Vector and one for Integer in Vector<Integer>.
if (binding.isParameterizedType()) {
binding = binding.getTypeDeclaration();
}
String s = importer.addImport(binding);
if (!ASTNodes.asString(element).equals(s)) {
rewriter.replace(element, rewriter.createStringPlaceholder(s, ASTNode.SIMPLE_NAME), null);
}
}
}
}
Aggregations