RegexByteCode.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  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 "RegexDebug.h"
  8. #include <AK/BinarySearch.h>
  9. #include <AK/CharacterTypes.h>
  10. #include <AK/StringBuilder.h>
  11. #include <LibUnicode/CharacterTypes.h>
  12. // U+2028 LINE SEPARATOR
  13. constexpr static u32 const LineSeparator { 0x2028 };
  14. // U+2029 PARAGRAPH SEPARATOR
  15. constexpr static u32 const ParagraphSeparator { 0x2029 };
  16. namespace regex {
  17. StringView OpCode::name(OpCodeId opcode_id)
  18. {
  19. switch (opcode_id) {
  20. #define __ENUMERATE_OPCODE(x) \
  21. case OpCodeId::x: \
  22. return #x##sv;
  23. ENUMERATE_OPCODES
  24. #undef __ENUMERATE_OPCODE
  25. default:
  26. VERIFY_NOT_REACHED();
  27. return "<Unknown>"sv;
  28. }
  29. }
  30. StringView OpCode::name() const
  31. {
  32. return name(opcode_id());
  33. }
  34. StringView execution_result_name(ExecutionResult result)
  35. {
  36. switch (result) {
  37. #define __ENUMERATE_EXECUTION_RESULT(x) \
  38. case ExecutionResult::x: \
  39. return #x##sv;
  40. ENUMERATE_EXECUTION_RESULTS
  41. #undef __ENUMERATE_EXECUTION_RESULT
  42. default:
  43. VERIFY_NOT_REACHED();
  44. return "<Unknown>"sv;
  45. }
  46. }
  47. StringView opcode_id_name(OpCodeId opcode)
  48. {
  49. switch (opcode) {
  50. #define __ENUMERATE_OPCODE(x) \
  51. case OpCodeId::x: \
  52. return #x##sv;
  53. ENUMERATE_OPCODES
  54. #undef __ENUMERATE_OPCODE
  55. default:
  56. VERIFY_NOT_REACHED();
  57. return "<Unknown>"sv;
  58. }
  59. }
  60. StringView boundary_check_type_name(BoundaryCheckType ty)
  61. {
  62. switch (ty) {
  63. #define __ENUMERATE_BOUNDARY_CHECK_TYPE(x) \
  64. case BoundaryCheckType::x: \
  65. return #x##sv;
  66. ENUMERATE_BOUNDARY_CHECK_TYPES
  67. #undef __ENUMERATE_BOUNDARY_CHECK_TYPE
  68. default:
  69. VERIFY_NOT_REACHED();
  70. return "<Unknown>"sv;
  71. }
  72. }
  73. StringView character_compare_type_name(CharacterCompareType ch_compare_type)
  74. {
  75. switch (ch_compare_type) {
  76. #define __ENUMERATE_CHARACTER_COMPARE_TYPE(x) \
  77. case CharacterCompareType::x: \
  78. return #x##sv;
  79. ENUMERATE_CHARACTER_COMPARE_TYPES
  80. #undef __ENUMERATE_CHARACTER_COMPARE_TYPE
  81. default:
  82. VERIFY_NOT_REACHED();
  83. return "<Unknown>"sv;
  84. }
  85. }
  86. static StringView character_class_name(CharClass ch_class)
  87. {
  88. switch (ch_class) {
  89. #define __ENUMERATE_CHARACTER_CLASS(x) \
  90. case CharClass::x: \
  91. return #x##sv;
  92. ENUMERATE_CHARACTER_CLASSES
  93. #undef __ENUMERATE_CHARACTER_CLASS
  94. default:
  95. VERIFY_NOT_REACHED();
  96. return "<Unknown>"sv;
  97. }
  98. }
  99. static void advance_string_position(MatchState& state, RegexStringView view, Optional<u32> code_point = {})
  100. {
  101. ++state.string_position;
  102. if (view.unicode()) {
  103. if (!code_point.has_value() && (state.string_position_in_code_units < view.length_in_code_units()))
  104. code_point = view[state.string_position_in_code_units];
  105. if (code_point.has_value())
  106. state.string_position_in_code_units += view.length_of_code_point(*code_point);
  107. } else {
  108. ++state.string_position_in_code_units;
  109. }
  110. }
  111. static void advance_string_position(MatchState& state, RegexStringView, RegexStringView advance_by)
  112. {
  113. state.string_position += advance_by.length();
  114. state.string_position_in_code_units += advance_by.length_in_code_units();
  115. }
  116. static void reverse_string_position(MatchState& state, RegexStringView view, size_t amount)
  117. {
  118. VERIFY(state.string_position >= amount);
  119. state.string_position -= amount;
  120. if (view.unicode())
  121. state.string_position_in_code_units = view.code_unit_offset_of(state.string_position);
  122. else
  123. state.string_position_in_code_units -= amount;
  124. }
  125. static void save_string_position(MatchInput const& input, MatchState const& state)
  126. {
  127. input.saved_positions.append(state.string_position);
  128. input.saved_forks_since_last_save.append(state.forks_since_last_save);
  129. input.saved_code_unit_positions.append(state.string_position_in_code_units);
  130. }
  131. static bool restore_string_position(MatchInput const& input, MatchState& state)
  132. {
  133. if (input.saved_positions.is_empty())
  134. return false;
  135. state.string_position = input.saved_positions.take_last();
  136. state.string_position_in_code_units = input.saved_code_unit_positions.take_last();
  137. state.forks_since_last_save = input.saved_forks_since_last_save.take_last();
  138. return true;
  139. }
  140. OwnPtr<OpCode> ByteCode::s_opcodes[(size_t)OpCodeId::Last + 1];
  141. bool ByteCode::s_opcodes_initialized { false };
  142. size_t ByteCode::s_next_checkpoint_serial_id { 0 };
  143. void ByteCode::ensure_opcodes_initialized()
  144. {
  145. if (s_opcodes_initialized)
  146. return;
  147. for (u32 i = (u32)OpCodeId::First; i <= (u32)OpCodeId::Last; ++i) {
  148. switch ((OpCodeId)i) {
  149. #define __ENUMERATE_OPCODE(OpCode) \
  150. case OpCodeId::OpCode: \
  151. s_opcodes[i] = make<OpCode_##OpCode>(); \
  152. break;
  153. ENUMERATE_OPCODES
  154. #undef __ENUMERATE_OPCODE
  155. }
  156. }
  157. s_opcodes_initialized = true;
  158. }
  159. ALWAYS_INLINE OpCode& ByteCode::get_opcode_by_id(OpCodeId id) const
  160. {
  161. VERIFY(id >= OpCodeId::First && id <= OpCodeId::Last);
  162. auto& opcode = s_opcodes[(u32)id];
  163. opcode->set_bytecode(*const_cast<ByteCode*>(this));
  164. return *opcode;
  165. }
  166. OpCode& ByteCode::get_opcode(MatchState& state) const
  167. {
  168. OpCodeId opcode_id;
  169. if (auto opcode_ptr = static_cast<DisjointChunks<ByteCodeValueType> const&>(*this).find(state.instruction_position))
  170. opcode_id = (OpCodeId)*opcode_ptr;
  171. else
  172. opcode_id = OpCodeId::Exit;
  173. auto& opcode = get_opcode_by_id(opcode_id);
  174. opcode.set_state(state);
  175. return opcode;
  176. }
  177. ALWAYS_INLINE ExecutionResult OpCode_Exit::execute(MatchInput const& input, MatchState& state) const
  178. {
  179. if (state.string_position > input.view.length() || state.instruction_position >= m_bytecode->size())
  180. return ExecutionResult::Succeeded;
  181. return ExecutionResult::Failed;
  182. }
  183. ALWAYS_INLINE ExecutionResult OpCode_Save::execute(MatchInput const& input, MatchState& state) const
  184. {
  185. save_string_position(input, state);
  186. state.forks_since_last_save = 0;
  187. return ExecutionResult::Continue;
  188. }
  189. ALWAYS_INLINE ExecutionResult OpCode_Restore::execute(MatchInput const& input, MatchState& state) const
  190. {
  191. if (!restore_string_position(input, state))
  192. return ExecutionResult::Failed;
  193. return ExecutionResult::Continue;
  194. }
  195. ALWAYS_INLINE ExecutionResult OpCode_GoBack::execute(MatchInput const& input, MatchState& state) const
  196. {
  197. if (count() > state.string_position)
  198. return ExecutionResult::Failed_ExecuteLowPrioForks;
  199. reverse_string_position(state, input.view, count());
  200. return ExecutionResult::Continue;
  201. }
  202. ALWAYS_INLINE ExecutionResult OpCode_FailForks::execute(MatchInput const& input, MatchState& state) const
  203. {
  204. input.fail_counter += state.forks_since_last_save;
  205. return ExecutionResult::Failed_ExecuteLowPrioForks;
  206. }
  207. ALWAYS_INLINE ExecutionResult OpCode_Jump::execute(MatchInput const&, MatchState& state) const
  208. {
  209. state.instruction_position += offset();
  210. return ExecutionResult::Continue;
  211. }
  212. ALWAYS_INLINE ExecutionResult OpCode_ForkJump::execute(MatchInput const&, MatchState& state) const
  213. {
  214. state.fork_at_position = state.instruction_position + size() + offset();
  215. state.forks_since_last_save++;
  216. return ExecutionResult::Fork_PrioHigh;
  217. }
  218. ALWAYS_INLINE ExecutionResult OpCode_ForkReplaceJump::execute(MatchInput const& input, MatchState& state) const
  219. {
  220. state.fork_at_position = state.instruction_position + size() + offset();
  221. input.fork_to_replace = state.instruction_position;
  222. state.forks_since_last_save++;
  223. return ExecutionResult::Fork_PrioHigh;
  224. }
  225. ALWAYS_INLINE ExecutionResult OpCode_ForkStay::execute(MatchInput const&, MatchState& state) const
  226. {
  227. state.fork_at_position = state.instruction_position + size() + offset();
  228. state.forks_since_last_save++;
  229. return ExecutionResult::Fork_PrioLow;
  230. }
  231. ALWAYS_INLINE ExecutionResult OpCode_ForkReplaceStay::execute(MatchInput const& input, MatchState& state) const
  232. {
  233. state.fork_at_position = state.instruction_position + size() + offset();
  234. input.fork_to_replace = state.instruction_position;
  235. return ExecutionResult::Fork_PrioLow;
  236. }
  237. ALWAYS_INLINE ExecutionResult OpCode_CheckBegin::execute(MatchInput const& input, MatchState& state) const
  238. {
  239. auto is_at_line_boundary = [&] {
  240. if (state.string_position == 0)
  241. return true;
  242. if (input.regex_options.has_flag_set(AllFlags::Multiline) && input.regex_options.has_flag_set(AllFlags::Internal_ConsiderNewline)) {
  243. auto input_view = input.view.substring_view(state.string_position - 1, 1)[0];
  244. return input_view == '\r' || input_view == '\n' || input_view == LineSeparator || input_view == ParagraphSeparator;
  245. }
  246. return false;
  247. }();
  248. if (is_at_line_boundary && (input.regex_options & AllFlags::MatchNotBeginOfLine))
  249. return ExecutionResult::Failed_ExecuteLowPrioForks;
  250. if ((is_at_line_boundary && !(input.regex_options & AllFlags::MatchNotBeginOfLine))
  251. || (!is_at_line_boundary && (input.regex_options & AllFlags::MatchNotBeginOfLine))
  252. || (is_at_line_boundary && (input.regex_options & AllFlags::Global)))
  253. return ExecutionResult::Continue;
  254. return ExecutionResult::Failed_ExecuteLowPrioForks;
  255. }
  256. ALWAYS_INLINE ExecutionResult OpCode_CheckBoundary::execute(MatchInput const& input, MatchState& state) const
  257. {
  258. auto isword = [](auto ch) { return is_ascii_alphanumeric(ch) || ch == '_'; };
  259. auto is_word_boundary = [&] {
  260. if (state.string_position == input.view.length()) {
  261. return (state.string_position > 0 && isword(input.view[state.string_position_in_code_units - 1]));
  262. }
  263. if (state.string_position == 0) {
  264. return (isword(input.view[0]));
  265. }
  266. return !!(isword(input.view[state.string_position_in_code_units]) ^ isword(input.view[state.string_position_in_code_units - 1]));
  267. };
  268. switch (type()) {
  269. case BoundaryCheckType::Word: {
  270. if (is_word_boundary())
  271. return ExecutionResult::Continue;
  272. return ExecutionResult::Failed_ExecuteLowPrioForks;
  273. }
  274. case BoundaryCheckType::NonWord: {
  275. if (!is_word_boundary())
  276. return ExecutionResult::Continue;
  277. return ExecutionResult::Failed_ExecuteLowPrioForks;
  278. }
  279. }
  280. VERIFY_NOT_REACHED();
  281. }
  282. ALWAYS_INLINE ExecutionResult OpCode_CheckEnd::execute(MatchInput const& input, MatchState& state) const
  283. {
  284. auto is_at_line_boundary = [&] {
  285. if (state.string_position == input.view.length())
  286. return true;
  287. if (input.regex_options.has_flag_set(AllFlags::Multiline) && input.regex_options.has_flag_set(AllFlags::Internal_ConsiderNewline)) {
  288. auto input_view = input.view.substring_view(state.string_position, 1)[0];
  289. return input_view == '\r' || input_view == '\n' || input_view == LineSeparator || input_view == ParagraphSeparator;
  290. }
  291. return false;
  292. }();
  293. if (is_at_line_boundary && (input.regex_options & AllFlags::MatchNotEndOfLine))
  294. return ExecutionResult::Failed_ExecuteLowPrioForks;
  295. if ((is_at_line_boundary && !(input.regex_options & AllFlags::MatchNotEndOfLine))
  296. || (!is_at_line_boundary && (input.regex_options & AllFlags::MatchNotEndOfLine || input.regex_options & AllFlags::MatchNotBeginOfLine)))
  297. return ExecutionResult::Continue;
  298. return ExecutionResult::Failed_ExecuteLowPrioForks;
  299. }
  300. ALWAYS_INLINE ExecutionResult OpCode_ClearCaptureGroup::execute(MatchInput const& input, MatchState& state) const
  301. {
  302. if (input.match_index < state.capture_group_matches.size()) {
  303. auto& group = state.capture_group_matches[input.match_index];
  304. auto group_id = id();
  305. if (group_id >= group.size())
  306. group.resize(group_id + 1);
  307. group[group_id].reset();
  308. }
  309. return ExecutionResult::Continue;
  310. }
  311. ALWAYS_INLINE ExecutionResult OpCode_SaveLeftCaptureGroup::execute(MatchInput const& input, MatchState& state) const
  312. {
  313. if (input.match_index >= state.capture_group_matches.size()) {
  314. state.capture_group_matches.ensure_capacity(input.match_index);
  315. auto capacity = state.capture_group_matches.capacity();
  316. for (size_t i = state.capture_group_matches.size(); i <= capacity; ++i)
  317. state.capture_group_matches.empend();
  318. }
  319. if (id() >= state.capture_group_matches.at(input.match_index).size()) {
  320. state.capture_group_matches.at(input.match_index).ensure_capacity(id());
  321. auto capacity = state.capture_group_matches.at(input.match_index).capacity();
  322. for (size_t i = state.capture_group_matches.at(input.match_index).size(); i <= capacity; ++i)
  323. state.capture_group_matches.at(input.match_index).empend();
  324. }
  325. state.capture_group_matches.at(input.match_index).at(id()).left_column = state.string_position;
  326. return ExecutionResult::Continue;
  327. }
  328. ALWAYS_INLINE ExecutionResult OpCode_SaveRightCaptureGroup::execute(MatchInput const& input, MatchState& state) const
  329. {
  330. auto& match = state.capture_group_matches.at(input.match_index).at(id());
  331. auto start_position = match.left_column;
  332. if (state.string_position < start_position) {
  333. dbgln("Right capture group {} is before left capture group {}!", state.string_position, start_position);
  334. return ExecutionResult::Failed_ExecuteLowPrioForks;
  335. }
  336. auto length = state.string_position - start_position;
  337. if (start_position < match.column)
  338. return ExecutionResult::Continue;
  339. VERIFY(start_position + length <= input.view.length());
  340. auto view = input.view.substring_view(start_position, length);
  341. if (input.regex_options & AllFlags::StringCopyMatches) {
  342. match = { view.to_deprecated_string(), input.line, start_position, input.global_offset + start_position }; // create a copy of the original string
  343. } else {
  344. match = { view, input.line, start_position, input.global_offset + start_position }; // take view to original string
  345. }
  346. return ExecutionResult::Continue;
  347. }
  348. ALWAYS_INLINE ExecutionResult OpCode_SaveRightNamedCaptureGroup::execute(MatchInput const& input, MatchState& state) const
  349. {
  350. auto& match = state.capture_group_matches.at(input.match_index).at(id());
  351. auto start_position = match.left_column;
  352. if (state.string_position < start_position)
  353. return ExecutionResult::Failed_ExecuteLowPrioForks;
  354. auto length = state.string_position - start_position;
  355. if (start_position < match.column)
  356. return ExecutionResult::Continue;
  357. VERIFY(start_position + length <= input.view.length());
  358. auto view = input.view.substring_view(start_position, length);
  359. if (input.regex_options & AllFlags::StringCopyMatches) {
  360. match = { view.to_deprecated_string(), name(), input.line, start_position, input.global_offset + start_position }; // create a copy of the original string
  361. } else {
  362. match = { view, name(), input.line, start_position, input.global_offset + start_position }; // take view to original string
  363. }
  364. return ExecutionResult::Continue;
  365. }
  366. ALWAYS_INLINE ExecutionResult OpCode_Compare::execute(MatchInput const& input, MatchState& state) const
  367. {
  368. bool inverse { false };
  369. bool temporary_inverse { false };
  370. bool reset_temp_inverse { false };
  371. struct DisjunctionState {
  372. bool active { false };
  373. bool is_conjunction { false };
  374. bool fail { false };
  375. size_t initial_position;
  376. size_t initial_code_unit_position;
  377. Optional<size_t> last_accepted_position {};
  378. Optional<size_t> last_accepted_code_unit_position {};
  379. };
  380. Vector<DisjunctionState, 4> disjunction_states;
  381. disjunction_states.empend();
  382. auto current_disjunction_state = [&]() -> DisjunctionState& { return disjunction_states.last(); };
  383. auto current_inversion_state = [&]() -> bool { return temporary_inverse ^ inverse; };
  384. size_t string_position = state.string_position;
  385. bool inverse_matched { false };
  386. bool had_zero_length_match { false };
  387. state.string_position_before_match = state.string_position;
  388. size_t offset { state.instruction_position + 3 };
  389. for (size_t i = 0; i < arguments_count(); ++i) {
  390. if (state.string_position > string_position)
  391. break;
  392. if (reset_temp_inverse) {
  393. reset_temp_inverse = false;
  394. temporary_inverse = false;
  395. } else {
  396. reset_temp_inverse = true;
  397. }
  398. auto compare_type = (CharacterCompareType)m_bytecode->at(offset++);
  399. if (compare_type == CharacterCompareType::Inverse) {
  400. inverse = !inverse;
  401. continue;
  402. } else if (compare_type == CharacterCompareType::TemporaryInverse) {
  403. // If "TemporaryInverse" is given, negate the current inversion state only for the next opcode.
  404. // it follows that this cannot be the last compare element.
  405. VERIFY(i != arguments_count() - 1);
  406. temporary_inverse = true;
  407. reset_temp_inverse = false;
  408. continue;
  409. } else if (compare_type == CharacterCompareType::Char) {
  410. u32 ch = m_bytecode->at(offset++);
  411. // We want to compare a string that is longer or equal in length to the available string
  412. if (input.view.length() <= state.string_position)
  413. return ExecutionResult::Failed_ExecuteLowPrioForks;
  414. compare_char(input, state, ch, current_inversion_state(), inverse_matched);
  415. } else if (compare_type == CharacterCompareType::AnyChar) {
  416. // We want to compare a string that is definitely longer than the available string
  417. if (input.view.length() <= state.string_position)
  418. return ExecutionResult::Failed_ExecuteLowPrioForks;
  419. auto input_view = input.view.substring_view(state.string_position, 1)[0];
  420. auto is_equivalent_to_newline = input_view == '\n'
  421. || (input.regex_options.has_flag_set(AllFlags::Internal_ECMA262DotSemantics)
  422. ? (input_view == '\r' || input_view == LineSeparator || input_view == ParagraphSeparator)
  423. : false);
  424. if (!is_equivalent_to_newline || (input.regex_options.has_flag_set(AllFlags::SingleLine) && input.regex_options.has_flag_set(AllFlags::Internal_ConsiderNewline))) {
  425. if (current_inversion_state())
  426. inverse_matched = true;
  427. else
  428. advance_string_position(state, input.view, input_view);
  429. }
  430. } else if (compare_type == CharacterCompareType::String) {
  431. VERIFY(!current_inversion_state());
  432. auto const& length = m_bytecode->at(offset++);
  433. // We want to compare a string that is definitely longer than the available string
  434. if (input.view.length() < state.string_position + length)
  435. return ExecutionResult::Failed_ExecuteLowPrioForks;
  436. Optional<DeprecatedString> str;
  437. Utf16Data utf16;
  438. Vector<u32> data;
  439. data.ensure_capacity(length);
  440. for (size_t i = offset; i < offset + length; ++i)
  441. data.unchecked_append(m_bytecode->at(i));
  442. auto view = input.view.construct_as_same(data, str, utf16);
  443. offset += length;
  444. if (compare_string(input, state, view, had_zero_length_match)) {
  445. if (current_inversion_state())
  446. inverse_matched = true;
  447. }
  448. } else if (compare_type == CharacterCompareType::CharClass) {
  449. if (input.view.length() <= state.string_position_in_code_units)
  450. return ExecutionResult::Failed_ExecuteLowPrioForks;
  451. auto character_class = (CharClass)m_bytecode->at(offset++);
  452. auto ch = input.view[state.string_position_in_code_units];
  453. compare_character_class(input, state, character_class, ch, current_inversion_state(), inverse_matched);
  454. } else if (compare_type == CharacterCompareType::LookupTable) {
  455. if (input.view.length() <= state.string_position)
  456. return ExecutionResult::Failed_ExecuteLowPrioForks;
  457. auto count = m_bytecode->at(offset++);
  458. auto range_data = m_bytecode->template spans<4>().slice(offset, count);
  459. offset += count;
  460. auto ch = input.view.substring_view(state.string_position, 1)[0];
  461. auto const* matching_range = binary_search(range_data, ch, nullptr, [insensitive = input.regex_options & AllFlags::Insensitive](auto needle, CharRange range) {
  462. auto upper_case_needle = needle;
  463. auto lower_case_needle = needle;
  464. if (insensitive) {
  465. upper_case_needle = to_ascii_uppercase(needle);
  466. lower_case_needle = to_ascii_lowercase(needle);
  467. }
  468. if (lower_case_needle >= range.from && lower_case_needle <= range.to)
  469. return 0;
  470. if (upper_case_needle >= range.from && upper_case_needle <= range.to)
  471. return 0;
  472. if (lower_case_needle > range.to || upper_case_needle > range.to)
  473. return 1;
  474. return -1;
  475. });
  476. if (matching_range) {
  477. if (current_inversion_state())
  478. inverse_matched = true;
  479. else
  480. advance_string_position(state, input.view, ch);
  481. }
  482. } else if (compare_type == CharacterCompareType::CharRange) {
  483. if (input.view.length() <= state.string_position)
  484. return ExecutionResult::Failed_ExecuteLowPrioForks;
  485. auto value = (CharRange)m_bytecode->at(offset++);
  486. auto from = value.from;
  487. auto to = value.to;
  488. auto ch = input.view[state.string_position_in_code_units];
  489. compare_character_range(input, state, from, to, ch, current_inversion_state(), inverse_matched);
  490. } else if (compare_type == CharacterCompareType::Reference) {
  491. auto reference_number = (size_t)m_bytecode->at(offset++);
  492. auto& groups = state.capture_group_matches.at(input.match_index);
  493. if (groups.size() <= reference_number)
  494. return ExecutionResult::Failed_ExecuteLowPrioForks;
  495. auto str = groups.at(reference_number).view;
  496. // We want to compare a string that is definitely longer than the available string
  497. if (input.view.length() < state.string_position + str.length())
  498. return ExecutionResult::Failed_ExecuteLowPrioForks;
  499. if (compare_string(input, state, str, had_zero_length_match)) {
  500. if (current_inversion_state())
  501. inverse_matched = true;
  502. }
  503. } else if (compare_type == CharacterCompareType::Property) {
  504. auto property = static_cast<Unicode::Property>(m_bytecode->at(offset++));
  505. compare_property(input, state, property, current_inversion_state(), inverse_matched);
  506. } else if (compare_type == CharacterCompareType::GeneralCategory) {
  507. auto general_category = static_cast<Unicode::GeneralCategory>(m_bytecode->at(offset++));
  508. compare_general_category(input, state, general_category, current_inversion_state(), inverse_matched);
  509. } else if (compare_type == CharacterCompareType::Script) {
  510. auto script = static_cast<Unicode::Script>(m_bytecode->at(offset++));
  511. compare_script(input, state, script, current_inversion_state(), inverse_matched);
  512. } else if (compare_type == CharacterCompareType::ScriptExtension) {
  513. auto script = static_cast<Unicode::Script>(m_bytecode->at(offset++));
  514. compare_script_extension(input, state, script, current_inversion_state(), inverse_matched);
  515. } else if (compare_type == CharacterCompareType::And) {
  516. disjunction_states.append({
  517. .active = true,
  518. .is_conjunction = false,
  519. .fail = false,
  520. .initial_position = state.string_position,
  521. .initial_code_unit_position = state.string_position_in_code_units,
  522. });
  523. continue;
  524. } else if (compare_type == CharacterCompareType::Or) {
  525. disjunction_states.append({
  526. .active = true,
  527. .is_conjunction = true,
  528. .fail = true,
  529. .initial_position = state.string_position,
  530. .initial_code_unit_position = state.string_position_in_code_units,
  531. });
  532. continue;
  533. } else if (compare_type == CharacterCompareType::EndAndOr) {
  534. auto disjunction_state = disjunction_states.take_last();
  535. if (!disjunction_state.fail) {
  536. state.string_position = disjunction_state.last_accepted_position.value_or(disjunction_state.initial_position);
  537. state.string_position_in_code_units = disjunction_state.last_accepted_code_unit_position.value_or(disjunction_state.initial_code_unit_position);
  538. }
  539. } else {
  540. warnln("Undefined comparison: {}", (int)compare_type);
  541. VERIFY_NOT_REACHED();
  542. break;
  543. }
  544. auto& new_disjunction_state = current_disjunction_state();
  545. if (current_inversion_state() && (!inverse || new_disjunction_state.active) && !inverse_matched) {
  546. advance_string_position(state, input.view);
  547. inverse_matched = true;
  548. }
  549. if (new_disjunction_state.active) {
  550. auto failed = (!had_zero_length_match && string_position == state.string_position) || state.string_position > input.view.length();
  551. if (!failed) {
  552. new_disjunction_state.last_accepted_position = state.string_position;
  553. new_disjunction_state.last_accepted_code_unit_position = state.string_position_in_code_units;
  554. }
  555. if (new_disjunction_state.is_conjunction)
  556. new_disjunction_state.fail = failed && new_disjunction_state.fail;
  557. else
  558. new_disjunction_state.fail = failed || new_disjunction_state.fail;
  559. state.string_position = new_disjunction_state.initial_position;
  560. state.string_position_in_code_units = new_disjunction_state.initial_code_unit_position;
  561. }
  562. }
  563. auto& new_disjunction_state = current_disjunction_state();
  564. if (new_disjunction_state.active) {
  565. if (!new_disjunction_state.fail) {
  566. state.string_position = new_disjunction_state.last_accepted_position.value_or(new_disjunction_state.initial_position);
  567. state.string_position_in_code_units = new_disjunction_state.last_accepted_code_unit_position.value_or(new_disjunction_state.initial_code_unit_position);
  568. }
  569. }
  570. if (current_inversion_state() && !inverse_matched)
  571. advance_string_position(state, input.view);
  572. if ((!had_zero_length_match && string_position == state.string_position) || state.string_position > input.view.length())
  573. return ExecutionResult::Failed_ExecuteLowPrioForks;
  574. return ExecutionResult::Continue;
  575. }
  576. ALWAYS_INLINE void OpCode_Compare::compare_char(MatchInput const& input, MatchState& state, u32 ch1, bool inverse, bool& inverse_matched)
  577. {
  578. if (state.string_position == input.view.length())
  579. return;
  580. auto input_view = input.view.substring_view(state.string_position, 1)[0];
  581. bool equal;
  582. if (input.regex_options & AllFlags::Insensitive)
  583. equal = to_ascii_lowercase(input_view) == to_ascii_lowercase(ch1); // FIXME: Implement case-insensitive matching for non-ascii characters
  584. else
  585. equal = input_view == ch1;
  586. if (equal) {
  587. if (inverse)
  588. inverse_matched = true;
  589. else
  590. advance_string_position(state, input.view, ch1);
  591. }
  592. }
  593. ALWAYS_INLINE bool OpCode_Compare::compare_string(MatchInput const& input, MatchState& state, RegexStringView str, bool& had_zero_length_match)
  594. {
  595. if (state.string_position + str.length() > input.view.length()) {
  596. if (str.is_empty()) {
  597. had_zero_length_match = true;
  598. return true;
  599. }
  600. return false;
  601. }
  602. if (str.length() == 0) {
  603. had_zero_length_match = true;
  604. return true;
  605. }
  606. auto subject = input.view.substring_view(state.string_position, str.length());
  607. bool equals;
  608. if (input.regex_options & AllFlags::Insensitive)
  609. equals = subject.equals_ignoring_case(str);
  610. else
  611. equals = subject.equals(str);
  612. if (equals)
  613. advance_string_position(state, input.view, str);
  614. return equals;
  615. }
  616. ALWAYS_INLINE void OpCode_Compare::compare_character_class(MatchInput const& input, MatchState& state, CharClass character_class, u32 ch, bool inverse, bool& inverse_matched)
  617. {
  618. if (matches_character_class(character_class, ch, input.regex_options & AllFlags::Insensitive)) {
  619. if (inverse)
  620. inverse_matched = true;
  621. else
  622. advance_string_position(state, input.view, ch);
  623. }
  624. }
  625. bool OpCode_Compare::matches_character_class(CharClass character_class, u32 ch, bool insensitive)
  626. {
  627. constexpr auto is_space_or_line_terminator = [](u32 code_point) {
  628. static auto space_separator = Unicode::general_category_from_string("Space_Separator"sv);
  629. if (!space_separator.has_value())
  630. return is_ascii_space(code_point);
  631. if ((code_point == 0x0a) || (code_point == 0x0d) || (code_point == 0x2028) || (code_point == 0x2029))
  632. return true;
  633. if ((code_point == 0x09) || (code_point == 0x0b) || (code_point == 0x0c) || (code_point == 0xfeff))
  634. return true;
  635. return Unicode::code_point_has_general_category(code_point, *space_separator);
  636. };
  637. switch (character_class) {
  638. case CharClass::Alnum:
  639. return is_ascii_alphanumeric(ch);
  640. case CharClass::Alpha:
  641. return is_ascii_alpha(ch);
  642. case CharClass::Blank:
  643. return is_ascii_blank(ch);
  644. case CharClass::Cntrl:
  645. return is_ascii_control(ch);
  646. case CharClass::Digit:
  647. return is_ascii_digit(ch);
  648. case CharClass::Graph:
  649. return is_ascii_graphical(ch);
  650. case CharClass::Lower:
  651. return is_ascii_lower_alpha(ch) || (insensitive && is_ascii_upper_alpha(ch));
  652. case CharClass::Print:
  653. return is_ascii_printable(ch);
  654. case CharClass::Punct:
  655. return is_ascii_punctuation(ch);
  656. case CharClass::Space:
  657. return is_space_or_line_terminator(ch);
  658. case CharClass::Upper:
  659. return is_ascii_upper_alpha(ch) || (insensitive && is_ascii_lower_alpha(ch));
  660. case CharClass::Word:
  661. return is_ascii_alphanumeric(ch) || ch == '_';
  662. case CharClass::Xdigit:
  663. return is_ascii_hex_digit(ch);
  664. }
  665. VERIFY_NOT_REACHED();
  666. }
  667. ALWAYS_INLINE void OpCode_Compare::compare_character_range(MatchInput const& input, MatchState& state, u32 from, u32 to, u32 ch, bool inverse, bool& inverse_matched)
  668. {
  669. if (input.regex_options & AllFlags::Insensitive) {
  670. from = to_ascii_lowercase(from);
  671. to = to_ascii_lowercase(to);
  672. ch = to_ascii_lowercase(ch);
  673. }
  674. if (ch >= from && ch <= to) {
  675. if (inverse)
  676. inverse_matched = true;
  677. else
  678. advance_string_position(state, input.view, ch);
  679. }
  680. }
  681. ALWAYS_INLINE void OpCode_Compare::compare_property(MatchInput const& input, MatchState& state, Unicode::Property property, bool inverse, bool& inverse_matched)
  682. {
  683. if (state.string_position == input.view.length())
  684. return;
  685. u32 code_point = input.view[state.string_position_in_code_units];
  686. bool equal = Unicode::code_point_has_property(code_point, property);
  687. if (equal) {
  688. if (inverse)
  689. inverse_matched = true;
  690. else
  691. advance_string_position(state, input.view, code_point);
  692. }
  693. }
  694. ALWAYS_INLINE void OpCode_Compare::compare_general_category(MatchInput const& input, MatchState& state, Unicode::GeneralCategory general_category, bool inverse, bool& inverse_matched)
  695. {
  696. if (state.string_position == input.view.length())
  697. return;
  698. u32 code_point = input.view[state.string_position_in_code_units];
  699. bool equal = Unicode::code_point_has_general_category(code_point, general_category);
  700. if (equal) {
  701. if (inverse)
  702. inverse_matched = true;
  703. else
  704. advance_string_position(state, input.view, code_point);
  705. }
  706. }
  707. ALWAYS_INLINE void OpCode_Compare::compare_script(MatchInput const& input, MatchState& state, Unicode::Script script, bool inverse, bool& inverse_matched)
  708. {
  709. if (state.string_position == input.view.length())
  710. return;
  711. u32 code_point = input.view[state.string_position_in_code_units];
  712. bool equal = Unicode::code_point_has_script(code_point, script);
  713. if (equal) {
  714. if (inverse)
  715. inverse_matched = true;
  716. else
  717. advance_string_position(state, input.view, code_point);
  718. }
  719. }
  720. ALWAYS_INLINE void OpCode_Compare::compare_script_extension(MatchInput const& input, MatchState& state, Unicode::Script script, bool inverse, bool& inverse_matched)
  721. {
  722. if (state.string_position == input.view.length())
  723. return;
  724. u32 code_point = input.view[state.string_position_in_code_units];
  725. bool equal = Unicode::code_point_has_script_extension(code_point, script);
  726. if (equal) {
  727. if (inverse)
  728. inverse_matched = true;
  729. else
  730. advance_string_position(state, input.view, code_point);
  731. }
  732. }
  733. DeprecatedString OpCode_Compare::arguments_string() const
  734. {
  735. return DeprecatedString::formatted("argc={}, args={} ", arguments_count(), arguments_size());
  736. }
  737. Vector<CompareTypeAndValuePair> OpCode_Compare::flat_compares() const
  738. {
  739. Vector<CompareTypeAndValuePair> result;
  740. size_t offset { state().instruction_position + 3 };
  741. for (size_t i = 0; i < arguments_count(); ++i) {
  742. auto compare_type = (CharacterCompareType)m_bytecode->at(offset++);
  743. if (compare_type == CharacterCompareType::Char) {
  744. auto ch = m_bytecode->at(offset++);
  745. result.append({ compare_type, ch });
  746. } else if (compare_type == CharacterCompareType::Reference) {
  747. auto ref = m_bytecode->at(offset++);
  748. result.append({ compare_type, ref });
  749. } else if (compare_type == CharacterCompareType::String) {
  750. auto& length = m_bytecode->at(offset++);
  751. if (length > 0)
  752. result.append({ compare_type, m_bytecode->at(offset) });
  753. StringBuilder str_builder;
  754. offset += length;
  755. } else if (compare_type == CharacterCompareType::CharClass) {
  756. auto character_class = m_bytecode->at(offset++);
  757. result.append({ compare_type, character_class });
  758. } else if (compare_type == CharacterCompareType::CharRange) {
  759. auto value = m_bytecode->at(offset++);
  760. result.append({ compare_type, value });
  761. } else if (compare_type == CharacterCompareType::LookupTable) {
  762. auto count = m_bytecode->at(offset++);
  763. for (size_t i = 0; i < count; ++i)
  764. result.append({ CharacterCompareType::CharRange, m_bytecode->at(offset++) });
  765. } else if (compare_type == CharacterCompareType::GeneralCategory
  766. || compare_type == CharacterCompareType::Property
  767. || compare_type == CharacterCompareType::Script
  768. || compare_type == CharacterCompareType::ScriptExtension) {
  769. auto value = m_bytecode->at(offset++);
  770. result.append({ compare_type, value });
  771. } else {
  772. result.append({ compare_type, 0 });
  773. }
  774. }
  775. return result;
  776. }
  777. Vector<DeprecatedString> OpCode_Compare::variable_arguments_to_deprecated_string(Optional<MatchInput const&> input) const
  778. {
  779. Vector<DeprecatedString> result;
  780. size_t offset { state().instruction_position + 3 };
  781. RegexStringView const& view = ((input.has_value()) ? input.value().view : StringView {});
  782. for (size_t i = 0; i < arguments_count(); ++i) {
  783. auto compare_type = (CharacterCompareType)m_bytecode->at(offset++);
  784. result.empend(DeprecatedString::formatted("type={} [{}]", (size_t)compare_type, character_compare_type_name(compare_type)));
  785. auto string_start_offset = state().string_position_before_match;
  786. if (compare_type == CharacterCompareType::Char) {
  787. auto ch = m_bytecode->at(offset++);
  788. auto is_ascii = is_ascii_printable(ch);
  789. if (is_ascii)
  790. result.empend(DeprecatedString::formatted(" value='{:c}'", static_cast<char>(ch)));
  791. else
  792. result.empend(DeprecatedString::formatted(" value={:x}", ch));
  793. if (!view.is_null() && view.length() > string_start_offset) {
  794. if (is_ascii) {
  795. result.empend(DeprecatedString::formatted(
  796. " compare against: '{}'",
  797. view.substring_view(string_start_offset, string_start_offset > view.length() ? 0 : 1).to_deprecated_string()));
  798. } else {
  799. auto str = view.substring_view(string_start_offset, string_start_offset > view.length() ? 0 : 1).to_deprecated_string();
  800. u8 buf[8] { 0 };
  801. __builtin_memcpy(buf, str.characters(), min(str.length(), sizeof(buf)));
  802. result.empend(DeprecatedString::formatted(" compare against: {:x},{:x},{:x},{:x},{:x},{:x},{:x},{:x}",
  803. buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]));
  804. }
  805. }
  806. } else if (compare_type == CharacterCompareType::Reference) {
  807. auto ref = m_bytecode->at(offset++);
  808. result.empend(DeprecatedString::formatted(" number={}", ref));
  809. if (input.has_value()) {
  810. if (state().capture_group_matches.size() > input->match_index) {
  811. auto& match = state().capture_group_matches[input->match_index];
  812. if (match.size() > ref) {
  813. auto& group = match[ref];
  814. result.empend(DeprecatedString::formatted(" left={}", group.left_column));
  815. result.empend(DeprecatedString::formatted(" right={}", group.left_column + group.view.length_in_code_units()));
  816. result.empend(DeprecatedString::formatted(" contents='{}'", group.view));
  817. } else {
  818. result.empend(DeprecatedString::formatted(" (invalid ref, max={})", match.size() - 1));
  819. }
  820. } else {
  821. result.empend(DeprecatedString::formatted(" (invalid index {}, max={})", input->match_index, state().capture_group_matches.size() - 1));
  822. }
  823. }
  824. } else if (compare_type == CharacterCompareType::String) {
  825. auto& length = m_bytecode->at(offset++);
  826. StringBuilder str_builder;
  827. for (size_t i = 0; i < length; ++i)
  828. str_builder.append(m_bytecode->at(offset++));
  829. result.empend(DeprecatedString::formatted(" value=\"{}\"", str_builder.string_view().substring_view(0, length)));
  830. if (!view.is_null() && view.length() > state().string_position)
  831. result.empend(DeprecatedString::formatted(
  832. " compare against: \"{}\"",
  833. input.value().view.substring_view(string_start_offset, string_start_offset + length > view.length() ? 0 : length).to_deprecated_string()));
  834. } else if (compare_type == CharacterCompareType::CharClass) {
  835. auto character_class = (CharClass)m_bytecode->at(offset++);
  836. result.empend(DeprecatedString::formatted(" ch_class={} [{}]", (size_t)character_class, character_class_name(character_class)));
  837. if (!view.is_null() && view.length() > state().string_position)
  838. result.empend(DeprecatedString::formatted(
  839. " compare against: '{}'",
  840. input.value().view.substring_view(string_start_offset, state().string_position > view.length() ? 0 : 1).to_deprecated_string()));
  841. } else if (compare_type == CharacterCompareType::CharRange) {
  842. auto value = (CharRange)m_bytecode->at(offset++);
  843. result.empend(DeprecatedString::formatted(" ch_range={:x}-{:x}", value.from, value.to));
  844. if (!view.is_null() && view.length() > state().string_position)
  845. result.empend(DeprecatedString::formatted(
  846. " compare against: '{}'",
  847. input.value().view.substring_view(string_start_offset, state().string_position > view.length() ? 0 : 1).to_deprecated_string()));
  848. } else if (compare_type == CharacterCompareType::LookupTable) {
  849. auto count = m_bytecode->at(offset++);
  850. for (size_t j = 0; j < count; ++j) {
  851. auto range = (CharRange)m_bytecode->at(offset++);
  852. result.append(DeprecatedString::formatted(" {:x}-{:x}", range.from, range.to));
  853. }
  854. if (!view.is_null() && view.length() > state().string_position)
  855. result.empend(DeprecatedString::formatted(
  856. " compare against: '{}'",
  857. input.value().view.substring_view(string_start_offset, state().string_position > view.length() ? 0 : 1).to_deprecated_string()));
  858. } else if (compare_type == CharacterCompareType::GeneralCategory
  859. || compare_type == CharacterCompareType::Property
  860. || compare_type == CharacterCompareType::Script
  861. || compare_type == CharacterCompareType::ScriptExtension) {
  862. auto value = m_bytecode->at(offset++);
  863. result.empend(DeprecatedString::formatted(" value={}", value));
  864. }
  865. }
  866. return result;
  867. }
  868. ALWAYS_INLINE ExecutionResult OpCode_Repeat::execute(MatchInput const&, MatchState& state) const
  869. {
  870. VERIFY(count() > 0);
  871. if (id() >= state.repetition_marks.size())
  872. state.repetition_marks.resize(id() + 1);
  873. auto& repetition_mark = state.repetition_marks.at(id());
  874. if (repetition_mark == count() - 1) {
  875. repetition_mark = 0;
  876. } else {
  877. state.instruction_position -= offset() + size();
  878. ++repetition_mark;
  879. }
  880. return ExecutionResult::Continue;
  881. }
  882. ALWAYS_INLINE ExecutionResult OpCode_ResetRepeat::execute(MatchInput const&, MatchState& state) const
  883. {
  884. if (id() >= state.repetition_marks.size())
  885. state.repetition_marks.resize(id() + 1);
  886. state.repetition_marks.at(id()) = 0;
  887. return ExecutionResult::Continue;
  888. }
  889. ALWAYS_INLINE ExecutionResult OpCode_Checkpoint::execute(MatchInput const& input, MatchState& state) const
  890. {
  891. auto id = this->id();
  892. if (id >= input.checkpoints.size())
  893. input.checkpoints.resize(id + 1);
  894. input.checkpoints[id] = state.string_position + 1;
  895. return ExecutionResult::Continue;
  896. }
  897. ALWAYS_INLINE ExecutionResult OpCode_JumpNonEmpty::execute(MatchInput const& input, MatchState& state) const
  898. {
  899. u64 current_position = state.string_position;
  900. auto checkpoint_position = input.checkpoints[checkpoint()];
  901. if (checkpoint_position != 0 && checkpoint_position != current_position + 1) {
  902. auto form = this->form();
  903. if (form == OpCodeId::Jump) {
  904. state.instruction_position += offset();
  905. return ExecutionResult::Continue;
  906. }
  907. state.fork_at_position = state.instruction_position + size() + offset();
  908. if (form == OpCodeId::ForkJump) {
  909. state.forks_since_last_save++;
  910. return ExecutionResult::Fork_PrioHigh;
  911. }
  912. if (form == OpCodeId::ForkStay) {
  913. state.forks_since_last_save++;
  914. return ExecutionResult::Fork_PrioLow;
  915. }
  916. if (form == OpCodeId::ForkReplaceStay) {
  917. input.fork_to_replace = state.instruction_position;
  918. return ExecutionResult::Fork_PrioLow;
  919. }
  920. if (form == OpCodeId::ForkReplaceJump) {
  921. input.fork_to_replace = state.instruction_position;
  922. return ExecutionResult::Fork_PrioHigh;
  923. }
  924. }
  925. return ExecutionResult::Continue;
  926. }
  927. }