use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project che by eclipse.
the class OrganizeImportsOperation method createTextEdit.
public TextEdit createTextEdit(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
try {
fNumberOfImportsAdded = 0;
fNumberOfImportsRemoved = 0;
monitor.beginTask(Messages.format(CodeGenerationMessages.OrganizeImportsOperation_description, BasicElementLabels.getFileName(fCompilationUnit)), 9);
CompilationUnit astRoot = fASTRoot;
if (astRoot == null) {
astRoot = SharedASTProvider.getAST(fCompilationUnit, SharedASTProvider.WAIT_YES, new SubProgressMonitor(monitor, 2));
if (monitor.isCanceled())
throw new OperationCanceledException();
} else {
monitor.worked(2);
}
ImportRewrite importsRewrite = StubUtility.createImportRewrite(astRoot, false);
Set<String> oldSingleImports = new HashSet<>();
Set<String> oldDemandImports = new HashSet<>();
List<SimpleName> typeReferences = new ArrayList<>();
List<SimpleName> staticReferences = new ArrayList<>();
if (!collectReferences(astRoot, typeReferences, staticReferences, oldSingleImports, oldDemandImports))
return null;
monitor.worked(1);
processor = new TypeReferenceProcessor(oldSingleImports, oldDemandImports, astRoot, importsRewrite, fIgnoreLowerCaseNames);
Iterator<SimpleName> refIterator = typeReferences.iterator();
while (refIterator.hasNext()) {
SimpleName typeRef = refIterator.next();
processor.add(typeRef);
}
hasOpenChoices = processor.process(new SubProgressMonitor(monitor, 3));
addStaticImports(staticReferences, importsRewrite);
if (hasOpenChoices) {
choices = processor.getChoices();
ISourceRange[] ranges = processor.getChoicesSourceRanges();
if (fChooseImportQuery != null) {
TypeNameMatch[] chosen = fChooseImportQuery.chooseImports(choices, ranges);
for (int i = 0; i < chosen.length; i++) {
TypeNameMatch typeInfo = chosen[i];
importsRewrite.addImport(typeInfo.getFullyQualifiedName());
}
} else if (chosenFQN != null) {
chosenFQN.forEach(importsRewrite::addImport);
}
}
TextEdit result = importsRewrite.rewriteImports(new SubProgressMonitor(monitor, 3));
determineImportDifferences(importsRewrite, oldSingleImports, oldDemandImports);
return result;
} finally {
monitor.done();
}
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite 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.rewrite.ImportRewrite 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.rewrite.ImportRewrite in project che by eclipse.
the class NewDefiningMethodProposal method addNewParameters.
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.correction.proposals.AbstractMethodCorrectionProposal#addNewParameters(org.eclipse.jdt.core
* .dom.rewrite.ASTRewrite, java.util.List, java.util.List)
*/
@Override
protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params) throws CoreException {
AST ast = rewrite.getAST();
ImportRewrite importRewrite = getImportRewrite();
ITypeBinding[] bindings = fMethod.getParameterTypes();
IJavaProject project = getCompilationUnit().getJavaProject();
String[][] paramNames = StubUtility.suggestArgumentNamesWithProposals(project, fParamNames);
for (int i = 0; i < bindings.length; i++) {
ITypeBinding curr = bindings[i];
String[] proposedNames = paramNames[i];
SingleVariableDeclaration newParam = ast.newSingleVariableDeclaration();
newParam.setType(importRewrite.addImport(curr, ast));
newParam.setName(ast.newSimpleName(proposedNames[0]));
params.add(newParam);
//$NON-NLS-1$
String groupId = "arg_name_" + i;
addLinkedPosition(rewrite.track(newParam.getName()), false, groupId);
for (int k = 0; k < proposedNames.length; k++) {
addLinkedPositionProposal(groupId, proposedNames[k], null);
}
}
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project che by eclipse.
the class NewDefiningMethodProposal method addNewExceptions.
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.correction.proposals.AbstractMethodCorrectionProposal#addNewExceptions(org.eclipse.jdt.core.dom.rewrite.ASTRewrite, java.util.List)
*/
@Override
protected void addNewExceptions(ASTRewrite rewrite, List<Type> exceptions) throws CoreException {
AST ast = rewrite.getAST();
ImportRewrite importRewrite = getImportRewrite();
ITypeBinding[] bindings = fMethod.getExceptionTypes();
for (int i = 0; i < bindings.length; i++) {
Type newType = importRewrite.addImport(bindings[i], ast);
exceptions.add(newType);
//$NON-NLS-1$
addLinkedPosition(rewrite.track(newType), false, "exc_type_" + i);
}
}
Aggregations