File tree Expand file tree Collapse file tree 2 files changed +21
-5
lines changed Expand file tree Collapse file tree 2 files changed +21
-5
lines changed Original file line number Diff line number Diff line change 1
1
#include " grammar.h"
2
+ #include < unordered_map>
3
+ #include < string>
4
+ #include < vector>
2
5
3
- struct llama_grammar * llama_parse_grammar (const char * grammar_str) {
4
- struct llama_grammar * grammar = NULL ;
6
+ struct llama_grammar * llama_cached_parse_grammar (const char * grammar_str) {
7
+ static std::unordered_map<std::string, grammar_parser::parse_state> parsed_grammar_cache;
8
+ std::string key = grammar_str;
9
+
10
+ auto it = parsed_grammar_cache.find (key);
5
11
grammar_parser::parse_state parsed_grammar;
12
+ if (it != parsed_grammar_cache.end ()) {
13
+ // Use cached parsed grammar
14
+ parsed_grammar = it->second ;
15
+ } else {
16
+ // Parse and cache the result
17
+ parsed_grammar = grammar_parser::parse (grammar_str);
18
+ parsed_grammar_cache[key] = parsed_grammar;
6
19
7
- parsed_grammar = grammar_parser::parse (grammar_str);
8
- grammar_parser::print_grammar (stderr, parsed_grammar);
20
+ // Optionally print the grammar
21
+ grammar_parser::print_grammar (stderr, parsed_grammar);
22
+ }
9
23
10
24
std::vector<const llama_grammar_element *> grammar_rules (parsed_grammar.c_rules ());
25
+
26
+ struct llama_grammar * grammar = NULL ;
11
27
grammar = llama_grammar_init (grammar_rules.data (), grammar_rules.size (), parsed_grammar.symbol_ids .at (" root" ));
12
28
13
29
return grammar;
Original file line number Diff line number Diff line change 8
8
extern "C" {
9
9
#endif
10
10
11
- struct llama_grammar * llama_parse_grammar (const char * grammar_str );
11
+ struct llama_grammar * llama_cached_parse_grammar (const char * grammar_str );
12
12
13
13
#ifdef __cplusplus
14
14
}
You can’t perform that action at this time.
0 commit comments