regorus 0.9.1

A fast, lightweight Rego (OPA policy language) interpreter
Documentation
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};

use super::types::{ComprehensionMode, LiteralOrRegister, LoopMode};

/// Loop parameters stored in program's instruction data table
#[repr(C)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoopStartParams {
    /// Loop mode (Existential/Universal/Comprehension types)
    pub mode: LoopMode,
    /// Register containing the collection to iterate over
    pub collection: u8,
    /// Register to store current key (same as value_reg if key not needed)
    pub key_reg: u8,
    /// Register to store current value
    pub value_reg: u8,
    /// Register to store final result
    pub result_reg: u8,
    /// Jump target for loop body start
    pub body_start: u16,
    /// Jump target for loop end
    pub loop_end: u16,
}

/// Builtin function call parameters stored in program's instruction data table
#[repr(C)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BuiltinCallParams {
    /// Destination register to store the result
    pub dest: u8,
    /// Index into program's builtin_info_table
    pub builtin_index: u16,
    /// Number of arguments actually used
    pub num_args: u8,
    /// Argument register numbers (unused slots contain undefined values)
    pub args: [u8; 8],
}

impl BuiltinCallParams {
    /// Get the number of arguments actually used
    pub fn arg_count(&self) -> usize {
        usize::from(self.num_args)
    }

    /// Get argument register numbers as a slice
    pub fn arg_registers(&self) -> &[u8] {
        let count = usize::from(self.num_args).min(self.args.len());
        self.args.get(..count).unwrap_or(&[])
    }
}

/// Function rule call parameters stored in program's instruction data table
#[repr(C)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionCallParams {
    /// Destination register to store the result
    pub dest: u8,
    /// Rule index of the function to call
    pub func_rule_index: u16,
    /// Number of arguments actually used
    pub num_args: u8,
    /// Argument register numbers (unused slots contain undefined values)
    pub args: [u8; 8],
}

impl FunctionCallParams {
    /// Get the number of arguments actually used
    pub fn arg_count(&self) -> usize {
        usize::from(self.num_args)
    }

    /// Get argument register numbers as a slice
    pub fn arg_registers(&self) -> &[u8] {
        let count = usize::from(self.num_args).min(self.args.len());
        self.args.get(..count).unwrap_or(&[])
    }
}

/// Object creation parameters stored in program's instruction data table
#[repr(C)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObjectCreateParams {
    /// Destination register to store the result object
    pub dest: u8,
    /// Literal index of template object with all keys (undefined values)
    /// Always present - empty object if no literal keys
    pub template_literal_idx: u16,
    /// Fields with literal keys: (literal_key_index, value_register) in sorted order
    pub literal_key_fields: Vec<(u16, u8)>,
    /// Fields with non-literal keys: (key_register, value_register)
    pub fields: Vec<(u8, u8)>,
}

impl ObjectCreateParams {
    /// Get the total number of fields
    pub const fn field_count(&self) -> usize {
        self.literal_key_fields
            .len()
            .saturating_add(self.fields.len())
    }

    /// Get literal key field pairs as a slice
    pub fn literal_key_field_pairs(&self) -> &[(u16, u8)] {
        &self.literal_key_fields
    }

    /// Get non-literal key field pairs as a slice
    pub fn field_pairs(&self) -> &[(u8, u8)] {
        &self.fields
    }
}

/// Array creation parameters stored in program's instruction data table
#[repr(C)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArrayCreateParams {
    /// Destination register to store the result array
    pub dest: u8,
    /// Register numbers containing the element values
    pub elements: Vec<u8>,
}

impl ArrayCreateParams {
    /// Get the number of elements
    pub const fn element_count(&self) -> usize {
        self.elements.len()
    }

    /// Get element register numbers as a slice
    pub fn element_registers(&self) -> &[u8] {
        &self.elements
    }
}

/// Set creation parameters stored in program's instruction data table
#[repr(C)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SetCreateParams {
    /// Destination register to store the result set
    pub dest: u8,
    /// Register numbers containing the element values
    pub elements: Vec<u8>,
}

impl SetCreateParams {
    /// Get the number of elements
    pub const fn element_count(&self) -> usize {
        self.elements.len()
    }

    /// Get element register numbers as a slice
    pub fn element_registers(&self) -> &[u8] {
        &self.elements
    }
}

/// Virtual data document lookup parameters for data namespace access with rule evaluation
#[repr(C)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VirtualDataDocumentLookupParams {
    /// Destination register to store the result
    pub dest: u8,
    /// Path components in order (e.g., for data.users[input.name].config)
    /// This would be [Literal("users"), Register(5), Literal("config")]
    /// where register 5 contains the value from input.name
    pub path_components: Vec<LiteralOrRegister>,
}

