| 335 | } |
| 336 | |
| 337 | static void print_rule( |
| 338 | FILE * file, |
| 339 | uint32_t rule_id, |
| 340 | const std::vector<llama_grammar_element> & rule, |
| 341 | const std::map<uint32_t, std::string> & symbol_id_names) { |
| 342 | if (rule.empty() || rule.back().type != LLAMA_GRETYPE_END) { |
| 343 | throw std::runtime_error( |
| 344 | "malformed rule, does not end with LLAMA_GRETYPE_END: " + std::to_string(rule_id)); |
| 345 | } |
| 346 | fprintf(file, "%s ::= ", symbol_id_names.at(rule_id).c_str()); |
| 347 | for (size_t i = 0, end = rule.size() - 1; i < end; i++) { |
| 348 | llama_grammar_element elem = rule[i]; |
| 349 | switch (elem.type) { |
| 350 | case LLAMA_GRETYPE_END: |
| 351 | throw std::runtime_error( |
| 352 | "unexpected end of rule: " + std::to_string(rule_id) + "," + |
| 353 | std::to_string(i)); |
| 354 | case LLAMA_GRETYPE_ALT: |
| 355 | fprintf(file, "| "); |
| 356 | break; |
| 357 | case LLAMA_GRETYPE_RULE_REF: |
| 358 | fprintf(file, "%s ", symbol_id_names.at(elem.value).c_str()); |
| 359 | break; |
| 360 | case LLAMA_GRETYPE_CHAR: |
| 361 | fprintf(file, "["); |
| 362 | print_grammar_char(file, elem.value); |
| 363 | break; |
| 364 | case LLAMA_GRETYPE_CHAR_NOT: |
| 365 | fprintf(file, "[^"); |
| 366 | print_grammar_char(file, elem.value); |
| 367 | break; |
| 368 | case LLAMA_GRETYPE_CHAR_RNG_UPPER: |
| 369 | if (i == 0 || !is_char_element(rule[i - 1])) { |
| 370 | throw std::runtime_error( |
| 371 | "LLAMA_GRETYPE_CHAR_RNG_UPPER without preceding char: " + |
| 372 | std::to_string(rule_id) + "," + std::to_string(i)); |
| 373 | } |
| 374 | fprintf(file, "-"); |
| 375 | print_grammar_char(file, elem.value); |
| 376 | break; |
| 377 | case LLAMA_GRETYPE_CHAR_ALT: |
| 378 | if (i == 0 || !is_char_element(rule[i - 1])) { |
| 379 | throw std::runtime_error( |
| 380 | "LLAMA_GRETYPE_CHAR_ALT without preceding char: " + |
| 381 | std::to_string(rule_id) + "," + std::to_string(i)); |
| 382 | } |
| 383 | print_grammar_char(file, elem.value); |
| 384 | break; |
| 385 | } |
| 386 | if (is_char_element(elem)) { |
| 387 | switch (rule[i + 1].type) { |
| 388 | case LLAMA_GRETYPE_CHAR_ALT: |
| 389 | case LLAMA_GRETYPE_CHAR_RNG_UPPER: |
| 390 | break; |
| 391 | default: |
| 392 | fprintf(file, "] "); |
| 393 | } |
| 394 | } |
no test coverage detected