Skip to main content

padlock_source/
fixgen.rs

1// padlock-source/src/fixgen.rs
2//
3// Generate reordered struct source text, unified diffs, and in-place rewrites.
4
5use padlock_core::ir::{StructLayout, optimal_order};
6use similar::{ChangeTag, TextDiff};
7
8/// Render a reordered C/C++ struct definition as source text.
9///
10/// Uses the field names already present in the layout — type names come from
11/// the `TypeInfo::Primitive/Opaque` name stored during source parsing.
12pub fn generate_c_fix(layout: &StructLayout) -> String {
13    let optimal = optimal_order(layout);
14    let mut out = format!("struct {} {{\n", layout.name);
15    for field in &optimal {
16        let ty = field_type_name(field);
17        out.push_str(&format!("    {ty} {};\n", field.name));
18    }
19    out.push_str("};\n");
20    out
21}
22
23/// Render a reordered Rust struct definition as source text.
24pub fn generate_rust_fix(layout: &StructLayout) -> String {
25    let optimal = optimal_order(layout);
26    let mut out = format!("struct {} {{\n", layout.name);
27    for field in &optimal {
28        let ty = field_type_name(field);
29        out.push_str(&format!("    {}: {ty},\n", field.name));
30    }
31    out.push_str("}\n");
32    out
33}
34
35/// Render a reordered Go struct definition as source text.
36pub fn generate_go_fix(layout: &StructLayout) -> String {
37    let optimal = optimal_order(layout);
38    let mut out = format!("type {} struct {{\n", layout.name);
39    for field in &optimal {
40        let ty = field_type_name(field);
41        out.push_str(&format!("\t{}\t{ty}\n", field.name));
42    }
43    out.push_str("}\n");
44    out
45}
46
47/// Produce a unified diff between `original` and `fixed` source text.
48pub fn unified_diff(original: &str, fixed: &str, context_lines: usize) -> String {
49    if original == fixed {
50        return String::from("(no changes)\n");
51    }
52    let diff = TextDiff::from_lines(original, fixed);
53    let mut out = String::new();
54    for (idx, group) in diff.grouped_ops(context_lines).iter().enumerate() {
55        if idx > 0 {
56            out.push_str("...\n");
57        }
58        for op in group {
59            for change in diff.iter_changes(op) {
60                let prefix = match change.tag() {
61                    ChangeTag::Delete => "-",
62                    ChangeTag::Insert => "+",
63                    ChangeTag::Equal => " ",
64                };
65                out.push_str(&format!("{prefix} {}", change.value()));
66                if !change.value().ends_with('\n') {
67                    out.push('\n');
68                }
69            }
70        }
71    }
72    out
73}
74
75// ── span finders ──────────────────────────────────────────────────────────────
76
77/// Count matching braces from the start of `s` (which must begin with `{`).
78/// Returns the byte index one past the matching `}`.
79fn match_braces(s: &str) -> Option<usize> {
80    let mut depth = 0usize;
81    for (i, c) in s.char_indices() {
82        match c {
83            '{' => depth += 1,
84            '}' => {
85                depth -= 1;
86                if depth == 0 {
87                    return Some(i + 1);
88                }
89            }
90            _ => {}
91        }
92    }
93    None
94}
95
96/// Consume an optional trailing semicolon (after optional whitespace) at `pos`.
97fn consume_semicolon(source: &str, pos: usize) -> usize {
98    let rest = &source[pos..];
99    let ws = rest.len()
100        - rest
101            .trim_start_matches(|c: char| c.is_whitespace() && c != '\n')
102            .len();
103    let after_ws = &rest[ws..];
104    if after_ws.starts_with(';') {
105        pos + ws + 1
106    } else {
107        pos
108    }
109}
110
111/// Find the byte range of a named struct/union in C/C++ source.
112/// The range covers from `struct/union Name` through the closing `};`.
113pub fn find_c_struct_span(source: &str, struct_name: &str) -> Option<std::ops::Range<usize>> {
114    for kw in &["struct", "union"] {
115        let needle = format!("{kw} {struct_name}");
116        let mut search_from = 0usize;
117        while let Some(rel) = source[search_from..].find(&needle) {
118            let start = search_from + rel;
119            let after_name = start + needle.len();
120            // Ensure the character after the name is a boundary (space, `{`, newline)
121            let boundary = source[after_name..].chars().next();
122            if matches!(
123                boundary,
124                Some('{') | Some('\n') | Some('\r') | Some(' ') | Some('\t') | None
125            ) {
126                // Find the opening brace (may have whitespace between name and `{`)
127                if let Some(brace_rel) = source[after_name..].find('{') {
128                    let brace_start = after_name + brace_rel;
129                    // Verify no word characters between name end and brace
130                    if source[after_name..brace_start]
131                        .chars()
132                        .all(|c| c.is_whitespace())
133                        && let Some(body_len) = match_braces(&source[brace_start..])
134                    {
135                        let end = consume_semicolon(source, brace_start + body_len);
136                        return Some(start..end);
137                    }
138                }
139            }
140            search_from = start + 1;
141        }
142    }
143    None
144}
145
146/// Find the byte range of a named struct in Rust source (`struct Name { ... }`).
147pub fn find_rust_struct_span(source: &str, struct_name: &str) -> Option<std::ops::Range<usize>> {
148    let needle = format!("struct {struct_name}");
149    let mut search_from = 0usize;
150    while let Some(rel) = source[search_from..].find(&needle) {
151        let start = search_from + rel;
152        let after_name = start + needle.len();
153        let boundary = source[after_name..].chars().next();
154        if matches!(
155            boundary,
156            Some('{') | Some('\n') | Some('\r') | Some(' ') | Some('\t') | None
157        ) && let Some(brace_rel) = source[after_name..].find('{')
158        {
159            let brace_start = after_name + brace_rel;
160            if source[after_name..brace_start]
161                .chars()
162                .all(|c| c.is_whitespace())
163                && let Some(body_len) = match_braces(&source[brace_start..])
164            {
165                // Rust structs have no trailing `;` (unit structs do, but we skip those)
166                return Some(start..brace_start + body_len);
167            }
168        }
169        search_from = start + 1;
170    }
171    None
172}
173
174/// Find the byte range of a named struct in Go source (`type Name struct { ... }`).
175pub fn find_go_struct_span(source: &str, struct_name: &str) -> Option<std::ops::Range<usize>> {
176    let needle = format!("type {struct_name} struct");
177    let mut search_from = 0usize;
178    while let Some(rel) = source[search_from..].find(&needle) {
179        let start = search_from + rel;
180        let after_kw = start + needle.len();
181        if let Some(brace_rel) = source[after_kw..].find('{') {
182            let brace_start = after_kw + brace_rel;
183            if source[after_kw..brace_start]
184                .chars()
185                .all(|c| c.is_whitespace())
186                && let Some(body_len) = match_braces(&source[brace_start..])
187            {
188                return Some(start..brace_start + body_len);
189            }
190        }
191        search_from = start + 1;
192    }
193    None
194}
195
196// ── in-place rewriters ────────────────────────────────────────────────────────
197
198/// Apply C/C++ struct reorderings in-place, returning the modified source.
199/// Each layout in `layouts` is looked up by name; matched structs are replaced
200/// with the optimally-ordered definition. Replacements are applied back-to-front
201/// so byte offsets remain valid.
202pub fn apply_fixes_c(source: &str, layouts: &[&StructLayout]) -> String {
203    apply_fixes(source, layouts, find_c_struct_span, generate_c_fix)
204}
205
206/// Apply Rust struct reorderings in-place, returning the modified source.
207pub fn apply_fixes_rust(source: &str, layouts: &[&StructLayout]) -> String {
208    apply_fixes(source, layouts, find_rust_struct_span, generate_rust_fix)
209}
210
211/// Apply Go struct reorderings in-place, returning the modified source.
212pub fn apply_fixes_go(source: &str, layouts: &[&StructLayout]) -> String {
213    apply_fixes(source, layouts, find_go_struct_span, generate_go_fix)
214}
215
216fn apply_fixes(
217    source: &str,
218    layouts: &[&StructLayout],
219    find_span: fn(&str, &str) -> Option<std::ops::Range<usize>>,
220    generate: fn(&StructLayout) -> String,
221) -> String {
222    // Collect (start, end, replacement) for each matching layout
223    let mut replacements: Vec<(usize, usize, String)> = layouts
224        .iter()
225        .filter_map(|layout| {
226            let span = find_span(source, &layout.name)?;
227            let fixed = generate(layout);
228            Some((span.start, span.end, fixed))
229        })
230        .collect();
231
232    // Sort by start offset ascending, then apply in reverse so offsets stay valid
233    replacements.sort_by_key(|(start, _, _)| *start);
234
235    let mut result = source.to_string();
236    for (start, end, fixed) in replacements.into_iter().rev() {
237        result.replace_range(start..end, &fixed);
238    }
239    result
240}
241
242fn field_type_name(field: &padlock_core::ir::Field) -> &str {
243    match &field.ty {
244        padlock_core::ir::TypeInfo::Primitive { name, .. }
245        | padlock_core::ir::TypeInfo::Opaque { name, .. } => name.as_str(),
246        padlock_core::ir::TypeInfo::Pointer { .. } => "void*",
247        padlock_core::ir::TypeInfo::Array { .. } => "/* array */",
248        padlock_core::ir::TypeInfo::Struct(l) => l.name.as_str(),
249    }
250}
251
252// ── tests ─────────────────────────────────────────────────────────────────────
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257    use padlock_core::ir::test_fixtures::connection_layout;
258
259    #[test]
260    fn c_fix_starts_with_struct() {
261        let out = generate_c_fix(&connection_layout());
262        assert!(out.starts_with("struct Connection {"));
263    }
264
265    #[test]
266    fn c_fix_contains_all_fields() {
267        let out = generate_c_fix(&connection_layout());
268        assert!(out.contains("timeout"));
269        assert!(out.contains("port"));
270        assert!(out.contains("is_active"));
271        assert!(out.contains("is_tls"));
272    }
273
274    #[test]
275    fn c_fix_puts_largest_align_first() {
276        let out = generate_c_fix(&connection_layout());
277        let timeout_pos = out.find("timeout").unwrap();
278        let is_active_pos = out.find("is_active").unwrap();
279        assert!(timeout_pos < is_active_pos);
280    }
281
282    #[test]
283    fn rust_fix_uses_colon_syntax() {
284        let out = generate_rust_fix(&connection_layout());
285        assert!(out.contains(": f64"));
286    }
287
288    #[test]
289    fn unified_diff_marks_changes() {
290        let orig = "struct T { char a; double b; };\n";
291        let fixed = "struct T { double b; char a; };\n";
292        let diff = unified_diff(orig, fixed, 1);
293        assert!(diff.contains('-') || diff.contains('+'));
294    }
295
296    #[test]
297    fn unified_diff_identical_is_no_changes() {
298        assert_eq!(unified_diff("x\n", "x\n", 3), "(no changes)\n");
299    }
300
301    // ── span finders ──────────────────────────────────────────────────────────
302
303    #[test]
304    fn find_c_struct_span_basic() {
305        let src = "struct Foo { int x; char y; };\nstruct Bar { double z; };\n";
306        let span = find_c_struct_span(src, "Foo").unwrap();
307        let text = &src[span];
308        assert!(text.starts_with("struct Foo"));
309        assert!(!text.contains("Bar"));
310    }
311
312    #[test]
313    fn find_c_struct_span_missing_returns_none() {
314        let src = "struct Other { int x; };";
315        assert!(find_c_struct_span(src, "Missing").is_none());
316    }
317
318    #[test]
319    fn find_rust_struct_span_basic() {
320        let src = "struct Foo {\n    x: u32,\n    y: u8,\n}\n";
321        let span = find_rust_struct_span(src, "Foo").unwrap();
322        assert!(src[span].starts_with("struct Foo"));
323    }
324
325    #[test]
326    fn find_go_struct_span_basic() {
327        let src = "type Foo struct {\n\tX int32\n\tY bool\n}\n";
328        let span = find_go_struct_span(src, "Foo").unwrap();
329        assert!(src[span].starts_with("type Foo struct"));
330    }
331
332    // ── apply_fixes ───────────────────────────────────────────────────────────
333
334    #[test]
335    fn apply_fixes_c_reorders_in_place() {
336        // Connection has char/double/char/int — after fix, double should come first
337        let src = "struct Connection { bool is_active; double timeout; bool is_tls; int port; };\n";
338        let layout = connection_layout();
339        let fixed = apply_fixes_c(src, &[&layout]);
340        let timeout_pos = fixed.find("timeout").unwrap();
341        let is_active_pos = fixed.find("is_active").unwrap();
342        assert!(
343            timeout_pos < is_active_pos,
344            "double should appear before bool after reorder"
345        );
346    }
347
348    #[test]
349    fn apply_fixes_rust_reorders_in_place() {
350        let src = "struct Connection {\n    is_active: bool,\n    timeout: f64,\n    is_tls: bool,\n    port: i32,\n}\n";
351        let layout = connection_layout();
352        let fixed = apply_fixes_rust(src, &[&layout]);
353        let timeout_pos = fixed.find("timeout").unwrap();
354        let is_active_pos = fixed.find("is_active").unwrap();
355        assert!(timeout_pos < is_active_pos);
356    }
357
358    #[test]
359    fn go_fix_uses_tab_syntax() {
360        let layout = connection_layout();
361        let out = generate_go_fix(&layout);
362        assert!(out.starts_with("type Connection struct"));
363        assert!(out.contains('\t'));
364    }
365}