Files
endorphin-aster-vm/crates/frontend/src/diagnostic.rs
T

141 lines
5.9 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! lexer、parser、AST 与 compiler 共用的位置/错误协议;字节跨度与用户显示的 Unicode 行列分开保存。
use std::error::Error;
use std::fmt;
/// Half-open UTF-8 byte range in the original source, including trivia between
/// the first and last syntax token. EOF has an empty range at source.len().
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
/// 语法节点及 Token 的半开原文字节范围 [start,end),EOF 使用 source.len() 处的空区间。
pub struct Span {
// 包含的起始字节偏移,应落在 UTF-8 字符边界。
pub start: usize,
// 不包含的结束字节偏移,包含两端 Token 之间的注释/空白。
pub end: usize,
}
impl Span {
/// 词法/语法规则及测试构造范围,仅保存偏移;合法性由 slice 或 AST 校验验证。
pub const fn new(start: usize, end: usize) -> Self {
Self { start, end }
}
/// Safely read this range, rejecting reversed, out-of-bounds or split UTF-8 ranges.
/// AST Spanned::source_text 及文档校验调用;安全拒绝倒序、越界或切断 UTF-8 字符的范围。
pub fn slice(self, source: &str) -> Option<&str> {
source.get(self.start..self.end)
}
/// AST Spanned::location 和编译器调用,先验证整个范围,再计算起点的显示行列。
pub fn location(self, source: &str) -> Option<SourceLocation> {
self.slice(source)?;
Some(source_location(source, self.start))
}
/// parser 组合左右节点及后缀范围时调用;沿用第一个起点和最后一个终点,不另做顺序检查。
pub(crate) fn through(self, last: Self) -> Self {
Self::new(self.start, last.end)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// 阶段分类供宿主和测试区分错误发生于分词、语法、名称分析还是生成。
pub enum DiagnosticKind {
// 词法规则无法接受字符或字符串转义等输入。
Lexical,
// Token 已合法,但无法匹配指定根的语法。
Syntax,
// 编译名称/控制流分析拒绝重复、未知或未初始化读取。
Semantic,
// AST 校验或指令生成/验证失败,尚未执行 VM。
Compilation,
}
/// Lines and Unicode scalar columns are one-based. CRLF counts as one newline.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// source_location 输出的一基位置;列按 Unicode 标量计数,CRLF 合并为一个换行。
pub struct SourceLocation {
// 从一开始的逻辑行号,独立 CR 和 LF 均换行,CRLF 只换一次。
pub line: usize,
// 从一开始的 Unicode 标量列,不是字节数、字素簇数或终端显示宽度。
pub column: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
/// 各阶段产生的不带来源快照的错误,SourceUnit::annotate 可补来源和行列。
pub struct Diagnostic {
// 原始失败阶段,便于测试和宿主按类别处理。
pub kind: DiagnosticKind,
// 原源码字节位置,Display 直接显示这个范围。
pub span: Span,
// 面向用户的说明,不含来源名及行列前缀。
pub message: String,
// 语法解析器报告的期望项;词法和编译器辅助构造通常留空。
pub expected: Vec<String>,
}
impl Diagnostic {
/// lexer 和词法规则共用的失败包装,统一设置 Lexical 类别并保留原文字节范围。
pub(crate) fn lexical(span: Span, message: impl Into<String>) -> Self {
Self {
kind: DiagnosticKind::Lexical,
span,
message: message.into(),
expected: Vec::new(),
}
}
/// SourceUnit::annotate 及宿主根据起始偏移计算位置;本入口不校验整个 span,调用方应传对应原文。
pub fn location(&self, source: &str) -> SourceLocation {
source_location(source, self.span.start)
}
}
impl fmt::Display for Diagnostic {
/// 未绑定来源的错误显示说明及字节区间;来源行列由 SourceDiagnostic 的 Display 提供。
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"{} at bytes {}..{}",
self.message, self.span.start, self.span.end
)
}
}
impl Error for Diagnostic {}
/// Span::location 和 Diagnostic::location 共用的纯文本扫描,计算 position 前缀的行列,不执行 IO。
/// 调用方应提供有效字节边界;此辅助函数只扫描到偏移或 EOF,不负责校验范围。
fn source_location(source: &str, position: usize) -> SourceLocation {
// 空前缀位于第一行第一列,每消费一个普通 Unicode 标量才前进一列。
let mut location = SourceLocation { line: 1, column: 1 };
// 记录上一个已消费字符是否 CR,使紧随其后的 LF 不再次增加行号。
let mut previous_cr = false;
// char_indices 同时提供字节边界和完整字符,避免把多字节字符算成多列。
for (offset, character) in source.char_indices() {
// 当前字符起点已到目标位置,不能把目标字符本身算进前缀。
if offset >= position {
break;
}
// 换行重置列;普通字符(包括 tab)仅按一个 Unicode 标量计列。
match character {
// CR 自身就是换行,可能随后与 LF 配成一个换行。
'\r' => {
location.line += 1;
location.column = 1;
}
// CR 已完成换行,这个 LF 不再增加行号。
'\n' if previous_cr => {}
// 独立 LF 换到下一行第一列。
'\n' => {
location.line += 1;
location.column = 1;
}
_ => location.column += 1,
}
// 每轮都更新,只有紧邻 CR 的 LF 才会被合并。
previous_cr = character == '\r';
}
location
}