Skip to main content

harn_rules/
fix.rs

1//! `fix` template interpolation and application.
2//!
3//! A `fix` is a replacement template that interpolates the match's
4//! metavars — both the captured `$VAR`s and any `transform`-synthesized
5//! ones — into replacement text. The engine computes one replacement per
6//! match and splices them into the source (format-preserving byte-splice,
7//! the same guarantee as `ast.batch_apply`).
8
9use std::collections::BTreeMap;
10
11use crate::engine::Span;
12
13/// Interpolate `$VAR` / `${VAR}` references in `template` from `vars`.
14/// An unknown reference is left verbatim (so a literal `$` survives), and
15/// `$$` is an escaped literal dollar sign.
16pub fn interpolate(template: &str, vars: &BTreeMap<String, String>) -> String {
17    let bytes = template.as_bytes();
18    let mut out = String::with_capacity(template.len());
19    let mut i = 0;
20    while i < bytes.len() {
21        if bytes[i] != b'$' {
22            let ch = template[i..].chars().next().unwrap();
23            out.push(ch);
24            i += ch.len_utf8();
25            continue;
26        }
27        // `$$` -> literal `$`.
28        if template[i..].starts_with("$$") {
29            out.push('$');
30            i += 2;
31            continue;
32        }
33        // `${NAME}` braced form.
34        let (name, consumed) = if template[i..].starts_with("${") {
35            match template[i + 2..].find('}') {
36                Some(rel) => (&template[i + 2..i + 2 + rel], 2 + rel + 1),
37                None => {
38                    out.push('$');
39                    i += 1;
40                    continue;
41                }
42            }
43        } else {
44            // `$NAME` bare form.
45            let name_start = i + 1;
46            let mut j = name_start;
47            if j < bytes.len() && is_ident_start(bytes[j]) {
48                j += 1;
49                while j < bytes.len() && is_ident_continue(bytes[j]) {
50                    j += 1;
51                }
52            }
53            (&template[name_start..j], j - i)
54        };
55
56        if name.is_empty() {
57            out.push('$');
58            i += 1;
59            continue;
60        }
61        match vars.get(name) {
62            Some(value) => out.push_str(value),
63            // Unknown metavar: keep the reference literal.
64            None => out.push_str(&template[i..i + consumed]),
65        }
66        i += consumed;
67    }
68    out
69}
70
71fn is_ident_start(b: u8) -> bool {
72    b.is_ascii_alphabetic() || b == b'_'
73}
74
75fn is_ident_continue(b: u8) -> bool {
76    b.is_ascii_alphanumeric() || b == b'_'
77}
78
79/// One concrete edit: replace `span`'s bytes (`before`) with `replacement`.
80#[derive(Debug, Clone)]
81pub struct AppliedEdit {
82    /// The replaced span.
83    pub span: Span,
84    /// The original text at the span.
85    pub before: String,
86    /// The interpolated replacement text.
87    pub replacement: String,
88}
89
90/// Apply `edits` to `source` by byte-splice. Edits are spliced in reverse
91/// start order so earlier offsets stay valid; whitespace outside each span
92/// is preserved verbatim.
93pub fn splice(source: &str, edits: &[AppliedEdit]) -> String {
94    let mut ordered: Vec<&AppliedEdit> = edits.iter().collect();
95    ordered.sort_by_key(|e| std::cmp::Reverse(e.span.start_byte));
96    let mut out = source.to_string();
97    for edit in ordered {
98        out.replace_range(edit.span.start_byte..edit.span.end_byte, &edit.replacement);
99    }
100    out
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    fn vars(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
108        pairs
109            .iter()
110            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
111            .collect()
112    }
113
114    #[test]
115    fn interpolates_bare_and_braced() {
116        let v = vars(&[("KEY", "userId"), ("NAME", "id")]);
117        assert_eq!(interpolate("{ $KEY: $NAME }", &v), "{ userId: id }");
118        assert_eq!(interpolate("${KEY}_${NAME}", &v), "userId_id");
119    }
120
121    #[test]
122    fn unknown_metavar_left_literal() {
123        let v = vars(&[("KEY", "x")]);
124        assert_eq!(interpolate("$KEY $UNKNOWN", &v), "x $UNKNOWN");
125    }
126
127    #[test]
128    fn escaped_dollar() {
129        let v = vars(&[]);
130        assert_eq!(interpolate("price is $$5", &v), "price is $5");
131    }
132
133    #[test]
134    fn splices_in_reverse_order() {
135        let source = "aaa bbb ccc";
136        let edits = vec![
137            AppliedEdit {
138                span: Span {
139                    start_byte: 0,
140                    end_byte: 3,
141                    start_row: 0,
142                    start_col: 0,
143                    end_row: 0,
144                    end_col: 3,
145                },
146                before: "aaa".into(),
147                replacement: "X".into(),
148            },
149            AppliedEdit {
150                span: Span {
151                    start_byte: 8,
152                    end_byte: 11,
153                    start_row: 0,
154                    start_col: 8,
155                    end_row: 0,
156                    end_col: 11,
157                },
158                before: "ccc".into(),
159                replacement: "ZZZZ".into(),
160            },
161        ];
162        assert_eq!(splice(source, &edits), "X bbb ZZZZ");
163    }
164}