| 906 | //////////////////// |
| 907 | |
| 908 | struct llama_grammar * llama_grammar_init_impl( |
| 909 | const struct llama_vocab * vocab, |
| 910 | const llama_grammar_element ** rules, |
| 911 | size_t n_rules, |
| 912 | size_t start_rule_index) { |
| 913 | const llama_grammar_element * pos; |
| 914 | |
| 915 | // copy rule definitions into vectors |
| 916 | llama_grammar_rules vec_rules(n_rules); |
| 917 | for (size_t i = 0; i < n_rules; i++) { |
| 918 | for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) { |
| 919 | vec_rules[i].push_back(*pos); |
| 920 | } |
| 921 | vec_rules[i].push_back({LLAMA_GRETYPE_END, 0}); |
| 922 | } |
| 923 | |
| 924 | // Check for left recursion |
| 925 | std::vector<bool> rules_visited(n_rules); |
| 926 | std::vector<bool> rules_in_progress(n_rules); |
| 927 | std::vector<bool> rules_may_be_empty(n_rules); |
| 928 | for (size_t i = 0; i < n_rules; i++) { |
| 929 | if (rules_visited[i]) { |
| 930 | continue; |
| 931 | } |
| 932 | if (llama_grammar_detect_left_recursion(vec_rules, i, &rules_visited, &rules_in_progress, &rules_may_be_empty)) { |
| 933 | LLAMA_LOG_ERROR("unsupported grammar, left recursion detected for nonterminal at index %zu", i); |
| 934 | return nullptr; |
| 935 | } |
| 936 | } |
| 937 | |
| 938 | // loop over alternates of start rule to build initial stacks |
| 939 | llama_grammar_stacks stacks; |
| 940 | pos = vec_rules[start_rule_index].data(); |
| 941 | do { |
| 942 | llama_grammar_stack stack; |
| 943 | if (!llama_grammar_is_end_of_sequence(pos)) { |
| 944 | // if alternate is nonempty, add to stack |
| 945 | stack.push_back(pos); |
| 946 | } |
| 947 | llama_grammar_advance_stack(vec_rules, stack, stacks); |
| 948 | while (!llama_grammar_is_end_of_sequence(pos)) { |
| 949 | // scan to end of alternate def |
| 950 | pos++; |
| 951 | } |
| 952 | if (pos->type == LLAMA_GRETYPE_ALT) { |
| 953 | // there's another alternate def of this rule to process |
| 954 | pos++; |
| 955 | } else { |
| 956 | break; |
| 957 | } |
| 958 | } while (true); |
| 959 | |
| 960 | // Important: vec_rules has to be moved here, not copied, because stacks contains |
| 961 | // pointers to elements of vec_rules. If vec_rules were copied into llama_grammar |
| 962 | // then the pointers would be invalidated when the local vec_rules goes out of scope. |
| 963 | return new llama_grammar { |
| 964 | vocab, |
| 965 | std::move(vec_rules), |