impl VirtualDataDocumentLookupParams {
    /// Get the number of path components
    pub const fn component_count(&self) -> usize {
        self.path_components.len()
    }

    /// Check if all components are literals (can be optimized at compile time)
    pub fn all_literals(&self) -> bool {
        self.path_components
            .iter()
            .all(|c| matches!(c, LiteralOrRegister::Literal(_)))
    }

    /// Get just the literal indices (for debugging/display)
    pub fn literal_indices(&self) -> Vec<u16> {
        self.path_components
            .iter()
            .filter_map(|c| match *c {
                LiteralOrRegister::Literal(idx) => Some(idx),
                _ => None,
            })
            .collect()
    }

    /// Get just the register numbers (for debugging/display)
    pub fn register_numbers(&self) -> Vec<u8> {
        self.path_components
            .iter()
            .filter_map(|c| match *c {
                LiteralOrRegister::Register(reg) => Some(reg),
                _ => None,
            })
            .collect()
    }
}

/// Chained index parameters for multi-level object access (input, locals, non-rule data paths)
#[repr(C)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChainedIndexParams {
    /// Destination register to store the result
    pub dest: u8,
    /// Root register containing the base object (input, local var, data subset)
    pub root: u8,
    /// Path components to traverse from the root
    pub path_components: Vec<LiteralOrRegister>,
}

impl ChainedIndexParams {
    /// Get the number of path components
    pub const fn component_count(&self) -> usize {
        self.path_components.len()
    }

    /// Check if all components are literals (can be optimized)
    pub fn all_literals(&self) -> bool {
        self.path_components
            .iter()
            .all(|c| matches!(c, LiteralOrRegister::Literal(_)))
    }

    /// Get just the literal indices (for debugging/display)
    pub fn literal_indices(&self) -> Vec<u16> {
        self.path_components
            .iter()
            .filter_map(|c| match *c {
                LiteralOrRegister::Literal(idx) => Some(idx),
                _ => None,
            })
            .collect()
    }

    /// Get just the register numbers (for debugging/display)
    pub fn register_numbers(&self) -> Vec<u8> {
        self.path_components
            .iter()
            .filter_map(|c| match *c {
                LiteralOrRegister::Register(reg) => Some(reg),
                _ => None,
            })
            .collect()
    }
}

/// Comprehension parameters stored in program's instruction data table
#[repr(C)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComprehensionBeginParams {
    /// Type of comprehension being created
    pub mode: ComprehensionMode,
    /// Register containing the source collection to iterate over
    pub collection_reg: u8,
    /// Register to store the comprehension result collection
    /// If not specified separately, this will match collection_reg
    pub result_reg: u8,
    /// Register to store current iteration key
    pub key_reg: u8,
    /// Register to store current iteration value
    pub value_reg: u8,
    /// Jump target for comprehension body start
    pub body_start: u16,
    /// Jump target for comprehension end
    pub comprehension_end: u16,
}

/// Instruction data container for complex instruction parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InstructionData {
    /// Loop parameter table for LoopStart instructions
    pub loop_params: Vec<LoopStartParams>,
    /// Builtin function call parameter table for BuiltinCall instructions
    pub builtin_call_params: Vec<BuiltinCallParams>,
    /// Function rule call parameter table for FunctionCall instructions
    pub function_call_params: Vec<FunctionCallParams>,
    /// Object creation parameter table for ObjectCreate instructions
    pub object_create_params: Vec<ObjectCreateParams>,
    /// Array creation parameter table for ArrayCreate instructions
    pub array_create_params: Vec<ArrayCreateParams>,
    /// Set creation parameter table for SetCreate instructions
    pub set_create_params: Vec<SetCreateParams>,
    /// Virtual data document lookup parameter table for VirtualDataDocumentLookup instructions
    pub virtual_data_document_lookup_params: Vec<VirtualDataDocumentLookupParams>,
    /// Chained index parameter table for ChainedIndex instructions
    pub chained_index_params: Vec<ChainedIndexParams>,
    /// Comprehension parameter table for ComprehensionBegin instructions
    pub comprehension_begin_params: Vec<ComprehensionBeginParams>,
}

impl InstructionData {
    fn ensure_u16_index(len: usize) -> u16 {
        debug_assert!(len <= usize::from(u16::MAX));
        u16::try_from(len).unwrap_or(u16::MAX)
    }

    /// Create a new empty instruction data container
    pub const fn new() -> Self {
        Self {
            loop_params: Vec::new(),
            builtin_call_params: Vec::new(),
            function_call_params: Vec::new(),
            object_create_params: Vec::new(),
            array_create_params: Vec::new(),
            set_create_params: Vec::new(),
            virtual_data_document_lookup_params: Vec::new(),
            chained_index_params: Vec::new(),
            comprehension_begin_params: Vec::new(),
        }
    }

