1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use pretty::RcDoc;

pub const INDENT_SPACE: isize = 2;
pub const LINE_WIDTH: usize = 80;

fn is_empty(doc: &RcDoc) -> bool {
    use pretty::Doc::*;
    match &**doc {
        Nil => true,
        FlatAlt(t1, t2) => is_empty(&(*t1)) && is_empty(&(*t2)),
        Group(t) => is_empty(&(*t)),
        Nest(_, t) => is_empty(&(*t)),
        Union(t1, t2) => is_empty(&(*t1)) && is_empty(&(*t2)),
        Annotated(_, t) => is_empty(&(*t)),
        _ => false,
    }
}

pub fn enclose<'a>(left: &'a str, doc: RcDoc<'a>, right: &'a str) -> RcDoc<'a> {
    if is_empty(&doc) {
        RcDoc::text(left).append(right)
    } else {
        RcDoc::text(left)
            .append(RcDoc::line_())
            .append(doc)
            .nest(INDENT_SPACE)
            .append(RcDoc::line_())
            .append(right)
            .group()
    }
}

pub fn enclose_space<'a>(left: &'a str, doc: RcDoc<'a>, right: &'a str) -> RcDoc<'a> {
    if is_empty(&doc) {
        RcDoc::text(left).append(right)
    } else {
        RcDoc::text(left)
            .append(RcDoc::line())
            .append(doc)
            .nest(INDENT_SPACE)
            .append(RcDoc::line())
            .append(right)
            .group()
    }
}

#[allow(dead_code)]
pub fn strict_concat<'a, D>(docs: D, sep: &'a str) -> RcDoc<'a>
where
    D: Iterator<Item = RcDoc<'a>>,
{
    RcDoc::intersperse(docs, RcDoc::text(sep).append(RcDoc::line()))
}

/// Append the separator to each docs items. If it is displayed in a single line, omit the last separator.
pub fn concat<'a, D>(docs: D, sep: &'a str) -> RcDoc<'a>
where
    D: Iterator<Item = RcDoc<'a>> + Clone,
{
    RcDoc::intersperse(docs.clone().map(|d| d.append(sep)), RcDoc::line()).flat_alt(
        RcDoc::intersperse(docs, RcDoc::text(sep).append(RcDoc::line())),
    )
}

pub fn lines<'a, D>(docs: D) -> RcDoc<'a>
where
    D: Iterator<Item = RcDoc<'a>>,
{
    RcDoc::concat(docs.map(|doc| doc.append(RcDoc::hardline())))
}

pub fn kwd<U: std::fmt::Display + ?Sized>(str: &U) -> RcDoc {
    RcDoc::as_string(str).append(RcDoc::space())
}

pub fn str(str: &str) -> RcDoc {
    RcDoc::text(str)
}

pub fn ident(id: &str) -> RcDoc {
    kwd(id)
}

pub fn quote_ident(id: &str) -> RcDoc {
    str("'")
        .append(format!("{}", id.escape_debug()))
        .append("'")
        .append(RcDoc::space())
}