Skip to main content

unitype_codegen/
writer.rs

1//! Building up a file of generated code.
2//!
3//! Nothing clever — an indented string builder. It exists so that indentation
4//! is tracked in one place rather than threaded through every emitter, and so
5//! that every generated file ends the same way: newline-terminated, no trailing
6//! blank lines, no stray whitespace at the end of a line.
7//!
8//! That tidiness matters more than it sounds. Generated files get committed and
9//! diffed, and a file that regenerates with invisible differences makes every
10//! diff useless.
11
12use std::fmt::Write as _;
13
14/// An indented buffer of generated code.
15#[derive(Debug, Default)]
16pub struct CodeWriter {
17    out: String,
18    depth: usize,
19    unit: &'static str,
20}
21
22impl CodeWriter {
23    /// A writer indenting by four spaces.
24    pub fn new() -> Self {
25        Self::with_indent("    ")
26    }
27
28    /// A writer indenting by something else.
29    pub fn with_indent(unit: &'static str) -> Self {
30        Self {
31            out: String::new(),
32            depth: 0,
33            unit,
34        }
35    }
36
37    /// Writes one line at the current indentation.
38    ///
39    /// An empty line stays empty rather than becoming indentation, since
40    /// trailing whitespace is exactly the kind of invisible difference that
41    /// makes a regenerated file look changed when it is not.
42    pub fn line(&mut self, text: impl AsRef<str>) {
43        let text = text.as_ref();
44        if text.is_empty() {
45            self.out.push('\n');
46            return;
47        }
48        for _ in 0..self.depth {
49            self.out.push_str(self.unit);
50        }
51        self.out.push_str(text.trim_end());
52        self.out.push('\n');
53    }
54
55    /// Writes a formatted line.
56    pub fn write(&mut self, args: std::fmt::Arguments<'_>) {
57        let mut text = String::new();
58        let _ = text.write_fmt(args);
59        self.line(text);
60    }
61
62    /// A blank line, unless the buffer is empty or already ends with one.
63    pub fn blank(&mut self) {
64        if self.out.is_empty() || self.out.ends_with("\n\n") {
65            return;
66        }
67        self.out.push('\n');
68    }
69
70    /// Writes prose as a comment, wrapped, with each line prefixed.
71    pub fn comment(&mut self, prefix: &str, text: &str) {
72        for line in wrap(text, 76_usize.saturating_sub(self.depth * self.unit.len())) {
73            if line.is_empty() {
74                self.line(prefix.trim_end());
75            } else {
76                self.line(format!("{prefix}{line}"));
77            }
78        }
79    }
80
81    /// Runs `body` one level further in.
82    pub fn indented(&mut self, body: impl FnOnce(&mut Self)) {
83        self.depth += 1;
84        body(self);
85        self.depth -= 1;
86    }
87
88    /// Opens a block, writes its contents indented, and closes it.
89    pub fn block(&mut self, open: impl AsRef<str>, close: &str, body: impl FnOnce(&mut Self)) {
90        self.line(open);
91        self.indented(body);
92        self.line(close);
93    }
94
95    /// Whether nothing has been written.
96    pub fn is_empty(&self) -> bool {
97        self.out.is_empty()
98    }
99
100    /// The finished file: newline-terminated, with no trailing blank lines.
101    pub fn finish(self) -> String {
102        let trimmed = self.out.trim_end();
103        if trimmed.is_empty() {
104            String::new()
105        } else {
106            format!("{trimmed}\n")
107        }
108    }
109}
110
111/// Breaks prose into lines no longer than `width`, keeping paragraph breaks.
112///
113/// A word longer than the width goes on its own line rather than being cut:
114/// a generated type name is not improved by hyphenation.
115fn wrap(text: &str, width: usize) -> Vec<String> {
116    let mut out = Vec::new();
117    for paragraph in text.split('\n') {
118        if paragraph.trim().is_empty() {
119            out.push(String::new());
120            continue;
121        }
122        let mut line = String::new();
123        for word in paragraph.split_whitespace() {
124            if line.is_empty() {
125                line.push_str(word);
126            } else if line.len() + 1 + word.len() <= width {
127                line.push(' ');
128                line.push_str(word);
129            } else {
130                out.push(std::mem::take(&mut line));
131                line.push_str(word);
132            }
133        }
134        if !line.is_empty() {
135            out.push(line);
136        }
137    }
138    out
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144
145    #[test]
146    fn lines_are_indented_by_how_deep_they_are() {
147        let mut w = CodeWriter::new();
148        w.line("outer");
149        w.indented(|w| {
150            w.line("inner");
151            w.indented(|w| w.line("deeper"));
152        });
153        assert_eq!(w.finish(), "outer\n    inner\n        deeper\n");
154    }
155
156    #[test]
157    fn a_block_opens_indents_and_closes() {
158        let mut w = CodeWriter::new();
159        w.block("interface Shape {", "}", |w| w.line("id: string;"));
160        assert_eq!(w.finish(), "interface Shape {\n    id: string;\n}\n");
161    }
162
163    #[test]
164    fn a_blank_line_is_blank_rather_than_indentation() {
165        let mut w = CodeWriter::new();
166        w.indented(|w| {
167            w.line("a");
168            w.line("");
169            w.line("b");
170        });
171        assert_eq!(w.finish(), "    a\n\n    b\n");
172    }
173
174    #[test]
175    fn nothing_ends_with_whitespace_that_a_diff_would_notice() {
176        let mut w = CodeWriter::new();
177        w.line("code   ");
178        w.blank();
179        w.blank();
180        let out = w.finish();
181        assert_eq!(out, "code\n");
182    }
183
184    #[test]
185    fn blank_lines_do_not_pile_up() {
186        let mut w = CodeWriter::new();
187        w.line("a");
188        w.blank();
189        w.blank();
190        w.blank();
191        w.line("b");
192        assert_eq!(w.finish(), "a\n\nb\n");
193    }
194
195    #[test]
196    fn prose_is_wrapped_and_prefixed() {
197        let mut w = CodeWriter::new();
198        w.comment(
199            "// ",
200            "A shape that is round. This sentence is long enough to need breaking \
201             across more than a single line of output.",
202        );
203        let out = w.finish();
204        assert!(out.lines().all(|l| l.starts_with("// ")), "{out}");
205        assert!(out.lines().all(|l| l.len() <= 80), "{out}");
206        assert!(out.lines().count() > 1, "it should have wrapped: {out}");
207    }
208
209    #[test]
210    fn a_word_too_long_to_wrap_is_left_alone() {
211        let mut w = CodeWriter::new();
212        w.comment("# ", &"x".repeat(120));
213        let out = w.finish();
214        assert_eq!(out.lines().count(), 1, "hyphenating a name would be worse");
215    }
216
217    #[test]
218    fn an_empty_file_stays_empty() {
219        assert_eq!(CodeWriter::new().finish(), "");
220        assert!(CodeWriter::new().is_empty());
221    }
222}