codeviz_rust/
file_spec.rs1use codeviz_common::ElementFormatter;
2use std::collections::BTreeSet;
3use super::*;
4
5#[derive(Debug, Clone)]
6pub struct FileSpec {
7 pub elements: Elements,
8}
9
10impl FileSpec {
11 pub fn new() -> FileSpec {
12 FileSpec { elements: Elements::new() }
13 }
14
15 pub fn push<E>(&mut self, element: E)
16 where
17 E: Into<Element>,
18 {
19 self.elements.push(element);
20 }
21
22 fn imports(&self) -> Option<Elements> {
23 let mut imports = BTreeSet::new();
24
25 self.elements.imports(&mut imports);
26
27 let modules: BTreeSet<(String, Option<String>)> = imports
28 .into_iter()
29 .map(|imported| (imported.module, imported.alias))
30 .collect();
31
32 if modules.is_empty() {
33 return None;
34 }
35
36 let mut elements = Elements::new();
37
38 for (module, alias) in modules {
39 let mut s = Statement::new();
40
41 s.push("use ");
42 s.push(&module);
43
44 if let Some(ref alias) = alias {
45 s.push(" as ");
46 s.push(alias);
47 }
48
49 s.push(";");
50
51 elements.push(s);
52 }
53
54 Some(elements)
55 }
56
57 pub fn format<W>(&self, out: &mut W) -> Result<()>
58 where
59 W: ::std::fmt::Write,
60 {
61 let mut elements = Elements::new();
62
63 if let Some(imports) = self.imports() {
64 elements.push(imports);
65 }
66
67 elements.push(self.elements.clone().join(Spacing));
68
69 let elements: Element = elements.clone().join(Spacing).into();
70 let mut extra = ();
71
72 elements.format(&mut ElementFormatter::new(out), &mut extra)?;
73 out.write_char('\n')?;
74
75 Ok(())
76 }
77}
78
79impl ImportReceiver for BTreeSet<ImportedName> {
80 fn receive(&mut self, name: &ImportedName) {
81 self.insert(name.clone());
82 }
83}
84
85impl ToString for FileSpec {
86 fn to_string(&self) -> String {
87 let mut s = String::new();
88 self.format(&mut s).unwrap();
89 s
90 }
91}