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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
// This file is part of yash, an extended POSIX shell.
// Copyright (C) 2021 WATANABE Yuki
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! Pretty-printing diagnostic messages containing references to source code.
//!
//! This module defines some data types for constructing intermediate data
//! structures for printing diagnostic messages referencing source code
//! fragments.  When you have an [`Error`](crate::parser::Error), you can
//! convert it to a [`Message`]. Then, you can in turn convert it into
//! `annotate_snippets::snippet::Snippet`, for example, and finally format a
//! printable diagnostic message string.
//!
//! When the `yash_syntax` crate is built with the `annotate-snippets` feature
//! enabled, it supports conversion from `Message` to `Snippet`. If you would
//! like to use another formatter instead, you can provide your own conversion
//! for yourself.
//!
//! TODO Elaborate

use super::Location;
use std::borrow::Cow;
use std::cell::Ref;
use std::ops::Deref;
use std::rc::Rc;

/// Type of annotation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AnnotationType {
    Error,
    Warning,
    Info,
    Note,
    Help,
}

/// Source code fragment annotated with a label.
///
/// Annotations are part of an entire [`Message`].
#[derive(Clone)]
pub struct Annotation<'a> {
    /// Type of annotation.
    pub r#type: AnnotationType,
    /// String that describes the annotated part of the source code.
    pub label: Cow<'a, str>,
    /// Position of the annotated fragment in the source code.
    pub location: &'a Location,
    /// Annotated code string.
    ///
    /// This value provides an access to the string held in
    /// `self.location.code.value`, which can only be accessed by a `Ref`.
    pub code: Rc<dyn Deref<Target = str> + 'a>,
}

impl std::fmt::Debug for Annotation<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Annotation")
            .field("type", &self.r#type)
            .field("label", &self.label)
            .field("location", &self.location)
            .field("code", &&**self.code)
            .finish()
    }
}

impl<'a> Annotation<'a> {
    /// Creates a new annotation.
    pub fn new(r#type: AnnotationType, label: Cow<'a, str>, location: &'a Location) -> Self {
        Annotation {
            r#type,
            label,
            location,
            code: Rc::new(Ref::map(location.code.value.borrow(), String::as_str)),
        }
    }
}

/// Entire diagnostic message.
#[derive(Clone, Debug)]
pub struct Message<'a> {
    /// Type of this message.
    pub r#type: AnnotationType,
    /// String that communicates the most important information in this message.
    pub title: Cow<'a, str>,
    /// References to source code fragments annotated with additional information.
    pub annotations: Vec<Annotation<'a>>,
}

impl super::Source {
    /// Appends complementary annotations describing this source.
    pub fn complement_annotations<'a, 's: 'a, T: Extend<Annotation<'a>>>(&'s self, result: &mut T) {
        use super::Source::*;
        match self {
            Unknown | Stdin => (),
            CommandSubst { original } => {
                // TODO Use Extend::extend_one
                result.extend(std::iter::once(Annotation::new(
                    AnnotationType::Info,
                    "command substitution appeared here".into(),
                    original,
                )));
            }
            Arith { original } => {
                // TODO Use Extend::extend_one
                result.extend(std::iter::once(Annotation::new(
                    AnnotationType::Info,
                    "arithmetic expansion appeared here".into(),
                    original,
                )));
            }
            Trap { origin, .. } => {
                // TODO Use Extend::extend_one
                result.extend(std::iter::once(Annotation::new(
                    AnnotationType::Info,
                    "trap was set here".into(),
                    origin,
                )));
            }
            Alias { original, alias } => {
                // TODO Use Extend::extend_one
                result.extend(std::iter::once(Annotation::new(
                    AnnotationType::Info,
                    format!("alias `{}` was substituted here", alias.name).into(),
                    original,
                )));
                original.code.source.complement_annotations(result);
                result.extend(std::iter::once(Annotation::new(
                    AnnotationType::Info,
                    format!("alias `{}` was defined here", alias.name).into(),
                    &alias.origin,
                )));
                alias.origin.code.source.complement_annotations(result);
            }
        }
    }
}

/// Helper for constructing a [`Message`]
///
/// Thanks to the blanket implementation `impl<'a, T: MessageBase> From<&'a T>
/// for Message<'a>`, implementors of this trait can be converted to a message
/// for free.
pub trait MessageBase {
    /// Returns the type of the entire message.
    ///
    /// The default implementation returns `AnnotationType::Error`.
    fn message_type(&self) -> AnnotationType {
        AnnotationType::Error
    }

    // TODO message tag

    /// Returns the main caption of the message.
    fn message_title(&self) -> Cow<str>;

    /// Returns an annotation to be the first in the message.
    fn main_annotation(&self) -> Annotation<'_>;

    /// Adds additional annotations to the given container.
    ///
    /// The default implementation does nothing.
    fn additional_annotations<'a, T: Extend<Annotation<'a>>>(&'a self, results: &mut T) {
        let _ = results;
    }
}

