use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project che by eclipse.
the class ImportCompletionProposal method createImportRewrite.
/**
* Creates and returns the import rewrite
* if imports should be added at all.
*
* @return the import rewrite or <code>null</code> if no imports can or should be added
*/
private ImportRewrite createImportRewrite() {
if (fCompilationUnit != null && shouldAddImports()) {
try {
CompilationUnit cu = getASTRoot(fCompilationUnit);
if (cu == null) {
ImportRewrite rewrite = StubUtility.createImportRewrite(fCompilationUnit, true);
fImportContext = null;
return rewrite;
} else {
ImportRewrite rewrite = StubUtility.createImportRewrite(cu, true);
fImportContext = new ContextSensitiveImportRewriteContext(cu, fInvocationContext.getInvocationOffset(), rewrite);
return rewrite;
}
} catch (CoreException x) {
JavaPlugin.log(x);
}
}
return null;
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite 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 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 in project che by eclipse.
the class ConvertForLoopOperation method convert.
@Override
protected Statement convert(CompilationUnitRewrite cuRewrite, TextEditGroup group, LinkedProposalModel positionGroups) throws CoreException {
ASTRewrite rewrite = cuRewrite.getASTRewrite();
ImportRewrite importRewrite = cuRewrite.getImportRewrite();
ForStatement forStatement = getForStatement();
IJavaProject javaProject = ((CompilationUnit) forStatement.getRoot()).getJavaElement().getJavaProject();
String[] proposals = getVariableNameProposals(fArrayAccess.resolveTypeBinding(), javaProject);
String parameterName;
if (fElementDeclaration != null) {
parameterName = fElementDeclaration.getName().getIdentifier();
} else {
parameterName = proposals[0];
}
LinkedProposalPositionGroup pg = positionGroups.getPositionGroup(parameterName, true);
if (fElementDeclaration != null)
pg.addProposal(parameterName, null, 10);
for (int i = 0; i < proposals.length; i++) {
pg.addProposal(proposals[i], null, 10);
}
AST ast = forStatement.getAST();
EnhancedForStatement result = ast.newEnhancedForStatement();
SingleVariableDeclaration parameterDeclaration = createParameterDeclaration(parameterName, fElementDeclaration, fArrayAccess, forStatement, importRewrite, rewrite, group, pg, fMakeFinal);
result.setParameter(parameterDeclaration);
result.setExpression((Expression) rewrite.createCopyTarget(fArrayAccess));
convertBody(forStatement.getBody(), fIndexBinding, fArrayBinding, parameterName, rewrite, group, pg);
result.setBody(getBody(cuRewrite, group, positionGroups));
positionGroups.setEndPosition(rewrite.track(result));
return result;
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite 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;
}
Aggregations