Skip to content

Commit 2960eae

Browse files
authored
grammar : verify parsed state (#5950)
1 parent c785414 commit 2960eae

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

common/grammar-parser.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,22 @@ namespace grammar_parser {
278278
while (*pos) {
279279
pos = parse_rule(state, pos);
280280
}
281+
// Validate the state to ensure that all rules are defined
282+
for (const auto & rule : state.rules) {
283+
for (const auto & elem : rule) {
284+
if (elem.type == LLAMA_GRETYPE_RULE_REF) {
285+
// Ensure that the rule at that location exists
286+
if (elem.value >= state.rules.size() || state.rules[elem.value].empty()) {
287+
// Get the name of the rule that is missing
288+
for (const auto & kv : state.symbol_ids) {
289+
if (kv.second == elem.value) {
290+
throw std::runtime_error("Undefined rule identifier '" + kv.first + "'");
291+
}
292+
}
293+
}
294+
}
295+
}
296+
}
281297
return state;
282298
} catch (const std::exception & err) {
283299
fprintf(stderr, "%s: error parsing grammar: %s\n", __func__, err.what());

0 commit comments

Comments
 (0)