RegexByteCode.cpp 33 KB

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