RegexByteCode.cpp 39 KB

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