yash-env 0.13.2

Yash shell execution environment interface
Documentation
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
// 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 object that can be converted to a
//! [`Report`], you can then convert it to `annotate_snippets::Group`, which
//! can be formatted into a human-readable diagnostic message string. If you
//! want to use another formatter instead of `annotate_snippets`, you can
//! provide your own conversion from `Report` to the formatter's data
//! structures.
//!
//! ## Printing an error
//!
//! This example shows how to format an
//! [`StartSubshellError`](crate::semantics::command::StartSubshellError)
//! instance into a human-readable string.
//!
//! ```
//! # use yash_env::semantics::Field;
//! # use yash_env::semantics::command::StartSubshellError;
//! # use yash_env::source::pretty::Report;
//! # use yash_env::system::Errno;
//! let error = StartSubshellError {
//!     utility: Field::dummy("foo"),
//!     errno: Errno::EAGAIN,
//! };
//! let report = Report::from(&error);
//! let group = annotate_snippets::Group::from(&report);
//! eprintln!("{}", annotate_snippets::Renderer::plain().render(&[group]));
//! ```
//!
//! You can also implement conversion from your custom error object to
//! [`Report`], which then can be used in the same way to format a diagnostic
//! message. To do this, implement `From<YourError>` or `From<&YourError>` for
//! `Report`.

use super::Location;
use std::borrow::Cow;
use std::cell::Ref;
use std::ops::Range;
#[cfg(test)]
use std::rc::Rc;

/// Type of [`Report`]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum ReportType {
    #[default]
    None,
    Error,
    Warning,
}

/// Type and label annotating a [`Span`]
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum SpanRole<'a> {
    /// Primary span, usually indicating the main cause of a problem
    Primary { label: Cow<'a, str> },
    /// Secondary span, usually indicating related information
    Supplementary { label: Cow<'a, str> },
    // Patch { replacement: Cow<'a, str> },
}

/// Part of source code [`Snippet`] annotated with additional information
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Span<'a> {
    /// Range of bytes in the source code
    pub range: Range<usize>,
    /// Type and label of this span
    pub role: SpanRole<'a>,
}

/// Fragment of source code with annotated spans highlighting specific regions
///
/// A snippet corresponds to a single source [`Code`](super::Code). It contains
/// zero or more [`Span`]s that annotate specific parts of the code.
///
/// `Snippet` holds a [`Ref`] to the string held in `self.code.value`, which
/// provides an access to the string without making a new borrow
/// ([`code_string`](Self::code_string)). This allows creating another
/// message builder such as `annotate_snippets::Snippet` without the need to
/// retain a borrow of `self.code.value`.
#[derive(Debug)]
pub struct Snippet<'a> {
    /// Source code to which the spans refer
    pub code: &'a super::Code,
    /// Reference to the string held in `self.code.value`
    code_string: Ref<'a, str>,
    /// Spans describing parts of the code
    pub spans: Vec<Span<'a>>,
}

impl Snippet<'_> {
    /// Creates a new snippet for the given code without any spans.
    #[must_use]
    pub fn with_code(code: &super::Code) -> Snippet<'_> {
        Self::with_code_and_spans(code, Vec::new())
    }

    /// Creates a new snippet for the given code with the given spans.
    #[must_use]
    pub fn with_code_and_spans<'a>(code: &'a super::Code, spans: Vec<Span<'a>>) -> Snippet<'a> {
        Snippet {
            code,
            code_string: Ref::map(code.value.borrow(), String::as_str),
            spans,
        }
    }

    /// Creates a vector containing a snippet with a primary span.
    ///
    /// This is a convenience function for creating a vector of snippets
    /// containing a primary span created from the given location and label.
    /// The returned vector can be used as the `snippets` field of a
    /// [`Report`].
    ///
    /// This function calls
    /// [`Source::extend_with_context`](super::Source::extend_with_context) for
    /// `location.code.source`, thereby adding supplementary spans describing the
    /// context of the source code. This means that the returned vector may
    /// contain multiple snippets or spans if the source has a related location.
    #[must_use]
    pub fn with_primary_span<'a>(location: &'a Location, label: Cow<'a, str>) -> Vec<Snippet<'a>> {
        let range = location.byte_range();
        let role = SpanRole::Primary { label };
        let spans = vec![Span { range, role }];
        let mut snippets = vec![Snippet::with_code_and_spans(&location.code, spans)];
        location.code.source.extend_with_context(&mut snippets);
        snippets
    }

    /// Returns the string held in `self.code.value`.
    ///
    /// This method returns a reference to the string held in `self.code.value`.
    /// `Snippet` internally holds a `Ref` to the string, which provides an
    /// access to the string without making a new borrow.
    #[inline(always)]
    #[must_use]
    pub fn code_string(&self) -> &str {
        &self.code_string
    }
}

