Skip to main content

cranelift_isle/
error.rs

1//! Error types.
2
3use std::sync::Arc;
4
5use crate::{files::Files, lexer::Pos};
6
7/// A collection of errors from attempting to compile some ISLE source files.
8pub struct Errors {
9    /// The individual errors.
10    pub errors: Vec<Error>,
11    pub(crate) files: Arc<Files>,
12}
13
14impl std::fmt::Debug for Errors {
15    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
16        if self.errors.is_empty() {
17            return Ok(());
18        }
19        let diagnostics = Vec::from_iter(self.errors.iter().map(|e| {
20            let message = match e {
21                Error::IoError { context, .. } => context.clone(),
22                Error::ParseError { msg, .. } => format!("parse error: {msg}"),
23                Error::TypeError { msg, .. } => format!("type error: {msg}"),
24                Error::UnreachableError { msg, .. } => format!("unreachable rule: {msg}"),
25                Error::OverlapError { msg, .. } => format!("overlap error: {msg}"),
26                Error::RecursionError { msg, .. } => format!("recursion error: {msg}"),
27                Error::ShadowedError { .. } => {
28                    "more general higher-priority rule shadows other rules".to_string()
29                }
30            };
31
32            let labels = match e {
33                Error::IoError { .. } => vec![],
34
35                Error::ParseError { span, .. }
36                | Error::TypeError { span, .. }
37                | Error::UnreachableError { span, .. }
38                | Error::RecursionError { span, .. } => {
39                    vec![Label::primary(span.from.file, span)]
40                }
41
42                Error::OverlapError { rules, .. } => {
43                    let mut labels = vec![Label::primary(rules[0].from.file, &rules[0])];
44                    labels.extend(
45                        rules[1..]
46                            .iter()
47                            .map(|span| Label::secondary(span.from.file, span)),
48                    );
49                    labels
50                }
51
52                Error::ShadowedError { shadowed, mask } => {
53                    let mut labels = vec![Label::primary(mask.from.file, mask)];
54                    labels.extend(
55                        shadowed
56                            .iter()
57                            .map(|span| Label::secondary(span.from.file, span)),
58                    );
59                    labels
60                }
61            };
62
63            let mut sources = Vec::new();
64            let mut source = e.source();
65            while let Some(e) = source {
66                sources.push(format!("{e:?}"));
67                source = std::error::Error::source(e);
68            }
69
70            Diagnostic::error()
71                .with_message(message)
72                .with_labels(labels)
73                .with_notes(sources)
74        }));
75        self.emit(f, diagnostics)?;
76        if self.errors.len() > 1 {
77            writeln!(f, "found {} errors", self.errors.len())?;
78        }
79        Ok(())
80    }
81}
82
83/// Errors produced by ISLE.
84#[derive(Debug)]
85pub enum Error {
86    /// An I/O error.
87    IoError {
88        /// The underlying I/O error.
89        error: std::io::Error,
90        /// The context explaining what caused the I/O error.
91        context: String,
92    },
93
94    /// The input ISLE source has a parse error.
95    ParseError {
96        /// The error message.
97        msg: String,
98
99        /// The location of the parse error.
100        span: Span,
101    },
102
103    /// The input ISLE source has a type error.
104    TypeError {
105        /// The error message.
106        msg: String,
107
108        /// The location of the type error.
109        span: Span,
110    },
111
112    /// The rule can never match any input.
113    UnreachableError {
114        /// The error message.
115        msg: String,
116
117        /// The location of the unreachable rule.
118        span: Span,
119    },
120
121    /// The rules mentioned overlap in the input they accept.
122    OverlapError {
123        /// The error message.
124        msg: String,
125
126        /// The locations of all the rules that overlap. When there are more than two rules
127        /// present, the first rule is the one with the most overlaps (likely a fall-through
128        /// wildcard case).
129        rules: Vec<Span>,
130    },
131
132    /// Recursive rules error. Term is recursive without explicit opt-in.
133    RecursionError {
134        /// The error message.
135        msg: String,
136
137        /// The location of the term declaration.
138        span: Span,
139    },
140
141    /// The rules can never match because another rule will always match first.
142    ShadowedError {
143        /// The locations of the unmatchable rules.
144        shadowed: Vec<Span>,
145
146        /// The location of the rule that shadows them.
147        mask: Span,
148    },
149}
150
151impl Errors {
152    /// Create new Errors
153    pub fn new(errors: Vec<Error>, files: Arc<Files>) -> Self {
154        Self { errors, files }
155    }
156
157    /// Create `isle::Errors` from the given I/O error and context.
158    pub fn from_io(error: std::io::Error, context: impl Into<String>) -> Self {
159        Errors {
160            errors: vec![Error::IoError {
161                error,
162                context: context.into(),
163            }],
164            files: Arc::new(Files::default()),
165        }
166    }
167
168    #[cfg(feature = "fancy-errors")]
169    fn emit(
170        &self,
171        f: &mut std::fmt::Formatter,
172        diagnostics: Vec<Diagnostic<usize>>,
173    ) -> std::fmt::Result {
174        use codespan_reporting::term::termcolor;
175        let w = termcolor::BufferWriter::stderr(termcolor::ColorChoice::Auto);
176        let mut b = w.buffer();
177        let mut files = codespan_reporting::files::SimpleFiles::new();
178        for (name, source) in self
179            .files
180            .file_names
181            .iter()
182            .zip(self.files.file_texts.iter())
183        {
184            files.add(name, source);
185        }
186        for diagnostic in diagnostics {
187            codespan_reporting::term::emit(&mut b, &Default::default(), &files, &diagnostic)
188                .map_err(|_| std::fmt::Error)?;
189        }
190        let b = b.into_inner();
191        let b = std::str::from_utf8(&b).map_err(|_| std::fmt::Error)?;
192        f.write_str(b)
193    }
194
195    #[cfg(not(feature = "fancy-errors"))]
196    fn emit(
197        &self,
198        f: &mut std::fmt::Formatter,
199        diagnostics: Vec<Diagnostic<usize>>,
200    ) -> std::fmt::Result {
201        let pos = |file_id: usize, offset| {
202            let ends = self.files.file_line_map(file_id).unwrap();
203            let line0 = ends.line(offset);
204            let text = &self.files.file_texts[file_id];
205            let start = line0.checked_sub(1).map_or(0, |prev| ends[prev]);
206            let end = ends.get(line0).copied().unwrap_or(text.len());
207            let col = offset - start + 1;
208            format!(
209                "{}:{}:{}: {}",
210                self.files.file_names[file_id],
211                line0 + 1,
212                col,
213                &text[start..end]
214            )
215        };
216        for diagnostic in diagnostics {
217            writeln!(f, "{}", diagnostic.message)?;
218            for label in diagnostic.labels {
219                f.write_str(&pos(label.file_id, label.range.start))?;
220            }
221            for note in diagnostic.notes {
222                writeln!(f, "{note}")?;
223            }
224            writeln!(f)?;
225        }
226        Ok(())
227    }
228}
229
230impl Error {
231    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
232        match self {
233            Error::IoError { error, .. } => Some(error),
234            _ => None,
235        }
236    }
237}
238
239/// A span in a given source.
240#[derive(Clone, Debug)]
241pub struct Span {
242    /// The byte offset of the start of the span.
243    pub from: Pos,
244    /// The byte offset of the end of the span.
245    pub to: Pos,
246}
247
248impl Span {
249    /// Create a new span that covers one character at the given offset.
250    pub fn new_single(pos: Pos) -> Span {
251        Span {
252            from: pos,
253            // This is a slight hack (we don't actually look at the
254            // file to find line/col of next char); but the `to`
255            // position only matters for pretty-printed errors and only
256            // the offset is used in that case.
257            to: Pos {
258                file: pos.file,
259                offset: pos.offset + 1,
260            },
261        }
262    }
263}
264
265impl From<&Span> for std::ops::Range<usize> {
266    fn from(span: &Span) -> Self {
267        span.from.offset..span.to.offset
268    }
269}
270
271use diagnostic::{Diagnostic, Label};
272
273#[cfg(feature = "fancy-errors")]
274use codespan_reporting::diagnostic;
275
276#[cfg(not(feature = "fancy-errors"))]
277/// Minimal versions of types from codespan-reporting.
278mod diagnostic {
279    use std::ops::Range;
280
281    pub struct Diagnostic<FileId> {
282        pub message: String,
283        pub labels: Vec<Label<FileId>>,
284        pub notes: Vec<String>,
285    }
286
287    impl<FileId> Diagnostic<FileId> {
288        pub fn error() -> Self {
289            Self {
290                message: String::new(),
291                labels: Vec::new(),
292                notes: Vec::new(),
293            }
294        }
295
296        pub fn with_message(mut self, message: impl Into<String>) -> Self {
297            self.message = message.into();
298            self
299        }
300
301        pub fn with_labels(mut self, labels: Vec<Label<FileId>>) -> Self {
302            self.labels = labels;
303            self
304        }
305
306        pub fn with_notes(mut self, notes: Vec<String>) -> Self {
307            self.notes = notes;
308            self
309        }
310    }
311
312    pub struct Label<FileId> {
313        pub file_id: FileId,
314        pub range: Range<usize>,
315    }
316
317    impl<FileId> Label<FileId> {
318        pub fn primary(file_id: FileId, range: impl Into<Range<usize>>) -> Self {
319            Self {
320                file_id,
321                range: range.into(),
322            }
323        }
324
325        pub fn secondary(file_id: FileId, range: impl Into<Range<usize>>) -> Self {
326            Self::primary(file_id, range)
327        }
328    }
329}