summaryrefslogtreecommitdiff
path: root/dhall/src/error/builder.rs
blob: 22b0d7752faeefe45284a13c2affe6ec4131f746 (plain)
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
use annotate_snippets::{
    display_list::DisplayList,
    formatter::DisplayListFormatter,
    snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation},
};

use crate::syntax::{ParsedSpan, Span};

#[derive(Debug, Clone, Default)]
pub struct ErrorBuilder {
    title: FreeAnnotation,
    annotations: Vec<SpannedAnnotation>,
    footer: Vec<FreeAnnotation>,
    /// Inducate that the current builder has already been consumed and consuming it again should
    /// panic.
    consumed: bool,
}

#[derive(Debug, Clone)]
struct SpannedAnnotation {
    span: ParsedSpan,
    message: String,
    annotation_type: AnnotationType,
}

#[derive(Debug, Clone)]
struct FreeAnnotation {
    message: String,
    annotation_type: AnnotationType,
}

impl SpannedAnnotation {
    fn into_annotation(self) -> SourceAnnotation {
        SourceAnnotation {
            label: self.message,
            annotation_type: self.annotation_type,
            range: self.span.as_char_range(),
        }
    }
}

impl FreeAnnotation {
    fn into_annotation(self) -> Annotation {
        Annotation {
            label: Some(self.message),
            id: None,
            annotation_type: self.annotation_type,
        }
    }
}

/// A builder that uses the annotate_snippets library to display nice error messages about source
/// code locations.
impl ErrorBuilder {
    pub fn new(message: impl ToString) -> Self {
        ErrorBuilder {
            title: FreeAnnotation {
                message: message.to_string(),
                annotation_type: AnnotationType::Error,
            },
            annotations: Vec::new(),
            footer: Vec::new(),
            consumed: false,
        }
    }
    pub fn new_span_err(span: &Span, message: impl ToString) -> Self {
        let message = message.to_string();
        let mut builder = Self::new(message.clone());
        builder.span_err(span, message);
        builder
    }

    pub fn span_err(
        &mut self,
        span: &Span,
        message: impl ToString,
    ) -> &mut Self {
        // Ignore spans not coming from a source file
        let span = match span {
            Span::Parsed(span) => span,
            _ => return self,
        };
        self.annotations.push(SpannedAnnotation {
            span: span.clone(),
            message: message.to_string(),
            annotation_type: AnnotationType::Error,
        });
        self
    }
    pub fn span_help(
        &mut self,
        span: &Span,
        message: impl ToString,
    ) -> &mut Self {
        // Ignore spans not coming from a source file
        let span = match span {
            Span::Parsed(span) => span,
            _ => return self,
        };
        self.annotations.push(SpannedAnnotation {
            span: span.clone(),
            message: message.to_string(),
            annotation_type: AnnotationType::Help,
        });
        self
    }
    pub fn help(&mut self, message: impl ToString) -> &mut Self {
        self.footer.push(FreeAnnotation {
            message: message.to_string(),
            annotation_type: AnnotationType::Help,
        });
        self
    }

    // TODO: handle multiple files
    pub fn format(&mut self) -> String {
        if self.consumed {
            panic!("tried to format the same ErrorBuilder twice")
        }
        let this = std::mem::replace(self, ErrorBuilder::default());
        self.consumed = true;
        drop(self); // Get rid of the self reference so we don't use it by mistake.

        let slices = if this.annotations.is_empty() {
            Vec::new()
        } else {
            let input = this.annotations[0].span.to_input();
            let annotations = this
                .annotations
                .into_iter()
                .map(|annot| annot.into_annotation())
                .collect();
            vec![Slice {
                source: input,
                line_start: 1, // TODO
                origin: Some("<current file>".to_string()),
                fold: true,
                annotations,
            }]
        };
        let footer = this
            .footer
            .into_iter()
            .map(|annot| annot.into_annotation())
            .collect();

        let snippet = Snippet {
            title: Some(this.title.into_annotation()),
            slices,
            footer,
        };
        let dl = DisplayList::from(snippet);
        let dlf = DisplayListFormatter::new(true, false);
        format!("{}", dlf.format(&dl))
    }
}

impl Default for FreeAnnotation {
    fn default() -> Self {
        FreeAnnotation {
            message: String::new(),
            annotation_type: AnnotationType::Error,
        }
    }
}