feat: add source and public protocol inputs
This commit is contained in:
1 parent
68b14db095
commit
e67697be06
30 files changed
+3021
No files matched your search
@@ -0,0 +1,130 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::Span;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Producer {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub markdown_profile: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AnalysisFunction {
|
||||
pub id: String,
|
||||
pub unit_id: String,
|
||||
pub local_name: String,
|
||||
pub span: Span,
|
||||
pub heading_span: Span,
|
||||
pub signature: Value,
|
||||
#[serde(default)]
|
||||
pub effects: Vec<String>,
|
||||
pub body: Vec<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AnalysisModule {
|
||||
pub id: String,
|
||||
pub package_instance_id: String,
|
||||
pub relative_path: String,
|
||||
pub source_digest: String,
|
||||
pub units: Vec<Value>,
|
||||
pub functions: Vec<AnalysisFunction>,
|
||||
#[serde(default)]
|
||||
pub imports: Vec<Value>,
|
||||
#[serde(default)]
|
||||
pub references: Vec<Value>,
|
||||
#[serde(default)]
|
||||
pub calls: Vec<Value>,
|
||||
#[serde(default)]
|
||||
pub resources: Vec<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct CoreDiagnostic {
|
||||
pub module: Option<String>,
|
||||
pub relative_path: Option<String>,
|
||||
pub span: Option<Span>,
|
||||
pub line: Option<usize>,
|
||||
pub column: Option<usize>,
|
||||
pub severity: String,
|
||||
pub code: String,
|
||||
pub message: String,
|
||||
#[serde(default)]
|
||||
pub hints: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExecutionProjection {
|
||||
pub producer: Producer,
|
||||
pub project: Value,
|
||||
pub modules: Vec<AnalysisModule>,
|
||||
pub diagnostics: Vec<CoreDiagnostic>,
|
||||
pub raw: Value,
|
||||
}
|
||||
|
||||
impl ExecutionProjection {
|
||||
pub fn from_json(raw: Value) -> Result<Self, String> {
|
||||
if raw.get("schema").and_then(Value::as_str) != Some("marqdo.analysis") {
|
||||
return Err("Analysis schema 不是 marqdo.analysis".into());
|
||||
}
|
||||
if raw.get("schema_version").and_then(Value::as_u64) != Some(2) {
|
||||
return Err("只支持 Analysis schema_version 2".into());
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Wire {
|
||||
producer: Producer,
|
||||
project: Value,
|
||||
modules: Vec<AnalysisModule>,
|
||||
#[serde(default)]
|
||||
diagnostics: Vec<CoreDiagnostic>,
|
||||
}
|
||||
let wire: Wire = serde_json::from_value(raw.clone()).map_err(|error| error.to_string())?;
|
||||
if wire.producer.markdown_profile != "marqdo.md.v1" {
|
||||
return Err(format!(
|
||||
"不支持的 Markdown Profile {}",
|
||||
wire.producer.markdown_profile
|
||||
));
|
||||
}
|
||||
for module in &wire.modules {
|
||||
if module.source_digest.len() != 64
|
||||
|| !module.source_digest.bytes().all(|byte| byte.is_ascii_hexdigit())
|
||||
{
|
||||
return Err(format!("模块 {} 的 source_digest 无效", module.id));
|
||||
}
|
||||
if module.relative_path.starts_with('/') || module.relative_path.contains("..") {
|
||||
return Err(format!("模块 {} 的 relative_path 不安全", module.id));
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
producer: wire.producer,
|
||||
project: wire.project,
|
||||
modules: wire.modules,
|
||||
diagnostics: wire.diagnostics,
|
||||
raw,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn semantic_nodes(body: &[Value]) -> impl Iterator<Item = &Value> {
|
||||
body.iter().flat_map(walk_node)
|
||||
}
|
||||
|
||||
fn walk_node(node: &Value) -> Box<dyn Iterator<Item = &Value> + '_> {
|
||||
let mut nested = Vec::new();
|
||||
if let Some(object) = node.as_object() {
|
||||
for value in object.values() {
|
||||
match value {
|
||||
Value::Object(_) => nested.push(value),
|
||||
Value::Array(array) => {
|
||||
nested.extend(array.iter().filter(|value| value.is_object()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Box::new(
|
||||
std::iter::once(node).chain(nested.into_iter().flat_map(|value| walk_node(value))),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::error::{LintError, Result};
|
||||
|
||||
use super::{SourceSnapshot, Span};
|
||||
|
||||
pub type NodeId = usize;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum HeadingMode {
|
||||
Knowledge,
|
||||
Exec,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CarrierKind {
|
||||
Code,
|
||||
Strong,
|
||||
Emph,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MarkdownNode {
|
||||
pub kind: String,
|
||||
pub span: Span,
|
||||
pub literal: Option<String>,
|
||||
pub level: Option<u8>,
|
||||
pub setext: bool,
|
||||
pub ordered: Option<bool>,
|
||||
pub start: Option<i64>,
|
||||
pub tight: Option<bool>,
|
||||
pub task: Option<bool>,
|
||||
pub ticks: Option<usize>,
|
||||
pub parent: Option<NodeId>,
|
||||
pub children: Vec<NodeId>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HeadingSegment {
|
||||
pub node: NodeId,
|
||||
pub level: u8,
|
||||
pub mode: HeadingMode,
|
||||
pub name: String,
|
||||
pub function: Option<NodeId>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Carrier {
|
||||
pub node: NodeId,
|
||||
pub kind: CarrierKind,
|
||||
pub span: Span,
|
||||
pub payload_span: Span,
|
||||
pub payload: String,
|
||||
pub heading: Option<NodeId>,
|
||||
pub function: Option<NodeId>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ProseFragment {
|
||||
pub node: NodeId,
|
||||
pub span: Span,
|
||||
pub text: String,
|
||||
pub function: NodeId,
|
||||
pub heading: Option<NodeId>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MarkdownTree {
|
||||
pub nodes: Vec<MarkdownNode>,
|
||||
pub root: NodeId,
|
||||
pub headings: Vec<HeadingSegment>,
|
||||
pub carriers: Vec<Carrier>,
|
||||
node_functions: Vec<Option<NodeId>>,
|
||||
node_headings: Vec<Option<NodeId>>,
|
||||
node_modes: Vec<HeadingMode>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawNode {
|
||||
kind: String,
|
||||
span: Span,
|
||||
#[serde(default)]
|
||||
literal: Option<String>,
|
||||
#[serde(default)]
|
||||
level: Option<u8>,
|
||||
#[serde(default)]
|
||||
setext: bool,
|
||||
#[serde(default)]
|
||||
ordered: Option<bool>,
|
||||
#[serde(default)]
|
||||
start: Option<i64>,
|
||||
#[serde(default)]
|
||||
tight: Option<bool>,
|
||||
#[serde(default)]
|
||||
task: Option<bool>,
|
||||
#[serde(default)]
|
||||
ticks: Option<usize>,
|
||||
#[serde(default)]
|
||||
children: Vec<RawNode>,
|
||||
}
|
||||
|
||||
impl MarkdownTree {
|
||||
pub fn from_json(value: Value, source: &SourceSnapshot) -> Result<Self> {
|
||||
let raw: RawNode = serde_json::from_value(value)
|
||||
.map_err(|error| LintError::Protocol(format!("AST JSON 无效:{error}")))?;
|
||||
Self::from_raw(raw, source)
|
||||
}
|
||||
|
||||
fn from_raw(raw: RawNode, source: &SourceSnapshot) -> Result<Self> {
|
||||
if raw.kind != "document" {
|
||||
return Err(LintError::Protocol("AST 根节点不是 document".into()));
|
||||
}
|
||||
let mut nodes = Vec::new();
|
||||
let root = flatten(raw, None, &mut nodes);
|
||||
for node in &nodes {
|
||||
node.span.validate(source.bytes.len())?;
|
||||
}
|
||||
let count = nodes.len();
|
||||
let mut tree = Self {
|
||||
nodes,
|
||||
root,
|
||||
headings: Vec::new(),
|
||||
carriers: Vec::new(),
|
||||
node_functions: vec![None; count],
|
||||
node_headings: vec![None; count],
|
||||
node_modes: vec![HeadingMode::Knowledge; count],
|
||||
};
|
||||
tree.index_headings_and_carriers(source)?;
|
||||
Ok(tree)
|
||||
}
|
||||
|
||||
fn index_headings_and_carriers(&mut self, source: &SourceSnapshot) -> Result<()> {
|
||||
struct Ancestor {
|
||||
level: u8,
|
||||
mode: HeadingMode,
|
||||
}
|
||||
let mut stack: Vec<Ancestor> = Vec::new();
|
||||
let mut current_heading = None;
|
||||
let mut current_function = None;
|
||||
let mut current_mode = HeadingMode::Knowledge;
|
||||
let root_children = self.nodes[self.root].children.clone();
|
||||
for child in root_children {
|
||||
if self.nodes[child].kind == "heading" {
|
||||
let level = self.nodes[child].level.unwrap_or(0);
|
||||
while stack.last().is_some_and(|entry| entry.level >= level) {
|
||||
stack.pop();
|
||||
}
|
||||
let inherited = stack
|
||||
.last()
|
||||
.map(|entry| entry.mode)
|
||||
.unwrap_or(HeadingMode::Knowledge);
|
||||
let declared = if self.nodes[child].setext {
|
||||
None
|
||||
} else {
|
||||
heading_declaration(self, child)
|
||||
};
|
||||
current_mode = declared
|
||||
.as_ref()
|
||||
.map(|(mode, _)| *mode)
|
||||
.unwrap_or(inherited);
|
||||
current_heading = Some(child);
|
||||
match level {
|
||||
1 => current_function = None,
|
||||
2 => {
|
||||
current_function = (current_mode == HeadingMode::Exec).then_some(child)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let name = declared
|
||||
.map(|(_, name)| name)
|
||||
.unwrap_or_else(|| plain_text(self, child));
|
||||
self.headings.push(HeadingSegment {
|
||||
node: child,
|
||||
level,
|
||||
mode: current_mode,
|
||||
name,
|
||||
function: current_function,
|
||||
});
|
||||
stack.push(Ancestor {
|
||||
level,
|
||||
mode: current_mode,
|
||||
});
|
||||
self.node_headings[child] = current_heading;
|
||||
self.node_functions[child] = current_function;
|
||||
self.node_modes[child] = current_mode;
|
||||
continue;
|
||||
}
|
||||
self.assign_region(child, current_heading, current_function, current_mode);
|
||||
if current_mode == HeadingMode::Exec && current_function.is_some() {
|
||||
self.collect_carriers(child, current_heading, current_function, source)?;
|
||||
}
|
||||
}
|
||||
self.carriers.sort_by_key(|carrier| carrier.span.start);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn assign_region(
|
||||
&mut self,
|
||||
node: NodeId,
|
||||
heading: Option<NodeId>,
|
||||
function: Option<NodeId>,
|
||||
mode: HeadingMode,
|
||||
) {
|
||||
self.node_headings[node] = heading;
|
||||
self.node_functions[node] = function;
|
||||
self.node_modes[node] = mode;
|
||||
let children = self.nodes[node].children.clone();
|
||||
for child in children {
|
||||
self.assign_region(child, heading, function, mode);
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_carriers(
|
||||
&mut self,
|
||||
node: NodeId,
|
||||
heading: Option<NodeId>,
|
||||
function: Option<NodeId>,
|
||||
source: &SourceSnapshot,
|
||||
) -> Result<()> {
|
||||
let kind = self.nodes[node].kind.as_str();
|
||||
let carrier_kind = match kind {
|
||||
"code" => Some(CarrierKind::Code),
|
||||
"strong" => Some(CarrierKind::Strong),
|
||||
"emph" => Some(CarrierKind::Emph),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(carrier_kind) = carrier_kind {
|
||||
let payload = if carrier_kind == CarrierKind::Code {
|
||||
self.nodes[node].literal.clone().unwrap_or_default()
|
||||
} else {
|
||||
self.nodes[node]
|
||||
.children
|
||||
.iter()
|
||||
.filter_map(|child| {
|
||||
let child = &self.nodes[*child];
|
||||
matches!(child.kind.as_str(), "text" | "code")
|
||||
.then(|| child.literal.clone().unwrap_or_default())
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let span = self.nodes[node].span;
|
||||
let payload_span = if carrier_kind == CarrierKind::Code {
|
||||
let ticks = self.nodes[node].ticks.unwrap_or(1);
|
||||
Span::new(
|
||||
span.start.saturating_add(ticks).min(span.end),
|
||||
span.end.saturating_sub(ticks).max(span.start),
|
||||
)
|
||||
} else {
|
||||
let children = self.nodes[node].children.iter().filter_map(|child| {
|
||||
let child = &self.nodes[*child];
|
||||
matches!(child.kind.as_str(), "text" | "code").then_some(child.span)
|
||||
});
|
||||
let mut spans = children;
|
||||
let first = spans.next().unwrap_or(span);
|
||||
let last = spans.last().unwrap_or(first);
|
||||
Span::new(first.start, last.end)
|
||||
};
|
||||
source.slice(span)?;
|
||||
self.carriers.push(Carrier {
|
||||
node,
|
||||
kind: carrier_kind,
|
||||
span,
|
||||
payload_span,
|
||||
payload,
|
||||
heading,
|
||||
function,
|
||||
});
|
||||
return Ok(());
|
||||
}
|
||||
if matches!(kind, "paragraph" | "list" | "item" | "block_quote") {
|
||||
let children = self.nodes[node].children.clone();
|
||||
for child in children {
|
||||
self.collect_carriers(child, heading, function, source)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn function_of(&self, node: NodeId) -> Option<NodeId> {
|
||||
self.node_functions.get(node).copied().flatten()
|
||||
}
|
||||
|
||||
pub fn heading_of(&self, node: NodeId) -> Option<NodeId> {
|
||||
self.node_headings.get(node).copied().flatten()
|
||||
}
|
||||
|
||||
pub fn mode_of(&self, node: NodeId) -> HeadingMode {
|
||||
self.node_modes
|
||||
.get(node)
|
||||
.copied()
|
||||
.unwrap_or(HeadingMode::Knowledge)
|
||||
}
|
||||
|
||||
pub fn heading(&self, node: NodeId) -> Option<&HeadingSegment> {
|
||||
self.headings.iter().find(|heading| heading.node == node)
|
||||
}
|
||||
|
||||
pub fn ancestors(&self, mut node: NodeId) -> Vec<NodeId> {
|
||||
let mut result = Vec::new();
|
||||
while let Some(parent) = self.nodes[node].parent {
|
||||
result.push(parent);
|
||||
node = parent;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub fn nearest(&self, node: NodeId, kind: &str) -> Option<NodeId> {
|
||||
self.ancestors(node)
|
||||
.into_iter()
|
||||
.find(|ancestor| self.nodes[*ancestor].kind == kind)
|
||||
}
|
||||
|
||||
pub fn item_carriers(&self, item: NodeId) -> Vec<&Carrier> {
|
||||
self.carriers
|
||||
.iter()
|
||||
.filter(|carrier| self.nearest(carrier.node, "item") == Some(item))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn first_carrier_in_item(&self, item: NodeId) -> Option<&Carrier> {
|
||||
self.item_carriers(item).into_iter().min_by_key(|c| c.span.start)
|
||||
}
|
||||
|
||||
pub fn is_descendant(&self, node: NodeId, ancestor: NodeId) -> bool {
|
||||
node == ancestor || self.ancestors(node).contains(&ancestor)
|
||||
}
|
||||
|
||||
pub fn prose_fragments(&self, function: NodeId) -> Vec<ProseFragment> {
|
||||
let mut fragments = Vec::new();
|
||||
for node in 0..self.nodes.len() {
|
||||
if self.nodes[node].kind == "text"
|
||||
&& self.function_of(node) == Some(function)
|
||||
&& self.mode_of(node) == HeadingMode::Exec
|
||||
&& !self.has_carrier_ancestor(node)
|
||||
&& !self.has_inert_ancestor(node)
|
||||
{
|
||||
if let Some(text) = self.nodes[node].literal.clone() {
|
||||
fragments.push(ProseFragment {
|
||||
node,
|
||||
span: self.nodes[node].span,
|
||||
text,
|
||||
function,
|
||||
heading: self.heading_of(node),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
fragments
|
||||
}
|
||||
|
||||
fn has_carrier_ancestor(&self, node: NodeId) -> bool {
|
||||
self.ancestors(node).into_iter().any(|ancestor| {
|
||||
matches!(self.nodes[ancestor].kind.as_str(), "strong" | "emph" | "code")
|
||||
})
|
||||
}
|
||||
|
||||
fn has_inert_ancestor(&self, node: NodeId) -> bool {
|
||||
self.ancestors(node).into_iter().any(|ancestor| {
|
||||
matches!(
|
||||
self.nodes[ancestor].kind.as_str(),
|
||||
"table" | "strikethrough" | "code_block" | "math" | "math_block" | "html_block" | "html_inline"
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn flatten(raw: RawNode, parent: Option<NodeId>, nodes: &mut Vec<MarkdownNode>) -> NodeId {
|
||||
let id = nodes.len();
|
||||
nodes.push(MarkdownNode {
|
||||
kind: raw.kind,
|
||||
span: raw.span,
|
||||
literal: raw.literal,
|
||||
level: raw.level,
|
||||
setext: raw.setext,
|
||||
ordered: raw.ordered,
|
||||
start: raw.start,
|
||||
tight: raw.tight,
|
||||
task: raw.task,
|
||||
ticks: raw.ticks,
|
||||
parent,
|
||||
children: Vec::new(),
|
||||
});
|
||||
for child in raw.children {
|
||||
let child = flatten(child, Some(id), nodes);
|
||||
nodes[id].children.push(child);
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
fn heading_declaration(tree: &MarkdownTree, heading: NodeId) -> Option<(HeadingMode, String)> {
|
||||
let first = tree.nodes[heading].children.first()?;
|
||||
let first = &tree.nodes[*first];
|
||||
if first.kind != "text" {
|
||||
return None;
|
||||
}
|
||||
let literal = first.literal.as_deref()?;
|
||||
for (prefix, mode) in [
|
||||
("@exec", HeadingMode::Exec),
|
||||
("@knowledge", HeadingMode::Knowledge),
|
||||
] {
|
||||
if let Some(rest) = literal.strip_prefix(prefix) {
|
||||
if rest.is_empty() || rest.starts_with(char::is_whitespace) {
|
||||
let name = rest.trim();
|
||||
if !name.is_empty() {
|
||||
return Some((mode, name.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn plain_text(tree: &MarkdownTree, node: NodeId) -> String {
|
||||
let node = &tree.nodes[node];
|
||||
if let Some(literal) = &node.literal {
|
||||
if node.kind == "text" || node.kind == "code" {
|
||||
return literal.clone();
|
||||
}
|
||||
}
|
||||
node.children
|
||||
.iter()
|
||||
.map(|child| plain_text(tree, *child))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn tree(markdown: &str) -> MarkdownTree {
|
||||
let source = SourceSnapshot::new(PathBuf::from("test.mq.md"), markdown.as_bytes().to_vec()).unwrap();
|
||||
let ast = crate::input::fallback_ast(&source).unwrap();
|
||||
MarkdownTree::from_json(ast, &source).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexes_functions_carriers_and_list_ancestors() {
|
||||
let tree = tree("# @knowledge 示例\n\n## @exec 判断\n\n说明。\n\n`params(x: Int)`\n\n1. `if x > 0`:正数。\n\n **结果 = 1**\n\n2. `else`:其他。\n\n **结果 = 0**\n\n`end`\n\n*return 结果*\n");
|
||||
assert_eq!(tree.headings.len(), 2);
|
||||
assert_eq!(tree.carriers.len(), 7);
|
||||
let if_carrier = tree.carriers.iter().find(|c| c.payload == "if x > 0").unwrap();
|
||||
let item = tree.nearest(if_carrier.node, "item").unwrap();
|
||||
assert_eq!(tree.first_carrier_in_item(item).unwrap().node, if_carrier.node);
|
||||
let list = tree.nearest(item, "list").unwrap();
|
||||
assert_eq!(tree.nodes[list].ordered, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn knowledge_carriers_are_not_executable() {
|
||||
let tree = tree("## @knowledge 说明\n\n**重要** 和 `code`。\n");
|
||||
assert!(tree.carriers.is_empty());
|
||||
assert!(tree.prose_fragments(0).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
mod analysis;
|
||||
mod markdown;
|
||||
mod source;
|
||||
mod span;
|
||||
|
||||
pub use analysis::{semantic_nodes, AnalysisFunction, AnalysisModule, CoreDiagnostic, ExecutionProjection};
|
||||
pub use markdown::{Carrier, CarrierKind, HeadingMode, HeadingSegment, MarkdownNode, MarkdownTree, NodeId};
|
||||
pub use source::SourceSnapshot;
|
||||
pub use span::{LineColumn, Span};
|
||||
@@ -0,0 +1,107 @@
|
||||
use std::{fs, path::{Path, PathBuf}};
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::error::{io, LintError, Result};
|
||||
|
||||
use super::{LineColumn, Span};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SourceSnapshot {
|
||||
pub path: PathBuf,
|
||||
pub bytes: Vec<u8>,
|
||||
pub digest: String,
|
||||
line_starts: Vec<usize>,
|
||||
}
|
||||
|
||||
impl SourceSnapshot {
|
||||
pub fn load(path: impl AsRef<Path>) -> Result<Self> {
|
||||
let path = path.as_ref();
|
||||
let bytes = fs::read(path).map_err(|error| io(path, error))?;
|
||||
Self::new(path.to_path_buf(), bytes)
|
||||
}
|
||||
|
||||
pub fn new(path: PathBuf, bytes: Vec<u8>) -> Result<Self> {
|
||||
std::str::from_utf8(&bytes).map_err(|source| LintError::Utf8 {
|
||||
path: path.clone(),
|
||||
source,
|
||||
})?;
|
||||
let digest = format!("sha256:{:x}", Sha256::digest(&bytes));
|
||||
let mut line_starts = vec![0];
|
||||
for (index, byte) in bytes.iter().enumerate() {
|
||||
if *byte == b'\n' {
|
||||
line_starts.push(index + 1);
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
path,
|
||||
bytes,
|
||||
digest,
|
||||
line_starts,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn text(&self) -> &str {
|
||||
std::str::from_utf8(&self.bytes).expect("SourceSnapshot 构造时已验证 UTF-8")
|
||||
}
|
||||
|
||||
pub fn digest_hex(&self) -> &str {
|
||||
self.digest.trim_start_matches("sha256:")
|
||||
}
|
||||
|
||||
pub fn slice(&self, span: Span) -> Result<&str> {
|
||||
span.validate(self.bytes.len())?;
|
||||
self.text().get(span.start..span.end).ok_or_else(|| {
|
||||
LintError::Protocol(format!("span [{}, {}) 不在 UTF-8 字符边界", span.start, span.end))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn line_column(&self, offset: usize) -> Result<LineColumn> {
|
||||
if offset > self.bytes.len() || !self.text().is_char_boundary(offset) {
|
||||
return Err(LintError::Protocol(format!("无效源码偏移 {offset}")));
|
||||
}
|
||||
let line_index = match self.line_starts.binary_search(&offset) {
|
||||
Ok(index) => index,
|
||||
Err(index) => index - 1,
|
||||
};
|
||||
let start = self.line_starts[line_index];
|
||||
let content_start = if line_index == 0 && self.bytes.starts_with(&[0xef, 0xbb, 0xbf]) {
|
||||
3
|
||||
} else {
|
||||
start
|
||||
};
|
||||
let column = self.text()[content_start..offset.max(content_start)]
|
||||
.chars()
|
||||
.count()
|
||||
+ 1;
|
||||
Ok(LineColumn {
|
||||
line: line_index + 1,
|
||||
column,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn digest_and_columns_use_original_utf8_bytes() {
|
||||
let source = SourceSnapshot::new(
|
||||
PathBuf::from("unicode.mq.md"),
|
||||
"\u{feff}甲😀\n乙".as_bytes().to_vec(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(source.digest.starts_with("sha256:"));
|
||||
assert_eq!(source.line_column(3).unwrap(), LineColumn { line: 1, column: 1 });
|
||||
assert_eq!(source.line_column(6).unwrap(), LineColumn { line: 1, column: 2 });
|
||||
assert_eq!(source.line_column(11).unwrap(), LineColumn { line: 2, column: 1 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_span_and_invalid_utf8() {
|
||||
let source = SourceSnapshot::new(PathBuf::from("x"), b"abc".to_vec()).unwrap();
|
||||
assert!(source.slice(Span::new(2, 4)).is_err());
|
||||
assert!(SourceSnapshot::new(PathBuf::from("x"), vec![0xff]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::error::{LintError, Result};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub struct Span {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
impl Span {
|
||||
pub fn new(start: usize, end: usize) -> Self {
|
||||
Self { start, end }
|
||||
}
|
||||
|
||||
pub fn contains(self, other: Span) -> bool {
|
||||
self.start <= other.start && other.end <= self.end
|
||||
}
|
||||
|
||||
pub fn validate(self, len: usize) -> Result<()> {
|
||||
if self.start > self.end || self.end > len {
|
||||
return Err(LintError::Protocol(format!(
|
||||
"span [{}, {}) 超出源码长度 {len}",
|
||||
self.start, self.end
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LineColumn {
|
||||
pub line: usize,
|
||||
pub column: usize,
|
||||
}
|
||||
Reference in new issue
Block a user