pretty_print/helpers/
soft_block.rs

1use super::*;
2
3/// A soft block is a block that is not required to be on a new line.
4///
5/// ```vk
6/// {a, b, c}
7///
8/// {
9///     a,
10///     b,
11/// }
12/// ```
13#[derive(Clone, Debug)]
14pub struct SoftBlock {
15    /// The indentation of the soft block
16    pub indent: usize,
17    /// The left hand side of the soft block
18    pub lhs: &'static str,
19    /// The right hand side of the soft block
20    pub rhs: &'static str,
21    /// The joint node of the soft block
22    pub joint: PrettyTree,
23    /// The tail node of the soft block
24    pub tail: PrettyTree,
25}
26
27impl SoftBlock {
28    /// Build a new soft block
29    pub fn new(lhs: &'static str, rhs: &'static str) -> Self {
30        Self { lhs, rhs, indent: 4, joint: PrettyTree::line_or_space(), tail: PrettyTree::Nil }
31    }
32    /// Build a new soft block with the tuple syntax
33    pub fn tuple() -> Self {
34        Self::new("(", ")")
35    }
36    /// Build a new soft block with the parentheses syntax
37    pub fn parentheses() -> Self {
38        Self::new("(", ")")
39    }
40    /// Build a new soft block with the brackets syntax
41    pub fn brackets() -> Self {
42        Self::new("[", "]")
43    }
44    /// Build a new soft block with the curly braces syntax
45    pub fn curly_braces() -> Self {
46        Self::new("{", "}")
47    }
48    /// Set the joint node of the soft block
49    pub fn with_joint(self, joint: PrettyTree) -> Self {
50        Self { joint, ..self }
51    }
52}
53
54impl SoftBlock {
55    /// Join a slice of pretty printables with the soft block
56    pub fn join_slice<T: PrettyPrint>(&self, slice: &[T], theme: &PrettyProvider) -> PrettyTree {
57        let mut outer = PrettySequence::new(5);
58        outer += self.lhs;
59        outer += PrettyTree::line_or_space();
60        let mut inner = PrettySequence::new(slice.len() * 2);
61        for (idx, term) in slice.iter().enumerate() {
62            if idx != 0 {
63                inner += self.joint.clone();
64            }
65            inner += term.pretty(theme);
66        }
67        outer += inner.indent(self.indent);
68        outer += PrettyTree::line_or_space();
69        outer += self.rhs;
70        outer.into()
71    }
72}