use of org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition in project flux by eclipse.
the class ModifierRewrite method internalSetModifiers.
/**
* Sets the given modifiers and removes all other modifiers that match the consideredFlags mask.
* Does not touch other flags and leaves annotations in place.
*
* @param modifiers the modifiers to set
* @param consideredFlags mask of modifiers to consider
* @param editGroup the edit group in which to collect the corresponding text edits, or
* <code>null</code> if ungrouped
* @return a tracked position that contains the changed modifiers
*/
private PositionInformation internalSetModifiers(int modifiers, int consideredFlags, TextEditGroup editGroup) {
int newModifiers = modifiers & consideredFlags;
ITrackedNodePosition trackedFallback = null;
List<ITrackedNodePosition> trackedNodes = new ArrayList<ITrackedNodePosition>();
// remove modifiers
List<IExtendedModifier> originalList = fModifierRewrite.getOriginalList();
for (int i = 0; i < originalList.size(); i++) {
ASTNode curr = (ASTNode) originalList.get(i);
if (curr instanceof Modifier) {
int flag = ((Modifier) curr).getKeyword().toFlagValue();
if ((consideredFlags & flag) != 0) {
if ((newModifiers & flag) == 0) {
fModifierRewrite.remove(curr, editGroup);
if (trackedFallback == null)
trackedFallback = fModifierRewrite.getASTRewrite().track(curr);
}
newModifiers &= ~flag;
}
}
}
// find last annotation
IExtendedModifier lastAnnotation = null;
List<IExtendedModifier> extendedList = fModifierRewrite.getRewrittenList();
for (int i = 0; i < extendedList.size(); i++) {
IExtendedModifier curr = extendedList.get(i);
if (curr.isAnnotation())
lastAnnotation = curr;
}
// add modifiers
List<Modifier> newNodes = ASTNodeFactory.newModifiers(fAst, newModifiers);
for (int i = 0; i < newNodes.size(); i++) {
Modifier curr = newNodes.get(i);
if ((curr.getKeyword().toFlagValue() & VISIBILITY_MODIFIERS) != 0) {
if (lastAnnotation != null)
fModifierRewrite.insertAfter(curr, (ASTNode) lastAnnotation, editGroup);
else
fModifierRewrite.insertFirst(curr, editGroup);
} else {
fModifierRewrite.insertLast(curr, editGroup);
}
trackedNodes.add(fModifierRewrite.getASTRewrite().track(curr));
}
if (trackedNodes.isEmpty()) {
if (trackedFallback == null) {
// out of tricks...
trackedFallback = fModifierRewrite.getASTRewrite().track(fModifierRewrite.getParent());
}
return new LinkedProposalPositionGroup.StartPositionInformation(trackedFallback);
} else {
return new LinkedProposalPositionGroup.TrackedNodesPosition(trackedNodes);
}
}
use of org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition 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.ITrackedNodePosition 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.ITrackedNodePosition in project che by eclipse.
the class ModifierRewrite method internalSetModifiers.
/**
* Sets the given modifiers and removes all other modifiers that match the consideredFlags mask.
* Does not touch other flags and leaves annotations in place.
*
* @param modifiers the modifiers to set
* @param consideredFlags mask of modifiers to consider
* @param editGroup the edit group in which to collect the corresponding text edits, or
* <code>null</code> if ungrouped
* @return a tracked position that contains the changed modifiers
*/
private PositionInformation internalSetModifiers(int modifiers, int consideredFlags, TextEditGroup editGroup) {
int newModifiers = modifiers & consideredFlags;
ITrackedNodePosition trackedFallback = null;
List<ITrackedNodePosition> trackedNodes = new ArrayList<ITrackedNodePosition>();
// remove modifiers
List<IExtendedModifier> originalList = fModifierRewrite.getOriginalList();
for (int i = 0; i < originalList.size(); i++) {
ASTNode curr = (ASTNode) originalList.get(i);
if (curr instanceof Modifier) {
int flag = ((Modifier) curr).getKeyword().toFlagValue();
if ((consideredFlags & flag) != 0) {
if ((newModifiers & flag) == 0) {
fModifierRewrite.remove(curr, editGroup);
if (trackedFallback == null)
trackedFallback = fModifierRewrite.getASTRewrite().track(curr);
}
newModifiers &= ~flag;
}
}
}
// find last annotation
IExtendedModifier lastAnnotation = null;
List<IExtendedModifier> extendedList = fModifierRewrite.getRewrittenList();
for (int i = 0; i < extendedList.size(); i++) {
IExtendedModifier curr = extendedList.get(i);
if (curr.isAnnotation())
lastAnnotation = curr;
}
// add modifiers
List<Modifier> newNodes = ASTNodeFactory.newModifiers(fAst, newModifiers);
for (int i = 0; i < newNodes.size(); i++) {
Modifier curr = newNodes.get(i);
if ((curr.getKeyword().toFlagValue() & VISIBILITY_MODIFIERS) != 0) {
if (lastAnnotation != null)
fModifierRewrite.insertAfter(curr, (ASTNode) lastAnnotation, editGroup);
else
fModifierRewrite.insertFirst(curr, editGroup);
} else {
fModifierRewrite.insertLast(curr, editGroup);
}
trackedNodes.add(fModifierRewrite.getASTRewrite().track(curr));
}
if (trackedNodes.isEmpty()) {
if (trackedFallback == null) {
// out of tricks...
trackedFallback = fModifierRewrite.getASTRewrite().track(fModifierRewrite.getParent());
}
return new LinkedProposalPositionGroup.StartPositionInformation(trackedFallback);
} else {
return new LinkedProposalPositionGroup.TrackedNodesPosition(trackedNodes);
}
}
Aggregations