RegexMatcher.cpp 18 KB

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