teo_parser/format/
writer.rs1use std::collections::btree_map::Values;
2use crate::ast::node::Node;
3use crate::format::command::Command;
4use crate::format::flusher::Flusher;
5use crate::format::Preferences;
6use crate::traits::write::Write;
7
8pub struct Writer<'a> {
9 pub(super) preferences: Preferences,
10 pub(super) commands: Vec<Command<'a>>,
11 can_write: bool,
12}
13
14impl Default for Writer<'_> {
15 fn default() -> Self {
16 Self::new(Preferences::default())
17 }
18}
19
20impl<'a> Writer<'a> {
21
22 pub fn new(preferences: Preferences) -> Self {
23 Self {
24 preferences,
25 commands: vec![],
26 can_write: true,
27 }
28 }
29
30 pub fn write_children(&mut self, node: &'a dyn Write, children: Values<'a, usize, Node>) {
31 if !self.can_write {
32 panic!("writer can only write only once in one call");
33 }
34 let mut writer: Writer = Self::new(self.preferences);
35 for c in children {
36 c.write(&mut writer);
37 writer.can_write = true;
38 }
39 self.commands.push(Command::branch(node, writer.commands));
40 self.can_write = false;
41 }
42
43 pub fn write_content(&mut self, node: &'a dyn Write, content: &'a str) {
44 if !self.can_write {
45 panic!("writer can only write only once in one call");
46 }
47 self.commands.push(Command::leaf(node, vec![content.as_ref()]));
48 self.can_write = false;
49 }
50
51 pub fn write_contents(&mut self, node: &'a dyn Write, contents: Vec<&'a str>) {
52 if !self.can_write {
53 panic!("writer can only write only once in one call");
54 }
55 self.commands.push(Command::leaf(node, contents));
56 self.can_write = false;
57 }
58
59 pub fn flush(&self) -> String {
60 let mut flusher = Flusher::new_from_beginning(&self.commands, self.preferences);
61 flusher.flush()
62 }
63}