Skip to main content

vexil_codegen_ts/
emit.rs

1/// Helper for emitting formatted TypeScript 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    /// Increase indentation.
35    pub fn indent(&mut self) {
36        self.indent += 1;
37    }
38
39    /// Decrease indentation.
40    pub fn dedent(&mut self) {
41        self.indent = self.indent.saturating_sub(1);
42    }
43
44    /// Write an opening brace line and indent.
45    pub fn open_block(&mut self, prefix: &str) {
46        self.line(&format!("{prefix} {{"));
47        self.indent();
48    }
49
50    /// Dedent and write closing brace.
51    pub fn close_block(&mut self) {
52        self.dedent();
53        self.line("}");
54    }
55
56    /// Emit an empty line.
57    pub fn blank(&mut self) {
58        self.buf.push('\n');
59    }
60
61    /// Consume and return the built string.
62    pub fn finish(self) -> String {
63        self.buf
64    }
65}