Skip to main content

variable_codegen/
template.rs

1use serde::Serialize;
2
3/// Context for rendering an entire generated file.
4///
5/// This is the top-level data structure passed to language templates.
6/// Each language's codegen module populates these structs with
7/// language-specific type names, formatted values, and naming conventions.
8#[derive(Debug, Serialize)]
9pub struct FileContext {
10    pub structs: Vec<StructContext>,
11    pub features: Vec<FeatureContext>,
12}
13
14/// Context for a struct type declaration.
15#[derive(Debug, Serialize)]
16pub struct StructContext {
17    pub name: String,
18    pub fields: Vec<StructFieldContext>,
19}
20
21/// Context for a single field within a struct type.
22#[derive(Debug, Serialize)]
23pub struct StructFieldContext {
24    pub name: String,
25    pub type_name: String,
26}
27
28/// Context for a single feature within the generated file.
29#[derive(Debug, Serialize)]
30pub struct FeatureContext {
31    pub name: String,
32    pub id: u32,
33    pub interface_name: String,
34    pub defaults_name: String,
35    pub variable_ids_name: String,
36    pub fn_name: String,
37    pub variables: Vec<VariableContext>,
38}
39
40/// Context for a single variable within a feature.
41#[derive(Debug, Serialize)]
42pub struct VariableContext {
43    pub name: String,
44    pub type_name: String,
45    pub default_value: String,
46    pub id: u32,
47}
48
49/// Render a template string with the given file context.
50///
51/// Uses Jinja2-style templates via minijinja with `trim_blocks` and
52/// `lstrip_blocks` enabled for clean template authoring.
53pub fn render(template_str: &str, context: &FileContext) -> String {
54    let mut env = minijinja::Environment::new();
55    env.set_trim_blocks(true);
56    env.set_lstrip_blocks(true);
57    env.add_template("output", template_str)
58        .expect("template parse error: this is a bug in the embedded template");
59    let tmpl = env.get_template("output").unwrap();
60    tmpl.render(context)
61        .expect("template render error: this is a bug in the template or context")
62}