RegexByteCode.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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& output) const
  255. {
  256. if (input.match_index >= output.capture_group_matches.size()) {
  257. output.capture_group_matches.ensure_capacity(input.match_index);
  258. auto capacity = output.capture_group_matches.capacity();
  259. for (size_t i = output.capture_group_matches.size(); i <= capacity; ++i)
  260. output.capture_group_matches.empend();
  261. }
  262. if (id() >= output.capture_group_matches.at(input.match_index).size()) {
  263. output.capture_group_matches.at(input.match_index).ensure_capacity(id());
  264. auto capacity = output.capture_group_matches.at(input.match_index).capacity();
  265. for (size_t i = output.capture_group_matches.at(input.match_index).size(); i <= capacity; ++i)
  266. output.capture_group_matches.at(input.match_index).empend();
  267. }
  268. output.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& output) const
  272. {
  273. auto& match = output.capture_group_matches.at(input.match_index).at(id());
  274. auto start_position = match.left_column;
  275. auto length = state.string_position - start_position;
  276. if (start_position < match.column)
  277. return ExecutionResult::Continue;
  278. VERIFY(start_position + length <= input.view.length());
  279. auto view = input.view.substring_view(start_position, length);
  280. if (input.regex_options & AllFlags::StringCopyMatches) {
  281. match = { view.to_string(), input.line, start_position, input.global_offset + start_position }; // create a copy of the original string
  282. } else {
  283. match = { view, input.line, start_position, input.global_offset + start_position }; // take view to original string
  284. }
  285. return ExecutionResult::Continue;
  286. }
  287. ALWAYS_INLINE ExecutionResult OpCode_SaveLeftNamedCaptureGroup::execute(const MatchInput& input, MatchState& state, MatchOutput& output) const
  288. {
  289. if (input.match_index >= output.named_capture_group_matches.size()) {
  290. output.named_capture_group_matches.ensure_capacity(input.match_index);
  291. auto capacity = output.named_capture_group_matches.capacity();
  292. for (size_t i = output.named_capture_group_matches.size(); i <= capacity; ++i)
  293. output.named_capture_group_matches.empend();
  294. }
  295. output.named_capture_group_matches.at(input.match_index).ensure(name()).column = state.string_position;
  296. return ExecutionResult::Continue;
  297. }
  298. ALWAYS_INLINE ExecutionResult OpCode_SaveRightNamedCaptureGroup::execute(const MatchInput& input, MatchState& state, MatchOutput& output) const
  299. {
  300. StringView capture_group_name = name();
  301. if (output.named_capture_group_matches.at(input.match_index).contains(capture_group_name)) {
  302. auto start_position = output.named_capture_group_matches.at(input.match_index).ensure(capture_group_name).column;
  303. auto length = state.string_position - start_position;
  304. auto& map = output.named_capture_group_matches.at(input.match_index);
  305. if constexpr (REGEX_DEBUG) {
  306. VERIFY(start_position + length <= input.view.length());
  307. dbgln("Save named capture group with name={} and content='{}'", capture_group_name, input.view.substring_view(start_position, length));
  308. }
  309. VERIFY(start_position + length <= input.view.length());
  310. auto view = input.view.substring_view(start_position, length);
  311. if (input.regex_options & AllFlags::StringCopyMatches) {
  312. map.set(capture_group_name, { view.to_string(), input.line, start_position, input.global_offset + start_position }); // create a copy of the original string
  313. } else {
  314. map.set(capture_group_name, { view, input.line, start_position, input.global_offset + start_position }); // take view to original string
  315. }
  316. } else {
  317. warnln("Didn't find corresponding capture group match for name={}, match_index={}", capture_group_name.to_string(), input.match_index);
  318. }
  319. return ExecutionResult::Continue;
  320. }
  321. ALWAYS_INLINE ExecutionResult OpCode_Compare::execute(const MatchInput& input, MatchState& state, MatchOutput& output) const
  322. {
  323. bool inverse { false };
  324. bool temporary_inverse { false };
  325. bool reset_temp_inverse { false };
  326. auto current_inversion_state = [&]() -> bool { return temporary_inverse ^ inverse; };
  327. size_t string_position = state.string_position;
  328. bool inverse_matched { false };
  329. bool had_zero_length_match { false };
  330. state.string_position_before_match = state.string_position;
  331. size_t offset { state.instruction_position + 3 };
  332. for (size_t i = 0; i < arguments_count(); ++i) {
  333. if (state.string_position > string_position)
  334. break;
  335. if (reset_temp_inverse) {
  336. reset_temp_inverse = false;
  337. temporary_inverse = false;
  338. } else {
  339. reset_temp_inverse = true;
  340. }
  341. auto compare_type = (CharacterCompareType)m_bytecode->at(offset++);
  342. if (compare_type == CharacterCompareType::Inverse)
  343. inverse = true;
  344. else if (compare_type == CharacterCompareType::TemporaryInverse) {
  345. // If "TemporaryInverse" is given, negate the current inversion state only for the next opcode.
  346. // it follows that this cannot be the last compare element.
  347. VERIFY(i != arguments_count() - 1);
  348. temporary_inverse = true;
  349. reset_temp_inverse = false;
  350. } else if (compare_type == CharacterCompareType::Char) {
  351. u32 ch = m_bytecode->at(offset++);
  352. // We want to compare a string that is longer or equal in length to the available string
  353. if (input.view.length() - state.string_position < 1)
  354. return ExecutionResult::Failed_ExecuteLowPrioForks;
  355. compare_char(input, state, ch, current_inversion_state(), inverse_matched);
  356. } else if (compare_type == CharacterCompareType::AnyChar) {
  357. // We want to compare a string that is definitely longer than the available string
  358. if (input.view.length() - state.string_position < 1)
  359. return ExecutionResult::Failed_ExecuteLowPrioForks;
  360. VERIFY(!current_inversion_state());
  361. ++state.string_position;
  362. } else if (compare_type == CharacterCompareType::String) {
  363. VERIFY(!current_inversion_state());
  364. const auto& length = m_bytecode->at(offset++);
  365. StringBuilder str_builder;
  366. for (size_t i = 0; i < length; ++i)
  367. str_builder.append(m_bytecode->at(offset++));
  368. // We want to compare a string that is definitely longer than the available string
  369. if (input.view.length() - state.string_position < length)
  370. return ExecutionResult::Failed_ExecuteLowPrioForks;
  371. if (!compare_string(input, state, str_builder.string_view().characters_without_null_termination(), length, had_zero_length_match))
  372. return ExecutionResult::Failed_ExecuteLowPrioForks;
  373. } else if (compare_type == CharacterCompareType::CharClass) {
  374. if (input.view.length() - state.string_position < 1)
  375. return ExecutionResult::Failed_ExecuteLowPrioForks;
  376. auto character_class = (CharClass)m_bytecode->at(offset++);
  377. auto ch = input.view[state.string_position];
  378. compare_character_class(input, state, character_class, ch, current_inversion_state(), inverse_matched);
  379. } else if (compare_type == CharacterCompareType::CharRange) {
  380. auto value = (CharRange)m_bytecode->at(offset++);
  381. auto from = value.from;
  382. auto to = value.to;
  383. auto ch = input.view[state.string_position];
  384. compare_character_range(input, state, from, to, ch, current_inversion_state(), inverse_matched);
  385. } else if (compare_type == CharacterCompareType::Reference) {
  386. auto reference_number = (size_t)m_bytecode->at(offset++);
  387. auto& groups = output.capture_group_matches.at(input.match_index);
  388. if (groups.size() <= reference_number)
  389. return ExecutionResult::Failed_ExecuteLowPrioForks;
  390. auto str = groups.at(reference_number).view;
  391. // We want to compare a string that is definitely longer than the available string
  392. if (input.view.length() - state.string_position < str.length())
  393. return ExecutionResult::Failed_ExecuteLowPrioForks;
  394. if (!compare_string(input, state, str.characters_without_null_termination(), str.length(), had_zero_length_match))
  395. return ExecutionResult::Failed_ExecuteLowPrioForks;
  396. } else if (compare_type == CharacterCompareType::NamedReference) {
  397. auto ptr = (const char*)m_bytecode->at(offset++);
  398. auto length = (size_t)m_bytecode->at(offset++);
  399. StringView name { ptr, length };
  400. auto group = output.named_capture_group_matches.at(input.match_index).get(name);
  401. if (!group.has_value())
  402. return ExecutionResult::Failed_ExecuteLowPrioForks;
  403. auto str = group.value().view;
  404. // We want to compare a string that is definitely longer than the available string
  405. if (input.view.length() - state.string_position < str.length())
  406. return ExecutionResult::Failed_ExecuteLowPrioForks;
  407. if (!compare_string(input, state, str.characters_without_null_termination(), str.length(), had_zero_length_match))
  408. return ExecutionResult::Failed_ExecuteLowPrioForks;
  409. } else {
  410. warnln("Undefined comparison: {}", (int)compare_type);
  411. VERIFY_NOT_REACHED();
  412. break;
  413. }
  414. }
  415. if (current_inversion_state() && !inverse_matched)
  416. ++state.string_position;
  417. if ((!had_zero_length_match && string_position == state.string_position) || state.string_position > input.view.length())
  418. return ExecutionResult::Failed_ExecuteLowPrioForks;
  419. return ExecutionResult::Continue;
  420. }
  421. ALWAYS_INLINE void OpCode_Compare::compare_char(const MatchInput& input, MatchState& state, u32 ch1, bool inverse, bool& inverse_matched)
  422. {
  423. u32 ch2 = input.view[state.string_position];
  424. if (input.regex_options & AllFlags::Insensitive) {
  425. ch1 = to_ascii_lowercase(ch1);
  426. ch2 = to_ascii_lowercase(ch2);
  427. }
  428. if (ch1 == ch2) {
  429. if (inverse)
  430. inverse_matched = true;
  431. else
  432. ++state.string_position;
  433. }
  434. }
  435. ALWAYS_INLINE bool OpCode_Compare::compare_string(const MatchInput& input, MatchState& state, const char* str, size_t length, bool& had_zero_length_match)
  436. {
  437. if (length == 0) {
  438. had_zero_length_match = true;
  439. return true;
  440. }
  441. if (input.view.is_u8_view()) {
  442. auto str_view1 = StringView(str, length);
  443. auto str_view2 = StringView(&input.view.u8view()[state.string_position], length);
  444. bool string_equals;
  445. if (input.regex_options & AllFlags::Insensitive)
  446. string_equals = str_view1.equals_ignoring_case(str_view2);
  447. else
  448. string_equals = str_view1 == str_view2;
  449. if (string_equals) {
  450. state.string_position += length;
  451. return true;
  452. }
  453. } else {
  454. bool equals;
  455. if (input.regex_options & AllFlags::Insensitive)
  456. TODO();
  457. else
  458. equals = __builtin_memcmp(str, &input.view.u32view().code_points()[state.string_position], length) == 0;
  459. if (equals) {
  460. state.string_position += length;
  461. return true;
  462. }
  463. }
  464. return false;
  465. }
  466. ALWAYS_INLINE void OpCode_Compare::compare_character_class(const MatchInput& input, MatchState& state, CharClass character_class, u32 ch, bool inverse, bool& inverse_matched)
  467. {
  468. switch (character_class) {
  469. case CharClass::Alnum:
  470. if (is_ascii_alphanumeric(ch)) {
  471. if (inverse)
  472. inverse_matched = true;
  473. else
  474. ++state.string_position;
  475. }
  476. break;
  477. case CharClass::Alpha:
  478. if (is_ascii_alpha(ch))
  479. ++state.string_position;
  480. break;
  481. case CharClass::Blank:
  482. if (is_ascii_blank(ch)) {
  483. if (inverse)
  484. inverse_matched = true;
  485. else
  486. ++state.string_position;
  487. }
  488. break;
  489. case CharClass::Cntrl:
  490. if (is_ascii_control(ch)) {
  491. if (inverse)
  492. inverse_matched = true;
  493. else
  494. ++state.string_position;
  495. }
  496. break;
  497. case CharClass::Digit:
  498. if (is_ascii_digit(ch)) {
  499. if (inverse)
  500. inverse_matched = true;
  501. else
  502. ++state.string_position;
  503. }
  504. break;
  505. case CharClass::Graph:
  506. if (is_ascii_graphical(ch)) {
  507. if (inverse)
  508. inverse_matched = true;
  509. else
  510. ++state.string_position;
  511. }
  512. break;
  513. case CharClass::Lower:
  514. if (is_ascii_lower_alpha(ch) || ((input.regex_options & AllFlags::Insensitive) && is_ascii_upper_alpha(ch))) {
  515. if (inverse)
  516. inverse_matched = true;
  517. else
  518. ++state.string_position;
  519. }
  520. break;
  521. case CharClass::Print:
  522. if (is_ascii_printable(ch)) {
  523. if (inverse)
  524. inverse_matched = true;
  525. else
  526. ++state.string_position;
  527. }
  528. break;
  529. case CharClass::Punct:
  530. if (is_ascii_punctuation(ch)) {
  531. if (inverse)
  532. inverse_matched = true;
  533. else
  534. ++state.string_position;
  535. }
  536. break;
  537. case CharClass::Space:
  538. if (is_ascii_space(ch)) {
  539. if (inverse)
  540. inverse_matched = true;
  541. else
  542. ++state.string_position;
  543. }
  544. break;
  545. case CharClass::Upper:
  546. if (is_ascii_upper_alpha(ch) || ((input.regex_options & AllFlags::Insensitive) && is_ascii_lower_alpha(ch))) {
  547. if (inverse)
  548. inverse_matched = true;
  549. else
  550. ++state.string_position;
  551. }
  552. break;
  553. case CharClass::Word:
  554. if (is_ascii_alphanumeric(ch) || ch == '_') {
  555. if (inverse)
  556. inverse_matched = true;
  557. else
  558. ++state.string_position;
  559. }
  560. break;
  561. case CharClass::Xdigit:
  562. if (is_ascii_hex_digit(ch)) {
  563. if (inverse)
  564. inverse_matched = true;
  565. else
  566. ++state.string_position;
  567. }
  568. break;
  569. }
  570. }
  571. ALWAYS_INLINE void OpCode_Compare::compare_character_range(const MatchInput& input, MatchState& state, u32 from, u32 to, u32 ch, bool inverse, bool& inverse_matched)
  572. {
  573. if (input.regex_options & AllFlags::Insensitive) {
  574. from = to_ascii_lowercase(from);
  575. to = to_ascii_lowercase(to);
  576. ch = to_ascii_lowercase(ch);
  577. }
  578. if (ch >= from && ch <= to) {
  579. if (inverse)
  580. inverse_matched = true;
  581. else
  582. ++state.string_position;
  583. }
  584. }
  585. const String OpCode_Compare::arguments_string() const
  586. {
  587. return String::formatted("argc={}, args={} ", arguments_count(), arguments_size());
  588. }
  589. const Vector<String> OpCode_Compare::variable_arguments_to_string(Optional<MatchInput> input) const
  590. {
  591. Vector<String> result;
  592. size_t offset { state().instruction_position + 3 };
  593. RegexStringView view = ((input.has_value()) ? input.value().view : nullptr);
  594. for (size_t i = 0; i < arguments_count(); ++i) {
  595. auto compare_type = (CharacterCompareType)m_bytecode->at(offset++);
  596. result.empend(String::formatted("type={} [{}]", (size_t)compare_type, character_compare_type_name(compare_type)));
  597. auto string_start_offset = state().string_position_before_match;
  598. if (compare_type == CharacterCompareType::Char) {
  599. auto ch = m_bytecode->at(offset++);
  600. auto is_ascii = is_ascii_printable(ch);
  601. if (is_ascii)
  602. result.empend(String::formatted("value='{:c}'", static_cast<char>(ch)));
  603. else
  604. result.empend(String::formatted("value={:x}", ch));
  605. if (!view.is_null() && view.length() > string_start_offset) {
  606. if (is_ascii) {
  607. result.empend(String::formatted(
  608. "compare against: '{}'",
  609. view.substring_view(string_start_offset, string_start_offset > view.length() ? 0 : 1).to_string()));
  610. } else {
  611. auto str = view.substring_view(string_start_offset, string_start_offset > view.length() ? 0 : 1).to_string();
  612. u8 buf[8] { 0 };
  613. __builtin_memcpy(buf, str.characters(), min(str.length(), sizeof(buf)));
  614. result.empend(String::formatted("compare against: {:x},{:x},{:x},{:x},{:x},{:x},{:x},{:x}",
  615. buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]));
  616. }
  617. }
  618. } else if (compare_type == CharacterCompareType::NamedReference) {
  619. auto ptr = (const char*)m_bytecode->at(offset++);
  620. auto length = m_bytecode->at(offset++);
  621. result.empend(String::formatted("name='{}'", StringView { ptr, (size_t)length }));
  622. } else if (compare_type == CharacterCompareType::Reference) {
  623. auto ref = m_bytecode->at(offset++);
  624. result.empend(String::formatted("number={}", ref));
  625. } else if (compare_type == CharacterCompareType::String) {
  626. auto& length = m_bytecode->at(offset++);
  627. StringBuilder str_builder;
  628. for (size_t i = 0; i < length; ++i)
  629. str_builder.append(m_bytecode->at(offset++));
  630. result.empend(String::formatted("value=\"{}\"", str_builder.string_view().substring_view(0, length)));
  631. if (!view.is_null() && view.length() > state().string_position)
  632. result.empend(String::formatted(
  633. "compare against: \"{}\"",
  634. input.value().view.substring_view(string_start_offset, string_start_offset + length > view.length() ? 0 : length).to_string()));
  635. } else if (compare_type == CharacterCompareType::CharClass) {
  636. auto character_class = (CharClass)m_bytecode->at(offset++);
  637. result.empend(String::formatted("ch_class={} [{}]", (size_t)character_class, character_class_name(character_class)));
  638. if (!view.is_null() && view.length() > state().string_position)
  639. result.empend(String::formatted(
  640. "compare against: '{}'",
  641. input.value().view.substring_view(string_start_offset, state().string_position > view.length() ? 0 : 1).to_string()));
  642. } else if (compare_type == CharacterCompareType::CharRange) {
  643. auto value = (CharRange)m_bytecode->at(offset++);
  644. result.empend(String::formatted("ch_range='{:c}'-'{:c}'", value.from, value.to));
  645. if (!view.is_null() && view.length() > state().string_position)
  646. result.empend(String::formatted(
  647. "compare against: '{}'",
  648. input.value().view.substring_view(string_start_offset, state().string_position > view.length() ? 0 : 1).to_string()));
  649. }
  650. }
  651. return result;
  652. }
  653. }