RegexMatcher.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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(const RegexStringView& 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(const Vector<RegexStringView> 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. if (input.regex_options.has_flag_set(AllFlags::Internal_Stateful)) {
  70. if (views.size() > 1 && input.start_offset > views.first().length()) {
  71. dbgln_if(REGEX_DEBUG, "Started with start={}, goff={}, skip={}", input.start_offset, input.global_offset, lines_to_skip);
  72. for (auto& view : views) {
  73. if (input.start_offset < view.length() + 1)
  74. break;
  75. ++lines_to_skip;
  76. input.start_offset -= view.length() + 1;
  77. input.global_offset += view.length() + 1;
  78. }
  79. dbgln_if(REGEX_DEBUG, "Ended with start={}, goff={}, skip={}", input.start_offset, input.global_offset, lines_to_skip);
  80. }
  81. }
  82. if (c_match_preallocation_count) {
  83. output.matches.ensure_capacity(c_match_preallocation_count);
  84. output.capture_group_matches.ensure_capacity(c_match_preallocation_count);
  85. output.named_capture_group_matches.ensure_capacity(c_match_preallocation_count);
  86. auto& capture_groups_count = m_pattern.parser_result.capture_groups_count;
  87. auto& named_capture_groups_count = m_pattern.parser_result.named_capture_groups_count;
  88. for (size_t j = 0; j < c_match_preallocation_count; ++j) {
  89. output.matches.empend();
  90. output.capture_group_matches.unchecked_append({});
  91. output.capture_group_matches.at(j).ensure_capacity(capture_groups_count);
  92. for (size_t k = 0; k < capture_groups_count; ++k)
  93. output.capture_group_matches.at(j).unchecked_append({});
  94. output.named_capture_group_matches.unchecked_append({});
  95. output.named_capture_group_matches.at(j).ensure_capacity(named_capture_groups_count);
  96. }
  97. }
  98. auto append_match = [](auto& input, auto& state, auto& output, auto& start_position) {
  99. if (output.matches.size() == input.match_index)
  100. output.matches.empend();
  101. VERIFY(start_position + state.string_position - start_position <= input.view.length());
  102. if (input.regex_options.has_flag_set(AllFlags::StringCopyMatches)) {
  103. 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 };
  104. } else { // let the view point to the original string ...
  105. 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 };
  106. }
  107. };
  108. #if REGEX_DEBUG
  109. s_regex_dbg.print_header();
  110. #endif
  111. bool continue_search = input.regex_options.has_flag_set(AllFlags::Global) || input.regex_options.has_flag_set(AllFlags::Multiline);
  112. if (input.regex_options.has_flag_set(AllFlags::Internal_Stateful))
  113. continue_search = false;
  114. for (auto& view : views) {
  115. if (lines_to_skip != 0) {
  116. ++input.line;
  117. --lines_to_skip;
  118. continue;
  119. }
  120. input.view = view;
  121. dbgln_if(REGEX_DEBUG, "[match] Starting match with view ({}): _{}_", view.length(), view);
  122. auto view_length = view.length();
  123. size_t view_index = m_pattern.start_offset;
  124. state.string_position = view_index;
  125. bool succeeded = false;
  126. if (view_index == view_length && m_pattern.parser_result.match_length_minimum == 0) {
  127. // Run the code until it tries to consume something.
  128. // This allows non-consuming code to run on empty strings, for instance
  129. // e.g. "Exit"
  130. MatchOutput temp_output { output };
  131. input.column = match_count;
  132. input.match_index = match_count;
  133. state.string_position = view_index;
  134. state.instruction_position = 0;
  135. auto success = execute(input, state, temp_output, 0);
  136. // This success is acceptable only if it doesn't read anything from the input (input length is 0).
  137. if (state.string_position <= view_index) {
  138. if (success.value()) {
  139. output = move(temp_output);
  140. if (!match_count) {
  141. // Nothing was *actually* matched, so append an empty match.
  142. append_match(input, state, output, view_index);
  143. ++match_count;
  144. }
  145. }
  146. }
  147. }
  148. for (; view_index < view_length; ++view_index) {
  149. auto& match_length_minimum = m_pattern.parser_result.match_length_minimum;
  150. // FIXME: More performant would be to know the remaining minimum string
  151. // length needed to match from the current position onwards within
  152. // the vm. Add new OpCode for MinMatchLengthFromSp with the value of
  153. // the remaining string length from the current path. The value though
  154. // has to be filled in reverse. That implies a second run over bytecode
  155. // after generation has finished.
  156. if (match_length_minimum && match_length_minimum > view_length - view_index)
  157. break;
  158. input.column = match_count;
  159. input.match_index = match_count;
  160. state.string_position = view_index;
  161. state.instruction_position = 0;
  162. auto success = execute(input, state, output, 0);
  163. if (!success.has_value())
  164. return { false, 0, {}, {}, {}, output.operations };
  165. if (success.value()) {
  166. succeeded = true;
  167. if (input.regex_options.has_flag_set(AllFlags::MatchNotEndOfLine) && state.string_position == input.view.length()) {
  168. if (!continue_search)
  169. break;
  170. continue;
  171. }
  172. if (input.regex_options.has_flag_set(AllFlags::MatchNotBeginOfLine) && view_index == 0) {
  173. if (!continue_search)
  174. break;
  175. continue;
  176. }
  177. dbgln_if(REGEX_DEBUG, "state.string_position={}, view_index={}", state.string_position, view_index);
  178. 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));
  179. ++match_count;
  180. if (continue_search) {
  181. append_match(input, state, output, view_index);
  182. bool has_zero_length = state.string_position == view_index;
  183. view_index = state.string_position - (has_zero_length ? 0 : 1);
  184. continue;
  185. } else if (input.regex_options.has_flag_set(AllFlags::Internal_Stateful)) {
  186. append_match(input, state, output, view_index);
  187. break;
  188. } else if (state.string_position < view_length) {
  189. return { false, 0, {}, {}, {}, output.operations };
  190. }
  191. append_match(input, state, output, view_index);
  192. break;
  193. }
  194. if (!continue_search && !input.regex_options.has_flag_set(AllFlags::Internal_Stateful))
  195. break;
  196. }
  197. ++input.line;
  198. input.global_offset += view.length() + 1; // +1 includes the line break character
  199. if (input.regex_options.has_flag_set(AllFlags::Internal_Stateful))
  200. m_pattern.start_offset = state.string_position;
  201. if (succeeded && !continue_search)
  202. break;
  203. }
  204. MatchOutput output_copy;
  205. if (match_count) {
  206. output_copy.capture_group_matches = output.capture_group_matches;
  207. // Make sure there are as many capture matches as there are actual matches.
  208. if (output_copy.capture_group_matches.size() < match_count)
  209. output_copy.capture_group_matches.resize(match_count);
  210. for (auto& matches : output_copy.capture_group_matches)
  211. matches.resize(m_pattern.parser_result.capture_groups_count + 1);
  212. if (!input.regex_options.has_flag_set(AllFlags::SkipTrimEmptyMatches)) {
  213. for (auto& matches : output_copy.capture_group_matches)
  214. matches.template remove_all_matching([](auto& match) { return match.view.is_null(); });
  215. }
  216. output_copy.named_capture_group_matches = output.named_capture_group_matches;
  217. // Make sure there are as many capture matches as there are actual matches.
  218. if (output_copy.named_capture_group_matches.size() < match_count)
  219. output_copy.named_capture_group_matches.resize(match_count);
  220. output_copy.matches = output.matches;
  221. } else {
  222. output_copy.capture_group_matches.clear_with_capacity();
  223. output_copy.named_capture_group_matches.clear_with_capacity();
  224. }
  225. return {
  226. match_count != 0,
  227. match_count,
  228. move(output_copy.matches),
  229. move(output_copy.capture_group_matches),
  230. move(output_copy.named_capture_group_matches),
  231. output.operations,
  232. m_pattern.parser_result.capture_groups_count,
  233. m_pattern.parser_result.named_capture_groups_count,
  234. };
  235. }
  236. template<class Parser>
  237. Optional<bool> Matcher<Parser>::execute(const MatchInput& input, MatchState& state, MatchOutput& output, size_t recursion_level) const
  238. {
  239. if (recursion_level > c_max_recursion)
  240. return false;
  241. Vector<MatchState> fork_low_prio_states;
  242. MatchState fork_high_prio_state;
  243. Optional<bool> success;
  244. auto& bytecode = m_pattern.parser_result.bytecode;
  245. for (;;) {
  246. ++output.operations;
  247. auto* opcode = bytecode.get_opcode(state);
  248. if (!opcode) {
  249. dbgln("Wrong opcode... failed!");
  250. return {};
  251. }
  252. #if REGEX_DEBUG
  253. s_regex_dbg.print_opcode("VM", *opcode, state, recursion_level, false);
  254. #endif
  255. ExecutionResult result;
  256. if (input.fail_counter > 0) {
  257. --input.fail_counter;
  258. result = ExecutionResult::Failed_ExecuteLowPrioForks;
  259. } else {
  260. result = opcode->execute(input, state, output);
  261. }
  262. #if REGEX_DEBUG
  263. s_regex_dbg.print_result(*opcode, bytecode, input, state, result);
  264. #endif
  265. state.instruction_position += opcode->size();
  266. switch (result) {
  267. case ExecutionResult::Fork_PrioLow:
  268. fork_low_prio_states.prepend(state);
  269. continue;
  270. case ExecutionResult::Fork_PrioHigh:
  271. fork_high_prio_state = state;
  272. fork_high_prio_state.instruction_position = fork_high_prio_state.fork_at_position;
  273. success = execute(input, fork_high_prio_state, output, ++recursion_level);
  274. if (!success.has_value())
  275. return {};
  276. if (success.value()) {
  277. state = fork_high_prio_state;
  278. return true;
  279. }
  280. continue;
  281. case ExecutionResult::Continue:
  282. continue;
  283. case ExecutionResult::Succeeded:
  284. return true;
  285. case ExecutionResult::Failed:
  286. return false;
  287. case ExecutionResult::Failed_ExecuteLowPrioForks:
  288. return execute_low_prio_forks(input, state, output, fork_low_prio_states, recursion_level + 1);
  289. }
  290. }
  291. VERIFY_NOT_REACHED();
  292. }
  293. template<class Parser>
  294. 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
  295. {
  296. for (auto& state : states) {
  297. state.instruction_position = state.fork_at_position;
  298. dbgln_if(REGEX_DEBUG, "Forkstay... ip = {}, sp = {}", state.instruction_position, state.string_position);
  299. auto success = execute(input, state, output, recursion_level);
  300. if (!success.has_value())
  301. return {};
  302. if (success.value()) {
  303. dbgln_if(REGEX_DEBUG, "Forkstay succeeded... ip = {}, sp = {}", state.instruction_position, state.string_position);
  304. original_state = state;
  305. return true;
  306. }
  307. }
  308. original_state.string_position = 0;
  309. return false;
  310. }
  311. template class Matcher<PosixExtendedParser>;
  312. template class Regex<PosixExtendedParser>;
  313. template class Matcher<ECMA262Parser>;
  314. template class Regex<ECMA262Parser>;
  315. }