feat(cli): route print through the bundled stdlib (Compat-B)
- Add Program.print_override and lazy stdlib injection: only programs that call 打印/print load std:io and route to io.写值 (ADR-0030). - Record resource.open/read/write/close as trace effect events so the stdlib print path is auditable; HostOp::Print no longer runs on that path. - Permit only stdio/stdout (existing console) in strict; file/network resource opens remain permission.denied. - Exclude std: modules from the human-readable checked-module count; update the Python analysis consumer to accept std: instance ids. - Add print-routing and strict-console tests, ADR-0030 and evidence. Gate: fmt, clippy -D warnings, 418 tests passed.
This commit is contained in:
1 parent
e119727c5d
commit
e26971f489
21 files changed
+560
-36
No files matched your search
@@ -353,7 +353,13 @@ pub fn check(
|
||||
let text = output::render_text(&project.diagnostics);
|
||||
eprint!("{text}");
|
||||
if errors == 0 {
|
||||
println!("checked {} module(s): ok", project.program.modules.len());
|
||||
let checked = project
|
||||
.program
|
||||
.modules
|
||||
.keys()
|
||||
.filter(|id| !id.instance.starts_with("std:"))
|
||||
.count();
|
||||
println!("checked {checked} module(s): ok");
|
||||
} else {
|
||||
eprintln!(
|
||||
"check failed: {} error(s), {} warning(s)",
|
||||
|
||||
@@ -13,8 +13,9 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use marqdo_expression::Expr;
|
||||
use marqdo_frontend::{analyze_source, AnalysisResult};
|
||||
use marqdo_ir::{ModuleId, Program, ResolvedImport};
|
||||
use marqdo_ir::{ModuleId, PlaceTarget, Program, ResolvedImport, Stmt};
|
||||
use marqdo_package::{
|
||||
discover_root, LockFile, Manifest, PackageResolver, ResolvedPackage, LOCK_FILE, MANIFEST_FILE,
|
||||
};
|
||||
@@ -278,6 +279,23 @@ pub fn load(entry: &Path) -> Result<LoadedProject, String> {
|
||||
};
|
||||
let entry_id = loader.load_module(&entry_module.package, &entry_module.relative_path)?;
|
||||
loader.program.main_module = Some(entry_id.clone());
|
||||
|
||||
// Compat-B (ADR-0030): only programs that actually call 打印/print need the
|
||||
// stdlib print module; injecting it for every program would change the
|
||||
// module graph, analysis output and startup cost for no benefit.
|
||||
if program_uses_print(&loader.program) {
|
||||
if let Some(stdlib) = loader.stdlib.clone() {
|
||||
let package = stdlib.package();
|
||||
let io = loader.load_module(&package, "io.mq.md")?;
|
||||
let Some(module) = loader.program.module(&io) else {
|
||||
return Err("stdlib print module was not loaded".to_string());
|
||||
};
|
||||
let Some(function) = module.function("写值") else {
|
||||
return Err("stdlib print module has no `写值` function".to_string());
|
||||
};
|
||||
loader.program.print_override = Some(function.id.clone());
|
||||
}
|
||||
}
|
||||
for (module_id, diagnostic) in marqdo_frontend::calls::validate_program(&loader.program) {
|
||||
if let Some(file) = loader.files.get(&module_id) {
|
||||
loader.diagnostics.push(FileDiagnostic {
|
||||
@@ -499,3 +517,57 @@ impl Loader {
|
||||
Ok(module_id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the loaded program calls the legacy `打印`/`print` builtin.
|
||||
fn program_uses_print(program: &Program) -> bool {
|
||||
program.modules.values().any(|module| {
|
||||
module
|
||||
.functions
|
||||
.iter()
|
||||
.any(|function| stmts_use_print(&function.body))
|
||||
})
|
||||
}
|
||||
|
||||
fn stmts_use_print(stmts: &[Stmt]) -> bool {
|
||||
stmts.iter().any(|stmt| match stmt {
|
||||
Stmt::Assign { target, value, .. } => {
|
||||
let target_uses = match target {
|
||||
PlaceTarget::Local { .. } => false,
|
||||
PlaceTarget::Index { base, index, .. } => {
|
||||
expr_uses_print(base) || expr_uses_print(index)
|
||||
}
|
||||
};
|
||||
target_uses || expr_uses_print(value)
|
||||
}
|
||||
Stmt::Eval { expr, .. } | Stmt::Return { value: expr, .. } => expr_uses_print(expr),
|
||||
Stmt::Call { call, .. } => call.args.iter().any(|arg| expr_uses_print(&arg.value)),
|
||||
Stmt::Branch { arms, .. } => arms
|
||||
.iter()
|
||||
.any(|arm| expr_uses_print(&arm.condition) || stmts_use_print(&arm.body)),
|
||||
Stmt::Loop {
|
||||
condition, body, ..
|
||||
} => expr_uses_print(condition) || stmts_use_print(body),
|
||||
})
|
||||
}
|
||||
|
||||
fn expr_uses_print(expr: &Expr) -> bool {
|
||||
match expr {
|
||||
Expr::Call { callee, args, .. } => {
|
||||
matches!(callee.as_ref(), Expr::Ident(ident) if matches!(ident.name.as_str(), "打印" | "print"))
|
||||
|| expr_uses_print(callee)
|
||||
|| args.iter().any(|arg| expr_uses_print(&arg.value))
|
||||
}
|
||||
Expr::List(items) => items.iter().any(expr_uses_print),
|
||||
Expr::Record(entries) => entries.iter().any(|entry| expr_uses_print(&entry.value)),
|
||||
Expr::Unary { operand, .. } => expr_uses_print(operand),
|
||||
Expr::Binary { left, right, .. } => expr_uses_print(left) || expr_uses_print(right),
|
||||
Expr::Member { base, .. } => expr_uses_print(base),
|
||||
Expr::Index { base, index, .. } => expr_uses_print(base) || expr_uses_print(index),
|
||||
Expr::Int(_)
|
||||
| Expr::Float(_)
|
||||
| Expr::Text(_)
|
||||
| Expr::Bool(_)
|
||||
| Expr::None
|
||||
| Expr::Ident(_) => false,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
//! Compat-B `打印` routing tests (ADR-0030).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("marqdo-print-route-{}-{tag}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn cli(dir: &Path, args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_marqdo"))
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.output()
|
||||
.expect("run marqdo")
|
||||
}
|
||||
|
||||
fn write(dir: &Path, name: &str, source: &str) -> PathBuf {
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, source).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_is_routed_through_the_stdlib_and_not_hostop_print() {
|
||||
let dir = TempDir::new("routed");
|
||||
write(
|
||||
dir.path(),
|
||||
"index.mq.md",
|
||||
"## main\n\n> 打印([\"x\", 1])\n\n*None*\n",
|
||||
);
|
||||
let trace = dir.path().join("trace.json");
|
||||
let output = cli(
|
||||
dir.path(),
|
||||
&[
|
||||
"run",
|
||||
"index.mq.md",
|
||||
"--trace-file",
|
||||
trace.to_str().unwrap(),
|
||||
],
|
||||
);
|
||||
assert_eq!(
|
||||
output.status.code(),
|
||||
Some(0),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert_eq!(String::from_utf8_lossy(&output.stdout), "[\"x\", 1]\n");
|
||||
|
||||
let trace: serde_json::Value = serde_json::from_slice(&std::fs::read(&trace).unwrap()).unwrap();
|
||||
let operations: Vec<&str> = trace["events"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|event| event["operation"].as_str())
|
||||
.collect();
|
||||
assert!(
|
||||
operations.contains(&"resource.write"),
|
||||
"stdlib print must write through the resource ABI: {operations:?}"
|
||||
);
|
||||
assert!(
|
||||
!operations.contains(&"print"),
|
||||
"legacy HostOp::Print must not run in Compat-B: {operations:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdlib_print_modules_are_injected_only_when_print_is_used() {
|
||||
let dir = TempDir::new("lazy");
|
||||
write(dir.path(), "plain.mq.md", "## main\n\n*1*\n");
|
||||
write(
|
||||
dir.path(),
|
||||
"prints.mq.md",
|
||||
"## main\n\n> 打印(1)\n\n*None*\n",
|
||||
);
|
||||
for (file, expected_stdlib) in [("plain.mq.md", false), ("prints.mq.md", true)] {
|
||||
let target = dir.path().join(format!("{file}.json"));
|
||||
let output = cli(
|
||||
dir.path(),
|
||||
&["check", file, "--emit", target.to_str().unwrap()],
|
||||
);
|
||||
assert_eq!(output.status.code(), Some(0), "{file}");
|
||||
let analysis: serde_json::Value =
|
||||
serde_json::from_slice(&std::fs::read(&target).unwrap()).unwrap();
|
||||
let modules = analysis["modules"].as_array().unwrap();
|
||||
let has_stdlib = modules
|
||||
.iter()
|
||||
.any(|module| module["id"].as_str().unwrap_or("").starts_with("std:"));
|
||||
assert_eq!(has_stdlib, expected_stdlib, "{file}: {modules:?}");
|
||||
// The bundle identity is recorded whenever a bundle is available; it
|
||||
// does not imply that this program loaded any stdlib module.
|
||||
assert!(analysis["project"]["stdlib"].is_object(), "{file}");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user