RegexByteCode.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  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. if (0 == state.string_position && (input.regex_options & AllFlags::MatchNotBeginOfLine))
  237. return ExecutionResult::Failed_ExecuteLowPrioForks;
  238. if ((0 == state.string_position && !(input.regex_options & AllFlags::MatchNotBeginOfLine))
  239. || (0 != state.string_position && (input.regex_options & AllFlags::MatchNotBeginOfLine))
  240. || (0 == state.string_position && (input.regex_options & AllFlags::Global)))
  241. return ExecutionResult::Continue;
  242. return ExecutionResult::Failed_ExecuteLowPrioForks;
  243. }
  244. ALWAYS_INLINE ExecutionResult OpCode_CheckBoundary::execute(MatchInput const& input, MatchState& state) const
  245. {
  246. auto isword = [](auto ch) { return is_ascii_alphanumeric(ch) || ch == '_'; };
  247. auto is_word_boundary = [&] {
  248. if (state.string_position == input.view.length()) {
  249. return (state.string_position > 0 && isword(input.view[state.string_position_in_code_units - 1]));
  250. }
  251. if (state.string_position == 0) {
  252. return (isword(input.view[0]));
  253. }
  254. return !!(isword(input.view[state.string_position_in_code_units]) ^ isword(input.view[state.string_position_in_code_units - 1]));
  255. };
  256. switch (type()) {
  257. case BoundaryCheckType::Word: {
  258. if (is_word_boundary())
  259. return ExecutionResult::Continue;
  260. return ExecutionResult::Failed_ExecuteLowPrioForks;
  261. }
  262. case BoundaryCheckType::NonWord: {
  263. if (!is_word_boundary())
  264. return ExecutionResult::Continue;
  265. return ExecutionResult::Failed_ExecuteLowPrioForks;
  266. }
  267. }
  268. VERIFY_NOT_REACHED();
  269. }
  270. ALWAYS_INLINE ExecutionResult OpCode_CheckEnd::execute(MatchInput const& input, MatchState& state) const
  271. {
  272. if (state.string_position == input.view.length() && (input.regex_options & AllFlags::MatchNotEndOfLine))
  273. return ExecutionResult::Failed_ExecuteLowPrioForks;
  274. if ((state.string_position == input.view.length() && !(input.regex_options & AllFlags::MatchNotEndOfLine))
  275. || (state.string_position != input.view.length() && (input.regex_options & AllFlags::MatchNotEndOfLine || input.regex_options & AllFlags::MatchNotBeginOfLine)))
  276. return ExecutionResult::Continue;
  277. return ExecutionResult::Failed_ExecuteLowPrioForks;
  278. }
  279. ALWAYS_INLINE ExecutionResult OpCode_ClearCaptureGroup::execute(MatchInput const& input, MatchState& state) const
  280. {
  281. if (input.match_index < state.capture_group_matches.size()) {
  282. auto& group = state.capture_group_matches[input.match_index];
  283. if (id() < group.size())
  284. group[id()].reset();
  285. }
  286. return ExecutionResult::Continue;
  287. }
  288. ALWAYS_INLINE ExecutionResult OpCode_SaveLeftCaptureGroup::execute(MatchInput const& input, MatchState& state) const
  289. {
  290. if (input.match_index >= state.capture_group_matches.size()) {
  291. state.capture_group_matches.ensure_capacity(input.match_index);
  292. auto capacity = state.capture_group_matches.capacity();
  293. for (size_t i = state.capture_group_matches.size(); i <= capacity; ++i)
  294. state.capture_group_matches.empend();
  295. }
  296. if (id() >= state.capture_group_matches.at(input.match_index).size()) {
  297. state.capture_group_matches.at(input.match_index).ensure_capacity(id());
  298. auto capacity = state.capture_group_matches.at(input.match_index).capacity();
  299. for (size_t i = state.capture_group_matches.at(input.match_index).size(); i <= capacity; ++i)
  300. state.capture_group_matches.at(input.match_index).empend();
  301. }
  302. state.capture_group_matches.at(input.match_index).at(id()).left_column = state.string_position;
  303. return ExecutionResult::Continue;
  304. }
  305. ALWAYS_INLINE ExecutionResult OpCode_SaveRightCaptureGroup::execute(MatchInput const& input, MatchState& state) const
  306. {
  307. auto& match = state.capture_group_matches.at(input.match_index).at(id());
  308. auto start_position = match.left_column;
  309. if (state.string_position < start_position)
  310. return ExecutionResult::Failed_ExecuteLowPrioForks;
  311. auto length = state.string_position - start_position;
  312. if (start_position < match.column)
  313. return ExecutionResult::Continue;
  314. VERIFY(start_position + length <= input.view.length());
  315. auto view = input.view.substring_view(start_position, length);
  316. if (input.regex_options & AllFlags::StringCopyMatches) {
  317. match = { view.to_string(), input.line, start_position, input.global_offset + start_position }; // create a copy of the original string
  318. } else {
  319. match = { view, input.line, start_position, input.global_offset + start_position }; // take view to original string
  320. }
  321. return ExecutionResult::Continue;
  322. }
  323. ALWAYS_INLINE ExecutionResult OpCode_SaveRightNamedCaptureGroup::execute(MatchInput const& input, MatchState& state) const
  324. {
  325. auto& match = state.capture_group_matches.at(input.match_index).at(id());
  326. auto start_position = match.left_column;
  327. if (state.string_position < start_position)
  328. return ExecutionResult::Failed_ExecuteLowPrioForks;
  329. auto length = state.string_position - start_position;
  330. if (start_position < match.column)
  331. return ExecutionResult::Continue;
  332. VERIFY(start_position + length <= input.view.length());
  333. auto view = input.view.substring_view(start_position, length);
  334. if (input.regex_options & AllFlags::StringCopyMatches) {
  335. match = { view.to_string(), name(), input.line, start_position, input.global_offset + start_position }; // create a copy of the original string
  336. } else {
  337. match = { view, name(), input.line, start_position, input.global_offset + start_position }; // take view to original string
  338. }
  339. return ExecutionResult::Continue;
  340. }
  341. ALWAYS_INLINE ExecutionResult OpCode_Compare::execute(MatchInput const& input, MatchState& state) const
  342. {
  343. bool inverse { false };
  344. bool temporary_inverse { false };
  345. bool reset_temp_inverse { false };
  346. auto current_inversion_state = [&]() -> bool { return temporary_inverse ^ inverse; };
  347. size_t string_position = state.string_position;
  348. bool inverse_matched { false };
  349. bool had_zero_length_match { false };
  350. state.string_position_before_match = state.string_position;
  351. size_t offset { state.instruction_position + 3 };
  352. for (size_t i = 0; i < arguments_count(); ++i) {
  353. if (state.string_position > string_position)
  354. break;
  355. if (reset_temp_inverse) {
  356. reset_temp_inverse = false;
  357. temporary_inverse = false;
  358. } else {
  359. reset_temp_inverse = true;
  360. }
  361. auto compare_type = (CharacterCompareType)m_bytecode->at(offset++);
  362. if (compare_type == CharacterCompareType::Inverse)
  363. inverse = true;
  364. else if (compare_type == CharacterCompareType::TemporaryInverse) {
  365. // If "TemporaryInverse" is given, negate the current inversion state only for the next opcode.
  366. // it follows that this cannot be the last compare element.
  367. VERIFY(i != arguments_count() - 1);
  368. temporary_inverse = true;
  369. reset_temp_inverse = false;
  370. } else if (compare_type == CharacterCompareType::Char) {
  371. u32 ch = m_bytecode->at(offset++);
  372. // We want to compare a string that is longer or equal in length to the available string
  373. if (input.view.length() <= state.string_position)
  374. return ExecutionResult::Failed_ExecuteLowPrioForks;
  375. compare_char(input, state, ch, current_inversion_state(), inverse_matched);
  376. } else if (compare_type == CharacterCompareType::AnyChar) {
  377. // We want to compare a string that is definitely longer than the available string
  378. if (input.view.length() <= state.string_position)
  379. return ExecutionResult::Failed_ExecuteLowPrioForks;
  380. VERIFY(!current_inversion_state());
  381. advance_string_position(state, input.view);
  382. } else if (compare_type == CharacterCompareType::String) {
  383. VERIFY(!current_inversion_state());
  384. auto const& length = m_bytecode->at(offset++);
  385. // We want to compare a string that is definitely longer than the available string
  386. if (input.view.length() < state.string_position + length)
  387. return ExecutionResult::Failed_ExecuteLowPrioForks;
  388. Optional<String> str;
  389. Vector<u16, 1> utf16;
  390. Vector<u32> data;
  391. data.ensure_capacity(length);
  392. for (size_t i = offset; i < offset + length; ++i)
  393. data.unchecked_append(m_bytecode->at(i));
  394. auto view = input.view.construct_as_same(data, str, utf16);
  395. offset += length;
  396. if (!compare_string(input, state, view, had_zero_length_match))
  397. return ExecutionResult::Failed_ExecuteLowPrioForks;
  398. } else if (compare_type == CharacterCompareType::CharClass) {
  399. if (input.view.length() <= state.string_position)
  400. return ExecutionResult::Failed_ExecuteLowPrioForks;
  401. auto character_class = (CharClass)m_bytecode->at(offset++);
  402. auto ch = input.view[state.string_position_in_code_units];
  403. compare_character_class(input, state, character_class, ch, current_inversion_state(), inverse_matched);
  404. } else if (compare_type == CharacterCompareType::LookupTable) {
  405. if (input.view.length() <= state.string_position)
  406. return ExecutionResult::Failed_ExecuteLowPrioForks;
  407. auto count = m_bytecode->at(offset++);
  408. auto range_data = m_bytecode->spans().slice(offset, count);
  409. offset += count;
  410. auto ch = input.view.substring_view(state.string_position, 1)[0];
  411. auto const* matching_range = binary_search(range_data, ch, nullptr, [insensitive = input.regex_options & AllFlags::Insensitive](auto needle, CharRange range) {
  412. auto from = range.from;
  413. auto to = range.to;
  414. if (insensitive) {
  415. from = to_ascii_lowercase(from);
  416. to = to_ascii_lowercase(to);
  417. needle = to_ascii_lowercase(needle);
  418. }
  419. if (needle > range.to)
  420. return 1;
  421. if (needle < range.from)
  422. return -1;
  423. return 0;
  424. });
  425. if (matching_range) {
  426. if (current_inversion_state())
  427. inverse_matched = true;
  428. else
  429. advance_string_position(state, input.view, ch);
  430. }
  431. } else if (compare_type == CharacterCompareType::CharRange) {
  432. if (input.view.length() <= state.string_position)
  433. return ExecutionResult::Failed_ExecuteLowPrioForks;
  434. auto value = (CharRange)m_bytecode->at(offset++);
  435. auto from = value.from;
  436. auto to = value.to;
  437. auto ch = input.view[state.string_position_in_code_units];
  438. compare_character_range(input, state, from, to, ch, current_inversion_state(), inverse_matched);
  439. } else if (compare_type == CharacterCompareType::Reference) {
  440. auto reference_number = (size_t)m_bytecode->at(offset++);
  441. auto& groups = state.capture_group_matches.at(input.match_index);
  442. if (groups.size() <= reference_number)
  443. return ExecutionResult::Failed_ExecuteLowPrioForks;
  444. auto str = groups.at(reference_number).view;
  445. // We want to compare a string that is definitely longer than the available string
  446. if (input.view.length() < state.string_position + str.length())
  447. return ExecutionResult::Failed_ExecuteLowPrioForks;
  448. if (!compare_string(input, state, str, had_zero_length_match))
  449. return ExecutionResult::Failed_ExecuteLowPrioForks;
  450. } else if (compare_type == CharacterCompareType::Property) {
  451. auto property = static_cast<Unicode::Property>(m_bytecode->at(offset++));
  452. compare_property(input, state, property, current_inversion_state(), inverse_matched);
  453. } else if (compare_type == CharacterCompareType::GeneralCategory) {
  454. auto general_category = static_cast<Unicode::GeneralCategory>(m_bytecode->at(offset++));
  455. compare_general_category(input, state, general_category, current_inversion_state(), inverse_matched);
  456. } else if (compare_type == CharacterCompareType::Script) {
  457. auto script = static_cast<Unicode::Script>(m_bytecode->at(offset++));
  458. compare_script(input, state, script, current_inversion_state(), inverse_matched);
  459. } else if (compare_type == CharacterCompareType::ScriptExtension) {
  460. auto script = static_cast<Unicode::Script>(m_bytecode->at(offset++));
  461. compare_script_extension(input, state, script, current_inversion_state(), inverse_matched);
  462. } else {
  463. warnln("Undefined comparison: {}", (int)compare_type);
  464. VERIFY_NOT_REACHED();
  465. break;
  466. }
  467. }
  468. if (current_inversion_state() && !inverse_matched)
  469. advance_string_position(state, input.view);
  470. if ((!had_zero_length_match && string_position == state.string_position) || state.string_position > input.view.length())
  471. return ExecutionResult::Failed_ExecuteLowPrioForks;
  472. return ExecutionResult::Continue;
  473. }
  474. ALWAYS_INLINE void OpCode_Compare::compare_char(MatchInput const& input, MatchState& state, u32 ch1, bool inverse, bool& inverse_matched)
  475. {
  476. if (state.string_position == input.view.length())
  477. return;
  478. auto input_view = input.view.substring_view(state.string_position, 1)[0];
  479. bool equal;
  480. if (input.regex_options & AllFlags::Insensitive)
  481. equal = to_ascii_lowercase(input_view) == to_ascii_lowercase(ch1); // FIXME: Implement case-insensitive matching for non-ascii characters
  482. else
  483. equal = input_view == ch1;
  484. if (equal) {
  485. if (inverse)
  486. inverse_matched = true;
  487. else
  488. advance_string_position(state, input.view, ch1);
  489. }
  490. }
  491. ALWAYS_INLINE bool OpCode_Compare::compare_string(MatchInput const& input, MatchState& state, RegexStringView str, bool& had_zero_length_match)
  492. {
  493. if (state.string_position + str.length() > input.view.length()) {
  494. if (str.is_empty()) {
  495. had_zero_length_match = true;
  496. return true;
  497. }
  498. return false;
  499. }
  500. if (str.length() == 0) {
  501. had_zero_length_match = true;
  502. return true;
  503. }
  504. auto subject = input.view.substring_view(state.string_position, str.length());
  505. bool equals;
  506. if (input.regex_options & AllFlags::Insensitive)
  507. equals = subject.equals_ignoring_case(str);
  508. else
  509. equals = subject.equals(str);
  510. if (equals)
  511. advance_string_position(state, input.view, str);
  512. return equals;
  513. }
  514. ALWAYS_INLINE void OpCode_Compare::compare_character_class(MatchInput const& input, MatchState& state, CharClass character_class, u32 ch, bool inverse, bool& inverse_matched)
  515. {
  516. switch (character_class) {
  517. case CharClass::Alnum:
  518. if (is_ascii_alphanumeric(ch)) {
  519. if (inverse)
  520. inverse_matched = true;
  521. else
  522. advance_string_position(state, input.view, ch);
  523. }
  524. break;
  525. case CharClass::Alpha:
  526. if (is_ascii_alpha(ch))
  527. advance_string_position(state, input.view, ch);
  528. break;
  529. case CharClass::Blank:
  530. if (is_ascii_blank(ch)) {
  531. if (inverse)
  532. inverse_matched = true;
  533. else
  534. advance_string_position(state, input.view, ch);
  535. }
  536. break;
  537. case CharClass::Cntrl:
  538. if (is_ascii_control(ch)) {
  539. if (inverse)
  540. inverse_matched = true;
  541. else
  542. advance_string_position(state, input.view, ch);
  543. }
  544. break;
  545. case CharClass::Digit:
  546. if (is_ascii_digit(ch)) {
  547. if (inverse)
  548. inverse_matched = true;
  549. else
  550. advance_string_position(state, input.view, ch);
  551. }
  552. break;
  553. case CharClass::Graph:
  554. if (is_ascii_graphical(ch)) {
  555. if (inverse)
  556. inverse_matched = true;
  557. else
  558. advance_string_position(state, input.view, ch);
  559. }
  560. break;
  561. case CharClass::Lower:
  562. if (is_ascii_lower_alpha(ch) || ((input.regex_options & AllFlags::Insensitive) && is_ascii_upper_alpha(ch))) {
  563. if (inverse)
  564. inverse_matched = true;
  565. else
  566. advance_string_position(state, input.view, ch);
  567. }
  568. break;
  569. case CharClass::Print:
  570. if (is_ascii_printable(ch)) {
  571. if (inverse)
  572. inverse_matched = true;
  573. else
  574. advance_string_position(state, input.view, ch);
  575. }
  576. break;
  577. case CharClass::Punct:
  578. if (is_ascii_punctuation(ch)) {
  579. if (inverse)
  580. inverse_matched = true;
  581. else
  582. advance_string_position(state, input.view, ch);
  583. }
  584. break;
  585. case CharClass::Space:
  586. if (is_ascii_space(ch)) {
  587. if (inverse)
  588. inverse_matched = true;
  589. else
  590. advance_string_position(state, input.view, ch);
  591. }
  592. break;
  593. case CharClass::Upper:
  594. if (is_ascii_upper_alpha(ch) || ((input.regex_options & AllFlags::Insensitive) && is_ascii_lower_alpha(ch))) {
  595. if (inverse)
  596. inverse_matched = true;
  597. else
  598. advance_string_position(state, input.view, ch);
  599. }
  600. break;
  601. case CharClass::Word:
  602. if (is_ascii_alphanumeric(ch) || ch == '_') {
  603. if (inverse)
  604. inverse_matched = true;
  605. else
  606. advance_string_position(state, input.view, ch);
  607. }
  608. break;
  609. case CharClass::Xdigit:
  610. if (is_ascii_hex_digit(ch)) {
  611. if (inverse)
  612. inverse_matched = true;
  613. else
  614. advance_string_position(state, input.view, ch);
  615. }
  616. break;
  617. }
  618. }
  619. ALWAYS_INLINE void OpCode_Compare::compare_character_range(MatchInput const& input, MatchState& state, u32 from, u32 to, u32 ch, bool inverse, bool& inverse_matched)
  620. {
  621. if (input.regex_options & AllFlags::Insensitive) {
  622. from = to_ascii_lowercase(from);
  623. to = to_ascii_lowercase(to);
  624. ch = to_ascii_lowercase(ch);
  625. }
  626. if (ch >= from && ch <= to) {
  627. if (inverse)
  628. inverse_matched = true;
  629. else
  630. advance_string_position(state, input.view, ch);
  631. }
  632. }
  633. ALWAYS_INLINE void OpCode_Compare::compare_property(MatchInput const& input, MatchState& state, Unicode::Property property, bool inverse, bool& inverse_matched)
  634. {
  635. if (state.string_position == input.view.length())
  636. return;
  637. u32 code_point = input.view[state.string_position_in_code_units];
  638. bool equal = Unicode::code_point_has_property(code_point, property);
  639. if (equal) {
  640. if (inverse)
  641. inverse_matched = true;
  642. else
  643. advance_string_position(state, input.view, code_point);
  644. }
  645. }
  646. ALWAYS_INLINE void OpCode_Compare::compare_general_category(MatchInput const& input, MatchState& state, Unicode::GeneralCategory general_category, bool inverse, bool& inverse_matched)
  647. {
  648. if (state.string_position == input.view.length())
  649. return;
  650. u32 code_point = input.view[state.string_position_in_code_units];
  651. bool equal = Unicode::code_point_has_general_category(code_point, general_category);
  652. if (equal) {
  653. if (inverse)
  654. inverse_matched = true;
  655. else
  656. advance_string_position(state, input.view, code_point);
  657. }
  658. }
  659. ALWAYS_INLINE void OpCode_Compare::compare_script(MatchInput const& input, MatchState& state, Unicode::Script script, bool inverse, bool& inverse_matched)
  660. {
  661. if (state.string_position == input.view.length())
  662. return;
  663. u32 code_point = input.view[state.string_position_in_code_units];
  664. bool equal = Unicode::code_point_has_script(code_point, script);
  665. if (equal) {
  666. if (inverse)
  667. inverse_matched = true;
  668. else
  669. advance_string_position(state, input.view, code_point);
  670. }
  671. }
  672. ALWAYS_INLINE void OpCode_Compare::compare_script_extension(MatchInput const& input, MatchState& state, Unicode::Script script, bool inverse, bool& inverse_matched)
  673. {
  674. if (state.string_position == input.view.length())
  675. return;
  676. u32 code_point = input.view[state.string_position_in_code_units];
  677. bool equal = Unicode::code_point_has_script_extension(code_point, script);
  678. if (equal) {
  679. if (inverse)
  680. inverse_matched = true;
  681. else
  682. advance_string_position(state, input.view, code_point);
  683. }
  684. }
  685. String OpCode_Compare::arguments_string() const
  686. {
  687. return String::formatted("argc={}, args={} ", arguments_count(), arguments_size());
  688. }
  689. Vector<CompareTypeAndValuePair> OpCode_Compare::flat_compares() const
  690. {
  691. Vector<CompareTypeAndValuePair> result;
  692. size_t offset { state().instruction_position + 3 };
  693. for (size_t i = 0; i < arguments_count(); ++i) {
  694. auto compare_type = (CharacterCompareType)m_bytecode->at(offset++);
  695. if (compare_type == CharacterCompareType::Char) {
  696. auto ch = m_bytecode->at(offset++);
  697. result.append({ compare_type, ch });
  698. } else if (compare_type == CharacterCompareType::Reference) {
  699. auto ref = m_bytecode->at(offset++);
  700. result.append({ compare_type, ref });
  701. } else if (compare_type == CharacterCompareType::String) {
  702. auto& length = m_bytecode->at(offset++);
  703. if (length > 0)
  704. result.append({ compare_type, m_bytecode->at(offset) });
  705. StringBuilder str_builder;
  706. offset += length;
  707. } else if (compare_type == CharacterCompareType::CharClass) {
  708. auto character_class = m_bytecode->at(offset++);
  709. result.append({ compare_type, character_class });
  710. } else if (compare_type == CharacterCompareType::CharRange) {
  711. auto value = m_bytecode->at(offset++);
  712. result.append({ compare_type, value });
  713. } else if (compare_type == CharacterCompareType::LookupTable) {
  714. auto count = m_bytecode->at(offset++);
  715. for (size_t i = 0; i < count; ++i)
  716. result.append({ CharacterCompareType::CharRange, m_bytecode->at(offset++) });
  717. } else {
  718. result.append({ compare_type, 0 });
  719. }
  720. }
  721. return result;
  722. }
  723. Vector<String> OpCode_Compare::variable_arguments_to_string(Optional<MatchInput> input) const
  724. {
  725. Vector<String> result;
  726. size_t offset { state().instruction_position + 3 };
  727. RegexStringView view = ((input.has_value()) ? input.value().view : nullptr);
  728. for (size_t i = 0; i < arguments_count(); ++i) {
  729. auto compare_type = (CharacterCompareType)m_bytecode->at(offset++);
  730. result.empend(String::formatted("type={} [{}]", (size_t)compare_type, character_compare_type_name(compare_type)));
  731. auto string_start_offset = state().string_position_before_match;
  732. if (compare_type == CharacterCompareType::Char) {
  733. auto ch = m_bytecode->at(offset++);
  734. auto is_ascii = is_ascii_printable(ch);
  735. if (is_ascii)
  736. result.empend(String::formatted("value='{:c}'", static_cast<char>(ch)));
  737. else
  738. result.empend(String::formatted("value={:x}", ch));
  739. if (!view.is_null() && view.length() > string_start_offset) {
  740. if (is_ascii) {
  741. result.empend(String::formatted(
  742. "compare against: '{}'",
  743. view.substring_view(string_start_offset, string_start_offset > view.length() ? 0 : 1).to_string()));
  744. } else {
  745. auto str = view.substring_view(string_start_offset, string_start_offset > view.length() ? 0 : 1).to_string();
  746. u8 buf[8] { 0 };
  747. __builtin_memcpy(buf, str.characters(), min(str.length(), sizeof(buf)));
  748. result.empend(String::formatted("compare against: {:x},{:x},{:x},{:x},{:x},{:x},{:x},{:x}",
  749. buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]));
  750. }
  751. }
  752. } else if (compare_type == CharacterCompareType::Reference) {
  753. auto ref = m_bytecode->at(offset++);
  754. result.empend(String::formatted("number={}", ref));
  755. } else if (compare_type == CharacterCompareType::String) {
  756. auto& length = m_bytecode->at(offset++);
  757. StringBuilder str_builder;
  758. for (size_t i = 0; i < length; ++i)
  759. str_builder.append(m_bytecode->at(offset++));
  760. result.empend(String::formatted("value=\"{}\"", str_builder.string_view().substring_view(0, length)));
  761. if (!view.is_null() && view.length() > state().string_position)
  762. result.empend(String::formatted(
  763. "compare against: \"{}\"",
  764. input.value().view.substring_view(string_start_offset, string_start_offset + length > view.length() ? 0 : length).to_string()));
  765. } else if (compare_type == CharacterCompareType::CharClass) {
  766. auto character_class = (CharClass)m_bytecode->at(offset++);
  767. result.empend(String::formatted("ch_class={} [{}]", (size_t)character_class, character_class_name(character_class)));
  768. if (!view.is_null() && view.length() > state().string_position)
  769. result.empend(String::formatted(
  770. "compare against: '{}'",
  771. input.value().view.substring_view(string_start_offset, state().string_position > view.length() ? 0 : 1).to_string()));
  772. } else if (compare_type == CharacterCompareType::CharRange) {
  773. auto value = (CharRange)m_bytecode->at(offset++);
  774. result.empend(String::formatted("ch_range={:x}-{:x}", value.from, value.to));
  775. if (!view.is_null() && view.length() > state().string_position)
  776. result.empend(String::formatted(
  777. "compare against: '{}'",
  778. input.value().view.substring_view(string_start_offset, state().string_position > view.length() ? 0 : 1).to_string()));
  779. } else if (compare_type == CharacterCompareType::LookupTable) {
  780. auto count = m_bytecode->at(offset++);
  781. for (size_t j = 0; j < count; ++j) {
  782. auto range = (CharRange)m_bytecode->at(offset++);
  783. result.append(String::formatted("{:x}-{:x}", range.from, range.to));
  784. }
  785. if (!view.is_null() && view.length() > state().string_position)
  786. result.empend(String::formatted(
  787. "compare against: '{}'",
  788. input.value().view.substring_view(string_start_offset, state().string_position > view.length() ? 0 : 1).to_string()));
  789. }
  790. }
  791. return result;
  792. }
  793. ALWAYS_INLINE ExecutionResult OpCode_Repeat::execute(MatchInput const&, MatchState& state) const
  794. {
  795. VERIFY(count() > 0);
  796. if (id() >= state.repetition_marks.size())
  797. state.repetition_marks.resize(id() + 1);
  798. auto& repetition_mark = state.repetition_marks.at(id());
  799. if (repetition_mark == count() - 1) {
  800. repetition_mark = 0;
  801. } else {
  802. state.instruction_position -= offset() + size();
  803. ++repetition_mark;
  804. }
  805. return ExecutionResult::Continue;
  806. }
  807. ALWAYS_INLINE ExecutionResult OpCode_ResetRepeat::execute(MatchInput const&, MatchState& state) const
  808. {
  809. if (id() >= state.repetition_marks.size())
  810. state.repetition_marks.resize(id() + 1);
  811. state.repetition_marks.at(id()) = 0;
  812. return ExecutionResult::Continue;
  813. }
  814. ALWAYS_INLINE ExecutionResult OpCode_Checkpoint::execute(MatchInput const& input, MatchState& state) const
  815. {
  816. input.checkpoints.set(state.instruction_position, state.string_position);
  817. return ExecutionResult::Continue;
  818. }
  819. ALWAYS_INLINE ExecutionResult OpCode_JumpNonEmpty::execute(MatchInput const& input, MatchState& state) const
  820. {
  821. auto current_position = state.string_position;
  822. auto checkpoint_ip = state.instruction_position + size() + checkpoint();
  823. if (input.checkpoints.get(checkpoint_ip).value_or(current_position) != current_position) {
  824. auto form = this->form();
  825. if (form == OpCodeId::Jump) {
  826. state.instruction_position += offset();
  827. return ExecutionResult::Continue;
  828. }
  829. state.fork_at_position = state.instruction_position + size() + offset();
  830. if (form == OpCodeId::ForkJump)
  831. return ExecutionResult::Fork_PrioHigh;
  832. if (form == OpCodeId::ForkStay)
  833. return ExecutionResult::Fork_PrioLow;
  834. if (form == OpCodeId::ForkReplaceStay) {
  835. input.fork_to_replace = state.instruction_position;
  836. return ExecutionResult::Fork_PrioLow;
  837. }
  838. if (form == OpCodeId::ForkReplaceJump) {
  839. input.fork_to_replace = state.instruction_position;
  840. return ExecutionResult::Fork_PrioHigh;
  841. }
  842. }
  843. return ExecutionResult::Continue;
  844. }
  845. }