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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
//! Core template functionality for the Tron template engine.
//!
//! This module contains the [`TronTemplate`] struct, which represents a single
//! template with placeholders that can be filled with values and rendered to
//! produce final output.
//!
//! # Template Syntax
//!
//! Tron templates use a simple `@[placeholder]@` syntax:
//!
//! ```
//! use tron::TronTemplate;
//!
//! let mut template = TronTemplate::new(
//!     "fn @[name]@(@[params]@) -> @[return_type]@ {\n    @[body]@\n}"
//! ).unwrap();
//!
//! template.set("name", "add").unwrap();
//! template.set("params", "a: i32, b: i32").unwrap();
//! template.set("return_type", "i32").unwrap();
//! template.set("body", "a + b").unwrap();
//!
//! let result = template.render().unwrap();
//! assert_eq!(result, "fn add(a: i32, b: i32) -> i32 {\n    a + b\n}");
//! ```

use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use crate::error::{Result, TronError};
use glob::glob;
use walkdir::WalkDir;

/// A template with placeholders that can be filled and rendered.
///
/// `TronTemplate` represents a template string containing placeholders marked
/// with `@[name]@` syntax. These placeholders can be filled with values and
/// the template can be rendered to produce the final output.
///
/// # Examples
///
/// Basic template usage:
///
/// ```
/// use tron::TronTemplate;
///
/// let mut template = TronTemplate::new("Hello @[name]@!").unwrap();
/// template.set("name", "World").unwrap();
/// let result = template.render().unwrap();
/// assert_eq!(result, "Hello World!");
/// ```
///
/// Loading from file:
///
/// ```no_run
/// use tron::TronTemplate;
///
/// let template = TronTemplate::from_file("template.tpl").unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct TronTemplate {
    /// The original template content with placeholders
    content: String,
    /// Map of placeholder names to their current values
    placeholders: HashMap<String, String>,
    /// Optional file path if template was loaded from file
    path: Option<PathBuf>,
}

