tron 2.1.0

A rust based template system built for speed and simplicity.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Compile-time template generation macros.
//!
//! This module provides procedural macros for embedding Tron templates directly
//! into Rust code at compile time, enabling zero-runtime-cost template usage.

/// Include a Tron template file at compile time and create a template instance.
///
/// This macro reads a template file during compilation and embeds its contents
/// as a `TronTemplate` in the resulting binary. The template is parsed and
/// validated at compile time.
///
/// # Examples
///
/// ```ignore
/// use tron::include_template;
///
/// // Include template from file
/// let template = include_template!("templates/function.tron");
///
/// // Use the template normally
/// let mut template = template.clone();
/// template.set("name", "example").unwrap();
/// template.set("body", "println!(\"Hello!\");").unwrap();
/// let result = template.render().unwrap();
/// ```
///
/// # Compile-time Validation
///
/// The macro validates template syntax at compile time:
///
/// ```compile_fail
/// // This would cause a compilation error if the template has invalid syntax
/// let template = include_template!("templates/invalid.tron");
/// ```
///
/// # Path Resolution
///
/// Template paths are resolved relative to the crate root or `CARGO_MANIFEST_DIR`.
/// You can use absolute paths or paths relative to the current file using
/// `include_template!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/file.tron"))`.
#[macro_export]
macro_rules! include_template {
    ($file:expr) => {{
        const CONTENT: &str = include_str!($file);
        let template = $crate::TronTemplate::new(CONTENT)
            .expect(concat!("Failed to parse template: ", $file));
        // Run validator at compile time (will panic if invalid)
        let validator = $crate::validation::TemplateValidator::new();
        let report = validator.validate(&template)
            .expect("Template validation failed unexpectedly");
        if report.has_errors() {
            panic!("Template validation errors: {}", report);
        }
        template
    }};
}

/// Create a template from a string literal at compile time.
///
/// This macro creates a `TronTemplate` from a string literal, with compile-time
/// syntax validation. It's useful for small templates that don't warrant
/// separate files.
///
/// # Examples
///
/// ```
/// use tron::template;
///
/// let template = template!("fn @[name]@() { @[body]@ }");
/// ```
#[macro_export]
macro_rules! template {
    ($template:literal) => {{
        let template = $crate::TronTemplate::new($template)
            .expect(concat!("Failed to parse template: ", $template));
        let validator = $crate::validation::TemplateValidator::new();
        let report = validator.validate(&template)
            .expect("Template validation failed unexpectedly");
        if report.has_errors() {
            panic!("Template validation errors: {}", report);
        }
        template
    }};
}

/// Create a template reference with dependencies at compile time.
///
/// This macro creates a `TronRef` from a template string and a list of dependencies.
/// Both template syntax and dependency format are validated at compile time.
///
/// # Examples
///
/// ```
/// use tron::template_ref;
///
/// let template_ref = template_ref!(
///     "use serde::Serialize;\n#[derive(Serialize)]\nstruct @[name]@ { @[fields]@ }",
///     dependencies = ["serde = \"1.0\""]
/// );
/// ```
///
/// # With Multiple Dependencies
///
/// ```
/// use tron::template_ref;
///
/// let template_ref = template_ref!(
///     "async fn @[name]@() -> Result<@[return_type]@, @[error_type]@> { @[body]@ }",
///     dependencies = [
///         "tokio = \"1.0\"",
///         "serde = \"1.0\"",
///         "anyhow = \"1.0\""
///     ]
/// );
/// ```
#[macro_export]
macro_rules! template_ref {
    ($template:literal, dependencies = [$($dep:literal),* $(,)?]) => {
        {
            let template = $crate::TronTemplate::new($template)
                .expect(concat!("Failed to parse template: ", $template));
            let mut template_ref = $crate::TronRef::new(template);
            $(
                template_ref = template_ref.with_dependency($dep);
            )*
            template_ref
        }
    };
    ($template:literal) => {
        {
            let template = $crate::TronTemplate::new($template)
                .expect(concat!("Failed to parse template: ", $template));
            $crate::TronRef::new(template)
        }
    };
}

