RegexByteCode.cpp 36 KB

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