diff --git a/src/load.rs b/src/load.rs index 252f214..e6416d5 100644 --- a/src/load.rs +++ b/src/load.rs @@ -290,8 +290,9 @@ fn label_error(label: &str, e: anyhow::Error) -> anyhow::Error { /// Effective markup mode declared by the file itself. `` M7 /// /// Looks for `markup: occlusion` (or `标记: 遮蔽`) inside the leading frontmatter -/// block. Files that say nothing keep the process default (classic today), so a -/// repository can migrate file by file without any silent shape change. +/// block. Files that say nothing retain the compatibility default (`classic`) +/// until the full library migration lands. There is no environment/process +/// default: an explicit file declaration always decides its own grammar. /// Parse a standalone source the way the file itself declares (`markup:` in /// frontmatter). The viewer must use this — otherwise an occluded document is /// re-parsed in classic mode and fails. `` M7/M8 diff --git a/src/main.rs b/src/main.rs index e08fe8a..1911e08 100644 --- a/src/main.rs +++ b/src/main.rs @@ -108,6 +108,11 @@ enum Commands { /// Emit diagnostics as JSON on stderr (machine-readable; AI/MLSP 面). #[arg(long)] json: bool, + + /// Parse unmarked files using the legacy `[key](collection)` grammar. + /// Explicit per-file `markup:` still wins; this flag is transitional. + #[arg(long)] + legacy_markup: bool, }, /// Static contract cross-check (渐进式契约): drift, unknown types, misplaced tables Check { @@ -122,6 +127,10 @@ enum Commands { /// Also check prose above `>` calls (implicit occlusion; fuzzy, off by default) #[arg(long)] implicit_labels: bool, + + /// Parse an unmarked file with the legacy grammar for migration review. + #[arg(long)] + legacy_markup: bool, }, /// Occlusion label queries: pending stubs (built-in words) or keyword search Labels { @@ -483,20 +492,7 @@ enum ViewAction { }, } -/// `` M2: `MARQDO_MARKUP=occlusion` enables `[描述](实现)` (purity mode). -/// Default stays `classic` so legacy `[键](集合)` keeps its meaning until M7. -fn init_markup_from_env() { - if let Ok(v) = std::env::var("MARQDO_MARKUP") { - let m = match v.trim().to_ascii_lowercase().as_str() { - "occlusion" | "purity" | "1" | "on" | "true" => marqdo::parse::expr::Markup::Occlusion, - _ => marqdo::parse::expr::Markup::Classic, - }; - marqdo::parse::expr::set_markup_default(m); - } -} - fn main() -> ExitCode { - init_markup_from_env(); let cli = Cli::parse(); let json_errors = matches!( &cli.command, @@ -633,6 +629,7 @@ fn try_main(cli: Cli) -> Result { binds, fs_root, json: _, + legacy_markup, } => { let path = file.unwrap_or_else(|| PathBuf::from("index.mq.md")); let stdin_lines = match stdin_file { @@ -672,15 +669,28 @@ fn try_main(cli: Cli) -> Result { if dump_all { opts.backend = backend.into(); } - marqdo::run_file(&path, &opts)?; + if legacy_markup { + marqdo::parse::expr::with_markup(marqdo::parse::expr::Markup::Classic, || { + marqdo::run_file(&path, &opts) + })?; + } else { + marqdo::run_file(&path, &opts)?; + } Ok(0) } Commands::Check { file, json, implicit_labels, + legacy_markup, } => { - let diags = marqdo::check::check_path_opts(&file, implicit_labels)?; + let diags = if legacy_markup { + marqdo::parse::expr::with_markup(marqdo::parse::expr::Markup::Classic, || { + marqdo::check::check_path_opts(&file, implicit_labels) + })? + } else { + marqdo::check::check_path_opts(&file, implicit_labels)? + }; let mut errors = 0i32; for d in &diags { if matches!(d.severity, marqdo::diagnostics::Severity::Error) { diff --git a/src/migrate.rs b/src/migrate.rs index 519cd50..2137eb6 100644 --- a/src/migrate.rs +++ b/src/migrate.rs @@ -33,7 +33,7 @@ fn has_marker(source: &str) -> bool { } let lower = t.to_ascii_lowercase(); if lower.starts_with("markup:") || t.starts_with("标记:") { - return true; + return lower.contains("occlusion") || lower.contains("purity") || t.contains("遮蔽") || t.contains("纯度"); } } false @@ -43,6 +43,21 @@ fn add_marker(source: &str) -> String { if has_marker(source) { return source.to_string(); } + // A classic marker is an explicit request to migrate; replace it rather + // than adding conflicting keys to the same frontmatter block. + if source.starts_with("---\n") { + let mut lines: Vec = source.lines().map(str::to_string).collect(); + for (index, line) in lines.iter_mut().enumerate() { + let lower = line.trim().to_ascii_lowercase(); + if lower.starts_with("markup:") || line.trim().starts_with("标记:") { + *line = "markup: occlusion".to_string(); + let mut out = lines.join("\n"); + if source.ends_with('\n') { out.push('\n'); } + return out; + } + if line.trim() == "---" && index != 0 { break; } + } + } if let Some(rest) = source.strip_prefix("---\n") { format!("---\nmarkup: occlusion\n{rest}") } else { diff --git a/src/parse/expr.rs b/src/parse/expr.rs index 7109726..48ace79 100644 --- a/src/parse/expr.rs +++ b/src/parse/expr.rs @@ -10,9 +10,10 @@ pub fn parse_expr(input: &str) -> Result { /// Markup mode for `[描述](实现)` vs the legacy `[键](集合)` index. `` M2 /// -/// `Classic` keeps today's index semantics; `Occlusion` reads the same shape as -/// an occlusion. The default is `Classic` until M7 migrates the corpus and flips -/// the gate (otherwise every legacy index would silently change meaning). +/// `Classic` keeps the legacy index semantics; `Occlusion` reads the same shape +/// as an occlusion. The compatibility default remains `Classic` until every +/// shipped library has an explicit per-file declaration; new syntax opts in +/// with `markup: occlusion`. No environment/process switch exists. #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] pub enum Markup { #[default] @@ -20,28 +21,17 @@ pub enum Markup { Occlusion, } -static MARKUP: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); - -/// Set the process-wide default markup mode (CLI / tests). -pub fn set_markup_default(m: Markup) { - MARKUP.store( - match m { - Markup::Classic => 0, - Markup::Occlusion => 1, - }, - std::sync::atomic::Ordering::Relaxed, - ); -} - thread_local! { - /// Per-module override (`markup:` in frontmatter) — wins over the process default. + /// Scoped parser context for loader/migration calls. It is never mutated + /// from environment/process configuration, so two project files cannot + /// silently change each other's grammar. static MARKUP_OVERRIDE: std::cell::Cell> = const { std::cell::Cell::new(None) }; } /// Run `f` with `markup` as the effective mode for everything parsed inside. /// -/// Frontmatter `markup: occlusion` uses this so that one process can load files -/// in different modes (imports!). `` M7 +/// Used by the loader and migration verifier to give one parse an explicit +/// mode. Imported files establish their own nested scope from frontmatter. pub fn with_markup(markup: Markup, f: impl FnOnce() -> T) -> T { let saved = MARKUP_OVERRIDE.with(|c| c.replace(Some(markup))); let out = f(); @@ -53,10 +43,7 @@ pub fn markup_default() -> Markup { if let Some(m) = MARKUP_OVERRIDE.with(|c| c.get()) { return m; } - match MARKUP.load(std::sync::atomic::Ordering::Relaxed) { - 1 => Markup::Occlusion, - _ => Markup::Classic, - } + Markup::Classic } /// Italic / bold value syntax: bare words are variables; text needs `"…"` / `'…'`. @@ -1921,7 +1908,7 @@ mod tests { #[test] fn link_shaped_index() { - let e = parse_expr_prefer_var("[拿铁](菜单)").unwrap(); + let e = parse_expr_markup("[拿铁](菜单)", true, Markup::Classic).unwrap(); match e { Expr::Index { base, label } => { assert!(matches!(base.as_ref(), Expr::Var(n) if n == "菜单")); @@ -1929,7 +1916,7 @@ mod tests { } other => panic!("expected link Index, got {other:?}"), } - let e = parse_expr_prefer_var("[`名`](菜单)").unwrap(); + let e = parse_expr_markup("[`名`](菜单)", true, Markup::Classic).unwrap(); match e { Expr::Index { base, label } => { assert!(matches!(base.as_ref(), Expr::Var(n) if n == "菜单")); @@ -1937,7 +1924,7 @@ mod tests { } other => panic!("expected dynamic link Index, got {other:?}"), } - let e = parse_expr_prefer_var("[1](篮子)").unwrap(); + let e = parse_expr_markup("[1](篮子)", true, Markup::Classic).unwrap(); assert!(matches!( e, Expr::Index { @@ -1945,7 +1932,7 @@ mod tests { .. } if s == "1" )); - let e = parse_expr_prefer_var("[1]([苹果](货架))").unwrap(); + let e = parse_expr_markup("[1]([苹果](货架))", true, Markup::Classic).unwrap(); match e { Expr::Index { base, label } => { assert_eq!(label, IndexKey::Lit("1".into())); @@ -2015,7 +2002,7 @@ mod bracket_call_tests { #[test] fn link_index_not_bracket_call() { - let e = parse_expr_prefer_var("[拿铁](菜单)").unwrap(); + let e = parse_expr_markup("[拿铁](菜单)", true, Markup::Classic).unwrap(); assert!(matches!(e, Expr::Index { .. })); } diff --git a/tests/contract_ablation.rs b/tests/contract_ablation.rs index d92bc4c..b9a104d 100644 --- a/tests/contract_ablation.rs +++ b/tests/contract_ablation.rs @@ -164,6 +164,10 @@ const BIND_BARE: &str = "\ "; const KEY_WRONG: &str = "\ +--- +markup: classic +--- + # main | 字段 | 类型 | 可空 | @@ -180,6 +184,10 @@ const KEY_WRONG: &str = "\ "; const KEY_RIGHT: &str = "\ +--- +markup: classic +--- + # main | 字段 | 类型 | 可空 | @@ -196,6 +204,10 @@ const KEY_RIGHT: &str = "\ "; const KEY_BARE: &str = "\ +--- +markup: classic +--- + # main `用户` = diff --git a/tests/drift_drill.rs b/tests/drift_drill.rs index 60d65cd..27a6eed 100644 --- a/tests/drift_drill.rs +++ b/tests/drift_drill.rs @@ -215,16 +215,21 @@ fn drills() -> Vec { ] } +fn classic(src: &str) -> String { + format!("---\nmarkup: classic\n---\n\n{src}") +} + #[test] fn drift_cases_all_reported() { let all = drills(); let total = all.len(); let mut caught = 0; for d in &all { + let src = classic(d.src); let diags = if d.runtime { - diagnose(Verify::Run(d.code), d.src, &format!("drift_{}", d.name)) + diagnose(Verify::Run(d.code), &src, &format!("drift_{}", d.name)) } else { - static_diags(d.src) + static_diags(&src) }; let hit = diags.iter().any(|v| v["code"].as_str() == Some(d.code)); assert!( @@ -240,15 +245,16 @@ fn drift_cases_all_reported() { #[test] fn negative_controls_zero_false_positives() { // 1. 被绑定的 `字段|类型|可空` 数据表 = 数据(web_db_migration 式)——绝不能被当契约吃掉。 - let diags = diagnose(Verify::Run(""), SRC_BOUND_DATA, "drill_neg_bound"); + let diags = diagnose(Verify::Run(""), &classic(SRC_BOUND_DATA), "drill_neg_bound"); assert!( diags.iter().all(|v| !v["code"].as_str().unwrap_or("").starts_with("contract.")), "绑定数据表被误当契约: {diags:?}" ); // 2. 干净契约 + 对值 ⇒ 静态零诊断、运行零诊断。 - let diags = static_diags(SRC_OK); + let src_ok = classic(SRC_OK); + let diags = static_diags(&src_ok); assert!(diags.is_empty(), "干净契约被误报(静态): {diags:?}"); - let diags = diagnose(Verify::Run(""), SRC_OK, "drill_neg_ok"); + let diags = diagnose(Verify::Run(""), &src_ok, "drill_neg_ok"); assert!(diags.is_empty(), "干净契约被误报(运行): {diags:?}"); eprintln!("负对照误报 = 0/2 = 0%"); } diff --git a/tests/migrate.rs b/tests/migrate.rs index c04a272..308a299 100644 --- a/tests/migrate.rs +++ b/tests/migrate.rs @@ -21,7 +21,7 @@ fn fixture() -> (std::path::PathBuf, String) { let dir = std::env::temp_dir().join(format!("marqdo-migrate-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("demo.mq.md"); - let src = "---\nimport json:lib/json.mq.md\n---\n\n# main\n\n`表` = > json.parse text={\"键\":\"值\"}\n**a = [键](`表`)**\n> print text=\"a=\" + `a`\n"; + let src = "---\nmarkup: classic\nimport json:lib/json.mq.md\n---\n\n# main\n\n`表` = > json.parse text={\"键\":\"值\"}\n**a = [键](`表`)**\n> print text=\"a=\" + `a`\n"; std::fs::write(&path, src).unwrap(); (path, src.to_string()) } diff --git a/tests/occlusion.rs b/tests/occlusion.rs index 33362c0..9f28cf4 100644 --- a/tests/occlusion.rs +++ b/tests/occlusion.rs @@ -1,7 +1,5 @@ -//! `` M2: occlusion syntax end-to-end (CLI + `MARQDO_MARKUP=occlusion`). -//! -//! The mode flag keeps `[键](集合)` (classic index) intact until M7 migrates the -//! corpus; these tests pin both sides of the switch. +//! Occlusion syntax end-to-end. Grammar is declared by each document, not a +//! process environment variable, so imports and MLSP requests stay isolated. use std::process::Command; @@ -27,21 +25,17 @@ fn occlusion_value_is_payload() { } #[test] -fn occlusion_off_keeps_classic_index() { +fn migrated_index_uses_access_without_a_process_mode() { let (code, stdout, stderr) = run("tests/occlusion/classic-index.mq.md", None); assert_eq!(code, 0, "stderr={stderr}"); assert_eq!(stdout.trim_end(), "值"); } #[test] -fn occlusion_mode_rejects_legacy_index_shape() { - // In occlusion mode `[键](集合)` is read as an occlusion whose payload is the - // collection — i.e. it returns the *whole* map, not the member. This is why - // M7 must migrate before flipping the default; here we only pin that the - // shape no longer means "index". - let (code, stdout, stderr) = run("tests/occlusion/classic-index.mq.md", Some("occlusion")); +fn declared_occlusion_ignores_legacy_environment_switches() { + let (code, stdout, stderr) = run("tests/occlusion/classic-index.mq.md", Some("classic")); assert_eq!(code, 0, "stderr={stderr}"); - assert_ne!(stdout.trim_end(), "值", "occlusion mode must not index"); + assert_eq!(stdout.trim_end(), "值"); } // ---- M2.5: label diagnostics (`label.missing` / `label.empty_payload`) ---- @@ -195,10 +189,11 @@ fn mlsp_session(reqs: &[&str]) -> Vec { } fn repair_req(src: &str, new_line: &str) -> String { - let src_json = serde_json::to_string(src).unwrap(); + let src = format!("---\nmarkup: occlusion\n---\n\n{src}"); + let src_json = serde_json::to_string(&src).unwrap(); let line_json = serde_json::to_string(new_line).unwrap(); format!( - r#"{{"id":1,"method":"repair_apply","params":{{"source":{src_json},"ranges":[[3,3]],"edits":[{{"op":"replace","line":3,"text":{line_json}}}],"check_labels":true}}}}"# + r#"{{"id":1,"method":"repair_apply","params":{{"source":{src_json},"ranges":[[7,7]],"edits":[{{"op":"replace","line":7,"text":{line_json}}}],"check_labels":true}}}}"# ) } diff --git a/tests/occlusion/classic-index.mq.md b/tests/occlusion/classic-index.mq.md index b790e35..722fd5c 100644 --- a/tests/occlusion/classic-index.mq.md +++ b/tests/occlusion/classic-index.mq.md @@ -1,10 +1,11 @@ --- title: classic index still works +markup: occlusion import json:lib/json.mq.md --- # main **表 = > json.parse text={"键":"值"}** -**v = [键](`表`)** +**v = access(`表`, "键")** > print text=`v`