RegexOptimizer.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.h>
  7. #include <AK/RedBlackTree.h>
  8. #include <AK/Stack.h>
  9. #include <LibRegex/Regex.h>
  10. #include <LibRegex/RegexBytecodeStreamOptimizer.h>
  11. namespace regex {
  12. using Detail::Block;
  13. template<typename Parser>
  14. void Regex<Parser>::run_optimization_passes()
  15. {
  16. parser_result.bytecode.flatten();
  17. // Rewrite fork loops as atomic groups
  18. // e.g. a*b -> (ATOMIC a*)b
  19. attempt_rewrite_loops_as_atomic_groups(split_basic_blocks(parser_result.bytecode));
  20. parser_result.bytecode.flatten();
  21. }
  22. template<typename Parser>
  23. typename Regex<Parser>::BasicBlockList Regex<Parser>::split_basic_blocks(ByteCode const& bytecode)
  24. {
  25. BasicBlockList block_boundaries;
  26. size_t end_of_last_block = 0;
  27. auto bytecode_size = bytecode.size();
  28. MatchState state;
  29. state.instruction_position = 0;
  30. auto check_jump = [&]<typename T>(OpCode const& opcode) {
  31. auto& op = static_cast<T const&>(opcode);
  32. ssize_t jump_offset = op.size() + op.offset();
  33. if (jump_offset >= 0) {
  34. block_boundaries.append({ end_of_last_block, state.instruction_position });
  35. end_of_last_block = state.instruction_position + opcode.size();
  36. } else {
  37. // This op jumps back, see if that's within this "block".
  38. if (jump_offset + state.instruction_position > end_of_last_block) {
  39. // Split the block!
  40. block_boundaries.append({ end_of_last_block, jump_offset + state.instruction_position });
  41. block_boundaries.append({ jump_offset + state.instruction_position, state.instruction_position });
  42. end_of_last_block = state.instruction_position + opcode.size();
  43. } else {
  44. // Nope, it's just a jump to another block
  45. block_boundaries.append({ end_of_last_block, state.instruction_position });
  46. end_of_last_block = state.instruction_position + opcode.size();
  47. }
  48. }
  49. };
  50. for (;;) {
  51. auto& opcode = bytecode.get_opcode(state);
  52. switch (opcode.opcode_id()) {
  53. case OpCodeId::Jump:
  54. check_jump.template operator()<OpCode_Jump>(opcode);
  55. break;
  56. case OpCodeId::JumpNonEmpty:
  57. check_jump.template operator()<OpCode_JumpNonEmpty>(opcode);
  58. break;
  59. case OpCodeId::ForkJump:
  60. check_jump.template operator()<OpCode_ForkJump>(opcode);
  61. break;
  62. case OpCodeId::ForkStay:
  63. check_jump.template operator()<OpCode_ForkStay>(opcode);
  64. break;
  65. case OpCodeId::FailForks:
  66. block_boundaries.append({ end_of_last_block, state.instruction_position });
  67. end_of_last_block = state.instruction_position + opcode.size();
  68. break;
  69. case OpCodeId::Repeat: {
  70. // Repeat produces two blocks, one containing its repeated expr, and one after that.
  71. auto repeat_start = state.instruction_position - static_cast<OpCode_Repeat const&>(opcode).offset();
  72. if (repeat_start > end_of_last_block)
  73. block_boundaries.append({ end_of_last_block, repeat_start });
  74. block_boundaries.append({ repeat_start, state.instruction_position });
  75. end_of_last_block = state.instruction_position + opcode.size();
  76. break;
  77. }
  78. default:
  79. break;
  80. }
  81. auto next_ip = state.instruction_position + opcode.size();
  82. if (next_ip < bytecode_size)
  83. state.instruction_position = next_ip;
  84. else
  85. break;
  86. }
  87. if (end_of_last_block < bytecode_size)
  88. block_boundaries.append({ end_of_last_block, bytecode_size });
  89. quick_sort(block_boundaries, [](auto& a, auto& b) { return a.start < b.start; });
  90. return block_boundaries;
  91. }
  92. enum class AtomicRewritePreconditionResult {
  93. SatisfiedWithProperHeader,
  94. SatisfiedWithEmptyHeader,
  95. NotSatisfied,
  96. };
  97. static AtomicRewritePreconditionResult block_satisfies_atomic_rewrite_precondition(ByteCode const& bytecode, Block const& repeated_block, Block const& following_block)
  98. {
  99. Vector<Vector<CompareTypeAndValuePair>> repeated_values;
  100. HashTable<size_t> active_capture_groups;
  101. MatchState state;
  102. for (state.instruction_position = repeated_block.start; state.instruction_position < repeated_block.end;) {
  103. auto& opcode = bytecode.get_opcode(state);
  104. switch (opcode.opcode_id()) {
  105. case OpCodeId::Compare: {
  106. auto compares = static_cast<OpCode_Compare const&>(opcode).flat_compares();
  107. if (repeated_values.is_empty() && any_of(compares, [](auto& compare) { return compare.type == CharacterCompareType::AnyChar; }))
  108. return AtomicRewritePreconditionResult::NotSatisfied;
  109. repeated_values.append(move(compares));
  110. break;
  111. }
  112. case OpCodeId::CheckBegin:
  113. case OpCodeId::CheckEnd:
  114. if (repeated_values.is_empty())
  115. return AtomicRewritePreconditionResult::SatisfiedWithProperHeader;
  116. break;
  117. case OpCodeId::CheckBoundary:
  118. // FIXME: What should we do with these? for now, let's fail.
  119. return AtomicRewritePreconditionResult::NotSatisfied;
  120. case OpCodeId::Restore:
  121. case OpCodeId::GoBack:
  122. return AtomicRewritePreconditionResult::NotSatisfied;
  123. case OpCodeId::SaveRightCaptureGroup:
  124. active_capture_groups.set(static_cast<OpCode_SaveRightCaptureGroup const&>(opcode).id());
  125. break;
  126. case OpCodeId::SaveLeftCaptureGroup:
  127. active_capture_groups.set(static_cast<OpCode_SaveLeftCaptureGroup const&>(opcode).id());
  128. break;
  129. default:
  130. break;
  131. }
  132. state.instruction_position += opcode.size();
  133. }
  134. dbgln_if(REGEX_DEBUG, "Found {} entries in reference", repeated_values.size());
  135. dbgln_if(REGEX_DEBUG, "Found {} active capture groups", active_capture_groups.size());
  136. bool following_block_has_at_least_one_compare = false;
  137. // Find the first compare in the following block, it must NOT match any of the values in `repeated_values'.
  138. for (state.instruction_position = following_block.start; state.instruction_position < following_block.end;) {
  139. auto& opcode = bytecode.get_opcode(state);
  140. switch (opcode.opcode_id()) {
  141. // Note: These have to exist since we're effectively repeating the following block as well
  142. case OpCodeId::SaveRightCaptureGroup:
  143. active_capture_groups.set(static_cast<OpCode_SaveRightCaptureGroup const&>(opcode).id());
  144. break;
  145. case OpCodeId::SaveLeftCaptureGroup:
  146. active_capture_groups.set(static_cast<OpCode_SaveLeftCaptureGroup const&>(opcode).id());
  147. break;
  148. case OpCodeId::Compare: {
  149. following_block_has_at_least_one_compare = true;
  150. // We found a compare, let's see what it has.
  151. auto compares = static_cast<OpCode_Compare const&>(opcode).flat_compares();
  152. if (compares.is_empty())
  153. break;
  154. if (any_of(compares, [&](auto& compare) {
  155. return compare.type == CharacterCompareType::AnyChar
  156. || (compare.type == CharacterCompareType::Reference && active_capture_groups.contains(compare.value));
  157. }))
  158. return AtomicRewritePreconditionResult::NotSatisfied;
  159. for (auto& repeated_value : repeated_values) {
  160. // FIXME: This is too naive!
  161. if (any_of(repeated_value, [](auto& compare) { return compare.type == CharacterCompareType::AnyChar; }))
  162. return AtomicRewritePreconditionResult::NotSatisfied;
  163. for (auto& repeated_compare : repeated_value) {
  164. // FIXME: This is too naive! it will miss _tons_ of cases since it doesn't check ranges!
  165. if (any_of(compares, [&](auto& compare) { return compare.type == repeated_compare.type && compare.value == repeated_compare.value; }))
  166. return AtomicRewritePreconditionResult::NotSatisfied;
  167. }
  168. }
  169. return AtomicRewritePreconditionResult::SatisfiedWithProperHeader;
  170. }
  171. case OpCodeId::CheckBegin:
  172. case OpCodeId::CheckEnd:
  173. return AtomicRewritePreconditionResult::SatisfiedWithProperHeader; // Nothing can match the end!
  174. case OpCodeId::CheckBoundary:
  175. // FIXME: What should we do with these? For now, consider them a failure.
  176. return AtomicRewritePreconditionResult::NotSatisfied;
  177. default:
  178. break;
  179. }
  180. state.instruction_position += opcode.size();
  181. }
  182. if (following_block_has_at_least_one_compare)
  183. return AtomicRewritePreconditionResult::SatisfiedWithProperHeader;
  184. return AtomicRewritePreconditionResult::SatisfiedWithEmptyHeader;
  185. }
  186. template<typename Parser>
  187. void Regex<Parser>::attempt_rewrite_loops_as_atomic_groups(BasicBlockList const& basic_blocks)
  188. {
  189. auto& bytecode = parser_result.bytecode;
  190. if constexpr (REGEX_DEBUG) {
  191. RegexDebug dbg;
  192. dbg.print_bytecode(*this);
  193. for (auto const& block : basic_blocks)
  194. dbgln("block from {} to {}", block.start, block.end);
  195. }
  196. // A pattern such as:
  197. // bb0 | RE0
  198. // | ForkX bb0
  199. // -------------------------
  200. // bb1 | RE1
  201. // can be rewritten as:
  202. // loop.hdr | ForkStay bb1 (if RE1 matches _something_, empty otherwise)
  203. // -------------------------
  204. // bb0 | RE0
  205. // | ForkReplaceX bb0
  206. // -------------------------
  207. // bb1 | RE1
  208. // provided that first(RE1) not-in end(RE0), which is to say
  209. // that RE1 cannot start with whatever RE0 has matched (ever).
  210. //
  211. // Alternatively, a second form of this pattern can also occur:
  212. // bb0 | *
  213. // | ForkX bb2
  214. // ------------------------
  215. // bb1 | RE0
  216. // | Jump bb0
  217. // ------------------------
  218. // bb2 | RE1
  219. // which can be transformed (with the same preconditions) to:
  220. // bb0 | *
  221. // | ForkReplaceX bb2
  222. // ------------------------
  223. // bb1 | RE0
  224. // | Jump bb0
  225. // ------------------------
  226. // bb2 | RE1
  227. enum class AlternateForm {
  228. DirectLoopWithoutHeader, // loop without proper header, a block forking to itself. i.e. the first form.
  229. DirectLoopWithoutHeaderAndEmptyFollow, // loop without proper header, a block forking to itself. i.e. the first form but with RE1 being empty.
  230. DirectLoopWithHeader, // loop with proper header, i.e. the second form.
  231. };
  232. struct CandidateBlock {
  233. Block forking_block;
  234. Optional<Block> new_target_block;
  235. AlternateForm form;
  236. };
  237. Vector<CandidateBlock> candidate_blocks;
  238. auto is_an_eligible_jump = [](OpCode const& opcode, size_t ip, size_t block_start, AlternateForm alternate_form) {
  239. switch (opcode.opcode_id()) {
  240. case OpCodeId::JumpNonEmpty: {
  241. auto const& op = static_cast<OpCode_JumpNonEmpty const&>(opcode);
  242. auto form = op.form();
  243. if (form != OpCodeId::Jump && alternate_form == AlternateForm::DirectLoopWithHeader)
  244. return false;
  245. if (form != OpCodeId::ForkJump && form != OpCodeId::ForkStay && alternate_form == AlternateForm::DirectLoopWithoutHeader)
  246. return false;
  247. return op.offset() + ip + opcode.size() == block_start;
  248. }
  249. case OpCodeId::ForkJump:
  250. if (alternate_form == AlternateForm::DirectLoopWithHeader)
  251. return false;
  252. return static_cast<OpCode_ForkJump const&>(opcode).offset() + ip + opcode.size() == block_start;
  253. case OpCodeId::ForkStay:
  254. if (alternate_form == AlternateForm::DirectLoopWithHeader)
  255. return false;
  256. return static_cast<OpCode_ForkStay const&>(opcode).offset() + ip + opcode.size() == block_start;
  257. case OpCodeId::Jump:
  258. // Infinite loop does *not* produce forks.
  259. if (alternate_form == AlternateForm::DirectLoopWithoutHeader)
  260. return false;
  261. if (alternate_form == AlternateForm::DirectLoopWithHeader)
  262. return static_cast<OpCode_Jump const&>(opcode).offset() + ip + opcode.size() == block_start;
  263. VERIFY_NOT_REACHED();
  264. default:
  265. return false;
  266. }
  267. };
  268. for (size_t i = 0; i < basic_blocks.size(); ++i) {
  269. auto forking_block = basic_blocks[i];
  270. Optional<Block> fork_fallback_block;
  271. if (i + 1 < basic_blocks.size())
  272. fork_fallback_block = basic_blocks[i + 1];
  273. MatchState state;
  274. // Check if the last instruction in this block is a jump to the block itself:
  275. {
  276. state.instruction_position = forking_block.end;
  277. auto& opcode = bytecode.get_opcode(state);
  278. if (is_an_eligible_jump(opcode, state.instruction_position, forking_block.start, AlternateForm::DirectLoopWithoutHeader)) {
  279. // We've found RE0 (and RE1 is just the following block, if any), let's see if the precondition applies.
  280. // if RE1 is empty, there's no first(RE1), so this is an automatic pass.
  281. if (!fork_fallback_block.has_value() || fork_fallback_block->end == fork_fallback_block->start) {
  282. candidate_blocks.append({ forking_block, fork_fallback_block, AlternateForm::DirectLoopWithoutHeader });
  283. break;
  284. }
  285. auto precondition = block_satisfies_atomic_rewrite_precondition(bytecode, forking_block, *fork_fallback_block);
  286. if (precondition == AtomicRewritePreconditionResult::SatisfiedWithProperHeader) {
  287. candidate_blocks.append({ forking_block, fork_fallback_block, AlternateForm::DirectLoopWithoutHeader });
  288. break;
  289. }
  290. if (precondition == AtomicRewritePreconditionResult::SatisfiedWithEmptyHeader) {
  291. candidate_blocks.append({ forking_block, fork_fallback_block, AlternateForm::DirectLoopWithoutHeaderAndEmptyFollow });
  292. break;
  293. }
  294. }
  295. }
  296. // Check if the last instruction in the last block is a direct jump to this block
  297. if (fork_fallback_block.has_value()) {
  298. state.instruction_position = fork_fallback_block->end;
  299. auto& opcode = bytecode.get_opcode(state);
  300. if (is_an_eligible_jump(opcode, state.instruction_position, forking_block.start, AlternateForm::DirectLoopWithHeader)) {
  301. // We've found bb1 and bb0, let's just make sure that bb0 forks to bb2.
  302. state.instruction_position = forking_block.end;
  303. auto& opcode = bytecode.get_opcode(state);
  304. if (opcode.opcode_id() == OpCodeId::ForkJump || opcode.opcode_id() == OpCodeId::ForkStay) {
  305. Optional<Block> block_following_fork_fallback;
  306. if (i + 2 < basic_blocks.size())
  307. block_following_fork_fallback = basic_blocks[i + 2];
  308. if (!block_following_fork_fallback.has_value()
  309. || block_satisfies_atomic_rewrite_precondition(bytecode, *fork_fallback_block, *block_following_fork_fallback) != AtomicRewritePreconditionResult::NotSatisfied) {
  310. candidate_blocks.append({ forking_block, {}, AlternateForm::DirectLoopWithHeader });
  311. break;
  312. }
  313. }
  314. }
  315. }
  316. }
  317. dbgln_if(REGEX_DEBUG, "Found {} candidate blocks", candidate_blocks.size());
  318. if (candidate_blocks.is_empty()) {
  319. dbgln_if(REGEX_DEBUG, "Failed to find anything for {}", pattern_value);
  320. return;
  321. }
  322. RedBlackTree<size_t, size_t> needed_patches;
  323. // Reverse the blocks, so we can patch the bytecode without messing with the latter patches.
  324. quick_sort(candidate_blocks, [](auto& a, auto& b) { return b.forking_block.start > a.forking_block.start; });
  325. for (auto& candidate : candidate_blocks) {
  326. // Note that both forms share a ForkReplace patch in forking_block.
  327. // Patch the ForkX in forking_block to be a ForkReplaceX instead.
  328. auto& opcode_id = bytecode[candidate.forking_block.end];
  329. if (opcode_id == (ByteCodeValueType)OpCodeId::ForkStay) {
  330. opcode_id = (ByteCodeValueType)OpCodeId::ForkReplaceStay;
  331. } else if (opcode_id == (ByteCodeValueType)OpCodeId::ForkJump) {
  332. opcode_id = (ByteCodeValueType)OpCodeId::ForkReplaceJump;
  333. } else if (opcode_id == (ByteCodeValueType)OpCodeId::JumpNonEmpty) {
  334. auto& jump_opcode_id = bytecode[candidate.forking_block.end + 3];
  335. if (jump_opcode_id == (ByteCodeValueType)OpCodeId::ForkStay)
  336. jump_opcode_id = (ByteCodeValueType)OpCodeId::ForkReplaceStay;
  337. else if (jump_opcode_id == (ByteCodeValueType)OpCodeId::ForkJump)
  338. jump_opcode_id = (ByteCodeValueType)OpCodeId::ForkReplaceJump;
  339. else
  340. VERIFY_NOT_REACHED();
  341. } else {
  342. VERIFY_NOT_REACHED();
  343. }
  344. if (candidate.form == AlternateForm::DirectLoopWithoutHeader) {
  345. if (candidate.new_target_block.has_value()) {
  346. // Insert a fork-stay targeted at the second block.
  347. bytecode.insert(candidate.forking_block.start, (ByteCodeValueType)OpCodeId::ForkStay);
  348. bytecode.insert(candidate.forking_block.start + 1, candidate.new_target_block->start - candidate.forking_block.start);
  349. needed_patches.insert(candidate.forking_block.start, 2u);
  350. }
  351. }
  352. }
  353. if (!needed_patches.is_empty()) {
  354. MatchState state;
  355. auto bytecode_size = bytecode.size();
  356. state.instruction_position = 0;
  357. struct Patch {
  358. ssize_t value;
  359. size_t offset;
  360. bool should_negate { false };
  361. };
  362. for (;;) {
  363. if (state.instruction_position >= bytecode_size)
  364. break;
  365. auto& opcode = bytecode.get_opcode(state);
  366. Stack<Patch, 2> patch_points;
  367. switch (opcode.opcode_id()) {
  368. case OpCodeId::Jump:
  369. patch_points.push({ static_cast<OpCode_Jump const&>(opcode).offset(), state.instruction_position + 1 });
  370. break;
  371. case OpCodeId::JumpNonEmpty:
  372. patch_points.push({ static_cast<OpCode_JumpNonEmpty const&>(opcode).offset(), state.instruction_position + 1 });
  373. patch_points.push({ static_cast<OpCode_JumpNonEmpty const&>(opcode).checkpoint(), state.instruction_position + 2 });
  374. break;
  375. case OpCodeId::ForkJump:
  376. patch_points.push({ static_cast<OpCode_ForkJump const&>(opcode).offset(), state.instruction_position + 1 });
  377. break;
  378. case OpCodeId::ForkStay:
  379. patch_points.push({ static_cast<OpCode_ForkStay const&>(opcode).offset(), state.instruction_position + 1 });
  380. break;
  381. case OpCodeId::Repeat:
  382. patch_points.push({ -(ssize_t) static_cast<OpCode_Repeat const&>(opcode).offset(), state.instruction_position + 1, true });
  383. break;
  384. default:
  385. break;
  386. }
  387. while (!patch_points.is_empty()) {
  388. auto& patch_point = patch_points.top();
  389. auto target_offset = patch_point.value + state.instruction_position + opcode.size();
  390. constexpr auto do_patch = [](auto& patch_it, auto& patch_point, auto& target_offset, auto& bytecode, auto ip) {
  391. if (patch_it.key() == ip)
  392. return;
  393. if (patch_point.value < 0 && target_offset < patch_it.key() && ip > patch_it.key())
  394. bytecode[patch_point.offset] += (patch_point.should_negate ? 1 : -1) * (*patch_it);
  395. else if (patch_point.value > 0 && target_offset > patch_it.key() && ip < patch_it.key())
  396. bytecode[patch_point.offset] += (patch_point.should_negate ? -1 : 1) * (*patch_it);
  397. };
  398. if (auto patch_it = needed_patches.find_largest_not_above_iterator(target_offset); !patch_it.is_end())
  399. do_patch(patch_it, patch_point, target_offset, bytecode, state.instruction_position);
  400. else if (auto patch_it = needed_patches.find_largest_not_above_iterator(state.instruction_position); !patch_it.is_end())
  401. do_patch(patch_it, patch_point, target_offset, bytecode, state.instruction_position);
  402. patch_points.pop();
  403. }
  404. state.instruction_position += opcode.size();
  405. }
  406. }
  407. if constexpr (REGEX_DEBUG) {
  408. warnln("Transformed to:");
  409. RegexDebug dbg;
  410. dbg.print_bytecode(*this);
  411. }
  412. }
  413. void Optimizer::append_alternation(ByteCode& target, ByteCode&& left, ByteCode&& right)
  414. {
  415. auto left_is_empty = left.is_empty();
  416. auto right_is_empty = right.is_empty();
  417. if (left_is_empty || right_is_empty) {
  418. if (left_is_empty && right_is_empty)
  419. return;
  420. // ForkJump right (+ left.size() + 2 + right.size())
  421. // (left)
  422. // Jump end (+ right.size())
  423. // (right)
  424. // LABEL end
  425. target.append(static_cast<ByteCodeValueType>(OpCodeId::ForkJump));
  426. target.append(left.size() + 2 + right.size());
  427. target.extend(move(left));
  428. target.append(static_cast<ByteCodeValueType>(OpCodeId::Jump));
  429. target.append(right.size());
  430. target.extend(move(right));
  431. return;
  432. }
  433. left.flatten();
  434. right.flatten();
  435. auto left_blocks = Regex<PosixBasicParser>::split_basic_blocks(left);
  436. auto right_blocks = Regex<PosixBasicParser>::split_basic_blocks(right);
  437. size_t left_skip = 0;
  438. MatchState state;
  439. for (size_t block_index = 0; block_index < left_blocks.size() && block_index < right_blocks.size(); block_index++) {
  440. auto& left_block = left_blocks[block_index];
  441. auto& right_block = right_blocks[block_index];
  442. auto left_end = block_index + 1 == left_blocks.size() ? left_block.end : left_blocks[block_index + 1].start;
  443. auto right_end = block_index + 1 == right_blocks.size() ? right_block.end : right_blocks[block_index + 1].start;
  444. if (left_end - left_block.start != right_end - right_block.start)
  445. break;
  446. if (left.spans().slice(left_block.start, left_end - left_block.start) != right.spans().slice(right_block.start, right_end - right_block.start))
  447. break;
  448. left_skip = left_end;
  449. }
  450. dbgln_if(REGEX_DEBUG, "Skipping {}/{} bytecode entries from {}/{}", left_skip, 0, left.size(), right.size());
  451. if (left_skip > 0) {
  452. target.extend(left.release_slice(left_blocks.first().start, left_skip));
  453. right = right.release_slice(left_skip);
  454. }
  455. auto left_size = left.size();
  456. target.empend(static_cast<ByteCodeValueType>(OpCodeId::ForkJump));
  457. target.empend(right.size() + (left_size > 0 ? 2 : 0)); // Jump to the _ALT label
  458. target.extend(move(right));
  459. if (left_size != 0) {
  460. target.empend(static_cast<ByteCodeValueType>(OpCodeId::Jump));
  461. target.empend(left.size()); // Jump to the _END label
  462. }
  463. // LABEL _ALT = bytecode.size() + 2
  464. target.extend(move(left));
  465. // LABEL _END = alterantive_bytecode.size
  466. }
  467. enum class LookupTableInsertionOutcome {
  468. Successful,
  469. ReplaceWithAnyChar,
  470. TemporaryInversionNeeded,
  471. PermanentInversionNeeded,
  472. CannotPlaceInTable,
  473. };
  474. static LookupTableInsertionOutcome insert_into_lookup_table(RedBlackTree<ByteCodeValueType, CharRange>& table, CompareTypeAndValuePair pair)
  475. {
  476. switch (pair.type) {
  477. case CharacterCompareType::Inverse:
  478. return LookupTableInsertionOutcome::PermanentInversionNeeded;
  479. case CharacterCompareType::TemporaryInverse:
  480. return LookupTableInsertionOutcome::TemporaryInversionNeeded;
  481. case CharacterCompareType::AnyChar:
  482. return LookupTableInsertionOutcome::ReplaceWithAnyChar;
  483. case CharacterCompareType::CharClass:
  484. return LookupTableInsertionOutcome::CannotPlaceInTable;
  485. case CharacterCompareType::Char:
  486. table.insert(pair.value, { (u32)pair.value, (u32)pair.value });
  487. break;
  488. case CharacterCompareType::CharRange: {
  489. CharRange range { pair.value };
  490. table.insert(range.from, range);
  491. break;
  492. }
  493. case CharacterCompareType::Reference:
  494. case CharacterCompareType::Property:
  495. case CharacterCompareType::GeneralCategory:
  496. case CharacterCompareType::Script:
  497. case CharacterCompareType::ScriptExtension:
  498. return LookupTableInsertionOutcome::CannotPlaceInTable;
  499. case CharacterCompareType::Undefined:
  500. case CharacterCompareType::RangeExpressionDummy:
  501. case CharacterCompareType::String:
  502. case CharacterCompareType::LookupTable:
  503. VERIFY_NOT_REACHED();
  504. }
  505. return LookupTableInsertionOutcome::Successful;
  506. }
  507. void Optimizer::append_character_class(ByteCode& target, Vector<CompareTypeAndValuePair>&& pairs)
  508. {
  509. ByteCode arguments;
  510. size_t argument_count = 0;
  511. if (pairs.size() <= 1) {
  512. for (auto& pair : pairs) {
  513. arguments.append(to_underlying(pair.type));
  514. if (pair.type != CharacterCompareType::AnyChar && pair.type != CharacterCompareType::TemporaryInverse && pair.type != CharacterCompareType::Inverse)
  515. arguments.append(pair.value);
  516. ++argument_count;
  517. }
  518. } else {
  519. RedBlackTree<ByteCodeValueType, CharRange> table;
  520. RedBlackTree<ByteCodeValueType, CharRange> inverted_table;
  521. auto* current_table = &table;
  522. auto* current_inverted_table = &inverted_table;
  523. bool invert_for_next_iteration = false;
  524. bool is_currently_inverted = false;
  525. for (auto& value : pairs) {
  526. auto should_invert_after_this_iteration = invert_for_next_iteration;
  527. invert_for_next_iteration = false;
  528. auto insertion_result = insert_into_lookup_table(*current_table, value);
  529. switch (insertion_result) {
  530. case LookupTableInsertionOutcome::Successful:
  531. break;
  532. case LookupTableInsertionOutcome::ReplaceWithAnyChar: {
  533. table.clear();
  534. inverted_table.clear();
  535. arguments.append(to_underlying(CharacterCompareType::AnyChar));
  536. ++argument_count;
  537. break;
  538. }
  539. case LookupTableInsertionOutcome::TemporaryInversionNeeded:
  540. swap(current_table, current_inverted_table);
  541. invert_for_next_iteration = true;
  542. is_currently_inverted = !is_currently_inverted;
  543. break;
  544. case LookupTableInsertionOutcome::PermanentInversionNeeded:
  545. swap(current_table, current_inverted_table);
  546. is_currently_inverted = !is_currently_inverted;
  547. break;
  548. case LookupTableInsertionOutcome::CannotPlaceInTable:
  549. if (is_currently_inverted) {
  550. arguments.append(to_underlying(CharacterCompareType::TemporaryInverse));
  551. ++argument_count;
  552. }
  553. arguments.append(to_underlying(value.type));
  554. arguments.append(value.value);
  555. ++argument_count;
  556. break;
  557. }
  558. if (should_invert_after_this_iteration) {
  559. swap(current_table, current_inverted_table);
  560. is_currently_inverted = !is_currently_inverted;
  561. }
  562. }
  563. auto append_table = [&](auto& table) {
  564. ++argument_count;
  565. arguments.append(to_underlying(CharacterCompareType::LookupTable));
  566. auto size_index = arguments.size();
  567. arguments.append(0);
  568. Optional<CharRange> active_range;
  569. size_t range_count = 0;
  570. for (auto& range : table) {
  571. if (!active_range.has_value()) {
  572. active_range = range;
  573. continue;
  574. }
  575. if (range.from <= active_range->to + 1 && range.to + 1 >= active_range->from) {
  576. active_range = CharRange { min(range.from, active_range->from), max(range.to, active_range->to) };
  577. } else {
  578. ++range_count;
  579. arguments.append(active_range.release_value());
  580. active_range = range;
  581. }
  582. }
  583. if (active_range.has_value()) {
  584. ++range_count;
  585. arguments.append(active_range.release_value());
  586. }
  587. arguments[size_index] = range_count;
  588. };
  589. if (!table.is_empty())
  590. append_table(table);
  591. if (!inverted_table.is_empty()) {
  592. ++argument_count;
  593. arguments.append(to_underlying(CharacterCompareType::TemporaryInverse));
  594. append_table(inverted_table);
  595. }
  596. }
  597. target.empend(static_cast<ByteCodeValueType>(OpCodeId::Compare));
  598. target.empend(argument_count); // number of arguments
  599. target.empend(arguments.size()); // size of arguments
  600. target.extend(move(arguments));
  601. }
  602. template void Regex<PosixBasicParser>::run_optimization_passes();
  603. template void Regex<PosixExtendedParser>::run_optimization_passes();
  604. template void Regex<ECMA262Parser>::run_optimization_passes();
  605. }