Files
marqdo-cli/crates/marqdo-ir/src/builtins.rs
T
cflmy a67f344b6b ext(00-08): RFC-EXT-0003 core/extension boundary, math detach and release stdlib
Implements issue #3 (RFC-EXT-0003) slices on the post-3.0.0-beta.1 tree.

PR-00/01/H-06: reproduce and fix sibling heading mode inheritance.
build_units now pops the current and same-or-higher-level headings from the
ancestor stack before deriving the inherited mode, so an unmarked heading can never
inherit the previous sibling. Covered by the units matrix, conformance fixtures
22/23, and black-box heading_inheritance through check --emit/run/call.

PR-02/H-08: the deterministic release archive now ships the complete verified
stdlib/ tree. package.py and smoke.py recompute the runtime tree/alias digests,
record them in RELEASE_INFO.json.stdlib, and fail on mismatch; smoke removes the
bundle and requires a fail-closed run. Release discovery no longer falls back to the
compile-time source tree (debug builds keep that development convenience).

PR-03/H-04: one marqdo_host::CORE_RESOURCE_KINDS registry is used by both the CLI
provider-manifest validator and every trusted host registration path; all six core
kinds are rejected as provider name or declared kind before registration.
H-03: docs/architecture/resource-operations.md records every reviewed
resource_request operation and architecture_boundaries pins the exact allowlist; new
domain operations are forbidden in core (ADR-0062).

PR-04/H-01: remove math.parse/eval/substitute/simplify/differentiate from
BUILTINS, HostOp, the runtime, the host kernel and the workspace
(crates/marqdo-math deleted). Formula stays inert; Int/Float arithmetic stays.
Math algorithms are a pure examples/math-library package plus an optional
examples/math-backend ABI plugin that requests the math.compute capability
(ADR-0061). Removed calls are static symbol.unknown; the math import namespace is
released again. Tests/examples/specs migrated; new math_library black-box test.

PR-05/06 Step A: ADR-0060 classifies @exec/@knowledge as the closed Core Modes
and specifies the Proposed metadata-only Heading Annotations v1 (target 3.1,
sem.invalid_mode_marker unchanged, Analysis v2 unchanged). ADR-0063 records the
foreign F-A retention and deferred F-B removal.

Docs/status/compatibility/changelog and the RFC-EXT-0003 evidence file are updated.
Full local gate: cargo fmt PASS, clippy -D warnings PASS, workspace tests 586
passed/0 failed/2 ignored, python tools/ci 28 passed.
2026-11-22 18:57:33 +08:00

409 lines
11 KiB
Rust

