RegexByteCode.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  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. StringView OpCode::name(OpCodeId opcode_id)
  15. {
  16. switch (opcode_id) {
  17. #define __ENUMERATE_OPCODE(x) \
  18. case OpCodeId::x: \
  19. return #x##sv;
  20. ENUMERATE_OPCODES
  21. #undef __ENUMERATE_OPCODE
  22. default:
  23. VERIFY_NOT_REACHED();
  24. return "<Unknown>"sv;
  25. }
  26. }
  27. StringView OpCode::name() const
  28. {
  29. return name(opcode_id());
  30. }
  31. StringView execution_result_name(ExecutionResult result)
  32. {
  33. switch (result) {
  34. #define __ENUMERATE_EXECUTION_RESULT(x) \
  35. case ExecutionResult::x: \
  36. return #x##sv;
  37. ENUMERATE_EXECUTION_RESULTS
  38. #undef __ENUMERATE_EXECUTION_RESULT
  39. default:
  40. VERIFY_NOT_REACHED();
  41. return "<Unknown>"sv;
  42. }
  43. }
  44. StringView opcode_id_name(OpCodeId opcode)
  45. {
  46. switch (opcode) {
  47. #define __ENUMERATE_OPCODE(x) \
  48. case OpCodeId::x: \
  49. return #x##sv;
  50. ENUMERATE_OPCODES
  51. #undef __ENUMERATE_OPCODE
  52. default:
  53. VERIFY_NOT_REACHED();
  54. return "<Unknown>"sv;
  55. }
  56. }
  57. StringView boundary_check_type_name(BoundaryCheckType ty)
  58. {
  59. switch (ty) {
  60. #define __ENUMERATE_BOUNDARY_CHECK_TYPE(x) \
  61. case BoundaryCheckType::x: \
  62. return #x##sv;
  63. ENUMERATE_BOUNDARY_CHECK_TYPES
  64. #undef __ENUMERATE_BOUNDARY_CHECK_TYPE
  65. default:
  66. VERIFY_NOT_REACHED();
  67. return "<Unknown>"sv;
  68. }
  69. }
  70. StringView 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##sv;
  76. ENUMERATE_CHARACTER_COMPARE_TYPES
  77. #undef __ENUMERATE_CHARACTER_COMPARE_TYPE
  78. default:
  79. VERIFY_NOT_REACHED();
  80. return "<Unknown>"sv;
  81. }
  82. }
  83. static StringView character_class_name(CharClass ch_class)
  84. {
  85. switch (ch_class) {
  86. #define __ENUMERATE_CHARACTER_CLASS(x) \
  87. case CharClass::x: \
  88. return #x##sv;
  89. ENUMERATE_CHARACTER_CLASSES
  90. #undef __ENUMERATE_CHARACTER_CLASS
  91. default:
  92. VERIFY_NOT_REACHED();
  93. return "<Unknown>"sv;
  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. struct DisjunctionState {
  367. bool active { false };
  368. bool is_conjunction { false };
  369. bool fail { false };
  370. size_t initial_position;
  371. size_t initial_code_unit_position;
  372. Optional<size_t> last_accepted_position {};
  373. Optional<size_t> last_accepted_code_unit_position {};
  374. };
  375. Vector<DisjunctionState, 4> disjunction_states;
  376. disjunction_states.empend();
  377. auto current_disjunction_state = [&]() -> DisjunctionState& { return disjunction_states.last(); };
  378. auto current_inversion_state = [&]() -> bool { return temporary_inverse ^ inverse; };
  379. size_t string_position = state.string_position;
  380. bool inverse_matched { false };
  381. bool had_zero_length_match { false };
  382. state.string_position_before_match = state.string_position;
  383. size_t offset { state.instruction_position + 3 };
  384. for (size_t i = 0; i < arguments_count(); ++i) {
  385. if (state.string_position > string_position)
  386. break;
  387. if (reset_temp_inverse) {
  388. reset_temp_inverse = false;
  389. temporary_inverse = false;
  390. } else {
  391. reset_temp_inverse = true;
  392. }
  393. auto compare_type = (CharacterCompareType)m_bytecode->at(offset++);
  394. if (compare_type == CharacterCompareType::Inverse) {
  395. inverse = !inverse;
  396. continue;
  397. } else if (compare_type == CharacterCompareType::TemporaryInverse) {
  398. // If "TemporaryInverse" is given, negate the current inversion state only for the next opcode.
  399. // it follows that this cannot be the last compare element.
  400. VERIFY(i != arguments_count() - 1);
  401. temporary_inverse = true;
  402. reset_temp_inverse = false;
  403. continue;
  404. } else if (compare_type == CharacterCompareType::Char) {
  405. u32 ch = m_bytecode->at(offset++);
  406. // We want to compare a string that is longer or equal in length to the available string
  407. if (input.view.length() <= state.string_position)
  408. return ExecutionResult::Failed_ExecuteLowPrioForks;
  409. compare_char(input, state, ch, current_inversion_state(), inverse_matched);
  410. } else if (compare_type == CharacterCompareType::AnyChar) {
  411. // We want to compare a string that is definitely longer than the available string
  412. if (input.view.length() <= state.string_position)
  413. return ExecutionResult::Failed_ExecuteLowPrioForks;
  414. auto input_view = input.view.substring_view(state.string_position, 1)[0];
  415. if (input_view != '\n' || (input.regex_options.has_flag_set(AllFlags::SingleLine) && input.regex_options.has_flag_set(AllFlags::Internal_ConsiderNewline))) {
  416. if (current_inversion_state())
  417. inverse_matched = true;
  418. else
  419. advance_string_position(state, input.view, input_view);
  420. }
  421. } else if (compare_type == CharacterCompareType::String) {
  422. VERIFY(!current_inversion_state());
  423. auto const& length = m_bytecode->at(offset++);
  424. // We want to compare a string that is definitely longer than the available string
  425. if (input.view.length() < state.string_position + length)
  426. return ExecutionResult::Failed_ExecuteLowPrioForks;
  427. Optional<String> str;
  428. Vector<u16, 1> utf16;
  429. Vector<u32> data;
  430. data.ensure_capacity(length);
  431. for (size_t i = offset; i < offset + length; ++i)
  432. data.unchecked_append(m_bytecode->at(i));
  433. auto view = input.view.construct_as_same(data, str, utf16);
  434. offset += length;
  435. if (compare_string(input, state, view, had_zero_length_match)) {
  436. if (current_inversion_state())
  437. inverse_matched = true;
  438. }
  439. } else if (compare_type == CharacterCompareType::CharClass) {
  440. if (input.view.length() <= state.string_position_in_code_units)
  441. return ExecutionResult::Failed_ExecuteLowPrioForks;
  442. auto character_class = (CharClass)m_bytecode->at(offset++);
  443. auto ch = input.view[state.string_position_in_code_units];
  444. compare_character_class(input, state, character_class, ch, current_inversion_state(), inverse_matched);
  445. } else if (compare_type == CharacterCompareType::LookupTable) {
  446. if (input.view.length() <= state.string_position)
  447. return ExecutionResult::Failed_ExecuteLowPrioForks;
  448. auto count = m_bytecode->at(offset++);
  449. auto range_data = m_bytecode->spans().slice(offset, count);
  450. offset += count;
  451. auto ch = input.view.substring_view(state.string_position, 1)[0];
  452. auto const* matching_range = binary_search(range_data, ch, nullptr, [insensitive = input.regex_options & AllFlags::Insensitive](auto needle, CharRange range) {
  453. auto upper_case_needle = needle;
  454. auto lower_case_needle = needle;
  455. if (insensitive) {
  456. upper_case_needle = to_ascii_uppercase(needle);
  457. lower_case_needle = to_ascii_lowercase(needle);
  458. }
  459. if (lower_case_needle >= range.from && lower_case_needle <= range.to)
  460. return 0;
  461. if (upper_case_needle >= range.from && upper_case_needle <= range.to)
  462. return 0;
  463. if (lower_case_needle > range.to || upper_case_needle > range.to)
  464. return 1;
  465. return -1;
  466. });
  467. if (matching_range) {
  468. if (current_inversion_state())
  469. inverse_matched = true;
  470. else
  471. advance_string_position(state, input.view, ch);
  472. }
  473. } else if (compare_type == CharacterCompareType::CharRange) {
  474. if (input.view.length() <= state.string_position)
  475. return ExecutionResult::Failed_ExecuteLowPrioForks;
  476. auto value = (CharRange)m_bytecode->at(offset++);
  477. auto from = value.from;
  478. auto to = value.to;
  479. auto ch = input.view[state.string_position_in_code_units];
  480. compare_character_range(input, state, from, to, ch, current_inversion_state(), inverse_matched);
  481. } else if (compare_type == CharacterCompareType::Reference) {
  482. auto reference_number = (size_t)m_bytecode->at(offset++);
  483. auto& groups = state.capture_group_matches.at(input.match_index);
  484. if (groups.size() <= reference_number)
  485. return ExecutionResult::Failed_ExecuteLowPrioForks;
  486. auto str = groups.at(reference_number).view;
  487. // We want to compare a string that is definitely longer than the available string
  488. if (input.view.length() < state.string_position + str.length())
  489. return ExecutionResult::Failed_ExecuteLowPrioForks;
  490. if (compare_string(input, state, str, had_zero_length_match)) {
  491. if (current_inversion_state())
  492. inverse_matched = true;
  493. }
  494. } else if (compare_type == CharacterCompareType::Property) {
  495. auto property = static_cast<Unicode::Property>(m_bytecode->at(offset++));
  496. compare_property(input, state, property, current_inversion_state(), inverse_matched);
  497. } else if (compare_type == CharacterCompareType::GeneralCategory) {
  498. auto general_category = static_cast<Unicode::GeneralCategory>(m_bytecode->at(offset++));
  499. compare_general_category(input, state, general_category, current_inversion_state(), inverse_matched);
  500. } else if (compare_type == CharacterCompareType::Script) {
  501. auto script = static_cast<Unicode::Script>(m_bytecode->at(offset++));
  502. compare_script(input, state, script, current_inversion_state(), inverse_matched);
  503. } else if (compare_type == CharacterCompareType::ScriptExtension) {
  504. auto script = static_cast<Unicode::Script>(m_bytecode->at(offset++));
  505. compare_script_extension(input, state, script, current_inversion_state(), inverse_matched);
  506. } else if (compare_type == CharacterCompareType::And) {
  507. disjunction_states.append({
  508. .active = true,
  509. .is_conjunction = false,
  510. .fail = false,
  511. .initial_position = state.string_position,
  512. .initial_code_unit_position = state.string_position_in_code_units,
  513. });
  514. continue;
  515. } else if (compare_type == CharacterCompareType::Or) {
  516. disjunction_states.append({
  517. .active = true,
  518. .is_conjunction = true,
  519. .fail = true,
  520. .initial_position = state.string_position,
  521. .initial_code_unit_position = state.string_position_in_code_units,
  522. });
  523. continue;
  524. } else if (compare_type == CharacterCompareType::EndAndOr) {
  525. auto disjunction_state = disjunction_states.take_last();
  526. if (!disjunction_state.fail) {
  527. state.string_position = disjunction_state.last_accepted_position.value_or(disjunction_state.initial_position);
  528. state.string_position_in_code_units = disjunction_state.last_accepted_code_unit_position.value_or(disjunction_state.initial_code_unit_position);
  529. }
  530. } else {
  531. warnln("Undefined comparison: {}", (int)compare_type);
  532. VERIFY_NOT_REACHED();
  533. break;
  534. }
  535. auto& new_disjunction_state = current_disjunction_state();
  536. if (current_inversion_state() && (!inverse || new_disjunction_state.active) && !inverse_matched) {
  537. advance_string_position(state, input.view);
  538. inverse_matched = true;
  539. }
  540. if (new_disjunction_state.active) {
  541. auto failed = (!had_zero_length_match && string_position == state.string_position) || state.string_position > input.view.length();
  542. if (!failed) {
  543. new_disjunction_state.last_accepted_position = state.string_position;
  544. new_disjunction_state.last_accepted_code_unit_position = state.string_position_in_code_units;
  545. }
  546. if (new_disjunction_state.is_conjunction)
  547. new_disjunction_state.fail = failed && new_disjunction_state.fail;
  548. else
  549. new_disjunction_state.fail = failed || new_disjunction_state.fail;
  550. state.string_position = new_disjunction_state.initial_position;
  551. state.string_position_in_code_units = new_disjunction_state.initial_code_unit_position;
  552. }
  553. }
  554. auto& new_disjunction_state = current_disjunction_state();
  555. if (new_disjunction_state.active) {
  556. if (!new_disjunction_state.fail) {
  557. state.string_position = new_disjunction_state.last_accepted_position.value_or(new_disjunction_state.initial_position);
  558. state.string_position_in_code_units = new_disjunction_state.last_accepted_code_unit_position.value_or(new_disjunction_state.initial_code_unit_position);
  559. }
  560. }
  561. if (current_inversion_state() && !inverse_matched)
  562. advance_string_position(state, input.view);
  563. if ((!had_zero_length_match && string_position == state.string_position) || state.string_position > input.view.length())
  564. return ExecutionResult::Failed_ExecuteLowPrioForks;
  565. return ExecutionResult::Continue;
  566. }
  567. ALWAYS_INLINE void OpCode_Compare::compare_char(MatchInput const& input, MatchState& state, u32 ch1, bool inverse, bool& inverse_matched)
  568. {
  569. if (state.string_position == input.view.length())
  570. return;
  571. auto input_view = input.view.substring_view(state.string_position, 1)[0];
  572. bool equal;
  573. if (input.regex_options & AllFlags::Insensitive)
  574. equal = to_ascii_lowercase(input_view) == to_ascii_lowercase(ch1); // FIXME: Implement case-insensitive matching for non-ascii characters
  575. else
  576. equal = input_view == ch1;
  577. if (equal) {
  578. if (inverse)
  579. inverse_matched = true;
  580. else
  581. advance_string_position(state, input.view, ch1);
  582. }
  583. }
  584. ALWAYS_INLINE bool OpCode_Compare::compare_string(MatchInput const& input, MatchState& state, RegexStringView str, bool& had_zero_length_match)
  585. {
  586. if (state.string_position + str.length() > input.view.length()) {
  587. if (str.is_empty()) {
  588. had_zero_length_match = true;
  589. return true;
  590. }
  591. return false;
  592. }
  593. if (str.length() == 0) {
  594. had_zero_length_match = true;
  595. return true;
  596. }
  597. auto subject = input.view.substring_view(state.string_position, str.length());
  598. bool equals;
  599. if (input.regex_options & AllFlags::Insensitive)
  600. equals = subject.equals_ignoring_case(str);
  601. else
  602. equals = subject.equals(str);
  603. if (equals)
  604. advance_string_position(state, input.view, str);
  605. return equals;
  606. }
  607. ALWAYS_INLINE void OpCode_Compare::compare_character_class(MatchInput const& input, MatchState& state, CharClass character_class, u32 ch, bool inverse, bool& inverse_matched)
  608. {
  609. if (matches_character_class(character_class, ch, input.regex_options & AllFlags::Insensitive)) {
  610. if (inverse)
  611. inverse_matched = true;
  612. else
  613. advance_string_position(state, input.view, ch);
  614. }
  615. }
  616. bool OpCode_Compare::matches_character_class(CharClass character_class, u32 ch, bool insensitive)
  617. {
  618. constexpr auto is_space_or_line_terminator = [](u32 code_point) {
  619. static auto space_separator = Unicode::general_category_from_string("Space_Separator"sv);
  620. if (!space_separator.has_value())
  621. return is_ascii_space(code_point);
  622. if ((code_point == 0x0a) || (code_point == 0x0d) || (code_point == 0x2028) || (code_point == 0x2029))
  623. return true;
  624. if ((code_point == 0x09) || (code_point == 0x0b) || (code_point == 0x0c) || (code_point == 0xfeff))
  625. return true;
  626. return Unicode::code_point_has_general_category(code_point, *space_separator);
  627. };
  628. switch (character_class) {
  629. case CharClass::Alnum:
  630. return is_ascii_alphanumeric(ch);
  631. case CharClass::Alpha:
  632. return is_ascii_alpha(ch);
  633. case CharClass::Blank:
  634. return is_ascii_blank(ch);
  635. case CharClass::Cntrl:
  636. return is_ascii_control(ch);
  637. case CharClass::Digit:
  638. return is_ascii_digit(ch);
  639. case CharClass::Graph:
  640. return is_ascii_graphical(ch);
  641. case CharClass::Lower:
  642. return is_ascii_lower_alpha(ch) || (insensitive && is_ascii_upper_alpha(ch));
  643. case CharClass::Print:
  644. return is_ascii_printable(ch);
  645. case CharClass::Punct:
  646. return is_ascii_punctuation(ch);
  647. case CharClass::Space:
  648. return is_space_or_line_terminator(ch);
  649. case CharClass::Upper:
  650. return is_ascii_upper_alpha(ch) || (insensitive && is_ascii_lower_alpha(ch));
  651. case CharClass::Word:
  652. return is_ascii_alphanumeric(ch) || ch == '_';
  653. case CharClass::Xdigit:
  654. return is_ascii_hex_digit(ch);
  655. }
  656. VERIFY_NOT_REACHED();
  657. }
  658. ALWAYS_INLINE void OpCode_Compare::compare_character_range(MatchInput const& input, MatchState& state, u32 from, u32 to, u32 ch, bool inverse, bool& inverse_matched)
  659. {
  660. if (input.regex_options & AllFlags::Insensitive) {
  661. from = to_ascii_lowercase(from);
  662. to = to_ascii_lowercase(to);
  663. ch = to_ascii_lowercase(ch);
  664. }
  665. if (ch >= from && ch <= to) {
  666. if (inverse)
  667. inverse_matched = true;
  668. else
  669. advance_string_position(state, input.view, ch);
  670. }
  671. }
  672. ALWAYS_INLINE void OpCode_Compare::compare_property(MatchInput const& input, MatchState& state, Unicode::Property property, bool inverse, bool& inverse_matched)
  673. {
  674. if (state.string_position == input.view.length())
  675. return;
  676. u32 code_point = input.view[state.string_position_in_code_units];
  677. bool equal = Unicode::code_point_has_property(code_point, property);
  678. if (equal) {
  679. if (inverse)
  680. inverse_matched = true;
  681. else
  682. advance_string_position(state, input.view, code_point);
  683. }
  684. }
  685. ALWAYS_INLINE void OpCode_Compare::compare_general_category(MatchInput const& input, MatchState& state, Unicode::GeneralCategory general_category, bool inverse, bool& inverse_matched)
  686. {
  687. if (state.string_position == input.view.length())
  688. return;
  689. u32 code_point = input.view[state.string_position_in_code_units];
  690. bool equal = Unicode::code_point_has_general_category(code_point, general_category);
  691. if (equal) {
  692. if (inverse)
  693. inverse_matched = true;
  694. else
  695. advance_string_position(state, input.view, code_point);
  696. }
  697. }
  698. ALWAYS_INLINE void OpCode_Compare::compare_script(MatchInput const& input, MatchState& state, Unicode::Script script, bool inverse, bool& inverse_matched)
  699. {
  700. if (state.string_position == input.view.length())
  701. return;
  702. u32 code_point = input.view[state.string_position_in_code_units];
  703. bool equal = Unicode::code_point_has_script(code_point, script);
  704. if (equal) {
  705. if (inverse)
  706. inverse_matched = true;
  707. else
  708. advance_string_position(state, input.view, code_point);
  709. }
  710. }
  711. ALWAYS_INLINE void OpCode_Compare::compare_script_extension(MatchInput const& input, MatchState& state, Unicode::Script script, bool inverse, bool& inverse_matched)
  712. {
  713. if (state.string_position == input.view.length())
  714. return;
  715. u32 code_point = input.view[state.string_position_in_code_units];
  716. bool equal = Unicode::code_point_has_script_extension(code_point, script);
  717. if (equal) {
  718. if (inverse)
  719. inverse_matched = true;
  720. else
  721. advance_string_position(state, input.view, code_point);
  722. }
  723. }
  724. String OpCode_Compare::arguments_string() const
  725. {
  726. return String::formatted("argc={}, args={} ", arguments_count(), arguments_size());
  727. }
  728. Vector<CompareTypeAndValuePair> OpCode_Compare::flat_compares() const
  729. {
  730. Vector<CompareTypeAndValuePair> result;
  731. size_t offset { state().instruction_position + 3 };
  732. for (size_t i = 0; i < arguments_count(); ++i) {
  733. auto compare_type = (CharacterCompareType)m_bytecode->at(offset++);
  734. if (compare_type == CharacterCompareType::Char) {
  735. auto ch = m_bytecode->at(offset++);
  736. result.append({ compare_type, ch });
  737. } else if (compare_type == CharacterCompareType::Reference) {
  738. auto ref = m_bytecode->at(offset++);
  739. result.append({ compare_type, ref });
  740. } else if (compare_type == CharacterCompareType::String) {
  741. auto& length = m_bytecode->at(offset++);
  742. if (length > 0)
  743. result.append({ compare_type, m_bytecode->at(offset) });
  744. StringBuilder str_builder;
  745. offset += length;
  746. } else if (compare_type == CharacterCompareType::CharClass) {
  747. auto character_class = m_bytecode->at(offset++);
  748. result.append({ compare_type, character_class });
  749. } else if (compare_type == CharacterCompareType::CharRange) {
  750. auto value = m_bytecode->at(offset++);
  751. result.append({ compare_type, value });
  752. } else if (compare_type == CharacterCompareType::LookupTable) {
  753. auto count = m_bytecode->at(offset++);
  754. for (size_t i = 0; i < count; ++i)
  755. result.append({ CharacterCompareType::CharRange, m_bytecode->at(offset++) });
  756. } else if (compare_type == CharacterCompareType::GeneralCategory
  757. || compare_type == CharacterCompareType::Property
  758. || compare_type == CharacterCompareType::Script
  759. || compare_type == CharacterCompareType::ScriptExtension) {
  760. auto value = m_bytecode->at(offset++);
  761. result.append({ compare_type, value });
  762. } else {
  763. result.append({ compare_type, 0 });
  764. }
  765. }
  766. return result;
  767. }
  768. Vector<String> OpCode_Compare::variable_arguments_to_string(Optional<MatchInput> input) const
  769. {
  770. Vector<String> result;
  771. size_t offset { state().instruction_position + 3 };
  772. RegexStringView view = ((input.has_value()) ? input.value().view : StringView {});
  773. for (size_t i = 0; i < arguments_count(); ++i) {
  774. auto compare_type = (CharacterCompareType)m_bytecode->at(offset++);
  775. result.empend(String::formatted("type={} [{}]", (size_t)compare_type, character_compare_type_name(compare_type)));
  776. auto string_start_offset = state().string_position_before_match;
  777. if (compare_type == CharacterCompareType::Char) {
  778. auto ch = m_bytecode->at(offset++);
  779. auto is_ascii = is_ascii_printable(ch);
  780. if (is_ascii)
  781. result.empend(String::formatted(" value='{:c}'", static_cast<char>(ch)));
  782. else
  783. result.empend(String::formatted(" value={:x}", ch));
  784. if (!view.is_null() && view.length() > string_start_offset) {
  785. if (is_ascii) {
  786. result.empend(String::formatted(
  787. " compare against: '{}'",
  788. view.substring_view(string_start_offset, string_start_offset > view.length() ? 0 : 1).to_string()));
  789. } else {
  790. auto str = view.substring_view(string_start_offset, string_start_offset > view.length() ? 0 : 1).to_string();
  791. u8 buf[8] { 0 };
  792. __builtin_memcpy(buf, str.characters(), min(str.length(), sizeof(buf)));
  793. result.empend(String::formatted(" compare against: {:x},{:x},{:x},{:x},{:x},{:x},{:x},{:x}",
  794. buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]));
  795. }
  796. }
  797. } else if (compare_type == CharacterCompareType::Reference) {
  798. auto ref = m_bytecode->at(offset++);
  799. result.empend(String::formatted(" number={}", ref));
  800. if (input.has_value()) {
  801. if (state().capture_group_matches.size() > input->match_index) {
  802. auto& match = state().capture_group_matches[input->match_index];
  803. if (match.size() > ref) {
  804. auto& group = match[ref];
  805. result.empend(String::formatted(" left={}", group.left_column));
  806. result.empend(String::formatted(" right={}", group.left_column + group.view.length_in_code_units()));
  807. result.empend(String::formatted(" contents='{}'", group.view));
  808. } else {
  809. result.empend(String::formatted(" (invalid ref, max={})", match.size() - 1));
  810. }
  811. } else {
  812. result.empend(String::formatted(" (invalid index {}, max={})", input->match_index, state().capture_group_matches.size() - 1));
  813. }
  814. }
  815. } else if (compare_type == CharacterCompareType::String) {
  816. auto& length = m_bytecode->at(offset++);
  817. StringBuilder str_builder;
  818. for (size_t i = 0; i < length; ++i)
  819. str_builder.append(m_bytecode->at(offset++));
  820. result.empend(String::formatted(" value=\"{}\"", str_builder.string_view().substring_view(0, length)));
  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, string_start_offset + length > view.length() ? 0 : length).to_string()));
  825. } else if (compare_type == CharacterCompareType::CharClass) {
  826. auto character_class = (CharClass)m_bytecode->at(offset++);
  827. result.empend(String::formatted(" ch_class={} [{}]", (size_t)character_class, character_class_name(character_class)));
  828. if (!view.is_null() && view.length() > state().string_position)
  829. result.empend(String::formatted(
  830. " compare against: '{}'",
  831. input.value().view.substring_view(string_start_offset, state().string_position > view.length() ? 0 : 1).to_string()));
  832. } else if (compare_type == CharacterCompareType::CharRange) {
  833. auto value = (CharRange)m_bytecode->at(offset++);
  834. result.empend(String::formatted(" ch_range={:x}-{:x}", value.from, value.to));
  835. if (!view.is_null() && view.length() > state().string_position)
  836. result.empend(String::formatted(
  837. " compare against: '{}'",
  838. input.value().view.substring_view(string_start_offset, state().string_position > view.length() ? 0 : 1).to_string()));
  839. } else if (compare_type == CharacterCompareType::LookupTable) {
  840. auto count = m_bytecode->at(offset++);
  841. for (size_t j = 0; j < count; ++j) {
  842. auto range = (CharRange)m_bytecode->at(offset++);
  843. result.append(String::formatted(" {:x}-{:x}", range.from, range.to));
  844. }
  845. if (!view.is_null() && view.length() > state().string_position)
  846. result.empend(String::formatted(
  847. " compare against: '{}'",
  848. input.value().view.substring_view(string_start_offset, state().string_position > view.length() ? 0 : 1).to_string()));
  849. } else if (compare_type == CharacterCompareType::GeneralCategory
  850. || compare_type == CharacterCompareType::Property
  851. || compare_type == CharacterCompareType::Script
  852. || compare_type == CharacterCompareType::ScriptExtension) {
  853. auto value = m_bytecode->at(offset++);
  854. result.empend(String::formatted(" value={}", value));
  855. }
  856. }
  857. return result;
  858. }
  859. ALWAYS_INLINE ExecutionResult OpCode_Repeat::execute(MatchInput const&, MatchState& state) const
  860. {
  861. VERIFY(count() > 0);
  862. if (id() >= state.repetition_marks.size())
  863. state.repetition_marks.resize(id() + 1);
  864. auto& repetition_mark = state.repetition_marks.at(id());
  865. if (repetition_mark == count() - 1) {
  866. repetition_mark = 0;
  867. } else {
  868. state.instruction_position -= offset() + size();
  869. ++repetition_mark;
  870. }
  871. return ExecutionResult::Continue;
  872. }
  873. ALWAYS_INLINE ExecutionResult OpCode_ResetRepeat::execute(MatchInput const&, MatchState& state) const
  874. {
  875. if (id() >= state.repetition_marks.size())
  876. state.repetition_marks.resize(id() + 1);
  877. state.repetition_marks.at(id()) = 0;
  878. return ExecutionResult::Continue;
  879. }
  880. ALWAYS_INLINE ExecutionResult OpCode_Checkpoint::execute(MatchInput const& input, MatchState& state) const
  881. {
  882. input.checkpoints.set(state.instruction_position, state.string_position);
  883. return ExecutionResult::Continue;
  884. }
  885. ALWAYS_INLINE ExecutionResult OpCode_JumpNonEmpty::execute(MatchInput const& input, MatchState& state) const
  886. {
  887. auto current_position = state.string_position;
  888. auto checkpoint_ip = state.instruction_position + size() + checkpoint();
  889. if (input.checkpoints.get(checkpoint_ip).value_or(current_position) != current_position) {
  890. auto form = this->form();
  891. if (form == OpCodeId::Jump) {
  892. state.instruction_position += offset();
  893. return ExecutionResult::Continue;
  894. }
  895. state.fork_at_position = state.instruction_position + size() + offset();
  896. if (form == OpCodeId::ForkJump)
  897. return ExecutionResult::Fork_PrioHigh;
  898. if (form == OpCodeId::ForkStay)
  899. return ExecutionResult::Fork_PrioLow;
  900. if (form == OpCodeId::ForkReplaceStay) {
  901. input.fork_to_replace = state.instruction_position;
  902. return ExecutionResult::Fork_PrioLow;
  903. }
  904. if (form == OpCodeId::ForkReplaceJump) {
  905. input.fork_to_replace = state.instruction_position;
  906. return ExecutionResult::Fork_PrioHigh;
  907. }
  908. }
  909. return ExecutionResult::Continue;
  910. }
  911. }