use of org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser in project che by eclipse.
the class ExtractConstantRefactoring method checkSource.
private void checkSource(SubProgressMonitor monitor, RefactoringStatus result) throws CoreException {
String newCuSource = fChange.getPreviewContent(new NullProgressMonitor());
CompilationUnit newCUNode = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(newCuSource, fCu, true, true, monitor);
IProblem[] newProblems = RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fCuRewrite.getRoot());
for (int i = 0; i < newProblems.length; i++) {
IProblem problem = newProblems[i];
if (problem.isError())
result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, SourceRangeFactory.create(problem))));
}
}
use of org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser in project che by eclipse.
the class TypeContextChecker method resolveSuperInterfaces.
public static ITypeBinding[] resolveSuperInterfaces(String[] interfaces, IType typeHandle, StubTypeContext superInterfaceContext) {
ITypeBinding[] result = new ITypeBinding[interfaces.length];
int[] interfaceOffsets = new int[interfaces.length];
StringBuffer cuString = new StringBuffer();
cuString.append(superInterfaceContext.getBeforeString());
int last = interfaces.length - 1;
for (int i = 0; i <= last; i++) {
interfaceOffsets[i] = cuString.length();
cuString.append(interfaces[i]);
if (i != last)
//$NON-NLS-1$
cuString.append(", ");
}
cuString.append(superInterfaceContext.getAfterString());
try {
ICompilationUnit wc = typeHandle.getCompilationUnit().getWorkingCopy(new WorkingCopyOwner() {
}, new NullProgressMonitor());
try {
wc.getBuffer().setContents(cuString.toString());
CompilationUnit compilationUnit = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(wc, true);
for (int i = 0; i <= last; i++) {
ASTNode type = NodeFinder.perform(compilationUnit, interfaceOffsets[i], interfaces[i].length());
if (type instanceof Type) {
result[i] = handleBug84585(((Type) type).resolveBinding());
} else if (type instanceof Name) {
ASTNode parent = type.getParent();
if (parent instanceof Type) {
result[i] = handleBug84585(((Type) parent).resolveBinding());
} else {
throw new IllegalStateException();
}
} else {
throw new IllegalStateException();
}
}
} finally {
wc.discardWorkingCopy();
}
} catch (JavaModelException e) {
// won't happen
}
return result;
}
use of org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser in project che by eclipse.
the class ReplaceInvocationsRefactoring method resolveSourceProvider.
private SourceProvider resolveSourceProvider(IMethodBinding methodBinding, RefactoringStatus status) throws JavaModelException {
final IMethod method = (IMethod) methodBinding.getJavaElement();
ITypeRoot typeRoot;
IDocument source;
CompilationUnit methodDeclarationAstRoot;
ICompilationUnit methodCu = (method).getCompilationUnit();
if (methodCu != null) {
typeRoot = methodCu;
ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
parser.setSource(methodCu);
parser.setFocalPosition(method.getNameRange().getOffset());
CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
MethodDeclaration methodDecl = (MethodDeclaration) NodeFinder.perform(compilationUnit, method.getNameRange()).getParent();
AST ast = compilationUnit.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
Block newBody = ast.newBlock();
newBody.statements().add(rewrite.createStringPlaceholder(fBody, ASTNode.EMPTY_STATEMENT));
rewrite.replace(methodDecl.getBody(), newBody, null);
List<SingleVariableDeclaration> parameters = methodDecl.parameters();
for (int i = 0; i < parameters.size(); i++) {
SingleVariableDeclaration parameter = parameters.get(i);
rewrite.set(parameter.getName(), SimpleName.IDENTIFIER_PROPERTY, fParameterNames[i], null);
}
TextEdit textEdit = rewrite.rewriteAST();
Document document = new Document(methodCu.getBuffer().getContents());
try {
textEdit.apply(document);
} catch (MalformedTreeException e) {
JavaPlugin.log(e);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
source = document;
methodDeclarationAstRoot = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(source.get(), methodCu, true, true, null);
} else {
IClassFile classFile = method.getClassFile();
//TODO: use source if available?
StubCreator stubCreator = new StubCreator(true) {
@Override
protected void appendMethodBody(IMethod currentMethod) throws JavaModelException {
if (currentMethod.equals(method)) {
fBuffer.append(fBody);
} else {
super.appendMethodBody(currentMethod);
}
}
/*
* @see org.eclipse.jdt.internal.corext.refactoring.binary.StubCreator#appendMethodParameterName(org.eclipse.jdt.core.IMethod, int)
*/
@Override
protected void appendMethodParameterName(IMethod currentMethod, int index) {
if (currentMethod.equals(method)) {
fBuffer.append(fParameterNames[index]);
} else {
super.appendMethodParameterName(currentMethod, index);
}
}
};
String stub = stubCreator.createStub(classFile.getType(), null);
source = new Document(stub);
methodDeclarationAstRoot = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(stub, classFile, true, true, null);
typeRoot = classFile;
}
ASTNode node = methodDeclarationAstRoot.findDeclaringNode(methodBinding.getKey());
if (node instanceof MethodDeclaration) {
return new SourceProvider(typeRoot, source, (MethodDeclaration) node);
} else {
status.addFatalError(RefactoringCoreMessages.ReplaceInvocationsRefactoring_cannot_find_method_declaration);
return null;
}
}
use of org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser in project che by eclipse.
the class SelfEncapsulateFieldRefactoring method checkFinalConditions.
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
pm.beginTask(NO_NAME, 12);
pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_checking_preconditions);
RefactoringStatus result = new RefactoringStatus();
fRewriter = ASTRewrite.create(fRoot.getAST());
fChangeManager.clear();
boolean usingLocalGetter = isUsingLocalGetter();
boolean usingLocalSetter = isUsingLocalSetter();
result.merge(checkMethodNames(usingLocalGetter, usingLocalSetter));
pm.worked(1);
if (result.hasFatalError())
return result;
pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_searching_for_cunits);
final SubProgressMonitor subPm = new SubProgressMonitor(pm, 5);
ICompilationUnit[] affectedCUs = RefactoringSearchEngine.findAffectedCompilationUnits(SearchPattern.createPattern(fField, IJavaSearchConstants.REFERENCES), RefactoringScopeFactory.create(fField, fConsiderVisibility), subPm, result, true);
checkInHierarchy(result, usingLocalGetter, usingLocalSetter);
if (result.hasFatalError())
return result;
pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_analyzing);
IProgressMonitor sub = new SubProgressMonitor(pm, 5);
sub.beginTask(NO_NAME, affectedCUs.length);
IVariableBinding fieldIdentifier = fFieldDeclaration.resolveBinding();
ITypeBinding declaringClass = ((AbstractTypeDeclaration) ASTNodes.getParent(fFieldDeclaration, AbstractTypeDeclaration.class)).resolveBinding();
List<TextEditGroup> ownerDescriptions = new ArrayList<TextEditGroup>();
ICompilationUnit owner = fField.getCompilationUnit();
fImportRewrite = StubUtility.createImportRewrite(fRoot, true);
for (int i = 0; i < affectedCUs.length; i++) {
ICompilationUnit unit = affectedCUs[i];
sub.subTask(BasicElementLabels.getFileName(unit));
CompilationUnit root = null;
ASTRewrite rewriter = null;
ImportRewrite importRewrite;
List<TextEditGroup> descriptions;
if (owner.equals(unit)) {
root = fRoot;
rewriter = fRewriter;
importRewrite = fImportRewrite;
descriptions = ownerDescriptions;
} else {
root = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(unit, true);
rewriter = ASTRewrite.create(root.getAST());
descriptions = new ArrayList<TextEditGroup>();
importRewrite = StubUtility.createImportRewrite(root, true);
}
checkCompileErrors(result, root, unit);
AccessAnalyzer analyzer = new AccessAnalyzer(this, unit, fieldIdentifier, declaringClass, rewriter, importRewrite);
root.accept(analyzer);
result.merge(analyzer.getStatus());
if (!fSetterMustReturnValue)
fSetterMustReturnValue = analyzer.getSetterMustReturnValue();
if (result.hasFatalError()) {
fChangeManager.clear();
return result;
}
descriptions.addAll(analyzer.getGroupDescriptions());
if (!owner.equals(unit))
createEdits(unit, rewriter, descriptions, importRewrite);
sub.worked(1);
if (pm.isCanceled())
throw new OperationCanceledException();
}
ownerDescriptions.addAll(addGetterSetterChanges(fRoot, fRewriter, owner.findRecommendedLineSeparator(), usingLocalSetter, usingLocalGetter));
createEdits(owner, fRewriter, ownerDescriptions, fImportRewrite);
sub.done();
IFile[] filesToBeModified = ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits());
result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
if (result.hasFatalError())
return result;
ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1));
return result;
}
use of org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser in project eclipse.platform.runtime by eclipse.
the class RemoveUnusedMessages method checkFinalConditions.
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
if (monitor == null)
monitor = new NullProgressMonitor();
change = new CompositeChange("Accessor Class Changes");
RefactoringStatus result = new RefactoringStatus();
ICompilationUnit unit = JavaCore.createCompilationUnitFrom((IFile) accessorClass.getResource());
CompilationUnit root = new RefactoringASTParser(AST.JLS3).parse(unit, true, null);
ASTRewrite rewriter = ASTRewrite.create(root.getAST());
// Search for references
IField[] fields = accessorClass.getFields();
ArrayList toDelete = new ArrayList();
// 10 units of work for modifying the properties file and AST
monitor.beginTask("Searching for references.", fields.length + 10);
try {
for (IField field : fields) {
if (monitor.isCanceled())
throw new OperationCanceledException();
String fieldName = field.getElementName();
monitor.subTask("Searching for references to: " + fieldName);
int flags = field.getFlags();
// only want to look at the public static String fields
if (!(Flags.isPublic(flags) && Flags.isStatic(flags)))
continue;
// search for references
ICompilationUnit[] affectedUnits = RefactoringSearchEngine.findAffectedCompilationUnits(SearchPattern.createPattern(field, IJavaSearchConstants.REFERENCES), RefactoringScopeFactory.create(accessorClass), new SubProgressMonitor(monitor, 1), result);
// there are references so go to the next field
if (affectedUnits.length > 0)
continue;
System.out.println("Found unused field: " + fieldName);
toDelete.add(fieldName);
}
System.out.println("Analysis of " + fields.length + " messages found " + toDelete.size() + " unused messages");
// any work to do?
if (toDelete.isEmpty())
return result;
if (monitor.isCanceled())
throw new OperationCanceledException();
// remove the field and its corresponding entry in the messages.properties file
processAST(root, rewriter, toDelete);
monitor.worked(5);
processPropertiesFile(toDelete);
monitor.worked(5);
TextFileChange cuChange = new TextFileChange(unit.getElementName(), (IFile) unit.getResource());
try {
ITextFileBuffer buffer = RefactoringFileBuffers.acquire(unit);
IDocument document = buffer.getDocument();
cuChange.setEdit(rewriter.rewriteAST(document, null));
} finally {
RefactoringFileBuffers.release(unit);
}
change.add(cuChange);
} finally {
monitor.done();
}
// return the result
return result;
}
Aggregations