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