PageRenderTime 73ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/jEdit/tags/jedit-4-2-pre4/org/gjt/sp/jedit/search/BoyerMooreSearchMatcher.java

#
Java | 316 lines | 149 code | 41 blank | 126 comment | 29 complexity | 00012e72e34d826054478fe0f8d7a139 MD5 | raw file
Possible License(s): BSD-3-Clause, AGPL-1.0, Apache-2.0, LGPL-2.0, LGPL-3.0, GPL-2.0, CC-BY-SA-3.0, LGPL-2.1, GPL-3.0, MPL-2.0-no-copyleft-exception, IPL-1.0
  1. /*
  2. * BoyerMooreSearchMatcher.java - Literal pattern String matcher utilizing the
  3. * Boyer-Moore algorithm
  4. * :tabSize=8:indentSize=8:noTabs=false:
  5. * :folding=explicit:collapseFolds=1:
  6. *
  7. * Copyright (C) 1999, 2000 mike dillon
  8. * Portions copyright (C) 2001 Tom Locke
  9. * Portions copyright (C) 2001, 2002 Slava Pestov
  10. *
  11. * This program is free software; you can redistribute it and/or
  12. * modify it under the terms of the GNU General Public License
  13. * as published by the Free Software Foundation; either version 2
  14. * of the License, or any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU General Public License
  22. * along with this program; if not, write to the Free Software
  23. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  24. */
  25. package org.gjt.sp.jedit.search;
  26. //{{{ Imports
  27. import bsh.BshMethod;
  28. import bsh.NameSpace;
  29. import gnu.regexp.CharIndexed;
  30. import org.gjt.sp.jedit.BeanShell;
  31. //}}}
  32. /**
  33. * Implements literal search using the Boyer-Moore algorithm.
  34. */
  35. public class BoyerMooreSearchMatcher extends SearchMatcher
  36. {
  37. //{{{ BoyerMooreSearchMatcher constructor
  38. /**
  39. * Creates a new string literal matcher.
  40. */
  41. public BoyerMooreSearchMatcher(String pattern, boolean ignoreCase)
  42. {
  43. this.pattern = pattern.toCharArray();
  44. if(ignoreCase)
  45. {
  46. for(int i = 0; i < this.pattern.length; i++)
  47. {
  48. this.pattern[i] = Character.toUpperCase(
  49. this.pattern[i]);
  50. }
  51. }
  52. this.replace = replace;
  53. this.ignoreCase = ignoreCase;
  54. pattern_end = this.pattern.length - 1;
  55. } //}}}
  56. //{{{ nextMatch() method
  57. /**
  58. * Returns the offset of the first match of the specified text
  59. * within this matcher.
  60. * @param text The text to search in
  61. * @param start True if the start of the segment is the beginning of the
  62. * buffer
  63. * @param end True if the end of the segment is the end of the buffer
  64. * @param firstTime If false and the search string matched at the start
  65. * offset with length zero, automatically find next match
  66. * @param reverse If true, searching will be performed in a backward
  67. * direction.
  68. * @return an array where the first element is the start offset
  69. * of the match, and the second element is the end offset of
  70. * the match
  71. * @since jEdit 4.2pre4
  72. */
  73. public SearchMatcher.Match nextMatch(CharIndexed text,
  74. boolean start, boolean end, boolean firstTime,
  75. boolean reverse)
  76. {
  77. int pos = match(text,reverse);
  78. if (pos == -1)
  79. {
  80. return null;
  81. }
  82. else
  83. {
  84. returnValue.start = pos;
  85. returnValue.end = pos + pattern.length;
  86. return returnValue;
  87. }
  88. } //}}}
  89. //{{{ match() method
  90. /*
  91. * a good introduction to the Boyer-Moore fast string matching
  92. * algorithm may be found on Moore's website at:
  93. *
  94. * http://www.cs.utexas.edu/users/moore/best-ideas/string-searching/
  95. *
  96. */
  97. public int match(CharIndexed text, boolean reverse)
  98. {
  99. //{{{
  100. // lazily create skip and suffix arrays for either the
  101. // search pattern, or the reversed search pattern
  102. int[] skip, suffix;
  103. if(reverse)
  104. {
  105. if(back_skip == null)
  106. {
  107. back_skip = generateSkipArray(true);
  108. back_suffix = generateSuffixArray(true);
  109. }
  110. skip = back_skip;
  111. suffix = back_suffix;
  112. }
  113. else
  114. {
  115. if(fwd_skip == null)
  116. {
  117. fwd_skip = generateSkipArray(false);
  118. fwd_suffix = generateSuffixArray(false);
  119. }
  120. skip = fwd_skip;
  121. suffix = fwd_suffix;
  122. } //}}}
  123. // position variable for pattern test position
  124. int pos;
  125. // position variable for pattern start
  126. int anchor = 0;
  127. // last possible start position of a match with this pattern;
  128. // this is negative if the pattern is longer than the text
  129. // causing the search loop below to immediately fail
  130. //int last_anchor = reverseSearch
  131. // ? offset + pattern.length - 1
  132. // : length - pattern.length;
  133. char ch = 0;
  134. int bad_char;
  135. int good_suffix;
  136. // the search works by starting the anchor (first character
  137. // of the pattern) at the initial offset. as long as the
  138. // anchor is far enough from the enough of the text for the
  139. // pattern to match, and until the pattern matches, we
  140. // compare the pattern to the text from the last character
  141. // to the first character in reverse order. where a character
  142. // in the pattern mismatches, we use the two heuristics
  143. // based on the mismatch character and its position in the
  144. // pattern to determine the furthest we can move the anchor
  145. // without missing any potential pattern matches.
  146. SEARCH:
  147. while (text.isValid())
  148. {
  149. for (pos = pattern_end; pos >= 0; --pos)
  150. {
  151. ch = text.charAt(pos);
  152. if(ignoreCase)
  153. ch = Character.toUpperCase(ch);
  154. // pattern test
  155. if ((reverse ? ch != pattern[pattern_end - pos]
  156. : ch != pattern[pos]))
  157. {
  158. // character mismatch, determine how many characters to skip
  159. // heuristic #1
  160. bad_char = pos - skip[getSkipIndex(ch)];
  161. // heuristic #2
  162. good_suffix = suffix[pos];
  163. // skip the greater of the two distances provided by the
  164. // heuristics
  165. int skip_index = (bad_char > good_suffix) ? bad_char : good_suffix;
  166. anchor += skip_index;
  167. text.move(skip_index);
  168. // go back to the while loop
  169. continue SEARCH;
  170. }
  171. }
  172. // MATCH: return the position of its first character
  173. return anchor;
  174. }
  175. // MISMATCH: return -1 as defined by API
  176. return -1;
  177. } //}}}
  178. //{{{ Private members
  179. private char[] pattern;
  180. private int pattern_end;
  181. private String replace;
  182. private boolean ignoreCase;
  183. // Boyer-Moore member fields
  184. private int[] fwd_skip;
  185. private int[] fwd_suffix;
  186. private int[] back_skip;
  187. private int[] back_suffix;
  188. //}}}
  189. // Boyer-Moore helper methods
  190. //{{{ generateSkipArray() method
  191. /*
  192. * the 'skip' array is used to determine for each index in the
  193. * hashed alphabet how many characters can be skipped if
  194. * a mismatch occurs on a characater hashing to that index.
  195. */
  196. private int[] generateSkipArray(boolean reverse)
  197. {
  198. // initialize the skip array to all zeros
  199. int[] skip = new int[256];
  200. // leave the table cleanly-initialized for an empty pattern
  201. if (pattern.length == 0)
  202. return skip;
  203. int pos = 0;
  204. do
  205. {
  206. skip[getSkipIndex(pattern[reverse ? pattern_end - pos : pos])] = pos;
  207. }
  208. while (++pos < pattern.length);
  209. return skip;
  210. } //}}}
  211. //{{{ getSkipIndex() method
  212. /*
  213. * to avoid our skip table having a length of 2 ^ 16, we hash each
  214. * character of the input into a character in the alphabet [\x00-\xFF]
  215. * using the lower 8 bits of the character's value (resulting in
  216. * a more reasonable skip table of length 2 ^ 8).
  217. *
  218. * the result of this is that more than one character can hash to the
  219. * same index, but since the skip table encodes the position of
  220. * occurence of the character furthest into the string with a particular
  221. * index (whether or not it is the only character with that index), an
  222. * index collision only means that that this heuristic will give a
  223. * sub-optimal skip (i.e. a complete skip table could use the differences
  224. * between colliding characters to maximal effect, at the expense of
  225. * building a table that is over 2 orders of magnitude larger and very
  226. * sparse).
  227. */
  228. private static final int getSkipIndex(char ch)
  229. {
  230. return ((int) ch) & 0x000000FF;
  231. } //}}}
  232. //{{{ generateSuffixArray() method
  233. /*
  234. * XXX: hairy code that is basically just a functional(?) port of some
  235. * other code i barely understood
  236. */
  237. private int[] generateSuffixArray(boolean reverse)
  238. {
  239. int m = pattern.length;
  240. int j = m + 1;
  241. int[] suffix = new int[j];
  242. int[] tmp = new int[j];
  243. tmp[m] = j;
  244. for (int i = m; i > 0; --i)
  245. {
  246. while (j <= m && pattern[reverse ? pattern_end - i + 1 : i - 1]
  247. != pattern[reverse ? pattern_end - j + 1 : j - 1])
  248. {
  249. if (suffix[j] == 0)
  250. {
  251. suffix[j] = j - i;
  252. }
  253. j = tmp[j];
  254. }
  255. tmp[i - 1] = --j;
  256. }
  257. int k = tmp[0];
  258. for (j = 0; j <= m; j++)
  259. {
  260. // the code above builds a 1-indexed suffix array,
  261. // but we shift it to be 0-indexed, ignoring the
  262. // original 0-th element
  263. if (j > 0)
  264. {
  265. suffix[j - 1] = (suffix[j] == 0) ? k : suffix[j];
  266. }
  267. if (j == k)
  268. {
  269. k = tmp[k];
  270. }
  271. }
  272. return suffix;
  273. } //}}}
  274. //}}}
  275. }