/// Create a template assembler with multiple templates at compile time.
///
/// This macro creates a `TronAssembler` with multiple templates, useful for
/// building complex code generation workflows.
///
/// # Examples
///
/// ```
/// use tron::assemble_templates;
///
/// let assembler = assemble_templates![
///     "// File header\nuse std::collections::HashMap;",
///     "pub struct @[struct_name]@ { @[fields]@ }",
///     "impl @[struct_name]@ { @[methods]@ }"
/// ];
/// ```
///
/// # With Custom Separator
///
/// ```
/// use tron::assemble_templates;
///
/// let assembler = assemble_templates![
///     separator = "\n\n",
///     "mod @[module_name]@ {",
///     "    @[module_content]@",
///     "}"
/// ];
/// ```
#[macro_export]
macro_rules! assemble_templates {
    (separator = $sep:literal, $($template:literal),+ $(,)?) => {
        {
            let mut assembler = $crate::TronAssembler::with_separator($sep);
            $(
                let template = $crate::TronTemplate::new($template)
                    .expect(concat!("Failed to parse template: ", $template));
                assembler.add_template($crate::TronRef::new(template));
            )+
            assembler
        }
    };
    ($($template:literal),+ $(,)?) => {
        {
            let mut assembler = $crate::TronAssembler::new();
            $(
                let template = $crate::TronTemplate::new($template)
                    .expect(concat!("Failed to parse template: ", $template));
                assembler.add_template($crate::TronRef::new(template));
            )+
            assembler
        }
    };
}

/// Generate code using a template at compile time.
///
/// This is an advanced macro that allows you to specify placeholder values
/// and generate code directly at compile time. The generated code is inlined
/// into your program.
///
/// **Note:** This macro requires the template to be fully resolved at compile time,
/// so all placeholder values must be string literals.
///
/// # Examples
///
/// ```
/// use tron::generate_code;
///
/// // Generate a simple function
/// generate_code!(
///     template = "fn @[name]@() -> @[return_type]@ { @[body]@ }",
///     placeholders = {
///         "name" => "hello_world",
///         "return_type" => "&'static str", 
///         "body" => "\"Hello, World!\""
///     }
/// );
/// 
/// // The above generates:
/// // fn hello_world() -> &'static str { "Hello, World!" }
/// ```
///
/// # Complex Example
///
/// ```
/// use tron::generate_code;
///
/// generate_code!(
///     template = r#"
///         #[derive(@[derives]@)]
///         pub struct @[name]@ {
///             @[fields]@
///         }
///     "#,
///     placeholders = {
///         "derives" => "Debug, Clone, PartialEq",
///         "name" => "Person",
///         "fields" => "pub name: String,\n    pub age: u32"
///     }
/// );
/// ```
#[macro_export]
macro_rules! generate_code {
    (
        template = $template:literal,
        placeholders = { $($key:literal => $value:literal),* $(,)? }
    ) => {
        {
            // This is a compile-time code generation macro
            // At runtime, this evaluates to the generated code string
            let mut content = String::from($template);
            $(
                content = content.replace(
                    &format!("@[{}]@", $key),
                    $value
                );
            )*
            content
        }
    };
}

