pagesift-syntax 1.8.1

Code outline extraction and pure-Rust tree-sitter runtime for PageSift (re-exports yolowsyntax).
Documentation
//! 与 tree-sitter 语法兼容的纯 Rust 解析运行时与代码大纲提取(基于 [`yolowsyntax`])。
//!
//! 语法表与外部扫描器由 [`yolowsyntax`] 提供;来源和许可见 `THIRD-PARTY.md`。

#![deny(unsafe_code)]
#![deny(unsafe_op_in_unsafe_fn)]

use std::time::{Duration, Instant};

#[allow(unsafe_code)]
mod fast_utf8 {
    /// [协议] RFC 3629 UTF-8 连续字节判别掩码与标记 (`(b & 0xC0) == 0x80`)。
    const UTF8_CONT_MASK: u8 = 0xC0;
    const UTF8_CONT_TAG: u8 = 0x80; // [协议] RFC 3629 UTF-8 continuation byte prefix

    #[inline]
    pub(crate) fn ceil_utf8_boundary(s: &str, idx: usize) -> usize {
        let bytes = s.as_bytes();
        let mut i = idx.min(bytes.len());
        while i < bytes.len() {
            // SAFETY: The `while i < bytes.len()` guard guarantees `i` is strictly in bounds of `bytes`.
            let b = unsafe { *bytes.get_unchecked(i) };
            if (b & UTF8_CONT_MASK) != UTF8_CONT_TAG {
                break;
            }
            i += 1;
        }
        i
    }
}

pub use yolowsyntax::{
    Limits, Outline, Section, Symbol, SymbolKind, compact, extract, langs, lexer, parser, recover,
    scanner, stack, table, tree,
};
#[cfg(feature = "tools")]
pub use yolowsyntax::{cdata, convert, corpus, lexconv};

/// 安全解析入口:对底层转译语法表与外部扫描器补充 `catch_unwind` 隔离,异常时降级为 `truncated` 退化树。
pub mod api {
    pub use yolowsyntax::api::{Ev, ParseTree, VNode};

    pub fn parse(
        lang: &yolowsyntax::table::Language,
        input: &[u8],
        limits: yolowsyntax::Limits,
    ) -> ParseTree {
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            yolowsyntax::api::parse(lang, input, limits)
        }))
        .unwrap_or_else(|_| {
            yolowsyntax::api::parse(
                lang,
                input,
                yolowsyntax::Limits {
                    max_nodes: 0,
                    ..limits
                },
            )
        })
    }

    /// 受截止时间预算约束的安全解析:`deadline_ms == Some(0)` 直接返回 `truncated` 退化树(规避
    /// `yolowsyntax` 将 `max_millis == 0` 视为不限时),否则夹紧 `Limits::max_millis`。
    pub fn parse_with_budget(
        lang: &yolowsyntax::table::Language,
        input: &[u8],
        limits: yolowsyntax::Limits,
        deadline_ms: Option<u64>,
    ) -> ParseTree {
        let clamped = match deadline_ms {
            Some(0) => yolowsyntax::Limits {
                max_nodes: 0,
                ..limits
            },
            Some(ms) => yolowsyntax::Limits {
                max_millis: if limits.max_millis == 0 {
                    ms
                } else {
                    limits.max_millis.min(ms)
                },
                ..limits
            },
            None => limits,
        };
        parse(lang, input, clamped)
    }
}

/// 提取代码大纲,并保证所有 `Section` 范围严格对齐在 `source` 的 UTF-8 字符边界上且首尾相接覆盖全文。
pub fn outline(tag: &str, source: &str) -> Option<Outline> {
    let mut out = yolowsyntax::outline(tag, source)?;
    sanitize_sections(source, &mut out.sections);
    Some(out)
}

/// 受输入大小与时间预算约束的大纲提取:前置拦截超限/零预算/空输入或未知语言,解析后校验 `deadline_ms` 并原地整理分节边界。
pub fn outline_with_budget(
    tag: &str,
    source: &str,
    max_input_bytes: usize,
    deadline_ms: Option<u64>,
) -> Option<Outline> {
    if deadline_ms == Some(0)
        || source.is_empty()
        || source.len() > max_input_bytes
        || langs::Lang::from_tag(tag).is_none()
    {
        return None;
    }
    let started = Instant::now();
    let mut out = yolowsyntax::outline(tag, source)?;
    if let Some(ms) = deadline_ms
        && started.elapsed() > Duration::from_millis(ms)
    {
        return None;
    }
    sanitize_sections(source, &mut out.sections);
    Some(out)
}

fn sanitize_sections(source: &str, sections: &mut Vec<Section>) {
    let len = source.len();
    if sections.is_empty() {
        sections.push(Section {
            start: 0,
            end: len,
            title: None,
        });
        return;
    }
    let mut cursor = 0usize;
    let mut write = 0usize;
    for read in 0..sections.len() {
        let end = fast_utf8::ceil_utf8_boundary(source, sections[read].end);
        if end <= cursor {
            continue;
        }
        let title = sections[read].title.take();
        sections[write] = Section {
            start: cursor,
            end,
            title,
        };
        write += 1;
        cursor = end;
    }
    if write == 0 {
        sections.truncate(1);
        sections[0] = Section {
            start: 0,
            end: len,
            title: None,
        };
    } else {
        sections.truncate(write);
        if let Some(last) = sections.last_mut() {
            last.end = len;
        }
    }
}

#[cfg(test)]
mod m1_2b_tests;