Skip to content

Commit f0acc64

Browse files
kushaMark BirgerCopilotCopilot
authored
feat(compiler): support registered host-await builtins for natural function call syntax (#667)
* feat(compiler): support registered host-await builtins Allow hosts to register function names at compile time so that calls to those names emit HostAwait instructions directly, enabling natural syntax like fetch(x) instead of __builtin_host_await(x, "fetch"). - Add host_await_builtins map and register_host_await_builtin() to Compiler - Validate arg_count == 1 and reject reserved __builtin_host_await name - Extend determine_call_target() resolution: explicit > registered > user > builtin - Both explicit and registered paths emit identical HostAwait bytecode - Add compile_from_policy_with_host_await() entry point in rules.rs - Extended test harness with HostAwaitBuiltinSpec and args assertion - 9 YAML test cases: suspend/resume, run-to-completion, multiple names, queue, shadowing, object packing, arg_count rejection, reserved name rejection, standard builtin override - Documentation: instruction-set.md, architecture.md * Update src/languages/rego/compiler/function_calls.rs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Signed-off-by: Mark Birger <birgerm@yandex.ru> * fix(compiler): address PR #667 review feedback on host-await registration - Compiler::register_host_await_builtin now rejects duplicate, empty, and whitespace-only names. Previously a duplicate registration would silently overwrite the existing entry, which could mask the host's own registration mistakes. - YAML test cases added: empty registration list as no-op, duplicate name rejection, empty/whitespace name rejection, out-param (a, out) calling syntax with a single-arg registered builtin, and mixed __builtin_host_await + registered builtins in the same policy consuming from their respective identifier queues. - Test harness: replace assert_eq! on HostAwait argument mismatch with anyhow::Error so mismatches propagate through the case reporter instead of panicking and skipping the harness's normal error path. - YAML comment fix: "Registration panics" -> "Registration fails with an error" (registration returns Err, never panics). Addresses anakrish + Copilot inline review comments on PR #667. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * compiler: split CallTarget::HostAwait into explicit and registered variants Addresses PR #667 review item #8: at the emit site in `compile_function_call`, the discrimination between explicit `__builtin_host_await(arg, id)` and a registered host-awaitable builtin was being recovered by string-comparing `original_fcn_path` against `"__builtin_host_await"`. The information was already known in `determine_call_target` and was being thrown away. Replace the single `CallTarget::HostAwait` variant with two: * `ExplicitHostAwait` (unit) — the two-argument call form. The identifier register comes from the user's second argument. * `RegisteredHostAwait { identifier: String }` — the one-argument call form for registered builtins. The identifier is the registered name and is captured in the variant at recognition time, so the emit site never re-derives it from the function path. This removes the magic-string comparison at the emit site (the source of truth is now `determine_call_target`) and makes both match sites in `compile_function_call` exhaustive over the two forms — adding a third host-await form in the future would force a compile error at every match site instead of silently falling through. Arities are now hardcoded in the `expected_args` extraction (`Some(2)` for explicit, `Some(1)` for registered) rather than carried in the variant; registered builtins are constrained to `arg_count == 1` at registration time, so there is no per-call variability to carry. Bytecode output is unchanged; the full RVM test suite (97 cases) and the registered_host_await suite (15 cases) pass without modification. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * docs(compiler): clarify registered host-await intercepts unqualified calls only PR #667 review (Medium): the docs implied registered host-await names shadow user functions and builtins unconditionally, but determine_call_target matches only the bare original_fcn_path. A package-qualified call such as data.demo.resolve(x) is therefore not intercepted -- it resolves through the normal path like any other call. Rather than expand registration to qualified paths (which would let a registered name leak into every package exposing a same-named rule), document the unqualified-only behavior and pin it with tests. - register_host_await_builtin: doc now states only the unqualified call form is intercepted; qualified calls resolve normally. - determine_call_target: inline comment explaining the deliberate original_fcn_path-only match. - docs/rvm/instruction-set.md: describe qualified-call resolution, including that builtins have no qualified form. - tests: cross-package and same-package qualified calls resolve to the rule; bare-name shadowing of a standard builtin; Unknown-function outcome when no rule exists at the qualified path. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(tests): compare host-await argument without re-running process_value PR #667 review (Low): the suspendable test harness compared the host-await argument via process_value(argument), but argument is already a runtime Value. process_value is a YAML-fixture decoder -- it rewrites "#undefined" to Undefined, {set!: [...]} to a set, and errors on a runtime Value::Set. Re-running it on the runtime argument could coerce a legitimate payload into a fixture sentinel (passing for the wrong reason) or error outright on sets. Compare the runtime argument directly against the expected value, which is already decoded once at YAML load time. Add a regression case (registered_builtin_suspendable_set_argument) that passes a set payload: it fails under the old double-processing ("unexpected set in value read from json/yaml") and passes with the fix. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(tests): reject `args:` payload expectations in run-to-completion mode PR #667 review (Low): a run-to-completion host-await response could carry an `args:` payload expectation, but RTC execution pre-loads responses and never surfaces the call argument to the harness, so the expectation was parsed and silently dropped. A case with `args: "WRONG"` passed as long as the result matched -- asserting a payload that was never checked. Reject `args:` for run-to-completion fixtures at load time, directing the author to suspendable mode where arguments are validated. Also only build the run-to-completion response vector when the case actually runs in RTC mode, so a suspendable case using the shared host_await_responses field with `args:` is not wrongly rejected. Route the fixture-load error through the same want_error handling used for compilation errors, and add registered_builtin_run_to_completion_rejects_args which now fails loudly instead of passing silently. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(compiler): reject host-await builtin names with surrounding whitespace PR #667 review (Low): register_host_await_builtin rejected all-whitespace names via name.trim().is_empty(), but accepted padded names like " lookup" or "lookup ". Those were inserted into host_await_builtins, but Rego function-call paths produce the trimmed identifier, so a padded registration could never match -- a silent dead registration. Reject any name that is not already trimmed (name != name.trim()) in addition to empty names, and update the error message accordingly. Add test cases for leading and trailing whitespace. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Signed-off-by: Mark Birger <birgerm@yandex.ru> Co-authored-by: Mark Birger <markbirger@microsoft.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 166ea72 commit f0acc64

7 files changed

Lines changed: 962 additions & 25 deletions

File tree

docs/rvm/architecture.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,13 @@ include formatted state snapshots where possible.
254254
7. **Host await**: In run-to-completion mode, `HostAwait` consumes a response
255255
from `host_await_responses`. Suspendable mode yields control with a
256256
`SuspendReason::HostAwait { dest, argument, identifier }` that the host must
257-
service.
257+
service. The compiler supports two ways to emit `HostAwait`:
258+
- **Explicit**: `__builtin_host_await(payload, identifier)` — raw 2-argument
259+
form.
260+
- **Registered**: `compile_from_policy_with_host_await` accepts a list of
261+
`(name, arg_count)` pairs. Calls to registered names are compiled as
262+
`HostAwait` with the function name as the identifier literal. Registered
263+
names take precedence over user-defined functions and standard builtins.
258264
8. **Completion**: `Return` wraps the selected register value into
259265
`InstructionOutcome::Return`, unwinding frames until the entry frame is
260266
cleared. `RuleReturn` is a specialised variant used by rule execution

docs/rvm/instruction-set.md

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,75 @@ Parameter tables:
177177
- Suspendable: emits `InstructionOutcome::Suspend` with `SuspendReason::HostAwait`.
178178
The host must resume with a value that will be written into `dest`.
179179

180+
### Registered host-await builtins
181+
182+
The compiler can be configured with a list of function names that map directly
183+
to `HostAwait` instructions. This allows policy authors to write natural
184+
function calls (e.g. `lookup(input.account_id)`) instead of the raw
185+
`__builtin_host_await(payload, identifier)` builtin.
186+
187+
Registration is done at compile time via `Compiler::compile_from_policy_with_host_await`:
188+
189+
```rust
190+
let builtins = [("lookup", 1), ("persist", 1)];
191+
let program = Compiler::compile_from_policy_with_host_await(
192+
&compiled_policy, &entry_points, &builtins,
193+
)?;
194+
```
195+
196+
Each registered name is a `(name, arg_count)` pair. When the compiler
197+
encounters a call to a registered name, it emits a `HostAwait` instruction
198+
with:
199+
- `arg` = the first argument register
200+
- `id` = a register loaded with a string literal containing the function name
201+
202+
Both the explicit `__builtin_host_await(arg, id)` call and a registered
203+
builtin call produce the **same `HostAwait` bytecode instruction**. The only
204+
difference is how the `id` register is populated: explicit calls take it from
205+
the second user-supplied argument, while registered calls auto-generate a
206+
`Load` instruction for the function name string. The VM cannot distinguish
207+
between the two at runtime.
208+
209+
**Resolution order** in `determine_call_target()`:
210+
1. `__builtin_host_await` (magic 2-argument form)
211+
2. Registered host-await builtins (matched by **bare** function name only)
212+
3. User-defined functions (matched by package-qualified path)
213+
4. Standard builtins (matched by bare function name)
214+
215+
Registered names shadow both user-defined functions and standard builtins.
216+
This means `time.parse_duration_ns` can be overridden to route through the
217+
host instead of the built-in Rust implementation.
218+
219+
**Only unqualified calls are intercepted.** Registration matches a call by
220+
the name *as written in the policy*. A bare call — `lookup(x)` — is
221+
intercepted and compiled to a `HostAwait`. A package-qualified call —
222+
`data.pkg.lookup(x)` — is **not** intercepted; it is resolved normally, as
223+
if the name were never registered.
224+
225+
```rego
226+
# "lookup" is registered as a host-await builtin.
227+
228+
package other
229+
import rego.v1
230+
lookup(k) := k # an ordinary rule that happens to share the name
231+
232+
package demo
233+
import rego.v1
234+
a := lookup(input.k) # intercepted -> HostAwait
235+
b := data.other.lookup(input.k) # NOT intercepted -> calls other.lookup
236+
```
237+
238+
The qualified form is resolved exactly as it would be without registration:
239+
if a rule exists at that path it is called, otherwise compilation fails with
240+
`Unknown function`. (A standard builtin like `count` has no qualified form at
241+
all, so `data.pkg.count(x)` is always an `Unknown function` error, registered
242+
or not.)
243+
244+
**Argument handling**: The `HostAwait` instruction carries a single `arg`
245+
register. Registered builtins must use `arg_count: 1`; the compiler rejects
246+
`arg_count > 1` at registration time. To pass multiple values, use object
247+
packing: `lookup({"user": x, "resource": y})`.
248+
180249
---
181250

182251
## Halt instruction

src/languages/rego/compiler/function_calls.rs

Lines changed: 79 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,20 @@ use crate::lexer::Span;
1717
use crate::rvm::instructions::{BuiltinCallParams, FunctionCallParams};
1818
use crate::rvm::Instruction;
1919
use crate::utils::get_path_string;
20-
use alloc::{format, string::ToString, vec::Vec};
20+
use crate::value::Value;
21+
use alloc::{
22+
format,
23+
string::{String, ToString},
24+
vec::Vec,
25+
};
2126

27+
/// Resolved destination of a Rego function-call expression. Produced by
28+
/// [`Compiler::determine_call_target`] and consumed by
29+
/// [`Compiler::compile_function_call`] to choose which instruction to emit.
30+
/// Carrying the discrimination in the type (rather than re-matching on a
31+
/// magic name at the emit site) keeps the host-await handling honest under
32+
/// future refactors — the compiler will refuse to build if a new variant is
33+
/// added without updating every match site.
2234
enum CallTarget {
2335
User {
2436
rule_index: u16,
@@ -28,9 +40,14 @@ enum CallTarget {
2840
builtin_index: u16,
2941
expected_args: Option<usize>,
3042
},
31-
HostAwait {
32-
expected_args: Option<usize>,
33-
},
43+
/// Explicit `__builtin_host_await(arg, id)` call form (2 user args).
44+
/// The identifier is supplied by the policy author at runtime via the
45+
/// second argument register.
46+
ExplicitHostAwait,
47+
/// A registered host-awaitable builtin invoked by its registered name
48+
/// (1 user arg). The identifier is the registered name itself and is
49+
/// baked into the bytecode as a string literal at compile time.
50+
RegisteredHostAwait { identifier: String },
3451
}
3552

3653
impl<'a> Compiler<'a> {
@@ -59,7 +76,11 @@ impl<'a> Compiler<'a> {
5976
let expected_args = match &call_target {
6077
CallTarget::User { expected_args, .. } => *expected_args,
6178
CallTarget::Builtin { expected_args, .. } => *expected_args,
62-
CallTarget::HostAwait { expected_args } => *expected_args,
79+
// Both host-await variants have a known fixed arity; carrying it
80+
// in the variant lets the rest of the compiler depend on the type
81+
// rather than re-matching on the magic name `__builtin_host_await`.
82+
CallTarget::ExplicitHostAwait => Some(2),
83+
CallTarget::RegisteredHostAwait { .. } => Some(1),
6384
};
6485

6586
if let Some(expected) = expected_args {
@@ -126,7 +147,8 @@ impl<'a> Compiler<'a> {
126147
});
127148
self.emit_instruction(Instruction::BuiltinCall { params_index }, &span);
128149
}
129-
CallTarget::HostAwait { .. } => {
150+
CallTarget::ExplicitHostAwait => {
151+
// Explicit __builtin_host_await(arg, id) — 2 arguments
130152
if arg_regs.len() != 2 {
131153
return Err(CompilerError::General {
132154
message: format!(
@@ -136,7 +158,6 @@ impl<'a> Compiler<'a> {
136158
}
137159
.at(&span));
138160
}
139-
140161
self.emit_instruction(
141162
Instruction::HostAwait {
142163
dest,
@@ -146,6 +167,37 @@ impl<'a> Compiler<'a> {
146167
&span,
147168
);
148169
}
170+
CallTarget::RegisteredHostAwait { identifier } => {
171+
// Registered host-awaitable builtin — the identifier is the
172+
// registered name and is baked into the bytecode as a literal.
173+
if arg_regs.len() != 1 {
174+
return Err(CompilerError::General {
175+
message: format!(
176+
"host-awaitable builtin '{}' expects exactly 1 argument, got {}",
177+
identifier,
178+
arg_regs.len()
179+
),
180+
}
181+
.at(&span));
182+
}
183+
let id_reg = self.alloc_register();
184+
let literal_idx = self.add_literal(Value::String(identifier.into()));
185+
self.emit_instruction(
186+
Instruction::Load {
187+
dest: id_reg,
188+
literal_idx,
189+
},
190+
&span,
191+
);
192+
self.emit_instruction(
193+
Instruction::HostAwait {
194+
dest,
195+
arg: arg_regs[0],
196+
id: id_reg,
197+
},
198+
&span,
199+
);
200+
}
149201
}
150202

151203
if let Some((plan, plan_span)) = &out_param_plan {
@@ -187,8 +239,26 @@ impl<'a> Compiler<'a> {
187239
span: &Span,
188240
) -> Result<CallTarget> {
189241
if original_fcn_path == "__builtin_host_await" {
190-
return Ok(CallTarget::HostAwait {
191-
expected_args: Some(2),
242+
return Ok(CallTarget::ExplicitHostAwait);
243+
}
244+
245+
// Check registered host-awaitable builtins. Registered builtins are
246+
// restricted to arg_count == 1 at registration time (see
247+
// `Compiler::register_host_await_builtin`), so the variant doesn't
248+
// need to carry an arity — it's fixed at 1.
249+
//
250+
// We deliberately match against `original_fcn_path` only, not
251+
// `full_fcn_path`. Registration intercepts the *unqualified* call
252+
// form (e.g. `lookup(x)` inside the policy's own package). A
253+
// package-qualified call like `data.other.lookup(x)` is left to
254+
// resolve through the normal user-defined / builtin path, so a
255+
// registered name does not leak into unrelated packages that
256+
// happen to expose a rule with the same identifier. This is
257+
// documented on `register_host_await_builtin`; the
258+
// `registered_host_await.yaml` suite pins the behavior.
259+
if self.host_await_builtins.contains_key(original_fcn_path) {
260+
return Ok(CallTarget::RegisteredHostAwait {
261+
identifier: original_fcn_path.to_string(),
192262
});
193263
}
194264

src/languages/rego/compiler/mod.rs

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,9 @@ use crate::rvm::program::{Program, RuleType, SpanInfo};
2626
use crate::CompiledPolicy;
2727
use crate::Value;
2828
use alloc::collections::{BTreeMap, BTreeSet};
29+
use alloc::format;
2930
use alloc::string::String;
31+
use alloc::string::ToString as _;
3032
use alloc::vec;
3133
use alloc::vec::Vec;
3234
use indexmap::IndexMap;
@@ -139,6 +141,10 @@ pub struct Compiler<'a> {
139141
current_call_stack: Vec<u16>,
140142
entry_points: IndexMap<String, usize>,
141143
soft_assert_mode: bool,
144+
/// Registered host-awaitable builtins: name → expected arg count.
145+
/// When the compiler encounters a call to one of these names, it emits a
146+
/// `HostAwait` instruction instead of a regular function or builtin call.
147+
host_await_builtins: BTreeMap<String, usize>,
142148
}
143149

144150
impl<'a> Compiler<'a> {
@@ -173,9 +179,75 @@ impl<'a> Compiler<'a> {
173179
current_call_stack: Vec::new(),
174180
entry_points: IndexMap::new(),
175181
soft_assert_mode: false,
182+
host_await_builtins: BTreeMap::new(),
176183
}
177184
}
178185

186+
/// Register a function name as a host-awaitable builtin.
187+
///
188+
/// When the compiler encounters an **unqualified** call to `name(arg)`
189+
/// (i.e. `name(arg)` from inside the policy's own package, not
190+
/// `data.pkg.name(arg)` or any other package-qualified form), it will
191+
/// emit a `HostAwait` instruction with the argument and `name` as the
192+
/// identifier, instead of treating it as a user-defined or standard
193+
/// builtin function.
194+
///
195+
/// Package-qualified calls (e.g. `data.other.name(arg)`) are **not**
196+
/// intercepted by registration. Those resolve through the normal
197+
/// user-defined / builtin lookup against their fully-qualified path
198+
/// (`data.other.name`).
199+
///
200+
/// `arg_count` must be exactly 1. The `HostAwait` instruction carries a
201+
/// single argument register; use object packing to pass multiple values
202+
/// (e.g. `name({"key1": v1, "key2": v2})`).
203+
///
204+
/// Returns `Err` when:
205+
/// - `name` is the reserved identifier `__builtin_host_await`,
206+
/// - `name` is empty, only whitespace, or has leading/trailing
207+
/// whitespace (whitespace-padded names would never match the
208+
/// trimmed identifier produced by the Rego parser, creating dead
209+
/// registrations),
210+
/// - `name` is already registered (duplicate registration is rejected
211+
/// rather than silently overwritten),
212+
/// - `arg_count` is not exactly 1.
213+
pub fn register_host_await_builtin(&mut self, name: &str, arg_count: usize) -> Result<()> {
214+
if name == "__builtin_host_await" {
215+
return Err(CompilerError::General {
216+
message: "__builtin_host_await is a reserved name and cannot be registered as a host-await builtin"
217+
.to_string(),
218+
}
219+
.into());
220+
}
221+
if name.is_empty() || name != name.trim() {
222+
return Err(CompilerError::General {
223+
message: format!(
224+
"host-await builtin name {name:?} must not be empty or contain leading/trailing whitespace"
225+
),
226+
}
227+
.into());
228+
}
229+
if self.host_await_builtins.contains_key(name) {
230+
return Err(CompilerError::General {
231+
message: format!(
232+
"host-await builtin '{name}' is already registered; \
233+
duplicate registration is not allowed"
234+
),
235+
}
236+
.into());
237+
}
238+
if arg_count != 1 {
239+
return Err(CompilerError::General {
240+
message: format!(
241+
"registered host-await builtin '{name}' must have arg_count == 1, got {arg_count}. \
242+
Use object packing to pass multiple values."
243+
),
244+
}
245+
.into());
246+
}
247+
self.host_await_builtins.insert(name.to_string(), arg_count);
248+
Ok(())
249+
}
250+
179251
pub(super) fn with_soft_assert_mode<F, R>(&mut self, enabled: bool, f: F) -> R
180252
where
181253
F: FnOnce(&mut Self) -> R,

src/languages/rego/compiler/rules.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,8 +234,20 @@ impl<'a> Compiler<'a> {
234234
pub fn compile_from_policy(
235235
policy: &CompiledPolicy,
236236
entry_points: &[&str],
237+
) -> Result<Arc<Program>> {
238+
Self::compile_from_policy_with_host_await(policy, entry_points, &[])
239+
}
240+
241+
/// Compile from a CompiledPolicy to RVM Program with registered host-awaitable builtins.
242+
pub fn compile_from_policy_with_host_await(
243+
policy: &CompiledPolicy,
244+
entry_points: &[&str],
245+
host_await_builtins: &[(&str, usize)],
237246
) -> Result<Arc<Program>> {
238247
let mut compiler = Compiler::with_policy(policy);
248+
for &(name, arg_count) in host_await_builtins {
249+
compiler.register_host_await_builtin(name, arg_count)?;
250+
}
239251
compiler.current_rule_path = "".to_string();
240252
let rules = policy.get_rules();
241253

0 commit comments

Comments
 (0)