RegexByteCode.h 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. /*
  2. * Copyright (c) 2020, Emanuel Sprung <emanuel.sprung@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include "RegexBytecodeStreamOptimizer.h"
  8. #include "RegexMatch.h"
  9. #include "RegexOptions.h"
  10. #include <AK/Concepts.h>
  11. #include <AK/DisjointChunks.h>
  12. #include <AK/Format.h>
  13. #include <AK/Forward.h>
  14. #include <AK/HashMap.h>
  15. #include <AK/NonnullOwnPtr.h>
  16. #include <AK/OwnPtr.h>
  17. #include <AK/Traits.h>
  18. #include <AK/TypeCasts.h>
  19. #include <AK/Types.h>
  20. #include <AK/Vector.h>
  21. #include <LibUnicode/Forward.h>
  22. namespace regex {
  23. using ByteCodeValueType = u64;
  24. #define ENUMERATE_OPCODES \
  25. __ENUMERATE_OPCODE(Compare) \
  26. __ENUMERATE_OPCODE(Jump) \
  27. __ENUMERATE_OPCODE(JumpNonEmpty) \
  28. __ENUMERATE_OPCODE(ForkJump) \
  29. __ENUMERATE_OPCODE(ForkStay) \
  30. __ENUMERATE_OPCODE(ForkReplaceJump) \
  31. __ENUMERATE_OPCODE(ForkReplaceStay) \
  32. __ENUMERATE_OPCODE(FailForks) \
  33. __ENUMERATE_OPCODE(SaveLeftCaptureGroup) \
  34. __ENUMERATE_OPCODE(SaveRightCaptureGroup) \
  35. __ENUMERATE_OPCODE(SaveRightNamedCaptureGroup) \
  36. __ENUMERATE_OPCODE(CheckBegin) \
  37. __ENUMERATE_OPCODE(CheckEnd) \
  38. __ENUMERATE_OPCODE(CheckBoundary) \
  39. __ENUMERATE_OPCODE(Save) \
  40. __ENUMERATE_OPCODE(Restore) \
  41. __ENUMERATE_OPCODE(GoBack) \
  42. __ENUMERATE_OPCODE(ClearCaptureGroup) \
  43. __ENUMERATE_OPCODE(Repeat) \
  44. __ENUMERATE_OPCODE(ResetRepeat) \
  45. __ENUMERATE_OPCODE(Checkpoint) \
  46. __ENUMERATE_OPCODE(Exit)
  47. // clang-format off
  48. enum class OpCodeId : ByteCodeValueType {
  49. #define __ENUMERATE_OPCODE(x) x,
  50. ENUMERATE_OPCODES
  51. #undef __ENUMERATE_OPCODE
  52. First = Compare,
  53. Last = Exit,
  54. };
  55. // clang-format on
  56. #define ENUMERATE_CHARACTER_COMPARE_TYPES \
  57. __ENUMERATE_CHARACTER_COMPARE_TYPE(Undefined) \
  58. __ENUMERATE_CHARACTER_COMPARE_TYPE(Inverse) \
  59. __ENUMERATE_CHARACTER_COMPARE_TYPE(TemporaryInverse) \
  60. __ENUMERATE_CHARACTER_COMPARE_TYPE(AnyChar) \
  61. __ENUMERATE_CHARACTER_COMPARE_TYPE(Char) \
  62. __ENUMERATE_CHARACTER_COMPARE_TYPE(String) \
  63. __ENUMERATE_CHARACTER_COMPARE_TYPE(CharClass) \
  64. __ENUMERATE_CHARACTER_COMPARE_TYPE(CharRange) \
  65. __ENUMERATE_CHARACTER_COMPARE_TYPE(Reference) \
  66. __ENUMERATE_CHARACTER_COMPARE_TYPE(Property) \
  67. __ENUMERATE_CHARACTER_COMPARE_TYPE(GeneralCategory) \
  68. __ENUMERATE_CHARACTER_COMPARE_TYPE(Script) \
  69. __ENUMERATE_CHARACTER_COMPARE_TYPE(ScriptExtension) \
  70. __ENUMERATE_CHARACTER_COMPARE_TYPE(RangeExpressionDummy) \
  71. __ENUMERATE_CHARACTER_COMPARE_TYPE(LookupTable) \
  72. __ENUMERATE_CHARACTER_COMPARE_TYPE(And) \
  73. __ENUMERATE_CHARACTER_COMPARE_TYPE(Or) \
  74. __ENUMERATE_CHARACTER_COMPARE_TYPE(EndAndOr)
  75. enum class CharacterCompareType : ByteCodeValueType {
  76. #define __ENUMERATE_CHARACTER_COMPARE_TYPE(x) x,
  77. ENUMERATE_CHARACTER_COMPARE_TYPES
  78. #undef __ENUMERATE_CHARACTER_COMPARE_TYPE
  79. };
  80. #define ENUMERATE_CHARACTER_CLASSES \
  81. __ENUMERATE_CHARACTER_CLASS(Alnum) \
  82. __ENUMERATE_CHARACTER_CLASS(Cntrl) \
  83. __ENUMERATE_CHARACTER_CLASS(Lower) \
  84. __ENUMERATE_CHARACTER_CLASS(Space) \
  85. __ENUMERATE_CHARACTER_CLASS(Alpha) \
  86. __ENUMERATE_CHARACTER_CLASS(Digit) \
  87. __ENUMERATE_CHARACTER_CLASS(Print) \
  88. __ENUMERATE_CHARACTER_CLASS(Upper) \
  89. __ENUMERATE_CHARACTER_CLASS(Blank) \
  90. __ENUMERATE_CHARACTER_CLASS(Graph) \
  91. __ENUMERATE_CHARACTER_CLASS(Punct) \
  92. __ENUMERATE_CHARACTER_CLASS(Word) \
  93. __ENUMERATE_CHARACTER_CLASS(Xdigit)
  94. enum class CharClass : ByteCodeValueType {
  95. #define __ENUMERATE_CHARACTER_CLASS(x) x,
  96. ENUMERATE_CHARACTER_CLASSES
  97. #undef __ENUMERATE_CHARACTER_CLASS
  98. };
  99. #define ENUMERATE_BOUNDARY_CHECK_TYPES \
  100. __ENUMERATE_BOUNDARY_CHECK_TYPE(Word) \
  101. __ENUMERATE_BOUNDARY_CHECK_TYPE(NonWord)
  102. enum class BoundaryCheckType : ByteCodeValueType {
  103. #define __ENUMERATE_BOUNDARY_CHECK_TYPE(x) x,
  104. ENUMERATE_BOUNDARY_CHECK_TYPES
  105. #undef __ENUMERATE_BOUNDARY_CHECK_TYPE
  106. };
  107. struct CharRange {
  108. u32 const from;
  109. u32 const to;
  110. CharRange(u64 value)
  111. : from(value >> 32)
  112. , to(value & 0xffffffff)
  113. {
  114. }
  115. CharRange(u32 from, u32 to)
  116. : from(from)
  117. , to(to)
  118. {
  119. }
  120. operator ByteCodeValueType() const { return ((u64)from << 32) | to; }
  121. };
  122. struct CompareTypeAndValuePair {
  123. CharacterCompareType type;
  124. ByteCodeValueType value;
  125. };
  126. class OpCode;
  127. class ByteCode : public DisjointChunks<ByteCodeValueType> {
  128. using Base = DisjointChunks<ByteCodeValueType>;
  129. public:
  130. ByteCode()
  131. {
  132. ensure_opcodes_initialized();
  133. }
  134. ByteCode(ByteCode const&) = default;
  135. virtual ~ByteCode() = default;
  136. ByteCode& operator=(ByteCode&&) = default;
  137. ByteCode& operator=(Base&& value)
  138. {
  139. static_cast<Base&>(*this) = move(value);
  140. return *this;
  141. }
  142. template<typename... Args>
  143. void empend(Args&&... args)
  144. {
  145. if (is_empty())
  146. Base::append({});
  147. Base::last_chunk().empend(forward<Args>(args)...);
  148. }
  149. template<typename T>
  150. void append(T&& value)
  151. {
  152. if (is_empty())
  153. Base::append({});
  154. Base::last_chunk().append(forward<T>(value));
  155. }
  156. template<typename T>
  157. void prepend(T&& value)
  158. {
  159. if (is_empty())
  160. return append(forward<T>(value));
  161. Base::first_chunk().prepend(forward<T>(value));
  162. }
  163. void last_chunk() const = delete;
  164. void first_chunk() const = delete;
  165. void insert_bytecode_compare_values(Vector<CompareTypeAndValuePair>&& pairs)
  166. {
  167. Optimizer::append_character_class(*this, move(pairs));
  168. }
  169. void insert_bytecode_check_boundary(BoundaryCheckType type)
  170. {
  171. ByteCode bytecode;
  172. bytecode.empend((ByteCodeValueType)OpCodeId::CheckBoundary);
  173. bytecode.empend((ByteCodeValueType)type);
  174. extend(move(bytecode));
  175. }
  176. void insert_bytecode_clear_capture_group(size_t index)
  177. {
  178. empend(static_cast<ByteCodeValueType>(OpCodeId::ClearCaptureGroup));
  179. empend(index);
  180. }
  181. void insert_bytecode_compare_string(StringView view)
  182. {
  183. ByteCode bytecode;
  184. bytecode.empend(static_cast<ByteCodeValueType>(OpCodeId::Compare));
  185. bytecode.empend(static_cast<u64>(1)); // number of arguments
  186. ByteCode arguments;
  187. arguments.empend(static_cast<ByteCodeValueType>(CharacterCompareType::String));
  188. arguments.insert_string(view);
  189. bytecode.empend(arguments.size()); // size of arguments
  190. bytecode.extend(move(arguments));
  191. extend(move(bytecode));
  192. }
  193. void insert_bytecode_group_capture_left(size_t capture_groups_count)
  194. {
  195. empend(static_cast<ByteCodeValueType>(OpCodeId::SaveLeftCaptureGroup));
  196. empend(capture_groups_count);
  197. }
  198. void insert_bytecode_group_capture_right(size_t capture_groups_count)
  199. {
  200. empend(static_cast<ByteCodeValueType>(OpCodeId::SaveRightCaptureGroup));
  201. empend(capture_groups_count);
  202. }
  203. void insert_bytecode_group_capture_right(size_t capture_groups_count, StringView name)
  204. {
  205. empend(static_cast<ByteCodeValueType>(OpCodeId::SaveRightNamedCaptureGroup));
  206. empend(reinterpret_cast<ByteCodeValueType>(name.characters_without_null_termination()));
  207. empend(name.length());
  208. empend(capture_groups_count);
  209. }
  210. enum class LookAroundType {
  211. LookAhead,
  212. LookBehind,
  213. NegatedLookAhead,
  214. NegatedLookBehind,
  215. };
  216. void insert_bytecode_lookaround(ByteCode&& lookaround_body, LookAroundType type, size_t match_length = 0)
  217. {
  218. // FIXME: The save stack will grow infinitely with repeated failures
  219. // as we do not discard that on failure (we don't necessarily know how many to pop with the current architecture).
  220. switch (type) {
  221. case LookAroundType::LookAhead: {
  222. // SAVE
  223. // REGEXP BODY
  224. // RESTORE
  225. empend((ByteCodeValueType)OpCodeId::Save);
  226. extend(move(lookaround_body));
  227. empend((ByteCodeValueType)OpCodeId::Restore);
  228. return;
  229. }
  230. case LookAroundType::NegatedLookAhead: {
  231. // JUMP _A
  232. // LABEL _L
  233. // REGEXP BODY
  234. // FAIL
  235. // LABEL _A
  236. // SAVE
  237. // FORKJUMP _L
  238. // RESTORE
  239. auto body_length = lookaround_body.size();
  240. empend((ByteCodeValueType)OpCodeId::Jump);
  241. empend((ByteCodeValueType)body_length + 1); // JUMP to label _A
  242. extend(move(lookaround_body));
  243. empend((ByteCodeValueType)OpCodeId::FailForks);
  244. empend((ByteCodeValueType)OpCodeId::Save);
  245. empend((ByteCodeValueType)OpCodeId::ForkJump);
  246. empend((ByteCodeValueType) - (body_length + 4)); // JUMP to label _L
  247. empend((ByteCodeValueType)OpCodeId::Restore);
  248. return;
  249. }
  250. case LookAroundType::LookBehind:
  251. // SAVE
  252. // GOBACK match_length(BODY)
  253. // REGEXP BODY
  254. // RESTORE
  255. empend((ByteCodeValueType)OpCodeId::Save);
  256. empend((ByteCodeValueType)OpCodeId::GoBack);
  257. empend((ByteCodeValueType)match_length);
  258. extend(move(lookaround_body));
  259. empend((ByteCodeValueType)OpCodeId::Restore);
  260. return;
  261. case LookAroundType::NegatedLookBehind: {
  262. // JUMP _A
  263. // LABEL _L
  264. // GOBACK match_length(BODY)
  265. // REGEXP BODY
  266. // FAIL
  267. // LABEL _A
  268. // SAVE
  269. // FORKJUMP _L
  270. // RESTORE
  271. auto body_length = lookaround_body.size();
  272. empend((ByteCodeValueType)OpCodeId::Jump);
  273. empend((ByteCodeValueType)body_length + 3); // JUMP to label _A
  274. empend((ByteCodeValueType)OpCodeId::GoBack);
  275. empend((ByteCodeValueType)match_length);
  276. extend(move(lookaround_body));
  277. empend((ByteCodeValueType)OpCodeId::FailForks);
  278. empend((ByteCodeValueType)OpCodeId::Save);
  279. empend((ByteCodeValueType)OpCodeId::ForkJump);
  280. empend((ByteCodeValueType) - (body_length + 6)); // JUMP to label _L
  281. empend((ByteCodeValueType)OpCodeId::Restore);
  282. return;
  283. }
  284. }
  285. VERIFY_NOT_REACHED();
  286. }
  287. void insert_bytecode_alternation(ByteCode&& left, ByteCode&& right)
  288. {
  289. // FORKJUMP _ALT
  290. // REGEXP ALT2
  291. // JUMP _END
  292. // LABEL _ALT
  293. // REGEXP ALT1
  294. // LABEL _END
  295. // Optimisation: Eliminate extra work by unifying common pre-and-postfix exprs.
  296. Optimizer::append_alternation(*this, move(left), move(right));
  297. }
  298. template<Integral T>
  299. static void transform_bytecode_repetition_min_max(ByteCode& bytecode_to_repeat, T minimum, Optional<T> maximum, size_t min_repetition_mark_id, size_t max_repetition_mark_id, bool greedy = true)
  300. {
  301. if (!maximum.has_value()) {
  302. if (minimum == 0)
  303. return transform_bytecode_repetition_any(bytecode_to_repeat, greedy);
  304. if (minimum == 1)
  305. return transform_bytecode_repetition_min_one(bytecode_to_repeat, greedy);
  306. }
  307. ByteCode new_bytecode;
  308. new_bytecode.insert_bytecode_repetition_n(bytecode_to_repeat, minimum, min_repetition_mark_id);
  309. if (maximum.has_value()) {
  310. // (REPEAT REGEXP MIN)
  311. // LABEL _MAX_LOOP |
  312. // FORK END |
  313. // REGEXP |
  314. // REPEAT _MAX_LOOP MAX-MIN | if max > min
  315. // FORK END |
  316. // REGEXP |
  317. // LABEL END |
  318. // RESET _MAX_LOOP |
  319. auto jump_kind = static_cast<ByteCodeValueType>(greedy ? OpCodeId::ForkStay : OpCodeId::ForkJump);
  320. if (maximum.value() > minimum) {
  321. new_bytecode.empend(jump_kind);
  322. new_bytecode.empend((ByteCodeValueType)0); // Placeholder for the jump target.
  323. auto pre_loop_fork_jump_index = new_bytecode.size();
  324. new_bytecode.extend(bytecode_to_repeat);
  325. auto repetitions = maximum.value() - minimum;
  326. auto fork_jump_address = new_bytecode.size();
  327. if (repetitions > 1) {
  328. new_bytecode.empend((ByteCodeValueType)OpCodeId::Repeat);
  329. new_bytecode.empend(bytecode_to_repeat.size() + 2);
  330. new_bytecode.empend(static_cast<ByteCodeValueType>(repetitions - 1));
  331. new_bytecode.empend(max_repetition_mark_id);
  332. new_bytecode.empend(jump_kind);
  333. new_bytecode.empend((ByteCodeValueType)0); // Placeholder for the jump target.
  334. auto post_loop_fork_jump_index = new_bytecode.size();
  335. new_bytecode.extend(bytecode_to_repeat);
  336. fork_jump_address = new_bytecode.size();
  337. new_bytecode[post_loop_fork_jump_index - 1] = (ByteCodeValueType)(fork_jump_address - post_loop_fork_jump_index);
  338. new_bytecode.empend((ByteCodeValueType)OpCodeId::ResetRepeat);
  339. new_bytecode.empend((ByteCodeValueType)max_repetition_mark_id);
  340. }
  341. new_bytecode[pre_loop_fork_jump_index - 1] = (ByteCodeValueType)(fork_jump_address - pre_loop_fork_jump_index);
  342. }
  343. } else {
  344. // no maximum value set, repeat finding if possible:
  345. // (REPEAT REGEXP MIN)
  346. // LABEL _START
  347. // CHECKPOINT _C
  348. // REGEXP
  349. // JUMP_NONEMPTY _C _START FORK
  350. // Note: This is only safe because REPEAT will leave one iteration outside (see repetition_n)
  351. new_bytecode.insert(new_bytecode.size() - bytecode_to_repeat.size(), (ByteCodeValueType)OpCodeId::Checkpoint);
  352. auto jump_kind = static_cast<ByteCodeValueType>(greedy ? OpCodeId::ForkJump : OpCodeId::ForkStay);
  353. new_bytecode.empend((ByteCodeValueType)OpCodeId::JumpNonEmpty);
  354. new_bytecode.empend(-bytecode_to_repeat.size() - 4 - 1); // Jump to the last iteration
  355. new_bytecode.empend(-bytecode_to_repeat.size() - 4 - 1); // if _C is not empty.
  356. new_bytecode.empend(jump_kind);
  357. }
  358. bytecode_to_repeat = move(new_bytecode);
  359. }
  360. template<Integral T>
  361. void insert_bytecode_repetition_n(ByteCode& bytecode_to_repeat, T n, size_t repetition_mark_id)
  362. {
  363. // LABEL _LOOP
  364. // REGEXP
  365. // REPEAT _LOOP N-1
  366. // REGEXP
  367. if (n == 0)
  368. return;
  369. // Note: this bytecode layout allows callers to repeat the last REGEXP instruction without the
  370. // REPEAT instruction forcing another loop.
  371. extend(bytecode_to_repeat);
  372. if (n > 1) {
  373. empend(static_cast<ByteCodeValueType>(OpCodeId::Repeat));
  374. empend(bytecode_to_repeat.size());
  375. empend(static_cast<ByteCodeValueType>(n - 1));
  376. empend(repetition_mark_id);
  377. extend(bytecode_to_repeat);
  378. }
  379. }
  380. static void transform_bytecode_repetition_min_one(ByteCode& bytecode_to_repeat, bool greedy)
  381. {
  382. // LABEL _START = -bytecode_to_repeat.size()
  383. // CHECKPOINT _C
  384. // REGEXP
  385. // JUMP_NONEMPTY _C _START FORKSTAY (FORKJUMP -> Greedy)
  386. bytecode_to_repeat.prepend((ByteCodeValueType)OpCodeId::Checkpoint);
  387. bytecode_to_repeat.empend((ByteCodeValueType)OpCodeId::JumpNonEmpty);
  388. bytecode_to_repeat.empend(-bytecode_to_repeat.size() - 3); // Jump to the _START label...
  389. bytecode_to_repeat.empend(-bytecode_to_repeat.size() - 2); // ...if _C is not empty
  390. if (greedy)
  391. bytecode_to_repeat.empend(static_cast<ByteCodeValueType>(OpCodeId::ForkJump));
  392. else
  393. bytecode_to_repeat.empend(static_cast<ByteCodeValueType>(OpCodeId::ForkStay));
  394. }
  395. static void transform_bytecode_repetition_any(ByteCode& bytecode_to_repeat, bool greedy)
  396. {
  397. // LABEL _START
  398. // FORKJUMP _END (FORKSTAY -> Greedy)
  399. // CHECKPOINT _C
  400. // REGEXP
  401. // JUMP_NONEMPTY _C _START JUMP
  402. // LABEL _END
  403. // LABEL _START = m_bytes.size();
  404. ByteCode bytecode;
  405. if (greedy)
  406. bytecode.empend(static_cast<ByteCodeValueType>(OpCodeId::ForkStay));
  407. else
  408. bytecode.empend(static_cast<ByteCodeValueType>(OpCodeId::ForkJump));
  409. bytecode.empend(bytecode_to_repeat.size() + 1 + 4); // Jump to the _END label
  410. auto c_label = bytecode.size();
  411. bytecode.empend(static_cast<ByteCodeValueType>(OpCodeId::Checkpoint));
  412. bytecode.extend(bytecode_to_repeat);
  413. bytecode.empend(static_cast<ByteCodeValueType>(OpCodeId::JumpNonEmpty));
  414. bytecode.empend(-bytecode.size() - 3); // Jump(...) to the _START label...
  415. bytecode.empend(c_label - bytecode.size() - 2); // ...only if _C passes.
  416. bytecode.empend((ByteCodeValueType)OpCodeId::Jump);
  417. // LABEL _END = bytecode.size()
  418. bytecode_to_repeat = move(bytecode);
  419. }
  420. static void transform_bytecode_repetition_zero_or_one(ByteCode& bytecode_to_repeat, bool greedy)
  421. {
  422. // FORKJUMP _END (FORKSTAY -> Greedy)
  423. // REGEXP
  424. // LABEL _END
  425. ByteCode bytecode;
  426. if (greedy)
  427. bytecode.empend(static_cast<ByteCodeValueType>(OpCodeId::ForkStay));
  428. else
  429. bytecode.empend(static_cast<ByteCodeValueType>(OpCodeId::ForkJump));
  430. bytecode.empend(bytecode_to_repeat.size()); // Jump to the _END label
  431. bytecode.extend(move(bytecode_to_repeat));
  432. // LABEL _END = bytecode.size()
  433. bytecode_to_repeat = move(bytecode);
  434. }
  435. OpCode& get_opcode(MatchState& state) const;
  436. private:
  437. void insert_string(StringView view)
  438. {
  439. empend((ByteCodeValueType)view.length());
  440. for (size_t i = 0; i < view.length(); ++i)
  441. empend((ByteCodeValueType)view[i]);
  442. }
  443. void ensure_opcodes_initialized();
  444. ALWAYS_INLINE OpCode& get_opcode_by_id(OpCodeId id) const;
  445. static OwnPtr<OpCode> s_opcodes[(size_t)OpCodeId::Last + 1];
  446. static bool s_opcodes_initialized;
  447. };
  448. #define ENUMERATE_EXECUTION_RESULTS \
  449. __ENUMERATE_EXECUTION_RESULT(Continue) \
  450. __ENUMERATE_EXECUTION_RESULT(Fork_PrioHigh) \
  451. __ENUMERATE_EXECUTION_RESULT(Fork_PrioLow) \
  452. __ENUMERATE_EXECUTION_RESULT(Failed) \
  453. __ENUMERATE_EXECUTION_RESULT(Failed_ExecuteLowPrioForks) \
  454. __ENUMERATE_EXECUTION_RESULT(Succeeded)
  455. enum class ExecutionResult : u8 {
  456. #define __ENUMERATE_EXECUTION_RESULT(x) x,
  457. ENUMERATE_EXECUTION_RESULTS
  458. #undef __ENUMERATE_EXECUTION_RESULT
  459. };
  460. StringView execution_result_name(ExecutionResult result);
  461. StringView opcode_id_name(OpCodeId opcode_id);
  462. StringView boundary_check_type_name(BoundaryCheckType);
  463. StringView character_compare_type_name(CharacterCompareType result);
  464. class OpCode {
  465. public:
  466. OpCode() = default;
  467. virtual ~OpCode() = default;
  468. virtual OpCodeId opcode_id() const = 0;
  469. virtual size_t size() const = 0;
  470. virtual ExecutionResult execute(MatchInput const& input, MatchState& state) const = 0;
  471. ALWAYS_INLINE ByteCodeValueType argument(size_t offset) const
  472. {
  473. VERIFY(state().instruction_position + offset <= m_bytecode->size());
  474. return m_bytecode->at(state().instruction_position + 1 + offset);
  475. }
  476. ALWAYS_INLINE StringView name() const;
  477. static StringView name(OpCodeId);
  478. ALWAYS_INLINE void set_state(MatchState& state) { m_state = &state; }
  479. ALWAYS_INLINE void set_bytecode(ByteCode& bytecode) { m_bytecode = &bytecode; }
  480. ALWAYS_INLINE MatchState const& state() const
  481. {
  482. VERIFY(m_state);
  483. return *m_state;
  484. }
  485. DeprecatedString to_deprecated_string() const
  486. {
  487. return DeprecatedString::formatted("[{:#02X}] {}", (int)opcode_id(), name(opcode_id()));
  488. }
  489. virtual DeprecatedString arguments_string() const = 0;
  490. ALWAYS_INLINE ByteCode const& bytecode() const { return *m_bytecode; }
  491. protected:
  492. ByteCode* m_bytecode { nullptr };
  493. MatchState* m_state { nullptr };
  494. };
  495. class OpCode_Exit final : public OpCode {
  496. public:
  497. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  498. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::Exit; }
  499. ALWAYS_INLINE size_t size() const override { return 1; }
  500. DeprecatedString arguments_string() const override { return DeprecatedString::empty(); }
  501. };
  502. class OpCode_FailForks final : public OpCode {
  503. public:
  504. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  505. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::FailForks; }
  506. ALWAYS_INLINE size_t size() const override { return 1; }
  507. DeprecatedString arguments_string() const override { return DeprecatedString::empty(); }
  508. };
  509. class OpCode_Save final : public OpCode {
  510. public:
  511. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  512. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::Save; }
  513. ALWAYS_INLINE size_t size() const override { return 1; }
  514. DeprecatedString arguments_string() const override { return DeprecatedString::empty(); }
  515. };
  516. class OpCode_Restore final : public OpCode {
  517. public:
  518. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  519. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::Restore; }
  520. ALWAYS_INLINE size_t size() const override { return 1; }
  521. DeprecatedString arguments_string() const override { return DeprecatedString::empty(); }
  522. };
  523. class OpCode_GoBack final : public OpCode {
  524. public:
  525. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  526. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::GoBack; }
  527. ALWAYS_INLINE size_t size() const override { return 2; }
  528. ALWAYS_INLINE size_t count() const { return argument(0); }
  529. DeprecatedString arguments_string() const override { return DeprecatedString::formatted("count={}", count()); }
  530. };
  531. class OpCode_Jump final : public OpCode {
  532. public:
  533. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  534. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::Jump; }
  535. ALWAYS_INLINE size_t size() const override { return 2; }
  536. ALWAYS_INLINE ssize_t offset() const { return argument(0); }
  537. DeprecatedString arguments_string() const override
  538. {
  539. return DeprecatedString::formatted("offset={} [&{}]", offset(), state().instruction_position + size() + offset());
  540. }
  541. };
  542. class OpCode_ForkJump : public OpCode {
  543. public:
  544. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  545. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::ForkJump; }
  546. ALWAYS_INLINE size_t size() const override { return 2; }
  547. ALWAYS_INLINE ssize_t offset() const { return argument(0); }
  548. DeprecatedString arguments_string() const override
  549. {
  550. return DeprecatedString::formatted("offset={} [&{}], sp: {}", offset(), state().instruction_position + size() + offset(), state().string_position);
  551. }
  552. };
  553. class OpCode_ForkReplaceJump final : public OpCode_ForkJump {
  554. public:
  555. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  556. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::ForkReplaceJump; }
  557. };
  558. class OpCode_ForkStay : public OpCode {
  559. public:
  560. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  561. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::ForkStay; }
  562. ALWAYS_INLINE size_t size() const override { return 2; }
  563. ALWAYS_INLINE ssize_t offset() const { return argument(0); }
  564. DeprecatedString arguments_string() const override
  565. {
  566. return DeprecatedString::formatted("offset={} [&{}], sp: {}", offset(), state().instruction_position + size() + offset(), state().string_position);
  567. }
  568. };
  569. class OpCode_ForkReplaceStay final : public OpCode_ForkStay {
  570. public:
  571. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  572. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::ForkReplaceStay; }
  573. };
  574. class OpCode_CheckBegin final : public OpCode {
  575. public:
  576. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  577. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::CheckBegin; }
  578. ALWAYS_INLINE size_t size() const override { return 1; }
  579. DeprecatedString arguments_string() const override { return DeprecatedString::empty(); }
  580. };
  581. class OpCode_CheckEnd final : public OpCode {
  582. public:
  583. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  584. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::CheckEnd; }
  585. ALWAYS_INLINE size_t size() const override { return 1; }
  586. DeprecatedString arguments_string() const override { return DeprecatedString::empty(); }
  587. };
  588. class OpCode_CheckBoundary final : public OpCode {
  589. public:
  590. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  591. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::CheckBoundary; }
  592. ALWAYS_INLINE size_t size() const override { return 2; }
  593. ALWAYS_INLINE size_t arguments_count() const { return 1; }
  594. ALWAYS_INLINE BoundaryCheckType type() const { return static_cast<BoundaryCheckType>(argument(0)); }
  595. DeprecatedString arguments_string() const override { return DeprecatedString::formatted("kind={} ({})", (long unsigned int)argument(0), boundary_check_type_name(type())); }
  596. };
  597. class OpCode_ClearCaptureGroup final : public OpCode {
  598. public:
  599. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  600. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::ClearCaptureGroup; }
  601. ALWAYS_INLINE size_t size() const override { return 2; }
  602. ALWAYS_INLINE size_t id() const { return argument(0); }
  603. DeprecatedString arguments_string() const override { return DeprecatedString::formatted("id={}", id()); }
  604. };
  605. class OpCode_SaveLeftCaptureGroup final : public OpCode {
  606. public:
  607. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  608. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::SaveLeftCaptureGroup; }
  609. ALWAYS_INLINE size_t size() const override { return 2; }
  610. ALWAYS_INLINE size_t id() const { return argument(0); }
  611. DeprecatedString arguments_string() const override { return DeprecatedString::formatted("id={}", id()); }
  612. };
  613. class OpCode_SaveRightCaptureGroup final : public OpCode {
  614. public:
  615. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  616. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::SaveRightCaptureGroup; }
  617. ALWAYS_INLINE size_t size() const override { return 2; }
  618. ALWAYS_INLINE size_t id() const { return argument(0); }
  619. DeprecatedString arguments_string() const override { return DeprecatedString::formatted("id={}", id()); }
  620. };
  621. class OpCode_SaveRightNamedCaptureGroup final : public OpCode {
  622. public:
  623. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  624. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::SaveRightNamedCaptureGroup; }
  625. ALWAYS_INLINE size_t size() const override { return 4; }
  626. ALWAYS_INLINE StringView name() const { return { reinterpret_cast<char*>(argument(0)), length() }; }
  627. ALWAYS_INLINE size_t length() const { return argument(1); }
  628. ALWAYS_INLINE size_t id() const { return argument(2); }
  629. DeprecatedString arguments_string() const override
  630. {
  631. return DeprecatedString::formatted("name={}, length={}", name(), length());
  632. }
  633. };
  634. class OpCode_Compare final : public OpCode {
  635. public:
  636. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  637. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::Compare; }
  638. ALWAYS_INLINE size_t size() const override { return arguments_size() + 3; }
  639. ALWAYS_INLINE size_t arguments_count() const { return argument(0); }
  640. ALWAYS_INLINE size_t arguments_size() const { return argument(1); }
  641. DeprecatedString arguments_string() const override;
  642. Vector<DeprecatedString> variable_arguments_to_deprecated_string(Optional<MatchInput const&> input = {}) const;
  643. Vector<CompareTypeAndValuePair> flat_compares() const;
  644. static bool matches_character_class(CharClass, u32, bool insensitive);
  645. private:
  646. ALWAYS_INLINE static void compare_char(MatchInput const& input, MatchState& state, u32 ch1, bool inverse, bool& inverse_matched);
  647. ALWAYS_INLINE static bool compare_string(MatchInput const& input, MatchState& state, RegexStringView str, bool& had_zero_length_match);
  648. ALWAYS_INLINE static void compare_character_class(MatchInput const& input, MatchState& state, CharClass character_class, u32 ch, bool inverse, bool& inverse_matched);
  649. ALWAYS_INLINE static void compare_character_range(MatchInput const& input, MatchState& state, u32 from, u32 to, u32 ch, bool inverse, bool& inverse_matched);
  650. ALWAYS_INLINE static void compare_property(MatchInput const& input, MatchState& state, Unicode::Property property, bool inverse, bool& inverse_matched);
  651. ALWAYS_INLINE static void compare_general_category(MatchInput const& input, MatchState& state, Unicode::GeneralCategory general_category, bool inverse, bool& inverse_matched);
  652. ALWAYS_INLINE static void compare_script(MatchInput const& input, MatchState& state, Unicode::Script script, bool inverse, bool& inverse_matched);
  653. ALWAYS_INLINE static void compare_script_extension(MatchInput const& input, MatchState& state, Unicode::Script script, bool inverse, bool& inverse_matched);
  654. };
  655. class OpCode_Repeat : public OpCode {
  656. public:
  657. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  658. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::Repeat; }
  659. ALWAYS_INLINE size_t size() const override { return 4; }
  660. ALWAYS_INLINE size_t offset() const { return argument(0); }
  661. ALWAYS_INLINE u64 count() const { return argument(1); }
  662. ALWAYS_INLINE size_t id() const { return argument(2); }
  663. DeprecatedString arguments_string() const override
  664. {
  665. auto reps = id() < state().repetition_marks.size() ? state().repetition_marks.at(id()) : 0;
  666. return DeprecatedString::formatted("offset={} count={} id={} rep={}, sp: {}", offset(), count() + 1, id(), reps + 1, state().string_position);
  667. }
  668. };
  669. class OpCode_ResetRepeat : public OpCode {
  670. public:
  671. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  672. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::ResetRepeat; }
  673. ALWAYS_INLINE size_t size() const override { return 2; }
  674. ALWAYS_INLINE size_t id() const { return argument(0); }
  675. DeprecatedString arguments_string() const override
  676. {
  677. auto reps = id() < state().repetition_marks.size() ? state().repetition_marks.at(id()) : 0;
  678. return DeprecatedString::formatted("id={} rep={}", id(), reps + 1);
  679. }
  680. };
  681. class OpCode_Checkpoint final : public OpCode {
  682. public:
  683. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  684. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::Checkpoint; }
  685. ALWAYS_INLINE size_t size() const override { return 1; }
  686. DeprecatedString arguments_string() const override { return DeprecatedString::empty(); }
  687. };
  688. class OpCode_JumpNonEmpty final : public OpCode {
  689. public:
  690. ExecutionResult execute(MatchInput const& input, MatchState& state) const override;
  691. ALWAYS_INLINE OpCodeId opcode_id() const override { return OpCodeId::JumpNonEmpty; }
  692. ALWAYS_INLINE size_t size() const override { return 4; }
  693. ALWAYS_INLINE ssize_t offset() const { return argument(0); }
  694. ALWAYS_INLINE ssize_t checkpoint() const { return argument(1); }
  695. ALWAYS_INLINE OpCodeId form() const { return (OpCodeId)argument(2); }
  696. DeprecatedString arguments_string() const override
  697. {
  698. return DeprecatedString::formatted("{} offset={} [&{}], cp={} [&{}]",
  699. opcode_id_name(form()),
  700. offset(), state().instruction_position + size() + offset(),
  701. checkpoint(), state().instruction_position + size() + checkpoint());
  702. }
  703. };
  704. template<typename T>
  705. bool is(OpCode const&);
  706. template<typename T>
  707. ALWAYS_INLINE bool is(OpCode const&)
  708. {
  709. return false;
  710. }
  711. template<typename T>
  712. ALWAYS_INLINE bool is(OpCode const* opcode)
  713. {
  714. return is<T>(*opcode);
  715. }
  716. template<>
  717. ALWAYS_INLINE bool is<OpCode_ForkStay>(OpCode const& opcode)
  718. {
  719. return opcode.opcode_id() == OpCodeId::ForkStay;
  720. }
  721. template<>
  722. ALWAYS_INLINE bool is<OpCode_Exit>(OpCode const& opcode)
  723. {
  724. return opcode.opcode_id() == OpCodeId::Exit;
  725. }
  726. template<>
  727. ALWAYS_INLINE bool is<OpCode_Compare>(OpCode const& opcode)
  728. {
  729. return opcode.opcode_id() == OpCodeId::Compare;
  730. }
  731. template<typename T>
  732. ALWAYS_INLINE T const& to(OpCode const& opcode)
  733. {
  734. return verify_cast<T>(opcode);
  735. }
  736. template<typename T>
  737. ALWAYS_INLINE T* to(OpCode* opcode)
  738. {
  739. return verify_cast<T>(opcode);
  740. }
  741. template<typename T>
  742. ALWAYS_INLINE T const* to(OpCode const* opcode)
  743. {
  744. return verify_cast<T>(opcode);
  745. }
  746. template<typename T>
  747. ALWAYS_INLINE T& to(OpCode& opcode)
  748. {
  749. return verify_cast<T>(opcode);
  750. }
  751. }