RegexByteCode.cpp 38 KB

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