1use serde::{Deserialize, Serialize};
2use std::fmt;
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
6pub struct Span {
7 pub start: u32,
9 pub end: u32,
11}
12
13impl Span {
14 pub fn new(start: usize, end: usize) -> Self {
16 Self {
17 start: start as u32,
18 end: end as u32,
19 }
20 }
21
22 pub fn range(self) -> std::ops::Range<usize> {
24 self.start as usize..self.end as usize
25 }
26
27 pub(crate) fn to(self, last: Span) -> Span {
29 Span {
30 start: self.start,
31 end: last.end,
32 }
33 }
34
35 pub fn line_col(self, src: &str) -> (usize, usize) {
38 let location = Lines::new(src).locate(self.start as usize);
39 (location.line, location.column)
40 }
41}
42
43#[derive(Debug, Clone)]
45#[allow(missing_docs)] pub enum CompileError {
47 Syntax { message: String, span: Span },
49 TooDeep { limit: usize, span: Span },
51 TooLarge { bytes: usize, limit: usize },
53}
54
55impl CompileError {
56 pub fn span(&self) -> Option<Span> {
58 match self {
59 CompileError::Syntax { span, .. } | CompileError::TooDeep { span, .. } => Some(*span),
60 CompileError::TooLarge { .. } => None,
61 }
62 }
63
64 pub fn report(&self, src: &str) -> String {
74 snippet(&Lines::new(src), self.span(), &self.headline())
75 }
76
77 pub fn report_all(src: &str, errors: &[CompileError]) -> String {
79 let lines = Lines::new(src);
80 errors
81 .iter()
82 .map(|e| snippet(&lines, e.span(), &e.headline()))
83 .collect::<Vec<_>>()
84 .join("\n\n")
85 }
86
87 fn headline(&self) -> String {
89 match self {
90 CompileError::Syntax { message, .. } => message.clone(),
91 CompileError::TooDeep { limit, .. } => {
92 format!("template nests too deeply (limit {limit} levels)")
93 }
94 CompileError::TooLarge { bytes, limit } => {
95 format!("template is too large: {bytes} bytes exceeds the limit of {limit}")
96 }
97 }
98 }
99}
100
101#[derive(Debug, Clone)]
103#[allow(missing_docs)] pub enum RenderError {
105 MissingPath {
107 path: String,
108 key: Option<String>,
109 span: Span,
110 },
111 TypeMismatch {
113 expected: &'static str,
114 got: String,
115 span: Span,
116 },
117 DivideByZero { span: Span },
119 ArithmeticOverflow { span: Span },
121 WhenNoMatch { span: Span },
123 UnknownMethod {
125 method: String,
126 on_type: String,
127 span: Span,
128 },
129 ArityMismatch {
131 method: String,
132 expected: usize,
133 got: usize,
134 span: Span,
135 },
136 IndexOutOfBounds {
138 index: i64,
139 length: usize,
140 span: Span,
141 },
142 NotIndexable { got: String, span: Span },
144 LambdaExpected { span: Span },
146 ValueTooDeep { limit: usize, span: Span },
148 DuplicateKey { key: String, span: Span },
150 Deserialize(String),
152}
153
154impl RenderError {
155 pub fn span(&self) -> Option<Span> {
157 match self {
158 RenderError::MissingPath { span, .. }
159 | RenderError::TypeMismatch { span, .. }
160 | RenderError::DivideByZero { span }
161 | RenderError::ArithmeticOverflow { span }
162 | RenderError::WhenNoMatch { span }
163 | RenderError::UnknownMethod { span, .. }
164 | RenderError::ArityMismatch { span, .. }
165 | RenderError::IndexOutOfBounds { span, .. }
166 | RenderError::NotIndexable { span, .. }
167 | RenderError::LambdaExpected { span }
168 | RenderError::ValueTooDeep { span, .. }
169 | RenderError::DuplicateKey { span, .. } => Some(*span),
170 RenderError::Deserialize(_) => None,
171 }
172 }
173
174 pub fn report(&self, src: &str) -> String {
177 snippet(&Lines::new(src), self.span(), &self.to_string())
178 }
179
180 #[cold]
181 pub(crate) fn type_mismatch(
182 expected: &'static str,
183 got: impl Into<String>,
184 span: Span,
185 ) -> Self {
186 RenderError::TypeMismatch {
187 expected,
188 got: got.into(),
189 span,
190 }
191 }
192
193 #[cold]
194 pub(crate) fn missing_field(name: &str, span: Span) -> Self {
195 RenderError::MissingPath {
196 path: name.to_string(),
197 key: Some(name.to_string()),
198 span,
199 }
200 }
201
202 #[cold]
203 pub(crate) fn not_indexable(got: &str, span: Span) -> Self {
204 RenderError::NotIndexable {
205 got: got.to_string(),
206 span,
207 }
208 }
209
210 #[cold]
211 pub(crate) fn unknown_method(method: &str, on_type: &str, span: Span) -> Self {
212 RenderError::UnknownMethod {
213 method: method.to_string(),
214 on_type: on_type.to_string(),
215 span,
216 }
217 }
218}
219
220#[derive(Debug, Clone)]
222#[allow(missing_docs)] pub enum LoadError {
224 Corrupt(String),
226 IncompatibleVersion { found: u32, expected: u32 },
228}
229
230impl fmt::Display for CompileError {
231 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232 match self.span() {
233 Some(span) => write!(f, "{} at {}..{}", self.headline(), span.start, span.end),
234 None => write!(f, "{}", self.headline()),
235 }
236 }
237}
238
239impl fmt::Display for RenderError {
240 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
241 match self {
242 RenderError::MissingPath { path, key, .. } => match key {
243 Some(k) => write!(f, "missing field `{k}` while resolving `{path}`"),
244 None => write!(f, "missing path `{path}`"),
245 },
246 RenderError::TypeMismatch { expected, got, .. } => {
247 write!(f, "type mismatch: expected {expected}, got {got}")
248 }
249 RenderError::DivideByZero { .. } => write!(f, "divide by zero"),
250 RenderError::ArithmeticOverflow { .. } => write!(f, "arithmetic overflow"),
251 RenderError::WhenNoMatch { .. } => {
252 write!(f, "no `when` branch matched and no `else` provided")
253 }
254 RenderError::UnknownMethod {
255 method, on_type, ..
256 } => write!(f, "no method `{method}` on {on_type}"),
257 RenderError::ArityMismatch {
258 method,
259 expected,
260 got,
261 ..
262 } => write!(f, "{}", arity_message(method, &arguments(*expected), *got)),
263 RenderError::IndexOutOfBounds { index, length, .. } => write!(
264 f,
265 "index {index} out of bounds for array of length {length}"
266 ),
267 RenderError::NotIndexable { got, .. } => write!(f, "cannot index into {got}"),
268 RenderError::LambdaExpected { .. } => write!(f, "expected a lambda"),
269 RenderError::ValueTooDeep { limit, .. } => {
270 write!(f, "value nests deeper than the limit of {limit} levels")
271 }
272 RenderError::DuplicateKey { key, .. } => write!(f, "duplicate object key `{key}`"),
273 RenderError::Deserialize(msg) => write!(f, "deserialize error: {msg}"),
274 }
275 }
276}
277
278impl fmt::Display for LoadError {
279 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280 match self {
281 LoadError::Corrupt(s) => write!(f, "corrupt blob: {s}"),
282 LoadError::IncompatibleVersion { found, expected } => write!(
283 f,
284 "incompatible blob version: found {found}, expected {expected}"
285 ),
286 }
287 }
288}
289
290#[derive(Debug, Clone)]
292#[allow(missing_docs)] pub enum EvalError {
294 Render(RenderError),
296 BudgetExceeded { limit: u64, span: Span },
298 TooDeep { limit: u32, span: Span },
301}
302
303impl EvalError {
304 pub fn span(&self) -> Option<Span> {
306 match self {
307 EvalError::Render(e) => e.span(),
308 EvalError::BudgetExceeded { span, .. } | EvalError::TooDeep { span, .. } => Some(*span),
309 }
310 }
311
312 pub fn report(&self, src: &str) -> String {
314 snippet(&Lines::new(src), self.span(), &self.to_string())
315 }
316
317 pub fn is_budget_exceeded(&self) -> bool {
319 matches!(self, EvalError::BudgetExceeded { .. })
320 }
321}
322
323impl From<RenderError> for EvalError {
324 fn from(e: RenderError) -> Self {
325 EvalError::Render(e)
326 }
327}
328
329impl fmt::Display for EvalError {
330 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331 match self {
332 EvalError::Render(e) => e.fmt(f),
333 EvalError::BudgetExceeded { limit, .. } => {
334 write!(f, "evaluation budget of {limit} steps exceeded")
335 }
336 EvalError::TooDeep { limit, .. } => {
337 write!(f, "evaluation nests more than {limit} levels deep")
338 }
339 }
340 }
341}
342
343impl std::error::Error for EvalError {
344 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
345 match self {
346 EvalError::Render(e) => Some(e),
347 EvalError::BudgetExceeded { .. } | EvalError::TooDeep { .. } => None,
348 }
349 }
350}
351
352impl std::error::Error for CompileError {}
353impl std::error::Error for RenderError {}
354impl std::error::Error for LoadError {}
355
356pub(crate) fn arity_message(name: &str, takes: &str, got: usize) -> String {
357 format!("`{name}` takes {takes}, got {got}")
358}
359
360pub(crate) fn arguments(count: usize) -> String {
361 if count == 1 {
362 "1 argument".to_string()
363 } else {
364 format!("{count} arguments")
365 }
366}
367
368pub(crate) struct Lines<'a> {
370 src: &'a str,
371 starts: Vec<usize>,
372}
373
374impl<'a> Lines<'a> {
375 pub(crate) fn new(src: &'a str) -> Self {
376 let mut starts = vec![0];
377 starts.extend(
378 src.bytes()
379 .enumerate()
380 .filter(|&(_, b)| b == b'\n')
381 .map(|(i, _)| i + 1),
382 );
383 Lines { src, starts }
384 }
385
386 pub(crate) fn locate(&self, at: usize) -> Location<'a> {
387 let at = floor_char_boundary(self.src, at);
388 let line_index = self.starts.partition_point(|&start| start <= at) - 1;
389 let start = self.starts[line_index];
390 let end = self
391 .starts
392 .get(line_index + 1)
393 .map_or(self.src.len(), |&next_start| next_start - 1);
394 let text = self.src[start..end]
395 .strip_suffix('\r')
396 .unwrap_or(&self.src[start..end]);
397 Location {
398 line: line_index + 1,
399 column: self.src[start..at].chars().count() + 1,
400 text,
401 }
402 }
403}
404
405pub(crate) struct Location<'a> {
407 pub line: usize,
408 pub column: usize,
409 pub text: &'a str,
410}
411
412pub(crate) fn snippet(lines: &Lines, span: Option<Span>, message: &str) -> String {
413 let Some(span) = span else {
414 return format!("error: {message}");
415 };
416 let at = lines.locate(span.start as usize);
417 let line_number = at.line.to_string();
418 let gutter = " ".repeat(line_number.len());
419 let indent = " ".repeat(at.column - 1);
420 let carets = "^".repeat(caret_width(lines.src, span));
421 format!(
422 "error: {message}\n{gutter} --> {}:{}\n{gutter} |\n{line_number} | {}\n{gutter} | {indent}{carets}",
423 at.line, at.column, at.text
424 )
425}
426
427fn caret_width(src: &str, span: Span) -> usize {
428 let start = floor_char_boundary(src, span.start as usize);
429 let end = floor_char_boundary(src, span.end as usize).max(start);
430 let first_line = src[start..end].split('\n').next().unwrap_or("");
431 first_line.chars().count().max(1)
432}
433
434fn floor_char_boundary(src: &str, mut i: usize) -> usize {
435 if i >= src.len() {
436 return src.len();
437 }
438 while i > 0 && !src.is_char_boundary(i) {
439 i -= 1;
440 }
441 i
442}