Skip to content

Commit d5fe4e8

Browse files
grammar : handle maxItems == 0 in JSON schema (#13117)
Co-authored-by: Richard Lyons <[email protected]>
1 parent 295354e commit d5fe4e8

File tree

4 files changed

+25
-0
lines changed

4 files changed

+25
-0
lines changed

common/json-schema-to-grammar.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ using json = nlohmann::ordered_json;
1616
static std::string build_repetition(const std::string & item_rule, int min_items, int max_items, const std::string & separator_rule = "") {
1717
auto has_max = max_items != std::numeric_limits<int>::max();
1818

19+
if (max_items == 0) {
20+
return "";
21+
}
1922
if (min_items == 0 && max_items == 1) {
2023
return item_rule + "?";
2124
}

examples/json_schema_to_grammar.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@
1010

1111
def _build_repetition(item_rule, min_items, max_items, separator_rule=None):
1212

13+
if max_items == 0:
14+
return ""
15+
1316
if min_items == 0 and max_items == 1:
1417
return f'{item_rule}?'
1518

examples/server/public_legacy/json-schema-to-grammar.mjs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
const SPACE_RULE = '| " " | "\\n"{1,2} [ \\t]{0,20}';
33

44
function _buildRepetition(itemRule, minItems, maxItems, opts={}) {
5+
if (maxItems == 0) {
6+
return '';
7+
}
58
if (minItems === 0 && maxItems === 1) {
69
return `${itemRule}?`;
710
}

tests/test-json-schema-to-grammar.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -597,6 +597,22 @@ static void test_all(const std::string & lang, std::function<void(const TestCase
597597
)"""
598598
});
599599

600+
test({
601+
SUCCESS,
602+
"maxItems 0",
603+
R"""({
604+
"items": {
605+
"type": "boolean"
606+
},
607+
"maxItems": 0
608+
})""",
609+
R"""(
610+
boolean ::= ("true" | "false") space
611+
root ::= "[" space "]" space
612+
space ::= | " " | "\n"{1,2} [ \t]{0,20}
613+
)"""
614+
});
615+
600616
test({
601617
SUCCESS,
602618
"maxItems 1",

0 commit comments

Comments
 (0)