impl Clone for Snippet<'_> {
    fn clone(&self) -> Self {
        Snippet {
            code: self.code,
            code_string: Ref::clone(&self.code_string),
            spans: self.spans.clone(),
        }
    }
}

impl PartialEq<Snippet<'_>> for Snippet<'_> {
    fn eq(&self, other: &Snippet<'_>) -> bool {
        self.code == other.code && self.spans == other.spans
    }
}

impl Eq for Snippet<'_> {}

/// Type of [`Footnote`]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum FootnoteType {
    /// No specific type
    #[default]
    None,
    /// For footnotes that provide additional information
    Note,
    /// For footnotes that provide suggestions
    Suggestion,
}

/// Message without associated source code
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Footnote<'a> {
    /// Type of this footnote
    pub r#type: FootnoteType,
    /// Text of this footnote
    pub label: Cow<'a, str>,
}

/// Entire report containing multiple snippets
///
/// `Report` is an intermediate data structure for constructing a diagnostic
/// message. It contains multiple [`Snippet`]s, each of which corresponds to a
/// specific part of the source code being analyzed.
/// See the [module documentation](self) for more details.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct Report<'a> {
    /// Type of this report
    pub r#type: ReportType,
    /// Optional identifier of this report (e.g., error code)
    pub id: Option<Cow<'a, str>>,
    /// Main caption of this report
    pub title: Cow<'a, str>,
    /// Source code fragments annotated with additional information
    pub snippets: Vec<Snippet<'a>>,
    /// Additional message without associated source code
    pub footnotes: Vec<Footnote<'a>>,
}

impl Report<'_> {
    /// Creates a new, empty report.
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Report::default()
    }
}

/// Returns a mutable reference to the snippet for the given code, creating it
/// if necessary.
///
/// This is a utility function used in constructing a vector of snippets.
///
/// If a snippet for the given code already exists in the vector, this function
/// returns a mutable reference to that snippet. Otherwise, it creates a new
/// snippet with the given code and appends it to the vector, returning a
/// mutable reference to the newly created snippet.
pub fn snippet_for_code<'a, 'b>(
    snippets: &'b mut Vec<Snippet<'a>>,
    code: &'a super::Code,
) -> &'b mut Snippet<'a> {
    // if let Some(snippet) = snippets.iter_mut().find(|s| std::ptr::eq(s.code, code)) {
    //     snippet
    if let Some(i) = snippets.iter().position(|s| std::ptr::eq(s.code, code)) {
        &mut snippets[i]
    } else {
        // TODO Use Vec::push_mut when stabilized
        snippets.push(Snippet::with_code(code));
        snippets.last_mut().unwrap()
    }
}

/// Adds a span to the appropriate snippet in the given vector.
///
/// This is a utility function used in constructing a vector of snippets with
/// annotated spans.
///
/// If a snippet for the given code already exists in the vector, this function
/// adds the span to that snippet. Otherwise, it creates a new snippet with the
/// given code and span, and appends it to the vector.
pub fn add_span<'a>(code: &'a super::Code, span: Span<'a>, snippets: &mut Vec<Snippet<'a>>) {
    snippet_for_code(snippets, code).spans.push(span);
}

#[test]
fn test_add_span_with_matching_code() {
    let code = Rc::new(super::Code {
        value: std::cell::RefCell::new("echo hello".to_string()),
        start_line_number: std::num::NonZero::new(1).unwrap(),
        source: Rc::new(super::Source::CommandString),
    });
    let span = Span {
        range: 5..10,
        role: SpanRole::Primary {
            label: "greeting".into(),
        },
    };
    let mut snippets = vec![Snippet::with_code(&code)];

    add_span(&code, span, &mut snippets);

    assert_eq!(snippets.len(), 1);
    assert_eq!(snippets[0].spans.len(), 1);
    assert_eq!(snippets[0].spans[0].range, 5..10);
    assert_eq!(
        snippets[0].spans[0].role,
        SpanRole::Primary {
            label: "greeting".into()
        }
    );
}

