RegexMatcher.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. /*
  2. * Copyright (c) 2020, Emanuel Sprung <emanuel.sprung@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/BumpAllocator.h>
  7. #include <AK/ByteString.h>
  8. #include <AK/Debug.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibRegex/RegexMatcher.h>
  11. #include <LibRegex/RegexParser.h>
  12. #if REGEX_DEBUG
  13. # include <LibRegex/RegexDebug.h>
  14. #endif
  15. namespace regex {
  16. #if REGEX_DEBUG
  17. static RegexDebug s_regex_dbg(stderr);
  18. #endif
  19. template<class Parser>
  20. regex::Parser::Result Regex<Parser>::parse_pattern(StringView pattern, typename ParserTraits<Parser>::OptionsType regex_options)
  21. {
  22. regex::Lexer lexer(pattern);
  23. Parser parser(lexer, regex_options);
  24. return parser.parse();
  25. }
  26. template<class Parser>
  27. Regex<Parser>::Regex(ByteString pattern, typename ParserTraits<Parser>::OptionsType regex_options)
  28. : pattern_value(move(pattern))
  29. {
  30. regex::Lexer lexer(pattern_value);
  31. Parser parser(lexer, regex_options);
  32. parser_result = parser.parse();
  33. run_optimization_passes();
  34. if (parser_result.error == regex::Error::NoError)
  35. matcher = make<Matcher<Parser>>(this, static_cast<decltype(regex_options.value())>(parser_result.options.value()));
  36. }
  37. template<class Parser>
  38. Regex<Parser>::Regex(regex::Parser::Result parse_result, ByteString pattern, typename ParserTraits<Parser>::OptionsType regex_options)
  39. : pattern_value(move(pattern))
  40. , parser_result(move(parse_result))
  41. {
  42. run_optimization_passes();
  43. if (parser_result.error == regex::Error::NoError)
  44. matcher = make<Matcher<Parser>>(this, regex_options | static_cast<decltype(regex_options.value())>(parse_result.options.value()));
  45. }
  46. template<class Parser>
  47. Regex<Parser>::Regex(Regex&& regex)
  48. : pattern_value(move(regex.pattern_value))
  49. , parser_result(move(regex.parser_result))
  50. , matcher(move(regex.matcher))
  51. , start_offset(regex.start_offset)
  52. {
  53. if (matcher)
  54. matcher->reset_pattern({}, this);
  55. }
  56. template<class Parser>
  57. Regex<Parser>& Regex<Parser>::operator=(Regex&& regex)
  58. {
  59. pattern_value = move(regex.pattern_value);
  60. parser_result = move(regex.parser_result);
  61. matcher = move(regex.matcher);
  62. if (matcher)
  63. matcher->reset_pattern({}, this);
  64. start_offset = regex.start_offset;
  65. return *this;
  66. }
  67. template<class Parser>
  68. typename ParserTraits<Parser>::OptionsType Regex<Parser>::options() const
  69. {
  70. if (!matcher || parser_result.error != Error::NoError)
  71. return {};
  72. return matcher->options();
  73. }
  74. template<class Parser>
  75. ByteString Regex<Parser>::error_string(Optional<ByteString> message) const
  76. {
  77. StringBuilder eb;
  78. eb.append("Error during parsing of regular expression:\n"sv);
  79. eb.appendff(" {}\n ", pattern_value);
  80. for (size_t i = 0; i < parser_result.error_token.position(); ++i)
  81. eb.append(' ');
  82. eb.appendff("^---- {}", message.value_or(get_error_string(parser_result.error)));
  83. return eb.to_byte_string();
  84. }
  85. template<typename Parser>
  86. RegexResult Matcher<Parser>::match(RegexStringView view, Optional<typename ParserTraits<Parser>::OptionsType> regex_options) const
  87. {
  88. AllOptions options = m_regex_options | regex_options.value_or({}).value();
  89. if constexpr (!IsSame<Parser, ECMA262>) {
  90. if (options.has_flag_set(AllFlags::Multiline))
  91. 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...
  92. }
  93. Vector<RegexStringView> views;
  94. views.append(view);
  95. return match(views, regex_options);
  96. }
  97. template<typename Parser>
  98. RegexResult Matcher<Parser>::match(Vector<RegexStringView> const& views, Optional<typename ParserTraits<Parser>::OptionsType> regex_options) const
  99. {
  100. // If the pattern *itself* isn't stateful, reset any changes to start_offset.
  101. if (!((AllFlags)m_regex_options.value() & AllFlags::Internal_Stateful))
  102. m_pattern->start_offset = 0;
  103. size_t match_count { 0 };
  104. MatchInput input;
  105. MatchState state;
  106. size_t operations = 0;
  107. input.regex_options = m_regex_options | regex_options.value_or({}).value();
  108. input.start_offset = m_pattern->start_offset;
  109. size_t lines_to_skip = 0;
  110. bool unicode = input.regex_options.has_flag_set(AllFlags::Unicode);
  111. for (auto const& view : views)
  112. const_cast<RegexStringView&>(view).set_unicode(unicode);
  113. if (input.regex_options.has_flag_set(AllFlags::Internal_Stateful)) {
  114. if (views.size() > 1 && input.start_offset > views.first().length()) {
  115. dbgln_if(REGEX_DEBUG, "Started with start={}, goff={}, skip={}", input.start_offset, input.global_offset, lines_to_skip);
  116. for (auto const& view : views) {
  117. if (input.start_offset < view.length() + 1)
  118. break;
  119. ++lines_to_skip;
  120. input.start_offset -= view.length() + 1;
  121. input.global_offset += view.length() + 1;
  122. }
  123. dbgln_if(REGEX_DEBUG, "Ended with start={}, goff={}, skip={}", input.start_offset, input.global_offset, lines_to_skip);
  124. }
  125. }
  126. if (c_match_preallocation_count) {
  127. state.matches.ensure_capacity(c_match_preallocation_count);
  128. state.capture_group_matches.ensure_capacity(c_match_preallocation_count);
  129. auto& capture_groups_count = m_pattern->parser_result.capture_groups_count;
  130. for (size_t j = 0; j < c_match_preallocation_count; ++j) {
  131. state.matches.empend();
  132. state.capture_group_matches.empend();
  133. state.capture_group_matches.at(j).ensure_capacity(capture_groups_count);
  134. for (size_t k = 0; k < capture_groups_count; ++k)
  135. state.capture_group_matches.at(j).unchecked_append({});
  136. }
  137. }
  138. auto append_match = [](auto& input, auto& state, auto& start_position) {
  139. if (state.matches.size() == input.match_index)
  140. state.matches.empend();
  141. VERIFY(start_position + state.string_position - start_position <= input.view.length());
  142. if (input.regex_options.has_flag_set(AllFlags::StringCopyMatches)) {
  143. state.matches.at(input.match_index) = { input.view.substring_view(start_position, state.string_position - start_position).to_byte_string(), input.line, start_position, input.global_offset + start_position };
  144. } else { // let the view point to the original string ...
  145. 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 };
  146. }
  147. };
  148. #if REGEX_DEBUG
  149. s_regex_dbg.print_header();
  150. #endif
  151. bool continue_search = input.regex_options.has_flag_set(AllFlags::Global) || input.regex_options.has_flag_set(AllFlags::Multiline);
  152. if (input.regex_options.has_flag_set(AllFlags::Sticky))
  153. continue_search = false;
  154. auto single_match_only = input.regex_options.has_flag_set(AllFlags::SingleMatch);
  155. for (auto const& view : views) {
  156. if (lines_to_skip != 0) {
  157. ++input.line;
  158. --lines_to_skip;
  159. continue;
  160. }
  161. input.view = view;
  162. dbgln_if(REGEX_DEBUG, "[match] Starting match with view ({}): _{}_", view.length(), view);
  163. auto view_length = view.length();
  164. size_t view_index = m_pattern->start_offset;
  165. state.string_position = view_index;
  166. state.string_position_in_code_units = view_index;
  167. bool succeeded = false;
  168. if (view_index == view_length && m_pattern->parser_result.match_length_minimum == 0) {
  169. // Run the code until it tries to consume something.
  170. // This allows non-consuming code to run on empty strings, for instance
  171. // e.g. "Exit"
  172. size_t temp_operations = operations;
  173. input.column = match_count;
  174. input.match_index = match_count;
  175. state.string_position = view_index;
  176. state.string_position_in_code_units = view_index;
  177. state.instruction_position = 0;
  178. state.repetition_marks.clear();
  179. auto success = execute(input, state, temp_operations);
  180. // This success is acceptable only if it doesn't read anything from the input (input length is 0).
  181. if (success && (state.string_position <= view_index)) {
  182. operations = temp_operations;
  183. if (!match_count) {
  184. // Nothing was *actually* matched, so append an empty match.
  185. append_match(input, state, view_index);
  186. ++match_count;
  187. // This prevents a regex pattern like ".*" from matching the empty string
  188. // multiple times, once in this block and once in the following for loop.
  189. if (view_index == 0 && view_length == 0)
  190. ++view_index;
  191. }
  192. }
  193. }
  194. for (; view_index <= view_length; ++view_index) {
  195. if (view_index == view_length && input.regex_options.has_flag_set(AllFlags::Multiline))
  196. break;
  197. auto& match_length_minimum = m_pattern->parser_result.match_length_minimum;
  198. // FIXME: More performant would be to know the remaining minimum string
  199. // length needed to match from the current position onwards within
  200. // the vm. Add new OpCode for MinMatchLengthFromSp with the value of
  201. // the remaining string length from the current path. The value though
  202. // has to be filled in reverse. That implies a second run over bytecode
  203. // after generation has finished.
  204. if (match_length_minimum && match_length_minimum > view_length - view_index)
  205. break;
  206. input.column = match_count;
  207. input.match_index = match_count;
  208. state.string_position = view_index;
  209. state.string_position_in_code_units = view_index;
  210. state.instruction_position = 0;
  211. state.repetition_marks.clear();
  212. auto success = execute(input, state, operations);
  213. if (success) {
  214. succeeded = true;
  215. if (input.regex_options.has_flag_set(AllFlags::MatchNotEndOfLine) && state.string_position == input.view.length()) {
  216. if (!continue_search)
  217. break;
  218. continue;
  219. }
  220. if (input.regex_options.has_flag_set(AllFlags::MatchNotBeginOfLine) && view_index == 0) {
  221. if (!continue_search)
  222. break;
  223. continue;
  224. }
  225. dbgln_if(REGEX_DEBUG, "state.string_position={}, view_index={}", state.string_position, view_index);
  226. 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));
  227. ++match_count;
  228. if (continue_search) {
  229. append_match(input, state, view_index);
  230. bool has_zero_length = state.string_position == view_index;
  231. view_index = state.string_position - (has_zero_length ? 0 : 1);
  232. if (single_match_only)
  233. break;
  234. continue;
  235. }
  236. if (input.regex_options.has_flag_set(AllFlags::Internal_Stateful)) {
  237. append_match(input, state, view_index);
  238. break;
  239. }
  240. if (state.string_position < view_length) {
  241. return { false, 0, {}, {}, {}, operations };
  242. }
  243. append_match(input, state, view_index);
  244. break;
  245. }
  246. if (!continue_search)
  247. break;
  248. }
  249. ++input.line;
  250. input.global_offset += view.length() + 1; // +1 includes the line break character
  251. if (input.regex_options.has_flag_set(AllFlags::Internal_Stateful))
  252. m_pattern->start_offset = state.string_position;
  253. if (succeeded && !continue_search)
  254. break;
  255. }
  256. RegexResult result {
  257. match_count != 0,
  258. match_count,
  259. move(state.matches).release(),
  260. move(state.capture_group_matches).release(),
  261. operations,
  262. m_pattern->parser_result.capture_groups_count,
  263. m_pattern->parser_result.named_capture_groups_count,
  264. };
  265. if (match_count) {
  266. // Make sure there are as many capture matches as there are actual matches.
  267. if (result.capture_group_matches.size() < match_count)
  268. result.capture_group_matches.resize(match_count);
  269. for (auto& matches : result.capture_group_matches)
  270. matches.resize(m_pattern->parser_result.capture_groups_count + 1);
  271. if (!input.regex_options.has_flag_set(AllFlags::SkipTrimEmptyMatches)) {
  272. for (auto& matches : result.capture_group_matches)
  273. matches.template remove_all_matching([](auto& match) { return match.view.is_null(); });
  274. }
  275. } else {
  276. result.capture_group_matches.clear_with_capacity();
  277. }
  278. return result;
  279. }
  280. template<typename T>
  281. class BumpAllocatedLinkedList {
  282. public:
  283. BumpAllocatedLinkedList() = default;
  284. ALWAYS_INLINE void append(T value)
  285. {
  286. auto node_ptr = m_allocator.allocate(move(value));
  287. VERIFY(node_ptr);
  288. if (!m_first) {
  289. m_first = node_ptr;
  290. m_last = node_ptr;
  291. return;
  292. }
  293. node_ptr->previous = m_last;
  294. m_last->next = node_ptr;
  295. m_last = node_ptr;
  296. }
  297. ALWAYS_INLINE T take_last()
  298. {
  299. VERIFY(m_last);
  300. T value = move(m_last->value);
  301. if (m_last == m_first) {
  302. m_last = nullptr;
  303. m_first = nullptr;
  304. } else {
  305. m_last = m_last->previous;
  306. m_last->next = nullptr;
  307. }
  308. return value;
  309. }
  310. ALWAYS_INLINE T& last()
  311. {
  312. return m_last->value;
  313. }
  314. ALWAYS_INLINE bool is_empty() const
  315. {
  316. return m_first == nullptr;
  317. }
  318. auto reverse_begin() { return ReverseIterator(m_last); }
  319. auto reverse_end() { return ReverseIterator(); }
  320. private:
  321. struct Node {
  322. T value;
  323. Node* next { nullptr };
  324. Node* previous { nullptr };
  325. };
  326. struct ReverseIterator {
  327. ReverseIterator() = default;
  328. explicit ReverseIterator(Node* node)
  329. : m_node(node)
  330. {
  331. }
  332. T* operator->() { return &m_node->value; }
  333. T& operator*() { return m_node->value; }
  334. bool operator==(ReverseIterator const& it) const { return m_node == it.m_node; }
  335. ReverseIterator& operator++()
  336. {
  337. if (m_node)
  338. m_node = m_node->previous;
  339. return *this;
  340. }
  341. private:
  342. Node* m_node;
  343. };
  344. UniformBumpAllocator<Node, true, 2 * MiB> m_allocator;
  345. Node* m_first { nullptr };
  346. Node* m_last { nullptr };
  347. };
  348. template<class Parser>
  349. bool Matcher<Parser>::execute(MatchInput const& input, MatchState& state, size_t& operations) const
  350. {
  351. if (m_pattern->parser_result.optimization_data.pure_substring_search.has_value() && input.view.is_string_view()) {
  352. // Yay, we can do a simple substring search!
  353. auto& needle = m_pattern->parser_result.optimization_data.pure_substring_search.value();
  354. if (needle.length() + state.string_position > input.view.length())
  355. return false;
  356. auto haystack = input.view.string_view().substring_view(state.string_position);
  357. if (input.regex_options.has_flag_set(AllFlags::Insensitive)) {
  358. if (!haystack.substring_view(0, needle.length()).equals_ignoring_ascii_case(needle))
  359. return false;
  360. } else {
  361. if (!haystack.starts_with(needle))
  362. return false;
  363. }
  364. state.string_position += needle.length();
  365. state.string_position_in_code_units += needle.length();
  366. return true;
  367. }
  368. BumpAllocatedLinkedList<MatchState> states_to_try_next;
  369. #if REGEX_DEBUG
  370. size_t recursion_level = 0;
  371. #endif
  372. auto& bytecode = m_pattern->parser_result.bytecode;
  373. for (;;) {
  374. auto& opcode = bytecode.get_opcode(state);
  375. ++operations;
  376. #if REGEX_DEBUG
  377. s_regex_dbg.print_opcode("VM", opcode, state, recursion_level, false);
  378. #endif
  379. ExecutionResult result;
  380. if (input.fail_counter > 0) {
  381. --input.fail_counter;
  382. result = ExecutionResult::Failed_ExecuteLowPrioForks;
  383. } else {
  384. result = opcode.execute(input, state);
  385. }
  386. #if REGEX_DEBUG
  387. s_regex_dbg.print_result(opcode, bytecode, input, state, result);
  388. #endif
  389. state.instruction_position += opcode.size();
  390. switch (result) {
  391. case ExecutionResult::Fork_PrioLow: {
  392. bool found = false;
  393. if (input.fork_to_replace.has_value()) {
  394. for (auto it = states_to_try_next.reverse_begin(); it != states_to_try_next.reverse_end(); ++it) {
  395. if (it->initiating_fork == input.fork_to_replace.value()) {
  396. (*it) = state;
  397. it->instruction_position = state.fork_at_position;
  398. it->initiating_fork = *input.fork_to_replace;
  399. found = true;
  400. break;
  401. }
  402. }
  403. input.fork_to_replace.clear();
  404. }
  405. if (!found) {
  406. states_to_try_next.append(state);
  407. states_to_try_next.last().initiating_fork = state.instruction_position - opcode.size();
  408. states_to_try_next.last().instruction_position = state.fork_at_position;
  409. }
  410. continue;
  411. }
  412. case ExecutionResult::Fork_PrioHigh: {
  413. bool found = false;
  414. if (input.fork_to_replace.has_value()) {
  415. for (auto it = states_to_try_next.reverse_begin(); it != states_to_try_next.reverse_end(); ++it) {
  416. if (it->initiating_fork == input.fork_to_replace.value()) {
  417. (*it) = state;
  418. it->initiating_fork = *input.fork_to_replace;
  419. found = true;
  420. break;
  421. }
  422. }
  423. input.fork_to_replace.clear();
  424. }
  425. if (!found) {
  426. states_to_try_next.append(state);
  427. states_to_try_next.last().initiating_fork = state.instruction_position - opcode.size();
  428. }
  429. state.instruction_position = state.fork_at_position;
  430. #if REGEX_DEBUG
  431. ++recursion_level;
  432. #endif
  433. continue;
  434. }
  435. case ExecutionResult::Continue:
  436. continue;
  437. case ExecutionResult::Succeeded:
  438. return true;
  439. case ExecutionResult::Failed:
  440. if (!states_to_try_next.is_empty()) {
  441. state = states_to_try_next.take_last();
  442. continue;
  443. }
  444. return false;
  445. case ExecutionResult::Failed_ExecuteLowPrioForks: {
  446. if (states_to_try_next.is_empty()) {
  447. return false;
  448. }
  449. state = states_to_try_next.take_last();
  450. #if REGEX_DEBUG
  451. ++recursion_level;
  452. #endif
  453. continue;
  454. }
  455. }
  456. }
  457. VERIFY_NOT_REACHED();
  458. }
  459. template class Matcher<PosixBasicParser>;
  460. template class Regex<PosixBasicParser>;
  461. template class Matcher<PosixExtendedParser>;
  462. template class Regex<PosixExtendedParser>;
  463. template class Matcher<ECMA262Parser>;
  464. template class Regex<ECMA262Parser>;
  465. }