1 10 11 package com.sun.source.util; 12 13 import com.sun.source.tree.*; 14 import java.util.Iterator ; 15 16 23 public class TreePath implements Iterable <Tree> { 24 28 public static TreePath getPath(CompilationUnitTree unit, Tree target) { 29 return getPath(new TreePath(unit), target); 30 } 31 32 36 public static TreePath getPath(TreePath path, Tree target) { 37 path.getClass(); 38 target.getClass(); 39 40 class Result extends Error { 41 static final long serialVersionUID = -5942088234594905625L; 42 TreePath path; 43 Result(TreePath path) { 44 this.path = path; 45 } 46 } 47 class PathFinder extends TreePathScanner<TreePath,Tree> { 48 public TreePath scan(Tree tree, Tree target) { 49 if (tree == target) 50 throw new Result(new TreePath(getCurrentPath(), target)); 51 return super.scan(tree, target); 52 } 53 } 54 55 try { 56 new PathFinder().scan(path, target); 57 } catch (Result result) { 58 return result.path; 59 } 60 return null; 61 } 62 63 66 public TreePath(CompilationUnitTree t) { 67 this(null, t); 68 } 69 70 73 public TreePath(TreePath p, Tree t) { 74 if (t.getKind() == Tree.Kind.COMPILATION_UNIT) { 75 compilationUnit = (CompilationUnitTree) t; 76 parent = null; 77 } 78 else { 79 compilationUnit = p.compilationUnit; 80 parent = p; 81 } 82 leaf = t; 83 } 84 87 public CompilationUnitTree getCompilationUnit() { 88 return compilationUnit; 89 } 90 91 94 public Tree getLeaf() { 95 return leaf; 96 } 97 98 101 public TreePath getParentPath() { 102 return parent; 103 } 104 105 public Iterator <Tree> iterator() { 106 return new Iterator <Tree>() { 107 public boolean hasNext() { 108 return curr.parent != null; 109 } 110 111 public Tree next() { 112 curr = curr.parent; 113 return curr.leaf; 114 } 115 116 public void remove() { 117 throw new UnsupportedOperationException (); 118 } 119 120 private TreePath curr; 121 }; 122 } 123 124 private CompilationUnitTree compilationUnit; 125 private Tree leaf; 126 private TreePath parent; 127 } 128 | Popular Tags |