//! Builtin function metadata shared by the frontend (static validation) and the
//! runtime (dispatch). Adding a builtin is a language change: update
//! `spec/evaluation.md` §8 together with this table.
/// One builtin parameter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BuiltinParam {
/// Parameter name used in diagnostics.
pub name: &'static str,
/// Whether callers must provide it.
pub required: bool,
}
const fn req(name: &'static str) -> BuiltinParam {
BuiltinParam {
name,
required: true,
}
}
const fn opt(name: &'static str) -> BuiltinParam {
BuiltinParam {
name,
required: false,
}
}
/// A builtin function or host operation.
#[derive(Debug, Clone, Copy)]
pub struct Builtin {
/// Canonical call name (may be namespaced, e.g. `foreign.run`).
pub name: &'static str,
/// Alternative names (Chinese/English aliases).
pub aliases: &'static [&'static str],
/// Parameters in declaration order.
pub params: &'static [BuiltinParam],
/// Whether all arguments must be named (inferred-style API) rather than
/// positional.
pub named_only: bool,
/// Whether invoking it has an effect that requires host authorization.
pub effectful: bool,
}
impl Builtin {
/// Whether `name` refers to this builtin.
pub fn matches(&self, name: &str) -> bool {
self.name == name || self.aliases.contains(&name)
}
}
const PRINT: Builtin = Builtin {
name: "打印",
aliases: &["print"],
params: &[req("值")],
named_only: false,
effectful: true,
};
const LEN: Builtin = Builtin {
name: "长度",
aliases: &["len"],
params: &[req("值")],
named_only: false,
effectful: false,
};
const TYPE_OF: Builtin = Builtin {
name: "类型",
aliases: &["type"],
params: &[req("值")],
named_only: false,
effectful: false,
};
const STR: Builtin = Builtin {
name: "文本",
aliases: &["str"],
params: &[req("值")],
named_only: false,
effectful: false,
};
const INT: Builtin = Builtin {
name: "整数",
aliases: &["int"],
params: &[req("值")],
named_only: false,
effectful: false,
};
const FLOAT: Builtin = Builtin {
name: "小数",
aliases: &["float"],
params: &[req("值")],
named_only: false,
effectful: false,
};
const TABLE: Builtin = Builtin {
name: "表",
aliases: &["table"],
params: &[req("表头"), req("行")],
named_only: false,
effectful: false,
};
const REF: Builtin = Builtin {
name: "ref",
aliases: &[],
params: &[req("目标")],
named_only: false,
effectful: false,
};
const FOREIGN_RUN: Builtin = Builtin {
name: "foreign.run",
aliases: &[],
params: &[req("ref"), opt("input")],
named_only: false,
effectful: true,
};
const FOREIGN_CALL: Builtin = Builtin {
name: "foreign.call",
aliases: &[],
params: &[req("ref"), req("input")],
named_only: false,
effectful: true,
};
const FS_READ: Builtin = Builtin {
name: "fs.read",
aliases: &[],
params: &[req("path")],
named_only: false,
effectful: true,
};
const FS_WRITE: Builtin = Builtin {
name: "fs.write",
aliases: &[],
params: &[req("path"), req("contents")],
named_only: false,
effectful: true,
};
const MEMORY_NEW: Builtin = Builtin {
name: "memory.new",
aliases: &[],
params: &[req("initial_pages"), req("max_pages")],
named_only: false,
effectful: false,
};
const MEMORY_SIZE: Builtin = Builtin {
name: "memory.size",
aliases: &[],
params: &[req("memory")],
named_only: false,
effectful: false,
};
const MEMORY_GROW: Builtin = Builtin {
name: "memory.grow",
aliases: &[],
params: &[req("memory"), req("pages")],
named_only: false,
effectful: false,
};
const LIST_APPEND: Builtin = Builtin {
name: "list.append",
aliases: &[],
params: &[req("list"), req("value")],
named_only: false,
effectful: false,
};
const LIST_CONCAT: Builtin = Builtin {
name: "list.concat",
aliases: &[],
params: &[req("left"), req("right")],
named_only: false,
effectful: false,
};
const MAP_KEYS: Builtin = Builtin {
name: "map.keys",
aliases: &[],
params: &[req("map")],
named_only: false,
effectful: false,
};
const MAP_HAS: Builtin = Builtin {
name: "map.has",
aliases: &[],
params: &[req("map"), req("key")],
named_only: false,
effectful: false,
};
const MAP_GET: Builtin = Builtin {
name: "map.get",
aliases: &[],
params: &[req("map"), req("key")],
named_only: false,
effectful: false,
};
const MAP_SET: Builtin = Builtin {
name: "map.set",
aliases: &[],
params: &[req("map"), req("key"), req("value")],
named_only: false,
effectful: false,
};
const MAP_REMOVE: Builtin = Builtin {
name: "map.remove",
aliases: &[],
params: &[req("map"), req("key")],
named_only: false,
effectful: false,
};
const TEXT_CODEPOINTS: Builtin = Builtin {
name: "text.codepoints",
aliases: &[],
params: &[req("text")],
named_only: false,
effectful: false,
};
const TEXT_FROM_CODEPOINT: Builtin = Builtin {
name: "text.from_codepoint",
aliases: &[],
params: &[req("codepoint")],
named_only: false,
effectful: false,
};
const TABLE_COLUMNS: Builtin = Builtin {
name: "table.columns",
aliases: &[],
params: &[req("table")],
named_only: false,
effectful: false,
};
const TABLE_ROW: Builtin = Builtin {
name: "table.row",
aliases: &[],
params: &[req("table"), req("row")],
named_only: false,
effectful: false,
};
const RESOURCE_OPEN: Builtin = Builtin {
name: "resource.open",
aliases: &[],
params: &[req("kind"), req("descriptor"), req("rights")],
named_only: false,
effectful: true,
};
const RESOURCE_READ: Builtin = Builtin {
name: "resource.read",
aliases: &[],
params: &[
req("handle"),
req("memory"),
req("offset"),
req("max_bytes"),
],
named_only: false,
effectful: true,
};
const RESOURCE_WRITE: Builtin = Builtin {
name: "resource.write",
aliases: &[],
params: &[req("handle"), req("memory"), req("offset"), req("length")],
named_only: false,
effectful: true,
};
const RESOURCE_CLOSE: Builtin = Builtin {
name: "resource.close",
aliases: &[],
params: &[req("handle")],
named_only: false,
effectful: true,
};
const RESOURCE_REQUEST: Builtin = Builtin {
name: "resource.request",
aliases: &[],
params: &[req("operation"), req("arguments")],
named_only: false,
effectful: true,
};
const RESOURCE_ACCEPT: Builtin = Builtin {
name: "resource.accept",
aliases: &[],
params: &[req("handle")],
named_only: false,
effectful: true,
};
const TABLE_CELL: Builtin = Builtin {
name: "table.cell",
aliases: &[],
params: &[req("table"), req("row"), req("column")],
named_only: false,
effectful: false,
};
/// All builtins known to the language. Host availability is decided at call
/// time by the capability layer, not here.
pub const BUILTINS: &[Builtin] = &[
PRINT,
LEN,
TYPE_OF,
STR,
INT,
FLOAT,
TABLE,
REF,
FOREIGN_RUN,
FOREIGN_CALL,
FS_READ,
FS_WRITE,
MEMORY_NEW,
MEMORY_SIZE,
MEMORY_GROW,
LIST_APPEND,
LIST_CONCAT,
MAP_KEYS,
MAP_HAS,
MAP_GET,
MAP_SET,
MAP_REMOVE,
TEXT_CODEPOINTS,
TEXT_FROM_CODEPOINT,
TABLE_COLUMNS,
TABLE_ROW,
TABLE_CELL,
RESOURCE_OPEN,
RESOURCE_READ,
RESOURCE_WRITE,
RESOURCE_CLOSE,
RESOURCE_REQUEST,
RESOURCE_ACCEPT,
];
/// Find a builtin by canonical name or alias.
pub fn find(name: &str) -> Option<&'static Builtin> {
BUILTINS.iter().find(|builtin| builtin.matches(name))
}
/// Validate an argument list against a builtin parameter list.
///
/// Returns `Ok(())` when every required parameter is supplied and no unknown
/// name is used; positional arguments are matched by declaration order.
pub fn validate_args(builtin: &Builtin, args: &[marqdo_expression::Arg]) -> Result<(), String> {
if builtin.named_only && args.iter().any(|arg| arg.name.is_none()) {
return Err(format!("`{}` only accepts named arguments", builtin.name));
}
let mut provided = Vec::new();
let mut positional = 0usize;
for arg in args {
match &arg.name {
Some(name) => {
if !builtin.params.iter().any(|param| param.name == name) {
return Err(format!(
"`{}` has no parameter named `{name}`",
builtin.name
));
}
if provided.contains(name) {
return Err(format!("duplicate argument `{name}`"));
}
provided.push(name.clone());
}
None => {
let Some(param) = builtin.params.get(positional) else {
return Err(format!(
"`{}` accepts at most {} positional arguments",
builtin.name,
builtin.params.len()
));
};
if provided.contains(&param.name.to_string()) {
return Err(format!("duplicate argument `{}`", param.name));
}
provided.push(param.name.to_string());
positional += 1;
}
}
}
for param in builtin.params {
if param.required && !provided.iter().any(|name| name == param.name) {
return Err(format!(
"`{}` is missing required argument `{}`",
builtin.name, param.name
));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lookup_aliases() {
assert_eq!(find("print").unwrap().name, "打印");
assert_eq!(find("打印").unwrap().name, "打印");
assert!(find("table").is_some());
assert!(find("math.eval").is_none());
assert!(find("nope").is_none());
}
#[test]
fn arity_validation() {
use marqdo_expression::parse_arguments;
let print = find("打印").unwrap();
assert!(validate_args(print, &parse_arguments("(1)").unwrap()).is_ok());
assert!(validate_args(print, &parse_arguments("()").unwrap()).is_err());
let table = find("table").unwrap();
assert!(validate_args(table, &parse_arguments("(表头=[1], 行=[])").unwrap()).is_ok());
// Builtins accept positional arguments followed by named ones.
assert!(validate_args(table, &parse_arguments("([1], [])").unwrap()).is_ok());
assert!(validate_args(table, &parse_arguments("(表头=[1], nope=[])").unwrap()).is_err());
assert!(validate_args(table, &parse_arguments("(1, 2, 3)").unwrap()).is_err());
}
}