Skip to main content

agentic_evolve_core/crystallization/
template_generator.rs

1//! TemplateGenerator — generates templates from code and detected variables.
2
3use crate::types::pattern::PatternVariable;
4
5/// Generates pattern templates by replacing variable parts with placeholders.
6#[derive(Debug, Default)]
7pub struct TemplateGenerator;
8
9impl TemplateGenerator {
10    pub fn new() -> Self {
11        Self
12    }
13
14    pub fn generate(&self, code: &str, variables: &[PatternVariable]) -> String {
15        let mut template = code.to_string();
16
17        for var in variables {
18            if let Some(default) = &var.default {
19                if !default.is_empty() {
20                    let placeholder = format!("{{{{{}}}}}", var.name);
21                    template = template.replacen(default, &placeholder, 1);
22                }
23            }
24        }
25
26        template
27    }
28
29    pub fn apply_bindings(
30        &self,
31        template: &str,
32        bindings: &std::collections::HashMap<String, String>,
33    ) -> String {
34        let mut result = template.to_string();
35        for (key, value) in bindings {
36            let placeholder = format!("{{{{{key}}}}}");
37            result = result.replace(&placeholder, value);
38        }
39        result
40    }
41
42    pub fn extract_placeholders(&self, template: &str) -> Vec<String> {
43        let re = regex::Regex::new(r"\{\{(\w+)\}\}").unwrap();
44        re.captures_iter(template)
45            .map(|cap| cap[1].to_string())
46            .collect()
47    }
48
49    pub fn has_unbound_placeholders(&self, template: &str) -> bool {
50        template.contains("{{") && template.contains("}}")
51    }
52}