/// Create a template builder at compile time with predefined values.
///
/// This macro creates a `TronTemplateBuilder` with template content and
/// predefined placeholder values, useful for creating reusable template
/// configurations.
///
/// # Examples
///
/// ```
/// use tron::template_builder;
///
/// let builder = template_builder!(
///     template = "struct @[name]@ { @[field]@: @[type]@ }",
///     values = {
///         "name" => "Example",
///         "field" => "value"
///     }
/// );
/// 
/// let template = builder
///     .set("type", "String")
///     .build()
///     .unwrap();
/// ```
#[macro_export]
macro_rules! template_builder {
    (
        template = $template:literal,
        values = { $($key:literal => $value:literal),* $(,)? }
    ) => {
        {
            let mut builder = $crate::TronTemplateBuilder::new()
                .content($template);
            $(
                builder = builder.set($key, $value);
            )*
            builder
        }
    };
    (template = $template:literal) => {
        $crate::TronTemplateBuilder::new().content($template)
    };
}

#[cfg(test)]
mod tests {

    #[test]
    fn test_template_macro() {
        let template = template!("Hello @[name]@!");
        assert_eq!(template.placeholder_names().len(), 1);
        assert!(template.has_placeholder("name"));
    }

    #[test]
    fn test_template_ref_macro() {
        let template_ref = template_ref!(
            "use @[crate_name]@;\nfn @[name]@() { @[body]@ }",
            dependencies = ["serde = \"1.0\"", "tokio = \"1.0\""]
        );
        
        assert_eq!(template_ref.dependencies().len(), 2);
        assert!(template_ref.inner().has_placeholder("name"));
        assert!(template_ref.inner().has_placeholder("body"));
        assert!(template_ref.inner().has_placeholder("crate_name"));
    }

    #[test]
    fn test_template_ref_macro_no_deps() {
        let template_ref = template_ref!("fn @[name]@() {}");
        assert_eq!(template_ref.dependencies().len(), 0);
        assert!(template_ref.inner().has_placeholder("name"));
    }

    #[test]
    fn test_assemble_templates_macro() {
        let assembler = assemble_templates![
            "// Header comment",
            "fn @[name]@() {}",
            "// Footer comment"
        ];
        
        assert_eq!(assembler.len(), 3);
    }

    #[test]
    fn test_assemble_templates_macro_with_separator() {
        let assembler = assemble_templates![
            separator = "\n\n",
            "mod test {",
            "    @[content]@",
            "}"
        ];
        
        assert_eq!(assembler.separator(), "\n\n");
        assert_eq!(assembler.len(), 3);
    }

    #[test]
    fn test_generate_code_macro() {
        let code = generate_code!(
            template = "fn @[name]@() -> @[type]@ { @[body]@ }",
            placeholders = {
                "name" => "test_function",
                "type" => "i32",
                "body" => "42"
            }
        );
        
        assert_eq!(code, "fn test_function() -> i32 { 42 }");
    }

    #[test]
    fn test_template_builder_macro() {
        let builder = template_builder!(
            template = "@[greeting]@ @[name]@!",
            values = {
                "greeting" => "Hello"
            }
        );
        
        let template = builder
            .set("name", "World")
            .build()
            .unwrap();
            
        let result = template.render().unwrap();
        assert_eq!(result, "Hello World!");
    }

    #[test]
    fn test_template_builder_macro_no_values() {
        let builder = template_builder!(template = "Hello @[name]@!");
        let template = builder
            .set("name", "Macro")
            .build()
            .unwrap();
            
        assert_eq!(template.render().unwrap(), "Hello Macro!");
    }

    #[test] 
    fn test_macro_with_complex_template() {
        let template = template!(r#"
            #[derive(Debug)]
            pub struct @[name]@ {
                @[fields]@
            }
            
            impl @[name]@ {
                pub fn new(@[constructor_params]@) -> Self {
                    Self {
                        @[constructor_body]@
                    }
                }
            }
        "#);
        
        assert!(template.has_placeholder("name"));
        assert!(template.has_placeholder("fields"));
        assert!(template.has_placeholder("constructor_params"));
        assert!(template.has_placeholder("constructor_body"));
    }

    #[test]
    #[should_panic(expected = "Failed to parse template")]
    fn test_template_macro_invalid_syntax() {
        let _template = template!("Invalid @[bad name]@ template");
    }
}