RegexByteCode.cpp 29 KB

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