RegexByteCode.cpp 32 KB

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