1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#![allow(
clippy::arithmetic_side_effects,
clippy::indexing_slicing,
clippy::unseparated_literal_suffix,
clippy::as_conversions,
clippy::unused_trait_names,
clippy::pattern_type_mismatch
)]
use super::{Compiler, CompilerError, Register, Result};
use crate::ast::ExprRef;
use crate::builtins;
use crate::compiler::destructuring_planner::plans::BindingPlan;
use crate::lexer::Span;
use crate::rvm::instructions::{BuiltinCallParams, FunctionCallParams};
use crate::rvm::Instruction;
use crate::utils::{append_path_component, get_path_string, split_canonical_path_root};
use crate::value::Value;
use alloc::{
format,
string::{String, ToString},
vec::Vec,
};
/// Resolved destination of a Rego function-call expression. Produced by
/// [`Compiler::determine_call_target`] and consumed by
/// [`Compiler::compile_function_call`] to choose which instruction to emit.
/// Carrying the discrimination in the type (rather than re-matching on a
/// magic name at the emit site) keeps the host-await handling honest under
/// future refactors — the compiler will refuse to build if a new variant is
/// added without updating every match site.
enum CallTarget {
User {
rule_index: u16,
expected_args: Option<usize>,
},
Builtin {
builtin_index: u16,
expected_args: Option<usize>,
},
/// Explicit `__builtin_host_await(arg, id)` call form (2 user args).
/// The identifier is supplied by the policy author at runtime via the
/// second argument register.
ExplicitHostAwait,
/// A registered host-awaitable builtin invoked by its registered name
/// (1 user arg). The identifier is the registered name itself and is
/// baked into the bytecode as a string literal at compile time.
RegisteredHostAwait { identifier: String },
}
impl<'a> Compiler<'a> {
pub(super) fn compile_function_call(
&mut self,
fcn: &ExprRef,
params: &[ExprRef],
span: Span,
) -> Result<Register> {
let fcn_path = get_path_string(fcn, None)
.map_err(|_| CompilerError::InvalidFunctionExpression.at(&span))?;
let original_fcn_path = fcn_path.clone();
let full_fcn_path = if self.policy.inner.rules.contains_key(&fcn_path) {
fcn_path
} else if let Some(resolved) = self.resolve_fcn_path_through_imports(&original_fcn_path) {
// Resolve a leading import alias before module-prefixing and builtins.
resolved
} else {
get_path_string(fcn, Some(&self.current_package))
.map_err(|_| CompilerError::InvalidFunctionExpressionWithPackage.at(&span))?
};
let mut out_param_plan: Option<(BindingPlan, Span)> = None;
let mut params_to_compile = params.len();
let call_target = self.determine_call_target(&original_fcn_path, &full_fcn_path, &span)?;
let expected_args = match &call_target {
CallTarget::User { expected_args, .. } => *expected_args,
CallTarget::Builtin { expected_args, .. } => *expected_args,
// Both host-await variants have a known fixed arity; carrying it
// in the variant lets the rest of the compiler depend on the type
// rather than re-matching on the magic name `__builtin_host_await`.
CallTarget::ExplicitHostAwait => Some(2),
CallTarget::RegisteredHostAwait { .. } => Some(1),
};
if let Some(expected) = expected_args {
if params.len() == expected + 1 {
if let Some(last_param) = params.last() {
let plan = self.expect_binding_plan_for_expr(
last_param,
&format!("extra argument for function '{}'", original_fcn_path),
)?;
match plan {
BindingPlan::Parameter { .. } => {
out_param_plan = Some((plan, last_param.span().clone()));
params_to_compile -= 1;
}
other => {
return Err(CompilerError::UnexpectedBindingPlan {
context: "function extra argument".to_string(),
found: format!("{other:?}"),
}
.at(last_param.span()));
}
}
}
}
}
let mut arg_regs = Vec::new();
for param in params.iter().take(params_to_compile) {
let param_reg = self.compile_rego_expr_with_span(param, param.span(), false)?;
arg_regs.push(param_reg);
}
let dest = self.alloc_register();
match call_target {
CallTarget::User { rule_index, .. } => {
let mut args_array = [0u8; 8];
let num_args = arg_regs.len().min(8) as u8;
for (i, ®) in arg_regs.iter().take(8).enumerate() {
args_array[i] = reg;
}
let params_index = self.program.add_function_call_params(FunctionCallParams {
func_rule_index: rule_index,
dest,
num_args,
args: args_array,
});
self.emit_instruction(Instruction::FunctionCall { params_index }, &span);
}
CallTarget::Builtin { builtin_index, .. } => {
let mut args_array = [0u8; 8];
let num_args = arg_regs.len().min(8) as u8;
for (i, ®) in arg_regs.iter().take(8).enumerate() {
args_array[i] = reg;
}
let params_index = self.program.add_builtin_call_params(BuiltinCallParams {
dest,
builtin_index,
num_args,
args: args_array,
});
self.emit_instruction(Instruction::BuiltinCall { params_index }, &span);
}
CallTarget::ExplicitHostAwait => {
// Explicit __builtin_host_await(arg, id) — 2 arguments
if arg_regs.len() != 2 {
return Err(CompilerError::General {
message: format!(
"__builtin_host_await expects 2 arguments, got {}",
arg_regs.len()
),
}
.at(&span));
}
self.emit_instruction(
Instruction::HostAwait {
dest,
arg: arg_regs[0],
id: arg_regs[1],
},
&span,
);
}
CallTarget::RegisteredHostAwait { identifier } => {
// Registered host-awaitable builtin — the identifier is the
// registered name and is baked into the bytecode as a literal.
if arg_regs.len() != 1 {
return Err(CompilerError::General {
message: format!(
"host-awaitable builtin '{}' expects exactly 1 argument, got {}",
identifier,
arg_regs.len()
),
}
.at(&span));
}
let id_reg = self.alloc_register();
let literal_idx = self.add_literal(Value::String(identifier.into()));
self.emit_instruction(
Instruction::Load {
dest: id_reg,
literal_idx,
},
&span,
);
self.emit_instruction(
Instruction::HostAwait {
dest,
arg: arg_regs[0],
id: id_reg,
},
&span,
);
}
}
if let Some((plan, plan_span)) = &out_param_plan {
let plan_result = self
.apply_binding_plan(plan, dest, plan_span)
.map_err(|err| CompilerError::from(err).at(plan_span))?;
if let Some(result_reg) = plan_result {
self.emit_instruction(
Instruction::Move {
dest,
src: result_reg,
},
&span,
);
} else {
self.emit_instruction(Instruction::LoadBool { dest, value: true }, &span);
}
}
Ok(dest)
}
/// Rewrite an import-aliased call path to its target, e.g. `b.f(1)` to
/// `data.a.b.f` after `import data.a.b`. Resolves only when the target is
/// a known function (the `rules` map cannot be used here: it also indexes
/// value rules and every rule-path prefix, which must not become callable
/// through an alias), so an alias whose target defines the called
/// function shadows a like-named builtin namespace, while other spellings
/// keep their prior meaning (e.g. a builtin call). OPA instead rewrites
/// aliases unconditionally and rejects calls to a missing target at
/// compile time.
fn resolve_fcn_path_through_imports(&self, path: &str) -> Option<String> {
if self.policy.inner.imports.is_empty() {
return None;
}
let (alias, suffix) = split_canonical_path_root(path)?;
if alias == "data" {
return None;
}
let import_key = append_path_component(&self.current_package, alias).ok()?;
let import_expr = self.policy.inner.imports.get(&import_key)?;
let mut candidate = get_path_string(import_expr.as_ref(), None).ok()?;
candidate.push_str(suffix);
self.policy
.inner
.functions
.contains_key(&candidate)
.then_some(candidate)
}
fn lookup_builtin_arity(&self, name: &str) -> Option<usize> {
if name == "print" {
Some(2)
} else {
builtins::BUILTINS
.get(name)
.map(|(_, arity)| *arity as usize)
}
}
}
impl<'a> Compiler<'a> {
fn determine_call_target(
&mut self,
original_fcn_path: &str,
full_fcn_path: &str,
span: &Span,
) -> Result<CallTarget> {
if original_fcn_path == "__builtin_host_await" {
return Ok(CallTarget::ExplicitHostAwait);
}
// Check registered host-awaitable builtins. Registered builtins are
// restricted to arg_count == 1 at registration time (see
// `Compiler::register_host_await_builtin`), so the variant doesn't
// need to carry an arity — it's fixed at 1.
//
// We deliberately match against `original_fcn_path` only, not
// `full_fcn_path`. Registration intercepts the *unqualified* call
// form (e.g. `lookup(x)` inside the policy's own package). A
// package-qualified call like `data.other.lookup(x)` is left to
// resolve through the normal user-defined / builtin path, so a
// registered name does not leak into unrelated packages that
// happen to expose a rule with the same identifier. This is
// documented on `register_host_await_builtin`; the
// `registered_host_await.yaml` suite pins the behavior.
if self.host_await_builtins.contains_key(original_fcn_path) {
return Ok(CallTarget::RegisteredHostAwait {
identifier: original_fcn_path.to_string(),
});
}
if self.is_user_defined_function(full_fcn_path) {
let rule_index = self.get_or_assign_rule_index(full_fcn_path)?;
let expected_args = self
.policy
.inner
.functions
.get(full_fcn_path)
.map(|(_, arity, _)| *arity as usize)
.or_else(|| {
self.rule_function_param_count
.get(rule_index as usize)
.and_then(|count| *count)
});
Ok(CallTarget::User {
rule_index,
expected_args,
})
} else if self.is_builtin(original_fcn_path) {
let builtin_index = self.get_builtin_index(original_fcn_path)?;
let expected_args = self.lookup_builtin_arity(original_fcn_path);
Ok(CallTarget::Builtin {
builtin_index,
expected_args,
})
} else {
Err(CompilerError::UnknownFunction {
name: original_fcn_path.to_string(),
}
.at(span))
}
}
}