feat(ext): single callable binding, provider v2 CLI, capability handlers, stdlib aliases
Implements RFC-EXT-0001 PR-00..PR-07 first pass: - CallSiteKey/CallBindingTable + one frontend binding pass; runtime dispatch by identity - prepare composition root shared by check/run/inspect/Analysis; exact plugin reconciliation - provider.json v2 --provider/--allow-provider worker CLI with fail-closed verification - capability handler registry with real fs.read and audit - verified stdlib public aliases replace print_override/AST scan - docs: specs, ADR-0054/0055/0057/0058, README, CI/release gates, evidence PR-04 extension selection/lock v4 and final frozen-binary evidence remain.
This commit is contained in:
1 parent
9aa536c2c9
commit
1f6fd644a0
54 files changed
+8710
-828
No files matched your search
@@ -0,0 +1,201 @@
|
||||
//! Resolved static call bindings (RFC-EXT-0001 §4.2, ADR-0054).
|
||||
//!
|
||||
//! The frontend resolves every statically visible call site exactly once and
|
||||
//! records the decision here. The runtime only dispatches by this table: it
|
||||
//! never re-resolves a qualified name and never guesses a plugin from a string
|
||||
//! prefix. The table is internal IR (not part of Analysis/Trace v2 wire
|
||||
//! contracts) and is deliberately skipped when a [`crate::Program`] is
|
||||
//! serialized.
|
||||
//!
|
||||
//! Identity rules:
|
||||
//!
|
||||
//! * a [`CallSiteKey`] is `(module, function, byte span)` and is therefore
|
||||
//! independent of disk paths, registration order and hash-map iteration;
|
||||
//! * a bound target names the *resolved implementation*, including the plugin
|
||||
//! package, complete export name and verified artifact digest for ABI calls;
|
||||
//! * [`BoundTarget::DynamicValue`] is the only non-static path and may only
|
||||
//! call language values (for example a `FunctionRef`); it is never a back
|
||||
//! door to an unknown ABI export.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{FunctionId, ModuleId};
|
||||
|
||||
/// Stable identity of one static call site.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub struct CallSiteKey {
|
||||
/// Module containing the call.
|
||||
pub module: ModuleId,
|
||||
/// Function containing the call.
|
||||
pub function: FunctionId,
|
||||
/// First byte offset of the call expression.
|
||||
pub span_start: usize,
|
||||
/// End byte offset (exclusive) of the call expression.
|
||||
pub span_end: usize,
|
||||
}
|
||||
|
||||
impl CallSiteKey {
|
||||
/// Construct a key from a function identity and an expression span.
|
||||
pub fn new(function: FunctionId, span: marqdo_span::Span) -> Self {
|
||||
Self {
|
||||
module: function.module.clone(),
|
||||
function,
|
||||
span_start: span.start,
|
||||
span_end: span.end,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for CallSiteKey {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}@{}..{}",
|
||||
self.function, self.span_start, self.span_end
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolved implementation target for a call site.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum BoundTarget {
|
||||
/// A fixed language builtin, by canonical builtin name.
|
||||
Builtin {
|
||||
/// Canonical name (for example `math.eval`), not a user alias.
|
||||
canonical_name: String,
|
||||
},
|
||||
/// A function defined by a Markdown heading.
|
||||
Marqdo {
|
||||
/// Exact function identity.
|
||||
function: FunctionId,
|
||||
},
|
||||
/// A statically declared ABI plugin export.
|
||||
AbiPlugin {
|
||||
/// Plugin package that owns the export.
|
||||
package: String,
|
||||
/// Complete dotted export name.
|
||||
export: String,
|
||||
/// Verified artifact digest from the selected manifest artifact.
|
||||
digest: String,
|
||||
/// Declared parameter names in manifest order; used to normalise
|
||||
/// positional arguments deterministically for the ABI v1 map wire.
|
||||
param_names: Vec<String>,
|
||||
},
|
||||
/// The callee is a language value resolved at runtime (local variable or
|
||||
/// an expression result). Only language callables such as `FunctionRef`
|
||||
/// are valid; this path cannot invoke an ABI plugin.
|
||||
DynamicValue,
|
||||
}
|
||||
|
||||
impl BoundTarget {
|
||||
/// Whether this binding names a statically known implementation.
|
||||
pub fn is_static(&self) -> bool {
|
||||
!matches!(self, BoundTarget::DynamicValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// One deterministic binding table for a prepared program.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct CallBindingTable {
|
||||
sites: BTreeMap<CallSiteKey, BoundTarget>,
|
||||
}
|
||||
|
||||
impl CallBindingTable {
|
||||
/// Insert a binding. Returns `false` when the site was already bound to a
|
||||
/// different target; re-binding the same target is idempotent.
|
||||
pub fn insert(&mut self, key: CallSiteKey, target: BoundTarget) -> bool {
|
||||
match self.sites.get(&key) {
|
||||
Some(existing) => existing == &target,
|
||||
None => {
|
||||
self.sites.insert(key, target);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Look up the bound target for a call site.
|
||||
pub fn get(&self, key: &CallSiteKey) -> Option<&BoundTarget> {
|
||||
self.sites.get(key)
|
||||
}
|
||||
|
||||
/// Number of bound call sites.
|
||||
pub fn len(&self) -> usize {
|
||||
self.sites.len()
|
||||
}
|
||||
|
||||
/// Whether no call site is bound.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.sites.is_empty()
|
||||
}
|
||||
|
||||
/// Iterate bindings deterministically (call site order).
|
||||
pub fn iter(&self) -> impl Iterator<Item = (&CallSiteKey, &BoundTarget)> {
|
||||
self.sites.iter()
|
||||
}
|
||||
|
||||
/// Number of statically bound (non-dynamic) call sites.
|
||||
pub fn static_count(&self) -> usize {
|
||||
self.sites
|
||||
.values()
|
||||
.filter(|target| target.is_static())
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Number of dynamically resolved call sites.
|
||||
pub fn dynamic_count(&self) -> usize {
|
||||
self.sites.len() - self.static_count()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use marqdo_span::Span;
|
||||
|
||||
fn function(name: &str) -> FunctionId {
|
||||
FunctionId {
|
||||
module: ModuleId::root_default("index.mq.md"),
|
||||
name: name.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn key(name: &str, span: Span) -> CallSiteKey {
|
||||
CallSiteKey::new(function(name), span)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_are_deterministic_and_span_based() {
|
||||
let left = key("f", Span::new(10, 20));
|
||||
let right = key("f", Span::new(10, 20));
|
||||
let other = key("f", Span::new(21, 30));
|
||||
assert_eq!(left, right);
|
||||
assert_ne!(left, other);
|
||||
assert_eq!(left.to_string(), "root:default::index.mq.md::f@10..20");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_is_idempotent_but_rejects_conflicting_targets() {
|
||||
let mut table = CallBindingTable::default();
|
||||
let site = key("f", Span::new(1, 2));
|
||||
assert!(table.insert(
|
||||
site.clone(),
|
||||
BoundTarget::Builtin {
|
||||
canonical_name: "长度".into()
|
||||
}
|
||||
));
|
||||
assert!(table.insert(
|
||||
site.clone(),
|
||||
BoundTarget::Builtin {
|
||||
canonical_name: "长度".into()
|
||||
}
|
||||
));
|
||||
assert!(!table.insert(site, BoundTarget::DynamicValue));
|
||||
assert_eq!(table.len(), 1);
|
||||
assert_eq!(table.static_count(), 1);
|
||||
assert_eq!(table.dynamic_count(), 0);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{builtins, Function, Module, ModuleId, Param, Program, SignatureKind};
|
||||
use crate::{builtins, Function, FunctionId, Module, ModuleId, Param, Program, SignatureKind};
|
||||
use marqdo_span::Span;
|
||||
|
||||
/// Globally unique callable identity.
|
||||
@@ -138,6 +138,42 @@ pub struct CallableRegistry {
|
||||
builtins: BTreeMap<String, CallableDescriptor>,
|
||||
functions: BTreeMap<ModuleId, BTreeMap<String, CallableDescriptor>>,
|
||||
external: BTreeMap<String, CallableDescriptor>,
|
||||
/// Official stdlib public aliases (for example `打印`/`print`) mapped to
|
||||
/// the bundled Markdown function that implements them. Only the verified
|
||||
/// stdlib loader may populate this table; third-party packages cannot.
|
||||
official_aliases: BTreeMap<String, FunctionId>,
|
||||
}
|
||||
|
||||
/// One official bundled-stdlib public alias.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct OfficialAlias {
|
||||
/// Public names that resolve to the same target (for example both
|
||||
/// `打印` and `print`).
|
||||
pub public_names: Vec<String>,
|
||||
/// Bundled Marqdo function implementing the alias.
|
||||
pub function: FunctionId,
|
||||
/// Effective signature; the loader must have checked it against the
|
||||
/// verified stdlib metadata before registration.
|
||||
pub signature: CallableSignature,
|
||||
/// Owner package instance (the verified stdlib instance).
|
||||
pub owner_package: String,
|
||||
/// Conservative effect request summary for Trace/Analysis.
|
||||
pub effects_requested: Vec<String>,
|
||||
}
|
||||
|
||||
/// A deterministic static-table conflict.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CallableConflict {
|
||||
/// Colliding public name.
|
||||
pub public_name: String,
|
||||
/// Human-readable reason; never used as a machine code.
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
impl fmt::Display for CallableConflict {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "`{}`: {}", self.public_name, self.reason)
|
||||
}
|
||||
}
|
||||
|
||||
impl CallableRegistry {
|
||||
@@ -150,21 +186,46 @@ impl CallableRegistry {
|
||||
}
|
||||
|
||||
/// Build a registry for all modules and declared external descriptors.
|
||||
pub fn from_program(program: &Program) -> Self {
|
||||
///
|
||||
/// Duplicate external names are rejected rather than silently keeping the
|
||||
/// first entry: a static table must never depend on registration order.
|
||||
pub fn try_from_program(program: &Program) -> Result<Self, CallableConflict> {
|
||||
let mut registry = Self::default();
|
||||
registry.add_builtins();
|
||||
for module in program.modules.values() {
|
||||
registry.add_module(module);
|
||||
}
|
||||
for descriptor in &program.external_callables {
|
||||
// Conflicting declarations are reported by the loader; keep the
|
||||
// first deterministic entry here rather than overwriting silently.
|
||||
registry
|
||||
.external
|
||||
.entry(descriptor.public_name.clone())
|
||||
.or_insert_with(|| descriptor.clone());
|
||||
.insert_external(descriptor.clone())
|
||||
.map_err(|reason| CallableConflict {
|
||||
public_name: descriptor.public_name.clone(),
|
||||
reason,
|
||||
})?;
|
||||
}
|
||||
registry
|
||||
Ok(registry)
|
||||
}
|
||||
|
||||
/// Build a registry for all modules and declared external descriptors.
|
||||
///
|
||||
/// Prefer [`CallableRegistry::try_from_program`] on the CLI composition
|
||||
/// path; this compatibility wrapper keeps the first declaration for
|
||||
/// already-validated callers (tests and embedders).
|
||||
pub fn from_program(program: &Program) -> Self {
|
||||
Self::try_from_program(program).unwrap_or_else(|_| {
|
||||
let mut registry = Self::default();
|
||||
registry.add_builtins();
|
||||
for module in program.modules.values() {
|
||||
registry.add_module(module);
|
||||
}
|
||||
for descriptor in &program.external_callables {
|
||||
registry
|
||||
.external
|
||||
.entry(descriptor.public_name.clone())
|
||||
.or_insert_with(|| descriptor.clone());
|
||||
}
|
||||
registry
|
||||
})
|
||||
}
|
||||
|
||||
/// Look up a builtin by canonical name or alias.
|
||||
@@ -188,6 +249,85 @@ impl CallableRegistry {
|
||||
self.external.values()
|
||||
}
|
||||
|
||||
/// Register one official bundled-stdlib public alias.
|
||||
///
|
||||
/// The loader calls this only after verifying the bundled stdlib digest and
|
||||
/// the metadata digest, so a third-party package can never claim `打印`,
|
||||
/// `print` or any other official public name through this path.
|
||||
pub fn insert_official_alias(&mut self, alias: OfficialAlias) -> Result<(), String> {
|
||||
if alias.public_names.is_empty() {
|
||||
return Err("official alias must declare at least one public name".to_string());
|
||||
}
|
||||
if alias.function.module.instance.is_empty() || alias.function.name.is_empty() {
|
||||
return Err("official alias target function identity must not be empty".to_string());
|
||||
}
|
||||
for name in &alias.public_names {
|
||||
if name.is_empty() {
|
||||
return Err("official alias public name must not be empty".to_string());
|
||||
}
|
||||
if self.external.contains_key(name) {
|
||||
return Err(format!(
|
||||
"official alias `{name}` conflicts with a declared plugin export"
|
||||
));
|
||||
}
|
||||
let descriptor = CallableDescriptor {
|
||||
id: CallableId(format!("marqdo:{}", alias.function)),
|
||||
public_name: name.clone(),
|
||||
owner_package: alias.owner_package.clone(),
|
||||
signature: alias.signature.clone(),
|
||||
effects_requested: alias.effects_requested.clone(),
|
||||
origin: CallableOrigin::Marqdo,
|
||||
implementation_digest: None,
|
||||
source_span: None,
|
||||
};
|
||||
// Official aliases intentionally replace the reserved placeholder
|
||||
// builtin (for example `打印`); no third-party path can do this.
|
||||
self.builtins.insert(name.clone(), descriptor);
|
||||
self.official_aliases
|
||||
.insert(name.clone(), alias.function.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Target Marqdo function of an official alias, if `name` is one.
|
||||
pub fn alias_target(&self, name: &str) -> Option<&FunctionId> {
|
||||
self.official_aliases.get(name)
|
||||
}
|
||||
|
||||
/// Iterate official aliases deterministically (public name, target).
|
||||
pub fn official_aliases(&self) -> impl Iterator<Item = (&String, &FunctionId)> {
|
||||
self.official_aliases.iter()
|
||||
}
|
||||
|
||||
/// Whether a dotted builtin namespace starts with `prefix.`.
|
||||
pub fn has_builtin_dotted_prefix(&self, prefix: &str) -> bool {
|
||||
self.builtins.keys().any(|name| {
|
||||
name.strip_prefix(prefix)
|
||||
.is_some_and(|rest| rest.starts_with('.'))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a declared plugin export starts with `prefix.`.
|
||||
pub fn has_external_dotted_prefix(&self, prefix: &str) -> bool {
|
||||
self.external.keys().any(|name| {
|
||||
name.strip_prefix(prefix)
|
||||
.is_some_and(|rest| rest.starts_with('.'))
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolve a module function to its exact identity.
|
||||
pub fn function_id(&self, module: &ModuleId, name: &str) -> Option<FunctionId> {
|
||||
let descriptor = self.function(module, name)?;
|
||||
if matches!(descriptor.origin, CallableOrigin::Marqdo) {
|
||||
Some(FunctionId {
|
||||
module: module.clone(),
|
||||
name: descriptor.public_name.clone(),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert an external descriptor, rejecting duplicate public names.
|
||||
pub fn insert_external(&mut self, descriptor: CallableDescriptor) -> Result<(), String> {
|
||||
if self.builtins.contains_key(&descriptor.public_name) {
|
||||
|
||||
@@ -17,6 +17,7 @@ use marqdo_span::Span;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub mod builtins;
|
||||
pub mod call_binding;
|
||||
pub mod callable;
|
||||
|
||||
/// Canonical logical identity of a module: package instance plus a path
|
||||
@@ -476,10 +477,13 @@ 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/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>,
|
||||
/// Resolved static call bindings (RFC-EXT-0001 §4.2, ADR-0054).
|
||||
///
|
||||
/// Internal IR: deliberately skipped on the wire so Analysis/Trace v2
|
||||
/// consumers are unaffected. A prepared program always carries a complete
|
||||
/// table; the runtime never re-resolves names.
|
||||
#[serde(skip)]
|
||||
pub call_bindings: call_binding::CallBindingTable,
|
||||
}
|
||||
|
||||
impl Program {
|
||||
@@ -517,6 +521,19 @@ impl Program {
|
||||
pub fn callable_registry(&self) -> callable::CallableRegistry {
|
||||
callable::CallableRegistry::from_program(self)
|
||||
}
|
||||
|
||||
/// Resolved static call binding for one call site, if any.
|
||||
pub fn call_binding(
|
||||
&self,
|
||||
key: &call_binding::CallSiteKey,
|
||||
) -> Option<&call_binding::BoundTarget> {
|
||||
self.call_bindings.get(key)
|
||||
}
|
||||
|
||||
/// Install the prepared binding table.
|
||||
pub fn set_call_bindings(&mut self, bindings: call_binding::CallBindingTable) {
|
||||
self.call_bindings = bindings;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
Reference in new issue
Block a user