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