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}");
|
||||
}
|
||||
}
|
||||
@@ -590,6 +590,34 @@ impl StdHost {
|
||||
Ok(Value::Unit)
|
||||
}
|
||||
|
||||
fn record_resource_effect(
|
||||
&mut self,
|
||||
op: &str,
|
||||
ctx: &ExecutionContext,
|
||||
started: Instant,
|
||||
summary: &str,
|
||||
) {
|
||||
let estimate = TraceState::estimate(
|
||||
"effect",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
Some(summary),
|
||||
Some(op),
|
||||
);
|
||||
if !self.trace_state.accept(estimate) {
|
||||
return;
|
||||
}
|
||||
let seq = self.next_seq();
|
||||
self.trace.record(
|
||||
seq,
|
||||
op,
|
||||
ctx.module_id.clone(),
|
||||
ctx.span,
|
||||
started.elapsed(),
|
||||
summary.to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
fn open_resource_stream(
|
||||
&mut self,
|
||||
kind: &str,
|
||||
@@ -597,12 +625,21 @@ impl StdHost {
|
||||
rights: &[String],
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let started = Instant::now();
|
||||
let requested: BTreeSet<&str> = rights.iter().map(String::as_str).collect();
|
||||
if self.mode == SandboxMode::Strict {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::PermissionDenied,
|
||||
ctx.span,
|
||||
"resource streams are not verified in strict mode and are refused",
|
||||
));
|
||||
// stdio/stdout is the existing console channel already permitted by
|
||||
// strict L1 (CM-A11); file/network/process providers are not.
|
||||
let stdio_console =
|
||||
kind == "stdio" && descriptor == "stdout" && requested == BTreeSet::from(["write"]);
|
||||
if !stdio_console {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::PermissionDenied,
|
||||
ctx.span,
|
||||
"strict mode permits only the existing stdio/stdout console channel; \
|
||||
other resource streams are refused",
|
||||
));
|
||||
}
|
||||
}
|
||||
if self.mode == SandboxMode::Pure && kind == "file" {
|
||||
return Err(RuntimeError::new(
|
||||
@@ -611,7 +648,6 @@ impl StdHost {
|
||||
"pure mode does not provide project file resources",
|
||||
));
|
||||
}
|
||||
let requested: BTreeSet<&str> = rights.iter().map(String::as_str).collect();
|
||||
match kind {
|
||||
"stdio" => {
|
||||
if descriptor != "stdout" || requested != BTreeSet::from(["write"]) {
|
||||
@@ -636,6 +672,7 @@ impl StdHost {
|
||||
ctx.span,
|
||||
Some("kind=stdio descriptor=stdout"),
|
||||
);
|
||||
self.record_resource_effect("resource.open", ctx, started, "ok");
|
||||
Ok(Value::Resource(handle))
|
||||
}
|
||||
"file" => {
|
||||
@@ -651,6 +688,7 @@ impl StdHost {
|
||||
ctx.span,
|
||||
Some("kind=file rights=read"),
|
||||
);
|
||||
self.record_resource_effect("resource.open", ctx, started, "ok");
|
||||
return Ok(Value::Resource(handle));
|
||||
}
|
||||
if requested == BTreeSet::from(["write"]) {
|
||||
@@ -664,6 +702,7 @@ impl StdHost {
|
||||
ctx.span,
|
||||
Some("kind=file rights=write"),
|
||||
);
|
||||
self.record_resource_effect("resource.open", ctx, started, "ok");
|
||||
return Ok(Value::Resource(handle));
|
||||
}
|
||||
Err(RuntimeError::new(
|
||||
@@ -756,6 +795,7 @@ impl Host for StdHost {
|
||||
max_bytes: usize,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<ResourceRead, RuntimeError> {
|
||||
let started = Instant::now();
|
||||
let kind = self.resources.kind(handle, ctx.span)?;
|
||||
let read = self.resources.read(handle, max_bytes, ctx.span)?;
|
||||
self.record_semantic(
|
||||
@@ -769,6 +809,12 @@ impl Host for StdHost {
|
||||
read.eof
|
||||
)),
|
||||
);
|
||||
self.record_resource_effect(
|
||||
"resource.read",
|
||||
ctx,
|
||||
started,
|
||||
&format!("kind={kind} count={}", read.bytes.len()),
|
||||
);
|
||||
Ok(read)
|
||||
}
|
||||
|
||||
@@ -778,6 +824,7 @@ impl Host for StdHost {
|
||||
bytes: &[u8],
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<usize, RuntimeError> {
|
||||
let started = Instant::now();
|
||||
let kind = self.resources.kind(handle, ctx.span)?;
|
||||
let count = self.resources.write(handle, bytes, ctx.span)?;
|
||||
if kind == "stdio" {
|
||||
@@ -791,6 +838,12 @@ impl Host for StdHost {
|
||||
ctx.span,
|
||||
Some(&format!("kind={kind} count={count}")),
|
||||
);
|
||||
self.record_resource_effect(
|
||||
"resource.write",
|
||||
ctx,
|
||||
started,
|
||||
&format!("kind={kind} count={count}"),
|
||||
);
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
@@ -799,6 +852,7 @@ impl Host for StdHost {
|
||||
handle: ResourceHandle,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<(), RuntimeError> {
|
||||
let started = Instant::now();
|
||||
let pending = self.resources.pending_file_write(handle, ctx.span)?;
|
||||
let count = match pending {
|
||||
Some((relative, bytes)) => {
|
||||
@@ -815,6 +869,12 @@ impl Host for StdHost {
|
||||
ctx.span,
|
||||
Some(&format!("flushed_bytes={count}")),
|
||||
);
|
||||
self.record_resource_effect(
|
||||
"resource.close",
|
||||
ctx,
|
||||
started,
|
||||
&format!("flushed_bytes={count}"),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -54,13 +54,25 @@ fn stdout_write_obeys_the_output_budget_atomically() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_mode_refuses_every_resource_open() {
|
||||
fn strict_mode_allows_only_the_existing_stdio_console_channel() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut host = StdHost::new(SandboxMode::Strict, Capabilities::pure(), dir.path());
|
||||
let error = host
|
||||
.resource_open("stdio", "stdout", &["write".to_string()], &context())
|
||||
let ctx = context();
|
||||
let handle = handle(
|
||||
host.resource_open("stdio", "stdout", &["write".to_string()], &ctx)
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(host.resource_write(handle, b"strict", &ctx).unwrap(), 6);
|
||||
assert_eq!(host.take_output(), b"strict");
|
||||
|
||||
let file = host
|
||||
.resource_open("file", "a.txt", &["read".to_string()], &ctx)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::PermissionDenied);
|
||||
assert_eq!(file.category, ErrorCategory::PermissionDenied);
|
||||
let socket = host
|
||||
.resource_open("socket", "example.test", &["read".to_string()], &ctx)
|
||||
.unwrap_err();
|
||||
assert_eq!(socket.category, ErrorCategory::PermissionDenied);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -517,6 +517,10 @@ pub struct Program {
|
||||
/// metadata only: `check` never loads a library.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub external_callables: Vec<callable::CallableDescriptor>,
|
||||
/// Compat-B `打印`/`print` destination (ADR-0030). When set, the runtime
|
||||
/// calls this stdlib function instead of the legacy `HostOp::Print`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub print_override: Option<FunctionId>,
|
||||
}
|
||||
|
||||
impl Program {
|
||||
|
||||
@@ -656,6 +656,25 @@ impl<'a> Interpreter<'a> {
|
||||
let args = self.eval_args(args, frame)?;
|
||||
return self.call_value(program, value, args, Some(span), Some(&caller_module));
|
||||
}
|
||||
if matches!(ident.name.as_str(), "打印" | "print") {
|
||||
if let Some(target) = program.print_override.clone() {
|
||||
let args = self.eval_args(args, frame)?;
|
||||
let Some(function) = program.function(&target) else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::UnknownSymbol,
|
||||
Some(span),
|
||||
format!("print override `{target}` does not exist"),
|
||||
));
|
||||
};
|
||||
return self.call_function(
|
||||
program,
|
||||
function,
|
||||
args,
|
||||
Some(span),
|
||||
Some(&caller_module),
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some(builtin) = builtins::find(&ident.name) {
|
||||
let args = self.eval_args(args, frame)?;
|
||||
return self.call_builtin(builtin, args, Some(span), frame);
|
||||
|
||||
Reference in new issue
Block a user