MCPcopy Create free account
hub / github.com/Tiiny-AI/PowerInfer / llama_grammar_match_partial_char

Function llama_grammar_match_partial_char

llama.cpp:7853–7897  ·  view source on GitHub ↗

returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char range at pos (regular or inverse range) asserts that pos is pointing to a char range element

Source from the content-addressed store, hash-verified

7851// range at pos (regular or inverse range)
7852// asserts that pos is pointing to a char range element
7853static bool llama_grammar_match_partial_char(
7854 const llama_grammar_element * pos,
7855 const llama_partial_utf8 partial_utf8) {
7856
7857 bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
7858 GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
7859
7860 uint32_t partial_value = partial_utf8.value;
7861 int n_remain = partial_utf8.n_remain;
7862
7863 // invalid sequence or 7-bit char split across 2 bytes (overlong)
7864 if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
7865 return false;
7866 }
7867
7868 // range of possible code points this partial UTF-8 sequence could complete to
7869 uint32_t low = partial_value << (n_remain * 6);
7870 uint32_t high = low | ((1 << (n_remain * 6)) - 1);
7871
7872 if (low == 0) {
7873 if (n_remain == 2) {
7874 low = 1 << 11;
7875 } else if (n_remain == 3) {
7876 low = 1 << 16;
7877 }
7878 }
7879
7880 do {
7881 if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
7882 // inclusive range, e.g. [a-z]
7883 if (pos->value <= high && low <= pos[1].value) {
7884 return is_positive_char;
7885 }
7886 pos += 2;
7887 } else {
7888 // exact char match, e.g. [a] or "a"
7889 if (low <= pos->value && pos->value <= high) {
7890 return is_positive_char;
7891 }
7892 pos += 1;
7893 }
7894 } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
7895
7896 return !is_positive_char;
7897}
7898
7899
7900// transforms a grammar pushdown stack into N possible stacks, all ending

Calls

no outgoing calls

Tested by

no test coverage detected