RegexByteCode.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  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/CharacterTypes.h>
  10. #include <AK/Debug.h>
  11. namespace regex {
  12. const char* OpCode::name(OpCodeId opcode_id)
  13. {
  14. switch (opcode_id) {
  15. #define __ENUMERATE_OPCODE(x) \
  16. case OpCodeId::x: \
  17. return #x;
  18. ENUMERATE_OPCODES
  19. #undef __ENUMERATE_OPCODE
  20. default:
  21. VERIFY_NOT_REACHED();
  22. return "<Unknown>";
  23. }
  24. }
  25. const char* OpCode::name() const
  26. {
  27. return name(opcode_id());
  28. }
  29. const char* execution_result_name(ExecutionResult result)
  30. {
  31. switch (result) {
  32. #define __ENUMERATE_EXECUTION_RESULT(x) \
  33. case ExecutionResult::x: \
  34. return #x;
  35. ENUMERATE_EXECUTION_RESULTS
  36. #undef __ENUMERATE_EXECUTION_RESULT
  37. default:
  38. VERIFY_NOT_REACHED();
  39. return "<Unknown>";
  40. }
  41. }
  42. const char* boundary_check_type_name(BoundaryCheckType ty)
  43. {
  44. switch (ty) {
  45. #define __ENUMERATE_BOUNDARY_CHECK_TYPE(x) \
  46. case BoundaryCheckType::x: \
  47. return #x;
  48. ENUMERATE_BOUNDARY_CHECK_TYPES
  49. #undef __ENUMERATE_BOUNDARY_CHECK_TYPE
  50. default:
  51. VERIFY_NOT_REACHED();
  52. return "<Unknown>";
  53. }
  54. }
  55. const char* character_compare_type_name(CharacterCompareType ch_compare_type)
  56. {
  57. switch (ch_compare_type) {
  58. #define __ENUMERATE_CHARACTER_COMPARE_TYPE(x) \
  59. case CharacterCompareType::x: \
  60. return #x;
  61. ENUMERATE_CHARACTER_COMPARE_TYPES
  62. #undef __ENUMERATE_CHARACTER_COMPARE_TYPE
  63. default:
  64. VERIFY_NOT_REACHED();
  65. return "<Unknown>";
  66. }
  67. }
  68. static const char* character_class_name(CharClass ch_class)
  69. {
  70. switch (ch_class) {
  71. #define __ENUMERATE_CHARACTER_CLASS(x) \
  72. case CharClass::x: \
  73. return #x;
  74. ENUMERATE_CHARACTER_CLASSES
  75. #undef __ENUMERATE_CHARACTER_CLASS
  76. default:
  77. VERIFY_NOT_REACHED();
  78. return "<Unknown>";
  79. }
  80. }
  81. OwnPtr<OpCode> ByteCode::s_opcodes[(size_t)OpCodeId::Last + 1];
  82. bool ByteCode::s_opcodes_initialized { false };
  83. void ByteCode::ensure_opcodes_initialized()
  84. {
  85. if (s_opcodes_initialized)
  86. return;
  87. for (u32 i = (u32)OpCodeId::First; i <= (u32)OpCodeId::Last; ++i) {
  88. switch ((OpCodeId)i) {
  89. case OpCodeId::Exit:
  90. s_opcodes[i] = make<OpCode_Exit>();
  91. break;
  92. case OpCodeId::Jump:
  93. s_opcodes[i] = make<OpCode_Jump>();
  94. break;
  95. case OpCodeId::Compare:
  96. s_opcodes[i] = make<OpCode_Compare>();
  97. break;
  98. case OpCodeId::CheckEnd:
  99. s_opcodes[i] = make<OpCode_CheckEnd>();
  100. break;
  101. case OpCodeId::CheckBoundary:
  102. s_opcodes[i] = make<OpCode_CheckBoundary>();
  103. break;
  104. case OpCodeId::ForkJump:
  105. s_opcodes[i] = make<OpCode_ForkJump>();
  106. break;
  107. case OpCodeId::ForkStay:
  108. s_opcodes[i] = make<OpCode_ForkStay>();
  109. break;
  110. case OpCodeId::FailForks:
  111. s_opcodes[i] = make<OpCode_FailForks>();
  112. break;
  113. case OpCodeId::Save:
  114. s_opcodes[i] = make<OpCode_Save>();
  115. break;
  116. case OpCodeId::Restore:
  117. s_opcodes[i] = make<OpCode_Restore>();
  118. break;
  119. case OpCodeId::GoBack:
  120. s_opcodes[i] = make<OpCode_GoBack>();
  121. break;
  122. case OpCodeId::CheckBegin:
  123. s_opcodes[i] = make<OpCode_CheckBegin>();
  124. break;
  125. case OpCodeId::SaveLeftCaptureGroup:
  126. s_opcodes[i] = make<OpCode_SaveLeftCaptureGroup>();
  127. break;
  128. case OpCodeId::SaveRightCaptureGroup:
  129. s_opcodes[i] = make<OpCode_SaveRightCaptureGroup>();
  130. break;
  131. case OpCodeId::SaveLeftNamedCaptureGroup:
  132. s_opcodes[i] = make<OpCode_SaveLeftNamedCaptureGroup>();
  133. break;
  134. case OpCodeId::SaveRightNamedCaptureGroup:
  135. s_opcodes[i] = make<OpCode_SaveRightNamedCaptureGroup>();
  136. break;
  137. }
  138. }
  139. s_opcodes_initialized = true;
  140. }
  141. ALWAYS_INLINE OpCode& ByteCode::get_opcode_by_id(OpCodeId id) const
  142. {
  143. VERIFY(id >= OpCodeId::First && id <= OpCodeId::Last);
  144. auto& opcode = s_opcodes[(u32)id];
  145. opcode->set_bytecode(*const_cast<ByteCode*>(this));
  146. return *opcode;
  147. }
  148. OpCode& ByteCode::get_opcode(MatchState& state) const
  149. {
  150. OpCodeId opcode_id;
  151. if (state.instruction_position >= size())
  152. opcode_id = OpCodeId::Exit;
  153. else
  154. opcode_id = (OpCodeId)at(state.instruction_position);
  155. auto& opcode = get_opcode_by_id(opcode_id);
  156. opcode.set_state(state);
  157. return opcode;
  158. }
  159. ALWAYS_INLINE ExecutionResult OpCode_Exit::execute(const MatchInput& input, MatchState& state, MatchOutput&) 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(const MatchInput& input, MatchState& state, MatchOutput&) const
  166. {
  167. input.saved_positions.append(state.string_position);
  168. return ExecutionResult::Continue;
  169. }
  170. ALWAYS_INLINE ExecutionResult OpCode_Restore::execute(const MatchInput& input, MatchState& state, MatchOutput&) const
  171. {
  172. if (input.saved_positions.is_empty())
  173. return ExecutionResult::Failed;
  174. state.string_position = input.saved_positions.take_last();
  175. return ExecutionResult::Continue;
  176. }
  177. ALWAYS_INLINE ExecutionResult OpCode_GoBack::execute(const MatchInput&, MatchState& state, MatchOutput&) const
  178. {
  179. if (count() > state.string_position)
  180. return ExecutionResult::Failed_ExecuteLowPrioForks;
  181. state.string_position -= count();
  182. return ExecutionResult::Continue;
  183. }
  184. ALWAYS_INLINE ExecutionResult OpCode_FailForks::execute(const MatchInput& input, MatchState&, MatchOutput&) const
  185. {
  186. VERIFY(count() > 0);
  187. input.fail_counter += count() - 1;
  188. return ExecutionResult::Failed_ExecuteLowPrioForks;
  189. }
  190. ALWAYS_INLINE ExecutionResult OpCode_Jump::execute(const MatchInput&, MatchState& state, MatchOutput&) const
  191. {
  192. state.instruction_position += offset();
  193. return ExecutionResult::Continue;
  194. }
  195. ALWAYS_INLINE ExecutionResult OpCode_ForkJump::execute(const MatchInput&, MatchState& state, MatchOutput&) const
  196. {
  197. state.fork_at_position = state.instruction_position + size() + offset();
  198. return ExecutionResult::Fork_PrioHigh;
  199. }
  200. ALWAYS_INLINE ExecutionResult OpCode_ForkStay::execute(const MatchInput&, MatchState& state, MatchOutput&) const
  201. {
  202. state.fork_at_position = state.instruction_position + size() + offset();
  203. return ExecutionResult::Fork_PrioLow;
  204. }
  205. ALWAYS_INLINE ExecutionResult OpCode_CheckBegin::execute(const MatchInput& input, MatchState& state, MatchOutput&) const
  206. {
  207. if (0 == state.string_position && (input.regex_options & AllFlags::MatchNotBeginOfLine))
  208. return ExecutionResult::Failed_ExecuteLowPrioForks;
  209. if ((0 == state.string_position && !(input.regex_options & AllFlags::MatchNotBeginOfLine))
  210. || (0 != state.string_position && (input.regex_options & AllFlags::MatchNotBeginOfLine))
  211. || (0 == state.string_position && (input.regex_options & AllFlags::Global)))
  212. return ExecutionResult::Continue;
  213. return ExecutionResult::Failed_ExecuteLowPrioForks;
  214. }
  215. ALWAYS_INLINE ExecutionResult OpCode_CheckBoundary::execute(const MatchInput& input, MatchState& state, MatchOutput&) const
  216. {
  217. auto isword = [](auto ch) { return is_ascii_alphanumeric(ch) || ch == '_'; };
  218. auto is_word_boundary = [&] {
  219. if (state.string_position == input.view.length()) {
  220. if (state.string_position > 0 && isword(input.view[state.string_position - 1]))
  221. return true;
  222. return false;
  223. }
  224. if (state.string_position == 0) {
  225. if (isword(input.view[0]))
  226. return true;
  227. return false;
  228. }
  229. return !!(isword(input.view[state.string_position]) ^ isword(input.view[state.string_position - 1]));
  230. };
  231. switch (type()) {
  232. case BoundaryCheckType::Word: {
  233. if (is_word_boundary())
  234. return ExecutionResult::Continue;
  235. return ExecutionResult::Failed_ExecuteLowPrioForks;
  236. }
  237. case BoundaryCheckType::NonWord: {
  238. if (!is_word_boundary())
  239. return ExecutionResult::Continue;
  240. return ExecutionResult::Failed_ExecuteLowPrioForks;
  241. }
  242. }
  243. VERIFY_NOT_REACHED();
  244. }
  245. ALWAYS_INLINE ExecutionResult OpCode_CheckEnd::execute(const MatchInput& input, MatchState& state, MatchOutput&) const
  246. {
  247. if (state.string_position == input.view.length() && (input.regex_options & AllFlags::MatchNotEndOfLine))
  248. return ExecutionResult::Failed_ExecuteLowPrioForks;
  249. if ((state.string_position == input.view.length() && !(input.regex_options & AllFlags::MatchNotEndOfLine))
  250. || (state.string_position != input.view.length() && (input.regex_options & AllFlags::MatchNotEndOfLine || input.regex_options & AllFlags::MatchNotBeginOfLine)))
  251. return ExecutionResult::Continue;
  252. return ExecutionResult::Failed_ExecuteLowPrioForks;
  253. }
  254. ALWAYS_INLINE ExecutionResult OpCode_SaveLeftCaptureGroup::execute(const MatchInput& input, MatchState& state, MatchOutput&) const
  255. {
  256. if (input.match_index >= state.capture_group_matches.size()) {
  257. state.capture_group_matches.ensure_capacity(input.match_index);
  258. auto capacity = state.capture_group_matches.capacity();
  259. for (size_t i = state.capture_group_matches.size(); i <= capacity; ++i)
  260. state.capture_group_matches.empend();
  261. }
  262. if (id() >= state.capture_group_matches.at(input.match_index).size()) {
  263. state.capture_group_matches.at(input.match_index).ensure_capacity(id());
  264. auto capacity = state.capture_group_matches.at(input.match_index).capacity();
  265. for (size_t i = state.capture_group_matches.at(input.match_index).size(); i <= capacity; ++i)
  266. state.capture_group_matches.at(input.match_index).empend();
  267. }
  268. state.capture_group_matches.at(input.match_index).at(id()).left_column = state.string_position;
  269. return ExecutionResult::Continue;
  270. }
  271. ALWAYS_INLINE ExecutionResult OpCode_SaveRightCaptureGroup::execute(const MatchInput& input, MatchState& state, MatchOutput&) const
  272. {
  273. auto& match = state.capture_group_matches.at(input.match_index).at(id());
  274. auto start_position = match.left_column;
  275. if (state.string_position < start_position)
  276. return ExecutionResult::Failed_ExecuteLowPrioForks;
  277. auto length = state.string_position - start_position;
  278. if (start_position < match.column)
  279. return ExecutionResult::Continue;
  280. VERIFY(start_position + length <= input.view.length());
  281. auto view = input.view.substring_view(start_position, length);
  282. if (input.regex_options & AllFlags::StringCopyMatches) {
  283. match = { view.to_string(), input.line, start_position, input.global_offset + start_position }; // create a copy of the original string
  284. } else {
  285. match = { view, input.line, start_position, input.global_offset + start_position }; // take view to original string
  286. }
  287. return ExecutionResult::Continue;
  288. }
  289. ALWAYS_INLINE ExecutionResult OpCode_SaveLeftNamedCaptureGroup::execute(const MatchInput& input, MatchState& state, MatchOutput&) const
  290. {
  291. if (input.match_index >= state.named_capture_group_matches.size()) {
  292. state.named_capture_group_matches.ensure_capacity(input.match_index);
  293. auto capacity = state.named_capture_group_matches.capacity();
  294. for (size_t i = state.named_capture_group_matches.size(); i <= capacity; ++i)
  295. state.named_capture_group_matches.empend();
  296. }
  297. state.named_capture_group_matches.at(input.match_index).ensure(name()).column = state.string_position;
  298. return ExecutionResult::Continue;
  299. }
  300. ALWAYS_INLINE ExecutionResult OpCode_SaveRightNamedCaptureGroup::execute(const MatchInput& input, MatchState& state, MatchOutput&) const
  301. {
  302. StringView capture_group_name = name();
  303. if (state.named_capture_group_matches.at(input.match_index).contains(capture_group_name)) {
  304. auto start_position = state.named_capture_group_matches.at(input.match_index).ensure(capture_group_name).column;
  305. auto length = state.string_position - start_position;
  306. auto& map = state.named_capture_group_matches.at(input.match_index);
  307. if constexpr (REGEX_DEBUG) {
  308. VERIFY(start_position + length <= input.view.length());
  309. dbgln("Save named capture group with name={} and content='{}'", capture_group_name, input.view.substring_view(start_position, length));
  310. }
  311. VERIFY(start_position + length <= input.view.length());
  312. auto view = input.view.substring_view(start_position, length);
  313. if (input.regex_options & AllFlags::StringCopyMatches) {
  314. map.set(capture_group_name, { view.to_string(), input.line, start_position, input.global_offset + start_position }); // create a copy of the original string
  315. } else {
  316. map.set(capture_group_name, { view, input.line, start_position, input.global_offset + start_position }); // take view to original string
  317. }
  318. } else {
  319. warnln("Didn't find corresponding capture group match for name={}, match_index={}", capture_group_name.to_string(), input.match_index);
  320. }
  321. return ExecutionResult::Continue;
  322. }
  323. ALWAYS_INLINE ExecutionResult OpCode_Compare::execute(const MatchInput& input, MatchState& state, MatchOutput&) const
  324. {
  325. bool inverse { false };
  326. bool temporary_inverse { false };
  327. bool reset_temp_inverse { false };
  328. auto current_inversion_state = [&]() -> bool { return temporary_inverse ^ inverse; };
  329. size_t string_position = state.string_position;
  330. bool inverse_matched { false };
  331. bool had_zero_length_match { false };
  332. state.string_position_before_match = state.string_position;
  333. size_t offset { state.instruction_position + 3 };
  334. for (size_t i = 0; i < arguments_count(); ++i) {
  335. if (state.string_position > string_position)
  336. break;
  337. if (reset_temp_inverse) {
  338. reset_temp_inverse = false;
  339. temporary_inverse = false;
  340. } else {
  341. reset_temp_inverse = true;
  342. }
  343. auto compare_type = (CharacterCompareType)m_bytecode->at(offset++);
  344. if (compare_type == CharacterCompareType::Inverse)
  345. inverse = true;
  346. else if (compare_type == CharacterCompareType::TemporaryInverse) {
  347. // If "TemporaryInverse" is given, negate the current inversion state only for the next opcode.
  348. // it follows that this cannot be the last compare element.
  349. VERIFY(i != arguments_count() - 1);
  350. temporary_inverse = true;
  351. reset_temp_inverse = false;
  352. } else if (compare_type == CharacterCompareType::Char) {
  353. u32 ch = m_bytecode->at(offset++);
  354. // We want to compare a string that is longer or equal in length to the available string
  355. if (input.view.length() <= state.string_position)
  356. return ExecutionResult::Failed_ExecuteLowPrioForks;
  357. compare_char(input, state, ch, current_inversion_state(), inverse_matched);
  358. } else if (compare_type == CharacterCompareType::AnyChar) {
  359. // We want to compare a string that is definitely longer than the available string
  360. if (input.view.length() <= state.string_position)
  361. return ExecutionResult::Failed_ExecuteLowPrioForks;
  362. VERIFY(!current_inversion_state());
  363. ++state.string_position;
  364. } else if (compare_type == CharacterCompareType::String) {
  365. VERIFY(!current_inversion_state());
  366. const auto& length = m_bytecode->at(offset++);
  367. // We want to compare a string that is definitely longer than the available string
  368. if (input.view.length() < state.string_position + length)
  369. return ExecutionResult::Failed_ExecuteLowPrioForks;
  370. Optional<String> str;
  371. Vector<u32> data;
  372. data.ensure_capacity(length);
  373. for (size_t i = offset; i < offset + length; ++i)
  374. data.unchecked_append(m_bytecode->at(i));
  375. auto view = input.view.construct_as_same(data, str);
  376. offset += length;
  377. if (!compare_string(input, state, view, had_zero_length_match))
  378. return ExecutionResult::Failed_ExecuteLowPrioForks;
  379. } else if (compare_type == CharacterCompareType::CharClass) {
  380. if (input.view.length() <= state.string_position)
  381. return ExecutionResult::Failed_ExecuteLowPrioForks;
  382. auto character_class = (CharClass)m_bytecode->at(offset++);
  383. auto ch = input.view[state.string_position];
  384. compare_character_class(input, state, character_class, ch, current_inversion_state(), inverse_matched);
  385. } else if (compare_type == CharacterCompareType::CharRange) {
  386. if (input.view.length() <= state.string_position)
  387. return ExecutionResult::Failed_ExecuteLowPrioForks;
  388. auto value = (CharRange)m_bytecode->at(offset++);
  389. auto from = value.from;
  390. auto to = value.to;
  391. auto ch = input.view[state.string_position];
  392. compare_character_range(input, state, from, to, ch, current_inversion_state(), inverse_matched);
  393. } else if (compare_type == CharacterCompareType::Reference) {
  394. auto reference_number = (size_t)m_bytecode->at(offset++);
  395. auto& groups = state.capture_group_matches.at(input.match_index);
  396. if (groups.size() <= reference_number)
  397. return ExecutionResult::Failed_ExecuteLowPrioForks;
  398. auto str = groups.at(reference_number).view;
  399. // We want to compare a string that is definitely longer than the available string
  400. if (input.view.length() < state.string_position + str.length())
  401. return ExecutionResult::Failed_ExecuteLowPrioForks;
  402. if (!compare_string(input, state, str, had_zero_length_match))
  403. return ExecutionResult::Failed_ExecuteLowPrioForks;
  404. } else if (compare_type == CharacterCompareType::NamedReference) {
  405. auto ptr = (const char*)m_bytecode->at(offset++);
  406. auto length = (size_t)m_bytecode->at(offset++);
  407. StringView name { ptr, length };
  408. auto group = state.named_capture_group_matches.at(input.match_index).get(name);
  409. if (!group.has_value())
  410. return ExecutionResult::Failed_ExecuteLowPrioForks;
  411. auto str = group.value().view;
  412. // We want to compare a string that is definitely longer than the available string
  413. if (input.view.length() < state.string_position + str.length())
  414. return ExecutionResult::Failed_ExecuteLowPrioForks;
  415. if (!compare_string(input, state, str, had_zero_length_match))
  416. return ExecutionResult::Failed_ExecuteLowPrioForks;
  417. } else {
  418. warnln("Undefined comparison: {}", (int)compare_type);
  419. VERIFY_NOT_REACHED();
  420. break;
  421. }
  422. }
  423. if (current_inversion_state() && !inverse_matched)
  424. ++state.string_position;
  425. if ((!had_zero_length_match && string_position == state.string_position) || state.string_position > input.view.length())
  426. return ExecutionResult::Failed_ExecuteLowPrioForks;
  427. return ExecutionResult::Continue;
  428. }
  429. ALWAYS_INLINE void OpCode_Compare::compare_char(const MatchInput& input, MatchState& state, u32 ch1, bool inverse, bool& inverse_matched)
  430. {
  431. if (state.string_position == input.view.length())
  432. return;
  433. auto input_view = input.view.substring_view(state.string_position, 1);
  434. Optional<String> str;
  435. auto compare_view = input_view.construct_as_same({ &ch1, 1 }, str);
  436. bool equal;
  437. if (input.regex_options & AllFlags::Insensitive)
  438. equal = input_view.equals_ignoring_case(compare_view);
  439. else
  440. equal = input_view.equals(compare_view);
  441. if (equal) {
  442. if (inverse)
  443. inverse_matched = true;
  444. else
  445. ++state.string_position;
  446. }
  447. }
  448. ALWAYS_INLINE bool OpCode_Compare::compare_string(const MatchInput& input, MatchState& state, RegexStringView const& str, bool& had_zero_length_match)
  449. {
  450. if (state.string_position + str.length() > input.view.length()) {
  451. if (str.is_empty()) {
  452. had_zero_length_match = true;
  453. return true;
  454. }
  455. return false;
  456. }
  457. if (str.length() == 0) {
  458. had_zero_length_match = true;
  459. return true;
  460. }
  461. auto subject = input.view.substring_view(state.string_position, str.length());
  462. bool equals;
  463. if (input.regex_options & AllFlags::Insensitive)
  464. equals = subject.equals_ignoring_case(str);
  465. else
  466. equals = subject.equals(str);
  467. if (equals)
  468. state.string_position += str.length();
  469. return equals;
  470. }
  471. ALWAYS_INLINE void OpCode_Compare::compare_character_class(const MatchInput& input, MatchState& state, CharClass character_class, u32 ch, bool inverse, bool& inverse_matched)
  472. {
  473. switch (character_class) {
  474. case CharClass::Alnum:
  475. if (is_ascii_alphanumeric(ch)) {
  476. if (inverse)
  477. inverse_matched = true;
  478. else
  479. ++state.string_position;
  480. }
  481. break;
  482. case CharClass::Alpha:
  483. if (is_ascii_alpha(ch))
  484. ++state.string_position;
  485. break;
  486. case CharClass::Blank:
  487. if (is_ascii_blank(ch)) {
  488. if (inverse)
  489. inverse_matched = true;
  490. else
  491. ++state.string_position;
  492. }
  493. break;
  494. case CharClass::Cntrl:
  495. if (is_ascii_control(ch)) {
  496. if (inverse)
  497. inverse_matched = true;
  498. else
  499. ++state.string_position;
  500. }
  501. break;
  502. case CharClass::Digit:
  503. if (is_ascii_digit(ch)) {
  504. if (inverse)
  505. inverse_matched = true;
  506. else
  507. ++state.string_position;
  508. }
  509. break;
  510. case CharClass::Graph:
  511. if (is_ascii_graphical(ch)) {
  512. if (inverse)
  513. inverse_matched = true;
  514. else
  515. ++state.string_position;
  516. }
  517. break;
  518. case CharClass::Lower:
  519. if (is_ascii_lower_alpha(ch) || ((input.regex_options & AllFlags::Insensitive) && is_ascii_upper_alpha(ch))) {
  520. if (inverse)
  521. inverse_matched = true;
  522. else
  523. ++state.string_position;
  524. }
  525. break;
  526. case CharClass::Print:
  527. if (is_ascii_printable(ch)) {
  528. if (inverse)
  529. inverse_matched = true;
  530. else
  531. ++state.string_position;
  532. }
  533. break;
  534. case CharClass::Punct:
  535. if (is_ascii_punctuation(ch)) {
  536. if (inverse)
  537. inverse_matched = true;
  538. else
  539. ++state.string_position;
  540. }
  541. break;
  542. case CharClass::Space:
  543. if (is_ascii_space(ch)) {
  544. if (inverse)
  545. inverse_matched = true;
  546. else
  547. ++state.string_position;
  548. }
  549. break;
  550. case CharClass::Upper:
  551. if (is_ascii_upper_alpha(ch) || ((input.regex_options & AllFlags::Insensitive) && is_ascii_lower_alpha(ch))) {
  552. if (inverse)
  553. inverse_matched = true;
  554. else
  555. ++state.string_position;
  556. }
  557. break;
  558. case CharClass::Word:
  559. if (is_ascii_alphanumeric(ch) || ch == '_') {
  560. if (inverse)
  561. inverse_matched = true;
  562. else
  563. ++state.string_position;
  564. }
  565. break;
  566. case CharClass::Xdigit:
  567. if (is_ascii_hex_digit(ch)) {
  568. if (inverse)
  569. inverse_matched = true;
  570. else
  571. ++state.string_position;
  572. }
  573. break;
  574. }
  575. }
  576. ALWAYS_INLINE void OpCode_Compare::compare_character_range(const MatchInput& input, MatchState& state, u32 from, u32 to, u32 ch, bool inverse, bool& inverse_matched)
  577. {
  578. if (input.regex_options & AllFlags::Insensitive) {
  579. from = to_ascii_lowercase(from);
  580. to = to_ascii_lowercase(to);
  581. ch = to_ascii_lowercase(ch);
  582. }
  583. if (ch >= from && ch <= to) {
  584. if (inverse)
  585. inverse_matched = true;
  586. else
  587. ++state.string_position;
  588. }
  589. }
  590. const String OpCode_Compare::arguments_string() const
  591. {
  592. return String::formatted("argc={}, args={} ", arguments_count(), arguments_size());
  593. }
  594. const Vector<String> OpCode_Compare::variable_arguments_to_string(Optional<MatchInput> input) const
  595. {
  596. Vector<String> result;
  597. size_t offset { state().instruction_position + 3 };
  598. RegexStringView view = ((input.has_value()) ? input.value().view : nullptr);
  599. for (size_t i = 0; i < arguments_count(); ++i) {
  600. auto compare_type = (CharacterCompareType)m_bytecode->at(offset++);
  601. result.empend(String::formatted("type={} [{}]", (size_t)compare_type, character_compare_type_name(compare_type)));
  602. auto string_start_offset = state().string_position_before_match;
  603. if (compare_type == CharacterCompareType::Char) {
  604. auto ch = m_bytecode->at(offset++);
  605. auto is_ascii = is_ascii_printable(ch);
  606. if (is_ascii)
  607. result.empend(String::formatted("value='{:c}'", static_cast<char>(ch)));
  608. else
  609. result.empend(String::formatted("value={:x}", ch));
  610. if (!view.is_null() && view.length() > string_start_offset) {
  611. if (is_ascii) {
  612. result.empend(String::formatted(
  613. "compare against: '{}'",
  614. view.substring_view(string_start_offset, string_start_offset > view.length() ? 0 : 1).to_string()));
  615. } else {
  616. auto str = view.substring_view(string_start_offset, string_start_offset > view.length() ? 0 : 1).to_string();
  617. u8 buf[8] { 0 };
  618. __builtin_memcpy(buf, str.characters(), min(str.length(), sizeof(buf)));
  619. result.empend(String::formatted("compare against: {:x},{:x},{:x},{:x},{:x},{:x},{:x},{:x}",
  620. buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]));
  621. }
  622. }
  623. } else if (compare_type == CharacterCompareType::NamedReference) {
  624. auto ptr = (const char*)m_bytecode->at(offset++);
  625. auto length = m_bytecode->at(offset++);
  626. result.empend(String::formatted("name='{}'", StringView { ptr, (size_t)length }));
  627. } else if (compare_type == CharacterCompareType::Reference) {
  628. auto ref = m_bytecode->at(offset++);
  629. result.empend(String::formatted("number={}", ref));
  630. } else if (compare_type == CharacterCompareType::String) {
  631. auto& length = m_bytecode->at(offset++);
  632. StringBuilder str_builder;
  633. for (size_t i = 0; i < length; ++i)
  634. str_builder.append(m_bytecode->at(offset++));
  635. result.empend(String::formatted("value=\"{}\"", str_builder.string_view().substring_view(0, length)));
  636. if (!view.is_null() && view.length() > state().string_position)
  637. result.empend(String::formatted(
  638. "compare against: \"{}\"",
  639. input.value().view.substring_view(string_start_offset, string_start_offset + length > view.length() ? 0 : length).to_string()));
  640. } else if (compare_type == CharacterCompareType::CharClass) {
  641. auto character_class = (CharClass)m_bytecode->at(offset++);
  642. result.empend(String::formatted("ch_class={} [{}]", (size_t)character_class, character_class_name(character_class)));
  643. if (!view.is_null() && view.length() > state().string_position)
  644. result.empend(String::formatted(
  645. "compare against: '{}'",
  646. input.value().view.substring_view(string_start_offset, state().string_position > view.length() ? 0 : 1).to_string()));
  647. } else if (compare_type == CharacterCompareType::CharRange) {
  648. auto value = (CharRange)m_bytecode->at(offset++);
  649. result.empend(String::formatted("ch_range='{:c}'-'{:c}'", value.from, value.to));
  650. if (!view.is_null() && view.length() > state().string_position)
  651. result.empend(String::formatted(
  652. "compare against: '{}'",
  653. input.value().view.substring_view(string_start_offset, state().string_position > view.length() ? 0 : 1).to_string()));
  654. }
  655. }
  656. return result;
  657. }
  658. }