Skip to main content

svelte_syntax/
ast.rs

1//! Svelte AST types.
2//!
3//! This module defines the tree structures produced by [`parse`](crate::parse)
4//! and [`parse_modern_root`](crate::parse_modern_root). The AST comes in two
5//! flavors:
6//!
7//! - [`modern`] — the primary representation with typed nodes for every Svelte
8//!   construct (elements, control flow blocks, snippets, scripts, styles).
9//! - [`legacy`] — a compatibility representation that mirrors the ESTree-like
10//!   shape used by the JavaScript Svelte compiler.
11//!
12//! Most consumers should use [`modern::Root`] via [`parse_modern_root`](crate::parse_modern_root).
13
14use std::sync::Arc;
15
16use serde::{Deserialize, Serialize};
17
18pub mod common;
19pub mod legacy;
20pub mod modern;
21
22/// A parsed Svelte component document containing either a [`modern`] or
23/// [`legacy`] AST root.
24///
25/// Returned by [`parse`](crate::parse).
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Document {
28    /// The AST root — either modern or legacy depending on [`ParseMode`](crate::ParseMode).
29    #[serde(flatten)]
30    pub root: Root,
31
32    #[serde(skip)]
33    pub(crate) source: Arc<str>,
34}
35
36/// The top-level AST, either modern or legacy.
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(untagged)]
39pub enum Root {
40    /// Legacy ESTree-compatible AST.
41    Legacy(legacy::Root),
42    /// Modern typed AST (recommended).
43    Modern(modern::Root),
44}
45
46impl Document {
47    /// Return the original source text that was parsed.
48    pub fn source(&self) -> &str {
49        &self.source
50    }
51}
52
53/// Discriminant for a standalone CSS AST root.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
55pub enum CssRootType {
56    /// A `.css` stylesheet file.
57    StyleSheetFile,
58}
59
60/// A parsed CSS stylesheet AST, returned by [`parse_css`](crate::parse_css).
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62pub struct CssAst {
63    /// Always [`CssRootType::StyleSheetFile`].
64    pub r#type: CssRootType,
65    /// Top-level CSS nodes (rules, at-rules, declarations).
66    pub children: Box<[modern::CssNode]>,
67    /// Byte offset of the start of the stylesheet.
68    pub start: usize,
69    /// Byte offset of the end of the stylesheet.
70    pub end: usize,
71}