1use std::path::PathBuf;
2
3use crate::ast::Span;
4
5pub type Result<T> = std::result::Result<T, Error>;
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
8pub enum ErrorCode {
9 InvalidCharacter,
10 InvalidWhitespace,
11 InvalidEscape,
12 UnexpectedToken,
13 UnterminatedString,
14 InvalidNumber,
15 InvalidRootType,
16 DuplicateKey,
17 PathConflict,
18 MissingReference,
19 TypeMismatch,
20 InvalidSpread,
21 InvalidIncludePath,
22 IncludeNotFound,
23 IncludeNotFile,
24 IncludePathDenied,
25 IncludeCycle,
26 IncludeParseError,
27 IncludeRootTypeError,
28 ResourceLimitExceeded,
29 Serde,
30}
31
32#[derive(Clone, Debug, thiserror::Error)]
33#[error("{code:?} at {line}:{column}: {message}")]
34pub struct Error {
35 pub code: ErrorCode,
36 pub message: String,
37 pub file: Option<PathBuf>,
38 pub line: usize,
39 pub column: usize,
40 pub span: Option<Span>,
41 pub path: Option<Vec<String>>,
42 pub include_stack: Vec<PathBuf>,
43 pub hint: Option<String>,
44}
45
46impl Error {
47 pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
48 Self {
49 code,
50 message: message.into(),
51 file: None,
52 line: 1,
53 column: 1,
54 span: None,
55 path: None,
56 include_stack: Vec::new(),
57 hint: None,
58 }
59 }
60
61 pub(crate) fn at(mut self, loc: crate::ast::Location) -> Self {
62 self.file = loc.file;
63 self.line = loc.line;
64 self.column = loc.column;
65 self.span = Some(loc.span);
66 self
67 }
68
69 pub(crate) fn with_path(mut self, path: &[String]) -> Self {
70 self.path = Some(path.to_vec());
71 self
72 }
73}
74
75impl serde::de::Error for Error {
76 fn custom<T: std::fmt::Display>(msg: T) -> Self {
77 Error::new(ErrorCode::Serde, msg.to_string())
78 }
79}
80
81impl serde::ser::Error for Error {
82 fn custom<T: std::fmt::Display>(msg: T) -> Self {
83 Error::new(ErrorCode::Serde, msg.to_string())
84 }
85}