use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext in project che by eclipse.
the class OverrideCompletionProposal method updateReplacementString.
/*
* @see JavaTypeCompletionProposal#updateReplacementString(IDocument,char,int,ImportRewrite)
*/
@Override
protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite importRewrite) throws CoreException, BadLocationException {
Document recoveredDocument = new Document();
CompilationUnit unit = getRecoveredAST(document, offset, recoveredDocument);
ImportRewriteContext context;
if (importRewrite != null) {
context = new ContextSensitiveImportRewriteContext(unit, offset, importRewrite);
} else {
// create a dummy import rewriter to have one
importRewrite = StubUtility.createImportRewrite(unit, true);
context = new // forces that all imports are fully qualified
ImportRewriteContext() {
@Override
public int findInContext(String qualifier, String name, int kind) {
return RES_NAME_CONFLICT;
}
};
}
ITypeBinding declaringType = null;
ChildListPropertyDescriptor descriptor = null;
ASTNode node = NodeFinder.perform(unit, offset, 1);
if (node instanceof AnonymousClassDeclaration) {
declaringType = ((AnonymousClassDeclaration) node).resolveBinding();
descriptor = AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
} else if (node instanceof AbstractTypeDeclaration) {
AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) node;
descriptor = declaration.getBodyDeclarationsProperty();
declaringType = declaration.resolveBinding();
}
if (declaringType != null) {
ASTRewrite rewrite = ASTRewrite.create(unit.getAST());
IMethodBinding methodToOverride = Bindings.findMethodInHierarchy(declaringType, fMethodName, fParamTypes);
if (methodToOverride == null && declaringType.isInterface()) {
//$NON-NLS-1$
methodToOverride = Bindings.findMethodInType(node.getAST().resolveWellKnownType("java.lang.Object"), fMethodName, fParamTypes);
}
if (methodToOverride != null) {
CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fJavaProject);
MethodDeclaration stub = StubUtility2.createImplementationStub(fCompilationUnit, rewrite, importRewrite, context, methodToOverride, declaringType.getName(), settings, declaringType.isInterface());
ListRewrite rewriter = rewrite.getListRewrite(node, descriptor);
rewriter.insertFirst(stub, null);
ITrackedNodePosition position = rewrite.track(stub);
try {
rewrite.rewriteAST(recoveredDocument, fJavaProject.getOptions(true)).apply(recoveredDocument);
String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength());
int generatedIndent = IndentManipulation.measureIndentUnits(getIndentAt(recoveredDocument, position.getStartPosition(), settings), settings.tabWidth, settings.indentWidth);
String indent = getIndentAt(document, getReplacementOffset(), settings);
setReplacementString(IndentManipulation.changeIndent(generatedCode, generatedIndent, settings.tabWidth, settings.indentWidth, indent, TextUtilities.getDefaultLineDelimiter(document)));
} catch (MalformedTreeException exception) {
JavaPlugin.log(exception);
} catch (BadLocationException exception) {
JavaPlugin.log(exception);
}
}
}
return true;
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext in project che by eclipse.
the class NewVariableCorrectionProposal method doAddField.
private ASTRewrite doAddField(CompilationUnit astRoot) {
SimpleName node = fOriginalNode;
boolean isInDifferentCU = false;
ASTNode newTypeDecl = astRoot.findDeclaringNode(fSenderBinding);
if (newTypeDecl == null) {
astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey());
isInDifferentCU = true;
}
ImportRewrite imports = createImportRewrite(astRoot);
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(node), imports);
if (newTypeDecl != null) {
AST ast = newTypeDecl.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment();
fragment.setName(ast.newSimpleName(node.getIdentifier()));
Type type = evaluateVariableType(ast, imports, importRewriteContext, fSenderBinding);
FieldDeclaration newDecl = ast.newFieldDeclaration(fragment);
newDecl.setType(type);
newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, evaluateFieldModifiers(newTypeDecl)));
if (fSenderBinding.isInterface() || fVariableKind == CONST_FIELD) {
fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0));
}
ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
List<BodyDeclaration> decls = ASTNodes.<BodyDeclaration>getChildListProperty(newTypeDecl, property);
int maxOffset = isInDifferentCU ? -1 : node.getStartPosition();
int insertIndex = findFieldInsertIndex(decls, newDecl, maxOffset);
ListRewrite listRewriter = rewrite.getListRewrite(newTypeDecl, property);
listRewriter.insertAt(newDecl, insertIndex, null);
ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(getLinkedProposalModel(), rewrite, newDecl.modifiers(), fSenderBinding.isInterface());
addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
if (!isInDifferentCU) {
addLinkedPosition(rewrite.track(node), true, KEY_NAME);
}
addLinkedPosition(rewrite.track(fragment.getName()), false, KEY_NAME);
if (fragment.getInitializer() != null) {
addLinkedPosition(rewrite.track(fragment.getInitializer()), false, KEY_INITIALIZER);
}
return rewrite;
}
return null;
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext in project che by eclipse.
the class NewVariableCorrectionProposal method doAddParam.
private ASTRewrite doAddParam(CompilationUnit cu) {
AST ast = cu.getAST();
SimpleName node = fOriginalNode;
BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(node);
if (decl instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration = (MethodDeclaration) decl;
ASTRewrite rewrite = ASTRewrite.create(ast);
ImportRewrite imports = createImportRewrite((CompilationUnit) decl.getRoot());
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
SingleVariableDeclaration newDecl = ast.newSingleVariableDeclaration();
newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, methodDeclaration.resolveBinding()));
newDecl.setName(ast.newSimpleName(node.getIdentifier()));
ListRewrite listRewriter = rewrite.getListRewrite(decl, MethodDeclaration.PARAMETERS_PROPERTY);
listRewriter.insertLast(newDecl, null);
addLinkedPosition(rewrite.track(node), true, KEY_NAME);
// add javadoc tag
Javadoc javadoc = methodDeclaration.getJavadoc();
if (javadoc != null) {
HashSet<String> leadingNames = new HashSet<String>();
for (Iterator<SingleVariableDeclaration> iter = methodDeclaration.parameters().iterator(); iter.hasNext(); ) {
SingleVariableDeclaration curr = iter.next();
leadingNames.add(curr.getName().getIdentifier());
}
SimpleName newTagRef = ast.newSimpleName(node.getIdentifier());
TagElement newTagElement = ast.newTagElement();
newTagElement.setTagName(TagElement.TAG_PARAM);
newTagElement.fragments().add(newTagRef);
TextElement commentStart = ast.newTextElement();
newTagElement.fragments().add(commentStart);
addLinkedPosition(rewrite.track(newTagRef), false, KEY_NAME);
//$NON-NLS-1$
addLinkedPosition(rewrite.track(commentStart), false, "comment_start");
ListRewrite tagsRewriter = rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY);
JavadocTagsSubProcessor.insertTag(tagsRewriter, newTagElement, leadingNames);
}
addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
addLinkedPosition(rewrite.track(newDecl.getName()), false, KEY_NAME);
return rewrite;
}
return null;
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext in project che by eclipse.
the class AdvancedQuickAssistProcessor method getConvertSwitchToIfProposals.
private static boolean getConvertSwitchToIfProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections, boolean preserveNPE) {
final AST ast = covering.getAST();
final ASTRewrite rewrite = ASTRewrite.create(ast);
final ImportRewrite importRewrite = StubUtility.createImportRewrite(context.getASTRoot(), true);
//
SwitchStatement switchStatement = (SwitchStatement) covering;
ITypeBinding expressionType = switchStatement.getExpression().resolveTypeBinding();
//$NON-NLS-1$
boolean isStringsInSwitch = expressionType != null && "java.lang.String".equals(expressionType.getQualifiedName());
if (!isStringsInSwitch && preserveNPE)
return false;
IfStatement firstIfStatement = null;
IfStatement currentIfStatement = null;
Block currentBlock = null;
boolean hasStopAsLastExecutableStatement = false;
Block defaultBlock = null;
Expression currentCondition = null;
boolean defaultFound = false;
ArrayList<Block> allBlocks = new ArrayList<Block>();
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(covering), importRewrite);
Expression switchExpression = switchStatement.getExpression();
Name varName;
VariableDeclarationStatement variableDeclarationStatement = null;
if (switchExpression instanceof Name) {
varName = (Name) switchExpression;
} else {
// Switch expression could have side effects, see bug 252040
VariableDeclarationFragment variableDeclarationFragment = ast.newVariableDeclarationFragment();
String[] varNames = StubUtility.getVariableNameSuggestions(NamingConventions.VK_LOCAL, context.getCompilationUnit().getJavaProject(), expressionType, switchExpression, null);
varName = ast.newSimpleName(varNames[0]);
variableDeclarationFragment.setName((SimpleName) varName);
variableDeclarationFragment.setStructuralProperty(VariableDeclarationFragment.INITIALIZER_PROPERTY, rewrite.createCopyTarget(switchExpression));
variableDeclarationStatement = ast.newVariableDeclarationStatement(variableDeclarationFragment);
Type type = importRewrite.addImport(expressionType, ast, importRewriteContext);
variableDeclarationStatement.setType(type);
}
for (Iterator<Statement> iter = switchStatement.statements().iterator(); iter.hasNext(); ) {
Statement statement = iter.next();
if (statement instanceof SwitchCase) {
SwitchCase switchCase = (SwitchCase) statement;
// special case: pass through
if (currentBlock != null) {
if (!hasStopAsLastExecutableStatement) {
return false;
}
currentBlock = null;
}
if (defaultFound) {
// This gets too complicated. We only support 'default' as last SwitchCase.
return false;
}
if (switchCase.isDefault()) {
defaultFound = true;
}
// prepare condition (is null for 'default')
Expression switchCaseCondition = createSwitchCaseCondition(ast, rewrite, importRewrite, importRewriteContext, varName, switchCase, isStringsInSwitch, preserveNPE);
if (currentCondition == null) {
currentCondition = switchCaseCondition;
} else {
InfixExpression condition = ast.newInfixExpression();
condition.setOperator(InfixExpression.Operator.CONDITIONAL_OR);
condition.setLeftOperand(currentCondition);
if (switchCaseCondition == null)
switchCaseCondition = ast.newBooleanLiteral(true);
condition.setRightOperand(switchCaseCondition);
currentCondition = condition;
}
} else {
// ensure that current block exists as 'then' statement of 'if'
if (currentBlock == null) {
if (currentCondition != null) {
IfStatement ifStatement;
if (firstIfStatement == null) {
firstIfStatement = ast.newIfStatement();
ifStatement = firstIfStatement;
} else {
ifStatement = ast.newIfStatement();
currentIfStatement.setElseStatement(ifStatement);
}
currentIfStatement = ifStatement;
ifStatement.setExpression(currentCondition);
currentCondition = null;
currentBlock = ast.newBlock();
ifStatement.setThenStatement(currentBlock);
allBlocks.add(currentBlock);
} else {
// case for default:
defaultBlock = ast.newBlock();
currentBlock = defaultBlock;
allBlocks.add(currentBlock);
// delay adding of default block
}
}
if (statement instanceof BreakStatement) {
currentBlock = null;
} else {
// add current statement in current block
hasStopAsLastExecutableStatement = hasStopAsLastExecutableStatement(statement);
Statement copyStatement = copyStatementExceptBreak(ast, rewrite, statement);
currentBlock.statements().add(copyStatement);
}
}
}
// check, may be we have delayed default block
if (defaultBlock != null) {
currentIfStatement.setElseStatement(defaultBlock);
}
// remove unnecessary blocks in blocks
for (int i = 0; i < allBlocks.size(); i++) {
Block block = allBlocks.get(i);
List<Statement> statements = block.statements();
if (statements.size() == 1 && statements.get(0) instanceof Block) {
Block innerBlock = (Block) statements.remove(0);
block.getParent().setStructuralProperty(block.getLocationInParent(), innerBlock);
}
}
if (variableDeclarationStatement == null) {
// replace 'switch' with single if-else-if statement
rewrite.replace(switchStatement, firstIfStatement, null);
} else {
new StatementRewrite(rewrite, new ASTNode[] { switchStatement }).replace(new ASTNode[] { variableDeclarationStatement, firstIfStatement }, null);
}
// add correction proposal
//$NON-NLS-1$ //$NON-NLS-2$
String source = ASTNodes.asString(switchExpression).replaceAll("\r\n?|\n", " ");
String label = preserveNPE ? Messages.format(CorrectionMessages.AdvancedQuickAssistProcessor_convertSwitchToIf_preserveNPE, source) : CorrectionMessages.AdvancedQuickAssistProcessor_convertSwitchToIf;
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_SWITCH_TO_IF_ELSE);
proposal.setImportRewrite(importRewrite);
resultingCollections.add(proposal);
return true;
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext 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);
}
Aggregations