RegexByteCode.cpp 44 KB

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