| 102 | } |
| 103 | |
| 104 | static void test_regex() { |
| 105 | auto test_throws = [](const std::string & input, const std::string & regex, const std::string & expected_exception_pattern = "") { |
| 106 | common_chat_msg_parser builder(input, /* is_partial= */ false, {}); |
| 107 | assert_throws([&]() { builder.consume_regex(common_regex(regex)); }, expected_exception_pattern); |
| 108 | }; |
| 109 | |
| 110 | test_throws("Hello, world!", "abc", "^abc$"); |
| 111 | test_throws("Hello, world!", "e", "^e$"); |
| 112 | |
| 113 | { |
| 114 | common_chat_msg_parser builder("Hello, world!", /* is_partial= */ false, {}); |
| 115 | builder.consume_regex(common_regex("Hello")); |
| 116 | assert_equals(", world!", builder.consume_rest()); |
| 117 | } |
| 118 | |
| 119 | { |
| 120 | // When in non partial mode, we can say whether the regex was consumed or not. |
| 121 | common_chat_msg_parser builder("Hello,", /* is_partial= */ false, {}); |
| 122 | assert_equals(false, builder.try_consume_regex(common_regex("Hello, world!")).has_value()); |
| 123 | } |
| 124 | { |
| 125 | common_chat_msg_parser builder("Hello,", /* is_partial= */ false, {}); |
| 126 | auto res = builder.try_consume_regex(common_regex("H(el)l(?:o, world!)?")); |
| 127 | assert_equals(true, res.has_value()); |
| 128 | // Verify captures |
| 129 | assert_equals<size_t>(2, res->groups.size()); |
| 130 | assert_equals("Hell", builder.str(res->groups[0])); |
| 131 | assert_equals("el", builder.str(res->groups[1])); |
| 132 | // Verify position is after the match |
| 133 | assert_equals<size_t>(4, builder.pos()); |
| 134 | assert_equals("o,", builder.consume_rest()); |
| 135 | } |
| 136 | { |
| 137 | // But in partial mode, we have a partial final match / can't decide, so we throw a partial exception. |
| 138 | common_chat_msg_parser builder("Hello,", /* is_partial= */ true, {}); |
| 139 | assert_throws([&]() { |
| 140 | builder.try_consume_regex(common_regex("Hello, world!")); |
| 141 | }, "^Hello, world!$"); |
| 142 | } |
| 143 | |
| 144 | // Now regardless of the mode, we can tell these aren't a match. |
| 145 | for (const auto is_partial : {false, true}) { |
| 146 | common_chat_msg_parser builder("Hello,", is_partial, {}); |
| 147 | assert_equals(false, builder.try_consume_regex(common_regex("a(b|c)(d|e)f")).has_value()); |
| 148 | } |
| 149 | for (const auto is_partial : {false, true}) { |
| 150 | common_chat_msg_parser builder("Hello,", is_partial, {}); |
| 151 | assert_equals(false, builder.try_consume_literal("Oh")); |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | const std::vector<std::string> barely_healable_jsons = { |
| 156 | "{", |
no test coverage detected