RegexByteCode.cpp 38 KB

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