Skip to main content

pagesift_syntax/
lib.rs

1//! 与 tree-sitter 语法兼容的纯 Rust 解析运行时与代码大纲提取(基于 [`yolowsyntax`])。
2//!
3//! 语法表与外部扫描器由 [`yolowsyntax`] 提供;来源和许可见 `THIRD-PARTY.md`。
4
5#![forbid(unsafe_code)]
6
7pub use yolowsyntax::{
8    Limits, Outline, Section, Symbol, SymbolKind, compact, extract, langs, lexer, parser, recover,
9    scanner, stack, table, tree,
10};
11#[cfg(feature = "tools")]
12pub use yolowsyntax::{cdata, convert, corpus, lexconv};
13
14/// 安全解析入口:对底层转译语法表与外部扫描器补充 `catch_unwind` 隔离,异常时降级为 `truncated` 退化树。
15pub mod api {
16    pub use yolowsyntax::api::{Ev, ParseTree, VNode};
17
18    pub fn parse(
19        lang: &yolowsyntax::table::Language,
20        input: &[u8],
21        limits: yolowsyntax::Limits,
22    ) -> ParseTree {
23        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
24            yolowsyntax::api::parse(lang, input, limits)
25        }))
26        .unwrap_or_else(|_| {
27            yolowsyntax::api::parse(
28                lang,
29                input,
30                yolowsyntax::Limits {
31                    max_nodes: 0,
32                    ..limits
33                },
34            )
35        })
36    }
37}
38
39/// 提取代码大纲,并保证所有 `Section` 范围严格对齐在 `source` 的 UTF-8 字符边界上且首尾相接覆盖全文。
40pub fn outline(tag: &str, source: &str) -> Option<Outline> {
41    let mut out = yolowsyntax::outline(tag, source)?;
42    sanitize_sections(source, &mut out.sections);
43    Some(out)
44}
45
46fn ceil_utf8_boundary(s: &str, mut idx: usize) -> usize {
47    idx = idx.min(s.len());
48    while idx < s.len() && !s.is_char_boundary(idx) {
49        idx += 1;
50    }
51    idx
52}
53
54fn sanitize_sections(source: &str, sections: &mut Vec<Section>) {
55    let len = source.len();
56    if sections.is_empty() {
57        sections.push(Section {
58            start: 0,
59            end: len,
60            title: None,
61        });
62        return;
63    }
64    let mut cursor = 0usize;
65    let mut sanitized = Vec::with_capacity(sections.len());
66    for sec in sections.drain(..) {
67        let end = ceil_utf8_boundary(source, sec.end);
68        if end <= cursor {
69            continue;
70        }
71        sanitized.push(Section {
72            start: cursor,
73            end,
74            title: sec.title,
75        });
76        cursor = end;
77    }
78    match sanitized.last_mut() {
79        Some(last) => last.end = len,
80        None => sanitized.push(Section {
81            start: 0,
82            end: len,
83            title: None,
84        }),
85    }
86    *sections = sanitized;
87}