feat: complete BoundCall dual-backend and reuse bind gate (G02)
Share resolve_for_exec across Tree/Bytecode and semantic projections, emit bound_calls/dynamic_calls, and require eng_reuse bind_targets before execute so discovery scores cannot be treated as handles. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
e9ae7ff1ae
commit
0e1bfb3359
12 files changed
+925
-154
No files matched your search
@@ -189,7 +189,7 @@ P0/P1/P2 分类改为缺口领域,不再按编号整组串行:G06 的未知
|
||||
|---|---|---|---|
|
||||
| S0 作者基线与最小语料 | 无 | 六类实际写作/复用任务、当前语法入口、无网络最小门禁(G10/G11) | **已落地**:[tests/executable_knowledge/](../../tests/executable_knowledge/README.md) + `cargo test --test executable_knowledge`;Bytecode 裸名同名误连记为基线缺陷待 S2/G02 |
|
||||
| S1 可读步骤与唯一目标 | S0 | 一份文档的源码/步骤/view 联动;统一 resolver、图与上下文节点(G01/G03) | **已落地子集**:G01 双图分离;G03 步骤 kind + `steps.json` + view 导航;同名 import resolve;正文 NarrativeRef 仍待 |
|
||||
| S2 确定执行与早期 AI 复用 | S1 | BoundCall 双后端、最小上下文卡、本地 handle 与现有 Agent 试点(G02/G06/G07/G09 的安全子集) | **已落地子集**:G06 效应;G07 MLSP symbol 绑定;G02 Bytecode 裸名不跨 import scope(`06b` 双后端拒绝);完整 BoundCall IR / Agent 强制 bind 仍待 |
|
||||
| S2 确定执行与早期 AI 复用 | S1 | BoundCall 双后端、最小上下文卡、本地 handle 与现有 Agent 试点(G02/G06/G07/G09 的安全子集) | **已落地**:G02 共享 `resolve_for_exec` + Tree/Bytecode + `bound_calls.json`/`dynamic_calls.json`(`10-boundcall`);G06 效应;G07 MLSP bind/execute;eng_reuse `bind_required`/`bind_targets` |
|
||||
| S3 局部编辑与库可读性 | S1–S2 | 摘要保护的局部补丁、语义 diff、受限纯表达式提取;lib/ext 示例优化(G03/G09/G10/G11) | 无无关改写;提取等价;声明变更可见;不为旧库增加兼容语法 |
|
||||
| S4 业务知识与适用性 | S2;与 S3 可交错 | 书店契约、来源/验证事件、传递效应及政策、负知识(G05/G06/G07/G09) | 分清输入不适用、来源过期和测试失败;纯工具免虚构来源 |
|
||||
| S5 变化传播与严格复用 | S1–S2/S4 | 分类摘要、SCC 闭包、整代快照、impact、严格 handle 复核(G04/G08) | 依赖/证据变化影响正确;文案不混同实现;故障注入无混代 |
|
||||
|
||||
@@ -430,14 +430,73 @@ pub fn eng_preflight(args: &Value) -> Result<Value, String> {
|
||||
}))
|
||||
}
|
||||
|
||||
/// `agent_eng_reuse` — alias of preflight focused on decision payload.
|
||||
/// `agent_eng_reuse` — discovery + REUSE|ADAPT|CREATE decision.
|
||||
///
|
||||
/// Scores and capability names are **not** executable targets (G02/G07).
|
||||
/// When decision is REUSE/ADAPT, callers must `artifact.bind` a
|
||||
/// `bind_targets[]` entry before `artifact.execute`.
|
||||
pub fn eng_reuse(args: &Value) -> Result<Value, String> {
|
||||
let mut pf = eng_preflight(args)?;
|
||||
if let Some(obj) = pf.as_object_mut() {
|
||||
obj.insert(
|
||||
"protocol".into(),
|
||||
json!("REUSE|ADAPT|CREATE"),
|
||||
);
|
||||
obj.insert("protocol".into(), json!("REUSE|ADAPT|CREATE"));
|
||||
obj.insert("discovery_only".into(), json!(true));
|
||||
let decision = obj
|
||||
.get("decision")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_ascii_uppercase();
|
||||
let bind_required = matches!(decision.as_str(), "REUSE" | "ADAPT");
|
||||
obj.insert("bind_required".into(), json!(bind_required));
|
||||
let mut targets = Vec::new();
|
||||
if let Some(cands) = obj.get("candidates").and_then(|v| v.as_array()) {
|
||||
for c in cands {
|
||||
if let Some(impls) = c.get("implemented_by").and_then(|v| v.as_array()) {
|
||||
for t in impls {
|
||||
if let Some(s) = t.as_str() {
|
||||
if !s.is_empty() {
|
||||
targets.push(json!({
|
||||
"query": s,
|
||||
"via": "implemented_by",
|
||||
"capability": c.get("name"),
|
||||
"note": "pass query to artifact.bind then artifact.execute",
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(id) = c.get("id").and_then(|v| v.as_str()) {
|
||||
if id.contains(':') || id.contains('.') {
|
||||
targets.push(json!({
|
||||
"query": id,
|
||||
"via": "candidate_id",
|
||||
"capability": c.get("name"),
|
||||
"note": "pass query to artifact.bind then artifact.execute",
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Dedup by query
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
targets.retain(|t| {
|
||||
t.get("query")
|
||||
.and_then(|q| q.as_str())
|
||||
.map(|q| seen.insert(q.to_string()))
|
||||
.unwrap_or(false)
|
||||
});
|
||||
obj.insert("bind_targets".into(), json!(targets));
|
||||
if bind_required {
|
||||
let mut reasons = obj
|
||||
.get("reason")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!([]));
|
||||
if let Some(arr) = reasons.as_array_mut() {
|
||||
arr.push(json!(
|
||||
"scores are discovery-only; bind SymbolId/handle before execute (G02/G07)"
|
||||
));
|
||||
}
|
||||
obj.insert("reason".into(), reasons);
|
||||
}
|
||||
}
|
||||
Ok(pf)
|
||||
}
|
||||
|
||||
+12
-9
@@ -500,13 +500,20 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
|
||||
fn compile_call(&mut self, call: &CallExpr, as_stmt: bool) -> Result<()> {
|
||||
// Mirror `sema::bind::resolve_for_exec` (G02 BoundCall):
|
||||
// static → Op::Call(fid); dynamic → MethodCall / CallFn / PluginCall.
|
||||
let mut call = call
|
||||
.with_modifiers_expanded()
|
||||
.map_err(|m| self.err(m))?;
|
||||
if let Some(recv) = &call.receiver {
|
||||
return self.compile_method_call(recv, &call, as_stmt);
|
||||
}
|
||||
if let Some(path) = &call.path {
|
||||
// Bare dotted callee `a.b`: if `a` is a local variable, it is a method
|
||||
// receiver (Python-style unified namespace); otherwise it's a library path.
|
||||
if path.len() == 2 && self.locals.contains_key(&path[0]) {
|
||||
// Local-var method sugar before import path (same as Tree / resolve_for_exec).
|
||||
if path.len() == 2
|
||||
&& self.locals.contains_key(&path[0])
|
||||
&& !self.flat[self.fn_id].path_index.keys().any(|p| p.first() == Some(&path[0]))
|
||||
{
|
||||
let recv = path[0].clone();
|
||||
return self.compile_method_call(&recv, &call, as_stmt);
|
||||
}
|
||||
@@ -518,10 +525,6 @@ impl<'a> FnCompiler<'a> {
|
||||
call.callee =
|
||||
crate::aliases::normalize_call_callee_and_args(&call.callee, &mut call.args);
|
||||
|
||||
if let Some(recv) = &call.receiver {
|
||||
return self.compile_method_call(recv, &call, as_stmt);
|
||||
}
|
||||
|
||||
match call.callee.as_str() {
|
||||
"print" => {
|
||||
let text_expr = call
|
||||
@@ -678,15 +681,15 @@ impl<'a> FnCompiler<'a> {
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// BoundCall bare name (same-module scope only) or DynamicCall plugin.
|
||||
match self.resolve_call(&call.callee) {
|
||||
Ok(fid) => self.compile_user_call(fid, &call, as_stmt),
|
||||
Err(err) => {
|
||||
// Ambiguous bare names must not fall through to PluginCall (G02).
|
||||
let msg = format!("{err:#}");
|
||||
if msg.contains("ambiguous function") {
|
||||
return Err(err);
|
||||
}
|
||||
// Unresolved bare names may still be runtime plugins.
|
||||
// DynamicCall(Plugin): unresolved bare names may be runtime plugins.
|
||||
self.compile_plugin_call(&call, as_stmt)
|
||||
}
|
||||
}
|
||||
|
||||
+145
-100
@@ -15,7 +15,7 @@ use crate::builtin::{
|
||||
};
|
||||
use crate::debug::{emit_trace, DebugController};
|
||||
use crate::diagnostics::{bail_at, Span};
|
||||
use crate::host::{call_host, HostContext, HostFn};
|
||||
use crate::host::{call_host, HostContext};
|
||||
use crate::input_feed::InputFeed;
|
||||
use crate::capture::{
|
||||
BranchHit, CallFrame, LoopFrame, LoopHit, LoopIter, StmtEvent, StmtEventKind, ViewTrace,
|
||||
@@ -1180,34 +1180,150 @@ impl Interpreter {
|
||||
return self.eval_method_call(module, fun, env, recv_name, &call.callee, &ev_args);
|
||||
}
|
||||
|
||||
// Local-var method sugar (`a.b` when `a` is in env) before BoundCall path resolve.
|
||||
if let Some(path) = &call.path {
|
||||
// Bare dotted callee `a.b`: if `a` is a local variable, it is a method
|
||||
// receiver (Python-style unified namespace); otherwise it's a library path.
|
||||
if path.len() == 2 && env.get(&path[0]).is_some() {
|
||||
if path.len() == 2
|
||||
&& env.get(&path[0]).is_some()
|
||||
&& !module.import_modules.contains_key(&path[0])
|
||||
{
|
||||
let recv = path[0].clone();
|
||||
let method = path[1].clone();
|
||||
return self.eval_method_call(module, fun, env, &recv, &method, &ev_args);
|
||||
}
|
||||
return self.eval_path_call(module, path, &ev_args);
|
||||
}
|
||||
|
||||
if let Some(u) = module.uses.iter().find(|u| u.bind == call.callee) {
|
||||
return self.eval_path_call(module, &u.path, &ev_args);
|
||||
use crate::sema::bind::{resolve_for_exec, DynamicReason, ExecTarget};
|
||||
match resolve_for_exec(module, fun, &call) {
|
||||
ExecTarget::Local(target) => {
|
||||
self.eval_bound_function_call(module, fun, env, target, &ev_args)
|
||||
}
|
||||
ExecTarget::Import {
|
||||
lib: lib_mod,
|
||||
fun: target,
|
||||
..
|
||||
} => self.eval_bound_function_call(lib_mod, fun, env, target, &ev_args),
|
||||
ExecTarget::Builtin(name) => self.eval_builtin_call(name, &ev_args),
|
||||
ExecTarget::Host(hf) => {
|
||||
let mut params: Vec<String> =
|
||||
hf.required_params().iter().map(|s| (*s).to_string()).collect();
|
||||
for p in hf.optional_params() {
|
||||
params.push((*p).to_string());
|
||||
}
|
||||
let bound = bind_args(¶ms, &ev_args, true).map_err(|m| self.err(m))?;
|
||||
for req in hf.required_params() {
|
||||
if !bound.contains_key(*req) {
|
||||
return Err(self.err(format!("{} requires `{req}`", hf.name())));
|
||||
}
|
||||
}
|
||||
call_host(&mut self.host, hf, &bound).map_err(|m| self.err(m))
|
||||
}
|
||||
ExecTarget::Dynamic {
|
||||
reason: DynamicReason::CallFn,
|
||||
..
|
||||
} => {
|
||||
let bound = bind_args(&["name".into()], &ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let name = match bound.get("name") {
|
||||
Some(Value::Text(s)) => s.as_str(),
|
||||
_ => return Err(self.err("call_fn requires text name")),
|
||||
};
|
||||
let target = lookup_function(module, fun, name).ok_or_else(|| {
|
||||
self.err(format!("call_fn: unknown function `{name}`"))
|
||||
})?;
|
||||
if !target.params.is_empty() {
|
||||
return Err(self.err(format!(
|
||||
"call_fn: `{name}` must have no parameters"
|
||||
)));
|
||||
}
|
||||
self.run_function(module, target, Env::new(), &[], false)
|
||||
}
|
||||
ExecTarget::Dynamic {
|
||||
reason: DynamicReason::Plugin,
|
||||
name,
|
||||
} => {
|
||||
if let Some(reg) = self.host.plugins.get(&name).cloned() {
|
||||
let bound =
|
||||
bind_args(®.params, &ev_args, false).map_err(|m| self.err(m))?;
|
||||
return self
|
||||
.call_plugin_registered(&name, &bound)
|
||||
.map_err(|m| self.err(m));
|
||||
}
|
||||
Err(self.err(format!("unknown function `{name}`")))
|
||||
}
|
||||
ExecTarget::Dynamic {
|
||||
reason: DynamicReason::MethodReceiver,
|
||||
name,
|
||||
} => {
|
||||
if let Some(path) = &call.path {
|
||||
if path.len() == 2 && env.get(&path[0]).is_some() {
|
||||
return self.eval_method_call(
|
||||
module,
|
||||
fun,
|
||||
env,
|
||||
&path[0],
|
||||
&path[1],
|
||||
&ev_args,
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(self.err(format!("unresolved dynamic call `{name}`")))
|
||||
}
|
||||
ExecTarget::Unresolved { message, .. } => Err(self.err(message)),
|
||||
}
|
||||
}
|
||||
|
||||
match call.callee.as_str() {
|
||||
/// Invoke a function already resolved via [`crate::sema::bind::resolve_for_exec`].
|
||||
fn eval_bound_function_call(
|
||||
&mut self,
|
||||
module: &Module,
|
||||
caller: &Function,
|
||||
env: &mut Env,
|
||||
target: &Function,
|
||||
ev_args: &[EvArg],
|
||||
) -> Result<Value> {
|
||||
let bound =
|
||||
bind_function_args(self, module, caller, env, &target.params, ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
if let Some(c) = &target.contract {
|
||||
if let Some(d) = crate::contract::call_arg_diag(
|
||||
c,
|
||||
&target.name,
|
||||
&bound,
|
||||
self.path.as_deref(),
|
||||
self.current_span,
|
||||
) {
|
||||
return Err(d.into());
|
||||
}
|
||||
}
|
||||
let mut call_env = Env::new();
|
||||
for (k, v) in bound {
|
||||
call_env.set(k, v);
|
||||
}
|
||||
self.host.push_call_site_line(self.host.current_line);
|
||||
let result = self.run_function(module, target, call_env, &[], false);
|
||||
self.host.pop_call_site_line();
|
||||
let result = result?;
|
||||
if target.is_object() {
|
||||
Ok(tag_instance(&target.name, result))
|
||||
} else {
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
fn eval_builtin_call(&mut self, name: &str, ev_args: &[EvArg]) -> Result<Value> {
|
||||
match name {
|
||||
"print" => {
|
||||
let bound = bind_args(&["text".into()], &ev_args, false)
|
||||
let bound = bind_args(&["text".into()], ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let text = bound
|
||||
.get("text")
|
||||
.map(|v| v.as_display())
|
||||
.ok_or_else(|| self.err("print requires text (named or positional)"))?;
|
||||
self.emit_line(&text);
|
||||
return Ok(Value::None);
|
||||
Ok(Value::None)
|
||||
}
|
||||
"input" => {
|
||||
let bound = bind_args(&["prompt".into()], &ev_args, true)
|
||||
let bound = bind_args(&["prompt".into()], ev_args, true)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let prompt = bound
|
||||
.get("prompt")
|
||||
@@ -1232,52 +1348,52 @@ impl Interpreter {
|
||||
e
|
||||
}
|
||||
})?;
|
||||
return Ok(Value::Text(line));
|
||||
Ok(Value::Text(line))
|
||||
}
|
||||
"len" => {
|
||||
let bound = bind_args(&["value".into()], &ev_args, false)
|
||||
let bound = bind_args(&["value".into()], ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let v = bound
|
||||
.get("value")
|
||||
.ok_or_else(|| self.err("len requires value"))?;
|
||||
let n = builtin_len(v).map_err(|m| self.err(m))?;
|
||||
return Ok(Value::Int(n));
|
||||
Ok(Value::Int(n))
|
||||
}
|
||||
"str" => {
|
||||
let bound = bind_args(&["value".into()], &ev_args, false)
|
||||
let bound = bind_args(&["value".into()], ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let v = bound
|
||||
.get("value")
|
||||
.ok_or_else(|| self.err("str requires value"))?;
|
||||
return Ok(builtin_str(v));
|
||||
Ok(builtin_str(v))
|
||||
}
|
||||
"int" => {
|
||||
let bound = bind_args(&["value".into()], &ev_args, false)
|
||||
let bound = bind_args(&["value".into()], ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let v = bound
|
||||
.get("value")
|
||||
.ok_or_else(|| self.err("int requires value"))?;
|
||||
let n = builtin_int(v).map_err(|m| self.err(m))?;
|
||||
return Ok(Value::Int(n));
|
||||
Ok(Value::Int(n))
|
||||
}
|
||||
"type" => {
|
||||
let bound = bind_args(&["value".into()], &ev_args, false)
|
||||
let bound = bind_args(&["value".into()], ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let v = bound
|
||||
.get("value")
|
||||
.ok_or_else(|| self.err("type requires value"))?;
|
||||
return Ok(builtin_type(v));
|
||||
Ok(builtin_type(v))
|
||||
}
|
||||
"trim" => {
|
||||
let bound = bind_args(&["value".into()], &ev_args, false)
|
||||
let bound = bind_args(&["value".into()], ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let v = bound
|
||||
.get("value")
|
||||
.ok_or_else(|| self.err("trim requires value"))?;
|
||||
return builtin_trim(v).map_err(|m| self.err(m));
|
||||
builtin_trim(v).map_err(|m| self.err(m))
|
||||
}
|
||||
"split" => {
|
||||
let bound = bind_args(&["value".into(), "sep".into()], &ev_args, false)
|
||||
let bound = bind_args(&["value".into(), "sep".into()], ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let value = bound
|
||||
.get("value")
|
||||
@@ -1285,10 +1401,10 @@ impl Interpreter {
|
||||
let sep = bound
|
||||
.get("sep")
|
||||
.ok_or_else(|| self.err("split requires sep"))?;
|
||||
return builtin_split(value, sep).map_err(|m| self.err(m));
|
||||
builtin_split(value, sep).map_err(|m| self.err(m))
|
||||
}
|
||||
"join" => {
|
||||
let bound = bind_args(&["value".into(), "sep".into()], &ev_args, false)
|
||||
let bound = bind_args(&["value".into(), "sep".into()], ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let value = bound
|
||||
.get("value")
|
||||
@@ -1296,10 +1412,10 @@ impl Interpreter {
|
||||
let sep = bound
|
||||
.get("sep")
|
||||
.ok_or_else(|| self.err("join requires sep"))?;
|
||||
return builtin_join(value, sep).map_err(|m| self.err(m));
|
||||
builtin_join(value, sep).map_err(|m| self.err(m))
|
||||
}
|
||||
"at" => {
|
||||
let bound = bind_args(&["value".into(), "index".into()], &ev_args, false)
|
||||
let bound = bind_args(&["value".into(), "index".into()], ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let value = bound
|
||||
.get("value")
|
||||
@@ -1307,80 +1423,9 @@ impl Interpreter {
|
||||
let index = bound
|
||||
.get("index")
|
||||
.ok_or_else(|| self.err("at requires index"))?;
|
||||
return builtin_at(value, index).map_err(|m| self.err(m));
|
||||
builtin_at(value, index).map_err(|m| self.err(m))
|
||||
}
|
||||
"call_fn" => {
|
||||
let bound = bind_args(&["name".into()], &ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let name = match bound.get("name") {
|
||||
Some(Value::Text(s)) => s.as_str(),
|
||||
_ => return Err(self.err("call_fn requires text name")),
|
||||
};
|
||||
let target = lookup_function(module, fun, name).ok_or_else(|| {
|
||||
self.err(format!("call_fn: unknown function `{name}`"))
|
||||
})?;
|
||||
if !target.params.is_empty() {
|
||||
return Err(self.err(format!(
|
||||
"call_fn: `{name}` must have no parameters"
|
||||
)));
|
||||
}
|
||||
return self.run_function(module, target, Env::new(), &[], false);
|
||||
}
|
||||
other if HostFn::from_name(other).is_some() => {
|
||||
let hf = HostFn::from_name(other).unwrap();
|
||||
let mut params: Vec<String> =
|
||||
hf.required_params().iter().map(|s| (*s).to_string()).collect();
|
||||
for p in hf.optional_params() {
|
||||
params.push((*p).to_string());
|
||||
}
|
||||
let bound = bind_args(¶ms, &ev_args, true).map_err(|m| self.err(m))?;
|
||||
for req in hf.required_params() {
|
||||
if !bound.contains_key(*req) {
|
||||
return Err(self.err(format!("{} requires `{req}`", hf.name())));
|
||||
}
|
||||
}
|
||||
return call_host(&mut self.host, hf, &bound).map_err(|m| self.err(m));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if let Some(reg) = self.host.plugins.get(&call.callee).cloned() {
|
||||
let bound = bind_args(®.params, &ev_args, false).map_err(|m| self.err(m))?;
|
||||
return self
|
||||
.call_plugin_registered(&call.callee, &bound)
|
||||
.map_err(|m| self.err(m));
|
||||
}
|
||||
|
||||
let target = lookup_function(module, fun, &call.callee)
|
||||
.ok_or_else(|| self.err(format!("unknown function `{}`", call.callee)))?;
|
||||
|
||||
let bound = bind_function_args(self, module, fun, env, &target.params, &ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
// 契约边界 1(T2.2):调用实参 vs 形参契约。
|
||||
if let Some(c) = &target.contract {
|
||||
if let Some(d) = crate::contract::call_arg_diag(
|
||||
c,
|
||||
&target.name,
|
||||
&bound,
|
||||
self.path.as_deref(),
|
||||
self.current_span,
|
||||
) {
|
||||
return Err(d.into());
|
||||
}
|
||||
}
|
||||
let mut call_env = Env::new();
|
||||
for (k, v) in bound {
|
||||
call_env.set(k, v);
|
||||
}
|
||||
|
||||
self.host.push_call_site_line(self.host.current_line);
|
||||
let result = self.run_function(module, target, call_env, &[], false);
|
||||
self.host.pop_call_site_line();
|
||||
let result = result?;
|
||||
if target.is_object() {
|
||||
Ok(tag_instance(&target.name, result))
|
||||
} else {
|
||||
Ok(result)
|
||||
other => Err(self.err(format!("unknown builtin `{other}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -274,6 +274,25 @@ pub fn format_reuse_text(task: &str, result: &ReuseResult) -> String {
|
||||
}
|
||||
|
||||
pub fn reuse_json(task: &str, result: &ReuseResult) -> Value {
|
||||
let bind_required = matches!(
|
||||
result.decision,
|
||||
ReuseDecision::Reuse | ReuseDecision::Adapt
|
||||
);
|
||||
let mut bind_targets = Vec::new();
|
||||
if let Some(sym) = &result.symbol {
|
||||
bind_targets.push(json!({
|
||||
"query": sym,
|
||||
"via": "reuse.symbol",
|
||||
"note": "pass query to artifact.bind then artifact.execute",
|
||||
}));
|
||||
}
|
||||
if let Some(src) = &result.source {
|
||||
bind_targets.push(json!({
|
||||
"query": src,
|
||||
"via": "reuse.source",
|
||||
"note": "pass query to artifact.bind then artifact.execute",
|
||||
}));
|
||||
}
|
||||
json!({
|
||||
"task": task,
|
||||
"decision": result.decision.as_str(),
|
||||
@@ -287,6 +306,9 @@ pub fn reuse_json(task: &str, result: &ReuseResult) -> Value {
|
||||
"constraints": result.constraints,
|
||||
"decisions": result.decisions,
|
||||
"failures": result.failures,
|
||||
"discovery_only": true,
|
||||
"bind_required": bind_required,
|
||||
"bind_targets": bind_targets,
|
||||
"candidates": result.candidates.iter().map(|c| json!({
|
||||
"id": c.id,
|
||||
"kind": c.kind,
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
//! Shared call binding for execution (G02 BoundCall).
|
||||
//!
|
||||
//! Tree and Bytecode must agree: explicit import paths and same-module bare
|
||||
//! names bind; bare names never silently pick an imported symbol; true
|
||||
//! dynamics are marked separately.
|
||||
|
||||
use crate::ast::{CallExpr, Function, Module};
|
||||
use crate::diagnostics::Span;
|
||||
use crate::host::HostFn;
|
||||
|
||||
/// Why a call site is not a static BoundCall.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DynamicReason {
|
||||
MethodReceiver,
|
||||
CallFn,
|
||||
Plugin,
|
||||
}
|
||||
|
||||
impl DynamicReason {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::MethodReceiver => "method_receiver",
|
||||
Self::CallFn => "call_fn",
|
||||
Self::Plugin => "plugin",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runtime resolution shared by Tree (and mirrored by Bytecode rules).
|
||||
#[derive(Debug)]
|
||||
pub enum ExecTarget<'a> {
|
||||
/// Function in the calling module (or nested children).
|
||||
Local(&'a Function),
|
||||
/// `bind.member…` through `module.import_modules`.
|
||||
Import {
|
||||
bind: String,
|
||||
lib: &'a Module,
|
||||
fun: &'a Function,
|
||||
path: Vec<String>,
|
||||
},
|
||||
Builtin(&'static str),
|
||||
Host(HostFn),
|
||||
/// Plugin / method / call_fn — not a static BoundCall.
|
||||
Dynamic {
|
||||
reason: DynamicReason,
|
||||
name: String,
|
||||
},
|
||||
Unresolved {
|
||||
message: String,
|
||||
#[allow(dead_code)]
|
||||
span_hint: Option<Span>,
|
||||
},
|
||||
}
|
||||
|
||||
pub fn call_display(call: &CallExpr) -> String {
|
||||
if let Some(path) = &call.path {
|
||||
return path.join(".");
|
||||
}
|
||||
if let Some(recv) = &call.receiver {
|
||||
return format!("{recv}.{}", call.callee);
|
||||
}
|
||||
call.callee.clone()
|
||||
}
|
||||
|
||||
fn find_in_children<'a>(fun: &'a Function, name: &str) -> Option<&'a Function> {
|
||||
for child in &fun.children {
|
||||
if child.name == name {
|
||||
return Some(child);
|
||||
}
|
||||
if let Some(f) = find_in_children(child, name) {
|
||||
return Some(f);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Same-module bare-name lookup (never searches imports).
|
||||
pub fn lookup_local<'a>(
|
||||
module: &'a Module,
|
||||
current: &'a Function,
|
||||
name: &str,
|
||||
) -> Option<&'a Function> {
|
||||
if let Some(f) = find_in_children(current, name) {
|
||||
return Some(f);
|
||||
}
|
||||
module.functions.iter().find(|f| f.name == name)
|
||||
}
|
||||
|
||||
fn walk_path<'a>(lib: &'a Module, path: &[String]) -> Result<&'a Function, String> {
|
||||
let display = path.join(".");
|
||||
if path.is_empty() {
|
||||
return Err("empty knowledge path".into());
|
||||
}
|
||||
let mut parent_is_object = false;
|
||||
let mut node = lib
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.name == path[0])
|
||||
.ok_or_else(|| format!("unknown `{display}`"))?;
|
||||
for seg in &path[1..] {
|
||||
parent_is_object = node.is_object();
|
||||
node = node
|
||||
.children
|
||||
.iter()
|
||||
.find(|c| c.name == *seg)
|
||||
.ok_or_else(|| format!("unknown `{display}`"))?;
|
||||
}
|
||||
if parent_is_object && node.level != 1 && crate::ast::function_uses_receiver(node) {
|
||||
return Err(format!(
|
||||
"`{display}` is an instance method; call it as `var`.{}",
|
||||
node.name
|
||||
));
|
||||
}
|
||||
Ok(node)
|
||||
}
|
||||
|
||||
fn resolve_import_path<'a>(module: &'a Module, path: &[String]) -> ExecTarget<'a> {
|
||||
let display = path.join(".");
|
||||
if path.len() < 2 {
|
||||
return ExecTarget::Unresolved {
|
||||
message: format!("library path `{display}`: need at least `lib.member`"),
|
||||
span_hint: None,
|
||||
};
|
||||
}
|
||||
let bind = &path[0];
|
||||
let Some(lib) = module.import_modules.get(bind) else {
|
||||
return ExecTarget::Unresolved {
|
||||
message: format!("unknown library `{bind}` (import it in frontmatter)"),
|
||||
span_hint: None,
|
||||
};
|
||||
};
|
||||
match walk_path(lib, &path[1..]) {
|
||||
Ok(fun) => ExecTarget::Import {
|
||||
bind: bind.clone(),
|
||||
lib,
|
||||
fun,
|
||||
path: path.to_vec(),
|
||||
},
|
||||
Err(message) => ExecTarget::Unresolved {
|
||||
message,
|
||||
span_hint: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve a call for execution. Import bare-name leakage is forbidden (G02).
|
||||
pub fn resolve_for_exec<'a>(
|
||||
module: &'a Module,
|
||||
current: &'a Function,
|
||||
call: &CallExpr,
|
||||
) -> ExecTarget<'a> {
|
||||
if call.receiver.is_some() {
|
||||
return ExecTarget::Dynamic {
|
||||
reason: DynamicReason::MethodReceiver,
|
||||
name: call_display(call),
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(path) = &call.path {
|
||||
if path.len() == 2 && module.import_modules.contains_key(&path[0]) {
|
||||
return resolve_import_path(module, path);
|
||||
}
|
||||
if path.len() == 2 {
|
||||
// Possible local-variable method; caller checks env.
|
||||
return ExecTarget::Dynamic {
|
||||
reason: DynamicReason::MethodReceiver,
|
||||
name: call_display(call),
|
||||
};
|
||||
}
|
||||
return resolve_import_path(module, path);
|
||||
}
|
||||
|
||||
if let Some(u) = module.uses.iter().find(|u| u.bind == call.callee) {
|
||||
return resolve_import_path(module, &u.path);
|
||||
}
|
||||
|
||||
match call.callee.as_str() {
|
||||
"print" | "input" | "len" | "str" | "int" | "type" | "trim" | "split" | "join" | "at" => {
|
||||
return ExecTarget::Builtin(match call.callee.as_str() {
|
||||
"print" => "print",
|
||||
"input" => "input",
|
||||
"len" => "len",
|
||||
"str" => "str",
|
||||
"int" => "int",
|
||||
"type" => "type",
|
||||
"trim" => "trim",
|
||||
"split" => "split",
|
||||
"join" => "join",
|
||||
"at" => "at",
|
||||
_ => unreachable!(),
|
||||
});
|
||||
}
|
||||
"call_fn" => {
|
||||
return ExecTarget::Dynamic {
|
||||
reason: DynamicReason::CallFn,
|
||||
name: "call_fn".into(),
|
||||
};
|
||||
}
|
||||
other if HostFn::from_name(other).is_some() => {
|
||||
return ExecTarget::Host(HostFn::from_name(other).unwrap());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if let Some(fun) = lookup_local(module, current, &call.callee) {
|
||||
return ExecTarget::Local(fun);
|
||||
}
|
||||
|
||||
ExecTarget::Dynamic {
|
||||
reason: DynamicReason::Plugin,
|
||||
name: call.callee.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_static_bound(target: &ExecTarget<'_>) -> bool {
|
||||
matches!(
|
||||
target,
|
||||
ExecTarget::Local(_)
|
||||
| ExecTarget::Import { .. }
|
||||
| ExecTarget::Builtin(_)
|
||||
| ExecTarget::Host(_)
|
||||
)
|
||||
}
|
||||
+295
-32
@@ -12,11 +12,12 @@ use anyhow::{Context, Result};
|
||||
use serde_json::{json, Value};
|
||||
use sha2::{Digest as _, Sha256};
|
||||
|
||||
use crate::ast::{Arg, CallExpr, Expr, Function, Stmt};
|
||||
use crate::ast::{Arg, CallExpr, Expr, Function, Module, Stmt};
|
||||
use crate::contract::Ty;
|
||||
use crate::diagnostics::{Diagnostic, Severity, Span};
|
||||
use crate::project::ProjectRoot;
|
||||
|
||||
use super::bind::{call_display, resolve_for_exec, DynamicReason, ExecTarget};
|
||||
use super::{CallableKind, ModuleId, ProjectIndex, SymbolDecl, SymbolId, SymbolKind};
|
||||
|
||||
pub const SCHEMA_VERSION: u32 = 1;
|
||||
@@ -99,7 +100,7 @@ impl EffectSet {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SourceLocation {
|
||||
pub file: String,
|
||||
pub line: u32,
|
||||
@@ -197,6 +198,23 @@ pub struct KnowledgeStep {
|
||||
pub source: SourceLocation,
|
||||
}
|
||||
|
||||
/// Static call site bound to a SymbolId (G02).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct BoundCall {
|
||||
pub target: SymbolId,
|
||||
pub call_site: String,
|
||||
pub source: SourceLocation,
|
||||
pub required_effects: EffectSet,
|
||||
}
|
||||
|
||||
/// Call site that must not pretend to be statically bound (G02).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DynamicCall {
|
||||
pub reason: String,
|
||||
pub call_site: String,
|
||||
pub source: SourceLocation,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SemanticProject {
|
||||
pub schema_version: u32,
|
||||
@@ -205,6 +223,8 @@ pub struct SemanticProject {
|
||||
pub artifacts: Vec<SemanticArtifact>,
|
||||
pub refs: Vec<KnowledgeRef>,
|
||||
pub steps: Vec<KnowledgeStep>,
|
||||
pub bound_calls: Vec<BoundCall>,
|
||||
pub dynamic_calls: Vec<DynamicCall>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -245,10 +265,16 @@ pub fn compile_project(options: &CompileOptions) -> Result<Compilation> {
|
||||
}
|
||||
}
|
||||
|
||||
// Wire import_modules from already-parsed project files so BoundCall path
|
||||
// resolve shares `resolve_for_exec` (no plugin load / no re-parse).
|
||||
attach_project_imports(&mut files);
|
||||
|
||||
let project_id = index.project_id().to_string();
|
||||
let mut artifacts = Vec::new();
|
||||
let mut refs = Vec::new();
|
||||
let mut steps = Vec::new();
|
||||
let mut bound_calls = Vec::new();
|
||||
let mut dynamic_calls = Vec::new();
|
||||
let mut local_by_name: BTreeMap<(ModuleId, String), SymbolId> = BTreeMap::new();
|
||||
for symbol in index.symbols() {
|
||||
local_by_name.insert((symbol.module.clone(), symbol.name.clone()), symbol.id.clone());
|
||||
@@ -260,16 +286,20 @@ pub fn compile_project(options: &CompileOptions) -> Result<Compilation> {
|
||||
collect_functions(&module.functions, &mut Vec::new(), &mut by_path);
|
||||
for symbol in index.symbols().iter().filter(|s| &s.module == module_id) {
|
||||
let function = by_path.get(&symbol.declaration_path).expect("symbol collected from module");
|
||||
let (artifact, mut artifact_refs, mut artifact_steps) = artifact_for_function(
|
||||
&index,
|
||||
module_id,
|
||||
path,
|
||||
function,
|
||||
symbol,
|
||||
&local_by_name,
|
||||
);
|
||||
let (artifact, mut artifact_refs, mut artifact_steps, mut bounds, mut dynamics) =
|
||||
artifact_for_function(
|
||||
&index,
|
||||
module_id,
|
||||
module,
|
||||
path,
|
||||
function,
|
||||
symbol,
|
||||
&local_by_name,
|
||||
);
|
||||
refs.append(&mut artifact_refs);
|
||||
steps.append(&mut artifact_steps);
|
||||
bound_calls.append(&mut bounds);
|
||||
dynamic_calls.append(&mut dynamics);
|
||||
artifacts.push(artifact);
|
||||
}
|
||||
}
|
||||
@@ -277,6 +307,20 @@ pub fn compile_project(options: &CompileOptions) -> Result<Compilation> {
|
||||
artifacts.sort_by(|a, b| a.artifact_id.0.cmp(&b.artifact_id.0));
|
||||
refs.sort_by(|a, b| a.id.cmp(&b.id));
|
||||
steps.sort_by(|a, b| a.id.0.cmp(&b.id.0));
|
||||
bound_calls.sort_by(|a, b| {
|
||||
a.source
|
||||
.file
|
||||
.cmp(&b.source.file)
|
||||
.then(a.source.line.cmp(&b.source.line))
|
||||
.then(a.call_site.cmp(&b.call_site))
|
||||
});
|
||||
dynamic_calls.sort_by(|a, b| {
|
||||
a.source
|
||||
.file
|
||||
.cmp(&b.source.file)
|
||||
.then(a.source.line.cmp(&b.source.line))
|
||||
.then(a.call_site.cmp(&b.call_site))
|
||||
});
|
||||
Ok(Compilation {
|
||||
index,
|
||||
semantics: SemanticProject {
|
||||
@@ -286,6 +330,8 @@ pub fn compile_project(options: &CompileOptions) -> Result<Compilation> {
|
||||
artifacts,
|
||||
refs,
|
||||
steps,
|
||||
bound_calls,
|
||||
dynamic_calls,
|
||||
},
|
||||
diagnostics,
|
||||
})
|
||||
@@ -315,30 +361,88 @@ fn module_artifact(index: &ProjectIndex, module: &ModuleId, path: &Path, text: &
|
||||
)
|
||||
}
|
||||
|
||||
fn path_key(path: &Path) -> PathBuf {
|
||||
path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
|
||||
}
|
||||
|
||||
/// Clone imported modules already present in `files` into each Module's
|
||||
/// `import_modules` map (G02 BoundCall for explicit import paths).
|
||||
fn attach_project_imports(files: &mut BTreeMap<ModuleId, (PathBuf, String, Module)>) {
|
||||
let by_path: BTreeMap<PathBuf, Module> = files
|
||||
.values()
|
||||
.map(|(path, _, module)| (path_key(path), module.clone()))
|
||||
.collect();
|
||||
for (path, _, module) in files.values_mut() {
|
||||
let base = path
|
||||
.parent()
|
||||
.map(|p| p.to_path_buf())
|
||||
.unwrap_or_else(|| path.to_path_buf());
|
||||
let mut import_modules = std::collections::HashMap::new();
|
||||
for imp in &module.imports {
|
||||
let Ok(resolved) = crate::load::resolve_import(&base, &imp.path) else {
|
||||
continue;
|
||||
};
|
||||
let key = path_key(&resolved);
|
||||
if let Some(dep) = by_path.get(&key) {
|
||||
import_modules.insert(imp.bind.clone(), dep.clone());
|
||||
}
|
||||
}
|
||||
module.import_modules = import_modules;
|
||||
}
|
||||
}
|
||||
|
||||
fn artifact_for_function(
|
||||
index: &ProjectIndex,
|
||||
module: &ModuleId,
|
||||
module_id: &ModuleId,
|
||||
ast_module: &Module,
|
||||
path: &Path,
|
||||
function: &Function,
|
||||
symbol: &SymbolDecl,
|
||||
local_by_name: &BTreeMap<(ModuleId, String), SymbolId>,
|
||||
) -> (SemanticArtifact, Vec<KnowledgeRef>, Vec<KnowledgeStep>) {
|
||||
) -> (
|
||||
SemanticArtifact,
|
||||
Vec<KnowledgeRef>,
|
||||
Vec<KnowledgeStep>,
|
||||
Vec<BoundCall>,
|
||||
Vec<DynamicCall>,
|
||||
) {
|
||||
let calls = collect_call_sites(function);
|
||||
let mut effects = direct_effects(&calls);
|
||||
let mut dependencies = Vec::new();
|
||||
for (_, call, _) in &calls {
|
||||
if let Some(target) = resolve_local_call(module, call, local_by_name) {
|
||||
dependencies.push(ArtifactId(target.as_str().to_string()));
|
||||
let mut bound_calls = Vec::new();
|
||||
let mut dynamic_calls = Vec::new();
|
||||
for (_, call, line) in &calls {
|
||||
let source = source_location(index.root().path(), path, *line, *line);
|
||||
match classify_call(index, module_id, ast_module, function, call, local_by_name) {
|
||||
CallClass::Bound { target, effects: call_effects } => {
|
||||
dependencies.push(ArtifactId(target.as_str().to_string()));
|
||||
bound_calls.push(BoundCall {
|
||||
target,
|
||||
call_site: call_display(call),
|
||||
source,
|
||||
required_effects: call_effects,
|
||||
});
|
||||
}
|
||||
CallClass::Dynamic { reason } => {
|
||||
dynamic_calls.push(DynamicCall {
|
||||
reason: reason.as_str().into(),
|
||||
call_site: call_display(call),
|
||||
source,
|
||||
});
|
||||
}
|
||||
CallClass::Other => {}
|
||||
}
|
||||
}
|
||||
let named = collect_named_steps(function);
|
||||
let mut refs = Vec::new();
|
||||
let mut steps = Vec::new();
|
||||
for (n, named) in named.iter().enumerate() {
|
||||
let target = named
|
||||
.call
|
||||
.as_ref()
|
||||
.and_then(|call| resolve_local_call(module, call, local_by_name));
|
||||
let target = named.call.as_ref().and_then(|call| {
|
||||
match classify_call(index, module_id, ast_module, function, call, local_by_name) {
|
||||
CallClass::Bound { target, .. } => Some(target),
|
||||
_ => None,
|
||||
}
|
||||
});
|
||||
let ref_id = format!("{}#ref-{}", symbol.id.as_str(), n + 1);
|
||||
refs.push(KnowledgeRef {
|
||||
id: ref_id.clone(),
|
||||
@@ -399,7 +503,109 @@ fn artifact_for_function(
|
||||
implementation,
|
||||
evidence,
|
||||
);
|
||||
(artifact, refs, steps)
|
||||
(artifact, refs, steps, bound_calls, dynamic_calls)
|
||||
}
|
||||
|
||||
enum CallClass {
|
||||
Bound {
|
||||
target: SymbolId,
|
||||
effects: EffectSet,
|
||||
},
|
||||
Dynamic {
|
||||
reason: DynamicReason,
|
||||
},
|
||||
Other,
|
||||
}
|
||||
|
||||
fn declaration_path_of(module: &Module, target: &Function) -> Option<Vec<String>> {
|
||||
fn walk(funs: &[Function], target: &Function, prefix: &mut Vec<String>) -> Option<Vec<String>> {
|
||||
for fun in funs {
|
||||
prefix.push(fun.name.clone());
|
||||
if std::ptr::eq(fun, target) {
|
||||
return Some(prefix.clone());
|
||||
}
|
||||
if let Some(found) = walk(&fun.children, target, prefix) {
|
||||
return Some(found);
|
||||
}
|
||||
prefix.pop();
|
||||
}
|
||||
None
|
||||
}
|
||||
walk(&module.functions, target, &mut Vec::new())
|
||||
}
|
||||
|
||||
fn symbol_for_path(
|
||||
index: &ProjectIndex,
|
||||
module_id: &ModuleId,
|
||||
decl_path: &[String],
|
||||
) -> Option<SymbolId> {
|
||||
index
|
||||
.symbols()
|
||||
.iter()
|
||||
.find(|s| &s.module == module_id && s.declaration_path == decl_path)
|
||||
.map(|s| s.id.clone())
|
||||
}
|
||||
|
||||
fn classify_call(
|
||||
index: &ProjectIndex,
|
||||
module_id: &ModuleId,
|
||||
ast_module: &Module,
|
||||
current: &Function,
|
||||
call: &CallExpr,
|
||||
_local_by_name: &BTreeMap<(ModuleId, String), SymbolId>,
|
||||
) -> CallClass {
|
||||
match resolve_for_exec(ast_module, current, call) {
|
||||
ExecTarget::Local(fun) => {
|
||||
let Some(decl) = declaration_path_of(ast_module, fun) else {
|
||||
return CallClass::Other;
|
||||
};
|
||||
let Some(target) = symbol_for_path(index, module_id, &decl) else {
|
||||
return CallClass::Other;
|
||||
};
|
||||
CallClass::Bound {
|
||||
target,
|
||||
effects: effects_for_call(call),
|
||||
}
|
||||
}
|
||||
ExecTarget::Import { bind, lib, fun, path } => {
|
||||
let Some(imp) = ast_module.imports.iter().find(|i| i.bind == bind) else {
|
||||
return CallClass::Other;
|
||||
};
|
||||
let base = index
|
||||
.modules()
|
||||
.get(module_id)
|
||||
.and_then(|p| p.parent().map(|d| d.to_path_buf()))
|
||||
.unwrap_or_else(|| index.root().path().to_path_buf());
|
||||
let Ok(imported_path) = crate::load::resolve_import(&base, &imp.path) else {
|
||||
return CallClass::Other;
|
||||
};
|
||||
let imported_path = imported_path
|
||||
.canonicalize()
|
||||
.unwrap_or(imported_path);
|
||||
let Some((imported_id, _)) = index.modules().iter().find(|(_, p)| {
|
||||
p.canonicalize().unwrap_or_else(|_| (*p).clone()) == imported_path
|
||||
}) else {
|
||||
return CallClass::Other;
|
||||
};
|
||||
let decl = if path.len() >= 2 {
|
||||
path[1..].to_vec()
|
||||
} else if let Some(d) = declaration_path_of(lib, fun) {
|
||||
d
|
||||
} else {
|
||||
return CallClass::Other;
|
||||
};
|
||||
let Some(target) = symbol_for_path(index, imported_id, &decl) else {
|
||||
return CallClass::Other;
|
||||
};
|
||||
CallClass::Bound {
|
||||
target,
|
||||
effects: effects_for_call(call),
|
||||
}
|
||||
}
|
||||
ExecTarget::Builtin(_) | ExecTarget::Host(_) => CallClass::Other,
|
||||
ExecTarget::Dynamic { reason, .. } => CallClass::Dynamic { reason },
|
||||
ExecTarget::Unresolved { .. } => CallClass::Other,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -666,11 +872,7 @@ fn collect_named_steps(function: &Function) -> Vec<NamedStepSite> {
|
||||
}
|
||||
|
||||
fn call_name(call: &CallExpr) -> String {
|
||||
call.path.as_ref().map(|path| path.join(".")).or_else(|| call.receiver.as_ref().map(|receiver| format!("{receiver}.{}", call.callee))).unwrap_or_else(|| call.callee.clone())
|
||||
}
|
||||
|
||||
fn resolve_local_call(module: &ModuleId, call: &CallExpr, symbols: &BTreeMap<(ModuleId, String), SymbolId>) -> Option<SymbolId> {
|
||||
if call.path.is_none() && call.receiver.is_none() { symbols.get(&(module.clone(), call.callee.clone())).cloned() } else { None }
|
||||
call_display(call)
|
||||
}
|
||||
|
||||
fn effects_for_call(call: &CallExpr) -> EffectSet {
|
||||
@@ -687,12 +889,12 @@ fn effects_for_call(call: &CallExpr) -> EffectSet {
|
||||
else if name.starts_with("print") || name.starts_with("log.") { "output.write" }
|
||||
else if is_observe_call(call) {
|
||||
return EffectSet::pure();
|
||||
} else if call.path.is_none() && call.receiver.is_none() {
|
||||
// Bare local name: effects filled by `close_effect_dependencies` from
|
||||
// resolved SymbolId deps. Do not guess pure.
|
||||
} else if call.path.is_some() || (call.path.is_none() && call.receiver.is_none()) {
|
||||
// Local bare name or import path: effects filled by BoundCall dependency
|
||||
// closure. Do not guess pure / unknown here.
|
||||
return EffectSet::default();
|
||||
} else {
|
||||
// Path/receiver/dynamic — unknown until BoundCall + metadata registry (G06).
|
||||
// Receiver / unresolved dynamic — unknown (G06).
|
||||
return EffectSet::unknown();
|
||||
};
|
||||
effects.add(effect);
|
||||
@@ -732,6 +934,22 @@ fn close_effect_dependencies(artifacts: &mut [SemanticArtifact]) {
|
||||
}
|
||||
}
|
||||
for artifact in artifacts.iter_mut() {
|
||||
if artifact.effects.contains("unknown")
|
||||
&& artifact
|
||||
.effects
|
||||
.values()
|
||||
.iter()
|
||||
.any(|e| e != "unknown" && e != "pure")
|
||||
{
|
||||
// Concrete effects from BoundCall closure supersede unknown.
|
||||
let mut cleaned = EffectSet::default();
|
||||
for e in artifact.effects.values() {
|
||||
if e != "unknown" {
|
||||
cleaned.add(e);
|
||||
}
|
||||
}
|
||||
artifact.effects = cleaned;
|
||||
}
|
||||
if artifact.effects.values().is_empty() {
|
||||
artifact.effects = EffectSet::pure();
|
||||
}
|
||||
@@ -762,6 +980,8 @@ impl SemanticProject {
|
||||
"artifacts": self.artifacts.iter().map(artifact_json).collect::<Vec<_>>(),
|
||||
"refs": self.refs.iter().map(ref_json).collect::<Vec<_>>(),
|
||||
"steps": self.steps.iter().map(step_json).collect::<Vec<_>>(),
|
||||
"bound_calls": self.bound_calls.iter().map(bound_call_json).collect::<Vec<_>>(),
|
||||
"dynamic_calls": self.dynamic_calls.iter().map(dynamic_call_json).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -771,6 +991,23 @@ pub fn artifact_json(artifact: &SemanticArtifact) -> Value {
|
||||
}
|
||||
fn ref_json(reference: &KnowledgeRef) -> Value { json!({"id":reference.id,"label":reference.label,"context":reference.context,"source":{"file":reference.source.file,"line":reference.source.line,"end_line":reference.source.end_line},"resolution":reference.resolution,"target":reference.target.as_ref().map(SymbolId::as_str)}) }
|
||||
fn step_json(step: &KnowledgeStep) -> Value { json!({"id":step.id.0,"reference":step.reference,"kind":step.kind,"calls":step.calls.iter().map(SymbolId::as_str).collect::<Vec<_>>(),"effects":step.effects.values(),"source":{"file":step.source.file,"line":step.source.line,"end_line":step.source.end_line}}) }
|
||||
fn bound_call_json(call: &BoundCall) -> Value {
|
||||
json!({
|
||||
"target": call.target.as_str(),
|
||||
"call_site": call.call_site,
|
||||
"source": {"file": call.source.file, "line": call.source.line, "end_line": call.source.end_line},
|
||||
"required_effects": call.required_effects.values(),
|
||||
"binding": "BoundCall",
|
||||
})
|
||||
}
|
||||
fn dynamic_call_json(call: &DynamicCall) -> Value {
|
||||
json!({
|
||||
"reason": call.reason,
|
||||
"call_site": call.call_site,
|
||||
"source": {"file": call.source.file, "line": call.source.line, "end_line": call.source.end_line},
|
||||
"binding": "DynamicCall",
|
||||
})
|
||||
}
|
||||
|
||||
/// Atomically write the semantic portion of `.marqdo/`. A reader therefore
|
||||
/// sees either the previous graph or the complete next graph, never a mix.
|
||||
@@ -785,6 +1022,8 @@ pub fn write_semantic_projections(out_dir: &Path, compilation: &Compilation) ->
|
||||
write_json(&stage.join("symbols.json"), &json!({"schema_version":SCHEMA_VERSION,"symbols":compilation.index.symbols().iter().map(|s|json!({"id":s.id.as_str(),"module":s.module.as_str(),"kind":s.kind.as_str(),"callable":s.callable.map(|c|c.as_str()),"name":s.name,"declaration_path":s.declaration_path,"source":{"file":rel_uri(compilation.index.root().path(),&s.source),"line":s.line}})).collect::<Vec<_>>() }))?;
|
||||
write_json(&stage.join("refs.json"), &json!({"schema_version":SCHEMA_VERSION,"refs":project["refs"]}))?;
|
||||
write_json(&stage.join("steps.json"), &json!({"schema_version":SCHEMA_VERSION,"steps":project["steps"]}))?;
|
||||
write_json(&stage.join("bound_calls.json"), &json!({"schema_version":SCHEMA_VERSION,"bound_calls":project["bound_calls"]}))?;
|
||||
write_json(&stage.join("dynamic_calls.json"), &json!({"schema_version":SCHEMA_VERSION,"dynamic_calls":project["dynamic_calls"]}))?;
|
||||
write_json(&stage.join("graph/nodes.json"), &json!({"schema_version":SCHEMA_VERSION,"nodes":project["artifacts"]}))?;
|
||||
write_json(&stage.join("graph/edges.json"), &json!({"schema_version":SCHEMA_VERSION,"authority":"SemanticProject","edges":compilation.semantics.artifacts.iter().flat_map(|a|a.dependencies.iter().map(move |d|json!({"from":a.artifact_id.0,"to":d.0,"kind":"calls"}))).collect::<Vec<_>>() }))?;
|
||||
for artifact in &compilation.semantics.artifacts {
|
||||
@@ -792,10 +1031,34 @@ pub fn write_semantic_projections(out_dir: &Path, compilation: &Compilation) ->
|
||||
write_json(&stage.join("artifacts").join(format!("{name}.json")), &artifact_json(artifact))?;
|
||||
write_json(&stage.join("verification").join(format!("{name}.json")), &artifact_json(artifact)["verification"])?;
|
||||
}
|
||||
const SEMANTIC_NAMES: &[&str] = &[
|
||||
"project.json",
|
||||
"symbols.json",
|
||||
"refs.json",
|
||||
"steps.json",
|
||||
"bound_calls.json",
|
||||
"dynamic_calls.json",
|
||||
"artifacts",
|
||||
"graph",
|
||||
"verification",
|
||||
];
|
||||
if out_dir.exists() {
|
||||
for name in ["project.json", "symbols.json", "refs.json", "steps.json", "artifacts", "graph", "verification"] { let target = out_dir.join(name); if target.exists() { if target.is_dir() { fs::remove_dir_all(&target)?; } else { fs::remove_file(&target)?; } } }
|
||||
} else { fs::create_dir_all(out_dir)?; }
|
||||
for name in ["project.json", "symbols.json", "refs.json", "steps.json", "artifacts", "graph", "verification"] { fs::rename(stage.join(name), out_dir.join(name))?; }
|
||||
for name in SEMANTIC_NAMES {
|
||||
let target = out_dir.join(name);
|
||||
if target.exists() {
|
||||
if target.is_dir() {
|
||||
fs::remove_dir_all(&target)?;
|
||||
} else {
|
||||
fs::remove_file(&target)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fs::create_dir_all(out_dir)?;
|
||||
}
|
||||
for name in SEMANTIC_NAMES {
|
||||
fs::rename(stage.join(name), out_dir.join(name))?;
|
||||
}
|
||||
fs::remove_dir_all(stage)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+6
-2
@@ -4,13 +4,17 @@
|
||||
//! binding facts so runtime, EKC, view, and agents do not independently infer
|
||||
//! the meaning of the same source text.
|
||||
|
||||
pub mod bind;
|
||||
pub mod ir;
|
||||
pub mod lock;
|
||||
pub mod symbols;
|
||||
|
||||
pub use bind::{
|
||||
call_display, is_static_bound, lookup_local, resolve_for_exec, DynamicReason, ExecTarget,
|
||||
};
|
||||
pub use ir::{
|
||||
artifact_json, compile_project, write_semantic_projections, ArtifactId, CompileOptions, Compilation,
|
||||
Digest, EffectSet, LockMode, SemanticArtifact, SemanticProject,
|
||||
artifact_json, compile_project, write_semantic_projections, ArtifactId, BoundCall, CompileOptions,
|
||||
Compilation, Digest, DynamicCall, EffectSet, LockMode, SemanticArtifact, SemanticProject,
|
||||
};
|
||||
pub use lock::{check_links_lock, impact as semantic_impact, update_links_lock, LockReport};
|
||||
pub use symbols::{CallableKind, ModuleId, ProjectIndex, SymbolDecl, SymbolId, SymbolKind};
|
||||
@@ -1,8 +1,7 @@
|
||||
//! S0 executable-knowledge baseline gate (offline).
|
||||
//! Executable-knowledge gate (offline): S0 baseline + S1/S2 BoundCall/effects.
|
||||
//!
|
||||
//! See `tests/executable_knowledge/README.md`. Design-status samples may run
|
||||
//! but do not prove source/applicability. Expected failures are asserted;
|
||||
//! the bytecode ambiguous-name defect is fingerprinted until S2 BoundCall.
|
||||
//! but do not prove source/applicability. Expected failures are asserted.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
@@ -417,3 +416,121 @@ fn s0_06b_ambiguous_bare_name_rejected_both_backends() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn s2_g02_boundcall_path_and_dynamic_projections() {
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let out = std::env::temp_dir().join(format!(
|
||||
"marqdo-ek-g02-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&out);
|
||||
let status = Command::new(env!("CARGO_BIN_EXE_marqdo"))
|
||||
.args([
|
||||
"knowledge",
|
||||
"tests/executable_knowledge/baseline/10-boundcall",
|
||||
"-o",
|
||||
out.to_str().unwrap(),
|
||||
])
|
||||
.current_dir(&root)
|
||||
.output()
|
||||
.expect("knowledge compile");
|
||||
assert_eq!(
|
||||
status.status.code(),
|
||||
Some(0),
|
||||
"stderr={}",
|
||||
String::from_utf8_lossy(&status.stderr)
|
||||
);
|
||||
let bound: serde_json::Value = serde_json::from_str(
|
||||
&std::fs::read_to_string(out.join("bound_calls.json")).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let dynamic: serde_json::Value = serde_json::from_str(
|
||||
&std::fs::read_to_string(out.join("dynamic_calls.json")).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let bounds = bound["bound_calls"].as_array().expect("bound_calls");
|
||||
assert!(
|
||||
bounds.iter().any(|c| {
|
||||
c["binding"] == "BoundCall"
|
||||
&& c["call_site"].as_str().unwrap_or("").contains("pricing.商品小计")
|
||||
&& c["target"].as_str().is_some_and(|t| !t.is_empty())
|
||||
}),
|
||||
"import path must be BoundCall with SymbolId: {bound}"
|
||||
);
|
||||
let dyns = dynamic["dynamic_calls"].as_array().expect("dynamic_calls");
|
||||
assert!(
|
||||
dyns.iter().any(|c| {
|
||||
c["binding"] == "DynamicCall" && c["reason"] == "call_fn"
|
||||
}),
|
||||
"call_fn must be DynamicCall: {dynamic}"
|
||||
);
|
||||
// Edges from caller must include the BoundCall target SymbolId.
|
||||
let edges: serde_json::Value = serde_json::from_str(
|
||||
&std::fs::read_to_string(out.join("graph/edges.json")).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let target = bounds
|
||||
.iter()
|
||||
.find(|c| c["call_site"].as_str().unwrap_or("").contains("pricing.商品小计"))
|
||||
.unwrap()["target"]
|
||||
.as_str()
|
||||
.unwrap();
|
||||
let edge_txt = edges.to_string();
|
||||
assert!(
|
||||
edge_txt.contains(target),
|
||||
"graph edges must mention BoundCall target {target}: {edges}"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&out);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn s2_g02_boundcall_runs_both_backends() {
|
||||
assert_out_both(
|
||||
"tests/executable_knowledge/baseline/10-boundcall/main.mq.md",
|
||||
"hi\n60",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn s2_g07_eng_reuse_requires_bind_before_execute() {
|
||||
// Discovery scores must not be treated as executable handles.
|
||||
use marqdo::knowledge::ir::{ReuseCandidate, ReuseDecision, ReuseResult};
|
||||
use marqdo::knowledge::reuse::reuse_json;
|
||||
let result = ReuseResult {
|
||||
decision: ReuseDecision::Reuse,
|
||||
confidence: 0.9,
|
||||
capability: Some("定价".into()),
|
||||
symbol: Some("商品小计".into()),
|
||||
source: None,
|
||||
reason: vec!["score meets REUSE threshold".into()],
|
||||
candidates: vec![ReuseCandidate {
|
||||
id: "capability:定价".into(),
|
||||
kind: "Capability".into(),
|
||||
title: "定价".into(),
|
||||
score: 0.9,
|
||||
resource: None,
|
||||
reason: vec![],
|
||||
}],
|
||||
constraints: vec![],
|
||||
decisions: vec![],
|
||||
failures: vec![],
|
||||
create_allowed: false,
|
||||
recommended: vec!["REUSE 定价".into()],
|
||||
};
|
||||
let v = reuse_json("商品小计", &result);
|
||||
assert_eq!(v["discovery_only"], true, "{v}");
|
||||
assert_eq!(v["bind_required"], true, "{v}");
|
||||
assert!(
|
||||
v["bind_targets"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|t| t["query"] == "商品小计"),
|
||||
"REUSE must expose bind_targets for MLSP bind: {v}"
|
||||
);
|
||||
}
|
||||
@@ -17,11 +17,14 @@
|
||||
| 05 | `baseline/05-policy-draft/` | **design** | 可试跑 → `113`;**不**宣称税率事实已证实 | 叙述中的来源意图(尚未有强制 schema) |
|
||||
| 06a | `baseline/06-reject/missing-import.mq.md` | expected_failure | 双后端均非 0 | 0(正确拒绝) |
|
||||
| 06b | `baseline/06-reject/ambiguous.mq.md` | expected_failure | **双后端均拒绝**裸名同名(G02) | — |
|
||||
| 10 | `baseline/10-boundcall/` | implemented | BoundCall 路径 SymbolId + DynamicCall(`call_fn`);双后端 `hi`/`60` | import 一行 |
|
||||
|
||||
### 同名裸调用(G02)
|
||||
|
||||
`06-reject/ambiguous.mq.md` 同时 `import` 了 `a` 与 `b`(同名 `商品小计`),正文用**裸名**调用。双后端均须拒绝;正确写法是 `a.商品小计` / `b.商品小计` 等显式路径。
|
||||
|
||||
`10-boundcall`:显式 `pricing.商品小计` 写入 `bound_calls.json`(`binding: BoundCall` + SymbolId);`call_fn` 写入 `dynamic_calls.json`(不得假装已绑定)。
|
||||
|
||||
## 不计为成功的项
|
||||
|
||||
- `status: design` 样例通过运行 ≠ 来源/适用性/ready 已实现(G05/G07)
|
||||
@@ -38,9 +41,9 @@
|
||||
| S1 同名 | **done** | `08-same-name` resolve→A + 运行 `60` |
|
||||
| S2/G06 | **done** | 包装继承 `fs.write`;未知不标 pure |
|
||||
| S2/G07 子集 | **done** | MLSP bind 含 `symbol_id`;execute 按源行绑定;pure 拒非纯 |
|
||||
| S2/G02 BoundCall | **done(作用域子集)** | Bytecode 裸名解析不跨 import scope;`06b` 双后端拒绝 |
|
||||
| S2/G02 BoundCall | **done** | 共享 `resolve_for_exec`;Tree/Bytecode 静态路径绑定;`bound_calls.json` / `dynamic_calls.json`;`10-boundcall` + `06b` |
|
||||
| S2/G07 eng_reuse | **done(子集)** | `reuse_json` / `agent_eng_reuse`:`discovery_only` + `bind_required` + `bind_targets`;执行仍须 MLSP bind |
|
||||
|
||||
## 与后续切片的关系
|
||||
|
||||
- S2 后续:sema 路径 BoundCall 记录、Agent eng_reuse 强制 bind
|
||||
- S3+:局部编辑、来源适用性、整代快照 — 见缺口路线图
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: S2 G02 BoundCall 路径绑定与动态标记
|
||||
status: implemented
|
||||
import:
|
||||
pricing: pricing.mq.md
|
||||
---
|
||||
|
||||
## helper
|
||||
|
||||
动态目标演示用无参函数。
|
||||
|
||||
> print text=hi
|
||||
|
||||
# main
|
||||
|
||||
显式 import 路径必须进 BoundCall;`call_fn` 必须进 DynamicCall。
|
||||
|
||||
**小计 = [两件](pricing.商品小计(数量=2, 单价=30))**
|
||||
> call_fn name=helper
|
||||
> print text=`小计`
|
||||
@@ -0,0 +1,11 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: BoundCall 目标定价
|
||||
status: implemented
|
||||
---
|
||||
|
||||
## 商品小计
|
||||
|
||||
根据购买数量`数量`和商品单价`单价`计算小计。
|
||||
|
||||
*[按数量与单价计算](数量 * 单价)*
|
||||
Reference in new issue
Block a user