feat: migrate corpus to file-scoped occlusion

This commit is contained in:
cflmy committed 2026-10-23 12:45:01 +00:00
1 parent c773503938
commit aea86746e7
485 files changed
+1160 -340

No files matched your search

+15 -17
View File
@@ -14,7 +14,10 @@ use crate::parse::parse_source;
/// Load `path` and recursively bind imported modules (no flat merge).
pub fn load_module(path: &Path) -> Result<Module> {
load_module_with_ctx(path, &BindingContext::from_binds(&[], cwd_for_path(Some(path))))
load_module_with_ctx(
path,
&BindingContext::from_binds(&[], cwd_for_path(Some(path))),
)
}
/// Load with BindingContext (CLI `--bind`, cwd for `sys.cwd`).
@@ -28,9 +31,7 @@ fn load_module_inner(
visited: &mut HashSet<PathBuf>,
ctx: &BindingContext,
) -> Result<Module> {
let canon = path
.canonicalize()
.unwrap_or_else(|_| path.to_path_buf());
let canon = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
if !visited.insert(canon.clone()) {
bail!("circular import involving {}", path.display());
}
@@ -86,7 +87,9 @@ fn read_module_source(path: &Path) -> Result<String> {
}
fn read_embedded_for_path(path: &Path) -> Option<String> {
lib_remainder(path).as_deref().and_then(embedded_lib::read_file)
lib_remainder(path)
.as_deref()
.and_then(embedded_lib::read_file)
}
fn lib_remainder(path: &Path) -> Option<String> {
@@ -156,10 +159,7 @@ pub fn resolve_import(from_dir: &Path, rel: &str) -> Result<PathBuf> {
if let Some(p) = find_in_ancestor_dir(from_dir, "ext", rest) {
return Ok(p);
}
let mut msg = format!(
"cannot resolve import `{rel}` from {}",
from_dir.display()
);
let mut msg = format!("cannot resolve import `{rel}` from {}", from_dir.display());
#[cfg(feature = "cli")]
{
let user_ext = crate::ext_cli::default_user_ext_dir();
@@ -290,9 +290,10 @@ fn label_error(label: &str, e: anyhow::Error) -> anyhow::Error {
/// Effective markup mode declared by the file itself. `<TAB>` M7
///
/// Looks for `markup: occlusion` (or `标记: 遮蔽`) inside the leading frontmatter
/// 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.
/// block. Unmarked sources use the new `occlusion` default; a legacy source
/// must opt in with `markup: classic` or be run through `--legacy-markup` for
/// the transition cycle. 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. `<TAB>` M7/M8
@@ -409,11 +410,8 @@ mod tests {
let prev = env::var_os("MARQDO_EXT");
env::remove_var("MARQDO_EXT");
// Unique path so cwd/ext cannot satisfy the import.
let err = resolve_import(
Path::new("/tmp"),
"ext/__gap12_missing__/nope.mq.md",
)
.unwrap_err();
let err =
resolve_import(Path::new("/tmp"), "ext/__gap12_missing__/nope.mq.md").unwrap_err();
let msg = format!("{err:#}");
match prev {
Some(v) => env::set_var("MARQDO_EXT", v),
+118 -30
View File
@@ -57,6 +57,10 @@ enum MigrateAction {
/// Actually rewrite files (default: dry run)
#[arg(long)]
write: bool,
/// Add `markup: occlusion` to every unmarked file, including files
/// with no legacy index. Use this when migrating a shipped library.
#[arg(long)]
mark: bool,
/// One JSON object on stdout
#[arg(long)]
json: bool,
@@ -550,7 +554,9 @@ fn resolve_knowledge_reference<'a>(
anyhow::bail!("knowledge reference `{reference}` must be a dotted value path or mq:// URI");
};
if !call.args.is_empty() {
anyhow::bail!("knowledge resolve only binds a zero-argument path; `{reference}` has arguments");
anyhow::bail!(
"knowledge resolve only binds a zero-argument path; `{reference}` has arguments"
);
}
let path = call.path.ok_or_else(|| {
anyhow::anyhow!("knowledge reference `{reference}` must start with an imported module bind")
@@ -566,7 +572,9 @@ fn resolve_knowledge_reference<'a>(
.imports
.iter()
.find(|item| item.bind == path[0])
.ok_or_else(|| anyhow::anyhow!("unknown import bind `{}` in {}", path[0], from.display()))?;
.ok_or_else(|| {
anyhow::anyhow!("unknown import bind `{}` in {}", path[0], from.display())
})?;
let base = from.parent().unwrap_or_else(|| std::path::Path::new("."));
let imported_path = marqdo::load::resolve_import(base, &imported.path)?;
let imported_path = imported_path.canonicalize().unwrap_or(imported_path);
@@ -872,26 +880,36 @@ fn try_main(cli: Cli) -> Result<i32> {
Ok(0)
}
Commands::Migrate { action } => match action {
MigrateAction::Labels { paths, write, json } => {
MigrateAction::Labels {
paths,
write,
mark,
json,
} => {
let mut reports = Vec::new();
for p in &paths {
reports.extend(marqdo::migrate::migrate_path(p, write)?);
reports.extend(marqdo::migrate::migrate_path_with_options(p, write, mark)?);
}
let (mut idx, mut loops, mut applied) = (0usize, 0usize, 0usize);
let (mut idx, mut loops, mut marked, mut applied) =
(0usize, 0usize, 0usize, 0usize);
for r in &reports {
idx += r.indexes;
loops += r.loops;
marked += usize::from(r.mode_marked);
applied += usize::from(r.applied);
}
if json {
let arr: Vec<serde_json::Value> = reports
.iter()
.filter(|r| r.indexes > 0 || r.loops > 0 || r.note.is_some())
.filter(|r| {
r.indexes > 0 || r.loops > 0 || r.mode_marked || r.note.is_some()
})
.map(|r| {
serde_json::json!({
"file": r.file.display().to_string(),
"indexes": r.indexes,
"loops": r.loops,
"mode_marked": r.mode_marked,
"applied": r.applied,
"note": r.note,
})
@@ -900,7 +918,7 @@ fn try_main(cli: Cli) -> Result<i32> {
println!("{}", serde_json::Value::Array(arr));
} else {
for r in &reports {
if r.indexes == 0 && r.loops == 0 {
if r.indexes == 0 && r.loops == 0 && !r.mode_marked {
continue;
}
let state = if r.applied {
@@ -911,10 +929,15 @@ fn try_main(cli: Cli) -> Result<i32> {
"would change"
};
println!(
"{} indexes={} loops={} {}{}",
"{} indexes={} loops={} mode={} {}{}",
r.file.display(),
r.indexes,
r.loops,
if r.mode_marked {
"occlusion"
} else {
"unchanged"
},
state,
r.note
.as_ref()
@@ -923,7 +946,7 @@ fn try_main(cli: Cli) -> Result<i32> {
);
}
println!(
"migrate labels: {idx} index, {loops} loop, {applied} file written{}",
"migrate labels: {idx} index, {loops} loop, {marked} explicit mode, {applied} file written{}",
if write {
""
} else {
@@ -942,9 +965,10 @@ fn try_main(cli: Cli) -> Result<i32> {
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
if r.note
.as_ref()
.is_some_and(|n| n != "no legacy import one-liners")
&& r.bindings == 0
{
problems += 1;
}
@@ -952,7 +976,12 @@ fn try_main(cli: Cli) -> Result<i32> {
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"))
.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(),
@@ -965,7 +994,11 @@ fn try_main(cli: Cli) -> Result<i32> {
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") {
if r.bindings == 0
&& r.note
.as_ref()
.is_some_and(|n| n == "no legacy import one-liners")
{
continue;
}
if r.bindings == 0 {
@@ -1155,7 +1188,9 @@ fn try_main(cli: Cli) -> Result<i32> {
"{}\n {}{} {} · module {}\n {}:{}",
item.id,
item.kind.as_str(),
item.callable.map(|kind| format!(" ({})", kind.as_str())).unwrap_or_default(),
item.callable
.map(|kind| format!(" ({})", kind.as_str()))
.unwrap_or_default(),
item.declaration_path.join("."),
item.module,
item.source.display(),
@@ -1172,15 +1207,17 @@ fn try_main(cli: Cli) -> Result<i32> {
Ok(0)
}
KnowledgeAction::Resolve { reference, from } => {
let from = from.as_deref().or_else(|| path.is_file().then_some(path.as_path()));
let from = from
.as_deref()
.or_else(|| path.is_file().then_some(path.as_path()));
let index = marqdo::sema::ProjectIndex::build(if path.is_dir() {
marqdo::project::ProjectRoot::new(&path)?
} else {
marqdo::project::ProjectRoot::discover(&path)?
})?;
let symbol = resolve_knowledge_reference(&index, &reference, from)?;
let instance_only = symbol.callable
== Some(marqdo::sema::CallableKind::InstanceMethod);
let instance_only =
symbol.callable == Some(marqdo::sema::CallableKind::InstanceMethod);
if json {
println!(
"{}",
@@ -1209,32 +1246,83 @@ fn try_main(cli: Cli) -> Result<i32> {
}
KnowledgeAction::Lock { update, strict } => {
let semantic_root = if path.is_file() {
path.parent().unwrap_or_else(|| std::path::Path::new(".")).to_path_buf()
path.parent()
.unwrap_or_else(|| std::path::Path::new("."))
.to_path_buf()
} else {
path.clone()
};
let compilation = marqdo::sema::compile_project(&marqdo::sema::CompileOptions {
project_root: semantic_root,
entry: path.is_file().then(|| path.clone()),
lock_mode: if strict { marqdo::sema::LockMode::Strict } else { marqdo::sema::LockMode::Check },
})?;
let compilation =
marqdo::sema::compile_project(&marqdo::sema::CompileOptions {
project_root: semantic_root,
entry: path.is_file().then(|| path.clone()),
lock_mode: if strict {
marqdo::sema::LockMode::Strict
} else {
marqdo::sema::LockMode::Check
},
})?;
if update {
marqdo::sema::update_links_lock(&out, &compilation.semantics)?;
let body = serde_json::json!({"schema_version": 1, "status": "updated", "path": out.join("links.lock.json")});
if json { println!("{body}"); } else { println!("knowledge lock updated: {}", out.join("links.lock.json").display()); }
if json {
println!("{body}");
} else {
println!(
"knowledge lock updated: {}",
out.join("links.lock.json").display()
);
}
Ok(0)
} else {
let report = marqdo::sema::check_links_lock(&out, &compilation.semantics)?;
if json { println!("{}", report.to_json()); } else { println!("knowledge lock: {}", report.status); for id in report.missing.iter().chain(report.changed.iter()).chain(report.removed.iter()) { println!(" {id}"); } }
if json {
println!("{}", report.to_json());
} else {
println!("knowledge lock: {}", report.status);
for id in report
.missing
.iter()
.chain(report.changed.iter())
.chain(report.removed.iter())
{
println!(" {id}");
}
}
Ok(if strict && !report.is_clean() { 3 } else { 0 })
}
}
KnowledgeAction::Impact { query } => {
let semantic_root = if path.is_file() { path.parent().unwrap_or_else(|| std::path::Path::new(".")).to_path_buf() } else { path.clone() };
let compilation = marqdo::sema::compile_project(&marqdo::sema::CompileOptions { project_root: semantic_root, entry: path.is_file().then(|| path.clone()), lock_mode: marqdo::sema::LockMode::Off })?;
let semantic_root = if path.is_file() {
path.parent()
.unwrap_or_else(|| std::path::Path::new("."))
.to_path_buf()
} else {
path.clone()
};
let compilation =
marqdo::sema::compile_project(&marqdo::sema::CompileOptions {
project_root: semantic_root,
entry: path.is_file().then(|| path.clone()),
lock_mode: marqdo::sema::LockMode::Off,
})?;
let report = marqdo::sema::semantic_impact(&compilation.semantics, &query);
if json { println!("{report}"); } else { for item in report["affected"].as_array().into_iter().flatten() { println!("{} {}", item["artifact_id"].as_str().unwrap_or(""), item["display_name"].as_str().unwrap_or("")); } }
Ok(if report["resolved"].as_bool() == Some(true) { 0 } else { 1 })
if json {
println!("{report}");
} else {
for item in report["affected"].as_array().into_iter().flatten() {
println!(
"{} {}",
item["artifact_id"].as_str().unwrap_or(""),
item["display_name"].as_str().unwrap_or("")
);
}
}
Ok(if report["resolved"].as_bool() == Some(true) {
0
} else {
1
})
}
KnowledgeAction::Preflight {
task,
+65 -20
View File
@@ -20,6 +20,9 @@ pub struct FileReport {
pub file: PathBuf,
pub indexes: usize,
pub loops: usize,
/// Whether this file will receive (or already has) an explicit
/// `markup: occlusion` declaration.
pub mode_marked: bool,
pub applied: bool,
pub note: Option<String>,
}
@@ -45,7 +48,10 @@ fn has_marker(source: &str) -> bool {
}
let lower = t.to_ascii_lowercase();
if lower.starts_with("markup:") || t.starts_with("标记:") {
return lower.contains("occlusion") || lower.contains("purity") || t.contains("遮蔽") || t.contains("纯度");
return lower.contains("occlusion")
|| lower.contains("purity")
|| t.contains("遮蔽")
|| t.contains("纯度");
}
}
false
@@ -64,10 +70,14 @@ fn add_marker(source: &str) -> String {
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'); }
if source.ends_with('\n') {
out.push('\n');
}
return out;
}
if line.trim() == "---" && index != 0 { break; }
if line.trim() == "---" && index != 0 {
break;
}
}
}
if let Some(rest) = source.strip_prefix("---\n") {
@@ -162,10 +172,7 @@ fn rewrite_one_innermost(line: &str) -> Option<String> {
} else {
quote_key(k)
};
let replaced = format!(
"[{label}](access({}, {key_arg}))",
coll.trim()
);
let replaced = format!("[{label}](access({}, {key_arg}))", coll.trim());
let mut out = String::new();
out.extend(chars[..i].iter());
out.push_str(&replaced);
@@ -284,9 +291,7 @@ fn rewrite_loop(line: &str) -> Option<String> {
}
let indent = &line[..line.len() - trimmed.len()];
let shown = item.trim_matches('`').to_string();
Some(format!(
"{indent}- [{shown}](遍历 {coll} 为 {item})"
))
Some(format!("{indent}- [{shown}](遍历 {coll} 为 {item})"))
}
fn says_foreach(s: &str) -> bool {
@@ -310,7 +315,9 @@ fn denorm_expr(expr: &Expr) -> Expr {
_ => return expr.clone(),
};
let key_label = match key {
Expr::Literal(crate::ast::Literal::Text(t)) if t == label => Some(IndexKey::Lit(t.clone())),
Expr::Literal(crate::ast::Literal::Text(t)) if t == label => {
Some(IndexKey::Lit(t.clone()))
}
Expr::Var(v) if v == label => Some(IndexKey::Var(v.clone())),
_ => None,
};
@@ -401,7 +408,10 @@ fn denorm_stmt(stmt: &Stmt) -> Stmt {
},
})
.collect();
Stmt::Call { call: c, span: *span }
Stmt::Call {
call: c,
span: *span,
}
}
Stmt::Branch { arms, span } => Stmt::Branch {
arms: arms
@@ -477,22 +487,40 @@ fn shape(module: &Module) -> String {
/// Migrate one file. `write=false` performs a dry run (still fully verified).
pub fn migrate_file(path: &Path, write: bool) -> anyhow::Result<FileReport> {
migrate_file_with_options(path, write, false)
}
/// Migrate one file and, when `mark_all` is set, give a file that has no
/// legacy index an explicit new-syntax declaration too. This is the mode used
/// for shipped libraries: their behavior must not depend on the process
/// default even if they happen not to contain a link-shaped index today.
pub fn migrate_file_with_options(
path: &Path,
write: bool,
mark_all: bool,
) -> anyhow::Result<FileReport> {
let source = std::fs::read_to_string(path)?;
let mut report = FileReport {
file: path.to_path_buf(),
indexes: 0,
loops: 0,
mode_marked: false,
applied: false,
note: None,
};
if has_marker(&source) {
report.mode_marked = true;
report.note = Some("already marked `markup: occlusion`".into());
return Ok(report);
}
// The original must be readable in classic mode (that is what it means today).
// Migration is deliberately syntax-only. Resolving imports here makes a
// library's safe local rewrite depend on the host checkout, unavailable
// plugins, or a transitive dependency that is itself being migrated.
// Import resolution and both execution backends are verified afterwards by
// the repository migration suite.
let original = crate::parse::expr::with_markup(crate::parse::expr::Markup::Classic, || {
crate::load::load_module(path)
crate::parse::parse_source(&source)
})?;
let classified = crate::lex::classify_source(&source);
@@ -516,7 +544,7 @@ pub fn migrate_file(path: &Path, write: bool) -> anyhow::Result<FileReport> {
lines[idx] = new_line;
}
}
if report.indexes == 0 && report.loops == 0 {
if report.indexes == 0 && report.loops == 0 && !mark_all {
report.note = Some("no legacy index or loop".into());
return Ok(report);
}
@@ -526,11 +554,12 @@ pub fn migrate_file(path: &Path, write: bool) -> anyhow::Result<FileReport> {
body.push('\n');
}
let migrated = add_marker(&body);
report.mode_marked = true;
// Prove equivalence: the migrated file, parsed in occlusion mode and
// denormalized, must be structurally identical to the original.
let reparsed = crate::parse::expr::with_markup(crate::parse::expr::Markup::Occlusion, || {
crate::load::load_module_from_source(&migrated)
crate::parse::parse_source(&migrated)
})?;
if std::env::var("MARQDO_MIGRATE_DEBUG").is_ok() {
eprintln!("ORIG: {}", shape(&original));
@@ -550,15 +579,25 @@ pub fn migrate_file(path: &Path, write: bool) -> anyhow::Result<FileReport> {
/// Recursively migrate every `*.mq.md` under `path`.
pub fn migrate_path(path: &Path, write: bool) -> anyhow::Result<Vec<FileReport>> {
migrate_path_with_options(path, write, false)
}
/// Recursive counterpart of [`migrate_file_with_options`].
pub fn migrate_path_with_options(
path: &Path,
write: bool,
mark_all: bool,
) -> anyhow::Result<Vec<FileReport>> {
let files = crate::migrate::collect_files(path);
let mut out = Vec::new();
for f in files {
match migrate_file(&f, write) {
match migrate_file_with_options(&f, write, mark_all) {
Ok(r) => out.push(r),
Err(e) => out.push(FileReport {
file: f,
indexes: 0,
loops: 0,
mode_marked: false,
applied: false,
note: Some(format!("load failed: {e:#}")),
}),
@@ -731,12 +770,17 @@ pub fn migrate_imports_path(path: &Path, write: bool) -> anyhow::Result<Vec<Impo
/// Collect `*.mq.md` under `path` (file → itself).
pub fn collect_files(path: &Path) -> Vec<PathBuf> {
fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(rd) = std::fs::read_dir(dir) else { return };
let Ok(rd) = std::fs::read_dir(dir) else {
return;
};
for e in rd.flatten() {
let p = e.path();
let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
if p.is_dir() {
if matches!(name, "target" | "dist" | "node_modules" | ".git" | ".marqdo") {
if matches!(
name,
"target" | "dist" | "node_modules" | ".git" | ".marqdo"
) {
continue;
}
walk(&p, out);
@@ -760,7 +804,8 @@ mod tests {
#[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 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"));
+99 -47
View File
@@ -11,13 +11,14 @@ pub fn parse_expr(input: &str) -> Result<Expr> {
/// Markup mode for `[描述](实现)` vs the legacy `[键](集合)` index. `<TAB>` M2
///
/// `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.
/// as an occlusion. Every shipped module declares its mode and new/unmarked
/// sources use `Occlusion`. The legacy grammar is available only through an
/// explicit `markup: classic` declaration or the one-cycle CLI compatibility
/// flag. No environment/process switch exists.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Markup {
#[default]
Classic,
#[default]
Occlusion,
}
@@ -43,7 +44,7 @@ pub fn markup_default() -> Markup {
if let Some(m) = MARKUP_OVERRIDE.with(|c| c.get()) {
return m;
}
Markup::Classic
Markup::Occlusion
}
/// Italic / bold value syntax: bare words are variables; text needs `"…"` / `'…'`.
@@ -160,7 +161,10 @@ fn is_text_only_div_chain(e: &Expr) -> bool {
op: BinaryOp::Div,
left,
right,
} => is_text_only_div_chain(left) && matches!(right.as_ref(), Expr::Literal(Literal::Text(_))),
} => {
is_text_only_div_chain(left)
&& matches!(right.as_ref(), Expr::Literal(Literal::Text(_)))
}
_ => false,
}
}
@@ -196,7 +200,10 @@ fn has_hyphenated_prose(s: &str) -> bool {
continue;
}
// `none-falsy` / `Hello-World` — not `` `n` - 1 ``
if left.is_alphanumeric() || right.is_alphanumeric() || !left.is_ascii() || !right.is_ascii()
if left.is_alphanumeric()
|| right.is_alphanumeric()
|| !left.is_ascii()
|| !right.is_ascii()
{
return true;
}
@@ -598,7 +605,10 @@ impl<'a> Parser<'a> {
self.i += '空'.len_utf8();
return Ok(Expr::Literal(Literal::None));
}
if self.peek_char().map(|c| c.is_ascii_digit()).unwrap_or(false)
if self
.peek_char()
.map(|c| c.is_ascii_digit())
.unwrap_or(false)
|| (self.peek_char() == Some('.')
&& self
.rest()
@@ -608,13 +618,21 @@ impl<'a> Parser<'a> {
.unwrap_or(false))
{
let start = self.i;
while self.peek_char().map(|c| c.is_ascii_digit()).unwrap_or(false) {
while self
.peek_char()
.map(|c| c.is_ascii_digit())
.unwrap_or(false)
{
self.bump_char();
}
if self.peek_char() == Some('.') {
self.bump_char();
let frac_start = self.i;
while self.peek_char().map(|c| c.is_ascii_digit()).unwrap_or(false) {
while self
.peek_char()
.map(|c| c.is_ascii_digit())
.unwrap_or(false)
{
self.bump_char();
}
// Require at least one digit on one side of the dot.
@@ -633,7 +651,10 @@ impl<'a> Parser<'a> {
}
// Bare identifier / text word. If immediately followed by `[^…]`, treat as
// variable + footnote index (exemption: ticks optional when `[^` marks the slot).
if self.peek_char().map(|c| c.is_alphanumeric() || c == '_' || !c.is_ascii()).unwrap_or(false)
if self
.peek_char()
.map(|c| c.is_alphanumeric() || c == '_' || !c.is_ascii())
.unwrap_or(false)
{
let start = self.i;
while let Some(c) = self.peek_char() {
@@ -1105,7 +1126,6 @@ pub fn parse_call_tail(s: &str, prefer_var: bool) -> Result<(CallExpr, usize)> {
))
}
/// Split a callee token into `(receiver, callee, lib path)`.
fn split_callee(callee_tok: &str) -> (Option<String>, String, Option<Vec<String>>) {
if let Some((r, m)) = split_method_callee(callee_tok) {
@@ -1180,7 +1200,13 @@ fn try_bracket_marked_call(s: &str, prefer_var: bool) -> Result<Option<(CallExpr
continue;
}
// Only treat as callee marker at start or after whitespace.
if i > 0 && !s[..i].chars().last().map(|c| c.is_whitespace()).unwrap_or(false) {
if i > 0
&& !s[..i]
.chars()
.last()
.map(|c| c.is_whitespace())
.unwrap_or(false)
{
i += 1;
continue;
}
@@ -1226,23 +1252,22 @@ fn try_bracket_marked_call(s: &str, prefer_var: bool) -> Result<Option<(CallExpr
} else {
inner.to_string()
};
let (receiver, callee, path) =
if let Some((r, m)) = split_method_callee(&callee_tok) {
(Some(r), m, None)
} else if let Some(segments) = split_lib_path_callee(&callee_tok) {
let last = segments.last().cloned().unwrap_or_default();
(None, last, Some(segments))
let (receiver, callee, path) = if let Some((r, m)) = split_method_callee(&callee_tok) {
(Some(r), m, None)
} else if let Some(segments) = split_lib_path_callee(&callee_tok) {
let last = segments.last().cloned().unwrap_or_default();
(None, last, Some(segments))
} else {
let name = if callee_tok.starts_with('`')
&& callee_tok.ends_with('`')
&& callee_tok.len() >= 2
{
callee_tok[1..callee_tok.len() - 1].to_string()
} else {
let name = if callee_tok.starts_with('`')
&& callee_tok.ends_with('`')
&& callee_tok.len() >= 2
{
callee_tok[1..callee_tok.len() - 1].to_string()
} else {
callee_tok
};
(None, name, None)
callee_tok
};
(None, name, None)
};
let after_full = &s[close + 1..];
let args_src = after_full.trim_start();
let ws = after_full.len() - args_src.len();
@@ -1325,10 +1350,7 @@ fn parse_call_args(
} else {
parse_call_arg_value_mode(val_raw, prefer_var, paren_mode)?
};
args.push(Arg::Named {
name: key,
value,
});
args.push(Arg::Named { name: key, value });
rest = after_eq[val_end..].trim_start();
} else {
if seen_named {
@@ -1647,7 +1669,6 @@ fn find_next_arg_boundary(after_eq: &str, paren_mode: bool) -> usize {
after_eq.len()
}
/// Parse `> callee args` call expression/statement text (without leading `>`).
/// When `prefer_var` (inside `*…*` / `**…**`), bare call-arg words are variables
/// and a bare dotted callee may be a method receiver (resolved at eval/compile).
@@ -1685,7 +1706,13 @@ mod tests {
let e = parse_expr_prefer_var("answer").unwrap();
assert!(matches!(e, Expr::Var(ref n) if n == "answer"));
let e = parse_expr_prefer_var("n + 1").unwrap();
assert!(matches!(e, Expr::Binary { op: BinaryOp::Add, .. }));
assert!(matches!(
e,
Expr::Binary {
op: BinaryOp::Add,
..
}
));
let e = parse_expr_prefer_var("\"ok\"").unwrap();
assert!(matches!(e, Expr::Literal(Literal::Text(ref s)) if s == "ok"));
let e = parse_expr_prefer_var("'hi'").unwrap();
@@ -1815,7 +1842,13 @@ mod tests {
#[test]
fn chinese_logic_and_literals() {
let e = parse_expr("`a` 且 非 `b`").unwrap();
assert!(matches!(e, Expr::Binary { op: BinaryOp::And, .. }));
assert!(matches!(
e,
Expr::Binary {
op: BinaryOp::And,
..
}
));
assert!(matches!(
parse_expr("真").unwrap(),
Expr::Literal(Literal::Bool(true))
@@ -1887,7 +1920,13 @@ mod tests {
let e = parse_expr("0.85").unwrap();
assert!(matches!(e, Expr::Literal(Literal::Num(n)) if (n - 0.85).abs() < 1e-12));
let e = parse_expr("28 * 0.85").unwrap();
assert!(matches!(e, Expr::Binary { op: BinaryOp::Mul, .. }));
assert!(matches!(
e,
Expr::Binary {
op: BinaryOp::Mul,
..
}
));
let e = parse_expr_prefer_var("菜单[^`名`]").unwrap();
match e {
Expr::Index { base, label } => {
@@ -1949,8 +1988,6 @@ mod tests {
}
}
#[cfg(test)]
mod bracket_call_tests {
use super::*;
@@ -2027,7 +2064,11 @@ mod bracket_call_tests {
fn paren_call_bare_number_stops_at_paren() {
// 历史缺陷:末个位置实参会吞掉 `)`
let (c, used) = parse_call_tail("加(31)", false).unwrap();
assert_eq!(used, "加(31)".len(), "consumed must cover the closing paren");
assert_eq!(
used,
"加(31)".len(),
"consumed must cover the closing paren"
);
assert_eq!(c.args.len(), 1);
}
@@ -2069,7 +2110,10 @@ mod bracket_call_tests {
fn paren_call_lib_path_and_method() {
let c = call_of(parse_expr("txt.str_trim(s)").unwrap());
assert_eq!(c.callee, "str_trim");
assert_eq!(c.path.as_deref(), Some(&["txt".to_string(), "str_trim".to_string()][..]));
assert_eq!(
c.path.as_deref(),
Some(&["txt".to_string(), "str_trim".to_string()][..])
);
// 点号 callee 在 parse 期保存为 lib path;若 `obj` 是局部变量,
// 运行期 eval_call 会把它当 method receiver(与 `> obj.方法` 一致)。
@@ -2088,11 +2132,13 @@ mod bracket_call_tests {
assert_eq!(c.callee, "birth_year");
assert_eq!(
c.path.as_deref(),
Some(&[
"facts".to_string(),
"Person".to_string(),
"birth_year".to_string(),
][..])
Some(
&[
"facts".to_string(),
"Person".to_string(),
"birth_year".to_string(),
][..]
)
);
assert!(c.args.is_empty());
}
@@ -2199,13 +2245,19 @@ mod bracket_call_tests {
assert_eq!(label, "外层");
let (inner_label, inner_payload) = occl(payload.unwrap());
assert_eq!(inner_label, "内层");
assert!(matches!(inner_payload, Some(Expr::Literal(Literal::Int(1)))));
assert!(matches!(
inner_payload,
Some(Expr::Literal(Literal::Int(1)))
));
}
#[test]
fn occlusion_classic_mode_keeps_index() {
let e = parse_expr_markup("[键](表)", false, Markup::Classic).unwrap();
assert!(matches!(e, Expr::Index { .. }), "classic must stay an index");
assert!(
matches!(e, Expr::Index { .. }),
"classic must stay an index"
);
}
#[test]