RegexMatcher.cpp 15 KB

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