impl TronTemplate {
    /// Create a new template from a string.
    ///
    /// This parses the template content and extracts all placeholders marked
    /// with `@[name]@` syntax. The placeholders are initially empty and must
    /// be set before rendering.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TronTemplate;
    ///
    /// let template = TronTemplate::new("fn @[name]@() { @[body]@ }").unwrap();
    /// assert_eq!(template.placeholder_names().len(), 2);
    /// assert!(template.placeholder_names().contains(&"name".to_string()));
    /// assert!(template.placeholder_names().contains(&"body".to_string()));
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`TronError::InvalidSyntax`] if the template contains malformed
    /// placeholder syntax.
    pub fn new(content: &str) -> Result<Self> {
        let placeholders = Self::extract_placeholders(content)?;
        Ok(Self {
            content: content.to_string(),
            placeholders,
            path: None,
        })
    }

    /// Load a template from a file.
    ///
    /// This reads the file content and parses it as a template. The file path
    /// is stored for reference and debugging purposes.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tron::TronTemplate;
    /// use std::path::Path;
    ///
    /// let template = TronTemplate::from_file("templates/function.tpl").unwrap();
    /// assert_eq!(template.path(), Some(Path::new("templates/function.tpl")));
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`TronError::Io`] if the file cannot be read, or
    /// [`TronError::InvalidSyntax`] if the template syntax is invalid.
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let content = fs::read_to_string(&path)?;
        let mut template = Self::new(&content)?;
        template.path = Some(path.as_ref().to_path_buf());
        Ok(template)
    }

    /// Load multiple templates from a directory.
    ///
    /// This recursively searches a directory for template files with common
    /// extensions (.tron, .tpl, .template) and loads them all. The returned
    /// vector contains tuples of (filename, template).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tron::TronTemplate;
    ///
    /// let templates = TronTemplate::from_directory("templates/").unwrap();
    /// for (name, template) in templates {
    ///     println!("Loaded template: {}", name);
    ///     println!("Placeholders: {:?}", template.placeholder_names());
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`TronError::Io`] if the directory cannot be read or if any
    /// template files cannot be parsed.
    pub fn from_directory<P: AsRef<Path>>(dir: P) -> Result<Vec<(String, Self)>> {
        let mut templates = Vec::new();
        let dir_path = dir.as_ref();
        
        if !dir_path.is_dir() {
            return Err(TronError::Io(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("Directory not found: {}", dir_path.display())
            )));
        }

        for entry in WalkDir::new(dir_path) {
            let entry = entry.map_err(|e| TronError::Io(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to walk directory: {}", e)
            )))?;
            let path = entry.path();
            
            if path.is_file() {
                if let Some(extension) = path.extension() {
                    let ext_str = extension.to_string_lossy().to_lowercase();
                    if matches!(ext_str.as_str(), "tron" | "tpl" | "template") {
                        let template = Self::from_file(path)?;
                        let name = path.file_name()
                            .unwrap()
                            .to_string_lossy()
                            .to_string();
                        templates.push((name, template));
                    }
                }
            }
        }
        
        Ok(templates)
    }

    /// Load templates matching a glob pattern.
    ///
    /// This uses glob patterns to match template files and loads all matches.
    /// Common patterns include:
    /// - `"templates/*.tron"` - all .tron files in templates/
    /// - `"**/*.tpl"` - all .tpl files recursively
    /// - `"src/templates/**/api_*.tron"` - API templates in nested directories
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tron::TronTemplate;
    ///
    /// // Load all .tron files in templates directory
    /// let templates = TronTemplate::from_glob("templates/*.tron").unwrap();
    /// 
    /// // Load all template files recursively
    /// let all_templates = TronTemplate::from_glob("**/*.{tron,tpl,template}").unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`TronError::Io`] if glob pattern is invalid or if any matched
    /// files cannot be read or parsed.
    pub fn from_glob(pattern: &str) -> Result<Vec<(String, Self)>> {
        let mut templates = Vec::new();
        
        let glob_result = glob(pattern)
            .map_err(|e| TronError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!("Invalid glob pattern '{}': {}", pattern, e)
            )))?;

        for entry in glob_result {
            let path = entry.map_err(|e| TronError::Io(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Glob error: {}", e)
            )))?;
            if path.is_file() {
                let template = Self::from_file(&path)?;
                let name = path.file_name()
                    .unwrap()
                    .to_string_lossy()
                    .to_string();
                templates.push((name, template));
            }
        }
        
        Ok(templates)
    }

    /// Load templates from multiple sources.
    ///
    /// This is a convenience method that can load templates from files, directories,
    /// and glob patterns all at once. Each source is specified as a string that
    /// can be:
    /// - A file path (loads single template)
    /// - A directory path ending with '/' (loads all templates in directory)
    /// - A glob pattern containing '*' or '?' (loads matching templates)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tron::TronTemplate;
    ///
    /// let templates = TronTemplate::from_sources(&[
    ///     "templates/base.tron",          // single file
    ///     "templates/components/",        // directory
    ///     "templates/api/*.tron",         // glob pattern
    ///     "**/*.tpl",                     // recursive glob
    /// ]).unwrap();
    ///
    /// println!("Loaded {} templates", templates.len());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns error if any source cannot be loaded. Processing stops at first error.
    pub fn from_sources(sources: &[&str]) -> Result<Vec<(String, Self)>> {
        let mut all_templates = Vec::new();
        
        for source in sources {
            let mut templates = if source.ends_with('/') {
                // Directory path
                Self::from_directory(source)?
            } else if source.contains('*') || source.contains('?') {
                // Glob pattern
                Self::from_glob(source)?
            } else {
                // Single file
                let template = Self::from_file(source)?;
                let name = Path::new(source)
                    .file_name()
                    .unwrap()
                    .to_string_lossy()
                    .to_string();
                vec![(name, template)]
            };
            
            all_templates.append(&mut templates);
        }
        
        Ok(all_templates)
    }

    /// Get the file path if this template was loaded from a file.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TronTemplate;
    ///
    /// let template = TronTemplate::new("@[content]@").unwrap();
    /// assert_eq!(template.path(), None);
    /// ```
    pub fn path(&self) -> Option<&Path> {
        self.path.as_deref()
    }

    /// Get the original template content.
    ///
    /// This returns the template content with placeholders still in their
    /// original `@[name]@` form.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TronTemplate;
    ///
    /// let template = TronTemplate::new("Hello @[name]@!").unwrap();
    /// assert_eq!(template.content(), "Hello @[name]@!");
    /// ```
    pub fn content(&self) -> &str {
        &self.content
    }

    /// Get a list of all placeholder names in the template.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TronTemplate;
    ///
    /// let template = TronTemplate::new("@[greeting]@ @[name]@!").unwrap();
    /// let names = template.placeholder_names();
    /// assert_eq!(names.len(), 2);
    /// assert!(names.contains(&"greeting".to_string()));
    /// assert!(names.contains(&"name".to_string()));
    /// ```
    pub fn placeholder_names(&self) -> Vec<String> {
        self.placeholders.keys().cloned().collect()
    }

    /// Check if a placeholder exists in the template.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TronTemplate;
    ///
    /// let template = TronTemplate::new("Hello @[name]@!").unwrap();
    /// assert!(template.has_placeholder("name"));
    /// assert!(!template.has_placeholder("age"));
    /// ```
    pub fn has_placeholder(&self, name: &str) -> bool {
        self.placeholders.contains_key(name)
    }

    /// Get the current value of a placeholder.
    ///
    /// Returns `None` if the placeholder doesn't exist or hasn't been set.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TronTemplate;
    ///
    /// let mut template = TronTemplate::new("Hello @[name]@!").unwrap();
    /// assert_eq!(template.get("name"), Some(""));
    ///
    /// template.set("name", "World").unwrap();
    /// assert_eq!(template.get("name"), Some("World"));
    /// ```
    pub fn get(&self, placeholder: &str) -> Option<&str> {
        self.placeholders.get(placeholder).map(|s| s.as_str())
    }

    /// Set a placeholder value.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TronTemplate;
    ///
    /// let mut template = TronTemplate::new("Hello @[name]@!").unwrap();
    /// template.set("name", "World").unwrap();
    /// assert_eq!(template.get("name"), Some("World"));
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`TronError::MissingPlaceholder`] if the placeholder doesn't
    /// exist in the template.
    pub fn set(&mut self, placeholder: &str, value: &str) -> Result<()> {
        if !self.placeholders.contains_key(placeholder) {
            return Err(TronError::MissingPlaceholder(placeholder.to_string()));
        }
        self.placeholders.insert(placeholder.to_string(), value.to_string());
        Ok(())
    }

    /// Set multiple placeholder values at once.
    ///
    /// This is a convenience method for setting multiple placeholders from
    /// a map or iterator of key-value pairs.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TronTemplate;
    /// use std::collections::HashMap;
    ///
    /// let mut template = TronTemplate::new("@[greeting]@ @[name]@!").unwrap();
    /// 
    /// let mut values = HashMap::new();
    /// values.insert("greeting", "Hello");
    /// values.insert("name", "World");
    ///
    /// template.set_many(values).unwrap();
    /// assert_eq!(template.render().unwrap(), "Hello World!");
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`TronError::MissingPlaceholder`] if any placeholder doesn't
    /// exist in the template.
    pub fn set_many<K, V, I>(&mut self, values: I) -> Result<()>
    where
        K: AsRef<str>,
        V: AsRef<str>,
        I: IntoIterator<Item = (K, V)>,
    {
        for (key, value) in values {
            self.set(key.as_ref(), value.as_ref())?;
        }
        Ok(())
    }

    /// Clear the value of a placeholder.
    ///
    /// This sets the placeholder back to an empty string.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TronTemplate;
    ///
    /// let mut template = TronTemplate::new("Hello @[name]@!").unwrap();
    /// template.set("name", "World").unwrap();
    /// template.clear("name").unwrap();
    /// assert_eq!(template.get("name"), Some(""));
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`TronError::MissingPlaceholder`] if the placeholder doesn't
    /// exist in the template.
    pub fn clear(&mut self, placeholder: &str) -> Result<()> {
        self.set(placeholder, "")
    }

    /// Check if all placeholders have been set to non-empty values.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TronTemplate;
    ///
    /// let mut template = TronTemplate::new("@[greeting]@ @[name]@!").unwrap();
    /// assert!(!template.is_complete());
    ///
    /// template.set("greeting", "Hello").unwrap();
    /// assert!(!template.is_complete());
    ///
    /// template.set("name", "World").unwrap();
    /// assert!(template.is_complete());
    /// ```
    pub fn is_complete(&self) -> bool {
        self.placeholders.values().all(|v| !v.is_empty())
    }

    /// Get a list of placeholders that haven't been set to non-empty values.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TronTemplate;
    ///
    /// let mut template = TronTemplate::new("@[greeting]@ @[name]@!").unwrap();
    /// let missing = template.missing_placeholders();
    /// assert_eq!(missing.len(), 2);
    ///
    /// template.set("greeting", "Hello").unwrap();
    /// let missing = template.missing_placeholders();
    /// assert_eq!(missing, vec!["name"]);
    /// ```
    pub fn missing_placeholders(&self) -> Vec<String> {
        self.placeholders
            .iter()
            .filter_map(|(k, v)| if v.is_empty() { Some(k.clone()) } else { None })
            .collect()
    }

    /// Render the template to a string.
    ///
    /// This replaces all placeholders with their values and returns the
    /// resulting string.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TronTemplate;
    ///
    /// let mut template = TronTemplate::new("fn @[name]@() {\n    @[body]@\n}").unwrap();
    /// template.set("name", "greet").unwrap();
    /// template.set("body", "println!(\"Hello!\");").unwrap();
    ///
    /// let result = template.render().unwrap();
    /// assert_eq!(result, "fn greet() {\n    println!(\"Hello!\");\n}");
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`TronError::MissingPlaceholder`] if any placeholder hasn't
    /// been set to a non-empty value.
    pub fn render(&self) -> Result<String> {
        let mut result = self.content.clone();
        
        for (placeholder, value) in &self.placeholders {
            let pattern = format!("@[{}]@", placeholder);
            if value.is_empty() {
                return Err(TronError::MissingPlaceholder(placeholder.clone()));
            }
            result = result.replace(&pattern, value);
        }
        
        Ok(result)
    }

    /// Render the template with partial placeholder filling.
    ///
    /// This is like [`render`] but doesn't require all placeholders to be filled.
    /// Unfilled placeholders remain as `@[name]@` in the output.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TronTemplate;
    ///
    /// let mut template = TronTemplate::new("Hello @[greeting]@ @[name]@!").unwrap();
    /// template.set("greeting", "Hi").unwrap();
    /// // name is not set
    ///
    /// let result = template.render_partial().unwrap();
    /// assert_eq!(result, "Hello Hi @[name]@!");
    /// ```
    pub fn render_partial(&self) -> Result<String> {
        let mut result = self.content.clone();
        
        for (placeholder, value) in &self.placeholders {
            if !value.is_empty() {
                let pattern = format!("@[{}]@", placeholder);
                result = result.replace(&pattern, value);
            }
        }
        
        Ok(result)
    }

    /// Extract placeholder names from template content.
    fn extract_placeholders(content: &str) -> Result<HashMap<String, String>> {
        let mut placeholders = HashMap::new();
        let pattern = regex::Regex::new(r"@\[([^]]+)\]@").unwrap();
        
        for capture in pattern.captures_iter(content) {
            let placeholder = capture.get(1).unwrap().as_str().trim();
            
            // Validate placeholder name
            if placeholder.is_empty() {
                return Err(TronError::InvalidSyntax("Empty placeholder name".to_string()));
            }
            
            if placeholder.contains(char::is_whitespace) {
                return Err(TronError::InvalidSyntax(
                    format!("Placeholder name '{}' contains whitespace", placeholder)
                ));
            }
            
            placeholders.insert(placeholder.to_string(), String::new());
        }
        
        Ok(placeholders)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn test_new_template() -> Result<()> {
        let template = TronTemplate::new("Hello @[name]@!")?;
        assert_eq!(template.content(), "Hello @[name]@!");
        assert!(template.has_placeholder("name"));
        assert_eq!(template.placeholder_names().len(), 1);
        Ok(())
    }

    #[test]
    fn test_set_and_get() -> Result<()> {
        let mut template = TronTemplate::new("Hello @[name]@!")?;
        assert_eq!(template.get("name"), Some(""));
        
        template.set("name", "World")?;
        assert_eq!(template.get("name"), Some("World"));
        Ok(())
    }

    #[test]
    fn test_set_many() -> Result<()> {
        let mut template = TronTemplate::new("@[greeting]@ @[name]@!")?;
        
        let mut values = HashMap::new();
        values.insert("greeting", "Hello");
        values.insert("name", "World");
        
        template.set_many(values)?;
        assert_eq!(template.get("greeting"), Some("Hello"));
        assert_eq!(template.get("name"), Some("World"));
        Ok(())
    }

    #[test]
    fn test_render() -> Result<()> {
        let mut template = TronTemplate::new("Hello @[name]@!")?;
        template.set("name", "World")?;
        
        let result = template.render()?;
        assert_eq!(result, "Hello World!");
        Ok(())
    }

    #[test]
    fn test_render_partial() -> Result<()> {
        let mut template = TronTemplate::new("@[greeting]@ @[name]@!")?;
        template.set("greeting", "Hello")?;
        
        let result = template.render_partial()?;
        assert_eq!(result, "Hello @[name]@!");
        Ok(())
    }

    #[test]
    fn test_missing_placeholder_error() {
        let mut template = TronTemplate::new("Hello @[name]@!").unwrap();
        let result = template.set("nonexistent", "value");
        assert!(matches!(result, Err(TronError::MissingPlaceholder(_))));
    }

    #[test]
    fn test_incomplete_render_error() {
        let template = TronTemplate::new("Hello @[name]@!").unwrap();
        let result = template.render();
        assert!(matches!(result, Err(TronError::MissingPlaceholder(_))));
    }

    #[test]
    fn test_is_complete() -> Result<()> {
        let mut template = TronTemplate::new("@[a]@ @[b]@")?;
        assert!(!template.is_complete());
        
        template.set("a", "1")?;
        assert!(!template.is_complete());
        
        template.set("b", "2")?;
        assert!(template.is_complete());
        Ok(())
    }

    #[test]
    fn test_missing_placeholders() -> Result<()> {
        let mut template = TronTemplate::new("@[a]@ @[b]@ @[c]@")?;
        
        let missing = template.missing_placeholders();
        assert_eq!(missing.len(), 3);
        
        template.set("a", "1")?;
        let missing = template.missing_placeholders();
        assert_eq!(missing.len(), 2);
        assert!(!missing.contains(&"a".to_string()));
        Ok(())
    }

    #[test]
    fn test_invalid_syntax() {
        // Test that empty brackets are handled properly (should result in no placeholders)
        let result = TronTemplate::new("@[]@");
        assert!(result.is_ok()); // This doesn't match the regex pattern, so no placeholders are extracted
        
        let result = TronTemplate::new("@[invalid name]@");
        assert!(matches!(result, Err(TronError::InvalidSyntax(_))));
        
        // Valid syntax should work
        let result = TronTemplate::new("@[valid_name]@");
        assert!(result.is_ok());
        
        // Test actual empty placeholder that would be matched
        let result = TronTemplate::new("@[ ]@"); // Space that gets trimmed to empty
        assert!(matches!(result, Err(TronError::InvalidSyntax(_))));
    }

    #[test]
    fn test_complex_template() -> Result<()> {
        let mut template = TronTemplate::new(
            "fn @[name]@(@[params]@) -> @[return_type]@ {\n    @[body]@\n}"
        )?;
        
        template.set("name", "add")?;
        template.set("params", "a: i32, b: i32")?;
        template.set("return_type", "i32")?;
        template.set("body", "a + b")?;
        
        let result = template.render()?;
        let expected = "fn add(a: i32, b: i32) -> i32 {\n    a + b\n}";
        assert_eq!(result, expected);
        Ok(())
    }

    #[test]
    #[cfg(test)]
    fn test_from_directory() -> Result<()> {
        // This test will work with our templates/ directory
        let templates = TronTemplate::from_directory("templates")?;
        
        // Should load several templates from our templates directory
        assert!(!templates.is_empty());
        
        // Check that we have some expected templates
        let template_names: Vec<&String> = templates.iter().map(|(name, _)| name).collect();
        assert!(template_names.iter().any(|&name| name.contains("rust_function")));
        
        Ok(())
    }

    #[test] 
    #[cfg(test)]
    fn test_from_glob() -> Result<()> {
        // Test loading templates with glob pattern
        let templates = TronTemplate::from_glob("templates/*.tron")?;
        
        // Should load .tron files from templates directory
        assert!(!templates.is_empty());
        
        // All loaded templates should have .tron extension in their names
        for (name, _template) in &templates {
            assert!(name.ends_with(".tron"));
        }
        
        Ok(())
    }

    #[test]
    #[cfg(test)]
    fn test_from_sources() -> Result<()> {
        let templates = TronTemplate::from_sources(&[
            "templates/",           // directory
            "templates/*.tpl",      // glob pattern
        ])?;
        
        // Should load templates from both sources
        assert!(!templates.is_empty());
        
        // Should include both .tron files from directory and .tpl files from glob
        let has_tron = templates.iter().any(|(name, _)| name.ends_with(".tron"));
        let has_tpl = templates.iter().any(|(name, _)| name.ends_with(".tpl"));
        
        assert!(has_tron); // From directory loading
        assert!(has_tpl);  // From glob pattern
        
        Ok(())
    }

    #[test]
    fn test_invalid_directory() {
        let result = TronTemplate::from_directory("nonexistent_directory");
        assert!(matches!(result, Err(TronError::Io(_))));
    }

    #[test]
    fn test_invalid_glob_pattern() {
        // Test with invalid glob pattern
        let result = TronTemplate::from_glob("[invalid");
        assert!(matches!(result, Err(TronError::Io(_))));
    }
}