RegexByteCode.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. /*
  2. * Copyright (c) 2020, Emanuel Sprung <emanuel.sprung@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "RegexByteCode.h"
  7. #include "AK/StringBuilder.h"
  8. #include "RegexDebug.h"
  9. #include <AK/CharacterTypes.h>
  10. #include <AK/Debug.h>
  11. #include <LibUnicode/CharacterTypes.h>
  12. namespace regex {
  13. char const* OpCode::name(OpCodeId opcode_id)
  14. {
  15. switch (opcode_id) {
  16. #define __ENUMERATE_OPCODE(x) \
  17. case OpCodeId::x: \
  18. return #x;
  19. ENUMERATE_OPCODES
  20. #undef __ENUMERATE_OPCODE
  21. default:
  22. VERIFY_NOT_REACHED();
  23. return "<Unknown>";
  24. }
  25. }
  26. char const* OpCode::name() const
  27. {
  28. return name(opcode_id());
  29. }
  30. char const* execution_result_name(ExecutionResult result)
  31. {
  32. switch (result) {
  33. #define __ENUMERATE_EXECUTION_RESULT(x) \
  34. case ExecutionResult::x: \
  35. return #x;
  36. ENUMERATE_EXECUTION_RESULTS
  37. #undef __ENUMERATE_EXECUTION_RESULT
  38. default:
  39. VERIFY_NOT_REACHED();
  40. return "<Unknown>";
  41. }
  42. }
  43. char const* opcode_id_name(OpCodeId opcode)
  44. {
  45. switch (opcode) {
  46. #define __ENUMERATE_OPCODE(x) \
  47. case OpCodeId::x: \
  48. return #x;
  49. ENUMERATE_OPCODES
  50. #undef __ENUMERATE_OPCODE
  51. default:
  52. VERIFY_NOT_REACHED();
  53. return "<Unknown>";
  54. }
  55. }
  56. char const* boundary_check_type_name(BoundaryCheckType ty)
  57. {
  58. switch (ty) {
  59. #define __ENUMERATE_BOUNDARY_CHECK_TYPE(x) \
  60. case BoundaryCheckType::x: \
  61. return #x;
  62. ENUMERATE_BOUNDARY_CHECK_TYPES
  63. #undef __ENUMERATE_BOUNDARY_CHECK_TYPE
  64. default:
  65. VERIFY_NOT_REACHED();
  66. return "<Unknown>";
  67. }
  68. }
  69. char const* character_compare_type_name(CharacterCompareType ch_compare_type)
  70. {
  71. switch (ch_compare_type) {
  72. #define __ENUMERATE_CHARACTER_COMPARE_TYPE(x) \
  73. case CharacterCompareType::x: \
  74. return #x;
  75. ENUMERATE_CHARACTER_COMPARE_TYPES
  76. #undef __ENUMERATE_CHARACTER_COMPARE_TYPE
  77. default:
  78. VERIFY_NOT_REACHED();
  79. return "<Unknown>";
  80. }
  81. }
  82. static char const* character_class_name(CharClass ch_class)
  83. {
  84. switch (ch_class) {
  85. #define __ENUMERATE_CHARACTER_CLASS(x) \
  86. case CharClass::x: \
  87. return #x;
  88. ENUMERATE_CHARACTER_CLASSES
  89. #undef __ENUMERATE_CHARACTER_CLASS
  90. default:
  91. VERIFY_NOT_REACHED();
  92. return "<Unknown>";
  93. }
  94. }
  95. static void advance_string_position(MatchState& state, RegexStringView const& view, Optional<u32> code_point = {})
  96. {
  97. ++state.string_position;
  98. if (view.unicode()) {
  99. if (!code_point.has_value() && (state.string_position_in_code_units < view.length_in_code_units()))
  100. code_point = view[state.string_position_in_code_units];
  101. if (code_point.has_value())
  102. state.string_position_in_code_units += view.length_of_code_point(*code_point);
  103. } else {
  104. ++state.string_position_in_code_units;
  105. }
  106. }
  107. static void advance_string_position(MatchState& state, RegexStringView const&, RegexStringView const& advance_by)
  108. {
  109. state.string_position += advance_by.length();
  110. state.string_position_in_code_units += advance_by.length_in_code_units();
  111. }
  112. static void reverse_string_position(MatchState& state, RegexStringView const& view, size_t amount)
  113. {
  114. VERIFY(state.string_position >= amount);
  115. state.string_position -= amount;
  116. if (view.unicode())
  117. state.string_position_in_code_units = view.code_unit_offset_of(state.string_position);
  118. else
  119. state.string_position_in_code_units -= amount;
  120. }
  121. static void save_string_position(MatchInput const& input, MatchState const& state)
  122. {
  123. input.saved_positions.append(state.string_position);
  124. input.saved_code_unit_positions.append(state.string_position_in_code_units);
  125. }
  126. static bool restore_string_position(MatchInput const& input, MatchState& state)
  127. {
  128. if (input.saved_positions.is_empty())
  129. return false;
  130. state.string_position = input.saved_positions.take_last();
  131. state.string_position_in_code_units = input.saved_code_unit_positions.take_last();
  132. return true;
  133. }
  134. OwnPtr<OpCode> ByteCode::s_opcodes[(size_t)OpCodeId::Last + 1];
  135. bool ByteCode::s_opcodes_initialized { false };
  136. void ByteCode::ensure_opcodes_initialized()
  137. {
  138. if (s_opcodes_initialized)
  139. return;
  140. for (u32 i = (u32)OpCodeId::First; i <= (u32)OpCodeId::Last; ++i) {
  141. switch ((OpCodeId)i) {
  142. #define __ENUMERATE_OPCODE(OpCode) \
  143. case OpCodeId::OpCode: \
  144. s_opcodes[i] = make<OpCode_##OpCode>(); \
  145. break;
  146. ENUMERATE_OPCODES
  147. #undef __ENUMERATE_OPCODE
  148. }
  149. }
  150. s_opcodes_initialized = true;
  151. }
  152. ALWAYS_INLINE OpCode& ByteCode::get_opcode_by_id(OpCodeId id) const
  153. {
  154. VERIFY(id >= OpCodeId::First && id <= OpCodeId::Last);
  155. auto& opcode = s_opcodes[(u32)id];
  156. opcode->set_bytecode(*const_cast<ByteCode*>(this));
  157. return *opcode;
  158. }
  159. OpCode& ByteCode::get_opcode(MatchState& state) const
  160. {
  161. OpCodeId opcode_id;
  162. if (state.instruction_position >= size())
  163. opcode_id = OpCodeId::Exit;
  164. else
  165. opcode_id = (OpCodeId)at(state.instruction_position);
  166. auto& opcode = get_opcode_by_id(opcode_id);
  167. opcode.set_state(state);
  168. return opcode;
  169. }
  170. ALWAYS_INLINE ExecutionResult OpCode_Exit::execute(MatchInput const& input, MatchState& state) const
  171. {
  172. if (state.string_position > input.view.length() || state.instruction_position >= m_bytecode->size())
  173. return ExecutionResult::Succeeded;
  174. return ExecutionResult::Failed;
  175. }
  176. ALWAYS_INLINE ExecutionResult OpCode_Save::execute(MatchInput const& input, MatchState& state) const
  177. {
  178. save_string_position(input, state);
  179. return ExecutionResult::Continue;
  180. }
  181. ALWAYS_INLINE ExecutionResult OpCode_Restore::execute(MatchInput const& input, MatchState& state) const
  182. {
  183. if (!restore_string_position(input, state))
  184. return ExecutionResult::Failed;
  185. return ExecutionResult::Continue;
  186. }
  187. ALWAYS_INLINE ExecutionResult OpCode_GoBack::execute(MatchInput const& input, MatchState& state) const
  188. {
  189. if (count() > state.string_position)
  190. return ExecutionResult::Failed_ExecuteLowPrioForks;
  191. reverse_string_position(state, input.view, count());
  192. return ExecutionResult::Continue;
  193. }
  194. ALWAYS_INLINE ExecutionResult OpCode_FailForks::execute(MatchInput const& input, MatchState&) const
  195. {
  196. VERIFY(count() > 0);
  197. input.fail_counter += count() - 1;
  198. return ExecutionResult::Failed_ExecuteLowPrioForks;
  199. }
  200. ALWAYS_INLINE ExecutionResult OpCode_Jump::execute(MatchInput const&, MatchState& state) const
  201. {
  202. state.instruction_position += offset();
  203. return ExecutionResult::Continue;
  204. }
  205. ALWAYS_INLINE ExecutionResult OpCode_ForkJump::execute(MatchInput const&, MatchState& state) const
  206. {
  207. state.fork_at_position = state.instruction_position + size() + offset();
  208. return ExecutionResult::Fork_PrioHigh;
  209. }
  210. ALWAYS_INLINE ExecutionResult OpCode_ForkStay::execute(MatchInput const&, MatchState& state) const
  211. {
  212. state.fork_at_position = state.instruction_position + size() + offset();
  213. return ExecutionResult::Fork_PrioLow;
  214. }
  215. ALWAYS_INLINE ExecutionResult OpCode_CheckBegin::execute(MatchInput const& input, MatchState& state) const
  216. {
  217. if (0 == state.string_position && (input.regex_options & AllFlags::MatchNotBeginOfLine))
  218. return ExecutionResult::Failed_ExecuteLowPrioForks;
  219. if ((0 == state.string_position && !(input.regex_options & AllFlags::MatchNotBeginOfLine))
  220. || (0 != state.string_position && (input.regex_options & AllFlags::MatchNotBeginOfLine))
  221. || (0 == state.string_position && (input.regex_options & AllFlags::Global)))
  222. return ExecutionResult::Continue;
  223. return ExecutionResult::Failed_ExecuteLowPrioForks;
  224. }
  225. ALWAYS_INLINE ExecutionResult OpCode_CheckBoundary::execute(MatchInput const& input, MatchState& state) const
  226. {
  227. auto isword = [](auto ch) { return is_ascii_alphanumeric(ch) || ch == '_'; };
  228. auto is_word_boundary = [&] {
  229. if (state.string_position == input.view.length()) {
  230. if (state.string_position > 0 && isword(input.view[state.string_position_in_code_units - 1]))
  231. return true;
  232. return false;
  233. }
  234. if (state.string_position == 0) {
  235. if (isword(input.view[0]))
  236. return true;
  237. return false;
  238. }
  239. return !!(isword(input.view[state.string_position_in_code_units]) ^ isword(input.view[state.string_position_in_code_units - 1]));
  240. };
  241. switch (type()) {
  242. case BoundaryCheckType::Word: {
  243. if (is_word_boundary())
  244. return ExecutionResult::Continue;
  245. return ExecutionResult::Failed_ExecuteLowPrioForks;
  246. }
  247. case BoundaryCheckType::NonWord: {
  248. if (!is_word_boundary())
  249. return ExecutionResult::Continue;
  250. return ExecutionResult::Failed_ExecuteLowPrioForks;
  251. }
  252. }
  253. VERIFY_NOT_REACHED();
  254. }
  255. ALWAYS_INLINE ExecutionResult OpCode_CheckEnd::execute(MatchInput const& input, MatchState& state) const
  256. {
  257. if (state.string_position == input.view.length() && (input.regex_options & AllFlags::MatchNotEndOfLine))
  258. return ExecutionResult::Failed_ExecuteLowPrioForks;
  259. if ((state.string_position == input.view.length() && !(input.regex_options & AllFlags::MatchNotEndOfLine))
  260. || (state.string_position != input.view.length() && (input.regex_options & AllFlags::MatchNotEndOfLine || input.regex_options & AllFlags::MatchNotBeginOfLine)))
  261. return ExecutionResult::Continue;
  262. return ExecutionResult::Failed_ExecuteLowPrioForks;
  263. }
  264. ALWAYS_INLINE ExecutionResult OpCode_ClearCaptureGroup::execute(MatchInput const& input, MatchState& state) const
  265. {
  266. if (input.match_index < state.capture_group_matches.size()) {
  267. auto& group = state.capture_group_matches[input.match_index];
  268. if (id() < group.size())
  269. group[id()].reset();
  270. }
  271. return ExecutionResult::Continue;
  272. }
  273. ALWAYS_INLINE ExecutionResult OpCode_SaveLeftCaptureGroup::execute(MatchInput const& input, MatchState& state) const
  274. {
  275. if (input.match_index >= state.capture_group_matches.size()) {
  276. state.capture_group_matches.ensure_capacity(input.match_index);
  277. auto capacity = state.capture_group_matches.capacity();
  278. for (size_t i = state.capture_group_matches.size(); i <= capacity; ++i)
  279. state.capture_group_matches.empend();
  280. }
  281. if (id() >= state.capture_group_matches.at(input.match_index).size()) {
  282. state.capture_group_matches.at(input.match_index).ensure_capacity(id());
  283. auto capacity = state.capture_group_matches.at(input.match_index).capacity();
  284. for (size_t i = state.capture_group_matches.at(input.match_index).size(); i <= capacity; ++i)
  285. state.capture_group_matches.at(input.match_index).empend();
  286. }
  287. state.capture_group_matches.at(input.match_index).at(id()).left_column = state.string_position;
  288. return ExecutionResult::Continue;
  289. }
  290. ALWAYS_INLINE ExecutionResult OpCode_SaveRightCaptureGroup::execute(MatchInput const& input, MatchState& state) const
  291. {
  292. auto& match = state.capture_group_matches.at(input.match_index).at(id());
  293. auto start_position = match.left_column;
  294. if (state.string_position < start_position)
  295. return ExecutionResult::Failed_ExecuteLowPrioForks;
  296. auto length = state.string_position - start_position;
  297. if (start_position < match.column)
  298. return ExecutionResult::Continue;
  299. VERIFY(start_position + length <= input.view.length());
  300. auto view = input.view.substring_view(start_position, length);
  301. if (input.regex_options & AllFlags::StringCopyMatches) {
  302. match = { view.to_string(), input.line, start_position, input.global_offset + start_position }; // create a copy of the original string
  303. } else {
  304. match = { view, input.line, start_position, input.global_offset + start_position }; // take view to original string
  305. }
  306. return ExecutionResult::Continue;
  307. }
  308. ALWAYS_INLINE ExecutionResult OpCode_SaveRightNamedCaptureGroup::execute(MatchInput const& input, MatchState& state) const
  309. {
  310. auto& match = state.capture_group_matches.at(input.match_index).at(id());
  311. auto start_position = match.left_column;
  312. if (state.string_position < start_position)
  313. return ExecutionResult::Failed_ExecuteLowPrioForks;
  314. auto length = state.string_position - start_position;
  315. if (start_position < match.column)
  316. return ExecutionResult::Continue;
  317. VERIFY(start_position + length <= input.view.length());
  318. auto view = input.view.substring_view(start_position, length);
  319. if (input.regex_options & AllFlags::StringCopyMatches) {
  320. match = { view.to_string(), name(), input.line, start_position, input.global_offset + start_position }; // create a copy of the original string
  321. } else {
  322. match = { view, name(), input.line, start_position, input.global_offset + start_position }; // take view to original string
  323. }
  324. return ExecutionResult::Continue;
  325. }
  326. ALWAYS_INLINE ExecutionResult OpCode_Compare::execute(MatchInput const& input, MatchState& state) const
  327. {
  328. bool inverse { false };
  329. bool temporary_inverse { false };
  330. bool reset_temp_inverse { false };
  331. auto current_inversion_state = [&]() -> bool { return temporary_inverse ^ inverse; };
  332. size_t string_position = state.string_position;
  333. bool inverse_matched { false };
  334. bool had_zero_length_match { false };
  335. state.string_position_before_match = state.string_position;
  336. size_t offset { state.instruction_position + 3 };
  337. for (size_t i = 0; i < arguments_count(); ++i) {
  338. if (state.string_position > string_position)
  339. break;
  340. if (reset_temp_inverse) {
  341. reset_temp_inverse = false;
  342. temporary_inverse = false;
  343. } else {
  344. reset_temp_inverse = true;
  345. }
  346. auto compare_type = (CharacterCompareType)m_bytecode->at(offset++);
  347. if (compare_type == CharacterCompareType::Inverse)
  348. inverse = true;
  349. else if (compare_type == CharacterCompareType::TemporaryInverse) {
  350. // If "TemporaryInverse" is given, negate the current inversion state only for the next opcode.
  351. // it follows that this cannot be the last compare element.
  352. VERIFY(i != arguments_count() - 1);
  353. temporary_inverse = true;
  354. reset_temp_inverse = false;
  355. } else if (compare_type == CharacterCompareType::Char) {
  356. u32 ch = m_bytecode->at(offset++);
  357. // We want to compare a string that is longer or equal in length to the available string
  358. if (input.view.length() <= state.string_position)
  359. return ExecutionResult::Failed_ExecuteLowPrioForks;
  360. compare_char(input, state, ch, current_inversion_state(), inverse_matched);
  361. } else if (compare_type == CharacterCompareType::AnyChar) {
  362. // We want to compare a string that is definitely longer than the available string
  363. if (input.view.length() <= state.string_position)
  364. return ExecutionResult::Failed_ExecuteLowPrioForks;
  365. VERIFY(!current_inversion_state());
  366. advance_string_position(state, input.view);
  367. } else if (compare_type == CharacterCompareType::String) {
  368. VERIFY(!current_inversion_state());
  369. auto const& length = m_bytecode->at(offset++);
  370. // We want to compare a string that is definitely longer than the available string
  371. if (input.view.length() < state.string_position + length)
  372. return ExecutionResult::Failed_ExecuteLowPrioForks;
  373. Optional<String> str;
  374. Vector<u16> utf16;
  375. Vector<u32> data;
  376. data.ensure_capacity(length);
  377. for (size_t i = offset; i < offset + length; ++i)
  378. data.unchecked_append(m_bytecode->at(i));
  379. auto view = input.view.construct_as_same(data, str, utf16);
  380. offset += length;
  381. if (!compare_string(input, state, view, had_zero_length_match))
  382. return ExecutionResult::Failed_ExecuteLowPrioForks;
  383. } else if (compare_type == CharacterCompareType::CharClass) {
  384. if (input.view.length() <= state.string_position)
  385. return ExecutionResult::Failed_ExecuteLowPrioForks;
  386. auto character_class = (CharClass)m_bytecode->at(offset++);
  387. auto ch = input.view[state.string_position_in_code_units];
  388. compare_character_class(input, state, character_class, ch, current_inversion_state(), inverse_matched);
  389. } else if (compare_type == CharacterCompareType::CharRange) {
  390. if (input.view.length() <= state.string_position)
  391. return ExecutionResult::Failed_ExecuteLowPrioForks;
  392. auto value = (CharRange)m_bytecode->at(offset++);
  393. auto from = value.from;
  394. auto to = value.to;
  395. auto ch = input.view[state.string_position_in_code_units];
  396. compare_character_range(input, state, from, to, ch, current_inversion_state(), inverse_matched);
  397. } else if (compare_type == CharacterCompareType::Reference) {
  398. auto reference_number = (size_t)m_bytecode->at(offset++);
  399. auto& groups = state.capture_group_matches.at(input.match_index);
  400. if (groups.size() <= reference_number)
  401. return ExecutionResult::Failed_ExecuteLowPrioForks;
  402. auto str = groups.at(reference_number).view;
  403. // We want to compare a string that is definitely longer than the available string
  404. if (input.view.length() < state.string_position + str.length())
  405. return ExecutionResult::Failed_ExecuteLowPrioForks;
  406. if (!compare_string(input, state, str, had_zero_length_match))
  407. return ExecutionResult::Failed_ExecuteLowPrioForks;
  408. } else if (compare_type == CharacterCompareType::Property) {
  409. auto property = static_cast<Unicode::Property>(m_bytecode->at(offset++));
  410. compare_property(input, state, property, current_inversion_state(), inverse_matched);
  411. } else if (compare_type == CharacterCompareType::GeneralCategory) {
  412. auto general_category = static_cast<Unicode::GeneralCategory>(m_bytecode->at(offset++));
  413. compare_general_category(input, state, general_category, current_inversion_state(), inverse_matched);
  414. } else if (compare_type == CharacterCompareType::Script) {
  415. auto script = static_cast<Unicode::Script>(m_bytecode->at(offset++));
  416. compare_script(input, state, script, current_inversion_state(), inverse_matched);
  417. } else if (compare_type == CharacterCompareType::ScriptExtension) {
  418. auto script = static_cast<Unicode::Script>(m_bytecode->at(offset++));
  419. compare_script_extension(input, state, script, current_inversion_state(), inverse_matched);
  420. } else {
  421. warnln("Undefined comparison: {}", (int)compare_type);
  422. VERIFY_NOT_REACHED();
  423. break;
  424. }
  425. }
  426. if (current_inversion_state() && !inverse_matched)
  427. advance_string_position(state, input.view);
  428. if ((!had_zero_length_match && string_position == state.string_position) || state.string_position > input.view.length())
  429. return ExecutionResult::Failed_ExecuteLowPrioForks;
  430. return ExecutionResult::Continue;
  431. }
  432. ALWAYS_INLINE void OpCode_Compare::compare_char(MatchInput const& input, MatchState& state, u32 ch1, bool inverse, bool& inverse_matched)
  433. {
  434. if (state.string_position == input.view.length())
  435. return;
  436. auto input_view = input.view.substring_view(state.string_position, 1);
  437. Optional<String> str;
  438. Vector<u16> utf16;
  439. auto compare_view = input_view.construct_as_same({ &ch1, 1 }, str, utf16);
  440. bool equal;
  441. if (input.regex_options & AllFlags::Insensitive)
  442. equal = input_view.equals_ignoring_case(compare_view);
  443. else
  444. equal = input_view.equals(compare_view);
  445. if (equal) {
  446. if (inverse)
  447. inverse_matched = true;
  448. else
  449. advance_string_position(state, input.view, ch1);
  450. }
  451. }
  452. ALWAYS_INLINE bool OpCode_Compare::compare_string(MatchInput const& input, MatchState& state, RegexStringView const& str, bool& had_zero_length_match)
  453. {
  454. if (state.string_position + str.length() > input.view.length()) {
  455. if (str.is_empty()) {
  456. had_zero_length_match = true;
  457. return true;
  458. }
  459. return false;
  460. }
  461. if (str.length() == 0) {
  462. had_zero_length_match = true;
  463. return true;
  464. }
  465. auto subject = input.view.substring_view(state.string_position, str.length());
  466. bool equals;
  467. if (input.regex_options & AllFlags::Insensitive)
  468. equals = subject.equals_ignoring_case(str);
  469. else
  470. equals = subject.equals(str);
  471. if (equals)
  472. advance_string_position(state, input.view, str);
  473. return equals;
  474. }
  475. ALWAYS_INLINE void OpCode_Compare::compare_character_class(MatchInput const& input, MatchState& state, CharClass character_class, u32 ch, bool inverse, bool& inverse_matched)
  476. {
  477. switch (character_class) {
  478. case CharClass::Alnum:
  479. if (is_ascii_alphanumeric(ch)) {
  480. if (inverse)
  481. inverse_matched = true;
  482. else
  483. advance_string_position(state, input.view, ch);
  484. }
  485. break;
  486. case CharClass::Alpha:
  487. if (is_ascii_alpha(ch))
  488. advance_string_position(state, input.view, ch);
  489. break;
  490. case CharClass::Blank:
  491. if (is_ascii_blank(ch)) {
  492. if (inverse)
  493. inverse_matched = true;
  494. else
  495. advance_string_position(state, input.view, ch);
  496. }
  497. break;
  498. case CharClass::Cntrl:
  499. if (is_ascii_control(ch)) {
  500. if (inverse)
  501. inverse_matched = true;
  502. else
  503. advance_string_position(state, input.view, ch);
  504. }
  505. break;
  506. case CharClass::Digit:
  507. if (is_ascii_digit(ch)) {
  508. if (inverse)
  509. inverse_matched = true;
  510. else
  511. advance_string_position(state, input.view, ch);
  512. }
  513. break;
  514. case CharClass::Graph:
  515. if (is_ascii_graphical(ch)) {
  516. if (inverse)
  517. inverse_matched = true;
  518. else
  519. advance_string_position(state, input.view, ch);
  520. }
  521. break;
  522. case CharClass::Lower:
  523. if (is_ascii_lower_alpha(ch) || ((input.regex_options & AllFlags::Insensitive) && is_ascii_upper_alpha(ch))) {
  524. if (inverse)
  525. inverse_matched = true;
  526. else
  527. advance_string_position(state, input.view, ch);
  528. }
  529. break;
  530. case CharClass::Print:
  531. if (is_ascii_printable(ch)) {
  532. if (inverse)
  533. inverse_matched = true;
  534. else
  535. advance_string_position(state, input.view, ch);
  536. }
  537. break;
  538. case CharClass::Punct:
  539. if (is_ascii_punctuation(ch)) {
  540. if (inverse)
  541. inverse_matched = true;
  542. else
  543. advance_string_position(state, input.view, ch);
  544. }
  545. break;
  546. case CharClass::Space:
  547. if (is_ascii_space(ch)) {
  548. if (inverse)
  549. inverse_matched = true;
  550. else
  551. advance_string_position(state, input.view, ch);
  552. }
  553. break;
  554. case CharClass::Upper:
  555. if (is_ascii_upper_alpha(ch) || ((input.regex_options & AllFlags::Insensitive) && is_ascii_lower_alpha(ch))) {
  556. if (inverse)
  557. inverse_matched = true;
  558. else
  559. advance_string_position(state, input.view, ch);
  560. }
  561. break;
  562. case CharClass::Word:
  563. if (is_ascii_alphanumeric(ch) || ch == '_') {
  564. if (inverse)
  565. inverse_matched = true;
  566. else
  567. advance_string_position(state, input.view, ch);
  568. }
  569. break;
  570. case CharClass::Xdigit:
  571. if (is_ascii_hex_digit(ch)) {
  572. if (inverse)
  573. inverse_matched = true;
  574. else
  575. advance_string_position(state, input.view, ch);
  576. }
  577. break;
  578. }
  579. }
  580. ALWAYS_INLINE void OpCode_Compare::compare_character_range(MatchInput const& input, MatchState& state, u32 from, u32 to, u32 ch, bool inverse, bool& inverse_matched)
  581. {
  582. if (input.regex_options & AllFlags::Insensitive) {
  583. from = to_ascii_lowercase(from);
  584. to = to_ascii_lowercase(to);
  585. ch = to_ascii_lowercase(ch);
  586. }
  587. if (ch >= from && ch <= to) {
  588. if (inverse)
  589. inverse_matched = true;
  590. else
  591. advance_string_position(state, input.view, ch);
  592. }
  593. }
  594. ALWAYS_INLINE void OpCode_Compare::compare_property(MatchInput const& input, MatchState& state, Unicode::Property property, bool inverse, bool& inverse_matched)
  595. {
  596. if (state.string_position == input.view.length())
  597. return;
  598. u32 code_point = input.view[state.string_position_in_code_units];
  599. bool equal = Unicode::code_point_has_property(code_point, property);
  600. if (equal) {
  601. if (inverse)
  602. inverse_matched = true;
  603. else
  604. advance_string_position(state, input.view, code_point);
  605. }
  606. }
  607. ALWAYS_INLINE void OpCode_Compare::compare_general_category(MatchInput const& input, MatchState& state, Unicode::GeneralCategory general_category, bool inverse, bool& inverse_matched)
  608. {
  609. if (state.string_position == input.view.length())
  610. return;
  611. u32 code_point = input.view[state.string_position_in_code_units];
  612. bool equal = Unicode::code_point_has_general_category(code_point, general_category);
  613. if (equal) {
  614. if (inverse)
  615. inverse_matched = true;
  616. else
  617. advance_string_position(state, input.view, code_point);
  618. }
  619. }
  620. ALWAYS_INLINE void OpCode_Compare::compare_script(MatchInput const& input, MatchState& state, Unicode::Script script, bool inverse, bool& inverse_matched)
  621. {
  622. if (state.string_position == input.view.length())
  623. return;
  624. u32 code_point = input.view[state.string_position_in_code_units];
  625. bool equal = Unicode::code_point_has_script(code_point, script);
  626. if (equal) {
  627. if (inverse)
  628. inverse_matched = true;
  629. else
  630. advance_string_position(state, input.view, code_point);
  631. }
  632. }
  633. ALWAYS_INLINE void OpCode_Compare::compare_script_extension(MatchInput const& input, MatchState& state, Unicode::Script script, bool inverse, bool& inverse_matched)
  634. {
  635. if (state.string_position == input.view.length())
  636. return;
  637. u32 code_point = input.view[state.string_position_in_code_units];
  638. bool equal = Unicode::code_point_has_script_extension(code_point, script);
  639. if (equal) {
  640. if (inverse)
  641. inverse_matched = true;
  642. else
  643. advance_string_position(state, input.view, code_point);
  644. }
  645. }
  646. String const OpCode_Compare::arguments_string() const
  647. {
  648. return String::formatted("argc={}, args={} ", arguments_count(), arguments_size());
  649. }
  650. Vector<String> const OpCode_Compare::variable_arguments_to_string(Optional<MatchInput> input) const
  651. {
  652. Vector<String> result;
  653. size_t offset { state().instruction_position + 3 };
  654. RegexStringView view = ((input.has_value()) ? input.value().view : nullptr);
  655. for (size_t i = 0; i < arguments_count(); ++i) {
  656. auto compare_type = (CharacterCompareType)m_bytecode->at(offset++);
  657. result.empend(String::formatted("type={} [{}]", (size_t)compare_type, character_compare_type_name(compare_type)));
  658. auto string_start_offset = state().string_position_before_match;
  659. if (compare_type == CharacterCompareType::Char) {
  660. auto ch = m_bytecode->at(offset++);
  661. auto is_ascii = is_ascii_printable(ch);
  662. if (is_ascii)
  663. result.empend(String::formatted("value='{:c}'", static_cast<char>(ch)));
  664. else
  665. result.empend(String::formatted("value={:x}", ch));
  666. if (!view.is_null() && view.length() > string_start_offset) {
  667. if (is_ascii) {
  668. result.empend(String::formatted(
  669. "compare against: '{}'",
  670. view.substring_view(string_start_offset, string_start_offset > view.length() ? 0 : 1).to_string()));
  671. } else {
  672. auto str = view.substring_view(string_start_offset, string_start_offset > view.length() ? 0 : 1).to_string();
  673. u8 buf[8] { 0 };
  674. __builtin_memcpy(buf, str.characters(), min(str.length(), sizeof(buf)));
  675. result.empend(String::formatted("compare against: {:x},{:x},{:x},{:x},{:x},{:x},{:x},{:x}",
  676. buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]));
  677. }
  678. }
  679. } else if (compare_type == CharacterCompareType::Reference) {
  680. auto ref = m_bytecode->at(offset++);
  681. result.empend(String::formatted("number={}", ref));
  682. } else if (compare_type == CharacterCompareType::String) {
  683. auto& length = m_bytecode->at(offset++);
  684. StringBuilder str_builder;
  685. for (size_t i = 0; i < length; ++i)
  686. str_builder.append(m_bytecode->at(offset++));
  687. result.empend(String::formatted("value=\"{}\"", str_builder.string_view().substring_view(0, length)));
  688. if (!view.is_null() && view.length() > state().string_position)
  689. result.empend(String::formatted(
  690. "compare against: \"{}\"",
  691. input.value().view.substring_view(string_start_offset, string_start_offset + length > view.length() ? 0 : length).to_string()));
  692. } else if (compare_type == CharacterCompareType::CharClass) {
  693. auto character_class = (CharClass)m_bytecode->at(offset++);
  694. result.empend(String::formatted("ch_class={} [{}]", (size_t)character_class, character_class_name(character_class)));
  695. if (!view.is_null() && view.length() > state().string_position)
  696. result.empend(String::formatted(
  697. "compare against: '{}'",
  698. input.value().view.substring_view(string_start_offset, state().string_position > view.length() ? 0 : 1).to_string()));
  699. } else if (compare_type == CharacterCompareType::CharRange) {
  700. auto value = (CharRange)m_bytecode->at(offset++);
  701. result.empend(String::formatted("ch_range='{:c}'-'{:c}'", value.from, value.to));
  702. if (!view.is_null() && view.length() > state().string_position)
  703. result.empend(String::formatted(
  704. "compare against: '{}'",
  705. input.value().view.substring_view(string_start_offset, state().string_position > view.length() ? 0 : 1).to_string()));
  706. }
  707. }
  708. return result;
  709. }
  710. ALWAYS_INLINE ExecutionResult OpCode_Repeat::execute(MatchInput const&, MatchState& state) const
  711. {
  712. VERIFY(count() > 0);
  713. if (id() >= state.repetition_marks.size())
  714. state.repetition_marks.resize(id() + 1);
  715. auto& repetition_mark = state.repetition_marks.at(id());
  716. if (repetition_mark == count() - 1) {
  717. repetition_mark = 0;
  718. } else {
  719. state.instruction_position -= offset() + size();
  720. ++repetition_mark;
  721. }
  722. return ExecutionResult::Continue;
  723. }
  724. ALWAYS_INLINE ExecutionResult OpCode_ResetRepeat::execute(MatchInput const&, MatchState& state) const
  725. {
  726. if (id() >= state.repetition_marks.size())
  727. state.repetition_marks.resize(id() + 1);
  728. state.repetition_marks.at(id()) = 0;
  729. return ExecutionResult::Continue;
  730. }
  731. ALWAYS_INLINE ExecutionResult OpCode_Checkpoint::execute(MatchInput const&, MatchState& state) const
  732. {
  733. state.checkpoints.set(state.instruction_position, state.string_position);
  734. return ExecutionResult::Continue;
  735. }
  736. ALWAYS_INLINE ExecutionResult OpCode_JumpNonEmpty::execute(MatchInput const&, MatchState& state) const
  737. {
  738. auto current_position = state.string_position;
  739. auto checkpoint_ip = state.instruction_position + size() + checkpoint();
  740. if (state.checkpoints.get(checkpoint_ip).value_or(current_position) != current_position) {
  741. auto form = this->form();
  742. if (form == OpCodeId::Jump) {
  743. state.instruction_position += offset();
  744. return ExecutionResult::Continue;
  745. }
  746. state.fork_at_position = state.instruction_position + size() + offset();
  747. if (form == OpCodeId::ForkJump)
  748. return ExecutionResult::Fork_PrioHigh;
  749. if (form == OpCodeId::ForkStay)
  750. return ExecutionResult::Fork_PrioLow;
  751. }
  752. return ExecutionResult::Continue;
  753. }
  754. }