| 163 | } |
| 164 | |
| 165 | static void test_regex() { |
| 166 | auto test_throws = [](const std::string & input, const std::string & regex, const std::string & expected_exception_pattern = "") { |
| 167 | common_chat_msg_parser builder(input, /* is_partial= */ false, {}); |
| 168 | assert_throws([&]() { builder.consume_regex(common_regex(regex)); }, expected_exception_pattern); |
| 169 | }; |
| 170 | |
| 171 | test_throws("Hello, world!", "abc", "^abc$"); |
| 172 | test_throws("Hello, world!", "e", "^e$"); |
| 173 | |
| 174 | { |
| 175 | common_chat_msg_parser builder("Hello, world!", /* is_partial= */ false, {}); |
| 176 | builder.consume_regex(common_regex("Hello")); |
| 177 | assert_equals(", world!", builder.consume_rest()); |
| 178 | } |
| 179 | |
| 180 | { |
| 181 | // When in non partial mode, we can say whether the regex was consumed or not. |
| 182 | common_chat_msg_parser builder("Hello,", /* is_partial= */ false, {}); |
| 183 | assert_equals(false, builder.try_consume_regex(common_regex("Hello, world!")).has_value()); |
| 184 | } |
| 185 | { |
| 186 | common_chat_msg_parser builder("Hello,", /* is_partial= */ false, {}); |
| 187 | auto res = builder.try_consume_regex(common_regex("H(el)l(?:o, world!)?")); |
| 188 | assert_equals(true, res.has_value()); |
| 189 | // Verify captures |
| 190 | assert_equals<size_t>(2, res->groups.size()); |
| 191 | assert_equals("Hell", builder.str(res->groups[0])); |
| 192 | assert_equals("el", builder.str(res->groups[1])); |
| 193 | // Verify position is after the match |
| 194 | assert_equals<size_t>(4, builder.pos()); |
| 195 | assert_equals("o,", builder.consume_rest()); |
| 196 | } |
| 197 | { |
| 198 | // But in partial mode, we have a partial final match / can't decide, so we throw a partial exception. |
| 199 | common_chat_msg_parser builder("Hello,", /* is_partial= */ true, {}); |
| 200 | assert_throws([&]() { |
| 201 | builder.try_consume_regex(common_regex("Hello, world!")); |
| 202 | }, "^Hello, world!$"); |
| 203 | } |
| 204 | |
| 205 | // Now regardless of the mode, we can tell these aren't a match. |
| 206 | for (const auto is_partial : {false, true}) { |
| 207 | common_chat_msg_parser builder("Hello,", is_partial, {}); |
| 208 | assert_equals(false, builder.try_consume_regex(common_regex("a(b|c)(d|e)f")).has_value()); |
| 209 | } |
| 210 | for (const auto is_partial : {false, true}) { |
| 211 | common_chat_msg_parser builder("Hello,", is_partial, {}); |
| 212 | assert_equals(false, builder.try_consume_literal("Oh")); |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | const std::vector<std::string> barely_healable_jsons = { |
| 217 | "{", |
no test coverage detected