#[test]
fn test_add_span_without_matching_code() {
    let code1 = Rc::new(super::Code {
        value: std::cell::RefCell::new("echo hello".to_string()),
        start_line_number: std::num::NonZero::new(1).unwrap(),
        source: Rc::new(super::Source::CommandString),
    });
    let code2 = Rc::new(super::Code {
        value: std::cell::RefCell::new("ls -l".to_string()),
        start_line_number: std::num::NonZero::new(1).unwrap(),
        source: Rc::new(super::Source::CommandString),
    });
    let span = Span {
        range: 0..2,
        role: SpanRole::Primary {
            label: "list".into(),
        },
    };
    let mut snippets = vec![Snippet::with_code(&code1)];

    add_span(&code2, span, &mut snippets);

    assert_eq!(snippets.len(), 2);
    assert_eq!(snippets[0].code.value.borrow().as_str(), "echo hello");
    assert_eq!(snippets[0].spans.len(), 0);
    assert_eq!(snippets[1].code.value.borrow().as_str(), "ls -l");
    assert_eq!(snippets[1].spans.len(), 1);
    assert_eq!(snippets[1].spans[0].range, 0..2);
    assert_eq!(
        snippets[1].spans[0].role,
        SpanRole::Primary {
            label: "list".into()
        }
    );
}

impl super::Source {
    /// Extends the given vector of snippets with spans annotating the context of this source.
    ///
    /// If `self` is a source that has a related location (e.g., the `original` field of
    /// `CommandSubst`), this method adds one or more spans describing the location to the given
    /// vector. If the `code` of the location is already present in the vector, it adds the span
    /// to the existing snippet; otherwise, it creates a new snippet.
    ///
    /// If `self` does not have a related location, this method does nothing.
    pub fn extend_with_context<'a>(&'a self, snippets: &mut Vec<Snippet<'a>>) {
        use super::Source::*;
        match self {
            Unknown
            | Stdin
            | CommandString
            | CommandFile { .. }
            | VariableValue { .. }
            | InitFile { .. }
            | Other { .. } => (),

            CommandSubst { original } => {
                let range = original.byte_range();
                let role = SpanRole::Supplementary {
                    label: "command substitution appeared here".into(),
                };
                add_span(&original.code, Span { range, role }, snippets);
            }

            Arith { original } => {
                let range = original.byte_range();
                let role = SpanRole::Supplementary {
                    label: "arithmetic expansion appeared here".into(),
                };
                add_span(&original.code, Span { range, role }, snippets);
            }

            Eval { original } => {
                let range = original.byte_range();
                let role = SpanRole::Supplementary {
                    label: "command passed to the eval built-in here".into(),
                };
                add_span(&original.code, Span { range, role }, snippets);
            }

            DotScript { name, origin } => {
                let range = origin.byte_range();
                let role = SpanRole::Supplementary {
                    label: format!("script `{name}` was sourced here").into(),
                };
                add_span(&origin.code, Span { range, role }, snippets);
            }

            Trap { origin, .. } => {
                let range = origin.byte_range();
                let role = SpanRole::Supplementary {
                    label: "trap was set here".into(),
                };
                add_span(&origin.code, Span { range, role }, snippets);
            }

            Alias { original, alias } => {
                // Where the alias was substituted
                let range = original.byte_range();
                let role = SpanRole::Supplementary {
                    label: format!("alias `{}` was substituted here", alias.name).into(),
                };
                add_span(&original.code, Span { range, role }, snippets);
                // Recurse into the source of the substituted code
                original.code.source.extend_with_context(snippets);

                // Where the alias was defined
                let range = alias.origin.byte_range();
                let role = SpanRole::Supplementary {
                    label: format!("alias `{}` was defined here", alias.name).into(),
                };
                add_span(&alias.origin.code, Span { range, role }, snippets);
                // Recurse into the source of the alias definition
                alias.origin.code.source.extend_with_context(snippets);
            }
        }
    }
}

