vos_core/pretty_print/
mod.rs

1use std::fmt::{Arguments, Display, Formatter, Write};
2
3use indenter::CodeFormatter;
4use vos_error::Validation;
5
6use crate::{Codegen, Project};
7
8pub struct PrettyPrinter {}
9
10impl Codegen for PrettyPrinter {
11    type Output = String;
12
13    fn generate(&self, project: &Project) -> Validation<Self::Output> {
14        Validation::Success { value: project.to_string(), diagnostics: vec![] }
15    }
16}
17
18struct Context<'s, T>
19where
20    T: Write,
21{
22    buffer: CodeFormatter<'s, T>,
23}
24
25impl<'s, T: Write> Write for Context<'s, T> {
26    fn write_str(&mut self, s: &str) -> std::fmt::Result {
27        self.buffer.write_str(s)
28    }
29    fn write_char(&mut self, c: char) -> std::fmt::Result {
30        self.buffer.write_char(c)
31    }
32    fn write_fmt(self: &mut Self, args: Arguments<'_>) -> std::fmt::Result {
33        self.buffer.write_fmt(args)
34    }
35}
36
37impl<'s, T> Context<'s, T>
38where
39    T: Write,
40{
41    pub fn new(s: &'s mut T) -> Context<'s, T> {
42        Self { buffer: CodeFormatter::new(s, "    ") }
43    }
44
45    pub fn visit_root(&mut self, root: &Project) -> std::fmt::Result {
46        write!(self, "{}", root.description)?;
47        self.write_str("service {")?;
48
49        Ok(())
50    }
51}
52
53impl Display for Project {
54    /// ```vos
55    /// /// dies
56    /// service {
57    ///     a:x
58    /// }
59    /// ```
60    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
61        let mut ctx = Context::new(f);
62        ctx.visit_root(self)
63    }
64}