1 package no.uio.ifi.refaktor.utils;
4 import org.eclipse.jdt.core.ICompilationUnit;
5 import org.eclipse.jdt.core.dom.AST;
6 import org.eclipse.jdt.core.dom.ASTNode;
7 import org.eclipse.jdt.core.dom.ASTParser;
8 import org.eclipse.jdt.core.dom.CompilationUnit;
9 import org.eclipse.jdt.core.dom.NodeFinder;
10 import org.eclipse.jdt.internal.core.dom.NaiveASTFlattener;
11 import org.eclipse.jface.text.BadLocationException;
12 import org.eclipse.jface.text.IDocument;
13 import org.eclipse.jface.text.ITextSelection;
14 import org.eclipse.jface.text.TextSelection;
16 @SuppressWarnings("restriction")
17 public class ParseUtils {
19 public static CompilationUnit parse(ICompilationUnit unit) {
20 ASTParser parser = ParseUtils.createParser();
21 parser.setSource(unit);
22 return (CompilationUnit) parser.createAST(null);
25 public static CompilationUnit parse(IDocument document) {
26 return ParseUtils.parse(document.get());
29 public static CompilationUnit parse(String text) {
30 return ParseUtils.parse(text.toCharArray());
33 public static CompilationUnit parse(char[] chars) {
34 ASTParser parser = ParseUtils.createParser();
35 parser.setSource(chars);
36 return (CompilationUnit) parser.createAST(null);
39 public static ASTParser createParser() {
40 ASTParser parser = ASTParser.newParser(AST.JLS4);
41 parser.setKind(ASTParser.K_COMPILATION_UNIT);
42 parser.setResolveBindings(true);
46 public static TextSelection stripTextSelection(IDocument document, TextSelection textSelection) {
49 text = document.get(textSelection.getOffset(), textSelection.getLength());
50 } catch (BadLocationException e) {
51 throw new RuntimeException(e);
55 while (Character.isWhitespace(text.charAt(lstrip)))
59 int rIdx = text.length() - 1;
60 while (Character.isWhitespace(text.charAt(rIdx--)))
63 int newOffset = textSelection.getOffset() + lstrip;
64 int newLength = textSelection.getLength() - (lstrip + rstrip);
66 return new TextSelection(document, newOffset, newLength);
69 public static String getNodeDebugText(ASTNode node) {
70 NaiveASTFlattener printer = new NaiveASTFlattener();
72 return printer.getResult();
75 public static String getNodeText(ASTNode node, IDocument document) {
77 return document.get(node.getStartPosition(), node.getLength());
78 } catch (BadLocationException e) {
79 throw new RuntimeException(e);
83 public static NodeFinder getNodeFinder(IDocument document, ITextSelection selection) {
84 CompilationUnit cu = parse(document);
85 return new NodeFinder(cu.getRoot(), selection.getOffset(), selection.getLength());