feat(parse): use nested YAML import: maps instead of one-liner binds
Frontmatter imports are now valid YAML (`import:` / `导入:` with bind→target entries), removing spaced keys. Add `marqdo migrate imports`, hard-error the old one-liner form, and migrate lib/ext/examples/tests/docs accordingly. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
8bbe017a5e
commit
687c168014
364 files changed
+1870
-1004
No files matched your search
+2
-2
@@ -6,14 +6,14 @@ use crate::diagnostics::Span;
|
||||
use crate::formula::Expr as FormulaExpr;
|
||||
use crate::value::CodeBlock;
|
||||
|
||||
/// Frontmatter file import: `import bind:path.mq.md` (see `doc/design/module-namespace.md`).
|
||||
/// Frontmatter file import under nested `import:\n bind: path.mq.md` (see `doc/design/module-namespace.md`).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Import {
|
||||
pub path: String,
|
||||
pub bind: String,
|
||||
}
|
||||
|
||||
/// Frontmatter short-name bind: `import bind:lib.member` (same keyword as file import).
|
||||
/// Frontmatter short-name bind under nested `import:\n bind: lib.member` (same map as file import).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Use {
|
||||
pub path: Vec<String>,
|
||||
|
||||
@@ -92,7 +92,8 @@ mod tests {
|
||||
#[test]
|
||||
fn boot_and_call_share_count() {
|
||||
let src = r##"---
|
||||
import json:lib/json.mq.md
|
||||
import:
|
||||
json: lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
+4
-22
@@ -293,28 +293,10 @@ fn inspect_file(abs: &Path, rel: &str) -> Result<ModuleInfo> {
|
||||
}
|
||||
|
||||
fn extract_frontmatter_imports(source: &str) -> Vec<String> {
|
||||
let source = source.strip_prefix('\u{feff}').unwrap_or(source);
|
||||
let mut imports = Vec::new();
|
||||
let lines: Vec<&str> = source.lines().collect();
|
||||
if lines.first().map(|l| l.trim()) != Some("---") {
|
||||
return imports;
|
||||
}
|
||||
for line in lines.iter().skip(1) {
|
||||
let t = line.trim();
|
||||
if t == "---" {
|
||||
break;
|
||||
}
|
||||
if let Ok(Some(crate::parse::ImportLine::File(imp))) =
|
||||
crate::parse::parse_import_line(t)
|
||||
{
|
||||
imports.push(format!("import {}:{}", imp.bind, imp.path));
|
||||
} else if let Ok(Some(crate::parse::ImportLine::Member(u))) =
|
||||
crate::parse::parse_import_line(t)
|
||||
{
|
||||
imports.push(format!("import {}:{}", u.bind, u.path.join(".")));
|
||||
}
|
||||
}
|
||||
imports
|
||||
crate::parse::scan_frontmatter_imports(source)
|
||||
.iter()
|
||||
.map(crate::parse::format_import_display)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn extract_frontmatter_title(source: &str) -> Option<String> {
|
||||
|
||||
+12
-6
@@ -1436,7 +1436,8 @@ mod tests {
|
||||
));
|
||||
let source = r#"---
|
||||
title: evaluated plan test
|
||||
import foreign:lib/foreign.mq.md
|
||||
import:
|
||||
foreign: lib/foreign.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
@@ -1521,7 +1522,8 @@ print(1)
|
||||
));
|
||||
let source = r#"---
|
||||
title: shared state test
|
||||
import foreign:lib/foreign.mq.md
|
||||
import:
|
||||
foreign: lib/foreign.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
@@ -1651,7 +1653,8 @@ console.log("stateless");
|
||||
));
|
||||
let source = r#"---
|
||||
title: clear outputs
|
||||
import foreign:lib/foreign.mq.md
|
||||
import:
|
||||
foreign: lib/foreign.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
@@ -1801,7 +1804,8 @@ print(950)
|
||||
));
|
||||
let source = r#"---
|
||||
title: plan inputs test
|
||||
import foreign:lib/foreign.mq.md
|
||||
import:
|
||||
foreign: lib/foreign.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
@@ -1861,7 +1865,8 @@ print(sys.stdin.read().strip())
|
||||
));
|
||||
let source = r#"---
|
||||
title: persistent node stdin test
|
||||
import foreign:lib/foreign.mq.md
|
||||
import:
|
||||
foreign: lib/foreign.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
@@ -1915,7 +1920,8 @@ import foreign:lib/foreign.mq.md
|
||||
));
|
||||
let source = r#"---
|
||||
title: persistent stdin test
|
||||
import foreign:lib/foreign.mq.md
|
||||
import:
|
||||
foreign: lib/foreign.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
+4
-3
@@ -659,8 +659,9 @@ PATCH:
|
||||
@@
|
||||
-> ext/ai/llm.mq.md
|
||||
-> lib/json.mq.md
|
||||
+import llm:ext/ai/llm.mq.md
|
||||
+import json:lib/json.mq.md
|
||||
+import:
|
||||
+ llm: ext/ai/llm.mq.md
|
||||
+ json: lib/json.mq.md
|
||||
*** End Patch
|
||||
```
|
||||
"#;
|
||||
@@ -674,7 +675,7 @@ PATCH:
|
||||
assert_eq!(n, Value::Int(1));
|
||||
assert_eq!(
|
||||
fs::read_to_string(&path).unwrap(),
|
||||
"import llm:ext/ai/llm.mq.md\nimport json:lib/json.mq.md\n"
|
||||
"import:\n llm: ext/ai/llm.mq.md\n json: lib/json.mq.md\n"
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -498,27 +498,9 @@ fn prose_field(source: &str, label: &str) -> Option<String> {
|
||||
}
|
||||
|
||||
fn extract_frontmatter_imports(source: &str) -> Vec<String> {
|
||||
let source = source.strip_prefix('\u{feff}').unwrap_or(source);
|
||||
let mut imports = Vec::new();
|
||||
let lines: Vec<&str> = source.lines().collect();
|
||||
if lines.first().map(|l| l.trim()) != Some("---") {
|
||||
return imports;
|
||||
}
|
||||
for line in lines.iter().skip(1) {
|
||||
let t = line.trim();
|
||||
if t == "---" {
|
||||
break;
|
||||
}
|
||||
if let Ok(Some(crate::parse::ImportLine::File(imp))) =
|
||||
crate::parse::parse_import_line(t)
|
||||
{
|
||||
imports.push(format!("import {}:{}", imp.bind, imp.path));
|
||||
} else if let Ok(Some(crate::parse::ImportLine::Member(u))) =
|
||||
crate::parse::parse_import_line(t)
|
||||
{
|
||||
imports.push(format!("import {}:{}", u.bind, u.path.join(".")));
|
||||
}
|
||||
}
|
||||
imports
|
||||
crate::parse::scan_frontmatter_imports(source)
|
||||
.iter()
|
||||
.map(crate::parse::format_import_display)
|
||||
.collect()
|
||||
}
|
||||
|
||||
+10
-1
@@ -471,7 +471,16 @@ fn payload_fingerprint(payload: &Option<Box<Expr>>) -> String {
|
||||
|
||||
fn render_payload(payload: &Option<Box<Expr>>) -> String {
|
||||
match payload {
|
||||
Some(e) => crate::view::expr_display(e),
|
||||
Some(e) => {
|
||||
#[cfg(feature = "view")]
|
||||
{
|
||||
crate::view::expr_display(e)
|
||||
}
|
||||
#[cfg(not(feature = "view"))]
|
||||
{
|
||||
format!("{e:?}")
|
||||
}
|
||||
}
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
+79
@@ -54,6 +54,17 @@ enum MigrateAction {
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// One-liner `import bind:target` → nested YAML `import:\n bind: target`
|
||||
Imports {
|
||||
#[arg(value_name = "PATH", default_value = ".")]
|
||||
paths: Vec<PathBuf>,
|
||||
/// Actually rewrite files (default: dry run)
|
||||
#[arg(long)]
|
||||
write: bool,
|
||||
/// One JSON array on stdout
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -795,6 +806,74 @@ fn try_main(cli: Cli) -> Result<i32> {
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
MigrateAction::Imports { paths, write, json } => {
|
||||
let mut reports = Vec::new();
|
||||
for p in &paths {
|
||||
reports.extend(marqdo::migrate::migrate_imports_path(p, write)?);
|
||||
}
|
||||
let (mut bindings, mut applied, mut problems) = (0usize, 0usize, 0usize);
|
||||
for r in &reports {
|
||||
bindings += r.bindings;
|
||||
applied += usize::from(r.applied);
|
||||
if r.note.as_ref().is_some_and(|n| {
|
||||
n != "no legacy import one-liners"
|
||||
}) && r.bindings == 0
|
||||
{
|
||||
problems += 1;
|
||||
}
|
||||
}
|
||||
if json {
|
||||
let arr: Vec<serde_json::Value> = reports
|
||||
.iter()
|
||||
.filter(|r| r.bindings > 0 || r.note.as_ref().is_some_and(|n| n != "no legacy import one-liners"))
|
||||
.map(|r| {
|
||||
serde_json::json!({
|
||||
"file": r.file.display().to_string(),
|
||||
"bindings": r.bindings,
|
||||
"applied": r.applied,
|
||||
"note": r.note,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
println!("{}", serde_json::Value::Array(arr));
|
||||
} else {
|
||||
for r in &reports {
|
||||
if r.bindings == 0 && r.note.as_ref().is_some_and(|n| n == "no legacy import one-liners") {
|
||||
continue;
|
||||
}
|
||||
if r.bindings == 0 {
|
||||
println!(
|
||||
"{} skipped ({})",
|
||||
r.file.display(),
|
||||
r.note.as_deref().unwrap_or("?")
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let state = if r.applied {
|
||||
"written"
|
||||
} else if r.note.is_some() {
|
||||
"skipped"
|
||||
} else {
|
||||
"would change"
|
||||
};
|
||||
println!(
|
||||
"{} bindings={} {}{}",
|
||||
r.file.display(),
|
||||
r.bindings,
|
||||
state,
|
||||
r.note
|
||||
.as_ref()
|
||||
.map(|n| format!(" ({n})"))
|
||||
.unwrap_or_default()
|
||||
);
|
||||
}
|
||||
println!(
|
||||
"migrate imports: {bindings} binding(s), {applied} file written, {problems} problem(s){}",
|
||||
if write { "" } else { " (dry run; pass --write)" }
|
||||
);
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
},
|
||||
Commands::Mlsp => {
|
||||
use std::io::{BufRead, Write};
|
||||
|
||||
+185
-3
@@ -2,7 +2,9 @@
|
||||
//! purity forms (`access(集合, 键)` and `- [描述](遍历 集合 为 项)`), then mark
|
||||
//! the file `markup: occlusion`.
|
||||
//!
|
||||
//! Safety model: **transform, re-parse, prove equivalence, then write.**
|
||||
//! Also: nested YAML `import:` migration (`marqdo migrate imports`).
|
||||
//!
|
||||
//! Safety model (labels): **transform, re-parse, prove equivalence, then write.**
|
||||
//! The transformed file is parsed in occlusion mode and *denormalized* back to
|
||||
//! the legacy AST shape; if the denormalized AST is not byte-identical (Debug)
|
||||
//! to the original, the file is left untouched and reported.
|
||||
@@ -10,8 +12,9 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::ast::{Arg, BranchArm, Expr, Function, IndexKey, Module, Stmt};
|
||||
use crate::parse::{is_legacy_import_oneliner, parse_import_binding};
|
||||
|
||||
/// Outcome of migrating one file.
|
||||
/// Outcome of migrating one file (labels).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FileReport {
|
||||
pub file: PathBuf,
|
||||
@@ -21,6 +24,15 @@ pub struct FileReport {
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
/// Outcome of migrating one-liner imports → nested `import:` / `导入:`.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ImportFileReport {
|
||||
pub file: PathBuf,
|
||||
pub bindings: usize,
|
||||
pub applied: bool,
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
fn has_marker(source: &str) -> bool {
|
||||
let mut lines = source.lines();
|
||||
if lines.next().map(|l| l.trim_end()) != Some("---") {
|
||||
@@ -540,6 +552,167 @@ pub fn migrate_path(path: &Path, write: bool) -> anyhow::Result<Vec<FileReport>>
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Rewrite frontmatter one-liner `import bind:target` / `导入 bind:target` into a
|
||||
/// nested YAML map. Returns `(new_source, binding_count)` or `None` if unchanged.
|
||||
pub fn rewrite_import_frontmatter(source: &str) -> Result<Option<(String, usize)>, String> {
|
||||
let source = source.strip_prefix('\u{feff}').unwrap_or(source);
|
||||
let lines: Vec<&str> = source.lines().collect();
|
||||
if lines.first().map(|l| l.trim()) != Some("---") {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut fm_end = None;
|
||||
for (i, line) in lines.iter().enumerate().skip(1) {
|
||||
if line.trim() == "---" {
|
||||
fm_end = Some(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(fm_end) = fm_end else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let mut keyword: Option<&'static str> = None;
|
||||
let mut entries: Vec<(String, String)> = Vec::new();
|
||||
let mut legacy_idxs: Vec<usize> = Vec::new();
|
||||
let mut has_nested = false;
|
||||
let mut nested_kw: Option<&'static str> = None;
|
||||
|
||||
for i in 1..fm_end {
|
||||
let t = lines[i].trim();
|
||||
// Nested header with empty RHS only (`import:` / `导入:`)
|
||||
if let Some(rest) = t.strip_prefix("import:") {
|
||||
if rest.trim().is_empty() {
|
||||
has_nested = true;
|
||||
nested_kw = Some("import");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if let Some(rest) = t.strip_prefix("导入:") {
|
||||
if rest.trim().is_empty() {
|
||||
has_nested = true;
|
||||
nested_kw = Some("导入");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if !is_legacy_import_oneliner(t) {
|
||||
continue;
|
||||
}
|
||||
let (kw, after) = if t.starts_with("import") {
|
||||
("import", t[6..].trim())
|
||||
} else if let Some(a) = t.strip_prefix("导入") {
|
||||
("导入", a.trim())
|
||||
} else {
|
||||
return Err(format!("internal: not a legacy import: {t}"));
|
||||
};
|
||||
// Pre-existing EN/ZH one-liner mixes: fold under the first keyword seen.
|
||||
if keyword.is_none() {
|
||||
keyword = Some(kw);
|
||||
}
|
||||
let _ = kw;
|
||||
let Some((bind_raw, target_raw)) = after.split_once(':') else {
|
||||
return Err(format!("expected bind:target in `{t}`"));
|
||||
};
|
||||
let bind = bind_raw.trim().to_string();
|
||||
let target = target_raw.trim().to_string();
|
||||
parse_import_binding(&bind, &target).map_err(|e| e.to_string())?;
|
||||
if entries.iter().any(|(b, _)| b == &bind) {
|
||||
return Err(format!("duplicate import bind `{bind}`"));
|
||||
}
|
||||
entries.push((bind, target));
|
||||
legacy_idxs.push(i);
|
||||
}
|
||||
|
||||
if entries.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if has_nested {
|
||||
return Err(format!(
|
||||
"file already has `{}:` block and legacy one-liners — resolve manually",
|
||||
nested_kw.unwrap_or("import")
|
||||
));
|
||||
}
|
||||
|
||||
let kw = keyword.unwrap_or("import");
|
||||
let insert_at = legacy_idxs[0];
|
||||
let skip: std::collections::HashSet<usize> = legacy_idxs.into_iter().collect();
|
||||
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for (i, line) in lines.iter().enumerate() {
|
||||
if i == insert_at {
|
||||
out.push(format!("{kw}:"));
|
||||
for (bind, target) in &entries {
|
||||
out.push(format!(" {bind}: {target}"));
|
||||
}
|
||||
}
|
||||
if skip.contains(&i) {
|
||||
continue;
|
||||
}
|
||||
out.push((*line).to_string());
|
||||
}
|
||||
|
||||
let mut body = out.join("\n");
|
||||
if source.ends_with('\n') {
|
||||
body.push('\n');
|
||||
}
|
||||
Ok(Some((body, entries.len())))
|
||||
}
|
||||
|
||||
/// Migrate one file's import frontmatter. `write=false` is dry-run.
|
||||
pub fn migrate_imports_file(path: &Path, write: bool) -> anyhow::Result<ImportFileReport> {
|
||||
let source = std::fs::read_to_string(path)?;
|
||||
let mut report = ImportFileReport {
|
||||
file: path.to_path_buf(),
|
||||
bindings: 0,
|
||||
applied: false,
|
||||
note: None,
|
||||
};
|
||||
match rewrite_import_frontmatter(&source) {
|
||||
Ok(None) => {
|
||||
report.note = Some("no legacy import one-liners".into());
|
||||
Ok(report)
|
||||
}
|
||||
Err(e) => {
|
||||
report.note = Some(e);
|
||||
Ok(report)
|
||||
}
|
||||
Ok(Some((new_src, n))) => {
|
||||
report.bindings = n;
|
||||
// Soft smoke: nested map must extract the same binding count.
|
||||
let scanned = crate::parse::scan_frontmatter_imports(&new_src);
|
||||
if scanned.len() != n {
|
||||
report.note = Some(format!(
|
||||
"scan mismatch after rewrite: got {} expected {n}",
|
||||
scanned.len()
|
||||
));
|
||||
return Ok(report);
|
||||
}
|
||||
if write {
|
||||
std::fs::write(path, &new_src)?;
|
||||
report.applied = true;
|
||||
}
|
||||
Ok(report)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Recursively migrate import one-liners under `path`.
|
||||
pub fn migrate_imports_path(path: &Path, write: bool) -> anyhow::Result<Vec<ImportFileReport>> {
|
||||
let files = collect_files(path);
|
||||
let mut out = Vec::new();
|
||||
for f in files {
|
||||
match migrate_imports_file(&f, write) {
|
||||
Ok(r) => out.push(r),
|
||||
Err(e) => out.push(ImportFileReport {
|
||||
file: f,
|
||||
bindings: 0,
|
||||
applied: false,
|
||||
note: Some(format!("read failed: {e:#}")),
|
||||
}),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Collect `*.mq.md` under `path` (file → itself).
|
||||
pub fn collect_files(path: &Path) -> Vec<PathBuf> {
|
||||
fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
@@ -568,7 +741,16 @@ pub fn collect_files(path: &Path) -> Vec<PathBuf> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{rewrite_indexes, rewrite_loop};
|
||||
use super::{rewrite_import_frontmatter, rewrite_indexes, rewrite_loop};
|
||||
|
||||
#[test]
|
||||
fn rewrites_import_oneliners_to_nested() {
|
||||
let src = "---\ntitle: t\nimport json:lib/json.mq.md\nimport fmt:time.format\n---\n\n# main\n";
|
||||
let (out, n) = rewrite_import_frontmatter(src).unwrap().unwrap();
|
||||
assert_eq!(n, 2);
|
||||
assert!(out.contains("import:\n json: lib/json.mq.md\n fmt: time.format\n"));
|
||||
assert!(!out.contains("import json:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_static_key() {
|
||||
|
||||
+230
-76
@@ -146,6 +146,7 @@ impl<'a> Cursor<'a> {
|
||||
let mut imports = Vec::new();
|
||||
let mut uses = Vec::new();
|
||||
let mut metadata_raw = Vec::new();
|
||||
let mut import_keyword: Option<&'static str> = None;
|
||||
if !self.skip_noise() {
|
||||
return Ok((imports, uses, metadata_raw));
|
||||
}
|
||||
@@ -166,40 +167,41 @@ impl<'a> Cursor<'a> {
|
||||
if let Some(msg) = legacy_frontmatter_import_hint(t) {
|
||||
return Err(bail_at(None, span, msg));
|
||||
}
|
||||
match parse_import_line(t) {
|
||||
Ok(Some(ImportLine::File(imp))) => {
|
||||
if imports.iter().any(|i| i.bind == imp.bind)
|
||||
|| uses.iter().any(|u| u.bind == imp.bind)
|
||||
{
|
||||
return Err(bail_at(
|
||||
None,
|
||||
span,
|
||||
format!("duplicate import bind `{}`", imp.bind),
|
||||
));
|
||||
}
|
||||
imports.push(imp);
|
||||
self.bump();
|
||||
continue;
|
||||
}
|
||||
Ok(Some(ImportLine::Member(u))) => {
|
||||
if imports.iter().any(|i| i.bind == u.bind)
|
||||
|| uses.iter().any(|x| x.bind == u.bind)
|
||||
{
|
||||
return Err(bail_at(
|
||||
None,
|
||||
span,
|
||||
format!("duplicate import bind `{}`", u.bind),
|
||||
));
|
||||
}
|
||||
uses.push(u);
|
||||
self.bump();
|
||||
continue;
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => return Err(bail_at(None, span, e.to_string())),
|
||||
}
|
||||
// Artifact metadata key: value (flat Phase 1)
|
||||
// Artifact metadata key: value (flat Phase 1); `import:` / `导入:` are nested maps
|
||||
if let Some((key, rest)) = split_frontmatter_key(t) {
|
||||
if key == "import" || key == "导入" {
|
||||
let kw = if key == "import" { "import" } else { "导入" };
|
||||
if let Some(prev) = import_keyword {
|
||||
if prev != kw {
|
||||
return Err(bail_at(
|
||||
None,
|
||||
span,
|
||||
format!(
|
||||
"cannot mix `{prev}:` and `{kw}:` in one frontmatter (one language per file)"
|
||||
),
|
||||
));
|
||||
}
|
||||
return Err(bail_at(
|
||||
None,
|
||||
span,
|
||||
format!("duplicate `{kw}:` block in frontmatter"),
|
||||
));
|
||||
}
|
||||
if !rest.is_empty() {
|
||||
return Err(bail_at(
|
||||
None,
|
||||
span,
|
||||
format!(
|
||||
"`{kw}:` must be a nested YAML map (not `{kw}: …` on one line); \
|
||||
use indented `bind: target` under `{kw}:`"
|
||||
),
|
||||
));
|
||||
}
|
||||
import_keyword = Some(kw);
|
||||
self.bump();
|
||||
self.collect_import_map(span, &mut imports, &mut uses)?;
|
||||
continue;
|
||||
}
|
||||
self.bump();
|
||||
let value_raw = if rest.is_empty()
|
||||
|| rest == "|"
|
||||
@@ -231,6 +233,47 @@ impl<'a> Cursor<'a> {
|
||||
Ok((imports, uses, metadata_raw))
|
||||
}
|
||||
|
||||
/// Consume indented `bind: target` lines under `import:` / `导入:`.
|
||||
fn collect_import_map(
|
||||
&mut self,
|
||||
header_span: Span,
|
||||
imports: &mut Vec<Import>,
|
||||
uses: &mut Vec<Use>,
|
||||
) -> Result<()> {
|
||||
let _ = header_span;
|
||||
while let Some(line) = self.peek() {
|
||||
let raw = line.text.trim_end_matches(['\r', '\n']);
|
||||
let bt = raw.trim();
|
||||
if bt == "---" {
|
||||
break;
|
||||
}
|
||||
if bt.is_empty() {
|
||||
self.bump();
|
||||
continue;
|
||||
}
|
||||
// Next top-level key ends the import map
|
||||
if !raw.starts_with(' ') && !raw.starts_with('\t') {
|
||||
break;
|
||||
}
|
||||
let span = Span::new(line.line_no, 1);
|
||||
self.bump();
|
||||
let content = strip_yaml_indent(raw);
|
||||
let Some((bind_raw, target_raw)) = content.split_once(':') else {
|
||||
return Err(bail_at(
|
||||
None,
|
||||
span,
|
||||
format!("expected `bind: target` under import map, got `{content}`"),
|
||||
));
|
||||
};
|
||||
let bind = bind_raw.trim();
|
||||
let target = target_raw.trim();
|
||||
let entry = parse_import_binding(bind, target)
|
||||
.map_err(|e| bail_at(None, span, e.to_string()))?;
|
||||
push_import_line(imports, uses, entry, span)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_function(&mut self, min_level: u8) -> Result<Function> {
|
||||
let line = self.bump().unwrap();
|
||||
let (level, raw_name) = parse_heading(line.text.trim())
|
||||
@@ -1541,19 +1584,22 @@ fn is_simple_type_name(s: &str) -> bool {
|
||||
chars.all(|c| c.is_alphanumeric() || c == '_' || !c.is_ascii())
|
||||
}
|
||||
|
||||
/// Result of parsing one frontmatter `import` / `导入` line.
|
||||
/// Result of one import map entry (`bind: target` under `import:` / `导入:`).
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ImportLine {
|
||||
File(Import),
|
||||
Member(Use),
|
||||
}
|
||||
|
||||
/// Hint shown when legacy one-line or `>` imports are rejected.
|
||||
pub const NESTED_IMPORT_HINT: &str = "legacy frontmatter import removed; use nested YAML \
|
||||
`import:\\n bind: target` (Chinese: `导入:`) — or run `marqdo migrate imports --write`";
|
||||
|
||||
fn split_frontmatter_key(trimmed: &str) -> Option<(&str, &str)> {
|
||||
let t = trimmed.trim();
|
||||
if t.is_empty() || t.starts_with('#') {
|
||||
return None;
|
||||
}
|
||||
// import lines are handled earlier
|
||||
let Some((key, rest)) = t.split_once(':') else {
|
||||
return None;
|
||||
};
|
||||
@@ -1576,10 +1622,9 @@ fn collect_block_scalar(cur: &mut Cursor<'_>, indicator: &str) -> Result<String>
|
||||
if bt == "---" {
|
||||
break;
|
||||
}
|
||||
// Next top-level key or import ends the block
|
||||
// Next top-level key ends the block
|
||||
if !raw.starts_with(' ') && !raw.starts_with('\t') && !bt.is_empty() {
|
||||
if split_frontmatter_key(bt).is_some() || parse_import_line(bt).ok().flatten().is_some()
|
||||
{
|
||||
if split_frontmatter_key(bt).is_some() {
|
||||
break;
|
||||
}
|
||||
if indicator.is_empty() {
|
||||
@@ -1622,8 +1667,32 @@ fn strip_yaml_indent(line: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// True for removed one-liner `import bind:target` / `导入 bind:target`.
|
||||
pub fn is_legacy_import_oneliner(trimmed: &str) -> bool {
|
||||
let t = trimmed.trim();
|
||||
if t.starts_with("import")
|
||||
&& t.get(6..)
|
||||
.is_some_and(|s| s.starts_with(|c: char| c.is_whitespace()))
|
||||
{
|
||||
let after = t[6..].trim();
|
||||
return after.contains(':') && !after.is_empty();
|
||||
}
|
||||
if let Some(a) = t.strip_prefix("导入") {
|
||||
let a = a.trim_start();
|
||||
// `导入:` is the new nested header, not a one-liner
|
||||
if a.is_empty() || a.starts_with(':') {
|
||||
return false;
|
||||
}
|
||||
return a.contains(':');
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn legacy_frontmatter_import_hint(trimmed: &str) -> Option<String> {
|
||||
let t = trimmed.trim();
|
||||
if is_legacy_import_oneliner(t) {
|
||||
return Some(NESTED_IMPORT_HINT.into());
|
||||
}
|
||||
if !t.starts_with('>') {
|
||||
return None;
|
||||
}
|
||||
@@ -1634,39 +1703,13 @@ fn legacy_frontmatter_import_hint(trimmed: &str) -> Option<String> {
|
||||
|| rest.starts_with("use ")
|
||||
|| rest.starts_with("使用 ");
|
||||
if looks_file || looks_use {
|
||||
return Some(
|
||||
"legacy frontmatter import `> …` is removed; use `import bind:path.mq.md` \
|
||||
or `import bind:lib.member` (Chinese: `导入`)"
|
||||
.into(),
|
||||
);
|
||||
return Some(NESTED_IMPORT_HINT.into());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Parse `import json:lib/json.mq.md` / `导入 fmt:time.format`.
|
||||
/// Returns `Ok(None)` for non-import frontmatter lines (e.g. `title:`).
|
||||
pub fn parse_import_line(trimmed: &str) -> Result<Option<ImportLine>> {
|
||||
let t = trimmed.trim();
|
||||
let after = if t.starts_with("import")
|
||||
&& t.get(6..)
|
||||
.is_some_and(|s| s.starts_with(|c: char| c.is_whitespace()))
|
||||
{
|
||||
t[6..].trim()
|
||||
} else if let Some(a) = t.strip_prefix("导入") {
|
||||
let a = a.trim();
|
||||
if a.is_empty() {
|
||||
bail!("expected `导入 bind:target`");
|
||||
}
|
||||
a
|
||||
} else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let Some((bind_raw, target_raw)) = after.split_once(':') else {
|
||||
bail!("expected `import bind:target` (file `.mq.md` or `lib.member`)");
|
||||
};
|
||||
let bind = bind_raw.trim();
|
||||
let target = target_raw.trim();
|
||||
/// Parse one `bind` / `target` pair from a nested import map entry.
|
||||
pub fn parse_import_binding(bind: &str, target: &str) -> Result<ImportLine> {
|
||||
if bind.is_empty() || !is_simple_bind_name(bind) {
|
||||
bail!("invalid import bind `{bind}`");
|
||||
}
|
||||
@@ -1675,10 +1718,10 @@ pub fn parse_import_line(trimmed: &str) -> Result<Option<ImportLine>> {
|
||||
}
|
||||
|
||||
if target.ends_with(".mq.md") {
|
||||
return Ok(Some(ImportLine::File(Import {
|
||||
return Ok(ImportLine::File(Import {
|
||||
path: target.to_string(),
|
||||
bind: bind.to_string(),
|
||||
})));
|
||||
}));
|
||||
}
|
||||
|
||||
let path: Vec<String> = target
|
||||
@@ -1690,25 +1733,136 @@ pub fn parse_import_line(trimmed: &str) -> Result<Option<ImportLine>> {
|
||||
"import target `{target}` must be a `.mq.md` path or dotted member path (e.g. `time.format`)"
|
||||
);
|
||||
}
|
||||
Ok(Some(ImportLine::Member(Use {
|
||||
Ok(ImportLine::Member(Use {
|
||||
path,
|
||||
bind: bind.to_string(),
|
||||
})))
|
||||
}))
|
||||
}
|
||||
|
||||
fn push_import_line(
|
||||
imports: &mut Vec<Import>,
|
||||
uses: &mut Vec<Use>,
|
||||
entry: ImportLine,
|
||||
span: Span,
|
||||
) -> Result<()> {
|
||||
match entry {
|
||||
ImportLine::File(imp) => {
|
||||
if imports.iter().any(|i| i.bind == imp.bind) || uses.iter().any(|u| u.bind == imp.bind)
|
||||
{
|
||||
return Err(bail_at(
|
||||
None,
|
||||
span,
|
||||
format!("duplicate import bind `{}`", imp.bind),
|
||||
));
|
||||
}
|
||||
imports.push(imp);
|
||||
}
|
||||
ImportLine::Member(u) => {
|
||||
if imports.iter().any(|i| i.bind == u.bind) || uses.iter().any(|x| x.bind == u.bind) {
|
||||
return Err(bail_at(
|
||||
None,
|
||||
span,
|
||||
format!("duplicate import bind `{}`", u.bind),
|
||||
));
|
||||
}
|
||||
uses.push(u);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Format an import entry as the catalog display string `import bind:target`.
|
||||
pub fn format_import_display(line: &ImportLine) -> String {
|
||||
match line {
|
||||
ImportLine::File(imp) => format!("import {}:{}", imp.bind, imp.path),
|
||||
ImportLine::Member(u) => format!("import {}:{}", u.bind, u.path.join(".")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Scan frontmatter for nested `import:` / `导入:` entries (soft; skips legacy / errors).
|
||||
pub fn scan_frontmatter_imports(source: &str) -> Vec<ImportLine> {
|
||||
let source = source.strip_prefix('\u{feff}').unwrap_or(source);
|
||||
let lines: Vec<&str> = source.lines().collect();
|
||||
if lines.first().map(|l| l.trim()) != Some("---") {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut i = 1usize;
|
||||
while i < lines.len() {
|
||||
let t = lines[i].trim();
|
||||
if t == "---" {
|
||||
break;
|
||||
}
|
||||
if let Some((key, rest)) = split_frontmatter_key(t) {
|
||||
if (key == "import" || key == "导入") && rest.is_empty() {
|
||||
i += 1;
|
||||
while i < lines.len() {
|
||||
let raw = lines[i].trim_end_matches(['\r', '\n']);
|
||||
let bt = raw.trim();
|
||||
if bt == "---" {
|
||||
break;
|
||||
}
|
||||
if bt.is_empty() {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if !raw.starts_with(' ') && !raw.starts_with('\t') {
|
||||
break;
|
||||
}
|
||||
let content = strip_yaml_indent(raw);
|
||||
if let Some((bind_raw, target_raw)) = content.split_once(':') {
|
||||
if let Ok(entry) =
|
||||
parse_import_binding(bind_raw.trim(), target_raw.trim())
|
||||
{
|
||||
out.push(entry);
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn is_simple_bind_name(s: &str) -> bool {
|
||||
is_simple_type_name(s)
|
||||
}
|
||||
|
||||
/// Parse a file import line body for catalog / tooling (`bind:path.mq.md` after keyword stripped),
|
||||
/// or the full `import bind:path` / legacy-free form via [`parse_import_line`].
|
||||
/// Parse a catalog-style `import bind:path` display string, or bare `bind:path`.
|
||||
pub fn parse_import_spec(line: &str) -> Option<Import> {
|
||||
match parse_import_line(line).ok()? {
|
||||
Some(ImportLine::File(imp)) => Some(imp),
|
||||
_ => None,
|
||||
let t = line.trim();
|
||||
let body = if t.starts_with("import")
|
||||
&& t.get(6..)
|
||||
.is_some_and(|s| s.starts_with(|c: char| c.is_whitespace()))
|
||||
{
|
||||
t[6..].trim()
|
||||
} else if let Some(a) = t.strip_prefix("导入") {
|
||||
let a = a.trim();
|
||||
if a.is_empty() || a.starts_with(':') {
|
||||
return None;
|
||||
}
|
||||
a
|
||||
} else {
|
||||
t
|
||||
};
|
||||
let (bind, target) = body.split_once(':')?;
|
||||
match parse_import_binding(bind.trim(), target.trim()).ok()? {
|
||||
ImportLine::File(imp) => Some(imp),
|
||||
ImportLine::Member(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rejected API: old one-liner always errors (kept for callers that still probe lines).
|
||||
pub fn parse_import_line(trimmed: &str) -> Result<Option<ImportLine>> {
|
||||
if is_legacy_import_oneliner(trimmed) {
|
||||
bail!("{NESTED_IMPORT_HINT}");
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn is_heading(trimmed: &str) -> bool {
|
||||
parse_heading(trimmed).is_some()
|
||||
}
|
||||
|
||||
+1
-1
@@ -1766,7 +1766,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn structure_omits_imported_lib_bodies() {
|
||||
let src = "---\ntitle: t\nimport text:lib/text.mq.md\n---\n\n# main\n\n> print text=hi\n";
|
||||
let src = "---\ntitle: t\nimport:\n text: lib/text.mq.md\n---\n\n# main\n\n> print text=hi\n";
|
||||
let local = crate::parse::parse_source(src).unwrap();
|
||||
let html = render_module_structure(&local, src);
|
||||
assert!(html.contains("doc-imports") || html.contains("lib/text.mq.md"), "{html}");
|
||||
|
||||
Reference in new issue
Block a user