feat(PR-02): DocumentModel, Analysis v2 projection, single renderer and Live browsing

- document.rs: comrak marqdo.md.v1 parse -> DocBlock/Inline with exact UTF-8 spans
- semantic.rs: typed Analysis v2 validation (schema/profile/root_id/source_digest,
  units/functions/statements/resources/imports/references/calls/diagnostics,
  per-span UTF-8 checks with explicit view.source_span_invalid warnings)
- presentation.rs: one PresentationModel/Outline with source status matrix
- render.rs: one ReaderRenderer; sanitized GFM, statement anchors, heading mode
  badges (display-only prefix strip), source pane, docs/Live|Static link policy,
  CSP meta, no inline scripts, no raw HTML execution
- server.rs: loopback-only Live reader with Host/DNS-rebinding checks, strict
  percent decoding, project path boundary, security headers, read-only APIs
- app.rs: AppContext degradation (core missing -> prose-only, check error ->
  diagnostics + revoked semantics, protocol mismatch -> hard error)
- assets: single reader.css/reader.js + embedded SHA-256 AssetBundle, copied
  legacy logo/blossom/feather with provenance
- examples + frozen-CLI Analysis goldens + rendering/HTTP/asset/no-coupling tests
- ADR-0003 heading prefix/anchor identity; docs updated
This commit is contained in:
marqdo-view dev committed 2026-11-22 11:19:11 +08:00
1 parent 8ba20a5c67
commit 80ce564f09
47 files changed
+26127 -203

No files matched your search

