Skip to content

Commit 5f58f08

Browse files
committed
Add minimal grammar parser in examples/
1 parent c091cdf commit 5f58f08

File tree

4 files changed

+37
-0
lines changed

4 files changed

+37
-0
lines changed

examples/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ else()
2727
add_subdirectory(embd-input)
2828
add_subdirectory(llama-bench)
2929
add_subdirectory(beam-search)
30+
add_subdirectory(grammar)
3031
if (LLAMA_METAL)
3132
add_subdirectory(metal)
3233
endif()

examples/grammar/CMakeLists.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
set(TARGET grammar)
2+
add_library(${TARGET} SHARED grammar.cpp)
3+
set_target_properties(${TARGET} PROPERTIES POSITION_INDEPENDENT_CODE ON)
4+
target_link_libraries(${TARGET} PRIVATE common llama ${CMAKE_THREAD_LIBS_INIT})
5+
target_compile_definitions(${TARGET} PRIVATE LLAMA_SHARED LLAMA_BUILD)

examples/grammar/grammar.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#include "grammar.h"
2+
3+
struct llama_grammar * llama_parse_grammar(const char * grammar_str) {
4+
struct llama_grammar * grammar = NULL;
5+
grammar_parser::parse_state parsed_grammar;
6+
7+
parsed_grammar = grammar_parser::parse(grammar_str);
8+
grammar_parser::print_grammar(stderr, parsed_grammar);
9+
10+
std::vector<const llama_grammar_element *> grammar_rules(parsed_grammar.c_rules());
11+
grammar = llama_grammar_init(grammar_rules.data(), grammar_rules.size(), parsed_grammar.symbol_ids.at("root"));
12+
13+
return grammar;
14+
}

examples/grammar/grammar.h

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#ifndef GRAMMAR_H
2+
#define GRAMMAR_H
3+
4+
#include "llama.h"
5+
#include "grammar-parser.h"
6+
7+
#ifdef __cplusplus
8+
extern "C" {
9+
#endif
10+
11+
struct llama_grammar * llama_parse_grammar(const char * grammar_str);
12+
13+
#ifdef __cplusplus
14+
}
15+
#endif
16+
17+
#endif // GRAMMAR_H

0 commit comments

Comments
 (0)