RegexMatcher.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /*
  2. * Copyright (c) 2020, Emanuel Sprung <emanuel.sprung@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "RegexMatcher.h"
  27. #include "RegexDebug.h"
  28. #include "RegexParser.h"
  29. #include <AK/String.h>
  30. #include <AK/StringBuilder.h>
  31. namespace regex {
  32. #ifdef REGEX_DEBUG
  33. static RegexDebug s_regex_dbg(stderr);
  34. #endif
  35. template<class Parser>
  36. Regex<Parser>::Regex(StringView pattern, typename ParserTraits<Parser>::OptionsType regex_options)
  37. {
  38. pattern_value = pattern.to_string();
  39. regex::Lexer lexer(pattern);
  40. Parser parser(lexer, regex_options);
  41. parser_result = parser.parse();
  42. if (parser_result.error == regex::Error::NoError) {
  43. matcher = make<Matcher<Parser>>(*this, regex_options);
  44. } else {
  45. fprintf(stderr, "%s\n", error_string().characters());
  46. }
  47. }
  48. template<class Parser>
  49. String Regex<Parser>::error_string(Optional<String> message) const
  50. {
  51. StringBuilder eb;
  52. eb.appendf("Error during parsing of regular expression:\n");
  53. eb.appendf(" %s\n ", pattern_value.characters());
  54. for (size_t i = 0; i < parser_result.error_token.position(); ++i)
  55. eb.append(" ");
  56. eb.appendf("^---- %s\n", message.value_or(get_error_string(parser_result.error)).characters());
  57. return eb.build();
  58. }
  59. template<typename Parser>
  60. RegexResult Matcher<Parser>::match(const RegexStringView& view, Optional<typename ParserTraits<Parser>::OptionsType> regex_options) const
  61. {
  62. AllOptions options = m_regex_options | regex_options.value_or({}).value();
  63. if (options.has_flag_set(AllFlags::Multiline))
  64. return match(view.lines(), regex_options); // FIXME: how do we know, which line ending a line has (1char or 2char)? This is needed to get the correct match offsets from start of string...
  65. Vector<RegexStringView> views;
  66. views.append(view);
  67. return match(views, regex_options);
  68. }
  69. template<typename Parser>
  70. RegexResult Matcher<Parser>::match(const Vector<RegexStringView> views, Optional<typename ParserTraits<Parser>::OptionsType> regex_options) const
  71. {
  72. size_t match_count { 0 };
  73. MatchInput input;
  74. MatchState state;
  75. MatchOutput output;
  76. input.regex_options = m_regex_options | regex_options.value_or({}).value();
  77. output.operations = 0;
  78. if (c_match_preallocation_count) {
  79. output.matches.ensure_capacity(c_match_preallocation_count);
  80. output.capture_group_matches.ensure_capacity(c_match_preallocation_count);
  81. output.named_capture_group_matches.ensure_capacity(c_match_preallocation_count);
  82. auto& capture_groups_count = m_pattern.parser_result.capture_groups_count;
  83. auto& named_capture_groups_count = m_pattern.parser_result.named_capture_groups_count;
  84. for (size_t j = 0; j < c_match_preallocation_count; ++j) {
  85. output.matches.empend();
  86. output.capture_group_matches.unchecked_append({});
  87. output.capture_group_matches.at(j).ensure_capacity(capture_groups_count);
  88. for (size_t k = 0; k < capture_groups_count; ++k)
  89. output.capture_group_matches.at(j).unchecked_append({});
  90. output.named_capture_group_matches.unchecked_append({});
  91. output.named_capture_group_matches.at(j).ensure_capacity(named_capture_groups_count);
  92. }
  93. }
  94. auto append_match = [](auto& input, auto& state, auto& output, auto& start_position) {
  95. if (output.matches.size() == input.match_index)
  96. output.matches.empend();
  97. ASSERT(start_position + state.string_position - start_position <= input.view.length());
  98. if (input.regex_options & AllFlags::StringCopyMatches) {
  99. output.matches.at(input.match_index) = { input.view.substring_view(start_position, state.string_position - start_position).to_string(), input.line, start_position, input.global_offset + start_position };
  100. } else { // let the view point to the original string ...
  101. output.matches.at(input.match_index) = { input.view.substring_view(start_position, state.string_position - start_position), input.line, start_position, input.global_offset + start_position };
  102. }
  103. };
  104. #ifdef REGEX_DEBUG
  105. s_regex_dbg.print_header();
  106. #endif
  107. bool continue_search = (input.regex_options & AllFlags::Global) || (input.regex_options & AllFlags::Multiline);
  108. for (auto& view : views) {
  109. input.view = view;
  110. #ifdef REGEX_DEBUG
  111. dbg() << "[match] Starting match with view (" << view.length() << "): _" << view.to_string() << "_";
  112. #endif
  113. auto view_length = view.length();
  114. for (size_t view_index = 0; view_index < view_length; ++view_index) {
  115. auto& match_length_minimum = m_pattern.parser_result.match_length_minimum;
  116. // FIXME: More performant would be to know the remaining minimum string
  117. // length needed to match from the current position onwards within
  118. // the vm. Add new OpCode for MinMatchLengthFromSp with the value of
  119. // the remaining string length from the current path. The value though
  120. // has to be filled in reverse. That implies a second run over bytecode
  121. // after generation has finished.
  122. if (match_length_minimum && match_length_minimum > view_length - view_index)
  123. break;
  124. input.column = match_count;
  125. input.match_index = match_count;
  126. state.string_position = view_index;
  127. state.instruction_position = 0;
  128. auto success = execute(input, state, output, 0);
  129. if (!success.has_value())
  130. return { false, 0, {}, {}, {}, output.operations };
  131. if (success.value()) {
  132. if ((input.regex_options & AllFlags::MatchNotEndOfLine) && state.string_position == input.view.length()) {
  133. if (!continue_search)
  134. break;
  135. continue;
  136. }
  137. if ((input.regex_options & AllFlags::MatchNotBeginOfLine) && view_index == 0) {
  138. if (!continue_search)
  139. break;
  140. continue;
  141. }
  142. #ifdef REGEX_DEBUG
  143. dbg() << "state.string_position: " << state.string_position << " view_index: " << view_index;
  144. dbg() << "[match] Found a match (length = " << state.string_position - view_index << "): " << input.view.substring_view(view_index, state.string_position - view_index).to_string();
  145. #endif
  146. ++match_count;
  147. if (continue_search) {
  148. append_match(input, state, output, view_index);
  149. bool has_zero_length = state.string_position == view_index;
  150. view_index = state.string_position - (has_zero_length ? 0 : 1);
  151. continue;
  152. } else if (!continue_search && state.string_position < view_length)
  153. return { false, 0, {}, {}, {}, output.operations };
  154. append_match(input, state, output, view_index);
  155. break;
  156. }
  157. if (!continue_search)
  158. break;
  159. }
  160. ++input.line;
  161. input.global_offset += view.length() + 1; // +1 includes the line break character
  162. }
  163. MatchOutput output_copy;
  164. if (match_count) {
  165. auto capture_groups_count = min(output.capture_group_matches.size(), output.matches.size());
  166. for (size_t i = 0; i < capture_groups_count; ++i) {
  167. if (input.regex_options & AllFlags::SkipTrimEmptyMatches) {
  168. output_copy.capture_group_matches.append(output.capture_group_matches.at(i));
  169. } else {
  170. Vector<Match> capture_group_matches;
  171. for (size_t j = 0; j < output.capture_group_matches.at(i).size(); ++j) {
  172. if (!output.capture_group_matches.at(i).at(j).view.is_null())
  173. capture_group_matches.append(output.capture_group_matches.at(i).at(j));
  174. }
  175. output_copy.capture_group_matches.append(capture_group_matches);
  176. }
  177. }
  178. auto named_capture_groups_count = min(output.named_capture_group_matches.size(), output.matches.size());
  179. for (size_t i = 0; i < named_capture_groups_count; ++i) {
  180. if (output.matches.at(i).view.length())
  181. output_copy.named_capture_group_matches.append(output.named_capture_group_matches.at(i));
  182. }
  183. for (size_t i = 0; i < match_count; ++i)
  184. output_copy.matches.append(output.matches.at(i));
  185. } else {
  186. output_copy.capture_group_matches.clear_with_capacity();
  187. output_copy.named_capture_group_matches.clear_with_capacity();
  188. }
  189. return {
  190. match_count ? true : false,
  191. match_count,
  192. move(output_copy.matches),
  193. move(output_copy.capture_group_matches),
  194. move(output_copy.named_capture_group_matches),
  195. output.operations,
  196. m_pattern.parser_result.capture_groups_count,
  197. m_pattern.parser_result.named_capture_groups_count,
  198. };
  199. }
  200. template<class Parser>
  201. Optional<bool> Matcher<Parser>::execute(const MatchInput& input, MatchState& state, MatchOutput& output, size_t recursion_level) const
  202. {
  203. if (recursion_level > c_max_recursion)
  204. return false;
  205. Vector<MatchState> fork_low_prio_states;
  206. MatchState fork_high_prio_state;
  207. Optional<bool> success;
  208. auto& bytecode = m_pattern.parser_result.bytecode;
  209. for (;;) {
  210. ++output.operations;
  211. auto* opcode = bytecode.get_opcode(state);
  212. if (!opcode) {
  213. dbg() << "Wrong opcode... failed!";
  214. return {};
  215. }
  216. #ifdef REGEX_DEBUG
  217. s_regex_dbg.print_opcode("VM", *opcode, state, recursion_level, false);
  218. #endif
  219. auto result = opcode->execute(input, state, output);
  220. #ifdef REGEX_DEBUG
  221. s_regex_dbg.print_result(*opcode, bytecode, input, state, result);
  222. #endif
  223. state.instruction_position += opcode->size();
  224. switch (result) {
  225. case ExecutionResult::Fork_PrioLow:
  226. fork_low_prio_states.prepend(state);
  227. continue;
  228. case ExecutionResult::Fork_PrioHigh:
  229. fork_high_prio_state = state;
  230. fork_high_prio_state.instruction_position = fork_high_prio_state.fork_at_position;
  231. success = execute(input, fork_high_prio_state, output, ++recursion_level);
  232. if (!success.has_value())
  233. return {};
  234. if (success.value()) {
  235. state = fork_high_prio_state;
  236. return true;
  237. }
  238. continue;
  239. case ExecutionResult::Continue:
  240. continue;
  241. case ExecutionResult::Succeeded:
  242. return true;
  243. case ExecutionResult::Failed:
  244. return false;
  245. case ExecutionResult::Failed_ExecuteLowPrioForks:
  246. return execute_low_prio_forks(input, state, output, fork_low_prio_states, recursion_level + 1);
  247. }
  248. }
  249. ASSERT_NOT_REACHED();
  250. }
  251. template<class Parser>
  252. ALWAYS_INLINE Optional<bool> Matcher<Parser>::execute_low_prio_forks(const MatchInput& input, MatchState& original_state, MatchOutput& output, Vector<MatchState> states, size_t recursion_level) const
  253. {
  254. for (auto& state : states) {
  255. state.instruction_position = state.fork_at_position;
  256. #ifdef REGEX_DEBUG
  257. fprintf(stderr, "Forkstay... ip = %lu, sp = %lu\n", state.instruction_position, state.string_position);
  258. #endif
  259. auto success = execute(input, state, output, recursion_level);
  260. if (!success.has_value())
  261. return {};
  262. if (success.value()) {
  263. #ifdef REGEX_DEBUG
  264. fprintf(stderr, "Forkstay succeeded... ip = %lu, sp = %lu\n", state.instruction_position, state.string_position);
  265. #endif
  266. original_state = state;
  267. return true;
  268. }
  269. }
  270. original_state.string_position = 0;
  271. return false;
  272. }
  273. template class Matcher<PosixExtendedParser>;
  274. template class Regex<PosixExtendedParser>;
  275. }