Skip to main content

pagesift_syntax/
api.rs

1//! 对外接口:解析入口、节点遍历、S 表达式输出。
2
3use crate::Limits;
4use crate::parser::Parser;
5use crate::table::{Language, SYM_ERROR};
6use crate::tree::{Arena, Len, NONE};
7
8/// 解析结果:树本身放在竞技场里,用 [`ParseTree::visit`] 遍历。
9pub struct ParseTree {
10    pub arena: Arena,
11    pub root: u32,
12    /// 因资源上限而中止,树是退化的单个 ERROR 节点。
13    pub truncated: bool,
14    pub input_len: usize,
15}
16
17/// 遍历事件里的可见节点信息。
18pub struct VNode<'a> {
19    pub kind: &'a str,
20    pub named: bool,
21    pub field: Option<&'a str>,
22    pub start: usize,
23    pub end: usize,
24    pub missing: bool,
25    pub error: bool,
26    /// 词法层面跳过的非法字符(仅 ERROR 叶子),没有则为 0。
27    pub unexpected: u32,
28    pub has_children: bool,
29}
30
31pub enum Ev<'a> {
32    Open(VNode<'a>),
33    Close,
34}
35
36/// 解析一段字节输入。输入不可信:任何资源上限被触发都返回退化的树而不是崩溃。
37pub fn parse(lang: &Language, input: &[u8], limits: Limits) -> ParseTree {
38    let mut p = Parser::new(lang, input, limits);
39    if input.len() >= u32::MAX as usize / 2 {
40        p.aborted = true;
41    } else {
42        p.run();
43    }
44    let (mut root, mut truncated) = (p.finished, false);
45    if root == NONE || p.aborted {
46        // 退化:整段输入作为一个 ERROR 叶子
47        let size = Len {
48            bytes: input.len() as u32,
49            rows: input.iter().filter(|b| **b == b'\n').count() as u32,
50        };
51        root = p.a.new_leaf(lang, SYM_ERROR, Len::default(), size);
52        p.a.n_mut(root).error_cost = 1;
53        truncated = true;
54    }
55    ParseTree {
56        arena: p.a,
57        root,
58        truncated,
59        input_len: input.len(),
60    }
61}
62
63struct Frame {
64    id: u32,
65    offset: u32,
66    alias: u16,
67    alias_named: bool,
68    field: Option<u16>,
69    pre: bool,
70    visible: bool,
71    child_index: usize,
72    structural: usize,
73    next_offset: u32,
74}
75
76impl ParseTree {
77    pub fn has_error(&self) -> bool {
78        self.arena.n(self.root).cost() > 0
79    }
80
81    /// 官方 `ts_subtree__write_to_string` 的遍历:对每个可见节点发出 Open/Close。
82    pub fn visit<'a>(&self, lang: &'a Language, mut f: impl FnMut(Ev<'a>)) {
83        let a = &self.arena;
84        let mut stack = vec![Frame {
85            id: self.root,
86            offset: 0,
87            alias: 0,
88            alias_named: false,
89            field: None,
90            pre: false,
91            visible: false,
92            child_index: 0,
93            structural: 0,
94            next_offset: 0,
95        }];
96        while let Some(top) = stack.len().checked_sub(1) {
97            let id = stack[top].id;
98            let node = a.n(id);
99            if !stack[top].pre {
100                let fr = &stack[top];
101                let visible = node.missing()
102                    || if fr.alias != 0 {
103                        fr.alias_named
104                    } else {
105                        node.visible() && node.named()
106                    };
107                let sym = if fr.alias != 0 { fr.alias } else { node.sym };
108                let start = fr.offset + node.padding.bytes;
109                if visible {
110                    f(Ev::Open(VNode {
111                        kind: lang.symbol_name(sym),
112                        named: fr.alias_named || node.named(),
113                        field: fr.field.map(|x| lang.field_name(x)),
114                        start: start as usize,
115                        end: (start + node.size.bytes) as usize,
116                        missing: node.missing(),
117                        error: node.is_error(),
118                        unexpected: if node.is_error()
119                            && node.child_count == 0
120                            && node.size.bytes > 0
121                        {
122                            node.lchar
123                        } else {
124                            0
125                        },
126                        has_children: node.child_count > 0,
127                    }));
128                }
129                let fr = &mut stack[top];
130                fr.visible = visible;
131                fr.pre = true;
132                fr.next_offset = fr.offset;
133            }
134            let fr_visible = stack[top].visible;
135            if stack[top].child_index < node.child_count as usize {
136                let ci = stack[top].child_index;
137                let child = a.children(id)[ci];
138                let cn = a.n(child);
139                let mut cf = Frame {
140                    id: child,
141                    offset: stack[top].next_offset,
142                    alias: 0,
143                    alias_named: false,
144                    field: None,
145                    pre: false,
146                    visible: false,
147                    child_index: 0,
148                    structural: 0,
149                    next_offset: 0,
150                };
151                if !cn.extra() {
152                    let seq = lang.alias_sequence(node.prod);
153                    let al = seq.map_or(0, |s| s.get(stack[top].structural).copied().unwrap_or(0));
154                    cf.alias = al;
155                    cf.alias_named = al != 0 && lang.named(al);
156                    let mut field = if fr_visible { None } else { stack[top].field };
157                    if let Some(&(s, l)) = lang.field_map_slices.get(node.prod as usize) {
158                        for e in lang
159                            .field_map_entries
160                            .iter()
161                            .skip(s as usize)
162                            .take(l as usize)
163                        {
164                            if !e.2 && e.1 as usize == stack[top].structural {
165                                field = Some(e.0);
166                                break;
167                            }
168                        }
169                    }
170                    cf.field = field;
171                    stack[top].structural += 1;
172                }
173                stack[top].next_offset += cn.total().bytes;
174                stack[top].child_index += 1;
175                stack.push(cf);
176                continue;
177            }
178            if fr_visible {
179                f(Ev::Close);
180            }
181            stack.pop();
182        }
183    }
184
185    /// 与 `tree-sitter` 的 `Node::to_sexp` 一致的 S 表达式(含字段名)。
186    pub fn to_sexp(&self, lang: &Language) -> String {
187        let mut out = String::new();
188        let mut depth = 0usize;
189        let mut first = true;
190        // 根节点不可见时官方输出 "(name" 开头,这里同样处理
191        let root = self.arena.n(self.root);
192        let root_visible = root.missing() || (root.visible() && root.named());
193        if !root_visible {
194            out.push('(');
195            out.push_str(lang.symbol_name(root.sym));
196            depth += 1;
197            first = false;
198        }
199        self.visit(lang, |ev| match ev {
200            Ev::Open(n) => {
201                if !first {
202                    out.push(' ');
203                    if let Some(fl) = n.field {
204                        out.push_str(fl);
205                        out.push_str(": ");
206                    }
207                }
208                first = false;
209                if n.unexpected != 0 || (n.error && !n.has_children && n.end > n.start) {
210                    out.push_str("(UNEXPECTED ");
211                    out.push_str(&char_repr(n.unexpected));
212                } else if n.missing {
213                    out.push_str("(MISSING ");
214                    if n.named {
215                        out.push_str(n.kind);
216                    } else {
217                        out.push('"');
218                        out.push_str(n.kind);
219                        out.push('"');
220                    }
221                } else {
222                    out.push('(');
223                    out.push_str(n.kind);
224                }
225                depth += 1;
226            }
227            Ev::Close => {
228                out.push(')');
229                depth -= 1;
230            }
231        });
232        while depth > 0 {
233            out.push(')');
234            depth -= 1;
235        }
236        out
237    }
238}
239
240fn char_repr(c: u32) -> String {
241    match c {
242        0 => "'\\0'".into(),
243        10 => "'\\n'".into(),
244        9 => "'\\t'".into(),
245        13 => "'\\r'".into(),
246        32..=126 => format!("'{}'", c as u8 as char),
247        _ => c.to_string(),
248    }
249}