Skip to main content

pagesift_syntax/
lib.rs

1//! 与 tree-sitter 语法兼容的纯 Rust 解析运行时与代码大纲提取(基于 [`yolowsyntax`])。
2//!
3//! 语法表与外部扫描器由 [`yolowsyntax`] 提供;来源和许可见 `THIRD-PARTY.md`。
4
5#![deny(unsafe_code)]
6#![deny(unsafe_op_in_unsafe_fn)]
7
8use std::time::{Duration, Instant};
9
10#[allow(unsafe_code)]
11mod fast_utf8 {
12    /// [协议] RFC 3629 UTF-8 连续字节判别掩码与标记 (`(b & 0xC0) == 0x80`)。
13    const UTF8_CONT_MASK: u8 = 0xC0;
14    const UTF8_CONT_TAG: u8 = 0x80; // [协议] RFC 3629 UTF-8 continuation byte prefix
15
16    #[inline]
17    pub(crate) fn ceil_utf8_boundary(s: &str, idx: usize) -> usize {
18        let bytes = s.as_bytes();
19        let mut i = idx.min(bytes.len());
20        while i < bytes.len() {
21            // SAFETY: The `while i < bytes.len()` guard guarantees `i` is strictly in bounds of `bytes`.
22            let b = unsafe { *bytes.get_unchecked(i) };
23            if (b & UTF8_CONT_MASK) != UTF8_CONT_TAG {
24                break;
25            }
26            i += 1;
27        }
28        i
29    }
30}
31
32pub use yolowsyntax::{
33    Limits, Outline, Section, Symbol, SymbolKind, compact, extract, langs, lexer, parser, recover,
34    scanner, stack, table, tree,
35};
36#[cfg(feature = "tools")]
37pub use yolowsyntax::{cdata, convert, corpus, lexconv};
38
39/// 安全解析入口:对底层转译语法表与外部扫描器补充 `catch_unwind` 隔离,异常时降级为 `truncated` 退化树。
40pub mod api {
41    pub use yolowsyntax::api::{Ev, ParseTree, VNode};
42
43    pub fn parse(
44        lang: &yolowsyntax::table::Language,
45        input: &[u8],
46        limits: yolowsyntax::Limits,
47    ) -> ParseTree {
48        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
49            yolowsyntax::api::parse(lang, input, limits)
50        }))
51        .unwrap_or_else(|_| {
52            yolowsyntax::api::parse(
53                lang,
54                input,
55                yolowsyntax::Limits {
56                    max_nodes: 0,
57                    ..limits
58                },
59            )
60        })
61    }
62
63    /// 受截止时间预算约束的安全解析:`deadline_ms == Some(0)` 直接返回 `truncated` 退化树(规避
64    /// `yolowsyntax` 将 `max_millis == 0` 视为不限时),否则夹紧 `Limits::max_millis`。
65    pub fn parse_with_budget(
66        lang: &yolowsyntax::table::Language,
67        input: &[u8],
68        limits: yolowsyntax::Limits,
69        deadline_ms: Option<u64>,
70    ) -> ParseTree {
71        let clamped = match deadline_ms {
72            Some(0) => yolowsyntax::Limits {
73                max_nodes: 0,
74                ..limits
75            },
76            Some(ms) => yolowsyntax::Limits {
77                max_millis: if limits.max_millis == 0 {
78                    ms
79                } else {
80                    limits.max_millis.min(ms)
81                },
82                ..limits
83            },
84            None => limits,
85        };
86        parse(lang, input, clamped)
87    }
88}
89
90/// 提取代码大纲,并保证所有 `Section` 范围严格对齐在 `source` 的 UTF-8 字符边界上且首尾相接覆盖全文。
91pub fn outline(tag: &str, source: &str) -> Option<Outline> {
92    let mut out = yolowsyntax::outline(tag, source)?;
93    sanitize_sections(source, &mut out.sections);
94    Some(out)
95}
96
97/// 受输入大小与时间预算约束的大纲提取:前置拦截超限/零预算/空输入或未知语言,解析后校验 `deadline_ms` 并原地整理分节边界。
98pub fn outline_with_budget(
99    tag: &str,
100    source: &str,
101    max_input_bytes: usize,
102    deadline_ms: Option<u64>,
103) -> Option<Outline> {
104    if deadline_ms == Some(0)
105        || source.is_empty()
106        || source.len() > max_input_bytes
107        || langs::Lang::from_tag(tag).is_none()
108    {
109        return None;
110    }
111    let started = Instant::now();
112    let mut out = yolowsyntax::outline(tag, source)?;
113    if let Some(ms) = deadline_ms
114        && started.elapsed() > Duration::from_millis(ms)
115    {
116        return None;
117    }
118    sanitize_sections(source, &mut out.sections);
119    Some(out)
120}
121
122fn sanitize_sections(source: &str, sections: &mut Vec<Section>) {
123    let len = source.len();
124    if sections.is_empty() {
125        sections.push(Section {
126            start: 0,
127            end: len,
128            title: None,
129        });
130        return;
131    }
132    let mut cursor = 0usize;
133    let mut write = 0usize;
134    for read in 0..sections.len() {
135        let end = fast_utf8::ceil_utf8_boundary(source, sections[read].end);
136        if end <= cursor {
137            continue;
138        }
139        let title = sections[read].title.take();
140        sections[write] = Section {
141            start: cursor,
142            end,
143            title,
144        };
145        write += 1;
146        cursor = end;
147    }
148    if write == 0 {
149        sections.truncate(1);
150        sections[0] = Section {
151            start: 0,
152            end: len,
153            title: None,
154        };
155    } else {
156        sections.truncate(write);
157        if let Some(last) = sections.last_mut() {
158            last.end = len;
159        }
160    }
161}
162
163#[cfg(test)]
164mod m1_2b_tests;