refactor(print): remove HostOp::Print and legacy formatting (Compat-C)

- Delete HostOp::Print and StdHost::op_print; the print builtin only routes to
  bundled io.写值 when Program.print_override is set, otherwise returns a
  structured kernel.unavailable error (ADR-0031).
- Keep the 打印/print builtin name for arity/static validation; Value::display
  remains only for CLI result rendering, not print execution.
- Teach the direct-runtime semantic harness to mirror loader stdlib injection
  and import edges; replace runtime tests that used print with non-print
  effects.
- Update spec/security/status/changelog/README, add ADR-0031 and evidence.

Gate: fmt, clippy -D warnings, 419 tests passed.
This commit is contained in:
cflmy committed 2026-11-20 22:22:51 +08:00
1 parent e26971f489
commit 49910ece43
16 files changed
+304 -56

No files matched your search

+72 -1
View File
@@ -24,7 +24,7 @@ use std::path::{Path, PathBuf};
use std::process::Command;
use marqdo_host::{Capabilities, Host, StdHost};
use marqdo_ir::ModuleId;
use marqdo_ir::{ModuleId, Program, ResolvedImport};
use marqdo_runtime::{run, EvaluatedArg};
use marqdo_sandbox::SandboxMode;
@@ -168,6 +168,7 @@ fn semantic_goldens_match_end_to_end_execution() {
let mut program = marqdo_ir::Program::default();
program.insert(analysis.module.clone());
program.main_module = Some(module_id.clone());
install_stdlib_print(&mut program);
let mut capabilities = Capabilities::pure();
if grant_foreign {
@@ -263,3 +264,73 @@ fn semantic_goldens_match_end_to_end_execution() {
fixtures.len()
);
}
/// Load the bundled stdlib print modules for direct-runtime fixtures.
///
/// The CLI loader normally injects these for Compat-B. The semantic harness
/// builds a Program directly, so it mirrors the same resolution here; without
/// it, fixtures that call `打印` would hit the Compat-C "no bundle" error.
fn install_stdlib_print(program: &mut Program) {
let root = repo_root().join("stdlib");
if !root.join("stdlib.json").is_file() {
return;
}
let mut loaded = std::collections::BTreeSet::new();
let io = match load_stdlib_module(&root, "io.mq.md", program, &mut loaded) {
Ok(id) => id,
Err(error) => panic!("cannot load bundled stdlib: {error}"),
};
let function = program
.module(&io)
.and_then(|module| module.function("写值"))
.unwrap_or_else(|| panic!("stdlib io has no 写值 function"));
program.print_override = Some(function.id.clone());
}
fn load_stdlib_module(
root: &Path,
relative: &str,
program: &mut Program,
loaded: &mut std::collections::BTreeSet<String>,
) -> Result<ModuleId, String> {
if !loaded.insert(relative.to_string()) {
return Err(format!("stdlib import cycle at `{relative}`"));
}
let path = root.join(relative);
let source = fs::read_to_string(&path)
.map_err(|error| format!("cannot read `{}`: {error}", path.display()))?;
let module_id = ModuleId::new("std:test", relative.replace('\\', "/"));
let analysis = marqdo_frontend::analyze_source(&module_id.to_string(), &source);
if analysis.has_errors() {
return Err(format!("stdlib module `{relative}` has diagnostics"));
}
let imports: Vec<(String, String)> = analysis
.document
.frontmatter()
.and_then(|frontmatter| frontmatter.imports().ok())
.map(|mapping| mapping.into_iter().collect())
.unwrap_or_default();
for (alias, target) in imports {
let target = target.strip_prefix("std:").unwrap_or(&target);
let child = if target.starts_with("./") || target.starts_with("../") {
let base = Path::new(relative)
.parent()
.unwrap_or_else(|| Path::new(""));
base.join(target)
.components()
.map(|component| component.as_os_str().to_string_lossy().to_string())
.collect::<Vec<_>>()
.join("/")
} else {
target.to_string()
};
let to = load_stdlib_module(root, &child, program, loaded)?;
program.resolved_imports.push(ResolvedImport {
from: module_id.clone(),
alias,
to,
});
}
program.insert(analysis.module);
Ok(module_id)
}
-25
View File
@@ -27,8 +27,6 @@ use marqdo_sandbox::{PlatformCapabilities, SandboxMode};
/// Host operations reachable from the language surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostOp {
/// Write a value to program stdout.
Print,
/// Parse a formula.
MathParse,
/// Evaluate a formula.
@@ -55,7 +53,6 @@ impl HostOp {
/// Stable operation name used in traces and diagnostics.
pub const fn name(self) -> &'static str {
match self {
HostOp::Print => "print",
HostOp::MathParse => "math.parse",
HostOp::MathEval => "math.eval",
HostOp::MathSubstitute => "math.substitute",
@@ -480,7 +477,6 @@ impl StdHost {
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
match op {
HostOp::Print => self.op_print(args, ctx),
HostOp::FsRead => self.op_fs_read(args, ctx),
HostOp::FsWrite => self.op_fs_write(args, ctx),
HostOp::MathParse
@@ -495,27 +491,6 @@ impl StdHost {
}
}
fn op_print(
&mut self,
args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
if !self.capabilities.console {
return Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
ctx.span,
"program output (console) capability was not granted",
));
}
if args.len() != 1 {
return Err(arity(ctx.span, "打印", 1, args.len()));
}
let text = format!("{}\n", args[0].display());
self.budget.consume_output(text.len(), ctx.span)?;
self.output.extend_from_slice(text.as_bytes());
Ok(Value::Unit)
}
fn op_fs_read(
&mut self,
args: Vec<Value>,
+1 -1
View File
@@ -85,7 +85,7 @@ fn resource_handles_cannot_cross_the_generic_host_boundary() {
.unwrap(),
);
let error = host
.invoke(HostOp::Print, vec![Value::Resource(handle)], &ctx)
.invoke(HostOp::FsRead, vec![Value::Resource(handle)], &ctx)
.unwrap_err();
assert_eq!(error.category, ErrorCategory::Type);
assert!(error.message.contains("Resource handles"));
+2 -2
View File
@@ -517,8 +517,8 @@ 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`.
/// Compat-B/C `打印`/`print` destination (ADR-0030/0031). When set, the
/// runtime calls this stdlib function; there is no legacy HostOp path.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub print_override: Option<FunctionId>,
}
+9 -4
View File
@@ -27,10 +27,15 @@ pub(crate) fn dispatch(
let module = frame.module().clone();
match builtin.name {
"打印" => {
let value = take(&bound, "值", builtin, span)?;
interpreter
.host_invoke(HostOp::Print, vec![value], span, &module)
.map(|_| Value::Unit)
// Compat-C (ADR-0031): the legacy HostOp::Print path is gone. On
// the official CLI the loader routes 打印/print to stdlib io.写值;
// reaching this builtin means the verified bundle was unavailable.
let _ = take(&bound, "值", builtin, span)?;
Err(RuntimeError::new(
ErrorCategory::KernelUnavailable,
span,
"打印 requires the bundled stdlib print module; install the official CLI bundle",
))
}
"长度" => {
let value = take(&bound, "值", builtin, span)?;
+18 -7
View File
@@ -70,11 +70,10 @@ fn recursion_branch_and_return() {
}
#[test]
fn loop_prints_and_returns_unit_for_fallthrough() {
let source = "## 倒计时\n\n**n = 3**\n\n- `n > 0`\n\n > 打印(n)\n\n **n = n - 1**\n";
let (result, output) = run_and_output(source, "倒计时");
fn loop_mutates_and_returns_unit_for_fallthrough() {
let source = "## 倒计时\n\n**n = 3**\n\n- `n > 0`\n\n **n = n - 1**\n";
let (result, _) = run_and_output(source, "倒计时");
assert_eq!(result.unwrap(), Value::Unit);
assert_eq!(output, "3\n2\n1\n");
}
#[test]
@@ -117,14 +116,14 @@ fn function_reference_can_be_called() {
#[test]
fn non_bool_condition_is_a_runtime_error() {
let source = "## f\n\n**x = 1**\n\n- `x`\n\n > 打印(1)\n\n*x*\n";
let source = "## f\n\n**x = 1**\n\n- `x`\n\n **x = x + 1**\n\n*x*\n";
let error = run_named(source, "f", &[]).unwrap_err();
assert_eq!(error.code(), "runtime.type");
}
#[test]
fn fuel_budget_is_enforced() {
let program = build("## f\n\n- `true`\n\n > 打印(1)\n\n*0*\n");
let program = build("## f\n\n- `true`\n\n **x = 1**\n\n*0*\n");
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::pure(),
@@ -171,6 +170,18 @@ fn ambiguous_ref_resource_is_an_error() {
assert_eq!(error.code(), "ref.ambiguous");
}
#[test]
fn print_without_the_bundled_stdlib_is_a_structured_error() {
let source = "## f\n\n> 打印(1)\n\n*None*\n";
let error = run_named(source, "f", &[]).unwrap_err();
assert_eq!(error.code(), "kernel.unavailable");
assert!(
error.message.contains("bundled stdlib"),
"unexpected message: {}",
error.message
);
}
#[test]
fn function_ref_and_resource_members_are_readable() {
let source = "## 目标\n\n*1*\n\n## main\n\n### 公式\n\n$$a = 1$$\n\n### 代码\n\n```text\nx\n```\n\n**f = ref(\"#目标\")**\n\n**g = ref(\"#公式\")**\n\n**c = ref(\"#代码\")**\n\n*[f.module, f.name, g.latex, g.display, c.language, c.source]*\n";
@@ -198,7 +209,7 @@ fn memory_region_is_shared_by_handle_identity() {
#[test]
fn memory_handle_cannot_reach_the_host_boundary() {
let source = "## f\n\n**m = memory.new(1, 1)**\n\n> 打印(m)\n\n*0*\n";
let source = "## f\n\n**m = memory.new(1, 1)**\n\n> fs.read(m)\n\n*0*\n";
let error = run_named(source, "f", &[]).unwrap_err();
assert_eq!(error.code(), "runtime.type");
assert!(