use std::fmt; use super::visitor::Visitor; use super::{AST_SCHEMA_ID, AstDocument, AstRoot}; use crate::Span; #[derive(Debug)] pub enum AstError { Json(serde_json::Error), SchemaMismatch { expected: &'static str, found: String, }, InvalidSpan(Span), ChildOutsideParent { parent: Span, child: Span, }, } impl fmt::Display for AstError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Json(error) => write!(f, "invalid AST JSON: {error}"), Self::SchemaMismatch { expected, found } => { write!(f, "AST schema mismatch: expected {expected}, found {found}") } Self::InvalidSpan(span) => { write!(f, "invalid AST source span: {}..{}", span.start, span.end) } Self::ChildOutsideParent { parent, child } => write!( f, "AST child span {}..{} is outside parent {}..{}", child.start, child.end, parent.start, parent.end ), } } } impl std::error::Error for AstError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Self::Json(error) => Some(error), _ => None, } } } impl From for AstError { fn from(error: serde_json::Error) -> Self { Self::Json(error) } } impl AstDocument { pub fn new(root: AstRoot) -> Result { let document = Self { schema: AST_SCHEMA_ID.into(), root, }; document.validate()?; Ok(document) } /// Decode a versioned syntax tree. This does not compile or execute it. pub fn from_json(text: &str) -> Result { let document: Self = serde_json::from_str(text)?; document.validate()?; Ok(document) } pub fn to_json(&self) -> Result { self.validate()?; Ok(serde_json::to_string(self)?) } /// Check schema identity, ranges, and parent/child containment. 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. pub fn validate_source(&self, source: &str) -> Result<(), AstError> { self.validate_with_source(Some(source)) } fn validate_with_source(&self, source: Option<&str>) -> Result<(), AstError> { if self.schema != AST_SCHEMA_ID { return Err(AstError::SchemaMismatch { expected: AST_SCHEMA_ID, found: self.schema.clone(), }); } SpanValidator { source, parents: Vec::new(), } .visit_ast_root(&self.root) } } struct SpanValidator<'a> { source: Option<&'a str>, parents: Vec, } impl Visitor for SpanValidator<'_> { type Error = AstError; fn enter_node(&mut self, span: Span) -> Result<(), AstError> { // JSON offsets must also be exactly representable by editor JS numbers. if span.start > span.end || span.end as u128 > 9_007_199_254_740_991 || self .source .is_some_and(|source| span.slice(source).is_none()) { return Err(AstError::InvalidSpan(span)); } if let Some(parent) = self.parents.last().copied() && (span.start < parent.start || span.end > parent.end) { return Err(AstError::ChildOutsideParent { parent, child: span, }); } self.parents.push(span); Ok(()) } fn leave_node(&mut self) { self.parents.pop(); } }