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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// SPDX-License-Identifier: Apache-2.0

//! Module for comments.
//!
//! [`Comment`]s can be added to nodes between the child edges to attach
//! additional miscellaneous information that doesn't fit in any of the more
//! structured types, intended purely to be formatted for and interpreted by
//! humans.

use crate::output::path;

/// Representation of a comment message intended only for human consumption.
/// Includes basic formatting information.
#[derive(Clone, Debug, PartialEq, Default)]
pub struct Comment {
    /// Formatting elements and spans that make up the comment.
    elements: Vec<Element>,
}

impl Comment {
    /// Creates an empty comment.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a piece of plain text to the comment.
    pub fn plain<S: ToString>(mut self, text: S) -> Self {
        self.push(Element::Span(text.to_string().into()));
        self
    }

    /// Adds a piece of text to the comment that links to the given path.
    pub fn link<S: ToString>(mut self, text: S, path: path::PathBuf) -> Self {
        self.push(Element::Span(Span {
            text: text.to_string(),
            link: Some(Link::Path(path)),
        }));
        self
    }

    /// Adds a piece of text to the comment that links to the given URL.
    pub fn url<S: ToString, U: ToString>(mut self, text: S, url: U) -> Self {
        self.push(Element::Span(Span {
            text: text.to_string(),
            link: Some(Link::Url(url.to_string())),
        }));
        self
    }

    /// Adds a newline/paragraph break.
    pub fn nl(mut self) -> Self {
        self.push(Element::NewLine);
        self
    }

    /// Opens a list.
    pub fn lo(mut self) -> Self {
        self.push(Element::ListOpen);
        self
    }

    /// Advances to the next list item.
    pub fn li(mut self) -> Self {
        self.push(Element::ListNext);
        self
    }

    /// Closes the current list.
    pub fn lc(mut self) -> Self {
        self.push(Element::ListClose);
        self
    }

    /// Pushes an element into this comment.
    pub fn push(&mut self, element: Element) {
        // Some pairs of element types should never follow each other, because
        // one implies the other.
        match self.elements.pop() {
            None => self.elements.push(element),
            Some(Element::Span(s1)) => {
                if let Element::Span(s2) = element {
                    let (s1, maybe_s2) = merge_spans(s1, s2);
                    self.elements.push(Element::Span(s1));
                    if let Some(s2) = maybe_s2 {
                        self.elements.push(Element::Span(s2));
                    }
                } else {
                    self.elements.push(Element::Span(s1));
                    self.elements.push(element);
                }
            }
            Some(Element::NewLine) => {
                if matches!(element, Element::Span(_)) {
                    self.elements.push(Element::NewLine);
                }
                self.elements.push(element);
            }
            Some(Element::ListOpen) => {
                self.elements.push(Element::ListOpen);
                if !matches!(element, Element::ListNext) {
                    self.elements.push(element);
                }
            }
            Some(Element::ListNext) => {
                self.elements.push(Element::ListNext);
                if !matches!(element, Element::ListNext) {
                    self.elements.push(element);
                }
            }
            Some(Element::ListClose) => {
                self.elements.push(Element::ListClose);
                if !matches!(element, Element::NewLine) {
                    self.elements.push(element);
                }
            }
        }
    }

    /// Pushes a whole other comment's worth of elements into this comment.
    pub fn extend(&mut self, other: Comment) {
        let mut it = other.elements.into_iter();

        // The first element of other may need to be merged with its new
        // predecessor.
        if let Some(element) = it.next() {
            self.push(element);
        }

        // The rest of the elements would already have been merged, so we can
        // just copy them over.
        self.elements.extend(it);
    }

    /// Returns the slice of elements that comprise the comment.
    ///
    /// This list is "minimal:"
    ///  - there are no consecutive newlines, list item tags, or spans with
    ///    equal formatting (they are merged together);
    ///  - there are no empty lists, and there is never a list item immediately
    ///    following a list open tag (as this is redundant).
    pub fn elements(&self) -> &[Element] {
        &self.elements
    }
}

impl std::fmt::Display for Comment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut indent = 0;
        for element in self.elements.iter() {
            match element {
                Element::Span(span) => span.fmt(f),
                Element::NewLine => write!(f, "\n\n{: >1$}", "", indent),
                Element::ListOpen => {
                    indent += 3;
                    write!(f, "\n\n{: >1$}", "- ", indent)
                }
                Element::ListNext => {
                    write!(f, "\n\n{: >1$}", "- ", indent)
                }
                Element::ListClose => {
                    indent -= 3;
                    write!(f, "\n\n{: >1$}", "", indent)
                }
            }?;
        }
        Ok(())
    }
}

