Skip to main content

js2rust_predicate/
error.rs

1//! 错误类型。
2
3use std::fmt;
4
5/// 错误分类。
6#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
7pub enum ErrorKind {
8    /// 词法/语法错误。
9    Syntax,
10    /// 语法或取值属于契约之外(正则、循环、函数、非 `Date` 的内置对象、
11    /// 无法用 `str` 表达的孤立代理等)。
12    Unsupported,
13    /// 类型不匹配,如对非数组调用 `.includes` 之外的情形。
14    Type,
15    /// 运行期异常:复刻 JS 抛错语义,由调用方决定 fail-open / fail-closed。
16    Runtime,
17    /// 超出节点数或嵌套深度上限。
18    Limit,
19}
20
21/// 编译期与求值期共用的错误。
22#[derive(Clone, Debug)]
23pub struct Error {
24    kind: ErrorKind,
25    offset: Option<usize>,
26    message: String,
27}
28
29impl Error {
30    /// 构造一个不带位置的错误。
31    pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
32        Self {
33            kind,
34            offset: None,
35            message: message.into(),
36        }
37    }
38
39    /// 附加源码字节偏移。
40    #[must_use]
41    pub fn with_offset(mut self, offset: usize) -> Self {
42        self.offset = Some(offset);
43        self
44    }
45
46    /// 把偏移平移 `base`(模板插值子源码用它换算回原始位置)。
47    pub(crate) fn shift(self, base: usize) -> Self {
48        match self.offset {
49            Some(o) => Self {
50                offset: Some(o.saturating_add(base)),
51                ..self
52            },
53            None => self,
54        }
55    }
56
57    /// 错误分类。
58    pub fn kind(&self) -> ErrorKind {
59        self.kind
60    }
61
62    /// 源码字节偏移(若已知)。
63    pub fn offset(&self) -> Option<usize> {
64        self.offset
65    }
66}
67
68impl fmt::Display for Error {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        match self.offset {
71            Some(off) => write!(f, "{:?} @{}: {}", self.kind, off, self.message),
72            None => write!(f, "{:?}: {}", self.kind, self.message),
73        }
74    }
75}
76
77impl std::error::Error for Error {}