+263 -142
View File
@@ -1,16 +1,157 @@
//! Application layer: turns parsed commands into use cases.
//!
//! No HTML is built here; no Markdown is parsed here. Browse uses the single
//! renderer (PR-02+), verify only checks bindings, export only writes static
//! files through the same renderer (PR-05).
//! No HTML is built here and no Markdown semantics are decided here. Browse and
//! (later) Export call the same `load` + one `ReaderRenderer`.
use crate::cli::{ExportArgs, RuntimeOpts, VerifyArgs};
use crate::core_client::{CheckOptions, CoreClient};
use crate::core_client::{CheckOptions, CheckResponse, CoreClient, RawCheckDiagnostic};
use crate::document::{DocumentIdentity, DocumentModel};
use crate::error::{ViewError, ViewResult};
use crate::project::Project;
use crate::source_map::sha256_hex;
use crate::presentation::{self, BuildInput, Navigation, PresentationModel, SourceStatus};
use crate::project::{Project, SafeRelativePath, ViewConfig};
use crate::semantic::{self, CoreDiagnostic};
use crate::version;
/// Process-wide context for one browsed project: root, optional site config and
/// an optional negotiated frozen core. A missing core degrades to prose only;
/// an incompatible protocol is a hard error (RFC §4).
pub struct AppContext {
project: Project,
config: ViewConfig,
core: Option<CoreClient>,
core_version: Option<String>,
core_note: Option<String>,
}
impl AppContext {
pub fn open(path: &std::path::Path, marqdo_bin: Option<&std::path::Path>) -> ViewResult<Self> {
let project = Project::open(path)?;
let config = ViewConfig::load(project.root())?;
let (core, core_version, core_note) = match CoreClient::from_env(marqdo_bin) {
Ok(client) => match client.negotiate() {
Ok(version) => (Some(client), Some(version.version.to_string()), None),
Err(err) if err.code() == "view.protocol_incompatible" => return Err(err),
Err(err) => (None, None, Some(generic_core_note(&err))),
},
Err(err) if err.code() == "view.core_missing" => {
(None, None, Some(generic_core_note(&err)))
}
Err(err) => return Err(err),
};
Ok(Self {
project,
config,
core,
core_version,
core_note,
})
}
pub fn project(&self) -> &Project {
&self.project
}
pub fn config(&self) -> &ViewConfig {
&self.config
}
pub fn core(&self) -> Option<&CoreClient> {
self.core.as_ref()
}
pub fn core_version(&self) -> Option<&str> {
self.core_version.as_deref()
}
pub fn core_note(&self) -> Option<&str> {
self.core_note.as_deref()
}
/// Read + parse + (optionally) check one document into the one presentation
/// model. Never executes the document.
pub fn load(&self, relative: &SafeRelativePath) -> ViewResult<PresentationModel> {
let source_bytes = self.project.read_source(relative)?;
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
detail: format!("{relative} is not valid UTF-8: {err}"),
})?;
let document = DocumentModel::parse(source, DocumentIdentity::placeholder(relative));
let navigation = Navigation::from_project(&self.project, &self.config, relative);
let mut status = SourceStatus::CoreUnavailable;
let mut status_note = self.core_note.clone();
let mut diagnostics = Vec::new();
let mut verified = None;
if let Some(client) = &self.core {
match client.check(&self.project, relative, &CheckOptions::default())? {
CheckResponse {
success: false,
diagnostics: raw_diagnostics,
exit_code,
..
} => {
status = SourceStatus::CoreError;
status_note = Some(format!(
"Core 检查失败(exit {exit_code}):语义标注已撤销,正文仍可阅读。"
));
diagnostics = raw_diagnostics
.iter()
.map(|diagnostic| diagnostic_to_view(diagnostic, relative))
.collect();
}
CheckResponse {
success: true,
analysis: Some(check),
..
} => match semantic::verify_analysis(
&check.analysis_bytes,
&document.source,
&document.source_index,
relative.as_str(),
) {
Ok(verified_analysis) => {
status = SourceStatus::StaticOk;
status_note = None;
verified = Some(verified_analysis);
}
Err(err) if err.code() == "view.source_mismatch" => {
status = SourceStatus::SourceMismatch;
status_note = Some(
"当前源码字节与 Analysis 的 source_digest 不一致,语义标注已禁用。"
.to_string(),
);
}
Err(err) if err.code() == "view.protocol_incompatible" => {
return Err(err);
}
Err(err) => {
status = SourceStatus::CoreError;
status_note = Some(generic_core_note(&err));
}
},
CheckResponse {
success: true,
analysis: None,
..
} => {
status = SourceStatus::CoreError;
status_note = Some("Core 声称检查成功但没有产出 Analysis。".to_string());
}
}
}
Ok(presentation::build(BuildInput {
document,
analysis: verified.as_ref(),
status,
status_note,
diagnostics,
navigation,
core_version: self.core_version.clone(),
}))
}
}
pub fn verify(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
let path = args
.path
@@ -20,14 +161,14 @@ pub fn verify(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
let project = Project::open(&path)?;
let entry = project.entry().relative.clone();
let source_bytes = project.read_source(&entry)?;
let source_text = String::from_utf8(source_bytes.clone()).map_err(|err| ViewError::Io {
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
detail: format!("{entry} is not valid UTF-8: {err}"),
})?;
let _ = source_text;
let source_index = crate::source_map::SourceIndex::new(&source);
let client = CoreClient::from_env(opts.marqdo_bin.as_deref())?;
let core_version = client.negotiate()?;
let check = client.check(
let response = client.check(
&project,
&entry,
&CheckOptions {
@@ -35,12 +176,51 @@ pub fn verify(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
timeout: None,
},
)?;
let analysis: serde_json::Value =
serde_json::from_slice(&check.analysis_bytes).map_err(|err| ViewError::AnalysisFailed {
detail: format!("emitted Analysis is not JSON: {err}"),
})?;
let summary = validate_static_binding(&analysis, entry.as_str(), &source_bytes)?;
let check = match response {
CheckResponse {
success: false,
diagnostics,
exit_code,
..
} => {
let first = diagnostics
.first()
.map(|diagnostic| {
format!(
"{}: {}",
if diagnostic.code.is_empty() {
"diagnostic"
} else {
&diagnostic.code
},
diagnostic.message
)
})
.unwrap_or_else(|| "no diagnostic detail".to_string());
return Err(ViewError::AnalysisFailed {
detail: format!(
"`marqdo check` failed with exit code {exit_code} ({} diagnostic(s)); first: {first}",
diagnostics.len()
),
});
}
CheckResponse {
analysis: Some(check),
..
} => check,
CheckResponse { analysis: None, .. } => {
return Err(ViewError::AnalysisFailed {
detail: "`marqdo check` succeeded but emitted no Analysis".to_string(),
})
}
};
let verified = semantic::verify_analysis(
&check.analysis_bytes,
&source,
&source_index,
entry.as_str(),
)?;
let projection = &verified.projection;
if args.json {
let doc = serde_json::json!({
@@ -53,17 +233,24 @@ pub fn verify(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
},
"analysis": {
"schema": "marqdo.analysis",
"schema_version": 2,
"digest": check.analysis_digest,
"producer_version": summary.producer_version,
"schema_version": version::ANALYSIS_PROTOCOL,
"digest": projection.analysis_digest,
"producer_version": projection.producer_version,
"markdown_profile": projection.markdown_profile,
"functions": projection.functions.len(),
"units": projection.units.len(),
"diagnostics": projection.diagnostics.len(),
},
"project": {
"root_id": summary.root_id,
"identity_kind": summary.identity_kind,
"root_id": projection.project_root_id,
"identity_kind": projection.identity_kind,
"lock_digest": projection.lock_digest,
"stdlib_version": projection.stdlib_version,
},
"document": {
"relative_path": entry.as_str(),
"source_digest": summary.source_digest,
"module_id": projection.module_id,
"source_digest": projection.source_digest,
"source_digest_matches": true,
},
"result": "PASS",
@@ -80,11 +267,16 @@ pub fn verify(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
core_version.version,
version::PRODUCT_RANGE
);
println!("project: {} ({})", summary.root_id, summary.identity_kind);
println!("document: {}", entry);
println!(
"analysis: schema=marqdo.analysis v2 modules={} digest={}",
summary.module_count, check.analysis_digest
"project: {} ({})",
projection.project_root_id, projection.identity_kind
);
println!("document: {entry}");
println!(
"analysis: schema=marqdo.analysis v2 modules={} functions={} digest={}",
projection.modules.len(),
projection.functions.len(),
projection.analysis_digest
);
println!("source digest: match");
println!("result: PASS (static only; document not executed)");
@@ -92,130 +284,59 @@ pub fn verify(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
Ok(0)
}
pub fn browse(opts: &RuntimeOpts) -> ViewResult<i32> {
let path = opts
.path
.clone()
.unwrap_or_else(|| std::path::PathBuf::from("."));
let context = AppContext::open(&path, opts.marqdo_bin.as_deref())?;
crate::server::serve(context, opts)
}
pub fn export(_opts: &RuntimeOpts, _args: &ExportArgs) -> ViewResult<i32> {
Err(ViewError::Unsupported {
detail: "static export lands with PR-05; this build teaches Tool Protocol and statics only"
detail: "static export lands with PR-05; browse and verify are available in this build"
.to_string(),
})
}
pub fn browse(_opts: &RuntimeOpts) -> ViewResult<i32> {
Err(ViewError::Unsupported {
detail: "the Live reader lands with PR-02/PR-03; this build teaches Tool Protocol and statics only"
.to_string(),
})
fn generic_core_note(err: &ViewError) -> String {
match err.code() {
"view.core_missing" => {
"未找到可用的冻结核心(MARQDO_BIN);当前为无语义标注的纯 Markdown 阅读模式。"
.to_string()
}
"view.analysis_failed" => "Core 检查失败;语义标注已撤销,正文仍可阅读。".to_string(),
other => format!("{other}:语义标注不可用,正文仍可阅读。"),
}
}
struct BindingSummary {
root_id: String,
identity_kind: String,
producer_version: String,
module_count: usize,
source_digest: String,
}
/// Structural binding checks that do not need the full typed projection yet
/// (the typed `SemanticProjection` replaces this in PR-02 without changing the
/// externally visible `verify` result).
fn validate_static_binding(
analysis: &serde_json::Value,
relative_path: &str,
source_bytes: &[u8],
) -> ViewResult<BindingSummary> {
let schema = analysis
.get("schema")
.and_then(|v| v.as_str())
.unwrap_or("");
if schema != "marqdo.analysis" {
return Err(ViewError::ProtocolIncompatible {
detail: format!("unexpected Analysis schema {schema:?}"),
});
fn diagnostic_to_view(
diagnostic: &RawCheckDiagnostic,
relative: &SafeRelativePath,
) -> CoreDiagnostic {
let belongs_to_entry = diagnostic
.module
.as_deref()
.map(|module| module.ends_with(relative.as_str()))
.unwrap_or(true);
CoreDiagnostic {
module: diagnostic.module.clone(),
relative_path: if belongs_to_entry {
Some(relative.as_str().to_string())
} else {
None
},
span: None,
line: diagnostic.line,
column: diagnostic.column,
severity: if diagnostic.severity.is_empty() {
"error".to_string()
} else {
diagnostic.severity.clone()
},
code: diagnostic.code.clone(),
message: diagnostic.message.clone(),
hints: diagnostic.hints.clone(),
}
match analysis.get("schema_version").and_then(|v| v.as_u64()) {
Some(2) => {}
other => {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"Analysis schema_version {other:?} is not supported (View implements v{})",
version::ANALYSIS_PROTOCOL
),
})
}
}
let producer = analysis
.get("producer")
.ok_or_else(|| ViewError::AnalysisFailed {
detail: "Analysis is missing producer".to_string(),
})?;
let producer_version = producer
.get("version")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let markdown_profile = producer
.get("markdown_profile")
.and_then(|v| v.as_str())
.unwrap_or("");
if markdown_profile != "marqdo.md.v1" {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"unexpected Markdown profile {markdown_profile:?}; this View targets marqdo.md.v1"
),
});
}
let project = analysis
.get("project")
.ok_or_else(|| ViewError::AnalysisFailed {
detail: "Analysis is missing project".to_string(),
})?;
let root_id = project
.get("root_id")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if root_id.is_empty() {
return Err(ViewError::AnalysisFailed {
detail: "Analysis project.root_id is empty".to_string(),
});
}
let identity_kind = project
.get("identity_kind")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let modules = analysis
.get("modules")
.and_then(|v| v.as_array())
.ok_or_else(|| ViewError::AnalysisFailed {
detail: "Analysis is missing modules[]".to_string(),
})?;
let expected_digest = sha256_hex(source_bytes);
let mut matches = 0usize;
for module in modules {
if module.get("relative_path").and_then(|v| v.as_str()) == Some(relative_path) {
matches += 1;
let digest = module
.get("source_digest")
.and_then(|v| v.as_str())
.unwrap_or("");
if digest != expected_digest {
return Err(ViewError::SourceMismatch {
expected: digest.to_string(),
actual: expected_digest,
});
}
}
}
if matches == 0 {
return Err(ViewError::AnalysisFailed {
detail: format!("Analysis has no module for {relative_path}"),
});
}
Ok(BindingSummary {
root_id,
identity_kind,
producer_version,
module_count: modules.len(),
source_digest: expected_digest,
})
}
+238
View File
@@ -0,0 +1,238 @@
//! The single embedded asset bundle.
//!
//! Live serving and static export both read these exact bytes (ADR-0002). Every
//! asset carries its SHA-256; browser URLs use a hash prefix so a changed asset
//! can never be confused with a cached older one.
use crate::source_map::sha256_hex;
use std::collections::HashMap;
use std::sync::OnceLock;
#[derive(Clone)]
pub struct Asset {
pub name: &'static str,
pub extension: &'static str,
pub mime: &'static str,
pub bytes: &'static [u8],
/// Lowercase hex SHA-256 of `bytes`.
pub sha256: String,
}
impl Asset {
/// Hashed file name, e.g. `reader.1a2b3c4d5e6f7788.css`.
pub fn hashed_name(&self) -> String {
format!("{}.{}.{}", self.name, &self.sha256[..16], self.extension)
}
pub fn data_uri(&self) -> String {
format!("data:{};base64,{}", self.mime, base64(self.bytes))
}
}
pub struct AssetBundle {
assets: Vec<Asset>,
by_hashed_name: HashMap<String, usize>,
/// CSS with the two image placeholders replaced by data URIs, so there is
/// still exactly one stylesheet and no extra network request.
css_with_images: String,
css_served_sha256: String,
}
impl AssetBundle {
fn new() -> Self {
let assets = vec![
asset(
"reader",
"css",
"text/css; charset=utf-8",
include_bytes!("../assets/reader.css"),
),
asset(
"reader",
"js",
"text/javascript; charset=utf-8",
include_bytes!("../assets/reader.js"),
),
asset(
"logo",
"svg",
"image/svg+xml",
include_bytes!("../assets/logo.svg"),
),
asset(
"blossom",
"webp",
"image/webp",
include_bytes!("../assets/blossom.webp"),
),
asset(
"feather",
"webp",
"image/webp",
include_bytes!("../assets/feather.webp"),
),
];
let mut by_hashed_name = HashMap::new();
for (index, asset) in assets.iter().enumerate() {
by_hashed_name.insert(asset.hashed_name(), index);
}
let css_text = std::str::from_utf8(assets[0].bytes).expect("reader.css is UTF-8");
let css_with_images = css_text
.replace("__BLOSSOM__", &assets[3].data_uri())
.replace("__FEATHER__", &assets[4].data_uri());
let css_served_sha256 = sha256_hex(css_with_images.as_bytes());
Self {
assets,
by_hashed_name,
css_with_images,
css_served_sha256,
}
}
pub fn get() -> &'static AssetBundle {
static BUNDLE: OnceLock<AssetBundle> = OnceLock::new();
BUNDLE.get_or_init(AssetBundle::new)
}
pub fn all(&self) -> &[Asset] {
&self.assets
}
pub fn css(&self) -> &Asset {
&self.assets[0]
}
pub fn js(&self) -> &Asset {
&self.assets[1]
}
pub fn logo(&self) -> &Asset {
&self.assets[2]
}
pub fn by_path(&self, hashed_name: &str) -> Option<&Asset> {
self.by_hashed_name
.get(hashed_name)
.map(|index| &self.assets[*index])
}
pub fn css_bytes(&self) -> &[u8] {
self.css_with_images.as_bytes()
}
/// SHA-256 of the served CSS (after image substitution).
pub fn css_served_sha256(&self) -> &str {
&self.css_served_sha256
}
pub fn hashed_css_name(&self) -> String {
format!("reader.{}.css", &self.css_served_sha256[..16])
}
pub fn hashed_js_name(&self) -> String {
self.js().hashed_name()
}
}
fn asset(
name: &'static str,
extension: &'static str,
mime: &'static str,
bytes: &'static [u8],
) -> Asset {
Asset {
name,
extension,
mime,
bytes,
sha256: sha256_hex(bytes),
}
}
/// Minimal standard base64 (RFC 4648) encoder for data URIs.
fn base64(bytes: &[u8]) -> String {
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let b0 = chunk[0] as u32;
let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
let triple = (b0 << 16) | (b1 << 8) | b2;
out.push(TABLE[(triple >> 18) as usize & 0x3f] as char);
out.push(TABLE[(triple >> 12) as usize & 0x3f] as char);
out.push(if chunk.len() > 1 {
TABLE[(triple >> 6) as usize & 0x3f] as char
} else {
'='
});
out.push(if chunk.len() > 2 {
TABLE[triple as usize & 0x3f] as char
} else {
'='
});
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bundle_digests_match_source_files() {
let bundle = AssetBundle::get();
assert_eq!(
bundle.css().sha256,
sha256_hex(include_bytes!("../assets/reader.css"))
);
assert_eq!(
bundle.js().sha256,
sha256_hex(include_bytes!("../assets/reader.js"))
);
assert_eq!(
bundle.logo().sha256,
sha256_hex(include_bytes!("../assets/logo.svg"))
);
assert_eq!(bundle.assets[3].sha256.len(), 64);
assert!(bundle.by_path(&bundle.logo().hashed_name()).is_some());
assert!(bundle.by_path("missing.css").is_none());
// Exactly one theme and one script entry.
let css_count = bundle
.all()
.iter()
.filter(|asset| asset.extension == "css")
.count();
let js_count = bundle
.all()
.iter()
.filter(|asset| asset.extension == "js")
.count();
assert_eq!(css_count, 1);
assert_eq!(js_count, 1);
}
#[test]
fn css_substitutes_images_and_keeps_one_asset() {
let bundle = AssetBundle::get();
let css = std::str::from_utf8(bundle.css_bytes()).unwrap();
assert!(!css.contains("__BLOSSOM__"));
assert!(!css.contains("__FEATHER__"));
assert!(css.contains("data:image/webp;base64,"));
assert!(bundle.hashed_css_name().starts_with("reader."));
assert_eq!(
bundle.hashed_css_name().len(),
"reader.".len() + 16 + ".css".len()
);
}
#[test]
fn base64_matches_known_vectors() {
assert_eq!(base64(b""), "");
assert_eq!(base64(b"f"), "Zg==");
assert_eq!(base64(b"fo"), "Zm8=");
assert_eq!(base64(b"foo"), "Zm9v");
assert_eq!(base64(b"foob"), "Zm9vYg==");
assert_eq!(base64(b"fooba"), "Zm9vYmE=");
assert_eq!(base64(b"foobar"), "Zm9vYmFy");
}
}
+74 -17
View File
@@ -106,6 +106,37 @@ pub struct CheckOutput {
pub stderr: String,
}
/// One compile diagnostic from `check --json`, normalized so no absolute
/// machine path can leak into pages, exports or logs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RawCheckDiagnostic {
#[serde(default)]
pub code: String,
#[serde(default)]
pub severity: String,
#[serde(default)]
pub message: String,
#[serde(default)]
pub line: Option<u64>,
#[serde(default)]
pub column: Option<u64>,
#[serde(default)]
pub module: Option<String>,
#[serde(default)]
pub hints: Vec<String>,
}
/// Result of one `check` invocation. A failed check is **not** an I/O error:
/// the prose stays readable and diagnostics must be shown (RFC §12.3).
#[derive(Debug)]
pub struct CheckResponse {
pub success: bool,
pub analysis: Option<CheckOutput>,
pub diagnostics: Vec<RawCheckDiagnostic>,
pub exit_code: i32,
pub stderr: String,
}
#[derive(Debug)]
pub struct RunOutput {
/// Exactly one JSON document emitted on stdout by the Core.
@@ -267,19 +298,20 @@ impl CoreClient {
Ok(version)
}
/// `check --emit`; on success returns the exact Analysis v2 bytes.
/// `check --json --emit`. On success the exact Analysis v2 bytes are
/// returned; on failure the structured diagnostics are returned without
/// any absolute path. Only spawn/timeout/IO failures are hard errors.
pub fn check(
&self,
project: &Project,
relative: &SafeRelativePath,
options: &CheckOptions,
) -> ViewResult<CheckOutput> {
) -> ViewResult<CheckResponse> {
let entry = project.absolute_for(relative)?;
let scratch = ScratchDir::create("check")?;
let emit = scratch.file("analysis.json");
let mut args = build_check_args(&entry);
// Scratch path is ours; the argument vector is explicit, no shell.
args.push(OsString::from("--json"));
args.push(OsString::from("--emit"));
args.push(emit.clone().into_os_string());
if options.refs {
@@ -291,13 +323,32 @@ impl CoreClient {
project.root(),
options.timeout.unwrap_or(DEFAULT_CHECK_TIMEOUT),
)?;
if output.exit_code != 0 {
return Err(ViewError::AnalysisFailed {
detail: format!(
"`marqdo check` failed with exit code {}: {}",
output.exit_code,
summarize_stderr(&output.stderr)
),
let check_json: Option<serde_json::Value> =
serde_json::from_slice(&output.stdout_bytes).ok();
let success = output.exit_code == 0
&& check_json
.as_ref()
.and_then(|json| json.get("success"))
.and_then(serde_json::Value::as_bool)
.unwrap_or(true);
let diagnostics = check_json
.as_ref()
.and_then(|json| json.get("diagnostics"))
.and_then(serde_json::Value::as_array)
.map(|items| {
items
.iter()
.filter_map(|item| serde_json::from_value(item.clone()).ok())
.collect::<Vec<RawCheckDiagnostic>>()
})
.unwrap_or_default();
if !success {
return Ok(CheckResponse {
success: false,
analysis: None,
diagnostics,
exit_code: output.exit_code,
stderr: output.stderr,
});
}
let analysis_bytes = std::fs::read(&emit).map_err(|err| ViewError::AnalysisFailed {
@@ -311,12 +362,18 @@ impl CoreClient {
detail: "`marqdo check` emitted an empty Analysis file".to_string(),
});
}
Ok(CheckOutput {
analysis_sha256: sha256_hex(&analysis_bytes),
analysis_digest: sha256_prefixed(&analysis_bytes),
analysis_bytes,
stdout: output.stdout,
stderr: output.stderr,
Ok(CheckResponse {
success: true,
analysis: Some(CheckOutput {
analysis_sha256: sha256_hex(&analysis_bytes),
analysis_digest: sha256_prefixed(&analysis_bytes),
analysis_bytes,
stdout: output.stdout,
stderr: output.stderr,
}),
diagnostics,
exit_code: 0,
stderr: String::new(),
})
}
+681
View File
@@ -0,0 +1,681 @@
//! Reader-oriented Markdown document model.
//!
//! Comrak (the same parser version as the frozen Markdown profile) parses the
//! source for **typography only**; the resulting tree is converted into a
//! View-owned `DocBlock`/`Inline` model that keeps exact UTF-8 byte spans.
//! No semantic decision (which node is executable) is taken here — that comes
//! exclusively from validated Analysis v2 (`semantic.rs`).
use crate::project::SafeRelativePath;
use crate::source_map::{sha256_hex, SourceIndex, SourceSpan};
use comrak::nodes::{ListType, NodeValue, Sourcepos, TableAlignment};
use comrak::{parse_document, Arena, Options};
/// Class of a table column.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TableAlign {
None,
Left,
Center,
Right,
}
#[derive(Debug, Clone)]
pub enum Inline {
Text {
span: SourceSpan,
literal: String,
},
Code {
span: SourceSpan,
literal: String,
ticks: usize,
},
Strong {
span: SourceSpan,
children: Vec<Inline>,
},
Emph {
span: SourceSpan,
children: Vec<Inline>,
},
Strikethrough {
span: SourceSpan,
children: Vec<Inline>,
},
Link {
span: SourceSpan,
url: String,
title: String,
children: Vec<Inline>,
},
Image {
span: SourceSpan,
url: String,
title: String,
alt: String,
},
Math {
span: SourceSpan,
literal: String,
display: bool,
},
HtmlInline {
span: SourceSpan,
raw: String,
},
SoftBreak {
span: SourceSpan,
},
LineBreak {
span: SourceSpan,
},
Other {
span: SourceSpan,
},
}
impl Inline {
pub fn span(&self) -> SourceSpan {
match self {
Inline::Text { span, .. }
| Inline::Code { span, .. }
| Inline::Strong { span, .. }
| Inline::Emph { span, .. }
| Inline::Strikethrough { span, .. }
| Inline::Link { span, .. }
| Inline::Image { span, .. }
| Inline::Math { span, .. }
| Inline::HtmlInline { span, .. }
| Inline::SoftBreak { span }
| Inline::LineBreak { span }
| Inline::Other { span } => *span,
}
}
pub fn plain_text(&self) -> String {
let mut out = String::new();
self.push_plain_text(&mut out);
out
}
fn push_plain_text(&self, out: &mut String) {
match self {
Inline::Text { literal, .. } | Inline::Code { literal, .. } => out.push_str(literal),
Inline::Strong { children, .. }
| Inline::Emph { children, .. }
| Inline::Strikethrough { children, .. }
| Inline::Link { children, .. } => {
for child in children {
child.push_plain_text(out);
}
}
Inline::Image { alt, .. } => out.push_str(alt),
Inline::Math { literal, .. } => out.push_str(literal),
Inline::SoftBreak { .. } | Inline::LineBreak { .. } => out.push(' '),
Inline::HtmlInline { .. } | Inline::Other { .. } => {}
}
}
}
#[derive(Debug, Clone)]
pub enum DocBlock {
Heading {
level: u8,
span: SourceSpan,
content: Vec<Inline>,
},
Paragraph {
span: SourceSpan,
content: Vec<Inline>,
},
List {
ordered: bool,
start: Option<usize>,
tight: bool,
span: SourceSpan,
items: Vec<DocBlock>,
},
ListItem {
span: SourceSpan,
task: Option<bool>,
children: Vec<DocBlock>,
},
BlockQuote {
span: SourceSpan,
children: Vec<DocBlock>,
},
CodeBlock {
span: SourceSpan,
info: String,
literal: String,
},
Table {
span: SourceSpan,
alignments: Vec<TableAlign>,
header: Vec<Vec<Inline>>,
rows: Vec<Vec<Vec<Inline>>>,
},
MathBlock {
span: SourceSpan,
literal: String,
},
ThematicBreak {
span: SourceSpan,
},
HtmlBlock {
span: SourceSpan,
literal: String,
},
Other {
span: SourceSpan,
},
}
impl DocBlock {
pub fn span(&self) -> SourceSpan {
match self {
DocBlock::Heading { span, .. }
| DocBlock::Paragraph { span, .. }
| DocBlock::List { span, .. }
| DocBlock::ListItem { span, .. }
| DocBlock::BlockQuote { span, .. }
| DocBlock::CodeBlock { span, .. }
| DocBlock::Table { span, .. }
| DocBlock::MathBlock { span, .. }
| DocBlock::ThematicBreak { span }
| DocBlock::HtmlBlock { span, .. }
| DocBlock::Other { span } => *span,
}
}
pub fn heading_text(&self) -> Option<String> {
match self {
DocBlock::Heading { content, .. } => {
Some(content.iter().map(Inline::plain_text).collect::<String>())
}
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct DocumentIdentity {
pub project_root_id: String,
pub module_id: String,
pub relative_path: String,
pub source_sha256: String,
}
impl DocumentIdentity {
pub fn placeholder(relative_path: &SafeRelativePath) -> Self {
Self {
project_root_id: String::new(),
module_id: String::new(),
relative_path: relative_path.as_str().to_string(),
source_sha256: String::new(),
}
}
}
#[derive(Debug, Clone)]
pub struct DocumentModel {
pub identity: DocumentIdentity,
pub source: String,
pub blocks: Vec<DocBlock>,
pub source_index: SourceIndex,
/// Number of leading BOM bytes stripped before parsing.
pub bom_len: usize,
}
impl DocumentModel {
/// Parse the exact source for display. Never decides executable semantics.
pub fn parse(source: String, identity: DocumentIdentity) -> Self {
let (bom_len, body) = strip_bom(&source);
let options = markdown_options();
let arena = Arena::new();
let root = parse_document(&arena, body, &options);
let lines = line_starts(body);
let body_len = body.len();
let blocks = root
.children()
.filter_map(|child| convert_block(child, &lines, bom_len, body_len))
.collect();
let source_index = SourceIndex::new(&source);
Self {
identity,
source,
blocks,
source_index,
bom_len,
}
}
/// First level-1 heading text, else the document stem.
pub fn title(&self) -> String {
for block in &self.blocks {
if let DocBlock::Heading {
level: 1, content, ..
} = block
{
let raw = content
.iter()
.map(Inline::plain_text)
.collect::<String>()
.trim()
.to_string();
// Display-only: strip a legal mode declaration prefix. Source
// view still shows the exact original text.
let text = raw
.strip_prefix("@exec ")
.or_else(|| raw.strip_prefix("@knowledge "))
.unwrap_or(&raw)
.trim()
.to_string();
if !text.is_empty() {
return text;
}
}
}
let name = self
.identity
.relative_path
.rsplit('/')
.next()
.unwrap_or(&self.identity.relative_path);
name.trim_end_matches(".mq.md").to_string()
}
/// Plain text of the whole document (search/alt helpers).
pub fn plain_text(&self) -> String {
let mut out = String::new();
collect_block_text(&self.blocks, &mut out);
out
}
pub fn source_digest(&self) -> String {
sha256_hex(self.source.as_bytes())
}
}
/// The frozen `marqdo.md.v1` parser options (same set as the Core profile).
pub fn markdown_options() -> Options<'static> {
let mut options = Options::default();
options.extension.table = true;
options.extension.strikethrough = true;
options.extension.tasklist = true;
options.extension.math_dollars = true;
options.extension.math_dollars_block = true;
options.extension.front_matter_delimiter = Some("---".to_string());
options
}
fn collect_block_text(blocks: &[DocBlock], out: &mut String) {
for block in blocks {
match block {
DocBlock::Heading { content, .. } | DocBlock::Paragraph { content, .. } => {
for inline in content {
out.push_str(&inline.plain_text());
}
out.push('\n');
}
DocBlock::List { items, .. } => collect_block_text(items, out),
DocBlock::ListItem { children, .. } => collect_block_text(children, out),
DocBlock::BlockQuote { children, .. } => collect_block_text(children, out),
DocBlock::CodeBlock { literal, .. } | DocBlock::MathBlock { literal, .. } => {
out.push_str(literal);
out.push('\n');
}
DocBlock::Table { header, rows, .. } => {
for cell in header {
for inline in cell {
out.push_str(&inline.plain_text());
}
}
for row in rows {
for cell in row {
for inline in cell {
out.push_str(&inline.plain_text());
}
}
}
out.push('\n');
}
DocBlock::ThematicBreak { .. }
| DocBlock::HtmlBlock { .. }
| DocBlock::Other { .. } => {}
}
}
}
fn strip_bom(source: &str) -> (usize, &str) {
match source.strip_prefix('\u{feff}') {
Some(rest) => (source.len() - rest.len(), rest),
None => (0, source),
}
}
fn line_starts(text: &str) -> Vec<usize> {
let bytes = text.as_bytes();
let mut starts = vec![0usize];
for (index, byte) in bytes.iter().enumerate() {
if *byte == b'\n' {
starts.push(index + 1);
}
}
starts
}
fn span_of(pos: Sourcepos, lines: &[usize], shift: usize, body_len: usize) -> SourceSpan {
fn offset_of(line: usize, column: usize, lines: &[usize], inclusive: bool) -> Option<usize> {
if line == 0 {
return None;
}
let line_start = *lines.get(line - 1)?;
Some(line_start + column.saturating_sub(1) + usize::from(inclusive))
}
let start = offset_of(pos.start.line, pos.start.column, lines, false)
.map(|offset| offset.min(body_len))
.unwrap_or(0);
let end = offset_of(pos.end.line, pos.end.column, lines, true)
.map(|offset| offset.min(body_len))
.unwrap_or(start)
.max(start);
SourceSpan::new((start + shift) as u64, (end + shift) as u64)
}
fn convert_block<'a>(
node: &'a comrak::nodes::AstNode<'a>,
lines: &[usize],
shift: usize,
body_len: usize,
) -> Option<DocBlock> {
let data = node.data();
let span = span_of(data.sourcepos, lines, shift, body_len);
let value = &data.value;
let block = match value {
NodeValue::Document => return None,
NodeValue::FrontMatter(_) => return None,
NodeValue::Paragraph => DocBlock::Paragraph {
span,
content: convert_inlines(node, lines, shift, body_len),
},
NodeValue::Heading(heading) => DocBlock::Heading {
level: heading.level,
span,
content: convert_inlines(node, lines, shift, body_len),
},
NodeValue::List(list) => {
let ordered = list.list_type == ListType::Ordered;
let items = node
.children()
.filter_map(|child| convert_block(child, lines, shift, body_len))
.collect();
DocBlock::List {
ordered,
start: if ordered { Some(list.start) } else { None },
tight: list.tight,
span,
items,
}
}
NodeValue::Item(_) => DocBlock::ListItem {
span,
task: None,
children: node
.children()
.filter_map(|child| convert_block(child, lines, shift, body_len))
.collect(),
},
NodeValue::TaskItem(item) => DocBlock::ListItem {
span,
task: Some(item.symbol.is_some()),
children: node
.children()
.filter_map(|child| convert_block(child, lines, shift, body_len))
.collect(),
},
NodeValue::BlockQuote | NodeValue::MultilineBlockQuote(_) => DocBlock::BlockQuote {
span,
children: node
.children()
.filter_map(|child| convert_block(child, lines, shift, body_len))
.collect(),
},
NodeValue::CodeBlock(code) => DocBlock::CodeBlock {
span,
info: code.info.clone(),
literal: code.literal.clone(),
},
NodeValue::HtmlBlock(html) => DocBlock::HtmlBlock {
span,
literal: html.literal.clone(),
},
NodeValue::ThematicBreak(_) => DocBlock::ThematicBreak { span },
NodeValue::MathBlock(math) => DocBlock::MathBlock {
span,
literal: math.literal.clone(),
},
NodeValue::Table(table) => {
let alignments = table
.alignments
.iter()
.map(|alignment| match alignment {
TableAlignment::None => TableAlign::None,
TableAlignment::Left => TableAlign::Left,
TableAlignment::Center => TableAlign::Center,
TableAlignment::Right => TableAlign::Right,
})
.collect();
let mut header = Vec::new();
let mut rows = Vec::new();
for row in node.children() {
let row_data = row.data();
let is_header = match &row_data.value {
NodeValue::TableRow(table_row) => table_row.header,
_ => false,
};
let mut cells = Vec::new();
for cell in row.children() {
cells.push(convert_inlines(cell, lines, shift, body_len));
}
if is_header {
header = cells;
} else {
rows.push(cells);
}
}
DocBlock::Table {
span,
alignments,
header,
rows,
}
}
_ => {
// Unknown block kinds are inert. If they carry block children, keep
// them so future additive nodes cannot hide readable content.
let children: Vec<DocBlock> = node
.children()
.filter_map(|child| convert_block(child, lines, shift, body_len))
.collect();
if children.is_empty() {
DocBlock::Other { span }
} else {
DocBlock::BlockQuote { span, children }
}
}
};
Some(block)
}
fn convert_inlines<'a>(
node: &'a comrak::nodes::AstNode<'a>,
lines: &[usize],
shift: usize,
body_len: usize,
) -> Vec<Inline> {
node.children()
.filter_map(|child| convert_inline(child, lines, shift, body_len))
.collect()
}
fn convert_inline<'a>(
node: &'a comrak::nodes::AstNode<'a>,
lines: &[usize],
shift: usize,
body_len: usize,
) -> Option<Inline> {
let data = node.data();
let span = span_of(data.sourcepos, lines, shift, body_len);
let inline = match &data.value {
NodeValue::Text(text) => Inline::Text {
span,
literal: text.to_string(),
},
NodeValue::Code(code) => Inline::Code {
span,
literal: code.literal.clone(),
ticks: code.num_backticks,
},
NodeValue::SoftBreak => Inline::SoftBreak { span },
NodeValue::LineBreak => Inline::LineBreak { span },
NodeValue::Strong(_) => Inline::Strong {
span,
children: convert_inlines(node, lines, shift, body_len),
},
NodeValue::Emph(_) => Inline::Emph {
span,
children: convert_inlines(node, lines, shift, body_len),
},
NodeValue::Strikethrough(_) => Inline::Strikethrough {
span,
children: convert_inlines(node, lines, shift, body_len),
},
NodeValue::Link(link) => Inline::Link {
span,
url: link.url.clone(),
title: link.title.clone(),
children: convert_inlines(node, lines, shift, body_len),
},
NodeValue::Image(link) => {
let children = convert_inlines(node, lines, shift, body_len);
Inline::Image {
span,
url: link.url.clone(),
title: link.title.clone(),
alt: children.iter().map(Inline::plain_text).collect(),
}
}
NodeValue::Math(math) => Inline::Math {
span,
literal: math.literal.clone(),
display: math.display_math,
},
NodeValue::HtmlInline(raw) => Inline::HtmlInline {
span,
raw: raw.clone(),
},
_ => Inline::Other { span },
};
Some(inline)
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(source: &str) -> DocumentModel {
DocumentModel::parse(
source.to_string(),
DocumentIdentity {
project_root_id: "root:t@0.1.0".into(),
module_id: "root:t@0.1.0::index.mq.md".into(),
relative_path: "index.mq.md".into(),
source_sha256: String::new(),
},
)
}
#[test]
fn parses_gfm_and_preserves_utf8_spans() {
let source =
"# @knowledge 标题\n\n| 名称 | 值 |\n| --- | --- |\n| 甲 | 1 |\n\n**加粗** 和 `代码`\n";
let document = parse(source);
// Display title drops a legal mode prefix; the source keeps it.
assert_eq!(document.title(), "标题");
assert!(document.source.starts_with("# @knowledge 标题"));
assert!(document
.blocks
.iter()
.any(|block| matches!(block, DocBlock::Table { .. })));
// Every block span slices valid UTF-8.
for block in &document.blocks {
let span = block.span();
assert!(
document
.source_index
.source_text(&document.source, span)
.is_some(),
"invalid span {span:?}"
);
}
}
#[test]
fn parses_math_and_code_as_inert_literals() {
let source = "行内 $a^2$ 与\n\n$$\n\\sum i\n$$\n\n```rust\nfn x() {}\n```\n";
let document = parse(source);
assert!(document.plain_text().contains("a^2"));
assert!(document.plain_text().contains("sum i"));
assert!(document.plain_text().contains("fn x()"));
}
#[test]
fn parses_lists_quotes_and_task_items() {
let source = "- [x] 完成\n- [ ] 未完成\n\n> 引用\n\n1. 一\n2. 二\n";
let document = parse(source);
let has_task = document.blocks.iter().any(|block| match block {
DocBlock::List { items, .. } => items.iter().any(|item| {
matches!(
item,
DocBlock::ListItem {
task: Some(true),
..
}
)
}),
_ => false,
});
assert!(has_task);
assert!(document
.blocks
.iter()
.any(|block| matches!(block, DocBlock::BlockQuote { .. })));
assert_eq!(document.blocks.len(), 3);
}
#[test]
fn heading_spans_are_exact() {
let source = "# 数学 #\n\n正文\n";
let document = parse(source);
match &document.blocks[0] {
DocBlock::Heading { span, .. } => {
let text = document
.source_index
.source_text(&document.source, *span)
.unwrap();
assert_eq!(text, "# 数学 #");
}
other => panic!("expected heading, got {other:?}"),
}
}
#[test]
fn front_matter_is_not_rendered_as_a_block() {
let source = "---\nimport:\n lib: \"./lib.mq.md\"\n---\n\n# hi\n";
let document = parse(source);
assert_eq!(document.blocks.len(), 1);
assert!(matches!(document.blocks[0], DocBlock::Heading { .. }));
}
}
+6
View File
@@ -7,10 +7,16 @@
//! this library so there is never a second renderer or a second parser.
pub mod app;
pub mod assets;
pub mod cli;
pub mod core_client;
pub mod document;
pub mod error;
pub mod presentation;
pub mod project;
pub mod render;
pub mod semantic;
pub mod server;
pub mod source_map;
pub mod version;
+275
View File
@@ -0,0 +1,275 @@
//! Presentation model: the one intermediate form between verified domain data
//! and the one `ReaderRenderer`.
//!
//! Nothing here spawns processes, builds HTML or parses Markdown semantics. It
//! only composes already-verified pieces (RFC-VIEW-0001 §6.3, §14.2).
use crate::document::{DocumentIdentity, DocumentModel};
use crate::project::{Project, SafeRelativePath, ViewConfig};
use crate::semantic::{CoreDiagnostic, SemanticProjection, ViewWarning};
/// Private View presentation-model version. Not a public protocol.
pub const PRESENTATION_VERSION: u32 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceStatus {
/// No usable `MARQDO_BIN`; prose only, semantics explicitly unverified.
CoreUnavailable,
/// `check` succeeded and Analysis v2 was verified.
StaticOk,
/// `check` failed; diagnostics shown, semantics revoked.
CoreError,
/// Analysis/source digest mismatch or an outdated artifact.
Stale,
/// Unknown Analysis/Tool major or product range.
ProtocolIncompatible,
/// Analysis `source_digest` differs from the current source bytes.
SourceMismatch,
}
impl SourceStatus {
pub fn data_value(&self) -> &'static str {
match self {
SourceStatus::CoreUnavailable => "core-unavailable",
SourceStatus::StaticOk => "static-ok",
SourceStatus::CoreError => "core-error",
SourceStatus::Stale => "stale",
SourceStatus::ProtocolIncompatible => "protocol-incompatible",
SourceStatus::SourceMismatch => "source-mismatch",
}
}
pub fn label(&self) -> &'static str {
match self {
SourceStatus::CoreUnavailable => "核心不可用 · 语义未验证",
SourceStatus::StaticOk => "静态检查已通过 · 未运行",
SourceStatus::CoreError => "Core 检查失败 · 语义不可用",
SourceStatus::Stale => "语义结果已过期",
SourceStatus::ProtocolIncompatible => "核心协议不兼容",
SourceStatus::SourceMismatch => "源码与分析不一致",
}
}
pub fn semantics_usable(&self) -> bool {
matches!(self, SourceStatus::StaticOk)
}
}
#[derive(Debug, Clone)]
pub struct Navigation {
pub site_title: String,
pub documents: Vec<SafeRelativePath>,
pub active: Option<SafeRelativePath>,
/// True only when an explicit `view.json` names this document as welcome.
pub welcome: bool,
}
impl Navigation {
pub fn from_project(project: &Project, config: &ViewConfig, active: &SafeRelativePath) -> Self {
let documents = project.list_documents().unwrap_or_default();
let welcome = config
.welcome
.as_ref()
.map(|welcome| welcome == active)
.unwrap_or(false);
Self {
site_title: config
.site_title
.clone()
.unwrap_or_else(|| "Marqdo".to_string()),
documents,
active: Some(active.clone()),
welcome,
}
}
}
#[derive(Debug, Clone)]
pub struct PresentationModel {
pub version: u32,
pub title: String,
pub document: DocumentModel,
pub semantic: Option<SemanticProjection>,
pub source_status: SourceStatus,
/// Human-readable reason for a degraded status (already normalized: no
/// absolute paths from the Core).
pub status_note: Option<String>,
pub diagnostics: Vec<CoreDiagnostic>,
pub warnings: Vec<ViewWarning>,
pub navigation: Navigation,
/// Function/section outline entries rendered from verified Analysis only.
pub outline: Vec<OutlineEntry>,
/// Frozen core product version used for this page, when one was consulted.
pub core_version: Option<String>,
}
#[derive(Debug, Clone)]
pub struct OutlineEntry {
pub label: String,
pub anchor: String,
pub detail: String,
pub kind: OutlineKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutlineKind {
Function,
Knowledge,
Section,
}
impl PresentationModel {
pub fn functions(&self) -> impl Iterator<Item = &OutlineEntry> {
self.outline
.iter()
.filter(|entry| entry.kind == OutlineKind::Function)
}
pub fn error_diagnostics(&self) -> impl Iterator<Item = &CoreDiagnostic> {
self.diagnostics
.iter()
.filter(|diagnostic| diagnostic.severity == "error")
}
}
/// Input to the one builder. `analysis` is already protocol/byte verified.
pub struct BuildInput<'a> {
pub document: DocumentModel,
pub analysis: Option<&'a crate::semantic::VerifiedAnalysis>,
pub status: SourceStatus,
pub status_note: Option<String>,
pub diagnostics: Vec<CoreDiagnostic>,
pub navigation: Navigation,
pub core_version: Option<String>,
}
pub fn build(input: BuildInput<'_>) -> PresentationModel {
let BuildInput {
mut document,
analysis,
status,
status_note,
mut diagnostics,
navigation,
core_version,
} = input;
let semantic = analysis.map(|verified| verified.projection.clone());
if let Some(projection) = &semantic {
document.identity = DocumentIdentity {
project_root_id: projection.project_root_id.clone(),
module_id: projection.module_id.clone(),
relative_path: projection.relative_path.clone(),
source_sha256: projection.source_digest.clone(),
};
for diagnostic in &projection.diagnostics {
if !diagnostics.iter().any(|existing| {
existing.code == diagnostic.code
&& existing.message == diagnostic.message
&& existing.span == diagnostic.span
}) {
diagnostics.push(diagnostic.clone());
}
}
}
let warnings = semantic
.as_ref()
.map(|projection| projection.warnings.clone())
.unwrap_or_default();
let outline = semantic.as_ref().map(build_outline).unwrap_or_default();
PresentationModel {
version: PRESENTATION_VERSION,
title: document.title(),
document,
semantic,
source_status: status,
status_note,
diagnostics,
warnings,
navigation,
outline,
core_version,
}
}
fn build_outline(projection: &SemanticProjection) -> Vec<OutlineEntry> {
let mut entries = Vec::new();
for function in &projection.functions {
let params = if function.signature.params.is_empty() {
String::new()
} else {
function
.signature
.params
.iter()
.map(|param| {
if param.ty.is_empty() {
param.name.clone()
} else {
format!("{}: {}", param.name, param.ty)
}
})
.collect::<Vec<_>>()
.join(", ")
};
let detail = if params.is_empty() {
"无参数".to_string()
} else {
format!("params({params})")
};
entries.push(OutlineEntry {
label: function.local_name.clone(),
anchor: anchor_for_span(function.heading_span.start, function.heading_span.end),
detail,
kind: OutlineKind::Function,
});
}
for unit in &projection.units {
let kind = match unit.kind {
crate::semantic::UnitKind::Knowledge if unit.level >= 2 => OutlineKind::Knowledge,
crate::semantic::UnitKind::Section => OutlineKind::Section,
_ => continue,
};
if unit.name.is_empty() {
continue;
}
entries.push(OutlineEntry {
label: unit.name.clone(),
anchor: anchor_for_span(unit.span.start, unit.span.end),
detail: if unit.level == 2 {
"知识单元".to_string()
} else {
"章节".to_string()
},
kind,
});
}
entries
}
/// Deterministic heading anchor derived from the heading byte span. It never
/// depends on rendered text, so duplicate headings cannot collide.
pub fn anchor_for_span(start: u64, end: u64) -> String {
format!("mq-h-{start:x}-{end:x}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn status_values_are_stable() {
assert_eq!(SourceStatus::StaticOk.data_value(), "static-ok");
assert_eq!(SourceStatus::CoreError.data_value(), "core-error");
assert!(SourceStatus::StaticOk.semantics_usable());
assert!(!SourceStatus::CoreUnavailable.semantics_usable());
assert!(!SourceStatus::SourceMismatch.semantics_usable());
}
#[test]
fn heading_anchors_are_deterministic_and_collision_free() {
assert_eq!(anchor_for_span(1, 2), "mq-h-1-2");
assert_ne!(anchor_for_span(1, 2), anchor_for_span(1, 3));
}
}
+80
View File
@@ -306,6 +306,86 @@ impl Project {
}
}
/// Optional View-only site configuration (`view.json`).
///
/// This is **not** a Marqdo language protocol and cannot grant execution: only
/// the fields below are read, and the welcome path is still subject to the same
/// project-root boundary (RFC-VIEW-0001 §9.4).
#[derive(Debug, Clone, Default)]
pub struct ViewConfig {
pub welcome: Option<SafeRelativePath>,
pub site_title: Option<String>,
pub theme: Option<String>,
}
impl ViewConfig {
pub fn load(root: &Path) -> ViewResult<Self> {
let path = root.join("view.json");
let metadata = match std::fs::metadata(&path) {
Ok(metadata) => metadata,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()),
Err(err) => return Err(ViewError::io(&format!("stat {}", path.display()), err)),
};
if !metadata.is_file() || metadata.len() > 64 * 1024 {
return Err(ViewError::PathForbidden {
detail: "view.json must be a regular file under 64 KiB".to_string(),
});
}
let bytes = std::fs::read(&path)
.map_err(|err| ViewError::io(&format!("read {}", path.display()), err))?;
#[derive(serde::Deserialize)]
struct RawConfig {
#[serde(default)]
schema: String,
#[serde(default)]
schema_version: u32,
#[serde(default)]
welcome: Option<String>,
#[serde(default)]
site_title: Option<String>,
#[serde(default)]
theme: Option<String>,
}
let raw: RawConfig = serde_json::from_slice(&bytes).map_err(|err| ViewError::Io {
detail: format!("view.json is not valid JSON: {err}"),
})?;
if raw.schema != "marqdo.view-config" || raw.schema_version != 1 {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"unsupported view.json schema {:?} version {}; expected marqdo.view-config v1",
raw.schema, raw.schema_version
),
});
}
let welcome = match raw.welcome {
Some(path) => Some(SafeRelativePath::parse(&path)?),
None => None,
};
if let Some(welcome) = &welcome {
if !root.join(welcome.to_path()).is_file() {
return Err(ViewError::PathForbidden {
detail: format!(
"view.json welcome file {welcome} does not exist under the project root"
),
});
}
}
let site_title = raw
.site_title
.map(|title| title.trim().to_string())
.filter(|title| !title.is_empty() && title.chars().count() <= 80);
let theme = raw
.theme
.map(|theme| theme.trim().to_string())
.filter(|theme| theme == "botanical" || theme == "paper");
Ok(Self {
welcome,
site_title,
theme,
})
}
}
/// Discover the project root for a source file: nearest ancestor with
/// `marqdo.yaml`, else the file's directory. The file itself is canonical.
pub fn discover_project_root(file: &Path) -> PathBuf {
+1162
View File
File diff suppressed because it is too large. Load diff
+941
View File
@@ -0,0 +1,941 @@
//! Analysis v2 validation and static semantic projection.
//!
//! This module is the only consumer of the public Analysis JSON. It verifies
//! protocol identity first, then projects functions/units/statements/diagnostics
//! into View-owned types with **validated** source spans. A span that is out of
//! range or not on a UTF-8 boundary is dropped with an explicit View warning
//! instead of being pointed at nearby text (RFC-VIEW-0001 §4.3, §8.2).
use crate::error::{ViewError, ViewResult};
use crate::source_map::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan};
use crate::version;
use serde::Deserialize;
use serde_json::Value;
/// Stable DOM identity for one source-bound annotation, local to this document
/// and run. It is not a cross-edit identity.
pub fn source_id(module_id: &str, span: SourceSpan, kind: &str) -> String {
let material = format!("{module_id}\0{}:{}:{}", span.start, span.end, kind);
sha256_hex(material.as_bytes())[..16].to_string()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnitKind {
Root,
Namespace,
Function,
Knowledge,
Section,
Other,
}
#[derive(Debug, Clone)]
pub struct SemanticUnit {
pub id: String,
pub name: String,
pub level: u8,
pub kind: UnitKind,
pub function: Option<String>,
pub span: SourceSpan,
}
#[derive(Debug, Clone)]
pub struct FunctionParam {
pub name: String,
pub ty: String,
pub required: bool,
pub default: Option<String>,
pub span: Option<SourceSpan>,
}
#[derive(Debug, Clone)]
pub struct FunctionSignature {
pub kind: String,
pub params: Vec<FunctionParam>,
}
#[derive(Debug, Clone)]
pub struct SemanticFunction {
pub id: String,
pub unit_id: String,
pub local_name: String,
pub namespace: Option<String>,
pub span: SourceSpan,
pub heading_span: SourceSpan,
pub signature: FunctionSignature,
pub effects: Vec<String>,
pub statements: Vec<SemanticStatement>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatementKind {
Assign,
Expression,
Branch,
Loop,
Return,
Other,
}
impl StatementKind {
pub fn label(&self) -> &'static str {
match self {
StatementKind::Assign => "赋值",
StatementKind::Expression => "表达式",
StatementKind::Branch => "条件分支",
StatementKind::Loop => "循环",
StatementKind::Return => "返回",
StatementKind::Other => "语句",
}
}
pub fn data_value(&self) -> &'static str {
match self {
StatementKind::Assign => "assign",
StatementKind::Expression => "expression",
StatementKind::Branch => "branch",
StatementKind::Loop => "loop",
StatementKind::Return => "return",
StatementKind::Other => "other",
}
}
}
#[derive(Debug, Clone)]
pub struct SemanticStatement {
pub kind: StatementKind,
/// Header span for control flow, payload span for simple statements.
pub span: SourceSpan,
/// For `if` arms and `while` conditions: the condition text span as the
/// compiler recorded it.
pub condition_span: Option<SourceSpan>,
pub arms: Vec<SemanticArm>,
pub body: Vec<SemanticStatement>,
/// Target name for assignments (local name or `index` form), for static
/// outline display only. Never a runtime value.
pub target: Option<String>,
}
#[derive(Debug, Clone)]
pub struct SemanticArm {
pub span: Option<SourceSpan>,
pub condition_span: Option<SourceSpan>,
pub body: Vec<SemanticStatement>,
}
impl SemanticFunction {
/// Depth-first statement walk in source order.
pub fn flattened_statements(&self) -> Vec<&SemanticStatement> {
let mut out = Vec::new();
for statement in &self.statements {
collect_statements(statement, &mut out);
}
out
}
}
fn collect_statements<'a>(statement: &'a SemanticStatement, out: &mut Vec<&'a SemanticStatement>) {
out.push(statement);
for arm in &statement.arms {
for child in &arm.body {
collect_statements(child, out);
}
}
for child in &statement.body {
collect_statements(child, out);
}
}
#[derive(Debug, Clone)]
pub struct StaticResource {
pub id: String,
pub kind: String,
pub span: SourceSpan,
pub content_digest: String,
pub language: Option<String>,
pub display: bool,
}
#[derive(Debug, Clone)]
pub struct StaticImport {
pub alias: String,
pub target: String,
pub resolved: Option<String>,
pub span: SourceSpan,
}
#[derive(Debug, Clone)]
pub struct StaticReference {
pub url: String,
pub span: SourceSpan,
pub state: String,
pub target_module: Option<String>,
pub target_unit: Option<String>,
}
#[derive(Debug, Clone)]
pub struct StaticCall {
pub state: String,
pub target: Option<String>,
pub function: Option<String>,
pub span: SourceSpan,
}
#[derive(Debug, Clone)]
pub struct CoreDiagnostic {
pub module: Option<String>,
pub relative_path: Option<String>,
pub span: Option<SourceSpan>,
pub line: Option<u64>,
pub column: Option<u64>,
pub severity: String,
pub code: String,
pub message: String,
pub hints: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct ViewWarning {
pub code: String,
pub message: String,
pub span: Option<SourceSpan>,
}
#[derive(Debug, Clone)]
pub struct ModuleSummary {
pub id: String,
pub package_instance_id: String,
pub relative_path: String,
pub source_digest: String,
}
#[derive(Debug, Clone)]
pub struct SemanticProjection {
pub analysis_sha256: String,
pub analysis_digest: String,
pub producer_version: String,
pub markdown_profile: String,
pub project_root_id: String,
pub identity_kind: String,
pub lock_digest: String,
pub stdlib_version: Option<String>,
pub module_id: String,
pub package_instance_id: String,
pub relative_path: String,
pub source_digest: String,
pub units: Vec<SemanticUnit>,
pub functions: Vec<SemanticFunction>,
pub resources: Vec<StaticResource>,
pub imports: Vec<StaticImport>,
pub references: Vec<StaticReference>,
pub calls: Vec<StaticCall>,
pub diagnostics: Vec<CoreDiagnostic>,
pub warnings: Vec<ViewWarning>,
pub modules: Vec<ModuleSummary>,
}
#[derive(Debug)]
pub struct VerifiedAnalysis {
pub projection: SemanticProjection,
}
impl SemanticProjection {
pub fn unit_for_heading(&self, span: SourceSpan, level: u8) -> Option<&SemanticUnit> {
self.units
.iter()
.filter(|unit| unit.level == level && unit.span.contains(span))
.min_by_key(|unit| unit.span.len())
}
pub fn function_by_heading(&self, span: SourceSpan) -> Option<&SemanticFunction> {
self.functions
.iter()
.find(|function| function.heading_span == span)
.or_else(|| {
self.functions
.iter()
.find(|function| function.span.contains(span))
})
}
/// All statements of all functions, flattened in deterministic order.
pub fn all_statements(&self) -> Vec<(&SemanticFunction, &SemanticStatement)> {
let mut out = Vec::new();
for function in &self.functions {
for statement in function.flattened_statements() {
out.push((function, statement));
}
}
out
}
/// The innermost statement whose span is contained in `inline_span`.
pub fn statement_for_inline(
&self,
inline_span: SourceSpan,
) -> Option<(&SemanticFunction, &SemanticStatement)> {
self.all_statements()
.into_iter()
.filter(|(_, statement)| {
statement.span.start >= inline_span.start
&& statement.span.end <= inline_span.end
&& !statement.span.is_empty()
})
.max_by_key(|(_, statement)| statement.span.start)
}
pub fn resource_for_span(&self, span: SourceSpan) -> Option<&StaticResource> {
self.resources
.iter()
.find(|resource| resource.span == span || resource.span.contains(span))
}
pub fn reference_for_span(&self, span: SourceSpan) -> Option<&StaticReference> {
self.references
.iter()
.find(|reference| reference.span == span || reference.span.contains(span))
}
}
// ---------------------------------------------------------------------------
// Raw protocol types (additive fields are tolerated and ignored).
// ---------------------------------------------------------------------------
#[derive(Debug, Deserialize)]
struct RawAnalysis {
schema: String,
schema_version: u32,
producer: RawProducer,
project: RawProject,
modules: Vec<RawModule>,
#[serde(default)]
diagnostics: Vec<RawDiagnostic>,
}
#[derive(Debug, Deserialize)]
struct RawProducer {
#[serde(default)]
name: String,
#[serde(default)]
version: String,
#[serde(default)]
markdown_profile: String,
}
#[derive(Debug, Deserialize)]
struct RawProject {
#[serde(default)]
root_id: String,
#[serde(default)]
identity_kind: String,
#[serde(default)]
lock_digest: String,
#[serde(default)]
stdlib: Option<RawStdlib>,
}
#[derive(Debug, Deserialize)]
struct RawStdlib {
#[serde(default)]
version: String,
}
#[derive(Debug, Deserialize)]
struct RawModule {
#[serde(default)]
id: String,
#[serde(default)]
package_instance_id: String,
#[serde(default)]
relative_path: String,
#[serde(default)]
source_digest: String,
#[serde(default)]
units: Vec<RawUnit>,
#[serde(default)]
functions: Vec<RawFunction>,
#[serde(default)]
imports: Vec<RawImport>,
#[serde(default)]
references: Vec<RawReference>,
#[serde(default)]
calls: Vec<RawCall>,
#[serde(default)]
resources: Vec<RawResource>,
}
#[derive(Debug, Deserialize)]
struct RawUnit {
#[serde(default)]
id: String,
#[serde(default)]
name: String,
#[serde(default)]
level: u8,
#[serde(default)]
kind: String,
#[serde(default)]
function: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawFunction {
#[serde(default)]
id: String,
#[serde(default)]
unit_id: String,
#[serde(default)]
local_name: String,
#[serde(default)]
namespace: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
heading_span: Option<SourceSpan>,
#[serde(default)]
signature: Option<RawSignature>,
#[serde(default)]
effects: Vec<String>,
#[serde(default)]
body: Vec<RawStatement>,
}
#[derive(Debug, Deserialize)]
struct RawSignature {
#[serde(default)]
kind: String,
#[serde(default)]
params: Vec<RawParam>,
}
#[derive(Debug, Deserialize)]
struct RawParam {
#[serde(default)]
name: String,
#[serde(default, rename = "type")]
ty: Option<String>,
#[serde(default)]
required: bool,
#[serde(default)]
default: Option<Value>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawStatement {
#[serde(default)]
kind: String,
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
condition_span: Option<SourceSpan>,
#[serde(default)]
arms: Vec<RawArm>,
#[serde(default)]
body: Vec<RawStatement>,
#[serde(default)]
target: Option<Value>,
}
#[derive(Debug, Deserialize)]
struct RawArm {
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
condition_span: Option<SourceSpan>,
#[serde(default)]
body: Vec<RawStatement>,
}
#[derive(Debug, Deserialize)]
struct RawResource {
#[serde(default)]
id: String,
#[serde(default)]
kind: String,
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
content_digest: String,
#[serde(default)]
language: Option<String>,
#[serde(default)]
display: bool,
}
#[derive(Debug, Deserialize)]
struct RawImport {
#[serde(default)]
alias: String,
#[serde(default)]
target: String,
#[serde(default)]
resolved: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawReference {
#[serde(default)]
url: String,
#[serde(default)]
state: String,
#[serde(default)]
target_module: Option<String>,
#[serde(default)]
target_unit: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawCall {
#[serde(default)]
state: String,
#[serde(default)]
target: Option<String>,
#[serde(default)]
function: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawDiagnostic {
#[serde(default)]
module: Option<String>,
#[serde(default)]
relative_path: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
line: Option<u64>,
#[serde(default)]
column: Option<u64>,
#[serde(default)]
severity: String,
#[serde(default)]
code: String,
#[serde(default)]
message: String,
#[serde(default)]
hints: Vec<String>,
}
// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------
/// Verify Analysis bytes against the exact source and project the static facts.
///
/// Rejects protocol incompatibility and source-digest mismatch as errors; drops
/// individual invalid spans as warnings so the prose stays readable.
pub fn verify_analysis(
analysis_bytes: &[u8],
source: &str,
source_index: &SourceIndex,
expected_relative_path: &str,
) -> ViewResult<VerifiedAnalysis> {
let raw: RawAnalysis =
serde_json::from_slice(analysis_bytes).map_err(|err| ViewError::AnalysisFailed {
detail: format!("Analysis v2 is not valid JSON: {err}"),
})?;
if raw.schema != "marqdo.analysis" {
return Err(ViewError::ProtocolIncompatible {
detail: format!("unexpected Analysis schema {:?}", raw.schema),
});
}
if raw.schema_version != version::ANALYSIS_PROTOCOL {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"Analysis schema_version {} is not supported (View implements v{})",
raw.schema_version,
version::ANALYSIS_PROTOCOL
),
});
}
if raw.producer.name != "marqdo" {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"Analysis producer.name {:?} is not `marqdo`",
raw.producer.name
),
});
}
if raw.producer.markdown_profile != "marqdo.md.v1" {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"unexpected Markdown profile {:?}; this View targets marqdo.md.v1",
raw.producer.markdown_profile
),
});
}
if raw.project.root_id.is_empty() {
return Err(ViewError::AnalysisFailed {
detail: "Analysis project.root_id is empty".to_string(),
});
}
let actual_digest = sha256_hex(source.as_bytes());
let module = raw
.modules
.iter()
.find(|module| module.relative_path == expected_relative_path)
.ok_or_else(|| ViewError::AnalysisFailed {
detail: format!("Analysis has no module for {expected_relative_path}"),
})?;
if module.source_digest != actual_digest {
return Err(ViewError::SourceMismatch {
expected: module.source_digest.clone(),
actual: actual_digest,
});
}
let mut warnings = Vec::new();
let mut valid_span = |span: Option<SourceSpan>, what: &str| -> Option<SourceSpan> {
let span = span?;
if source_index.validate_span_bytes(source.as_bytes(), span) {
Some(span)
} else {
warnings.push(ViewWarning {
code: "view.source_span_invalid".to_string(),
message: format!("{what} 的字节区间超出源码或不在 UTF-8 边界,已跳过该标注"),
span: Some(span),
});
None
}
};
let units: Vec<SemanticUnit> = module
.units
.iter()
.filter_map(|unit| {
let span = valid_span(unit.span, "语义单元")?;
Some(SemanticUnit {
id: unit.id.clone(),
name: unit.name.clone(),
level: unit.level,
kind: match unit.kind.as_str() {
"root" => UnitKind::Root,
"namespace" => UnitKind::Namespace,
"function" => UnitKind::Function,
"knowledge" => UnitKind::Knowledge,
"section" => UnitKind::Section,
_ => UnitKind::Other,
},
function: unit.function.clone(),
span,
})
})
.collect();
let functions: Vec<SemanticFunction> = module
.functions
.iter()
.filter_map(|function| {
let span = valid_span(function.span, "函数范围")?;
let heading_span = valid_span(function.heading_span, "函数标题")?;
let statements = function
.body
.iter()
.filter_map(|statement| convert_statement(statement, &mut valid_span))
.collect();
Some(SemanticFunction {
id: function.id.clone(),
unit_id: function.unit_id.clone(),
local_name: function.local_name.clone(),
namespace: function.namespace.clone(),
span,
heading_span,
signature: FunctionSignature {
kind: function
.signature
.as_ref()
.map(|signature| signature.kind.clone())
.unwrap_or_default(),
params: function
.signature
.as_ref()
.map(|signature| {
signature
.params
.iter()
.map(|param| FunctionParam {
name: param.name.clone(),
ty: param.ty.clone().unwrap_or_default(),
required: param.required,
default: param.default.as_ref().map(compact_value),
span: param.span.filter(|span| {
source_index.validate_span_bytes(source.as_bytes(), *span)
}),
})
.collect()
})
.unwrap_or_default(),
},
effects: function.effects.clone(),
statements,
})
})
.collect();
let resources: Vec<StaticResource> = module
.resources
.iter()
.filter(|resource| matches!(resource.kind.as_str(), "formula" | "code"))
.filter_map(|resource| {
let span = valid_span(resource.span, "资源")?;
Some(StaticResource {
id: resource.id.clone(),
kind: resource.kind.clone(),
span,
content_digest: resource.content_digest.clone(),
language: resource.language.clone(),
display: resource.display,
})
})
.collect();
let imports: Vec<StaticImport> = module
.imports
.iter()
.filter_map(|import| {
Some(StaticImport {
alias: import.alias.clone(),
target: import.target.clone(),
resolved: import.resolved.clone(),
span: valid_span(import.span, "导入声明")?,
})
})
.collect();
let references: Vec<StaticReference> = module
.references
.iter()
.filter_map(|reference| {
Some(StaticReference {
url: reference.url.clone(),
state: reference.state.clone(),
target_module: reference.target_module.clone(),
target_unit: reference.target_unit.clone(),
span: valid_span(reference.span, "Markdown 引用")?,
})
})
.collect();
let calls: Vec<StaticCall> = module
.calls
.iter()
.filter_map(|call| {
Some(StaticCall {
state: call.state.clone(),
target: call.target.clone(),
function: call.function.clone(),
span: valid_span(call.span, "调用点")?,
})
})
.collect();
let diagnostics: Vec<CoreDiagnostic> = raw
.diagnostics
.iter()
.map(|diagnostic| {
let span = diagnostic
.span
.filter(|span| source_index.validate_span_bytes(source.as_bytes(), *span));
CoreDiagnostic {
module: diagnostic.module.clone(),
relative_path: diagnostic.relative_path.clone(),
span,
line: diagnostic.line,
column: diagnostic.column,
severity: if diagnostic.severity.is_empty() {
"error".to_string()
} else {
diagnostic.severity.clone()
},
code: diagnostic.code.clone(),
message: diagnostic.message.clone(),
hints: diagnostic.hints.clone(),
}
})
.collect();
let modules = raw
.modules
.iter()
.map(|module| ModuleSummary {
id: module.id.clone(),
package_instance_id: module.package_instance_id.clone(),
relative_path: module.relative_path.clone(),
source_digest: module.source_digest.clone(),
})
.collect();
Ok(VerifiedAnalysis {
projection: SemanticProjection {
analysis_sha256: sha256_hex(analysis_bytes),
analysis_digest: sha256_prefixed(analysis_bytes),
producer_version: raw.producer.version.clone(),
markdown_profile: raw.producer.markdown_profile.clone(),
project_root_id: raw.project.root_id.clone(),
identity_kind: raw.project.identity_kind.clone(),
lock_digest: raw.project.lock_digest.clone(),
stdlib_version: raw.project.stdlib.as_ref().map(|s| s.version.clone()),
module_id: module.id.clone(),
package_instance_id: module.package_instance_id.clone(),
relative_path: module.relative_path.clone(),
source_digest: module.source_digest.clone(),
units,
functions,
resources,
imports,
references,
calls,
diagnostics,
warnings,
modules,
},
})
}
fn convert_statement(
raw: &RawStatement,
valid_span: &mut impl FnMut(Option<SourceSpan>, &str) -> Option<SourceSpan>,
) -> Option<SemanticStatement> {
let span = valid_span(raw.span, "语句")?;
let kind = match raw.kind.as_str() {
"assign" => StatementKind::Assign,
"expression" => StatementKind::Expression,
"branch" => StatementKind::Branch,
"loop" => StatementKind::Loop,
"return" => StatementKind::Return,
_ => StatementKind::Other,
};
let body = raw
.body
.iter()
.filter_map(|child| convert_statement(child, valid_span))
.collect();
let arms = raw
.arms
.iter()
.map(|arm| SemanticArm {
span: valid_span(arm.span, "分支臂"),
condition_span: valid_span(arm.condition_span, "分支条件"),
body: arm
.body
.iter()
.filter_map(|child| convert_statement(child, valid_span))
.collect(),
})
.collect();
Some(SemanticStatement {
kind,
span,
condition_span: valid_span(raw.condition_span, "控制条件"),
arms,
body,
target: raw.target.as_ref().and_then(assignment_target_label),
})
}
fn assignment_target_label(target: &Value) -> Option<String> {
match target {
Value::String(name) => Some(name.clone()),
Value::Object(map) => {
if map.get("kind").and_then(Value::as_str) == Some("index") {
Some("索引赋值".to_string())
} else {
None
}
}
_ => None,
}
}
fn compact_value(value: &Value) -> String {
match value {
Value::String(text) => text.clone(),
other => {
let text = other.to_string();
if text.chars().count() > 40 {
format!("{}…", text.chars().take(40).collect::<String>())
} else {
text
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn analysis(schema_version: u32, digest: &str) -> Vec<u8> {
serde_json::json!({
"schema": "marqdo.analysis",
"schema_version": schema_version,
"producer": {"name": "marqdo", "version": "3.0.0-beta.1", "markdown_profile": "marqdo.md.v1"},
"project": {"root_id": "root:t@0.1.0", "identity_kind": "manifest", "lock_digest": "", "stdlib": null},
"modules": [{
"id": "root:t@0.1.0::index.mq.md",
"package_instance_id": "root:t@0.1.0",
"relative_path": "index.mq.md",
"source_digest": digest,
"units": [],
"functions": [],
"imports": [],
"references": [],
"calls": [],
"resources": []
}],
"diagnostics": []
})
.to_string()
.into_bytes()
}
#[test]
fn rejects_unknown_schema_major_and_profile() {
let source = "# hi\n";
let index = SourceIndex::new(source);
let digest = sha256_hex(source.as_bytes());
let err =
verify_analysis(&analysis(3, &digest), source, &index, "index.mq.md").unwrap_err();
assert_eq!(err.code(), "view.protocol_incompatible");
}
#[test]
fn rejects_digest_mismatch() {
let source = "# hi\n";
let index = SourceIndex::new(source);
let err = verify_analysis(&analysis(2, &"0".repeat(64)), source, &index, "index.mq.md")
.unwrap_err();
assert_eq!(err.code(), "view.source_mismatch");
}
#[test]
fn projects_valid_analysis() {
let source = "# hi\n";
let index = SourceIndex::new(source);
let digest = sha256_hex(source.as_bytes());
let verified =
verify_analysis(&analysis(2, &digest), source, &index, "index.mq.md").unwrap();
assert_eq!(verified.projection.project_root_id, "root:t@0.1.0");
assert_eq!(verified.projection.relative_path, "index.mq.md");
}
#[test]
fn source_id_is_deterministic_and_bounded() {
let span = SourceSpan::new(1, 5);
let id = source_id("mod", span, "statement");
assert_eq!(id.len(), 16);
assert_eq!(id, source_id("mod", span, "statement"));
assert_ne!(id, source_id("mod", span, "resource"));
}
}
+663
View File
@@ -0,0 +1,663 @@
//! Localhost Live reader.
//!
//! Minimal, loopback-only surface (RFC-VIEW-0001 §11.1). Only read APIs are
//! exposed until the explicit-run flow lands; every response carries a strict
//! CSP and the Host header is validated to blunt DNS-rebinding.
use crate::app::AppContext;
use crate::assets::AssetBundle;
use crate::cli::RuntimeOpts;
use crate::error::{ViewError, ViewResult};
use crate::presentation::PresentationModel;
use crate::project::SafeRelativePath;
use crate::render::{ReaderRenderer, RenderContext};
use crate::source_map::sha256_hex;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
const MAX_URL_BYTES: usize = 2048;
const MAX_QUERY_BYTES: usize = 4096;
pub fn serve(ctx: AppContext, opts: &RuntimeOpts) -> ViewResult<i32> {
let address = format!("{}:{}", opts.host, opts.port);
let server = Server::http(&address).map_err(|err| ViewError::Io {
detail: format!("listen on {address}: {err}"),
})?;
let bound = server.server_addr().to_ip().ok_or_else(|| ViewError::Io {
detail: "server address is not an IP socket".to_string(),
})?;
let port = bound.port();
let display_host = match opts.host.as_str() {
"localhost" => "localhost".to_string(),
"::1" | "[::1]" => "[::1]".to_string(),
_ => "127.0.0.1".to_string(),
};
let url = format!("http://{display_host}:{port}/");
eprintln!("marqdo view: {url}");
eprintln!("root: {}", ctx.project().root().display());
eprintln!(
"{} .mq.md document(s). Ctrl+C to stop.",
ctx.project()
.list_documents()
.map(|docs| docs.len())
.unwrap_or(0)
);
if ctx.core_version().is_some() {
eprintln!(
"core: marqdo {} (Analysis v2, Trace v2)",
ctx.core_version().unwrap_or_default()
);
} else if let Some(note) = ctx.core_note() {
eprintln!("core: unavailable ({note})");
}
if !opts.no_open {
open_browser(&url);
}
let state = Arc::new(ServerState {
ctx,
csrf_token: random_token(),
renderer: ReaderRenderer::new(),
cache: Mutex::new(HashMap::new()),
allowed_hosts: allowed_hosts(port),
});
loop {
let request = match server.recv() {
Ok(request) => request,
Err(err) => {
eprintln!("view: accept failed: {err}");
continue;
}
};
let state = Arc::clone(&state);
std::thread::spawn(move || {
if let Err(err) = handle(&state, request) {
eprintln!("view request error: {err}");
}
});
}
}
struct ServerState {
ctx: AppContext,
csrf_token: String,
renderer: ReaderRenderer,
cache: Mutex<HashMap<String, CacheEntry>>,
allowed_hosts: Vec<String>,
}
struct CacheEntry {
source_digest: String,
model: PresentationModel,
}
impl ServerState {
/// Load one document, reusing a cached model only while the exact source
/// bytes are unchanged (no path-only cache identity, RFC §6.5).
fn load(&self, relative: &SafeRelativePath) -> ViewResult<PresentationModel> {
let digest = self.ctx.project().source_digest(relative)?;
if let Ok(cache) = self.cache.lock() {
if let Some(entry) = cache.get(relative.as_str()) {
if entry.source_digest == digest {
return Ok(entry.model.clone());
}
}
}
let model = self.ctx.load(relative)?;
if let Ok(mut cache) = self.cache.lock() {
if cache.len() < 64 {
cache.insert(
relative.as_str().to_string(),
CacheEntry {
source_digest: digest,
model: model.clone(),
},
);
}
}
Ok(model)
}
}
fn handle(state: &ServerState, request: Request) -> ViewResult<()> {
let method = request.method().clone();
if !matches!(method, Method::Get | Method::Head) {
return respond_text(
request,
StatusCode(405),
"text/plain; charset=utf-8",
"method not allowed\n".as_bytes().to_vec(),
CacheKind::NoStore,
);
}
let is_head = method == Method::Head;
if !host_is_allowed(&request, &state.allowed_hosts) {
return respond_text(
request,
StatusCode(400),
"text/plain; charset=utf-8",
"invalid Host header\n".as_bytes().to_vec(),
CacheKind::NoStore,
);
}
let raw_url = request.url().to_string();
if raw_url.len() > MAX_URL_BYTES {
return respond_text(
request,
StatusCode(414),
"text/plain; charset=utf-8",
"request target too long\n".as_bytes().to_vec(),
CacheKind::NoStore,
);
}
let (path_part, query) = split_url(&raw_url);
if query.len() > MAX_QUERY_BYTES {
return respond_text(
request,
StatusCode(414),
"text/plain; charset=utf-8",
"query too long\n".as_bytes().to_vec(),
CacheKind::NoStore,
);
}
if let Some(hashed_name) = path_part.strip_prefix("/assets/") {
return serve_asset(request, hashed_name, is_head);
}
match path_part {
"/" | "/index.html" => {
let entry = state.ctx.project().entry().relative.clone();
match state.load(&entry) {
Ok(model) => serve_page(state, request, &model, is_head),
Err(err) => serve_error_page(request, &err, is_head),
}
}
"/file" => {
let Some(raw_path) = query_param(query, "path") else {
return respond_text(
request,
StatusCode(400),
"text/plain; charset=utf-8",
"missing path\n".as_bytes().to_vec(),
CacheKind::NoStore,
);
};
let Some(decoded) = percent_decode(&raw_path) else {
return respond_text(
request,
StatusCode(400),
"text/plain; charset=utf-8",
"malformed path\n".as_bytes().to_vec(),
CacheKind::NoStore,
);
};
let relative = match SafeRelativePath::parse(&decoded) {
Ok(relative) => relative,
Err(err) => {
return respond_text(
request,
StatusCode(403),
"text/plain; charset=utf-8",
format!("{}\n", err.code()).into_bytes(),
CacheKind::NoStore,
)
}
};
if state.ctx.project().read_source(&relative).is_err() {
return respond_text(
request,
StatusCode(404),
"text/plain; charset=utf-8",
"document not found\n".as_bytes().to_vec(),
CacheKind::NoStore,
);
}
match state.load(&relative) {
Ok(model) => serve_page(state, request, &model, is_head),
Err(err) => serve_error_page(request, &err, is_head),
}
}
"/api/document" => {
let relative = match query_param(query, "path")
.and_then(|raw| percent_decode(&raw))
.map(|decoded| SafeRelativePath::parse(&decoded))
{
Some(Ok(relative)) => relative,
Some(Err(err)) => {
return respond_json_error(request, StatusCode(400), &err);
}
None => state.ctx.project().entry().relative.clone(),
};
match state.load(&relative) {
Ok(model) => serve_document_json(request, &model),
Err(err) => respond_json_error(request, StatusCode(500), &err),
}
}
"/api/health" => {
let documents = state
.ctx
.project()
.list_documents()
.map(|documents| documents.len())
.unwrap_or(0);
let health = serde_json::json!({
"schema": "marqdo.view-health",
"schema_version": 1,
"ok": true,
"view": {
"name": "marqdo-view",
"version": env!("CARGO_PKG_VERSION"),
},
"core": {
"version": state.ctx.core_version(),
},
"protocols": {
"tool": crate::version::TOOL_PROTOCOL,
"analysis": crate::version::ANALYSIS_PROTOCOL,
"trace": crate::version::TRACE_PROTOCOL,
},
"documents": documents,
"run_api": false,
});
respond_json(request, StatusCode(200), &health)
}
_ => respond_text(
request,
StatusCode(404),
"text/plain; charset=utf-8",
"not found\n".as_bytes().to_vec(),
CacheKind::NoStore,
),
}
}
fn serve_page(
state: &ServerState,
request: Request,
model: &PresentationModel,
is_head: bool,
) -> ViewResult<()> {
let ctx = RenderContext {
links: crate::render::LinkPolicy::LocalServer,
live: true,
csrf_token: Some(state.csrf_token.clone()),
run_available: false,
};
let page = state.renderer.render(model, &ctx);
respond_html(request, page.html.into_bytes(), is_head)
}
fn serve_error_page(request: Request, err: &ViewError, is_head: bool) -> ViewResult<()> {
let html = format!(
"<!DOCTYPE html><html lang=\"zh-CN\"><head><meta charset=\"utf-8\"/><title>Marqdo View · 错误</title><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/></head><body style=\"font:16px/1.6 system-ui,serif;background:#fcf9f5;color:#29251f;padding:2rem;max-width:46rem;margin:auto\"><h1>无法生成阅读页面</h1><p><code>{code}</code></p><p>{message}</p><p><a href=\"/\">返回入口</a></p></body></html>",
code = escape_html(err.code()),
message = escape_html(&err.to_string()),
);
respond_html(request, html.into_bytes(), is_head)
}
fn serve_document_json(request: Request, model: &PresentationModel) -> ViewResult<()> {
let semantic = model.semantic.as_ref();
let doc = serde_json::json!({
"schema": "marqdo.view-document",
"schema_version": 1,
"title": model.title,
"document": {
"relative_path": model.document.identity.relative_path,
"module_id": model.document.identity.module_id,
"source_sha256": sha256_hex(model.document.source.as_bytes()),
},
"source_status": model.source_status.data_value(),
"semantics_usable": model.source_status.semantics_usable(),
"analysis": semantic.map(|projection| serde_json::json!({
"digest": projection.analysis_digest,
"schema_version": crate::version::ANALYSIS_PROTOCOL,
"producer_version": projection.producer_version,
"project_root_id": projection.project_root_id,
"functions": projection.functions.len(),
"units": projection.units.len(),
"diagnostics": projection.diagnostics.len(),
})),
"outline": model.outline.iter().map(|entry| serde_json::json!({
"label": entry.label,
"anchor": entry.anchor,
"detail": entry.detail,
"kind": match entry.kind {
crate::presentation::OutlineKind::Function => "function",
crate::presentation::OutlineKind::Knowledge => "knowledge",
crate::presentation::OutlineKind::Section => "section",
},
})).collect::<Vec<_>>(),
"navigation": {
"documents": model.navigation.documents.iter().map(|doc| doc.as_str()).collect::<Vec<_>>(),
"welcome": model.navigation.welcome,
},
"note": "Read-only PresentationModel summary; the document was not executed.",
});
respond_json(request, StatusCode(200), &doc)
}
fn serve_asset(request: Request, hashed_name: &str, is_head: bool) -> ViewResult<()> {
let bundle = AssetBundle::get();
if hashed_name == bundle.hashed_css_name() {
return respond_asset(
request,
bundle.css_bytes().to_vec(),
"text/css; charset=utf-8",
is_head,
);
}
let Some(asset) = bundle.by_path(hashed_name) else {
return respond_text(
request,
StatusCode(404),
"text/plain; charset=utf-8",
"asset not found\n".as_bytes().to_vec(),
CacheKind::NoStore,
);
};
respond_asset(request, asset.bytes.to_vec(), asset.mime, is_head)
}
enum CacheKind {
NoStore,
Immutable,
}
fn respond_html(request: Request, body: Vec<u8>, is_head: bool) -> ViewResult<()> {
respond_with(
request,
StatusCode(200),
"text/html; charset=utf-8",
if is_head { Vec::new() } else { body },
CacheKind::NoStore,
)
}
fn respond_asset(
request: Request,
body: Vec<u8>,
content_type: &str,
is_head: bool,
) -> ViewResult<()> {
respond_with(
request,
StatusCode(200),
content_type,
if is_head { Vec::new() } else { body },
CacheKind::Immutable,
)
}
fn respond_json(request: Request, status: StatusCode, value: &serde_json::Value) -> ViewResult<()> {
let body = serde_json::to_vec_pretty(value).unwrap_or_else(|_| b"{}".to_vec());
respond_with(
request,
status,
"application/json; charset=utf-8",
body,
CacheKind::NoStore,
)
}
fn respond_json_error(request: Request, status: StatusCode, err: &ViewError) -> ViewResult<()> {
respond_json(request, status, &err.to_json())
}
fn respond_text(
request: Request,
status: StatusCode,
content_type: &str,
body: Vec<u8>,
cache: CacheKind,
) -> ViewResult<()> {
respond_with(request, status, content_type, body, cache)
}
fn respond_with(
request: Request,
status: StatusCode,
content_type: &str,
body: Vec<u8>,
cache: CacheKind,
) -> ViewResult<()> {
let length = body.len();
let mut response = Response::from_data(body).with_status_code(status);
if let Ok(header) = Header::from_bytes(&b"Content-Type"[..], content_type.as_bytes()) {
response.add_header(header);
}
for (name, value) in security_headers() {
if let Ok(header) = Header::from_bytes(name.as_bytes(), value.as_bytes()) {
response.add_header(header);
}
}
let cache_value = match cache {
CacheKind::NoStore => "no-store",
CacheKind::Immutable => "public, max-age=31536000, immutable",
};
if let Ok(header) = Header::from_bytes(&b"Cache-Control"[..], cache_value.as_bytes()) {
response.add_header(header);
}
let _ = length;
request.respond(response).map_err(|err| ViewError::Io {
detail: format!("write response: {err}"),
})
}
fn security_headers() -> Vec<(&'static str, &'static str)> {
vec![
(
"Content-Security-Policy",
"default-src 'none'; style-src 'self'; script-src 'self' file:; img-src 'self' data:; font-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'; object-src 'none'",
),
("X-Content-Type-Options", "nosniff"),
("Referrer-Policy", "no-referrer"),
("X-Frame-Options", "DENY"),
("Cross-Origin-Resource-Policy", "same-origin"),
("Cross-Origin-Opener-Policy", "same-origin"),
]
}
fn split_url(url: &str) -> (&str, &str) {
match url.split_once('?') {
Some((path, query)) => (path, query),
None => (url, ""),
}
}
fn query_param(query: &str, key: &str) -> Option<String> {
for pair in query.split('&') {
let (name, value) = match pair.split_once('=') {
Some(parts) => parts,
None => (pair, ""),
};
if name == key {
return Some(value.to_string());
}
}
None
}
/// Decode `%XX` exactly once. Rejects malformed escapes, NUL, other control
/// characters and non-UTF-8 results (RFC §11.2.4).
fn percent_decode(raw: &str) -> Option<String> {
let bytes = raw.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
match bytes[index] {
b'%' => {
if index + 2 >= bytes.len() {
return None;
}
let high = hex_value(*bytes.get(index + 1)?)?;
let low = hex_value(*bytes.get(index + 2)?)?;
out.push(high * 16 + low);
index += 3;
}
b'+' => {
// Query strings here are paths, not form data: keep a literal +.
out.push(b'+');
index += 1;
}
byte => {
out.push(byte);
index += 1;
}
}
}
if out.contains(&0) || out.iter().any(|byte| *byte < 0x20 || *byte == 0x7f) {
return None;
}
String::from_utf8(out).ok()
}
fn hex_value(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
fn allowed_hosts(port: u16) -> Vec<String> {
vec![
format!("127.0.0.1:{port}"),
format!("localhost:{port}"),
format!("[::1]:{port}"),
]
}
fn host_is_allowed(request: &Request, allowed: &[String]) -> bool {
let mut host: Option<&str> = None;
for header in request.headers() {
if header.field.equiv("Host") {
host = Some(header.value.as_str());
break;
}
}
match host {
Some(value) => allowed
.iter()
.any(|allowed| allowed.eq_ignore_ascii_case(value)),
None => false,
}
}
fn escape_html(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
for ch in raw.chars() {
match ch {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&#39;"),
_ => out.push(ch),
}
}
out
}
fn random_token() -> String {
#[cfg(unix)]
{
use std::io::Read as _;
if let Ok(mut file) = std::fs::File::open("/dev/urandom") {
let mut bytes = [0u8; 32];
if file.read_exact(&mut bytes).is_ok() {
return hex_encode(&bytes);
}
}
}
// Fallback: still unique per process/session, never a constant.
let material = format!(
"{}-{}-{:?}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0),
std::thread::current().id()
);
sha256_hex(material.as_bytes())
}
fn hex_encode(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
use std::fmt::Write as _;
let _ = write!(out, "{byte:02x}");
}
out
}
fn open_browser(url: &str) {
let program = if cfg!(target_os = "macos") {
"open"
} else if cfg!(target_os = "windows") {
"cmd"
} else {
"xdg-open"
};
let mut command = std::process::Command::new(program);
if cfg!(target_os = "windows") {
command.args(["/C", "start", ""]);
}
command.arg(url);
command
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
if command.spawn().is_err() {
eprintln!("view: could not open a browser; open {url} manually");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn percent_decode_is_single_pass_and_strict() {
assert_eq!(percent_decode("a%20b").as_deref(), Some("a b"));
assert_eq!(percent_decode("100%25").as_deref(), Some("100%"));
assert_eq!(percent_decode("a+b").as_deref(), Some("a+b"));
assert!(percent_decode("%2e%2e%2fsecret").is_some());
assert!(percent_decode("%zz").is_none());
assert!(percent_decode("%2").is_none());
assert!(percent_decode("a%00b").is_none());
assert!(percent_decode("%0a").is_none());
assert!(percent_decode("%ff").is_none());
}
#[test]
fn query_params_are_parsed_without_form_plus_rules() {
assert_eq!(query_param("path=a%2Fb", "path").as_deref(), Some("a%2Fb"));
assert_eq!(query_param("x=1&path=y", "path").as_deref(), Some("y"));
assert_eq!(query_param("", "path"), None);
}
#[test]
fn allowed_hosts_include_loopback_and_port() {
let hosts = allowed_hosts(7429);
assert!(hosts.contains(&"127.0.0.1:7429".to_string()));
assert!(hosts.contains(&"localhost:7429".to_string()));
assert!(!hosts.contains(&"127.0.0.1:7428".to_string()));
}
#[test]
fn random_token_is_64_hex_chars_and_unique() {
let a = random_token();
let b = random_token();
assert_eq!(a.len(), 64);
assert_ne!(a, b);
}
}
+28
View File
@@ -127,6 +127,34 @@ impl SourceIndex {
is_char_boundary(bytes, start) && is_char_boundary(bytes, end)
}
/// Byte offset of the start of a 1-based line.
pub fn line_start(&self, line: usize) -> Option<usize> {
if line == 0 {
return None;
}
self.line_starts.get(line - 1).copied()
}
/// Number of lines in the source.
pub fn line_count(&self) -> usize {
self.line_starts.len()
}
/// Text of a 1-based line without its trailing newline.
pub fn line_text<'a>(&self, source: &'a str, line: usize) -> Option<&'a str> {
let start = self.line_start(line)?;
let end = self.line_starts.get(line).copied().unwrap_or(self.len);
let bytes = source.as_bytes();
let mut end = end.min(bytes.len());
if end > start && bytes.get(end - 1) == Some(&b'\n') {
end -= 1;
if end > start && bytes.get(end - 1) == Some(&b'\r') {
end -= 1;
}
}
source.get(start..end)
}
/// 1-based line and 1-based byte column for a byte offset, clamped to the
/// file length. Column counts bytes, matching Core's presentation fields.
pub fn line_col(&self, byte: usize) -> (usize, usize) {