mod annotate_snippets_support {
    use super::*;

    impl From<ReportType> for annotate_snippets::Level<'_> {
        fn from(r#type: ReportType) -> Self {
            use ReportType::*;
            match r#type {
                None => Self::INFO.no_name(),
                Error => Self::ERROR,
                Warning => Self::WARNING,
            }
        }
    }

    /// Converts `yash_env::source::pretty::Span` into
    /// `annotate_snippets::Annotation`.
    ///
    /// This conversion is not provided as a public `From<&Span> for Annotation` implementation
    /// because a future variant of `SpanRole` may map to
    /// `annotate_snippets::Patch` instead of `annotate_snippets::Annotation`.
    fn span_to_annotation<'a>(span: &'a Span<'a>) -> annotate_snippets::Annotation<'a> {
        use annotate_snippets::AnnotationKind as AK;
        let (kind, label) = match &span.role {
            SpanRole::Primary { label } => (AK::Primary, label),
            SpanRole::Supplementary { label } => (AK::Context, label),
        };
        kind.span(span.range.clone()).label(label)
    }

    // `From<&Snippet>` is not implemented for
    // `annotate_snippets::Snippet<'_, annotate_snippets::Annotation<'_>>`
    // because a future variant of `SpanRole` may map to
    // `annotate_snippets::Patch` instead of `annotate_snippets::Annotation`.

    /// Converts `yash_env::source::pretty::Snippet` into
    /// `annotate_snippets::Snippet<'a, annotate_snippets::Annotation<'a>>`.
    ///
    /// This conversion is not provided as a public `From<&Snippet> for Snippet` implementation
    /// because a future variant of `SpanRole` may map to
    /// `annotate_snippets::Patch` instead of `annotate_snippets::Annotation`, which does not fit
    /// into a single `annotate_snippets::Snippet<'a, annotate_snippets::Annotation<'a>>`.
    fn snippet_to_annotation_snippet<'a>(
        snippet: &'a Snippet<'a>,
    ) -> annotate_snippets::Snippet<'a, annotate_snippets::Annotation<'a>> {
        annotate_snippets::Snippet::source(snippet.code_string())
            .line_start(
                snippet
                    .code
                    .start_line_number
                    .get()
                    .try_into()
                    .unwrap_or(usize::MAX),
            )
            .path(snippet.code.source.label())
            .annotations(snippet.spans.iter().map(span_to_annotation))
    }

    /// Converts `yash_env::source::pretty::FootnoteType` into
    /// `annotate_snippets::Level`.
    impl From<FootnoteType> for annotate_snippets::Level<'_> {
        fn from(r#type: FootnoteType) -> Self {
            use FootnoteType::*;
            match r#type {
                None => Self::INFO.no_name(),
                Note => Self::NOTE,
                Suggestion => Self::HELP,
            }
        }
    }

    /// Converts `yash_env::source::pretty::Footnote` into
    /// `annotate_snippets::Message`.
    impl<'a> From<Footnote<'a>> for annotate_snippets::Message<'a> {
        fn from(footer: Footnote<'a>) -> Self {
            annotate_snippets::Level::from(footer.r#type).message(footer.label)
        }
    }

    /// Converts `&yash_env::source::pretty::Footnote` into
    /// `annotate_snippets::Message`.
    impl<'a> From<&'a Footnote<'a>> for annotate_snippets::Message<'a> {
        fn from(footer: &'a Footnote<'a>) -> Self {
            annotate_snippets::Level::from(footer.r#type).message(&*footer.label)
        }
    }

    /// Converts `yash_env::source::pretty::Report` into
    /// `annotate_snippets::Group`.
    impl<'a> From<&'a Report<'a>> for annotate_snippets::Group<'a> {
        fn from(report: &'a Report<'a>) -> Self {
            let title = annotate_snippets::Level::from(report.r#type).primary_title(&*report.title);
            let title = if let Some(id) = &report.id {
                title.id(&**id)
            } else {
                title
            };

            title
                .elements(report.snippets.iter().map(snippet_to_annotation_snippet))
                .elements(
                    report
                        .footnotes
                        .iter()
                        .map(annotate_snippets::Message::from),
                )
        }
    }
}