impl From<String> for Comment {
    fn from(text: String) -> Self {
        Self {
            elements: vec![Element::Span(text.into())],
        }
    }
}

/// A comment element.
#[derive(Clone, Debug, PartialEq)]
pub enum Element {
    /// A span of text. Should not include newlines.
    Span(Span),

    /// A newline/paragraph break.
    NewLine,

    /// Starts a new list. Subsequent spans form the text for the first item.
    ListOpen,

    /// Advances to the next list item.
    ListNext,

    /// Closes a list.
    ListClose,
}

/// Like Comment, but single-line.
#[derive(Clone, Debug, PartialEq, Default)]
pub struct Brief {
    /// Spans that make up the comment. These are simply concatenated, but
    /// spans may contain optional formatting information.
    spans: Vec<Span>,
}

impl Brief {
    /// Creates an empty comment.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a piece of plain text to the comment.
    pub fn plain<S: ToString>(mut self, text: S) -> Self {
        self.push(text.to_string().into());
        self
    }

    /// Adds a piece of text to the comment that links to the given path.
    pub fn link<S: ToString>(mut self, text: S, path: path::PathBuf) -> Self {
        self.push(Span {
            text: text.to_string(),
            link: Some(Link::Path(path)),
        });
        self
    }

    /// Adds a piece of text to the comment that links to the given URL.
    pub fn url<S: ToString, U: ToString>(mut self, text: S, url: U) -> Self {
        self.push(Span {
            text: text.to_string(),
            link: Some(Link::Url(url.to_string())),
        });
        self
    }

    /// Pushes a span into this brief.
    pub fn push(&mut self, span: Span) {
        if let Some(s1) = self.spans.pop() {
            let s2 = span;
            let (s1, maybe_s2) = merge_spans(s1, s2);
            self.spans.push(s1);
            if let Some(s2) = maybe_s2 {
                self.spans.push(s2);
            }
        } else {
            self.spans.push(span);
        }
    }

    /// Pushes a whole other brief's worth of elements into this brief.
    pub fn extend(&mut self, other: Brief) {
        let mut it = other.spans.into_iter();

        // The first span of other may need to be merged with its new
        // predecessor.
        if let Some(element) = it.next() {
            self.push(element);
        }

        // The rest of the spans would already have been merged, so we can
        // just copy them over.
        self.spans.extend(it);
    }

    /// Returns the slice of spans that comprise the brief.
    pub fn spans(&self) -> &[Span] {
        &self.spans
    }
}

impl std::fmt::Display for Brief {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for span in self.spans.iter() {
            span.fmt(f)?;
        }
        Ok(())
    }
}

impl From<String> for Brief {
    fn from(text: String) -> Self {
        Self {
            spans: vec![text.into()],
        }
    }
}

impl From<Brief> for Comment {
    fn from(brief: Brief) -> Self {
        Self {
            elements: brief.spans.into_iter().map(Element::Span).collect(),
        }
    }
}

/// A span of text within a comment.
#[derive(Clone, Debug, PartialEq)]
pub struct Span {
    /// The span of text.
    pub text: String,

    /// Whether this span of text should link to something.
    pub link: Option<Link>,
}

impl std::fmt::Display for Span {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.text)
    }
}

impl From<String> for Span {
    fn from(text: String) -> Self {
        Span { text, link: None }
    }
}

/// Merges two spans together, if possible. A space is inserted between the
/// spans if there isn't one already.
fn merge_spans(mut a: Span, b: Span) -> (Span, Option<Span>) {
    if b.text.is_empty() {
        return (a, None);
    }
    if !a.text.ends_with(' ') && !b.text.starts_with(' ') {
        a.text.push(' ');
    }
    if a.link == b.link {
        a.text += &b.text;
        return (a, None);
    }
    (a, Some(b))
}

/// A link to something.
#[derive(Clone, Debug, PartialEq)]
pub enum Link {
    /// Link to another node in the tree, via an absolute node path.
    Path(path::PathBuf),

    /// Link to some external URL.
    Url(String),
}