use of org.eclipse.jdt.core.dom.rewrite.ListRewrite in project che by eclipse.
the class NewAnnotationMemberProposal method getRewrite.
@Override
protected ASTRewrite getRewrite() throws CoreException {
CompilationUnit astRoot = ASTResolving.findParentCompilationUnit(fInvocationNode);
ASTNode typeDecl = astRoot.findDeclaringNode(fSenderBinding);
ASTNode newTypeDecl = null;
if (typeDecl != null) {
newTypeDecl = typeDecl;
} else {
astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey());
}
createImportRewrite(astRoot);
if (newTypeDecl instanceof AnnotationTypeDeclaration) {
AnnotationTypeDeclaration newAnnotationTypeDecl = (AnnotationTypeDeclaration) newTypeDecl;
ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
AnnotationTypeMemberDeclaration newStub = getStub(rewrite, newAnnotationTypeDecl);
List<BodyDeclaration> members = newAnnotationTypeDecl.bodyDeclarations();
int insertIndex = members.size();
ListRewrite listRewriter = rewrite.getListRewrite(newAnnotationTypeDecl, AnnotationTypeDeclaration.BODY_DECLARATIONS_PROPERTY);
listRewriter.insertAt(newStub, insertIndex, null);
return rewrite;
}
return null;
}
use of org.eclipse.jdt.core.dom.rewrite.ListRewrite in project che by eclipse.
the class AnonymousTypeCompletionProposal method createNewBody.
private String createNewBody(ImportRewrite importRewrite) throws CoreException {
if (importRewrite == null)
return null;
ICompilationUnit workingCopy = null;
try {
//$NON-NLS-1$
String name = "Type" + System.currentTimeMillis();
workingCopy = fCompilationUnit.getPrimary().getWorkingCopy(null);
ISourceRange range = fSuperType.getSourceRange();
boolean sameUnit = range != null && fCompilationUnit.equals(fSuperType.getCompilationUnit());
// creates a type that extends the super type
String dummyClassContent = createDummyType(name);
StringBuffer workingCopyContents = new StringBuffer(fCompilationUnit.getSource());
int insertPosition;
if (sameUnit) {
insertPosition = range.getOffset() + range.getLength();
} else {
ISourceRange firstTypeRange = fCompilationUnit.getTypes()[0].getSourceRange();
insertPosition = firstTypeRange.getOffset();
}
if (fSuperType.isLocal()) {
// add an extra block: helps the AST to recover
workingCopyContents.insert(insertPosition, '{' + dummyClassContent + '}');
insertPosition++;
} else {
/*
* The two empty lines are added because the trackedDeclaration uses the covered range
* and hence would also included comments that directly follow the dummy class.
*/
//$NON-NLS-1$
workingCopyContents.insert(insertPosition, dummyClassContent + "\n\n");
}
workingCopy.getBuffer().setContents(workingCopyContents.toString());
CheASTParser parser = CheASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
parser.setResolveBindings(true);
parser.setStatementsRecovery(true);
parser.setSource(workingCopy);
CompilationUnit astRoot = (CompilationUnit) parser.createAST(new NullProgressMonitor());
ASTNode newType = NodeFinder.perform(astRoot, insertPosition, dummyClassContent.length());
if (!(newType instanceof AbstractTypeDeclaration))
return null;
AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) newType;
ITypeBinding dummyTypeBinding = declaration.resolveBinding();
if (dummyTypeBinding == null)
return null;
IMethodBinding[] bindings = StubUtility2.getOverridableMethods(astRoot.getAST(), dummyTypeBinding, true);
if (fSuperType.isInterface()) {
ITypeBinding[] dummySuperInterfaces = dummyTypeBinding.getInterfaces();
if (dummySuperInterfaces.length == 0 || dummySuperInterfaces.length == 1 && dummySuperInterfaces[0].isRawType())
bindings = new IMethodBinding[0];
} else {
ITypeBinding dummySuperclass = dummyTypeBinding.getSuperclass();
if (dummySuperclass == null || dummySuperclass.isRawType())
bindings = new IMethodBinding[0];
}
CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fSuperType.getJavaProject());
IMethodBinding[] methodsToOverride = null;
IType type = null;
if (!fSuperType.isInterface() && !fSuperType.isAnnotation()) {
IJavaElement typeElement = dummyTypeBinding.getJavaElement();
// add extra checks here as the recovered code is fragile
if (typeElement instanceof IType && name.equals(typeElement.getElementName()) && typeElement.exists()) {
type = (IType) typeElement;
}
}
if (type != null) {
//TODO window
throw new UnsupportedOperationException();
} else {
settings.createComments = false;
List<IMethodBinding> result = new ArrayList<IMethodBinding>();
for (int i = 0; i < bindings.length; i++) {
IMethodBinding curr = bindings[i];
if (Modifier.isAbstract(curr.getModifiers()))
result.add(curr);
}
methodsToOverride = result.toArray(new IMethodBinding[result.size()]);
}
ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
ITrackedNodePosition trackedDeclaration = rewrite.track(declaration);
ListRewrite rewriter = rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
for (int i = 0; i < methodsToOverride.length; i++) {
IMethodBinding curr = methodsToOverride[i];
MethodDeclaration stub = StubUtility2.createImplementationStub(workingCopy, rewrite, importRewrite, null, curr, dummyTypeBinding.getName(), settings, dummyTypeBinding.isInterface());
rewriter.insertFirst(stub, null);
}
IDocument document = new Document(workingCopy.getSource());
try {
rewrite.rewriteAST().apply(document);
int bodyStart = trackedDeclaration.getStartPosition() + dummyClassContent.indexOf('{');
int bodyEnd = trackedDeclaration.getStartPosition() + trackedDeclaration.getLength();
return document.get(bodyStart, bodyEnd - bodyStart);
} catch (MalformedTreeException exception) {
JavaPlugin.log(exception);
} catch (BadLocationException exception) {
JavaPlugin.log(exception);
}
return null;
} finally {
if (workingCopy != null)
workingCopy.discardWorkingCopy();
}
}
use of org.eclipse.jdt.core.dom.rewrite.ListRewrite 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.ListRewrite 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.ListRewrite 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;
}
Aggregations