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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
use crate::document::Document;
use alloc::{string::String, vec, vec::Vec};
use core::iter::repeat;

const INDENT: &str = "  ";

struct Context<'a> {
    outputs: Vec<&'a str>,
    // Omit extra indent output so that we do not need to remove them later.
    next_level: usize,
    line_suffixes: Vec<&'a str>,
}

pub fn format(document: &Document) -> String {
    let mut context = Context {
        outputs: vec![],
        next_level: 0,
        line_suffixes: vec![],
    };

    format_document(&mut context, document, 0, true);

    context.outputs.concat()
}

fn format_document<'a>(
    context: &mut Context<'a>,
    document: &Document<'a>,
    level: usize,
    broken: bool,
) {
    match document {
        Document::Break(broken, document) => format_document(context, document, level, *broken),
        Document::Indent(document) => format_document(context, document, level + 1, broken),
        Document::Line => {
            if broken {
                format_line(context, level);
            } else {
                context.outputs.push(" ");
            }
        }
        Document::LineSuffix(suffix) => {
            if !suffix.is_empty() {
                flush(context);
            }

            context.line_suffixes.push(suffix);
        }
        Document::Sequence(documents) => {
            for document in *documents {
                format_document(context, document, level, broken);
            }
        }
        Document::String(string) => {
            if !string.is_empty() {
                flush(context);
            }

            context.outputs.push(string);
        }
    }
}

fn format_line(context: &mut Context, level: usize) {
    context
        .outputs
        .extend(context.line_suffixes.drain(..).chain(["\n"]));

    context.next_level = level;
}

fn flush(context: &mut Context) {
    context
        .outputs
        .extend(repeat(INDENT).take(context.next_level));
    context.next_level = 0;
}

#[cfg(test)]
mod tests {
    use super::{super::build::*, *};
    use alloc::boxed::Box;
    use indoc::indoc;

    fn allocate<T>(value: T) -> &'static T {
        Box::leak(Box::new(value))
    }

    #[test]
    fn format_string() {
        assert_eq!(format(&"foo".into()), "foo");
    }

    mod group {
        use super::*;

        fn create_group() -> Document<'static> {
            sequence(allocate([
                "{".into(),
                indent(allocate(sequence(allocate([
                    line(),
                    "foo".into(),
                    line(),
                    "bar".into(),
                ])))),
                line(),
                "}".into(),
            ]))
        }

        #[test]
        fn format_flat_group() {
            assert_eq!(format(&flatten(&create_group())), "{ foo bar }");
        }

        #[test]
        fn format_empty_line_with_indent() {
            assert_eq!(format(&indent(&line())), "\n");
        }

        #[test]
        fn format_broken_group() {
            assert_eq!(
                format(&create_group()),
                indoc!(
                    "
                    {
                      foo
                      bar
                    }
                    "
                )
                .trim(),
            );
        }

        #[test]
        fn format_unbroken_group_in_broken_group() {
            assert_eq!(
                format(&sequence(&[
                    "{".into(),
                    indent(&sequence(&[line(), flatten(&create_group())])),
                    line(),
                    "}".into(),
                ])),
                indoc!(
                    "
                    {
                      { foo bar }
                    }
                    "
                )
                .trim(),
            );
        }
    }

    mod line_suffix {
        use super::*;

        #[test]
        fn format_line_suffix_between_strings() {
            assert_eq!(
                format(&sequence(&[
                    "{".into(),
                    line_suffix("foo"),
                    "}".into(),
                    line()
                ])),
                "{}foo\n",
            );
        }

        #[test]
        fn format_two_line_suffixes_between_strings() {
            assert_eq!(
                format(&sequence(&[
                    "{".into(),
                    line_suffix("foo"),
                    line_suffix("bar"),
                    "}".into(),
                    line()
                ])),
                "{}foobar\n",
            );
        }
    }
}