Skip to main content

pagesift_syntax/
tree.rs

1//! 子树竞技场:所有节点放在一个向量里,用 u32 下标互相引用(不可变共享,没有递归释放)。
2
3use crate::table::{Language, SYM_ERROR, SYM_ERROR_REPEAT};
4
5pub const ERROR_COST_PER_RECOVERY: u32 = 500;
6pub const ERROR_COST_PER_MISSING_TREE: u32 = 110;
7pub const ERROR_COST_PER_SKIPPED_TREE: u32 = 100;
8pub const ERROR_COST_PER_SKIPPED_LINE: u32 = 30;
9pub const ERROR_COST_PER_SKIPPED_CHAR: u32 = 1;
10
11/// 位置/长度:字节数与行数(换行个数)。
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
13pub struct Len {
14    pub bytes: u32,
15    pub rows: u32,
16}
17
18impl Len {
19    #[allow(clippy::should_implement_trait)]
20    pub fn add(self, o: Len) -> Len {
21        Len {
22            bytes: self.bytes.wrapping_add(o.bytes),
23            rows: self.rows.wrapping_add(o.rows),
24        }
25    }
26    #[allow(clippy::should_implement_trait)]
27    pub fn sub(self, o: Len) -> Len {
28        Len {
29            bytes: self.bytes.wrapping_sub(o.bytes),
30            rows: self.rows.wrapping_sub(o.rows),
31        }
32    }
33}
34
35pub const NONE: u32 = u32::MAX;
36
37pub const F_VISIBLE: u8 = 1;
38pub const F_NAMED: u8 = 2;
39pub const F_EXTRA: u8 = 4;
40pub const F_MISSING: u8 = 8;
41pub const F_KEYWORD: u8 = 16;
42
43#[derive(Clone, Debug)]
44pub struct Node {
45    pub sym: u16,
46    pub flags: u8,
47    pub prod: u16,
48    pub padding: Len,
49    pub size: Len,
50    pub first_child: u32,
51    pub child_count: u32,
52    pub error_cost: u32,
53    pub dprec: i32,
54    pub visible_descendants: u32,
55    pub visible_children: u32,
56    pub named_children: u32,
57    /// 词法跳过的非法字符(ERROR 叶子)。
58    pub lchar: u32,
59    /// 最后一个外部记号之后的扫描器状态编号(`Arena::ext_bytes` 的下标),子树里没有外部记号为 NONE。
60    pub ext: u32,
61}
62
63impl Node {
64    #[inline]
65    pub fn extra(&self) -> bool {
66        self.flags & F_EXTRA != 0
67    }
68    #[inline]
69    pub fn visible(&self) -> bool {
70        self.flags & F_VISIBLE != 0
71    }
72    #[inline]
73    pub fn named(&self) -> bool {
74        self.flags & F_NAMED != 0
75    }
76    #[inline]
77    pub fn missing(&self) -> bool {
78        self.flags & F_MISSING != 0
79    }
80    #[inline]
81    pub fn is_error(&self) -> bool {
82        self.sym == SYM_ERROR
83    }
84    #[inline]
85    pub fn total(&self) -> Len {
86        self.padding.add(self.size)
87    }
88    /// 官方 `ts_subtree_error_cost`:缺失节点固定代价。
89    #[inline]
90    pub fn cost(&self) -> u32 {
91        if self.missing() {
92            ERROR_COST_PER_MISSING_TREE + ERROR_COST_PER_RECOVERY
93        } else {
94            self.error_cost
95        }
96    }
97}
98
99#[derive(Default)]
100pub struct Arena {
101    pub nodes: Vec<Node>,
102    pub kids: Vec<u32>,
103    /// 去重后的扫描器状态;编号 0 固定表示空状态,编号 i>0 对应 `ext[i-1]`。
104    pub ext: Vec<Vec<u8>>,
105    pub ext_map: std::collections::HashMap<Vec<u8>, u32>,
106    pub ext_total: usize,
107}
108
109fn extent_cost(size: Len) -> u32 {
110    ERROR_COST_PER_RECOVERY
111        .wrapping_add(ERROR_COST_PER_SKIPPED_CHAR.wrapping_mul(size.bytes))
112        .wrapping_add(ERROR_COST_PER_SKIPPED_LINE.wrapping_mul(size.rows))
113}
114
115impl Arena {
116    #[inline]
117    pub fn n(&self, i: u32) -> &Node {
118        &self.nodes[i as usize]
119    }
120    #[inline]
121    pub fn n_mut(&mut self, i: u32) -> &mut Node {
122        &mut self.nodes[i as usize]
123    }
124    /// 登记一份扫描器状态,相同内容共用同一个编号。
125    pub fn intern_ext(&mut self, bytes: &[u8]) -> u32 {
126        if bytes.is_empty() {
127            return 0;
128        }
129        if let Some(&i) = self.ext_map.get(bytes) {
130            return i;
131        }
132        self.ext.push(bytes.to_vec());
133        let i = self.ext.len() as u32;
134        self.ext_map.insert(bytes.to_vec(), i);
135        self.ext_total += bytes.len() * 2;
136        i
137    }
138    pub fn ext_bytes(&self, i: u32) -> &[u8] {
139        if i == 0 || i == NONE {
140            &[]
141        } else {
142            self.ext.get(i as usize - 1).map_or(&[], |v| v.as_slice())
143        }
144    }
145    pub fn children(&self, i: u32) -> &[u32] {
146        let n = &self.nodes[i as usize];
147        &self.kids[n.first_child as usize..(n.first_child + n.child_count) as usize]
148    }
149
150    pub fn new_leaf(&mut self, lang: &Language, sym: u16, padding: Len, size: Len) -> u32 {
151        let mut flags = 0;
152        if lang.visible(sym) {
153            flags |= F_VISIBLE;
154        }
155        if lang.named(sym) {
156            flags |= F_NAMED;
157        }
158        if sym == 0 {
159            flags |= F_EXTRA; // 输入结束记号本身是 extra
160        }
161        self.push(Node {
162            sym,
163            flags,
164            prod: 0,
165            padding,
166            size,
167            first_child: 0,
168            child_count: 0,
169            error_cost: 0,
170            dprec: 0,
171            visible_descendants: 0,
172            visible_children: 0,
173            named_children: 0,
174            lchar: 0,
175            ext: NONE,
176        })
177    }
178
179    pub fn new_missing_leaf(&mut self, lang: &Language, sym: u16) -> u32 {
180        let i = self.new_leaf(lang, sym, Len::default(), Len::default());
181        self.n_mut(i).flags |= F_MISSING;
182        i
183    }
184
185    fn push(&mut self, n: Node) -> u32 {
186        self.nodes.push(n);
187        (self.nodes.len() - 1) as u32
188    }
189
190    /// 官方 `ts_subtree_new_node` + `summarize_children`。
191    pub fn new_node(&mut self, lang: &Language, sym: u16, children: &[u32], prod: u16) -> u32 {
192        let first_child = self.kids.len() as u32;
193        self.kids.extend_from_slice(children);
194        let mut node = Node {
195            sym,
196            flags: 0,
197            prod,
198            padding: Len::default(),
199            size: Len::default(),
200            first_child,
201            child_count: children.len() as u32,
202            error_cost: 0,
203            dprec: 0,
204            visible_descendants: 0,
205            visible_children: 0,
206            named_children: 0,
207            lchar: 0,
208            ext: NONE,
209        };
210        if lang.visible(sym) {
211            node.flags |= F_VISIBLE;
212        }
213        if lang.named(sym) {
214            node.flags |= F_NAMED;
215        }
216        let is_err_parent = sym == SYM_ERROR || sym == SYM_ERROR_REPEAT;
217        let alias = lang.alias_sequence(prod);
218        let mut structural = 0usize;
219        for (i, &c) in children.iter().enumerate() {
220            let ch = &self.nodes[c as usize];
221            if i == 0 {
222                node.padding = ch.padding;
223                node.size = ch.size;
224            } else {
225                node.size = node.size.add(ch.total());
226            }
227            let gc = ch.child_count;
228            if ch.sym == SYM_ERROR_REPEAT {
229                node.error_cost = node
230                    .error_cost
231                    .wrapping_add(ch.error_cost.wrapping_sub(extent_cost(ch.size)));
232            } else {
233                node.error_cost = node.error_cost.wrapping_add(ch.cost());
234                if is_err_parent && !ch.extra() && !(ch.is_error() && gc == 0) {
235                    if ch.visible() {
236                        node.error_cost += ERROR_COST_PER_SKIPPED_TREE;
237                    } else if gc > 0 {
238                        node.error_cost += ERROR_COST_PER_SKIPPED_TREE * ch.visible_children;
239                    }
240                }
241            }
242            node.dprec += ch.dprec;
243            if ch.ext != NONE {
244                node.ext = ch.ext;
245            }
246            node.visible_descendants += ch.visible_descendants;
247            let aliased = !ch.extra()
248                && ch.sym != 0
249                && alias.is_some_and(|a| a.get(structural).copied().unwrap_or(0) != 0);
250            if aliased {
251                node.visible_descendants += 1;
252                node.visible_children += 1;
253                if lang.named(alias.unwrap()[structural]) {
254                    node.named_children += 1;
255                }
256            } else if ch.visible() {
257                node.visible_descendants += 1;
258                node.visible_children += 1;
259                if ch.named() {
260                    node.named_children += 1;
261                }
262            } else if gc > 0 {
263                node.visible_children += ch.visible_children;
264                node.named_children += ch.named_children;
265            }
266            if !ch.extra() {
267                structural += 1;
268            }
269        }
270        if is_err_parent {
271            node.error_cost = node.error_cost.wrapping_add(extent_cost(node.size));
272        }
273        self.push(node)
274    }
275
276    pub fn new_error_node(&mut self, lang: &Language, children: &[u32], extra: bool) -> u32 {
277        let i = self.new_node(lang, SYM_ERROR, children, 0);
278        if extra {
279            self.n_mut(i).flags |= F_EXTRA;
280        }
281        i
282    }
283
284    /// 官方 `ts_subtree_compare`:按符号、子节点数逐个比较,返回 -1/0/1。
285    pub fn compare(&self, a: u32, b: u32) -> i32 {
286        let mut work = vec![(a, b)];
287        while let Some((l, r)) = work.pop() {
288            let (ln, rn) = (self.n(l), self.n(r));
289            let res = if ln.sym < rn.sym {
290                -1
291            } else if rn.sym < ln.sym {
292                1
293            } else if ln.child_count < rn.child_count {
294                -1
295            } else if rn.child_count < ln.child_count {
296                1
297            } else {
298                0
299            };
300            if res != 0 {
301                return res;
302            }
303            let (lc, rc) = (self.children(l), self.children(r));
304            for i in (0..lc.len()).rev() {
305                work.push((lc[i], rc[i]));
306            }
307        }
308        0
309    }
310}