Skip to content

Commit b81fcc4

Browse files
committed
feat(compiler): add resource typing and frame-local ownership
1 parent 2f6fa98 commit b81fcc4

64 files changed

Lines changed: 14672 additions & 938 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

build.rs

Lines changed: 77 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1208,9 +1208,9 @@ fn render_callable_consts(callables: &[&CallableDecl]) -> String {
12081208
for param in &callable.params {
12091209
writeln!(
12101210
&mut out,
1211-
" CallableParam {{ name: {:?}, ty: CallableParamType::{}, optional: {} }},",
1211+
" CallableParam {{ name: {:?}, ty: {}, optional: {} }},",
12121212
param.name,
1213-
callable_param_variant(&param.ty_label),
1213+
callable_param_expr(&param.ty_label),
12141214
param.optional
12151215
)
12161216
.unwrap();
@@ -1633,18 +1633,38 @@ fn callable_const_base(callable: &CallableDecl) -> String {
16331633
to_shouty_snake(&format!("{prefix}_{}", callable.rust_ident))
16341634
}
16351635

1636-
fn callable_param_variant(label: &str) -> &'static str {
1636+
pub(crate) fn callable_param_expr(label: &str) -> String {
16371637
match label {
1638-
"any" => "Any",
1639-
"null" => "Null",
1640-
"int" => "Int",
1641-
"float" => "Float",
1642-
"bool" => "Bool",
1643-
"string" => "String",
1644-
"bytes" => "Bytes",
1645-
"array" => "Array",
1646-
"map" => "Map",
1647-
"number" => "Number",
1638+
"any" => "CallableParamType::Any".to_string(),
1639+
"null" => "CallableParamType::Null".to_string(),
1640+
"int" => "CallableParamType::Int".to_string(),
1641+
"float" => "CallableParamType::Float".to_string(),
1642+
"bool" => "CallableParamType::Bool".to_string(),
1643+
"string" => "CallableParamType::String".to_string(),
1644+
"bytes" => "CallableParamType::Bytes".to_string(),
1645+
"array" => "CallableParamType::Array".to_string(),
1646+
"map" => "CallableParamType::Map".to_string(),
1647+
"number" => "CallableParamType::Number".to_string(),
1648+
other if other.starts_with("fn(") => {
1649+
let (params, result) = other
1650+
.strip_prefix("fn(")
1651+
.and_then(|value| value.split_once(") -> "))
1652+
.unwrap_or_else(|| panic!("invalid callable schema '{other}'"));
1653+
let params = if params.is_empty() {
1654+
Vec::new()
1655+
} else {
1656+
params
1657+
.split(", ")
1658+
.map(callable_param_expr)
1659+
.collect::<Vec<_>>()
1660+
};
1661+
let result = callable_param_expr(result);
1662+
format!(
1663+
"CallableParamType::Callable(CallableType {{ params: &[{}], return_type: &{} }})",
1664+
params.join(", "),
1665+
result
1666+
)
1667+
}
16481668
other => panic!("unsupported callable param type '{other}'"),
16491669
}
16501670
}
@@ -2070,7 +2090,7 @@ fn static_return_type_label(output: &ReturnType) -> String {
20702090
value_type_from_label(&return_type_label(output)).to_string()
20712091
}
20722092

2073-
fn type_label(ty: &Type) -> String {
2093+
pub(crate) fn type_label(ty: &Type) -> String {
20742094
match ty {
20752095
Type::Group(group) => type_label(&group.elem),
20762096
Type::Paren(paren) => type_label(&paren.elem),
@@ -2108,6 +2128,7 @@ fn type_label(ty: &Type) -> String {
21082128
"Array" | "VmArray" | "VmArrayRef" | "VmArrayHandle" => "array".to_string(),
21092129
"Map" | "VmMap" | "VmMapRef" | "VmMapHandle" => "map".to_string(),
21102130
"Number" | "NumberValue" => "number".to_string(),
2131+
"VmCallable" => callable_type_label(segment),
21112132
"Unknown" | "UnknownValue" => "unknown".to_string(),
21122133
"CallOutcome" => "unknown".to_string(),
21132134
"Option" => {
@@ -2136,6 +2157,25 @@ fn type_label(ty: &Type) -> String {
21362157
}
21372158
}
21382159

2160+
fn callable_type_label(segment: &syn::PathSegment) -> String {
2161+
let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
2162+
panic!("VmCallable requires a function signature");
2163+
};
2164+
let Some(syn::GenericArgument::Type(Type::BareFn(function))) = args.args.first() else {
2165+
panic!("VmCallable requires fn(...) -> ...");
2166+
};
2167+
let params = function
2168+
.inputs
2169+
.iter()
2170+
.map(|input| type_label(&input.ty))
2171+
.collect::<Vec<_>>();
2172+
let result = match &function.output {
2173+
ReturnType::Default => "null".to_string(),
2174+
ReturnType::Type(_, ty) => type_label(ty),
2175+
};
2176+
format!("fn({}) -> {result}", params.join(", "))
2177+
}
2178+
21392179
fn type_label_for_vec(segment: &syn::PathSegment) -> String {
21402180
let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
21412181
panic!("Vec<T> requires one generic argument");
@@ -2310,3 +2350,26 @@ fn find_matching_paren(source: &str) -> usize {
23102350
}
23112351
panic!("unterminated macro invocation");
23122352
}
2353+
2354+
#[cfg(test)]
2355+
mod callable_schema_tests {
2356+
use super::*;
2357+
use syn::parse_quote;
2358+
2359+
#[test]
2360+
fn build_metadata_renders_typed_callable_parameters() {
2361+
let ty: Type = parse_quote!(VmCallable<fn(VmMap) -> VmMap>);
2362+
assert_eq!(type_label(&ty), "fn(map) -> map");
2363+
assert_eq!(
2364+
callable_param_expr("fn(map) -> map"),
2365+
"CallableParamType::Callable(CallableType { params: &[CallableParamType::Map], return_type: &CallableParamType::Map })"
2366+
);
2367+
2368+
let float_ty: Type = parse_quote!(VmCallable<fn(f64) -> f64>);
2369+
assert_eq!(type_label(&float_ty), "fn(float) -> float");
2370+
assert_eq!(
2371+
callable_param_expr("fn(float) -> float"),
2372+
"CallableParamType::Callable(CallableType { params: &[CallableParamType::Float], return_type: &CallableParamType::Float })"
2373+
);
2374+
}
2375+
}

docs/callable-runtime.md

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,24 @@
11
# Script call frames and callable values
22

3-
RustScript bytecode format version 11 (VMBC v11) introduces runtime script call frames, first-class callable values, and the static builtin ID catalog.
3+
RustScript bytecode format version 12 (VMBC v12) carries runtime script call frames, first-class callable values, the static builtin ID catalog, and the direct script-call opcode. Version 11 introduced frames, callable values, and the static catalog; version 12 adds `callscript` for statically resolved named calls.
44

55
## Bytecode contract
66

77
- `call <import:u16> <argc:u8>` remains the direct host/builtin operation; the `u16` operand is an explicit static builtin call index from the catalog (or a host-import slot) — never a count-derived offset.
88
- `callvalue <argc:u8>` consumes a stack segment in `callee, arg0, ..., argN` order.
9+
- `callscript <prototype_id:u32> <argc:u8>` calls a statically resolved named script function by prototype ID. It consumes only `argc` arguments; no callable value is taken from the stack, so environment-free named functions can be called without a hidden callable local.
910
- callable environments are bound through the internal builtin call path; callable creation adds no bytecode opcode.
1011
- `ret` completes the active script frame. A nested frame leaves exactly one result at the caller segment base, using `null` when the body produced no value. Root `ret` keeps the historical program-result stack behavior.
1112

12-
VMBC v11 is a hard format boundary. Decoders reject all earlier versions (v10 and below) with a deterministic unsupported-version error; there is no compatibility decoder and no old-ID alias. The stream includes script-function entry ranges, callable prototypes, function regions, root callable bindings, and call indices drawn from the static builtin catalog. PDRC v6 recordings and AOT artifacts (format 7, ABI 6) use their corresponding bumped versions and include callable metadata in cache identity.
13+
### Call ownership
14+
15+
The three call opcodes differ in who owns the callee and what the frame must provide:
16+
17+
- `call` — the callee is owned by the static builtin catalog (or the host-import slot). The frame contributes only `argc` arguments; there is no callable value anywhere in the program.
18+
- `callvalue` — the callee is a `Value::Callable` owned by the caller operand stack at the call site, and remains the caller's responsibility after the call. This path carries environments, closures, and any callable whose identity or capture state is runtime-valued.
19+
- `callscript` — the callee is owned by program callable metadata (the prototype table). The frame contributes only `argc` arguments and no callable value, but unlike `call` the callee is a script function rather than a builtin, so the call enters a new script frame with its own local base.
20+
21+
VMBC v12 is a hard format boundary. Decoders reject all earlier versions (v11 and below) with a deterministic unsupported-version error; there is no compatibility decoder and no old-ID alias. The stream includes script-function entry ranges, callable prototypes, function regions, root callable bindings, and call indices drawn from the static builtin catalog. PDRC v6 recordings and AOT artifacts (format 8, ABI 8) use their corresponding bumped versions and include callable metadata in cache identity.
1322

1423
## Static builtin IDs
1524

@@ -18,7 +27,7 @@ Every VM-visible builtin (ordinary, internal, and special-call) has one explicit
1827
- **Immutable explicit IDs.** IDs never change once assigned. Adding or reordering catalog entries never renumbers existing entries; new builtins take the next free ID in their documented block (extension `0x0000..=0xFF8F` for future builtins and host imports, special-call `0xFF90..=0xFFA1`, ordinary `0xFFA2..=0xFFFF`). The reserved sentinel gap `0xFF90..=0xFF92` stays unassigned.
1928
- **Build-time validation.** The build fails on duplicate IDs, duplicate source names, duplicate Rust variants, out-of-block IDs, class/gate inconsistencies, a discovered runtime callable without an explicit ID, or a catalog entry without a runtime callable.
2029
- **Shared std/no-std IDs.** `pd-vm-nostd` dispatches on the same static indices through the checked-in generated mirror `pd-vm-nostd/src/generated_builtin_ids.rs`; the workspace test `static_builtin_ids_are_frozen` fails when the mirror drifts from the catalog.
21-
- **One-time format break.** The static ID migration bumped VMBC to v11 (and the internal bytecode ABI to 11). Older VMBC versions are rejected, never decoded.
30+
- **Format breaks are permanent.** The static ID migration bumped VMBC to v11 (and the internal bytecode ABI to 11); the `callscript` opcode break bumped both to v12. Versions below the current format are rejected, never decoded.
2231

2332
## Runtime model
2433

@@ -29,10 +38,24 @@ Each script invocation owns:
2938
- frame-local count;
3039
- active prototype and callable identity.
3140

32-
Arguments, captures, named callable bindings, and the self binding are installed before control moves to the function entry. Recursive calls therefore allocate independent local storage and are limited to 1,024 script frames.
41+
Arguments, captures, hidden callable bindings for materialized named functions, and the self binding are installed before control moves to the function entry. Recursive calls therefore allocate independent local storage and are limited to 1,024 script frames.
3342

3443
Branches are restricted to the active function region. Validation rejects cross-region targets before execution, and the interpreter repeats the check at runtime.
3544

45+
## Frame-local allocation and callable materialization
46+
47+
Each script invocation frame is an independent local-address space with its own `local_base`. Locals that are live at the same time inside one frame interfere and receive distinct relative slot numbers; locals that belong to different frames never interfere and may reuse the same relative slot number, because the runtime frame bases already separate them. A statically resolved named call keeps the caller's argument slots and post-call values live in the caller frame, while the callee body's locals are analyzed inside the callee frame.
48+
49+
Named functions receive a hidden callable slot only when runtime `Value::Callable` identity is actually required:
50+
51+
- the function is exported under the `ExportedCallable { local_slot }` contract;
52+
- the function is referenced as a value (stored, passed, or returned);
53+
- the function captures an environment;
54+
- a dynamic call site can target the function (invoked slot or argument flow into an invoked parameter);
55+
- the function's runtime self identity is required by a capturing or dynamic recursion path.
56+
57+
Functions that only receive plain direct calls — including non-capturing direct recursion — are lowered through `callscript` by prototype ID and consume no hidden callable local. The compiler reports the aggregate frame-local count (data slots plus materialized callable slots) in `FrameLocalLimitExceeded` diagnostics, so overflow reports real counts instead of a sentinel. Genuine same-frame pressure beyond 256 simultaneous locals keeps failing until wide local bytecode lands.
58+
3659
## Callable identity and lifetime
3760

3861
A callable contains its prototype ID, kind, and optional environment. The Program/Store owns the callable lifetime. Capture-free function items compare by prototype identity inside that Program; closures compare by runtime environment identity. Callable constants are forbidden; functions are initialized from Program metadata and closures are materialized at their declaration site.
@@ -49,16 +72,16 @@ PDRC recordings preserve full execution-frame metadata. Callable environments us
4972

5073
- `InvocationItem::Event(value)` items arrive in order for each `stream::emit(value)` call; `stream::emit` still evaluates to `()` inside RSS.
5174
- exactly one `InvocationItem::Complete(value)` carries the callable return value; events never replace it;
52-
- cancellation, fuel exhaustion, epoch deadline expiry, runtime capability failures (including event payload bound violations), and host failures each produce exactly one typed `InvocationError` item;
75+
- cancellation, fuel exhaustion, epoch deadline expiry, runtime capability failures, and host failures each produce exactly one typed `InvocationError` item;
5376
- every poll after `Complete` or the error item returns `Ready(None)` (fused end of stream);
5477
- `InvocationPoll::Pending` means the VM is paused on an outstanding host operation; drive it through the embedding-owned async bridge and poll again.
5578

56-
Polling drives execution and provides backpressure: at most one event item is buffered between polls, and the VM does not produce items while the consumer is not polling. `stream::emit` validates only the configured per-item value bound (payload bytes and nesting depth); sequence assignment, receipts, persistence, and delivery policy belong to the embedding. At most one invocation is active per VM, `Invocation::cancel(reason)` cancels with a typed `OperationCancelReason`, dropping the handle retires the invocation synchronously for immediate VM reuse, and the low-level `Vm::run` pump is unchanged for custom drivers.
79+
Polling drives execution and provides backpressure: at most one event item is buffered between polls, and the VM does not produce items while the consumer is not polling. `stream::emit` validates only the configured per-item value bound; sequence assignment, receipts, persistence, and delivery policy belong to the embedding. At most one invocation is active per VM, `Invocation::cancel(reason)` cancels with a typed `CancellationReason`, and the low-level `Vm::run` pump is unchanged for custom drivers.
5780

5881
## Optimized backends
5982

60-
Whole-program AOT and Trace JIT use the same builtin call path (static catalog IDs) for environment binding and native frame dispatch for `callvalue`. Script-frame entry and return preserve frame-relative locals and typed continuations.
83+
Whole-program AOT and Trace JIT use the same builtin call path (static catalog IDs) for environment binding, native frame dispatch for `callvalue`, and prototype-direct native dispatch for `callscript`. Script-frame entry and return preserve frame-relative locals and typed continuations.
6184

6285
## Embedded runtime
6386

64-
`pd-vm-nostd` decodes the same VMBC v11 callable metadata and executes callable binding, `callvalue`, recursive frames, captures, and direct host targets using `core` plus `alloc`, dispatching on the identical static builtin IDs via its checked-in generated mirror.
87+
`pd-vm-nostd` decodes the same VMBC v12 callable metadata and executes callable binding, `callvalue`, `callscript`, recursive frames, captures, and direct host targets using `core` plus `alloc`, dispatching on the identical static builtin IDs via its checked-in generated mirror.

pd-host-function/src/lib.rs

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ use pd_host_schema::{
1212
#[proc_macro_attribute]
1313
pub fn pd_host_function(attr: TokenStream, item: TokenStream) -> TokenStream {
1414
let args = parse_macro_input!(attr with Punctuated::<Meta, Token![,]>::parse_terminated);
15-
match expand_pd_host_function(args, parse_macro_input!(item as ItemFn)) {
15+
let item = parse_macro_input!(item as ItemFn);
16+
let result = expand_pd_host_function(args, item);
17+
match result {
1618
Ok(tokens) => tokens.into(),
1719
Err(err) => err.to_compile_error().into(),
1820
}
@@ -470,7 +472,7 @@ fn generate_async_vm_wrapper(
470472
continue;
471473
}
472474
let label = LitStr::new(
473-
&format!("{} {ident}", wrapper_name),
475+
&format!("{} {}", wrapper_name, ident),
474476
proc_macro2::Span::call_site(),
475477
);
476478
let index = syn::Index::from(arg_index);
@@ -594,12 +596,6 @@ fn unwrap_vm_result_type(ty: &Type) -> Result<Option<Type>, Error> {
594596
}
595597
}
596598

597-
fn return_is_vm_result(output: &ReturnType) -> bool {
598-
vm_result_inner_type(output)
599-
.expect("pd_host_function return type should already be validated")
600-
.is_some()
601-
}
602-
603599
fn return_is_host_future_output(output: &ReturnType) -> bool {
604600
vm_result_inner_type(output)
605601
.expect("pd_host_function return type should already be validated")
@@ -614,6 +610,12 @@ fn return_is_host_future_output(output: &ReturnType) -> bool {
614610
.is_some_and(|ident| ident == "HostFutureOutput")
615611
}
616612

613+
fn return_is_vm_result(output: &ReturnType) -> bool {
614+
vm_result_inner_type(output)
615+
.expect("pd_host_function return type should already be validated")
616+
.is_some()
617+
}
618+
617619
fn type_label(ty: &Type) -> Result<String, Error> {
618620
match ty {
619621
Type::Group(group) => type_label(&group.elem),

pd-vm-nostd/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ compiler, parser, CLI, debugger, JIT/AOT backends, filesystem support, and opera
66

77
## Runtime surface
88

9-
- VMBC v11 decoding with script-call and callable metadata
9+
- VMBC v12 decoding with environment-free `CallScript` direct script calls alongside dynamic callable calls
1010
- stack, local, and recursive script-frame execution for direct bytecode opcodes
1111
- instruction fuel with pause/resume support
1212
- synchronous named host bindings and dynamic host dispatch

0 commit comments

Comments
 (0)