feat(m0.6-r1): unified callable registry

- add CallableId/Descriptor/Origin and CallableRegistry in marqdo-ir
- include builtins, Marqdo functions and declared ABI exports in one static
  lookup model with deterministic conflict rules
- validate declared plugin export signatures in the frontend without loading
  any shared library
- add registry and frontend static-plugin-signature tests
This commit is contained in:
cflmy committed 2026-11-20 11:38:04 +08:00
1 parent 5877d9aa5e
commit 4ecf537141
4 files changed
+440 -1

No files matched your search

+61
View File
@@ -268,6 +268,21 @@ impl<'a> CallChecker<'a> {
}
}
}
// A declared ABI export is a static descriptor: validate
// its signature here, without loading the shared library.
if let Some(program) = self.program {
if let Some(descriptor) = program.external_callable(&qualified) {
if let Err(message) =
descriptor.signature.validate_args(args, &qualified)
{
self.diagnostics.push(
Diagnostic::error(codes::CALL_ARITY, Some(span), message)
.with_hint("check the plugin manifest export signature"),
);
}
return;
}
}
}
self.expr(base);
}
@@ -437,6 +452,52 @@ mod tests {
assert!(diagnostics.iter().any(|d| d.code == codes::SYMBOL_UNKNOWN));
}
#[test]
fn declared_plugin_export_is_checked_statically() {
use marqdo_ir::callable::{
CallableDescriptor, CallableId, CallableOrigin, CallableSignature,
};
let module = make_module(vec![function(
"main",
&[],
SignatureKind::Explicit,
vec![return_call("solver.add(a=1)")],
)]);
let mut program = marqdo_ir::Program::default();
program.modules.insert(module.id.clone(), module.clone());
program.external_callables.push(CallableDescriptor {
id: CallableId("plugin:demo:solver.add".into()),
public_name: "solver.add".into(),
owner_package: "demo".into(),
signature: CallableSignature {
params: vec![
Param {
name: "a".into(),
span: Span::new(0, 0),
type_annotation: None,
default: None,
},
Param {
name: "b".into(),
span: Span::new(0, 0),
type_annotation: None,
default: None,
},
],
kind: SignatureKind::Explicit,
},
effects_requested: vec!["host".into()],
origin: CallableOrigin::AbiPlugin {
package: "demo".into(),
export: "solver.add".into(),
},
implementation_digest: None,
source_span: None,
});
let diagnostics = validate_program(&program);
assert!(diagnostics.iter().any(|(_, d)| d.code == codes::CALL_ARITY));
}
#[test]
fn inferred_signature_requires_named_arguments() {
let callee = function("f", &["n"], SignatureKind::Inferred, vec![]);
+361
View File
@@ -0,0 +1,361 @@
//! Unified callable descriptors and lookup (ADR-0009).
//!
//! The language keeps builtins closed and functions defined by Markdown
//! headings, but the *resolution* layer is shared by the frontend, the runtime
//! and plugin export registration. A descriptor carries a static signature and
//! an explicit origin; it never grants authority by itself.
use std::collections::BTreeMap;
use std::fmt;
use serde::{Deserialize, Serialize};
use crate::{builtins, Function, Module, ModuleId, Param, Program, SignatureKind};
use marqdo_span::Span;
/// Globally unique callable identity.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct CallableId(pub String);
impl fmt::Display for CallableId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
/// Where the implementation lives.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CallableOrigin {
/// A fixed language builtin.
Builtin,
/// A function defined by a Markdown heading.
Marqdo,
/// An export declared by a plugin manifest.
AbiPlugin {
/// Plugin package name.
package: String,
/// Complete dotted export name.
export: String,
},
}
/// Static signature used for checking calls before execution.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CallableSignature {
/// Parameters in declaration order.
pub params: Vec<Param>,
/// Explicit signatures allow positional arguments; inferred do not.
pub kind: SignatureKind,
}
impl CallableSignature {
/// Validate an argument list by name/position and arity.
pub fn validate_args(
&self,
args: &[marqdo_expression::Arg],
display: &str,
) -> Result<(), String> {
let mut provided = Vec::new();
let mut positional = 0usize;
for arg in args {
match &arg.name {
Some(name) => {
if !self.params.iter().any(|param| &param.name == name) {
return Err(format!("`{display}` has no parameter named `{name}`"));
}
if provided.contains(name) {
return Err(format!("duplicate argument `{name}`"));
}
provided.push(name.clone());
}
None => {
if self.kind != SignatureKind::Explicit {
return Err(format!(
"`{display}` has an inferred signature and only accepts named arguments"
));
}
let Some(param) = self.params.get(positional) else {
return Err(format!(
"`{display}` accepts at most {} positional arguments",
self.params.len()
));
};
if provided.contains(&param.name) {
return Err(format!("duplicate argument `{}`", param.name));
}
provided.push(param.name.clone());
positional += 1;
}
}
}
for param in &self.params {
if param.default.is_none() && !provided.iter().any(|name| name == &param.name) {
return Err(format!(
"`{display}` is missing required argument `{}`",
param.name
));
}
}
Ok(())
}
}
/// One statically visible callable.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CallableDescriptor {
/// Globally unique id.
pub id: CallableId,
/// Name used from the language surface.
pub public_name: String,
/// Owning package instance (`core` for builtins).
pub owner_package: String,
/// Signature.
pub signature: CallableSignature,
/// Conservative effect request summary; not proof of purity.
#[serde(default)]
pub effects_requested: Vec<String>,
/// Implementation origin.
pub origin: CallableOrigin,
/// Content digest of the implementation, when known.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub implementation_digest: Option<String>,
/// Declaration source location, when known.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_span: Option<Span>,
}
impl CallableDescriptor {
/// Whether this is a builtin.
pub fn is_builtin(&self) -> bool {
matches!(self.origin, CallableOrigin::Builtin)
}
}
/// Deterministic callable index for one program or module.
#[derive(Debug, Clone, Default)]
pub struct CallableRegistry {
builtins: BTreeMap<String, CallableDescriptor>,
functions: BTreeMap<ModuleId, BTreeMap<String, CallableDescriptor>>,
external: BTreeMap<String, CallableDescriptor>,
}
impl CallableRegistry {
/// Build a registry containing builtins plus every function in `module`.
pub fn for_module(module: &Module) -> Self {
let mut registry = Self::default();
registry.add_builtins();
registry.add_module(module);
registry
}
/// Build a registry for all modules and declared external descriptors.
pub fn from_program(program: &Program) -> Self {
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());
}
registry
}
/// Look up a builtin by canonical name or alias.
pub fn builtin(&self, name: &str) -> Option<&CallableDescriptor> {
self.builtins.get(name)
}
/// Look up an ABI export by complete dotted name.
pub fn external(&self, name: &str) -> Option<&CallableDescriptor> {
self.external.get(name)
}
/// Look up a function in a module by canonical name, then unique local name.
pub fn function(&self, module: &ModuleId, name: &str) -> Option<&CallableDescriptor> {
let table = self.functions.get(module)?;
table.get(name)
}
/// Iterate external descriptors deterministically.
pub fn externals(&self) -> impl Iterator<Item = &CallableDescriptor> {
self.external.values()
}
/// 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) {
return Err(format!(
"external callable `{}` conflicts with a builtin",
descriptor.public_name
));
}
if self.external.contains_key(&descriptor.public_name) {
return Err(format!(
"external callable `{}` is declared more than once",
descriptor.public_name
));
}
self.external
.insert(descriptor.public_name.clone(), descriptor);
Ok(())
}
fn add_builtins(&mut self) {
for builtin in builtins::BUILTINS {
let descriptor = builtin_descriptor(builtin);
self.builtins
.insert(builtin.name.to_string(), descriptor.clone());
for alias in builtin.aliases {
self.builtins
.insert((*alias).to_string(), descriptor.clone());
}
}
}
fn add_module(&mut self, module: &Module) {
let mut table = BTreeMap::new();
for function in &module.functions {
let descriptor = function_descriptor(module, function);
table.insert(function.id.name.clone(), descriptor.clone());
}
// A local name is only a stable key when it is unique in the module.
for function in &module.functions {
let local_matches = module
.functions
.iter()
.filter(|candidate| candidate.local_name == function.local_name)
.count();
if local_matches == 1 {
if let Some(descriptor) = table.get(&function.id.name).cloned() {
table
.entry(function.local_name.clone())
.or_insert(descriptor);
}
}
}
self.functions.insert(module.id.clone(), table);
}
}
fn builtin_descriptor(builtin: &builtins::Builtin) -> CallableDescriptor {
CallableDescriptor {
id: CallableId(format!("builtin:{}", builtin.name)),
public_name: builtin.name.to_string(),
owner_package: "core".to_string(),
signature: CallableSignature {
params: builtin
.params
.iter()
.map(|param| Param {
name: param.name.to_string(),
span: Span::default(),
type_annotation: None,
default: None,
})
.collect(),
kind: SignatureKind::Explicit,
},
effects_requested: if builtin.effectful {
vec!["host".to_string()]
} else {
Vec::new()
},
origin: CallableOrigin::Builtin,
implementation_digest: None,
source_span: None,
}
}
fn function_descriptor(module: &Module, function: &Function) -> CallableDescriptor {
CallableDescriptor {
id: CallableId(format!("marqdo:{}", function.id)),
public_name: function.id.name.clone(),
owner_package: module.id.instance.clone(),
signature: CallableSignature {
params: function.params.clone(),
kind: function.signature,
},
effects_requested: vec!["unknown".to_string()],
origin: CallableOrigin::Marqdo,
implementation_digest: None,
source_span: Some(function.heading_span),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Module;
fn empty_module(id: &str) -> Module {
Module {
id: ModuleId::from(id),
units: Vec::new(),
functions: Vec::new(),
imports: Vec::new(),
resources: Vec::new(),
anchors: BTreeMap::new(),
}
}
#[test]
fn builtins_are_registered_with_aliases() {
let registry = CallableRegistry::for_module(&empty_module("index.mq.md"));
assert_eq!(registry.builtin("print").unwrap().id.0, "builtin:打印");
assert_eq!(registry.builtin("打印").unwrap().id.0, "builtin:打印");
assert!(registry.builtin("nope").is_none());
assert!(registry
.builtin("print")
.unwrap()
.effects_requested
.contains(&"host".to_string()));
}
#[test]
fn external_names_must_be_unique_and_not_shadow_builtins() {
let mut registry = CallableRegistry::for_module(&empty_module("index.mq.md"));
let descriptor = CallableDescriptor {
id: CallableId("plugin:demo:solver.add".into()),
public_name: "solver.add".into(),
owner_package: "demo".into(),
signature: CallableSignature {
params: Vec::new(),
kind: SignatureKind::Explicit,
},
effects_requested: Vec::new(),
origin: CallableOrigin::AbiPlugin {
package: "demo".into(),
export: "solver.add".into(),
},
implementation_digest: None,
source_span: None,
};
registry.insert_external(descriptor.clone()).unwrap();
assert!(registry.insert_external(descriptor).is_err());
let mut shadow = CallableDescriptor {
id: CallableId("plugin:demo:print".into()),
public_name: "print".into(),
owner_package: "demo".into(),
signature: CallableSignature {
params: Vec::new(),
kind: SignatureKind::Explicit,
},
effects_requested: Vec::new(),
origin: CallableOrigin::AbiPlugin {
package: "demo".into(),
export: "print".into(),
},
implementation_digest: None,
source_span: None,
};
shadow.public_name = "print".into();
assert!(registry.insert_external(shadow).is_err());
}
}
+17
View File
@@ -17,6 +17,7 @@ use marqdo_span::Span;
use serde::{Deserialize, Serialize};
pub mod builtins;
pub mod callable;
/// Canonical logical identity of a module: package instance plus a path
/// relative to that package's module root.
@@ -477,6 +478,10 @@ pub struct Program {
/// Resolved import edges.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub resolved_imports: Vec<ResolvedImport>,
/// Explicit external callable descriptors (plugin manifests). They are
/// metadata only: `check` never loads a library.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub external_callables: Vec<callable::CallableDescriptor>,
}
impl Program {
@@ -502,6 +507,18 @@ impl Program {
.find(|edge| &edge.from == from && edge.alias == alias)
.map(|edge| &edge.to)
}
/// Static external callable descriptor by complete dotted name.
pub fn external_callable(&self, name: &str) -> Option<&callable::CallableDescriptor> {
self.external_callables
.iter()
.find(|descriptor| descriptor.public_name == name)
}
/// Build the unified callable registry for this program.
pub fn callable_registry(&self) -> callable::CallableRegistry {
callable::CallableRegistry::from_program(self)
}
}
#[cfg(test)]
+1 -1
View File
@@ -40,7 +40,7 @@ providers).
| Step | State | Evidence |
|---|---|---|
| R0 baseline + ADRs | **Done** | this section; `docs/adr/0008`–`0012`; full workspace gate |
| R1 package-aware identity | **In progress** | `ModuleId { instance, relative_path }`; `PackageResolver` path sources; `lock_version: 2` with v1 migration; tests in `marqdo-package` |
| R1 package-aware identity + callable registry | **Done for statics** | `ModuleId { instance, relative_path }`; `PackageResolver` path sources; `lock_version: 2` with v1 migration; `CallableRegistry` for builtins/marqdo/declared ABI exports; external manifest wiring is R2 |
| R2 ABI/Kernel/Broker | Not started | — |
| R3 Tool Protocol | Not started | — |
| R4 Analysis/Trace v1 | Not started | — |