RegexByteCode.h 33 KB

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