Skip to main content

vexil_codegen_rust/
emit.rs

1/// Helper for emitting formatted Rust source code with indentation management.
2pub struct CodeWriter {
3    buf: String,
4    indent: usize,
5}
6
7impl Default for CodeWriter {
8    fn default() -> Self {
9        Self::new()
10    }
11}
12
13impl CodeWriter {
14    pub fn new() -> Self {
15        Self {
16            buf: String::new(),
17            indent: 0,
18        }
19    }
20
21    /// Write a line with current indentation.
22    pub fn line(&mut self, text: &str) {
23        if text.is_empty() {
24            self.buf.push('\n');
25        } else {
26            for _ in 0..self.indent {
27                self.buf.push_str("    ");
28            }
29            self.buf.push_str(text);
30            self.buf.push('\n');
31        }
32    }
33
34    /// Write text without trailing newline (for partial lines).
35    pub fn write(&mut self, text: &str) {
36        for _ in 0..self.indent {
37            self.buf.push_str("    ");
38        }
39        self.buf.push_str(text);
40    }
41
42    /// Append text to current line (no indentation).
43    pub fn append(&mut self, text: &str) {
44        self.buf.push_str(text);
45    }
46
47    /// Increase indentation.
48    pub fn indent(&mut self) {
49        self.indent += 1;
50    }
51
52    /// Decrease indentation.
53    pub fn dedent(&mut self) {
54        self.indent = self.indent.saturating_sub(1);
55    }
56
57    /// Write an opening brace line and indent.
58    pub fn open_block(&mut self, prefix: &str) {
59        self.line(&format!("{prefix} {{"));
60        self.indent();
61    }
62
63    /// Dedent and write closing brace.
64    pub fn close_block(&mut self) {
65        self.dedent();
66        self.line("}");
67    }
68
69    /// Emit an empty line.
70    pub fn blank(&mut self) {
71        self.buf.push('\n');
72    }
73
74    /// Consume and return the built string.
75    pub fn finish(self) -> String {
76        self.buf
77    }
78}