    /// Add loop parameters and return the index
    pub fn add_loop_params(&mut self, params: LoopStartParams) -> u16 {
        let index = Self::ensure_u16_index(self.loop_params.len());
        self.loop_params.push(params);
        index
    }

    /// Add builtin call parameters and return the index
    pub fn add_builtin_call_params(&mut self, params: BuiltinCallParams) -> u16 {
        let index = Self::ensure_u16_index(self.builtin_call_params.len());
        self.builtin_call_params.push(params);
        index
    }

    /// Add function call parameters and return the index
    pub fn add_function_call_params(&mut self, params: FunctionCallParams) -> u16 {
        let index = Self::ensure_u16_index(self.function_call_params.len());
        self.function_call_params.push(params);
        index
    }

    /// Add object create parameters and return the index
    pub fn add_object_create_params(&mut self, params: ObjectCreateParams) -> u16 {
        let index = Self::ensure_u16_index(self.object_create_params.len());
        self.object_create_params.push(params);
        index
    }

    /// Add array create parameters and return the index
    pub fn add_array_create_params(&mut self, params: ArrayCreateParams) -> u16 {
        let index = Self::ensure_u16_index(self.array_create_params.len());
        self.array_create_params.push(params);
        index
    }

    /// Add set create parameters and return the index
    pub fn add_set_create_params(&mut self, params: SetCreateParams) -> u16 {
        let index = Self::ensure_u16_index(self.set_create_params.len());
        self.set_create_params.push(params);
        index
    }

    /// Get loop parameters by index
    pub fn get_loop_params(&self, index: u16) -> Option<&LoopStartParams> {
        self.loop_params.get(usize::from(index))
    }

    /// Get builtin call parameters by index
    pub fn get_builtin_call_params(&self, index: u16) -> Option<&BuiltinCallParams> {
        self.builtin_call_params.get(usize::from(index))
    }

    /// Get function call parameters by index
    pub fn get_function_call_params(&self, index: u16) -> Option<&FunctionCallParams> {
        self.function_call_params.get(usize::from(index))
    }

    /// Get object create parameters by index
    pub fn get_object_create_params(&self, index: u16) -> Option<&ObjectCreateParams> {
        self.object_create_params.get(usize::from(index))
    }

    /// Get array create parameters by index
    pub fn get_array_create_params(&self, index: u16) -> Option<&ArrayCreateParams> {
        self.array_create_params.get(usize::from(index))
    }

    /// Get set create parameters by index
    pub fn get_set_create_params(&self, index: u16) -> Option<&SetCreateParams> {
        self.set_create_params.get(usize::from(index))
    }

    /// Add virtual data document lookup parameters and return the index
    pub fn add_virtual_data_document_lookup_params(
        &mut self,
        params: VirtualDataDocumentLookupParams,
    ) -> u16 {
        let index = Self::ensure_u16_index(self.virtual_data_document_lookup_params.len());
        self.virtual_data_document_lookup_params.push(params);
        index
    }

    /// Get virtual data document lookup parameters by index
    pub fn get_virtual_data_document_lookup_params(
        &self,
        index: u16,
    ) -> Option<&VirtualDataDocumentLookupParams> {
        self.virtual_data_document_lookup_params
            .get(usize::from(index))
    }

    /// Add chained index parameters and return the index
    pub fn add_chained_index_params(&mut self, params: ChainedIndexParams) -> u16 {
        let index = Self::ensure_u16_index(self.chained_index_params.len());
        self.chained_index_params.push(params);
        index
    }

    /// Get chained index parameters by index
    pub fn get_chained_index_params(&self, index: u16) -> Option<&ChainedIndexParams> {
        self.chained_index_params.get(usize::from(index))
    }

    /// Get mutable reference to loop parameters by index
    pub fn get_loop_params_mut(&mut self, index: u16) -> Option<&mut LoopStartParams> {
        self.loop_params.get_mut(usize::from(index))
    }

    /// Add comprehension begin parameters and return the index
    pub fn add_comprehension_begin_params(&mut self, params: ComprehensionBeginParams) -> u16 {
        let index = Self::ensure_u16_index(self.comprehension_begin_params.len());
        self.comprehension_begin_params.push(params);
        index
    }

    /// Get comprehension begin parameters by index
    pub fn get_comprehension_begin_params(&self, index: u16) -> Option<&ComprehensionBeginParams> {
        self.comprehension_begin_params.get(usize::from(index))
    }

    /// Get mutable reference to comprehension begin parameters by index
    pub fn get_comprehension_begin_params_mut(
        &mut self,
        index: u16,
    ) -> Option<&mut ComprehensionBeginParams> {
        self.comprehension_begin_params.get_mut(usize::from(index))
    }
}

impl Default for InstructionData {
    fn default() -> Self {
        Self::new()
    }
}