RegexByteCode.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. /*
  2. * Copyright (c) 2020, Emanuel Sprung <emanuel.sprung@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "RegexByteCode.h"
  27. #include "AK/StringBuilder.h"
  28. #include "RegexDebug.h"
  29. #include <ctype.h>
  30. namespace regex {
  31. const char* OpCode::name(OpCodeId opcode_id)
  32. {
  33. switch (opcode_id) {
  34. #define __ENUMERATE_OPCODE(x) \
  35. case OpCodeId::x: \
  36. return #x;
  37. ENUMERATE_OPCODES
  38. #undef __ENUMERATE_OPCODE
  39. default:
  40. ASSERT_NOT_REACHED();
  41. return "<Unknown>";
  42. }
  43. }
  44. const char* OpCode::name() const
  45. {
  46. return name(opcode_id());
  47. }
  48. const char* execution_result_name(ExecutionResult result)
  49. {
  50. switch (result) {
  51. #define __ENUMERATE_EXECUTION_RESULT(x) \
  52. case ExecutionResult::x: \
  53. return #x;
  54. ENUMERATE_EXECUTION_RESULTS
  55. #undef __ENUMERATE_EXECUTION_RESULT
  56. default:
  57. ASSERT_NOT_REACHED();
  58. return "<Unknown>";
  59. }
  60. }
  61. const char* boundary_check_type_name(BoundaryCheckType ty)
  62. {
  63. switch (ty) {
  64. #define __ENUMERATE_BOUNDARY_CHECK_TYPE(x) \
  65. case BoundaryCheckType::x: \
  66. return #x;
  67. ENUMERATE_BOUNDARY_CHECK_TYPES
  68. #undef __ENUMERATE_BOUNDARY_CHECK_TYPE
  69. default:
  70. ASSERT_NOT_REACHED();
  71. return "<Unknown>";
  72. }
  73. }
  74. const char* character_compare_type_name(CharacterCompareType ch_compare_type)
  75. {
  76. switch (ch_compare_type) {
  77. #define __ENUMERATE_CHARACTER_COMPARE_TYPE(x) \
  78. case CharacterCompareType::x: \
  79. return #x;
  80. ENUMERATE_CHARACTER_COMPARE_TYPES
  81. #undef __ENUMERATE_CHARACTER_COMPARE_TYPE
  82. default:
  83. ASSERT_NOT_REACHED();
  84. return "<Unknown>";
  85. }
  86. }
  87. static const char* character_class_name(CharClass ch_class)
  88. {
  89. switch (ch_class) {
  90. #define __ENUMERATE_CHARACTER_CLASS(x) \
  91. case CharClass::x: \
  92. return #x;
  93. ENUMERATE_CHARACTER_CLASSES
  94. #undef __ENUMERATE_CHARACTER_CLASS
  95. default:
  96. ASSERT_NOT_REACHED();
  97. return "<Unknown>";
  98. }
  99. }
  100. HashMap<u32, OwnPtr<OpCode>> ByteCode::s_opcodes {};
  101. ALWAYS_INLINE OpCode* ByteCode::get_opcode_by_id(OpCodeId id) const
  102. {
  103. if (!s_opcodes.size()) {
  104. for (u32 i = (u32)OpCodeId::First; i <= (u32)OpCodeId::Last; ++i) {
  105. switch ((OpCodeId)i) {
  106. case OpCodeId::Exit:
  107. s_opcodes.set(i, make<OpCode_Exit>(*const_cast<ByteCode*>(this)));
  108. break;
  109. case OpCodeId::Jump:
  110. s_opcodes.set(i, make<OpCode_Jump>(*const_cast<ByteCode*>(this)));
  111. break;
  112. case OpCodeId::Compare:
  113. s_opcodes.set(i, make<OpCode_Compare>(*const_cast<ByteCode*>(this)));
  114. break;
  115. case OpCodeId::CheckEnd:
  116. s_opcodes.set(i, make<OpCode_CheckEnd>(*const_cast<ByteCode*>(this)));
  117. break;
  118. case OpCodeId::CheckBoundary:
  119. s_opcodes.set(i, make<OpCode_CheckBoundary>(*const_cast<ByteCode*>(this)));
  120. break;
  121. case OpCodeId::ForkJump:
  122. s_opcodes.set(i, make<OpCode_ForkJump>(*const_cast<ByteCode*>(this)));
  123. break;
  124. case OpCodeId::ForkStay:
  125. s_opcodes.set(i, make<OpCode_ForkStay>(*const_cast<ByteCode*>(this)));
  126. break;
  127. case OpCodeId::FailForks:
  128. s_opcodes.set(i, make<OpCode_FailForks>(*const_cast<ByteCode*>(this)));
  129. break;
  130. case OpCodeId::Save:
  131. s_opcodes.set(i, make<OpCode_Save>(*const_cast<ByteCode*>(this)));
  132. break;
  133. case OpCodeId::Restore:
  134. s_opcodes.set(i, make<OpCode_Restore>(*const_cast<ByteCode*>(this)));
  135. break;
  136. case OpCodeId::GoBack:
  137. s_opcodes.set(i, make<OpCode_GoBack>(*const_cast<ByteCode*>(this)));
  138. break;
  139. case OpCodeId::CheckBegin:
  140. s_opcodes.set(i, make<OpCode_CheckBegin>(*const_cast<ByteCode*>(this)));
  141. break;
  142. case OpCodeId::SaveLeftCaptureGroup:
  143. s_opcodes.set(i, make<OpCode_SaveLeftCaptureGroup>(*const_cast<ByteCode*>(this)));
  144. break;
  145. case OpCodeId::SaveRightCaptureGroup:
  146. s_opcodes.set(i, make<OpCode_SaveRightCaptureGroup>(*const_cast<ByteCode*>(this)));
  147. break;
  148. case OpCodeId::SaveLeftNamedCaptureGroup:
  149. s_opcodes.set(i, make<OpCode_SaveLeftNamedCaptureGroup>(*const_cast<ByteCode*>(this)));
  150. break;
  151. case OpCodeId::SaveRightNamedCaptureGroup:
  152. s_opcodes.set(i, make<OpCode_SaveRightNamedCaptureGroup>(*const_cast<ByteCode*>(this)));
  153. break;
  154. }
  155. }
  156. }
  157. if (id > OpCodeId::Last)
  158. return nullptr;
  159. return const_cast<OpCode*>(s_opcodes.get((u32)id).value())->set_bytecode(*const_cast<ByteCode*>(this));
  160. }
  161. OpCode* ByteCode::get_opcode(MatchState& state) const
  162. {
  163. OpCode* op_code;
  164. if (state.instruction_position >= size()) {
  165. op_code = get_opcode_by_id(OpCodeId::Exit);
  166. } else
  167. op_code = get_opcode_by_id((OpCodeId)at(state.instruction_position));
  168. if (op_code)
  169. op_code->set_state(state);
  170. return op_code;
  171. }
  172. ALWAYS_INLINE ExecutionResult OpCode_Exit::execute(const MatchInput& input, MatchState& state, MatchOutput&) const
  173. {
  174. if (state.string_position > input.view.length() || state.instruction_position >= m_bytecode->size())
  175. return ExecutionResult::Succeeded;
  176. return ExecutionResult::Failed;
  177. }
  178. ALWAYS_INLINE ExecutionResult OpCode_Save::execute(const MatchInput& input, MatchState& state, MatchOutput&) const
  179. {
  180. input.saved_positions.append(state.string_position);
  181. return ExecutionResult::Continue;
  182. }
  183. ALWAYS_INLINE ExecutionResult OpCode_Restore::execute(const MatchInput& input, MatchState& state, MatchOutput&) const
  184. {
  185. if (input.saved_positions.is_empty())
  186. return ExecutionResult::Failed;
  187. state.string_position = input.saved_positions.take_last();
  188. return ExecutionResult::Continue;
  189. }
  190. ALWAYS_INLINE ExecutionResult OpCode_GoBack::execute(const MatchInput&, MatchState& state, MatchOutput&) const
  191. {
  192. if (count() > state.string_position)
  193. return ExecutionResult::Failed_ExecuteLowPrioForks;
  194. state.string_position -= count();
  195. return ExecutionResult::Continue;
  196. }
  197. ALWAYS_INLINE ExecutionResult OpCode_FailForks::execute(const MatchInput& input, MatchState&, MatchOutput&) const
  198. {
  199. ASSERT(count() > 0);
  200. input.fail_counter += count() - 1;
  201. return ExecutionResult::Failed_ExecuteLowPrioForks;
  202. }
  203. ALWAYS_INLINE ExecutionResult OpCode_Jump::execute(const MatchInput&, MatchState& state, MatchOutput&) const
  204. {
  205. state.instruction_position += offset();
  206. return ExecutionResult::Continue;
  207. }
  208. ALWAYS_INLINE ExecutionResult OpCode_ForkJump::execute(const MatchInput&, MatchState& state, MatchOutput&) const
  209. {
  210. state.fork_at_position = state.instruction_position + size() + offset();
  211. return ExecutionResult::Fork_PrioHigh;
  212. }
  213. ALWAYS_INLINE ExecutionResult OpCode_ForkStay::execute(const MatchInput&, MatchState& state, MatchOutput&) const
  214. {
  215. state.fork_at_position = state.instruction_position + size() + offset();
  216. return ExecutionResult::Fork_PrioLow;
  217. }
  218. ALWAYS_INLINE ExecutionResult OpCode_CheckBegin::execute(const MatchInput& input, MatchState& state, MatchOutput&) const
  219. {
  220. if (0 == state.string_position && (input.regex_options & AllFlags::MatchNotBeginOfLine))
  221. return ExecutionResult::Failed_ExecuteLowPrioForks;
  222. if ((0 == state.string_position && !(input.regex_options & AllFlags::MatchNotBeginOfLine))
  223. || (0 != state.string_position && (input.regex_options & AllFlags::MatchNotBeginOfLine))
  224. || (0 == state.string_position && (input.regex_options & AllFlags::Global)))
  225. return ExecutionResult::Continue;
  226. return ExecutionResult::Failed_ExecuteLowPrioForks;
  227. }
  228. ALWAYS_INLINE ExecutionResult OpCode_CheckBoundary::execute(const MatchInput& input, MatchState& state, MatchOutput&) const
  229. {
  230. auto isword = [](auto ch) { return isalnum(ch) || ch == '_'; };
  231. auto is_word_boundary = [&] {
  232. if (state.string_position == input.view.length()) {
  233. if (state.string_position > 0 && isword(input.view[state.string_position - 1]))
  234. return true;
  235. return false;
  236. }
  237. if (state.string_position == 0) {
  238. if (isword(input.view[0]))
  239. return true;
  240. return false;
  241. }
  242. return !!(isword(input.view[state.string_position]) ^ isword(input.view[state.string_position - 1]));
  243. };
  244. switch (type()) {
  245. case BoundaryCheckType::Word: {
  246. if (is_word_boundary())
  247. return ExecutionResult::Continue;
  248. return ExecutionResult::Failed_ExecuteLowPrioForks;
  249. }
  250. case BoundaryCheckType::NonWord: {
  251. if (!is_word_boundary())
  252. return ExecutionResult::Continue;
  253. return ExecutionResult::Failed_ExecuteLowPrioForks;
  254. }
  255. }
  256. ASSERT_NOT_REACHED();
  257. }
  258. ALWAYS_INLINE ExecutionResult OpCode_CheckEnd::execute(const MatchInput& input, MatchState& state, MatchOutput&) const
  259. {
  260. if (state.string_position == input.view.length() && (input.regex_options & AllFlags::MatchNotEndOfLine))
  261. return ExecutionResult::Failed_ExecuteLowPrioForks;
  262. if ((state.string_position == input.view.length() && !(input.regex_options & AllFlags::MatchNotEndOfLine))
  263. || (state.string_position != input.view.length() && (input.regex_options & AllFlags::MatchNotEndOfLine || input.regex_options & AllFlags::MatchNotBeginOfLine)))
  264. return ExecutionResult::Continue;
  265. return ExecutionResult::Failed_ExecuteLowPrioForks;
  266. }
  267. ALWAYS_INLINE ExecutionResult OpCode_SaveLeftCaptureGroup::execute(const MatchInput& input, MatchState& state, MatchOutput& output) const
  268. {
  269. if (input.match_index >= output.capture_group_matches.size()) {
  270. output.capture_group_matches.ensure_capacity(input.match_index);
  271. auto capacity = output.capture_group_matches.capacity();
  272. for (size_t i = output.capture_group_matches.size(); i <= capacity; ++i)
  273. output.capture_group_matches.empend();
  274. }
  275. if (id() >= output.capture_group_matches.at(input.match_index).size()) {
  276. output.capture_group_matches.at(input.match_index).ensure_capacity(id());
  277. auto capacity = output.capture_group_matches.at(input.match_index).capacity();
  278. for (size_t i = output.capture_group_matches.at(input.match_index).size(); i <= capacity; ++i)
  279. output.capture_group_matches.at(input.match_index).empend();
  280. }
  281. output.capture_group_matches.at(input.match_index).at(id()).left_column = state.string_position;
  282. return ExecutionResult::Continue;
  283. }
  284. ALWAYS_INLINE ExecutionResult OpCode_SaveRightCaptureGroup::execute(const MatchInput& input, MatchState& state, MatchOutput& output) const
  285. {
  286. auto& match = output.capture_group_matches.at(input.match_index).at(id());
  287. auto start_position = match.left_column;
  288. auto length = state.string_position - start_position;
  289. if (start_position < match.column)
  290. return ExecutionResult::Continue;
  291. ASSERT(start_position + length <= input.view.length());
  292. auto view = input.view.substring_view(start_position, length);
  293. if (input.regex_options & AllFlags::StringCopyMatches) {
  294. match = { view.to_string(), input.line, start_position, input.global_offset + start_position }; // create a copy of the original string
  295. } else {
  296. match = { view, input.line, start_position, input.global_offset + start_position }; // take view to original string
  297. }
  298. return ExecutionResult::Continue;
  299. }
  300. ALWAYS_INLINE ExecutionResult OpCode_SaveLeftNamedCaptureGroup::execute(const MatchInput& input, MatchState& state, MatchOutput& output) const
  301. {
  302. if (input.match_index >= output.named_capture_group_matches.size()) {
  303. output.named_capture_group_matches.ensure_capacity(input.match_index);
  304. auto capacity = output.named_capture_group_matches.capacity();
  305. for (size_t i = output.named_capture_group_matches.size(); i <= capacity; ++i)
  306. output.named_capture_group_matches.empend();
  307. }
  308. output.named_capture_group_matches.at(input.match_index).ensure(name()).column = state.string_position;
  309. return ExecutionResult::Continue;
  310. }
  311. ALWAYS_INLINE ExecutionResult OpCode_SaveRightNamedCaptureGroup::execute(const MatchInput& input, MatchState& state, MatchOutput& output) const
  312. {
  313. StringView capture_group_name = name();
  314. if (output.named_capture_group_matches.at(input.match_index).contains(capture_group_name)) {
  315. auto start_position = output.named_capture_group_matches.at(input.match_index).ensure(capture_group_name).column;
  316. auto length = state.string_position - start_position;
  317. auto& map = output.named_capture_group_matches.at(input.match_index);
  318. #ifdef REGEX_DEBUG
  319. ASSERT(start_position + length <= input.view.length());
  320. dbg() << "Save named capture group with name=" << capture_group_name << " and content: " << input.view.substring_view(start_position, length).to_string();
  321. #endif
  322. ASSERT(start_position + length <= input.view.length());
  323. auto view = input.view.substring_view(start_position, length);
  324. if (input.regex_options & AllFlags::StringCopyMatches) {
  325. map.set(capture_group_name, { view.to_string(), input.line, start_position, input.global_offset + start_position }); // create a copy of the original string
  326. } else {
  327. map.set(capture_group_name, { view, input.line, start_position, input.global_offset + start_position }); // take view to original string
  328. }
  329. } else {
  330. fprintf(stderr, "Didn't find corresponding capture group match for name=%s, match_index=%lu\n", capture_group_name.to_string().characters(), input.match_index);
  331. }
  332. return ExecutionResult::Continue;
  333. }
  334. ALWAYS_INLINE ExecutionResult OpCode_Compare::execute(const MatchInput& input, MatchState& state, MatchOutput& output) const
  335. {
  336. bool inverse { false };
  337. bool temporary_inverse { false };
  338. bool reset_temp_inverse { false };
  339. auto current_inversion_state = [&]() -> bool { return temporary_inverse ^ inverse; };
  340. size_t string_position = state.string_position;
  341. bool inverse_matched { false };
  342. size_t offset { state.instruction_position + 3 };
  343. for (size_t i = 0; i < arguments_count(); ++i) {
  344. if (state.string_position > string_position)
  345. break;
  346. if (reset_temp_inverse) {
  347. reset_temp_inverse = false;
  348. temporary_inverse = false;
  349. } else {
  350. reset_temp_inverse = true;
  351. }
  352. auto compare_type = (CharacterCompareType)m_bytecode->at(offset++);
  353. if (compare_type == CharacterCompareType::Inverse)
  354. inverse = true;
  355. else if (compare_type == CharacterCompareType::TemporaryInverse) {
  356. // If "TemporaryInverse" is given, negate the current inversion state only for the next opcode.
  357. // it follows that this cannot be the last compare element.
  358. ASSERT(i != arguments_count() - 1);
  359. temporary_inverse = true;
  360. reset_temp_inverse = false;
  361. } else if (compare_type == CharacterCompareType::Char) {
  362. u32 ch = m_bytecode->at(offset++);
  363. // We want to compare a string that is longer or equal in length to the available string
  364. if (input.view.length() - state.string_position < 1)
  365. return ExecutionResult::Failed_ExecuteLowPrioForks;
  366. compare_char(input, state, ch, current_inversion_state(), inverse_matched);
  367. } else if (compare_type == CharacterCompareType::AnyChar) {
  368. // We want to compare a string that is definitely longer than the available string
  369. if (input.view.length() - state.string_position < 1)
  370. return ExecutionResult::Failed_ExecuteLowPrioForks;
  371. ASSERT(!current_inversion_state());
  372. ++state.string_position;
  373. } else if (compare_type == CharacterCompareType::String) {
  374. ASSERT(!current_inversion_state());
  375. char* str = reinterpret_cast<char*>(m_bytecode->at(offset++));
  376. auto& length = m_bytecode->at(offset++);
  377. // We want to compare a string that is definitely longer than the available string
  378. if (input.view.length() - state.string_position < length)
  379. return ExecutionResult::Failed_ExecuteLowPrioForks;
  380. if (!compare_string(input, state, str, length))
  381. return ExecutionResult::Failed_ExecuteLowPrioForks;
  382. } else if (compare_type == CharacterCompareType::CharClass) {
  383. if (input.view.length() - state.string_position < 1)
  384. return ExecutionResult::Failed_ExecuteLowPrioForks;
  385. auto character_class = (CharClass)m_bytecode->at(offset++);
  386. auto ch = input.view[state.string_position];
  387. compare_character_class(input, state, character_class, ch, current_inversion_state(), inverse_matched);
  388. } else if (compare_type == CharacterCompareType::CharRange) {
  389. auto value = (CharRange)m_bytecode->at(offset++);
  390. auto from = value.from;
  391. auto to = value.to;
  392. auto ch = input.view[state.string_position];
  393. compare_character_range(input, state, from, to, ch, current_inversion_state(), inverse_matched);
  394. } else if (compare_type == CharacterCompareType::Reference) {
  395. auto reference_number = (size_t)m_bytecode->at(offset++);
  396. auto& groups = output.capture_group_matches.at(input.match_index);
  397. if (groups.size() <= reference_number)
  398. return ExecutionResult::Failed_ExecuteLowPrioForks;
  399. auto str = groups.at(reference_number).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()))
  404. return ExecutionResult::Failed_ExecuteLowPrioForks;
  405. } else if (compare_type == CharacterCompareType::NamedReference) {
  406. auto ptr = (const char*)m_bytecode->at(offset++);
  407. auto length = (size_t)m_bytecode->at(offset++);
  408. StringView name { ptr, length };
  409. auto group = output.named_capture_group_matches.at(input.match_index).get(name);
  410. if (!group.has_value())
  411. return ExecutionResult::Failed_ExecuteLowPrioForks;
  412. auto str = group.value().view;
  413. // We want to compare a string that is definitely longer than the available string
  414. if (input.view.length() - state.string_position < str.length())
  415. return ExecutionResult::Failed_ExecuteLowPrioForks;
  416. if (!compare_string(input, state, str.characters_without_null_termination(), str.length()))
  417. return ExecutionResult::Failed_ExecuteLowPrioForks;
  418. } else {
  419. fprintf(stderr, "Undefined comparison: %i\n", (int)compare_type);
  420. ASSERT_NOT_REACHED();
  421. break;
  422. }
  423. }
  424. if (current_inversion_state() && !inverse_matched)
  425. ++state.string_position;
  426. if (string_position == state.string_position || state.string_position > input.view.length())
  427. return ExecutionResult::Failed_ExecuteLowPrioForks;
  428. return ExecutionResult::Continue;
  429. }
  430. ALWAYS_INLINE void OpCode_Compare::compare_char(const MatchInput& input, MatchState& state, u32 ch1, bool inverse, bool& inverse_matched)
  431. {
  432. u32 ch2 = input.view[state.string_position];
  433. if (input.regex_options & AllFlags::Insensitive) {
  434. ch1 = tolower(ch1);
  435. ch2 = tolower(ch2);
  436. }
  437. if (ch1 == ch2) {
  438. if (inverse)
  439. inverse_matched = true;
  440. else
  441. ++state.string_position;
  442. }
  443. }
  444. ALWAYS_INLINE bool OpCode_Compare::compare_string(const MatchInput& input, MatchState& state, const char* str, size_t length)
  445. {
  446. if (input.view.is_u8_view()) {
  447. auto str_view1 = StringView(str, length);
  448. auto str_view2 = StringView(&input.view.u8view()[state.string_position], length);
  449. String str1, str2;
  450. if (input.regex_options & AllFlags::Insensitive) {
  451. str1 = str_view1.to_string().to_lowercase();
  452. str2 = str_view2.to_string().to_lowercase();
  453. str_view1 = str1.view();
  454. str_view2 = str2.view();
  455. }
  456. if (str_view1 == str_view2) {
  457. state.string_position += length;
  458. return true;
  459. }
  460. }
  461. return false;
  462. }
  463. ALWAYS_INLINE void OpCode_Compare::compare_character_class(const MatchInput& input, MatchState& state, CharClass character_class, u32 ch, bool inverse, bool& inverse_matched)
  464. {
  465. switch (character_class) {
  466. case CharClass::Alnum:
  467. if (isalnum(ch)) {
  468. if (inverse)
  469. inverse_matched = true;
  470. else
  471. ++state.string_position;
  472. }
  473. break;
  474. case CharClass::Alpha:
  475. if (isalpha(ch))
  476. ++state.string_position;
  477. break;
  478. case CharClass::Blank:
  479. if (ch == ' ' || ch == '\t') {
  480. if (inverse)
  481. inverse_matched = true;
  482. else
  483. ++state.string_position;
  484. }
  485. break;
  486. case CharClass::Cntrl:
  487. if (iscntrl(ch)) {
  488. if (inverse)
  489. inverse_matched = true;
  490. else
  491. ++state.string_position;
  492. }
  493. break;
  494. case CharClass::Digit:
  495. if (isdigit(ch)) {
  496. if (inverse)
  497. inverse_matched = true;
  498. else
  499. ++state.string_position;
  500. }
  501. break;
  502. case CharClass::Graph:
  503. if (isgraph(ch)) {
  504. if (inverse)
  505. inverse_matched = true;
  506. else
  507. ++state.string_position;
  508. }
  509. break;
  510. case CharClass::Lower:
  511. if (islower(ch) || ((input.regex_options & AllFlags::Insensitive) && isupper(ch))) {
  512. if (inverse)
  513. inverse_matched = true;
  514. else
  515. ++state.string_position;
  516. }
  517. break;
  518. case CharClass::Print:
  519. if (isprint(ch)) {
  520. if (inverse)
  521. inverse_matched = true;
  522. else
  523. ++state.string_position;
  524. }
  525. break;
  526. case CharClass::Punct:
  527. if (ispunct(ch)) {
  528. if (inverse)
  529. inverse_matched = true;
  530. else
  531. ++state.string_position;
  532. }
  533. break;
  534. case CharClass::Space:
  535. if (isspace(ch)) {
  536. if (inverse)
  537. inverse_matched = true;
  538. else
  539. ++state.string_position;
  540. }
  541. break;
  542. case CharClass::Upper:
  543. if (isupper(ch) || ((input.regex_options & AllFlags::Insensitive) && islower(ch))) {
  544. if (inverse)
  545. inverse_matched = true;
  546. else
  547. ++state.string_position;
  548. }
  549. break;
  550. case CharClass::Word:
  551. if (isalnum(ch) || ch == '_') {
  552. if (inverse)
  553. inverse_matched = true;
  554. else
  555. ++state.string_position;
  556. }
  557. break;
  558. case CharClass::Xdigit:
  559. if (isxdigit(ch)) {
  560. if (inverse)
  561. inverse_matched = true;
  562. else
  563. ++state.string_position;
  564. }
  565. break;
  566. }
  567. }
  568. ALWAYS_INLINE void OpCode_Compare::compare_character_range(const MatchInput& input, MatchState& state, u32 from, u32 to, u32 ch, bool inverse, bool& inverse_matched)
  569. {
  570. if (input.regex_options & AllFlags::Insensitive) {
  571. from = tolower(from);
  572. to = tolower(to);
  573. ch = tolower(ch);
  574. }
  575. if (ch >= from && ch <= to) {
  576. if (inverse)
  577. inverse_matched = true;
  578. else
  579. ++state.string_position;
  580. }
  581. }
  582. const String OpCode_Compare::arguments_string() const
  583. {
  584. return String::format("argc=%lu, args=%lu ", arguments_count(), arguments_size());
  585. }
  586. const Vector<String> OpCode_Compare::variable_arguments_to_string(Optional<MatchInput> input) const
  587. {
  588. Vector<String> result;
  589. size_t offset { state().instruction_position + 3 };
  590. RegexStringView view = ((input.has_value()) ? input.value().view : nullptr);
  591. for (size_t i = 0; i < arguments_count(); ++i) {
  592. auto compare_type = (CharacterCompareType)m_bytecode->at(offset++);
  593. result.empend(String::format("type=%lu [%s]", (size_t)compare_type, character_compare_type_name(compare_type)));
  594. if (compare_type == CharacterCompareType::Char) {
  595. char ch = m_bytecode->at(offset++);
  596. result.empend(String::format("value='%c'", ch));
  597. if (!view.is_null())
  598. result.empend(String::format("compare against: '%s'", view.substring_view(state().string_position, state().string_position + 1 > view.length() ? 0 : 1).to_string().characters()));
  599. } else if (compare_type == CharacterCompareType::NamedReference) {
  600. auto ptr = (const char*)m_bytecode->at(offset++);
  601. auto length = m_bytecode->at(offset++);
  602. result.empend(String::format("name='%.*s'", length, ptr));
  603. } else if (compare_type == CharacterCompareType::Reference) {
  604. auto ref = m_bytecode->at(offset++);
  605. result.empend(String::format("number=%lu", ref));
  606. } else if (compare_type == CharacterCompareType::String) {
  607. char* str = reinterpret_cast<char*>(m_bytecode->at(offset++));
  608. auto& length = m_bytecode->at(offset++);
  609. result.empend(String::format("value=\"%.*s\"", length, str));
  610. if (!view.is_null())
  611. result.empend(String::format("compare against: \"%s\"", input.value().view.substring_view(state().string_position, state().string_position + length > view.length() ? 0 : length).to_string().characters()));
  612. } else if (compare_type == CharacterCompareType::CharClass) {
  613. auto character_class = (CharClass)m_bytecode->at(offset++);
  614. result.empend(String::format("ch_class=%lu [%s]", (size_t)character_class, character_class_name(character_class)));
  615. if (!view.is_null())
  616. result.empend(String::format("compare against: '%s'", input.value().view.substring_view(state().string_position, state().string_position + 1 > view.length() ? 0 : 1).to_string().characters()));
  617. } else if (compare_type == CharacterCompareType::CharRange) {
  618. auto value = (CharRange)m_bytecode->at(offset++);
  619. result.empend(String::format("ch_range='%c'-'%c'", value.from, value.to));
  620. if (!view.is_null())
  621. result.empend(String::format("compare against: '%s'", input.value().view.substring_view(state().string_position, state().string_position + 1 > view.length() ? 0 : 1).to_string().characters()));
  622. }
  623. }
  624. return result;
  625. }
  626. }