json-schema: control-character escapes match their JSON escape; other class escapes are refused

Inside a class, escapes GBNF does not know ([\b], [\f], [\v], [\0], an escaped space, \p{..}, \c,
a backreference) were copied raw and the grammar then failed to load, an internal error on a
schema the converter had accepted.

A JSON string holds a control character only as an escape, so \t \n \r \f \v \0 (and \b in a
class) now match that escape, in a positive class as alternatives beside it and in a negated
class by leaving the escape out. Outside a class the escape is a group, so a quantifier takes all
of it. An escaped space or non-ASCII character is itself; \x and \u in a class need their hex
digits. Any other class escape is refused at conversion with a message naming it.
vendor/patches/0020, vendor/UPSTREAM; gbnf_test cases.
This commit is contained in:
davetha authored and StillDeadcode committed 2026-10-19 10:38:06 +02:00
1 parent 12735a62dc
commit 8015d9a639
4 files changed
+279 -14

No files matched your search

+24 -1
View File
@@ -1728,6 +1728,23 @@ TEST(json_schema_grammars_admit_exactly_their_instances) {
{ R"({"type":"string","pattern":"^[\\--z]$"})", { R"("-")", R"("a")" }, { R"("+")" } },
{ R"({"type":"string","pattern":"^[\\.]$"})", { R"(".")" }, { R"("a")" } },
{ R"({"type":"string","pattern":"a\\-b"})", { R"("xa-by")" }, { R"("ab")" } },
/* control-character escapes (0020): a JSON string holds a tab or a backspace only as an
* escape, so [\t] [\b] [\f] [\v] [\0] and \t outside a class match the escape, and an
* escaped space or non-ASCII character is itself. */
{ R"({"type":"string","pattern":"^[\\b]$"})", { R"("\b")" }, { R"("b")", R"("\\")" } },
{ R"({"type":"string","pattern":"^[a\\t]+$"})", { R"("a\ta")", R"("a")" }, { R"("t")", R"("a b")" } },
{ R"({"type":"string","pattern":"^[\\f\\v]$"})", { R"("\f")", R"("\u000b")", R"("\u000B")" }, { R"("f")", R"("v")" } },
{ R"({"type":"string","pattern":"^[\\0]$"})", { R"("\u0000")" }, { R"("0")" } },
{ R"({"type":"string","pattern":"^a\\tb$"})", { R"("a\tb")" }, { R"("atb")" } },
{ R"({"type":"string","pattern":"^[a\\ ]+$"})", { R"("a a")" }, { R"("ab")" } },
{ R"({"type":"string","pattern":"^a\\ b$"})", { R"("a b")" }, { R"("ab")" } },
{ R"({"type":"string","pattern":"^[\\s]$"})", { R"(" ")", R"("\n")" }, { R"("n")" } },
{ R"({"type":"string","pattern":"^[^\\t]$"})", { R"("a")" }, { R"("")" } },
{ R"({"type":"string","pattern":"^a\\t+b$"})", { R"("a\t\tb")" }, { R"("a\tttb")", R"("ab")" } },
{ R"({"type":"string","pattern":"^x\\v{2}$"})", { R"("x\u000b\u000B")" }, { R"("x\u000b")" } },
{ R"({"type":"string","pattern":"^[\\t]{2}$"})", { R"("\t\t")" }, { R"("\t")" } },
{ R"({"type":"string","pattern":"^[^\\n]+$"})", { R"("ab")", R"("a\tb")" }, { R"("a\nb")" } },
{ R"({"type":"string","pattern":"^[^\\s]+$"})", { R"("ab")" }, { R"("\t")", R"("a b")" } },
{ R"({"type":"string","pattern":"^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"})",
{ R"("a.b@c.io")", R"("x-y@d-e.org")" }, { R"("a@b")", R"("a b@c.io")" } },
{ R"({"type":"array","items":{"type":"integer"},"minItems":1,"maxItems":3})",
@@ -1751,7 +1768,13 @@ TEST(json_schema_grammars_admit_exactly_their_instances) {
"on \"number\"\n");
for (const char* schema : { R"({"type":"string","pattern":"^a|b"})",
R"({"type":"string","pattern":"a|b$"})",
R"({"type":"string","pattern":"^[a\\S]$"})" }) {
R"({"type":"string","pattern":"^[a\\S]$"})",
R"({"type":"string","pattern":"^[\\p{L}]$"})",
R"({"type":"string","pattern":"^[\\cA]$"})",
R"({"type":"string","pattern":"^[a\\1]$"})",
R"({"type":"string","pattern":"^[\\01]$"})",
R"({"type":"string","pattern":"^[\\xZ]$"})",
R"({"type":"string","pattern":"^[\\u{41}]$"})" }) {
std::string gbnf, err;
CHECK(grammar_from_json_schema(schema, "root", &gbnf, &err) < 0);
}
+18
View File
@@ -104,6 +104,7 @@ vendor/llama/common/regex-partial.{h,cpp} <- llama.cpp common/*
patches/0017-json-schema-a-pattern-without-anchors-searches.patch
patches/0018-json-schema-shorthand-classes-are-written-out.patch
patches/0019-json-schema-identity-escapes-of-punctuation.patch
patches/0020-json-schema-control-escapes-and-unloadable-class-escapes.patch
On 0003: a `pattern` in a `response_format` reaches _visit_pattern() as client data, and three
of its paths do not survive that. `front()`/`back()` run on an empty string; `seq.back()` runs
@@ -536,3 +537,20 @@ PATCH SERIES
and inside a class it is written \xHH, so an escaped '-' or '^' cannot read as a range or
a negation. gbnf_test covers "\/" and "\-" in literals, "\-" "\^" "\." in classes and as
a range endpoint, an unanchored "a\-b", and zod's email pattern.
patches/0020-json-schema-control-escapes-and-unloadable-class-escapes.patch
Inside a class, escapes GBNF does not know (\b \f \v \0, an escaped space, \p{..}, \c, a
backreference) were copied raw and the grammar failed to load -- an internal error on a
schema the converter had accepted. A JSON string holds a control character only as an
escape, so \t \n \r \f \b \v \0 in a class, and \t \n \r \f \v \0 outside one, now
match that escape: a positive class gains them as alternatives ("[a\t]" reads
"(?:[a]|\\t)", and "[\s]" gains "\\[tnfr]" as 0018 gave the bare \s), and a negated class is
spelled as text that is neither a listed character nor one of those escapes ("[^\n]+" no
longer admits the escape \n). An outside escape is a group, so a quantifier takes all of it.
An escaped space or non-ASCII character is itself. \x and \u in a class need their hex
digits; "\0" before a digit (a legacy octal) is refused. Every other class escape is now
refused at conversion with a message naming it. Limits: a negated class still admits the
\u form of a character it leaves out (\u0009 for \t), and a positive class admits \t \n
\r \f \b only in their short form. gbnf_test covers each escape in and out of a class, quantified, and negated, and the
refusals.
+87 -13
View File
@@ -338,12 +338,33 @@ static std::string anchor_pattern(const std::string & p) {
// \s adds the escapes \t \n \f \r for the same reason. In a class a positive shorthand becomes its
// ranges and [\s\S] and its kin become any text; a negated one mixed into a class has no spelling,
// so false is returned and the pattern refused. Identity escapes of punctuation, which JavaScript
// writes freely ("\/" in a path, "\-" in a class), become characters GBNF can read.
// writes freely ("\/" in a path, "\-" in a class), become characters GBNF can read. \t \n \r \f
// \b (in a class) \v \0 are control characters, which a JSON string carries only as escapes, so
// they match the escape. Any other escape in a class (\p{..}, \c, a backreference) has no GBNF
// spelling: `bad` names it and false is returned, rather than copying it into a grammar that
// would then fail to load.
static bool is_identity_punct(char c) {
return c > ' ' && c < 0x7F && c != '\\' && !std::isalnum(static_cast<unsigned char>(c));
}
static bool expand_shorthands(const std::string & p, std::string & out) {
// The JSON escape for the control character a regex escape names, or "" if it names none.
static std::string json_control_escape(char n) {
switch (n) {
case 't': case 'n': case 'r': case 'f': case 'b': return std::string("\\\\") + n;
case 'v': return "\\\\u000[bB]";
case '0': return "\\\\u0000";
default: return "";
}
}
static std::string hex_escape(char n) {
std::string s = "\\x";
s += "0123456789ABCDEF"[(n >> 4) & 0xF];
s += "0123456789ABCDEF"[n & 0xF];
return s;
}
static bool expand_shorthands(const std::string & p, std::string & out, char & bad) {
static const std::string sp = " \\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF";
static const std::string esc = "\\\\(?:[\"\\\\/bfnrt]|u[0-9A-Fa-f]{4})";
static const std::string raw = "\"\\\\\\x00-\\x1F";
@@ -365,6 +386,12 @@ static bool expand_shorthands(const std::string & p, std::string & out) {
// bare character; regex syntax characters and '"' keep their backslash.
if (is_identity_punct(n) && std::string("^$.[](){}|*+?\"").find(n) == std::string::npos) {
out += n;
} else if (n != 'b' && !json_control_escape(n).empty()) {
// A group, so a following quantifier takes the whole escape. Outside a class
// \b is a word boundary, which the scanner refuses.
out += "(?:" + json_control_escape(n) + ")";
} else if (n == ' ' || static_cast<unsigned char>(n) >= 0x80) {
out += n;
} else {
out += c;
out += n;
@@ -395,28 +422,74 @@ static bool expand_shorthands(const std::string & p, std::string & out) {
continue;
}
std::string cls = "[";
// A positive class's control characters can only appear as JSON escapes, which are two
// or six characters long, so they become alternatives beside the class.
std::vector<std::string> escapes;
const bool negated_cls = !body.empty() && body[0] == '^';
std::string excluded; // the control characters a negated class leaves out, by escape letter
for (size_t k = 0; k < body.size(); ++k) {
if (body[k] == '\\' && k + 1 < body.size()) {
const char n = body[++k];
if (n == 'd') cls += "0-9";
else if (n == 'w') cls += "A-Za-z0-9_";
else if (n == 's') cls += sp;
else if (n == 'D' || n == 'W' || n == 'S') return false;
else if (n == 's') {
cls += sp;
if (!negated_cls) escapes.push_back("\\\\[tnfr]");
else excluded += "tnfr";
}
else if (n == 'D' || n == 'W' || n == 'S') { bad = n; return false; }
else if (!json_control_escape(n).empty()) {
if (n == '0' && k + 1 < body.size() && std::isdigit(static_cast<unsigned char>(body[k + 1]))) {
bad = n; // "\01" is a legacy octal escape
return false;
}
if (negated_cls) excluded += n;
else escapes.push_back(json_control_escape(n));
}
else if (is_identity_punct(n) && n != '"' && n != '[' && n != ']') {
// "\-" "\." "\^" and the like: GBNF has no such escape, and bare they could
// read as a range or a negation, so they are written as \xHH.
cls += "\\x";
cls += "0123456789ABCDEF"[(n >> 4) & 0xF];
cls += "0123456789ABCDEF"[n & 0xF];
cls += hex_escape(n);
}
else { cls += '\\'; cls += n; }
else if (n == 'x' || n == 'u') {
// Copied for GBNF to read, so the hex digits must be there.
const size_t len = n == 'x' ? 2 : 4;
for (size_t h = 1; h <= len; ++h) {
if (k + h >= body.size() || !std::isxdigit(static_cast<unsigned char>(body[k + h]))) {
bad = n;
return false;
}
}
cls += '\\';
cls += n;
}
else if (std::string("\"[]\\").find(n) != std::string::npos) { cls += '\\'; cls += n; }
else if (n == ' ' || static_cast<unsigned char>(n) >= 0x80) cls += n;
else { bad = n; return false; }
} else {
cls += body[k];
}
}
out += cls;
if (j < p.size()) {
out += ']';
cls += ']';
}
if (negated_cls && !excluded.empty() && j < p.size()) {
// A string holds those characters only as escapes, so the class becomes text that is
// neither a listed character nor one of those escapes. Their \u forms (\u0009 for \t)
// are still admitted.
std::string letters;
for (char e : std::string("bfnrt")) {
if (excluded.find(e) == std::string::npos) letters += e;
}
out += "(?:[^" + cls.substr(2, cls.size() - 3) + raw + "]|\\\\(?:[\"\\\\/" + letters +
"]|u[0-9A-Fa-f]{4}))";
} else if (!escapes.empty() && j < p.size()) {
out += "(?:";
if (cls != "[]") out += cls + "|";
for (size_t e = 0; e < escapes.size(); ++e) out += (e ? "|" : "") + escapes[e];
out += ")";
} else {
out += cls;
}
i = j;
}
@@ -491,9 +564,10 @@ private:
std::string _visit_pattern(const std::string & client_pattern, const std::string & name) {
std::string expanded;
if (!expand_shorthands(client_pattern, expanded)) {
_errors.push_back("Unsupported pattern: \\D, \\W or \\S inside a character class "
"cannot be spelled in GBNF");
char bad = 0;
if (!expand_shorthands(client_pattern, expanded, bad)) {
_errors.push_back(std::string("Unsupported regex escape '\\") + bad +
"' inside a character class: GBNF cannot spell it");
return "";
}
const std::string pattern = anchor_pattern(expanded);
@@ -0,0 +1,150 @@
diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index 92561c4..53f067c 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -338,12 +338,33 @@ static std::string anchor_pattern(const std::string & p) {
// \s adds the escapes \t \n \f \r for the same reason. In a class a positive shorthand becomes its
// ranges and [\s\S] and its kin become any text; a negated one mixed into a class has no spelling,
// so false is returned and the pattern refused. Identity escapes of punctuation, which JavaScript
-// writes freely ("\/" in a path, "\-" in a class), become characters GBNF can read.
+// writes freely ("\/" in a path, "\-" in a class), become characters GBNF can read. \t \n \r \f
+// \b (in a class) \v \0 are control characters, which a JSON string carries only as escapes, so
+// they match the escape. Any other escape in a class (\p{..}, \c, a backreference) has no GBNF
+// spelling: `bad` names it and false is returned, rather than copying it into a grammar that
+// would then fail to load.
static bool is_identity_punct(char c) {
return c > ' ' && c < 0x7F && c != '\\' && !std::isalnum(static_cast<unsigned char>(c));
}
-static bool expand_shorthands(const std::string & p, std::string & out) {
+// The JSON escape for the control character a regex escape names, or "" if it names none.
+static std::string json_control_escape(char n) {
+ switch (n) {
+ case 't': case 'n': case 'r': case 'f': case 'b': return std::string("\\\\") + n;
+ case 'v': return "\\\\u000[bB]";
+ case '0': return "\\\\u0000";
+ default: return "";
+ }
+}
+
+static std::string hex_escape(char n) {
+ std::string s = "\\x";
+ s += "0123456789ABCDEF"[(n >> 4) & 0xF];
+ s += "0123456789ABCDEF"[n & 0xF];
+ return s;
+}
+
+static bool expand_shorthands(const std::string & p, std::string & out, char & bad) {
static const std::string sp = " \\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF";
static const std::string esc = "\\\\(?:[\"\\\\/bfnrt]|u[0-9A-Fa-f]{4})";
static const std::string raw = "\"\\\\\\x00-\\x1F";
@@ -365,6 +386,12 @@ static bool expand_shorthands(const std::string & p, std::string & out) {
// bare character; regex syntax characters and '"' keep their backslash.
if (is_identity_punct(n) && std::string("^$.[](){}|*+?\"").find(n) == std::string::npos) {
out += n;
+ } else if (n != 'b' && !json_control_escape(n).empty()) {
+ // A group, so a following quantifier takes the whole escape. Outside a class
+ // \b is a word boundary, which the scanner refuses.
+ out += "(?:" + json_control_escape(n) + ")";
+ } else if (n == ' ' || static_cast<unsigned char>(n) >= 0x80) {
+ out += n;
} else {
out += c;
out += n;
@@ -395,28 +422,74 @@ static bool expand_shorthands(const std::string & p, std::string & out) {
continue;
}
std::string cls = "[";
+ // A positive class's control characters can only appear as JSON escapes, which are two
+ // or six characters long, so they become alternatives beside the class.
+ std::vector<std::string> escapes;
+ const bool negated_cls = !body.empty() && body[0] == '^';
+ std::string excluded; // the control characters a negated class leaves out, by escape letter
for (size_t k = 0; k < body.size(); ++k) {
if (body[k] == '\\' && k + 1 < body.size()) {
const char n = body[++k];
if (n == 'd') cls += "0-9";
else if (n == 'w') cls += "A-Za-z0-9_";
- else if (n == 's') cls += sp;
- else if (n == 'D' || n == 'W' || n == 'S') return false;
+ else if (n == 's') {
+ cls += sp;
+ if (!negated_cls) escapes.push_back("\\\\[tnfr]");
+ else excluded += "tnfr";
+ }
+ else if (n == 'D' || n == 'W' || n == 'S') { bad = n; return false; }
+ else if (!json_control_escape(n).empty()) {
+ if (n == '0' && k + 1 < body.size() && std::isdigit(static_cast<unsigned char>(body[k + 1]))) {
+ bad = n; // "\01" is a legacy octal escape
+ return false;
+ }
+ if (negated_cls) excluded += n;
+ else escapes.push_back(json_control_escape(n));
+ }
else if (is_identity_punct(n) && n != '"' && n != '[' && n != ']') {
// "\-" "\." "\^" and the like: GBNF has no such escape, and bare they could
// read as a range or a negation, so they are written as \xHH.
- cls += "\\x";
- cls += "0123456789ABCDEF"[(n >> 4) & 0xF];
- cls += "0123456789ABCDEF"[n & 0xF];
+ cls += hex_escape(n);
}
- else { cls += '\\'; cls += n; }
+ else if (n == 'x' || n == 'u') {
+ // Copied for GBNF to read, so the hex digits must be there.
+ const size_t len = n == 'x' ? 2 : 4;
+ for (size_t h = 1; h <= len; ++h) {
+ if (k + h >= body.size() || !std::isxdigit(static_cast<unsigned char>(body[k + h]))) {
+ bad = n;
+ return false;
+ }
+ }
+ cls += '\\';
+ cls += n;
+ }
+ else if (std::string("\"[]\\").find(n) != std::string::npos) { cls += '\\'; cls += n; }
+ else if (n == ' ' || static_cast<unsigned char>(n) >= 0x80) cls += n;
+ else { bad = n; return false; }
} else {
cls += body[k];
}
}
- out += cls;
if (j < p.size()) {
- out += ']';
+ cls += ']';
+ }
+ if (negated_cls && !excluded.empty() && j < p.size()) {
+ // A string holds those characters only as escapes, so the class becomes text that is
+ // neither a listed character nor one of those escapes. Their \u forms (\u0009 for \t)
+ // are still admitted.
+ std::string letters;
+ for (char e : std::string("bfnrt")) {
+ if (excluded.find(e) == std::string::npos) letters += e;
+ }
+ out += "(?:[^" + cls.substr(2, cls.size() - 3) + raw + "]|\\\\(?:[\"\\\\/" + letters +
+ "]|u[0-9A-Fa-f]{4}))";
+ } else if (!escapes.empty() && j < p.size()) {
+ out += "(?:";
+ if (cls != "[]") out += cls + "|";
+ for (size_t e = 0; e < escapes.size(); ++e) out += (e ? "|" : "") + escapes[e];
+ out += ")";
+ } else {
+ out += cls;
}
i = j;
}
@@ -491,9 +564,10 @@ private:
std::string _visit_pattern(const std::string & client_pattern, const std::string & name) {
std::string expanded;
- if (!expand_shorthands(client_pattern, expanded)) {
- _errors.push_back("Unsupported pattern: \\D, \\W or \\S inside a character class "
- "cannot be spelled in GBNF");
+ char bad = 0;
+ if (!expand_shorthands(client_pattern, expanded, bad)) {
+ _errors.push_back(std::string("Unsupported regex escape '\\") + bad +
+ "' inside a character class: GBNF cannot spell it");
return "";
}
const std::string pattern = anchor_pattern(expanded);