swc_html_parser/parser/
node.rs

1use std::{
2    cell::{Cell, RefCell},
3    fmt, mem,
4    rc::{Rc, Weak},
5};
6
7use swc_atoms::Atom;
8use swc_common::Span;
9use swc_html_ast::*;
10
11#[derive(Debug, Clone)]
12pub struct TokenAndInfo {
13    pub span: Span,
14    pub acknowledged: bool,
15    pub token: Token,
16}
17
18#[derive(Debug, Clone)]
19pub enum Data {
20    Document {
21        mode: RefCell<DocumentMode>,
22    },
23    DocumentType {
24        name: Option<Atom>,
25        public_id: Option<Atom>,
26        system_id: Option<Atom>,
27        raw: Option<Atom>,
28    },
29    Element {
30        namespace: Namespace,
31        tag_name: Atom,
32        attributes: RefCell<Vec<Attribute>>,
33        is_self_closing: bool,
34    },
35    Text {
36        data: RefCell<String>,
37        raw: RefCell<String>,
38    },
39    Comment {
40        data: Atom,
41        raw: Option<Atom>,
42    },
43}
44
45pub struct Node {
46    pub parent: Cell<Option<WeakNode>>,
47    pub children: RefCell<Vec<RcNode>>,
48    pub data: Data,
49    pub start_span: RefCell<Span>,
50    pub end_span: RefCell<Option<Span>>,
51}
52
53impl Node {
54    /// Create a new node from its contents
55    pub fn new(data: Data, span: Span) -> Rc<Self> {
56        Rc::new(Node {
57            parent: Cell::new(None),
58            children: RefCell::new(Vec::new()),
59            start_span: RefCell::new(span),
60            end_span: RefCell::new(None),
61            data,
62        })
63    }
64}
65
66impl Drop for Node {
67    fn drop(&mut self) {
68        let mut nodes = mem::take(&mut *self.children.borrow_mut());
69
70        while let Some(node) = nodes.pop() {
71            let children = mem::take(&mut *node.children.borrow_mut());
72
73            nodes.extend(children);
74        }
75    }
76}
77
78impl fmt::Debug for Node {
79    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
80        fmt.debug_struct("Node")
81            .field("data", &self.data)
82            .field("children", &self.children)
83            .finish()
84    }
85}
86
87pub type RcNode = Rc<Node>;
88type WeakNode = Weak<Node>;