RegexMatcher.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. /*
  2. * Copyright (c) 2020, Emanuel Sprung <emanuel.sprung@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "RegexMatcher.h"
  7. #include "RegexDebug.h"
  8. #include "RegexParser.h"
  9. #include <AK/Debug.h>
  10. #include <AK/ScopedValueRollback.h>
  11. #include <AK/String.h>
  12. #include <AK/StringBuilder.h>
  13. namespace regex {
  14. #if REGEX_DEBUG
  15. static RegexDebug s_regex_dbg(stderr);
  16. #endif
  17. template<class Parser>
  18. Regex<Parser>::Regex(StringView pattern, typename ParserTraits<Parser>::OptionsType regex_options)
  19. {
  20. pattern_value = pattern.to_string();
  21. regex::Lexer lexer(pattern);
  22. Parser parser(lexer, regex_options);
  23. parser_result = parser.parse();
  24. if (parser_result.error == regex::Error::NoError)
  25. matcher = make<Matcher<Parser>>(*this, regex_options);
  26. }
  27. template<class Parser>
  28. typename ParserTraits<Parser>::OptionsType Regex<Parser>::options() const
  29. {
  30. if (parser_result.error != Error::NoError)
  31. return {};
  32. return matcher->options();
  33. }
  34. template<class Parser>
  35. String Regex<Parser>::error_string(Optional<String> message) const
  36. {
  37. StringBuilder eb;
  38. eb.append("Error during parsing of regular expression:\n");
  39. eb.appendff(" {}\n ", pattern_value);
  40. for (size_t i = 0; i < parser_result.error_token.position(); ++i)
  41. eb.append(' ');
  42. eb.appendff("^---- {}", message.value_or(get_error_string(parser_result.error)));
  43. return eb.build();
  44. }
  45. template<typename Parser>
  46. RegexResult Matcher<Parser>::match(RegexStringView const& view, Optional<typename ParserTraits<Parser>::OptionsType> regex_options) const
  47. {
  48. AllOptions options = m_regex_options | regex_options.value_or({}).value();
  49. if (options.has_flag_set(AllFlags::Multiline))
  50. 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...
  51. Vector<RegexStringView> views;
  52. views.append(view);
  53. return match(views, regex_options);
  54. }
  55. template<typename Parser>
  56. RegexResult Matcher<Parser>::match(Vector<RegexStringView> const views, Optional<typename ParserTraits<Parser>::OptionsType> regex_options) const
  57. {
  58. // If the pattern *itself* isn't stateful, reset any changes to start_offset.
  59. if (!((AllFlags)m_regex_options.value() & AllFlags::Internal_Stateful))
  60. m_pattern.start_offset = 0;
  61. size_t match_count { 0 };
  62. MatchInput input;
  63. MatchState state;
  64. MatchOutput output;
  65. input.regex_options = m_regex_options | regex_options.value_or({}).value();
  66. input.start_offset = m_pattern.start_offset;
  67. output.operations = 0;
  68. size_t lines_to_skip = 0;
  69. bool unicode = input.regex_options.has_flag_set(AllFlags::Unicode);
  70. for (auto& view : views)
  71. const_cast<RegexStringView&>(view).set_unicode(unicode);
  72. if (input.regex_options.has_flag_set(AllFlags::Internal_Stateful)) {
  73. if (views.size() > 1 && input.start_offset > views.first().length()) {
  74. dbgln_if(REGEX_DEBUG, "Started with start={}, goff={}, skip={}", input.start_offset, input.global_offset, lines_to_skip);
  75. for (auto& view : views) {
  76. if (input.start_offset < view.length() + 1)
  77. break;
  78. ++lines_to_skip;
  79. input.start_offset -= view.length() + 1;
  80. input.global_offset += view.length() + 1;
  81. }
  82. dbgln_if(REGEX_DEBUG, "Ended with start={}, goff={}, skip={}", input.start_offset, input.global_offset, lines_to_skip);
  83. }
  84. }
  85. if (c_match_preallocation_count) {
  86. state.matches.ensure_capacity(c_match_preallocation_count);
  87. state.capture_group_matches.ensure_capacity(c_match_preallocation_count);
  88. state.named_capture_group_matches.ensure_capacity(c_match_preallocation_count);
  89. auto& capture_groups_count = m_pattern.parser_result.capture_groups_count;
  90. auto& named_capture_groups_count = m_pattern.parser_result.named_capture_groups_count;
  91. for (size_t j = 0; j < c_match_preallocation_count; ++j) {
  92. state.matches.empend();
  93. state.capture_group_matches.unchecked_append({});
  94. state.capture_group_matches.at(j).ensure_capacity(capture_groups_count);
  95. for (size_t k = 0; k < capture_groups_count; ++k)
  96. state.capture_group_matches.at(j).unchecked_append({});
  97. state.named_capture_group_matches.unchecked_append({});
  98. state.named_capture_group_matches.at(j).ensure_capacity(named_capture_groups_count);
  99. }
  100. }
  101. auto append_match = [](auto& input, auto& state, auto& start_position) {
  102. if (state.matches.size() == input.match_index)
  103. state.matches.empend();
  104. VERIFY(start_position + state.string_position - start_position <= input.view.length());
  105. if (input.regex_options.has_flag_set(AllFlags::StringCopyMatches)) {
  106. state.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 };
  107. } else { // let the view point to the original string ...
  108. state.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 };
  109. }
  110. };
  111. #if REGEX_DEBUG
  112. s_regex_dbg.print_header();
  113. #endif
  114. bool continue_search = input.regex_options.has_flag_set(AllFlags::Global) || input.regex_options.has_flag_set(AllFlags::Multiline);
  115. if (input.regex_options.has_flag_set(AllFlags::Internal_Stateful))
  116. continue_search = false;
  117. for (auto& view : views) {
  118. if (lines_to_skip != 0) {
  119. ++input.line;
  120. --lines_to_skip;
  121. continue;
  122. }
  123. input.view = view;
  124. dbgln_if(REGEX_DEBUG, "[match] Starting match with view ({}): _{}_", view.length(), view);
  125. auto view_length = view.length();
  126. size_t view_index = m_pattern.start_offset;
  127. state.string_position = view_index;
  128. bool succeeded = false;
  129. if (view_index == view_length && m_pattern.parser_result.match_length_minimum == 0) {
  130. // Run the code until it tries to consume something.
  131. // This allows non-consuming code to run on empty strings, for instance
  132. // e.g. "Exit"
  133. MatchOutput temp_output { output };
  134. input.column = match_count;
  135. input.match_index = match_count;
  136. state.string_position = view_index;
  137. state.instruction_position = 0;
  138. auto success = execute(input, state, temp_output, 0);
  139. // This success is acceptable only if it doesn't read anything from the input (input length is 0).
  140. if (state.string_position <= view_index) {
  141. if (success.value()) {
  142. output = move(temp_output);
  143. if (!match_count) {
  144. // Nothing was *actually* matched, so append an empty match.
  145. append_match(input, state, view_index);
  146. ++match_count;
  147. }
  148. }
  149. }
  150. }
  151. for (; view_index < view_length; ++view_index) {
  152. auto& match_length_minimum = m_pattern.parser_result.match_length_minimum;
  153. // FIXME: More performant would be to know the remaining minimum string
  154. // length needed to match from the current position onwards within
  155. // the vm. Add new OpCode for MinMatchLengthFromSp with the value of
  156. // the remaining string length from the current path. The value though
  157. // has to be filled in reverse. That implies a second run over bytecode
  158. // after generation has finished.
  159. if (match_length_minimum && match_length_minimum > view_length - view_index)
  160. break;
  161. input.column = match_count;
  162. input.match_index = match_count;
  163. state.string_position = view_index;
  164. state.instruction_position = 0;
  165. auto success = execute(input, state, output, 0);
  166. if (!success.has_value())
  167. return { false, 0, {}, {}, {}, output.operations };
  168. if (success.value()) {
  169. succeeded = true;
  170. if (input.regex_options.has_flag_set(AllFlags::MatchNotEndOfLine) && state.string_position == input.view.length()) {
  171. if (!continue_search)
  172. break;
  173. continue;
  174. }
  175. if (input.regex_options.has_flag_set(AllFlags::MatchNotBeginOfLine) && view_index == 0) {
  176. if (!continue_search)
  177. break;
  178. continue;
  179. }
  180. dbgln_if(REGEX_DEBUG, "state.string_position={}, view_index={}", state.string_position, view_index);
  181. dbgln_if(REGEX_DEBUG, "[match] Found a match (length={}): '{}'", state.string_position - view_index, input.view.substring_view(view_index, state.string_position - view_index));
  182. ++match_count;
  183. if (continue_search) {
  184. append_match(input, state, view_index);
  185. bool has_zero_length = state.string_position == view_index;
  186. view_index = state.string_position - (has_zero_length ? 0 : 1);
  187. continue;
  188. } else if (input.regex_options.has_flag_set(AllFlags::Internal_Stateful)) {
  189. append_match(input, state, view_index);
  190. break;
  191. } else if (state.string_position < view_length) {
  192. return { false, 0, {}, {}, {}, output.operations };
  193. }
  194. append_match(input, state, view_index);
  195. break;
  196. }
  197. if (!continue_search)
  198. break;
  199. }
  200. ++input.line;
  201. input.global_offset += view.length() + 1; // +1 includes the line break character
  202. if (input.regex_options.has_flag_set(AllFlags::Internal_Stateful))
  203. m_pattern.start_offset = state.string_position;
  204. if (succeeded && !continue_search)
  205. break;
  206. }
  207. MatchOutput output_copy;
  208. if (match_count) {
  209. output_copy.capture_group_matches = state.capture_group_matches;
  210. // Make sure there are as many capture matches as there are actual matches.
  211. if (output_copy.capture_group_matches.size() < match_count)
  212. output_copy.capture_group_matches.resize(match_count);
  213. for (auto& matches : output_copy.capture_group_matches)
  214. matches.resize(m_pattern.parser_result.capture_groups_count + 1);
  215. if (!input.regex_options.has_flag_set(AllFlags::SkipTrimEmptyMatches)) {
  216. for (auto& matches : output_copy.capture_group_matches)
  217. matches.template remove_all_matching([](auto& match) { return match.view.is_null(); });
  218. }
  219. output_copy.named_capture_group_matches = state.named_capture_group_matches;
  220. // Make sure there are as many capture matches as there are actual matches.
  221. if (output_copy.named_capture_group_matches.size() < match_count)
  222. output_copy.named_capture_group_matches.resize(match_count);
  223. output_copy.matches = state.matches;
  224. } else {
  225. output_copy.capture_group_matches.clear_with_capacity();
  226. output_copy.named_capture_group_matches.clear_with_capacity();
  227. }
  228. return {
  229. match_count != 0,
  230. match_count,
  231. move(output_copy.matches),
  232. move(output_copy.capture_group_matches),
  233. move(output_copy.named_capture_group_matches),
  234. output.operations,
  235. m_pattern.parser_result.capture_groups_count,
  236. m_pattern.parser_result.named_capture_groups_count,
  237. };
  238. }
  239. template<class Parser>
  240. Optional<bool> Matcher<Parser>::execute(MatchInput const& input, MatchState& state, MatchOutput& output, size_t recursion_level) const
  241. {
  242. if (recursion_level > c_max_recursion)
  243. return false;
  244. Vector<MatchState, 64> reversed_fork_low_prio_states;
  245. MatchState fork_high_prio_state;
  246. Optional<bool> success;
  247. auto& bytecode = m_pattern.parser_result.bytecode;
  248. for (;;) {
  249. ++output.operations;
  250. auto& opcode = bytecode.get_opcode(state);
  251. #if REGEX_DEBUG
  252. s_regex_dbg.print_opcode("VM", opcode, state, recursion_level, false);
  253. #endif
  254. ExecutionResult result;
  255. if (input.fail_counter > 0) {
  256. --input.fail_counter;
  257. result = ExecutionResult::Failed_ExecuteLowPrioForks;
  258. } else {
  259. result = opcode.execute(input, state, output);
  260. }
  261. #if REGEX_DEBUG
  262. s_regex_dbg.print_result(opcode, bytecode, input, state, result);
  263. #endif
  264. state.instruction_position += opcode.size();
  265. switch (result) {
  266. case ExecutionResult::Fork_PrioLow:
  267. reversed_fork_low_prio_states.append(state);
  268. continue;
  269. case ExecutionResult::Fork_PrioHigh:
  270. fork_high_prio_state = state;
  271. fork_high_prio_state.instruction_position = fork_high_prio_state.fork_at_position;
  272. success = execute(input, fork_high_prio_state, output, ++recursion_level);
  273. if (!success.has_value())
  274. return {};
  275. if (success.value()) {
  276. state = fork_high_prio_state;
  277. return true;
  278. }
  279. continue;
  280. case ExecutionResult::Continue:
  281. continue;
  282. case ExecutionResult::Succeeded:
  283. return true;
  284. case ExecutionResult::Failed:
  285. return false;
  286. case ExecutionResult::Failed_ExecuteLowPrioForks: {
  287. Vector<MatchState> fork_low_prio_states;
  288. fork_low_prio_states.ensure_capacity(reversed_fork_low_prio_states.size());
  289. for (ssize_t i = reversed_fork_low_prio_states.size() - 1; i >= 0; i--)
  290. fork_low_prio_states.unchecked_append(move(reversed_fork_low_prio_states[i]));
  291. return execute_low_prio_forks(input, state, output, move(fork_low_prio_states), recursion_level + 1);
  292. }
  293. }
  294. }
  295. VERIFY_NOT_REACHED();
  296. }
  297. template<class Parser>
  298. ALWAYS_INLINE Optional<bool> Matcher<Parser>::execute_low_prio_forks(MatchInput const& input, MatchState& original_state, MatchOutput& output, Vector<MatchState> states, size_t recursion_level) const
  299. {
  300. for (auto& state : states) {
  301. state.instruction_position = state.fork_at_position;
  302. dbgln_if(REGEX_DEBUG, "Forkstay... ip = {}, sp = {}", state.instruction_position, state.string_position);
  303. auto success = execute(input, state, output, recursion_level);
  304. if (!success.has_value())
  305. return {};
  306. if (success.value()) {
  307. dbgln_if(REGEX_DEBUG, "Forkstay succeeded... ip = {}, sp = {}", state.instruction_position, state.string_position);
  308. original_state = state;
  309. return true;
  310. }
  311. }
  312. original_state.string_position = 0;
  313. return false;
  314. }
  315. template class Matcher<PosixBasicParser>;
  316. template class Regex<PosixBasicParser>;
  317. template class Matcher<PosixExtendedParser>;
  318. template class Regex<PosixExtendedParser>;
  319. template class Matcher<ECMA262Parser>;
  320. template class Regex<ECMA262Parser>;
  321. }