js2rust-predicate 0.1.6

Compile side-effect-free JavaScript predicates into a zero-allocation Rust evaluator
Documentation
//! 错误类型。

use std::fmt;

/// 错误分类。
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ErrorKind {
    /// 词法/语法错误。
    Syntax,
    /// 语法或取值属于契约之外(正则、循环、函数、非 `Date` 的内置对象、
    /// 无法用 `str` 表达的孤立代理等)。
    Unsupported,
    /// 类型不匹配,如对非数组调用 `.includes` 之外的情形。
    Type,
    /// 运行期异常:复刻 JS 抛错语义,由调用方决定 fail-open / fail-closed。
    Runtime,
    /// 超出节点数或嵌套深度上限。
    Limit,
}

/// 编译期与求值期共用的错误。
#[derive(Clone, Debug)]
pub struct Error {
    kind: ErrorKind,
    offset: Option<usize>,
    message: String,
}

impl Error {
    /// 构造一个不带位置的错误。
    pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            offset: None,
            message: message.into(),
        }
    }

    /// 附加源码字节偏移。
    #[must_use]
    pub fn with_offset(mut self, offset: usize) -> Self {
        self.offset = Some(offset);
        self
    }

    /// 把偏移平移 `base`(模板插值子源码用它换算回原始位置)。
    pub(crate) fn shift(self, base: usize) -> Self {
        match self.offset {
            Some(o) => Self {
                offset: Some(o.saturating_add(base)),
                ..self
            },
            None => self,
        }
    }

    /// 错误分类。
    pub fn kind(&self) -> ErrorKind {
        self.kind
    }

    /// 源码字节偏移(若已知)。
    pub fn offset(&self) -> Option<usize> {
        self.offset
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.offset {
            Some(off) => write!(f, "{:?} @{}: {}", self.kind, off, self.message),
            None => write!(f, "{:?}: {}", self.kind, self.message),
        }
    }
}

impl std::error::Error for Error {}