RegexMatcher.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. #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(String 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. if (parser_result.error == regex::Error::NoError)
  34. matcher = make<Matcher<Parser>>(this, regex_options);
  35. }
  36. template<class Parser>
  37. Regex<Parser>::Regex(regex::Parser::Result parse_result, String pattern, typename ParserTraits<Parser>::OptionsType regex_options)
  38. : pattern_value(move(pattern))
  39. , parser_result(move(parse_result))
  40. {
  41. if (parser_result.error == regex::Error::NoError)
  42. matcher = make<Matcher<Parser>>(this, regex_options);
  43. }
  44. template<class Parser>
  45. Regex<Parser>::Regex(Regex&& regex)
  46. : pattern_value(move(regex.pattern_value))
  47. , parser_result(move(regex.parser_result))
  48. , matcher(move(regex.matcher))
  49. , start_offset(regex.start_offset)
  50. {
  51. if (matcher)
  52. matcher->reset_pattern({}, this);
  53. }
  54. template<class Parser>
  55. Regex<Parser>& Regex<Parser>::operator=(Regex&& regex)
  56. {
  57. pattern_value = move(regex.pattern_value);
  58. parser_result = move(regex.parser_result);
  59. matcher = move(regex.matcher);
  60. if (matcher)
  61. matcher->reset_pattern({}, this);
  62. start_offset = regex.start_offset;
  63. return *this;
  64. }
  65. template<class Parser>
  66. typename ParserTraits<Parser>::OptionsType Regex<Parser>::options() const
  67. {
  68. if (!matcher || parser_result.error != Error::NoError)
  69. return {};
  70. return matcher->options();
  71. }
  72. template<class Parser>
  73. String Regex<Parser>::error_string(Optional<String> message) const
  74. {
  75. StringBuilder eb;
  76. eb.append("Error during parsing of regular expression:\n");
  77. eb.appendff(" {}\n ", pattern_value);
  78. for (size_t i = 0; i < parser_result.error_token.position(); ++i)
  79. eb.append(' ');
  80. eb.appendff("^---- {}", message.value_or(get_error_string(parser_result.error)));
  81. return eb.build();
  82. }
  83. template<typename Parser>
  84. RegexResult Matcher<Parser>::match(RegexStringView const& view, Optional<typename ParserTraits<Parser>::OptionsType> regex_options) const
  85. {
  86. AllOptions options = m_regex_options | regex_options.value_or({}).value();
  87. if (options.has_flag_set(AllFlags::Multiline))
  88. 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...
  89. Vector<RegexStringView> views;
  90. views.append(view);
  91. return match(views, regex_options);
  92. }
  93. template<typename Parser>
  94. RegexResult Matcher<Parser>::match(Vector<RegexStringView> const& views, Optional<typename ParserTraits<Parser>::OptionsType> regex_options) const
  95. {
  96. // If the pattern *itself* isn't stateful, reset any changes to start_offset.
  97. if (!((AllFlags)m_regex_options.value() & AllFlags::Internal_Stateful))
  98. m_pattern->start_offset = 0;
  99. size_t match_count { 0 };
  100. MatchInput input;
  101. MatchState state;
  102. MatchOutput output;
  103. input.regex_options = m_regex_options | regex_options.value_or({}).value();
  104. input.start_offset = m_pattern->start_offset;
  105. output.operations = 0;
  106. size_t lines_to_skip = 0;
  107. bool unicode = input.regex_options.has_flag_set(AllFlags::Unicode);
  108. for (auto& view : views)
  109. const_cast<RegexStringView&>(view).set_unicode(unicode);
  110. if (input.regex_options.has_flag_set(AllFlags::Internal_Stateful)) {
  111. if (views.size() > 1 && input.start_offset > views.first().length()) {
  112. dbgln_if(REGEX_DEBUG, "Started with start={}, goff={}, skip={}", input.start_offset, input.global_offset, lines_to_skip);
  113. for (auto& view : views) {
  114. if (input.start_offset < view.length() + 1)
  115. break;
  116. ++lines_to_skip;
  117. input.start_offset -= view.length() + 1;
  118. input.global_offset += view.length() + 1;
  119. }
  120. dbgln_if(REGEX_DEBUG, "Ended with start={}, goff={}, skip={}", input.start_offset, input.global_offset, lines_to_skip);
  121. }
  122. }
  123. if (c_match_preallocation_count) {
  124. state.matches.ensure_capacity(c_match_preallocation_count);
  125. state.capture_group_matches.ensure_capacity(c_match_preallocation_count);
  126. state.named_capture_group_matches.ensure_capacity(c_match_preallocation_count);
  127. auto& capture_groups_count = m_pattern->parser_result.capture_groups_count;
  128. auto& named_capture_groups_count = m_pattern->parser_result.named_capture_groups_count;
  129. for (size_t j = 0; j < c_match_preallocation_count; ++j) {
  130. state.matches.empend();
  131. state.capture_group_matches.unchecked_append({});
  132. state.capture_group_matches.at(j).ensure_capacity(capture_groups_count);
  133. for (size_t k = 0; k < capture_groups_count; ++k)
  134. state.capture_group_matches.at(j).unchecked_append({});
  135. state.named_capture_group_matches.unchecked_append({});
  136. state.named_capture_group_matches.at(j).ensure_capacity(named_capture_groups_count);
  137. }
  138. }
  139. auto append_match = [](auto& input, auto& state, auto& start_position) {
  140. if (state.matches.size() == input.match_index)
  141. state.matches.empend();
  142. VERIFY(start_position + state.string_position - start_position <= input.view.length());
  143. if (input.regex_options.has_flag_set(AllFlags::StringCopyMatches)) {
  144. 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 };
  145. } else { // let the view point to the original string ...
  146. 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 };
  147. }
  148. };
  149. #if REGEX_DEBUG
  150. s_regex_dbg.print_header();
  151. #endif
  152. bool continue_search = input.regex_options.has_flag_set(AllFlags::Global) || input.regex_options.has_flag_set(AllFlags::Multiline);
  153. if (input.regex_options.has_flag_set(AllFlags::Internal_Stateful))
  154. continue_search = false;
  155. for (auto& 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. bool succeeded = false;
  167. if (view_index == view_length && m_pattern->parser_result.match_length_minimum == 0) {
  168. // Run the code until it tries to consume something.
  169. // This allows non-consuming code to run on empty strings, for instance
  170. // e.g. "Exit"
  171. MatchOutput temp_output { output };
  172. input.column = match_count;
  173. input.match_index = match_count;
  174. state.string_position = view_index;
  175. state.instruction_position = 0;
  176. auto success = execute(input, state, temp_output);
  177. // This success is acceptable only if it doesn't read anything from the input (input length is 0).
  178. if (state.string_position <= view_index) {
  179. if (success.has_value() && success.value()) {
  180. output = move(temp_output);
  181. if (!match_count) {
  182. // Nothing was *actually* matched, so append an empty match.
  183. append_match(input, state, view_index);
  184. ++match_count;
  185. }
  186. }
  187. }
  188. }
  189. for (; view_index < view_length; ++view_index) {
  190. auto& match_length_minimum = m_pattern->parser_result.match_length_minimum;
  191. // FIXME: More performant would be to know the remaining minimum string
  192. // length needed to match from the current position onwards within
  193. // the vm. Add new OpCode for MinMatchLengthFromSp with the value of
  194. // the remaining string length from the current path. The value though
  195. // has to be filled in reverse. That implies a second run over bytecode
  196. // after generation has finished.
  197. if (match_length_minimum && match_length_minimum > view_length - view_index)
  198. break;
  199. input.column = match_count;
  200. input.match_index = match_count;
  201. state.string_position = view_index;
  202. state.instruction_position = 0;
  203. auto success = execute(input, state, output);
  204. if (!success.has_value())
  205. return { false, 0, {}, {}, {}, output.operations };
  206. if (success.value()) {
  207. succeeded = true;
  208. if (input.regex_options.has_flag_set(AllFlags::MatchNotEndOfLine) && state.string_position == input.view.length()) {
  209. if (!continue_search)
  210. break;
  211. continue;
  212. }
  213. if (input.regex_options.has_flag_set(AllFlags::MatchNotBeginOfLine) && view_index == 0) {
  214. if (!continue_search)
  215. break;
  216. continue;
  217. }
  218. dbgln_if(REGEX_DEBUG, "state.string_position={}, view_index={}", state.string_position, view_index);
  219. 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));
  220. ++match_count;
  221. if (continue_search) {
  222. append_match(input, state, view_index);
  223. bool has_zero_length = state.string_position == view_index;
  224. view_index = state.string_position - (has_zero_length ? 0 : 1);
  225. continue;
  226. } else if (input.regex_options.has_flag_set(AllFlags::Internal_Stateful)) {
  227. append_match(input, state, view_index);
  228. break;
  229. } else if (state.string_position < view_length) {
  230. return { false, 0, {}, {}, {}, output.operations };
  231. }
  232. append_match(input, state, view_index);
  233. break;
  234. }
  235. if (!continue_search)
  236. break;
  237. }
  238. ++input.line;
  239. input.global_offset += view.length() + 1; // +1 includes the line break character
  240. if (input.regex_options.has_flag_set(AllFlags::Internal_Stateful))
  241. m_pattern->start_offset = state.string_position;
  242. if (succeeded && !continue_search)
  243. break;
  244. }
  245. MatchOutput output_copy;
  246. if (match_count) {
  247. output_copy.capture_group_matches = state.capture_group_matches;
  248. // Make sure there are as many capture matches as there are actual matches.
  249. if (output_copy.capture_group_matches.size() < match_count)
  250. output_copy.capture_group_matches.resize(match_count);
  251. for (auto& matches : output_copy.capture_group_matches)
  252. matches.resize(m_pattern->parser_result.capture_groups_count + 1);
  253. if (!input.regex_options.has_flag_set(AllFlags::SkipTrimEmptyMatches)) {
  254. for (auto& matches : output_copy.capture_group_matches)
  255. matches.template remove_all_matching([](auto& match) { return match.view.is_null(); });
  256. }
  257. output_copy.named_capture_group_matches = state.named_capture_group_matches;
  258. // Make sure there are as many capture matches as there are actual matches.
  259. if (output_copy.named_capture_group_matches.size() < match_count)
  260. output_copy.named_capture_group_matches.resize(match_count);
  261. output_copy.matches = state.matches;
  262. } else {
  263. output_copy.capture_group_matches.clear_with_capacity();
  264. output_copy.named_capture_group_matches.clear_with_capacity();
  265. }
  266. return {
  267. match_count != 0,
  268. match_count,
  269. move(output_copy.matches),
  270. move(output_copy.capture_group_matches),
  271. move(output_copy.named_capture_group_matches),
  272. output.operations,
  273. m_pattern->parser_result.capture_groups_count,
  274. m_pattern->parser_result.named_capture_groups_count,
  275. };
  276. }
  277. template<typename T>
  278. class BumpAllocatedLinkedList {
  279. public:
  280. BumpAllocatedLinkedList() = default;
  281. ALWAYS_INLINE void append(T value)
  282. {
  283. auto new_node = m_allocator.allocate();
  284. VERIFY(new_node);
  285. auto node_ptr = new (new_node) Node { move(value), nullptr, nullptr };
  286. if (!m_first) {
  287. m_first = new_node;
  288. m_last = new_node;
  289. return;
  290. }
  291. node_ptr->previous = m_last;
  292. m_last->next = node_ptr;
  293. m_last = node_ptr;
  294. }
  295. ALWAYS_INLINE T take_last()
  296. {
  297. VERIFY(m_last);
  298. T value = move(m_last->value);
  299. if (m_last == m_first) {
  300. m_last = nullptr;
  301. m_first = nullptr;
  302. } else {
  303. m_last = m_last->previous;
  304. m_last->next = nullptr;
  305. }
  306. return value;
  307. }
  308. ALWAYS_INLINE T& last()
  309. {
  310. return m_last->value;
  311. }
  312. ALWAYS_INLINE bool is_empty() const
  313. {
  314. return m_first == nullptr;
  315. }
  316. private:
  317. struct Node {
  318. T value;
  319. Node* next { nullptr };
  320. Node* previous { nullptr };
  321. };
  322. UniformBumpAllocator<Node, true> m_allocator;
  323. Node* m_first { nullptr };
  324. Node* m_last { nullptr };
  325. };
  326. template<class Parser>
  327. Optional<bool> Matcher<Parser>::execute(MatchInput const& input, MatchState& state, MatchOutput& output) const
  328. {
  329. state.recursion_level = 0;
  330. BumpAllocatedLinkedList<MatchState> states_to_try_next;
  331. auto& bytecode = m_pattern->parser_result.bytecode;
  332. for (;;) {
  333. ++output.operations;
  334. auto& opcode = bytecode.get_opcode(state);
  335. #if REGEX_DEBUG
  336. s_regex_dbg.print_opcode("VM", opcode, state, state.recursion_level, false);
  337. #endif
  338. ExecutionResult result;
  339. if (input.fail_counter > 0) {
  340. --input.fail_counter;
  341. result = ExecutionResult::Failed_ExecuteLowPrioForks;
  342. } else {
  343. result = opcode.execute(input, state, output);
  344. }
  345. #if REGEX_DEBUG
  346. s_regex_dbg.print_result(opcode, bytecode, input, state, result);
  347. #endif
  348. state.instruction_position += opcode.size();
  349. switch (result) {
  350. case ExecutionResult::Fork_PrioLow:
  351. states_to_try_next.append(state);
  352. states_to_try_next.last().instruction_position = state.fork_at_position;
  353. continue;
  354. case ExecutionResult::Fork_PrioHigh:
  355. states_to_try_next.append(state);
  356. state.instruction_position = state.fork_at_position;
  357. ++state.recursion_level;
  358. continue;
  359. case ExecutionResult::Continue:
  360. continue;
  361. case ExecutionResult::Succeeded:
  362. return true;
  363. case ExecutionResult::Failed:
  364. if (!states_to_try_next.is_empty()) {
  365. state = states_to_try_next.take_last();
  366. continue;
  367. }
  368. return false;
  369. case ExecutionResult::Failed_ExecuteLowPrioForks: {
  370. if (states_to_try_next.is_empty()) {
  371. if (input.regex_options.has_flag_set(AllFlags::Internal_Stateful))
  372. return {};
  373. return false;
  374. }
  375. state = states_to_try_next.take_last();
  376. ++state.recursion_level;
  377. continue;
  378. }
  379. }
  380. }
  381. VERIFY_NOT_REACHED();
  382. }
  383. template class Matcher<PosixBasicParser>;
  384. template class Regex<PosixBasicParser>;
  385. template class Matcher<PosixExtendedParser>;
  386. template class Regex<PosixExtendedParser>;
  387. template class Matcher<ECMA262Parser>;
  388. template class Regex<ECMA262Parser>;
  389. }