/// Constructs a message based on the message base.
impl<'a, T: MessageBase> From<&'a T> for Message<'a> {
    fn from(base: &'a T) -> Self {
        let main_annotation = base.main_annotation();
        let main_source = &main_annotation.location.code.source;
        let mut annotations = vec![main_annotation];

        main_source.complement_annotations(&mut annotations);
        base.additional_annotations(&mut annotations);

        Message {
            r#type: base.message_type(),
            title: base.message_title(),
            annotations,
        }
    }
}

#[cfg(feature = "annotate-snippets")]
mod annotate_snippets_support {
    use super::*;
    use annotate_snippets::snippet;
    use annotate_snippets::snippet::Snippet;

    /// Converts `yash_syntax::source::pretty::AnnotationType` into
    /// `annotate_snippets::snippet::AnnotationType`.
    ///
    /// This implementation is only available when the `yash_syntax` crate is
    /// built with the `annotate-snippets` feature enabled.
    impl From<AnnotationType> for annotate_snippets::snippet::AnnotationType {
        fn from(r#type: AnnotationType) -> Self {
            use AnnotationType::*;
            match r#type {
                Error => snippet::AnnotationType::Error,
                Warning => snippet::AnnotationType::Warning,
                Info => snippet::AnnotationType::Info,
                Note => snippet::AnnotationType::Note,
                Help => snippet::AnnotationType::Help,
            }
        }
    }

    impl<'a> From<&'a Message<'a>> for Snippet<'a> {
        fn from(message: &'a Message<'a>) -> Self {
            let mut snippet = Snippet {
                title: Some(snippet::Annotation {
                    id: None,
                    label: Some(&message.title),
                    annotation_type: message.r#type.into(),
                }),
                footer: vec![],
                slices: vec![],
                opt: annotate_snippets::display_list::FormatOptions::default(),
            };

            let mut lines = vec![];
            for annotation in &message.annotations {
                let code = &annotation.location.code;
                let line_start = code
                    .start_line_number
                    .get()
                    .try_into()
                    .unwrap_or(usize::MAX);
                let value = &annotation.code;
                let range = &annotation.location.range;
                let annotation = snippet::SourceAnnotation {
                    range: (range.start, range.end),
                    label: &annotation.label,
                    annotation_type: annotation.r#type.into(),
                };
                if let Some(i) = lines.iter().position(|l| l == code) {
                    snippet.slices[i].annotations.push(annotation);
                } else {
                    snippet.slices.push(snippet::Slice {
                        source: value,
                        line_start,
                        origin: Some(code.source.label()),
                        fold: true,
                        annotations: vec![annotation],
                    });
                    lines.push(code.clone());
                }
            }

            snippet
        }
    }

    #[test]
    fn from_message_type_and_title() {
        let message = Message {
            r#type: AnnotationType::Error,
            title: "my title".into(),
            annotations: vec![],
        };
        let snippet = Snippet::from(&message);
        let title = snippet.title.unwrap();
        assert_eq!(title.id, None);
        assert_eq!(title.label, Some("my title"));
        assert_eq!(title.annotation_type, snippet::AnnotationType::Error);
    }

    #[test]
    fn from_message_one_annotation() {
        let location = Location::dummy("my location");
        let message = Message {
            r#type: AnnotationType::Warning,
            title: "my title".into(),
            annotations: vec![Annotation::new(
                AnnotationType::Info,
                "my label".into(),
                &location,
            )],
        };
        let snippet = Snippet::from(&message);
        let title = snippet.title.unwrap();
        assert_eq!(title.id, None);
        assert_eq!(title.label, Some("my title"));
        assert_eq!(title.annotation_type, snippet::AnnotationType::Warning);
        assert_eq!(snippet.slices.len(), 1, "{:?}", snippet.slices);
        assert_eq!(snippet.slices[0].source, "my location");
        assert_eq!(snippet.slices[0].line_start, 1);
        assert_eq!(snippet.slices[0].origin, Some("<?>"));
        assert_eq!(snippet.slices[0].annotations.len(), 1);
        assert_eq!(snippet.slices[0].annotations[0].range, (0, 11));
        assert_eq!(snippet.slices[0].annotations[0].label, "my label");
        assert_eq!(
            snippet.slices[0].annotations[0].annotation_type,
            snippet::AnnotationType::Info
        );
    }

    #[test]
    fn from_message_non_default_line_start() {
        use super::super::*;
        use std::num::NonZeroU64;
        use std::rc::Rc;

        let location = Location {
            code: Rc::new(Code {
                value: "".to_string().into(),
                start_line_number: NonZeroU64::new(128).unwrap(),
                source: Source::Unknown,
            }),
            range: 42..123,
        };
        let message = Message {
            r#type: AnnotationType::Warning,
            title: "".into(),
            annotations: vec![Annotation::new(AnnotationType::Info, "".into(), &location)],
        };
        let snippet = Snippet::from(&message);
        assert_eq!(snippet.slices[0].line_start, 128);
    }

    #[test]
    fn from_message_non_default_range() {
        let mut location = Location::dummy("my location");
        location.range = 6..9;
        let message = Message {
            r#type: AnnotationType::Warning,
            title: "".into(),
            annotations: vec![Annotation::new(AnnotationType::Info, "".into(), &location)],
        };
        let snippet = Snippet::from(&message);
        assert_eq!(snippet.slices[0].annotations[0].range, (6, 9));
    }

    #[test]
    fn from_message_non_default_origin() {
        use super::super::*;
        use std::num::NonZeroU64;

        let original = Location::dummy("my original");
        let alias = Rc::new(Alias {
            name: "foo".to_string(),
            replacement: "bar".to_string(),
            global: false,
            origin: Location::dummy("my origin"),
        });
        let code = Rc::new(Code {
            value: "substitution".to_string().into(),
            start_line_number: NonZeroU64::new(10).unwrap(),
            source: Source::Alias { original, alias },
        });
        let location = Location { code, range: 4..9 };
        let message = Message {
            r#type: AnnotationType::Warning,
            title: "my title".into(),
            annotations: vec![Annotation::new(
                AnnotationType::Info,
                "my label".into(),
                &location,
            )],
        };
        let snippet = Snippet::from(&message);
        assert_eq!(snippet.slices[0].source, "substitution");
        assert_eq!(snippet.slices[0].line_start, 10);
        assert_eq!(snippet.slices[0].origin, Some("<alias>"));
    }

    #[test]
    fn from_message_two_annotations_different_slice() {
        let location_1 = Location::dummy("my location 1");
        let location_2 = Location::dummy("my location 2");
        let message = Message {
            r#type: AnnotationType::Error,
            title: "some title".into(),
            annotations: vec![
                Annotation::new(AnnotationType::Note, "my label 1".into(), &location_1),
                Annotation::new(AnnotationType::Info, "my label 2".into(), &location_2),
            ],
        };
        let snippet = Snippet::from(&message);
        let title = snippet.title.unwrap();
        assert_eq!(title.id, None);
        assert_eq!(title.label, Some("some title"));
        assert_eq!(title.annotation_type, snippet::AnnotationType::Error);
        assert_eq!(snippet.slices.len(), 2, "{:?}", snippet.slices);
        assert_eq!(snippet.slices[0].source, "my location 1");
        assert_eq!(snippet.slices[0].annotations.len(), 1);
        assert_eq!(snippet.slices[0].annotations[0].range, (0, 13));
        assert_eq!(snippet.slices[0].annotations[0].label, "my label 1");
        assert_eq!(
            snippet.slices[0].annotations[0].annotation_type,
            snippet::AnnotationType::Note
        );
        assert_eq!(snippet.slices[1].source, "my location 2");
        assert_eq!(snippet.slices[1].annotations.len(), 1);
        assert_eq!(snippet.slices[1].annotations[0].range, (0, 13));
        assert_eq!(snippet.slices[1].annotations[0].label, "my label 2");
        assert_eq!(
            snippet.slices[1].annotations[0].annotation_type,
            snippet::AnnotationType::Info
        );
    }

    #[test]
    fn from_message_two_annotations_same_slice() {
        let location_1 = Location::dummy("my location");
        let location_3 = Location {
            range: 2..4,
            ..location_1.clone()
        };
        let message = Message {
            r#type: AnnotationType::Error,
            title: "some title".into(),
            annotations: vec![
                Annotation::new(AnnotationType::Info, "my label 1".into(), &location_3),
                Annotation::new(AnnotationType::Help, "my label 2".into(), &location_1),
            ],
        };
        let snippet = Snippet::from(&message);
        let title = snippet.title.unwrap();
        assert_eq!(title.id, None);
        assert_eq!(title.label, Some("some title"));
        assert_eq!(title.annotation_type, snippet::AnnotationType::Error);
        assert_eq!(snippet.slices.len(), 1, "{:?}", snippet.slices);
        assert_eq!(snippet.slices[0].source, "my location");
        assert_eq!(snippet.slices[0].annotations.len(), 2);
        assert_eq!(snippet.slices[0].annotations[0].range, (2, 4));
        assert_eq!(snippet.slices[0].annotations[0].label, "my label 1");
        assert_eq!(
            snippet.slices[0].annotations[0].annotation_type,
            snippet::AnnotationType::Info
        );
        assert_eq!(snippet.slices[0].annotations[1].range, (0, 11));
        assert_eq!(snippet.slices[0].annotations[1].label, "my label 2");
        assert_eq!(
            snippet.slices[0].annotations[1].annotation_type,
            snippet::AnnotationType::Help
        );
    }
}