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
//! Source spans and the unified compile error type.
use thiserror::Error;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// A half-open byte range `[start, end)` into the original source string.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Span {
/// Start byte offset (inclusive).
pub start: usize,
/// End byte offset (exclusive).
pub end: usize,
}
impl Span {
/// Construct a span from a start and end byte offset.
pub fn new(start: usize, end: usize) -> Self {
Self { start, end }
}
/// A span covering both `self` and `other`.
pub fn merge(self, other: Span) -> Span {
Span::new(self.start.min(other.start), self.end.max(other.end))
}
}
/// Any error produced while compiling rill-lang source.
#[derive(Error, Debug, Clone, PartialEq)]
pub enum CompileError {
/// The lexer hit a character it cannot start a token with.
#[error("lex error at {span:?}: {msg}")]
Lex {
/// Human-readable cause.
msg: String,
/// Location in source.
span: Span,
},
/// The parser encountered unexpected or missing tokens.
#[error("parse error at {span:?}: {msg}")]
Parse {
/// Human-readable cause.
msg: String,
/// Location in source.
span: Span,
},
/// The type checker rejected the program (arity or scalar mismatch, etc.).
#[error("type error at {span:?}: {msg}")]
Type {
/// Human-readable cause.
msg: String,
/// Location in source.
span: Span,
},
/// A well-typed program that the MVP backend cannot lower/run.
#[error("unsupported: {0}")]
Unsupported(String),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn span_merge_covers_both() {
let a = Span::new(2, 5);
let b = Span::new(8, 10);
assert_eq!(a.merge(b), Span::new(2, 10));
}
}