docs(frontend): explain AST validation and lexical tests
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
//! 宿主与 compiler::compile_ast 使用的版本化 AST 文档接口;校验结构、跨度和包含关系,不执行源码。
|
||||
use std::fmt;
|
||||
|
||||
use super::visitor::Visitor;
|
||||
@@ -5,21 +6,32 @@ use super::{AST_SCHEMA_ID, AstDocument, AstRoot};
|
||||
use crate::Span;
|
||||
|
||||
#[derive(Debug)]
|
||||
/// JSON 编解码或文档验证的公开错误,供宿主、编译器包装及 AST 测试按类别判断。
|
||||
pub enum AstError {
|
||||
// JSON 语法、生成类型反序列化约束或序列化失败,保留 serde 原因。
|
||||
Json(serde_json::Error),
|
||||
// 文档 schema 身份与当前生成类型不一致,不能按此版本解释。
|
||||
SchemaMismatch {
|
||||
// 当前编译进前端的 schema 标识,来自生成代码的 AST_SCHEMA_ID。
|
||||
expected: &'static str,
|
||||
// 外部文档提供的拥有型标识,错误不依赖原输入缓冲存活。
|
||||
found: String,
|
||||
},
|
||||
// 逆序、超出 JS 安全整数,或有源码校验时越界/切断 UTF-8 的节点范围。
|
||||
InvalidSpan(Span),
|
||||
// 子节点虽可能单独合法,但没有完全落在直接父节点范围内。
|
||||
ChildOutsideParent {
|
||||
// Visitor 祖先栈顶的直接父范围,用于诊断包含关系。
|
||||
parent: Span,
|
||||
// 当前试图进入、但越过父边界的子范围。
|
||||
child: Span,
|
||||
},
|
||||
}
|
||||
|
||||
impl fmt::Display for AstError {
|
||||
/// 宿主显示文档错误时调用,按类别保留 schema 或字节范围细节。
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
// 根据具体错误分类输出信息或提供底层原因;schema/跨度错误由本模块产生。
|
||||
match self {
|
||||
Self::Json(error) => write!(f, "invalid AST JSON: {error}"),
|
||||
Self::SchemaMismatch { expected, found } => {
|
||||
@@ -38,7 +50,9 @@ impl fmt::Display for AstError {
|
||||
}
|
||||
|
||||
impl std::error::Error for AstError {
|
||||
/// 标准 Error 链查询入口;只有 serde JSON 失败有外部底层错误对象。
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
// 根据具体错误分类输出信息或提供底层原因;schema/跨度错误由本模块产生。
|
||||
match self {
|
||||
Self::Json(error) => Some(error),
|
||||
_ => None,
|
||||
@@ -47,13 +61,16 @@ impl std::error::Error for AstError {
|
||||
}
|
||||
|
||||
impl From<serde_json::Error> for AstError {
|
||||
/// from_json/to_json 使用 ? 时,把 serde 错误统一转换为 AstError::Json。
|
||||
fn from(error: serde_json::Error) -> Self {
|
||||
Self::Json(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl AstDocument {
|
||||
/// compiler::compile_ast、宿主及测试为已有根创建文档;附当前 schema 并校验结构,尚无原文可查边界。
|
||||
pub fn new(root: AstRoot) -> Result<Self, AstError> {
|
||||
// 按当前 schema 包装拥有根,再校验,失败不把无效文档作为成功结果返回。
|
||||
let document = Self {
|
||||
schema: AST_SCHEMA_ID.into(),
|
||||
root,
|
||||
@@ -63,35 +80,45 @@ impl AstDocument {
|
||||
}
|
||||
|
||||
/// Decode a versioned syntax tree. This does not compile or execute it.
|
||||
/// 宿主/编辑器或测试输入 JSON 时调用;先解码类型结构,再检查 schema 身份及节点跨度。
|
||||
pub fn from_json(text: &str) -> Result<Self, AstError> {
|
||||
// 生成类型上的 serde 约束会在此拒绝未知字段或错误形状,再由 validate 检查文档级规则。
|
||||
let document: Self = serde_json::from_str(text)?;
|
||||
document.validate()?;
|
||||
Ok(document)
|
||||
}
|
||||
|
||||
/// 宿主/编辑器传输及往返测试调用;先验证当前文档,避免序列化已被手工改坏的结构。
|
||||
pub fn to_json(&self) -> Result<String, AstError> {
|
||||
self.validate()?;
|
||||
Ok(serde_json::to_string(self)?)
|
||||
}
|
||||
|
||||
/// Check schema identity, ranges, and parent/child containment.
|
||||
/// new/from_json/to_json 共用的无原文验证:范围顺序、JS 安全整数及父子包含;不推断文本长度。
|
||||
pub fn validate(&self) -> Result<(), AstError> {
|
||||
self.validate_with_source(None)
|
||||
}
|
||||
|
||||
/// Additionally check bounds and UTF-8 boundaries against original text.
|
||||
/// This does not check that the text and AST have identical semantics.
|
||||
/// compiler::compile_ast 和源码范围测试调用;额外用对应原文检查字节边界及长度,不证明 AST 语义与文本相同。
|
||||
pub fn validate_source(&self, source: &str) -> Result<(), AstError> {
|
||||
self.validate_with_source(Some(source))
|
||||
}
|
||||
|
||||
/// validate/validate_source 共用实现,source 的有无决定是否检查真实 UTF-8 原文范围。
|
||||
fn validate_with_source(&self, source: Option<&str>) -> Result<(), AstError> {
|
||||
// 先核对文档版本,避免用当前访问器接受另一结构版本的数据。
|
||||
if self.schema != AST_SCHEMA_ID {
|
||||
return Err(AstError::SchemaMismatch {
|
||||
// 当前编译进前端的 schema 标识,来自生成代码的 AST_SCHEMA_ID。
|
||||
expected: AST_SCHEMA_ID,
|
||||
// 外部文档提供的拥有型标识,错误不依赖原输入缓冲存活。
|
||||
found: self.schema.clone(),
|
||||
});
|
||||
}
|
||||
// 每次验证使用新祖先栈,从根递归,失败后这份临时状态随调用结束释放。
|
||||
SpanValidator {
|
||||
source,
|
||||
parents: Vec::new(),
|
||||
@@ -100,16 +127,21 @@ impl AstDocument {
|
||||
}
|
||||
}
|
||||
|
||||
/// AstDocument 校验使用的借用节点访问器;source 可选,parents 跟踪当前递归路径的节点范围。
|
||||
struct SpanValidator<'a> {
|
||||
// 有原文时校验 slice;无原文时只做结构与可表示范围检查。
|
||||
source: Option<&'a str>,
|
||||
// 成功进入才压栈,离开时弹栈,确保每个子节点与直接父节点比较。
|
||||
parents: Vec<Span>,
|
||||
}
|
||||
|
||||
impl Visitor for SpanValidator<'_> {
|
||||
type Error = AstError;
|
||||
|
||||
/// 默认 Visitor 在进入各语法节点前调用;只有检查通过才登记本节点,失败不需要为当前节点弹栈。
|
||||
fn enter_node(&mut self, span: Span) -> Result<(), AstError> {
|
||||
// JSON offsets must also be exactly representable by editor JS numbers.
|
||||
// end 不超过 JS Number 的最大安全整数;顺序合法同时保证 start 不会比 end 更大。
|
||||
if span.start > span.end
|
||||
|| span.end as u128 > 9_007_199_254_740_991
|
||||
|| self
|
||||
@@ -118,6 +150,7 @@ impl Visitor for SpanValidator<'_> {
|
||||
{
|
||||
return Err(AstError::InvalidSpan(span));
|
||||
}
|
||||
// 根没有父范围;其余节点不能越过直接父节点的任一端点,允许范围相等。
|
||||
if let Some(parent) = self.parents.last().copied()
|
||||
&& (span.start < parent.start || span.end > parent.end)
|
||||
{
|
||||
@@ -126,10 +159,12 @@ impl Visitor for SpanValidator<'_> {
|
||||
child: span,
|
||||
});
|
||||
}
|
||||
// 当前节点全部合法后才成为后续子节点的父范围。
|
||||
self.parents.push(span);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 默认 Visitor 在已进入节点的遍历结束后调用,即使子遍历失败,也会为成功进入的祖先执行退出。
|
||||
fn leave_node(&mut self) {
|
||||
self.parents.pop();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user