1 11 package org.eclipse.jdt.internal.corext.dom; 12 13 import org.eclipse.jdt.core.ICompilationUnit; 14 import org.eclipse.jdt.core.ISourceRange; 15 import org.eclipse.jdt.core.JavaModelException; 16 import org.eclipse.jdt.core.ToolFactory; 17 import org.eclipse.jdt.core.compiler.IScanner; 18 import org.eclipse.jdt.core.compiler.ITerminalSymbols; 19 import org.eclipse.jdt.core.compiler.InvalidInputException; 20 import org.eclipse.jdt.core.dom.ASTNode; 21 26 public class NodeFinder extends GenericVisitor { 27 28 48 public static ASTNode perform(ASTNode root, int start, int length) { 49 NodeFinder finder= new NodeFinder(start, length); 50 root.accept(finder); 51 ASTNode result= finder.getCoveredNode(); 52 if (result == null || result.getStartPosition() != start || result.getLength() != length) { 53 return finder.getCoveringNode(); 54 } 55 return result; 56 } 57 58 public static ASTNode perform(ASTNode root, ISourceRange range) { 59 return perform(root, range.getOffset(), range.getLength()); 60 } 61 62 87 public static ASTNode perform(ASTNode root, int start, int length, ICompilationUnit source) throws JavaModelException { 88 NodeFinder finder= new NodeFinder(start, length); 89 root.accept(finder); 90 ASTNode result= finder.getCoveredNode(); 91 if (result == null) 92 return null; 93 Selection selection= Selection.createFromStartLength(start, length); 94 if (selection.covers(result)) { 95 IScanner scanner= ToolFactory.createScanner(false, false, false, false); 96 scanner.setSource(source.getBuffer().getText(start, length).toCharArray()); 97 try { 98 int token= scanner.getNextToken(); 99 if (token != ITerminalSymbols.TokenNameEOF) { 100 int tStart= scanner.getCurrentTokenStartPosition(); 101 if (tStart == result.getStartPosition() - start) { 102 scanner.resetTo(tStart + result.getLength(), length - 1); 103 token= scanner.getNextToken(); 104 if (token == ITerminalSymbols.TokenNameEOF) 105 return result; 106 } 107 } 108 } catch (InvalidInputException e) { 109 } 110 } 111 return finder.getCoveringNode(); 112 } 113 114 private int fStart; 115 private int fEnd; 116 117 private ASTNode fCoveringNode; 118 private ASTNode fCoveredNode; 119 120 public NodeFinder(int offset, int length) { 121 super(true); fStart= offset; 123 fEnd= offset + length; 124 } 125 126 protected boolean visitNode(ASTNode node) { 127 int nodeStart= node.getStartPosition(); 128 int nodeEnd= nodeStart + node.getLength(); 129 if (nodeEnd < fStart || fEnd < nodeStart) { 130 return false; 131 } 132 if (nodeStart <= fStart && fEnd <= nodeEnd) { 133 fCoveringNode= node; 134 } 135 if (fStart <= nodeStart && nodeEnd <= fEnd) { 136 if (fCoveringNode == node) { fCoveredNode= node; 138 return true; } else if (fCoveredNode == null) { fCoveredNode= node; 141 } 142 return false; 143 } 144 return true; 145 } 146 147 152 public ASTNode getCoveredNode() { 153 return fCoveredNode; 154 } 155 156 161 public ASTNode getCoveringNode() { 162 return fCoveringNode; 163 } 164 165 } 166 | Popular Tags |