ferricel-core 0.1.0

Core compiler and runtime library for ferricel (CEL → Wasm)
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
use cel::common::ast::{CallExpr, operators};
use ferricel_types::functions::RuntimeFunction;
use walrus::{InstrSeqBuilder, ValType};

use crate::compiler::{
    context::{CompilerContext, CompilerEnv},
    expr::compile_expr,
    helpers,
};

/// Compile a binary operator: validate 2 args, compile both, call a runtime function.
pub(crate) fn compile_binary_op(
    call_expr: &CallExpr,
    op_name: &str,
    runtime_fn: RuntimeFunction,
    body: &mut InstrSeqBuilder,
    env: &CompilerEnv,
    ctx: &CompilerContext,
    module: &mut walrus::Module,
) -> Result<(), anyhow::Error> {
    if call_expr.args.len() != 2 {
        anyhow::bail!("{} operator expects 2 arguments", op_name);
    }
    compile_expr(&call_expr.args[0].expr, body, env, ctx, module)?;
    compile_expr(&call_expr.args[1].expr, body, env, ctx, module)?;
    body.call(env.get(runtime_fn));
    Ok(())
}

/// Compile a unary operator: validate 1 arg, compile it, call a runtime function.
pub(crate) fn compile_unary_op(
    call_expr: &CallExpr,
    op_name: &str,
    runtime_fn: RuntimeFunction,
    body: &mut InstrSeqBuilder,
    env: &CompilerEnv,
    ctx: &CompilerContext,
    module: &mut walrus::Module,
) -> Result<(), anyhow::Error> {
    if call_expr.args.len() != 1 {
        anyhow::bail!("{} operator expects 1 argument", op_name);
    }
    compile_expr(&call_expr.args[0].expr, body, env, ctx, module)?;
    body.call(env.get(runtime_fn));
    Ok(())
}

/// Compile logical AND with short-circuit evaluation.
///
/// CEL AND semantics: false && <anything> => false (errors absorbed)
///                    true && <error> => <error> (error propagates)
fn compile_logical_and(
    call_expr: &CallExpr,
    body: &mut InstrSeqBuilder,
    env: &CompilerEnv,
    ctx: &CompilerContext,
    module: &mut walrus::Module,
) -> Result<(), anyhow::Error> {
    if call_expr.args.len() != 2 {
        anyhow::bail!("Logical AND operator expects 2 arguments");
    }

    // Compile left operand
    compile_expr(&call_expr.args[0].expr, body, env, ctx, module)?;

    // Create a local variable to store the left result
    let left_local = module.locals.add(ValType::I32); // *mut CelValue is i32
    body.local_tee(left_local); // Duplicate and store left value

    // Check if left is strictly false
    body.call(env.get(RuntimeFunction::IsStrictlyFalse)); // Returns i32: 1 if false, 0 otherwise

    // Create dangling instruction sequences for then and else branches
    // Both branches must produce *mut CelValue (i32) on the stack
    let then_seq = body.dangling_instr_seq(Some(ValType::I32));
    let then_id = then_seq.id();
    let else_seq = body.dangling_instr_seq(Some(ValType::I32));
    let else_id = else_seq.id();

    // Generate the if/else instruction
    body.instr(walrus::ir::IfElse {
        consequent: then_id,
        alternative: else_id,
    });

    // Then branch: return left (which is false)
    body.instr_seq(then_id).local_get(left_local);

    // Else branch: evaluate right and call cel_bool_and
    let mut else_body = body.instr_seq(else_id);
    compile_expr(&call_expr.args[1].expr, &mut else_body, env, ctx, module)?;
    let right_local = module.locals.add(ValType::I32);
    else_body.local_set(right_local); // Store right, consumes stack
    else_body.local_get(left_local); // Push left
    else_body.local_get(right_local); // Push right
    else_body.call(env.get(RuntimeFunction::BoolAnd)); // Call and(left, right)

    Ok(())
}

/// Compile logical OR with short-circuit evaluation.
///
/// CEL OR semantics: true || <anything> => true (errors absorbed)
///                   false || <error> => <error> (error propagates)
fn compile_logical_or(
    call_expr: &CallExpr,
    body: &mut InstrSeqBuilder,
    env: &CompilerEnv,
    ctx: &CompilerContext,
    module: &mut walrus::Module,
) -> Result<(), anyhow::Error> {
    if call_expr.args.len() != 2 {
        anyhow::bail!("Logical OR operator expects 2 arguments");
    }

    // Compile left operand
    compile_expr(&call_expr.args[0].expr, body, env, ctx, module)?;

    // Create a local variable to store the left result
    let left_local = module.locals.add(ValType::I32); // *mut CelValue is i32
    body.local_tee(left_local); // Duplicate and store left value

    // Check if left is strictly true
    body.call(env.get(RuntimeFunction::IsStrictlyTrue)); // Returns i32: 1 if true, 0 otherwise

    // Create dangling instruction sequences for then and else branches
    // Both branches must produce *mut CelValue (i32) on the stack
    let then_seq = body.dangling_instr_seq(Some(ValType::I32));
    let then_id = then_seq.id();
    let else_seq = body.dangling_instr_seq(Some(ValType::I32));
    let else_id = else_seq.id();

    // Generate the if/else instruction
    body.instr(walrus::ir::IfElse {
        consequent: then_id,
        alternative: else_id,
    });

    // Then branch: return left (which is true)
    body.instr_seq(then_id).local_get(left_local);

    // Else branch: evaluate right and call cel_bool_or
    let mut else_body = body.instr_seq(else_id);
    compile_expr(&call_expr.args[1].expr, &mut else_body, env, ctx, module)?;
    let right_local = module.locals.add(ValType::I32);
    else_body.local_set(right_local); // Store right, consumes stack
    else_body.local_get(left_local); // Push left
    else_body.local_get(right_local); // Push right
    else_body.call(env.get(RuntimeFunction::BoolOr)); // Call or(left, right)

    Ok(())
}

/// Compile the ternary conditional operator: condition ? true_value : false_value
///
/// CEL semantics: if condition is error, return error.
/// Otherwise evaluate only the appropriate branch.
fn compile_conditional(
    call_expr: &CallExpr,
    body: &mut InstrSeqBuilder,
    env: &CompilerEnv,
    ctx: &CompilerContext,
    module: &mut walrus::Module,
) -> Result<(), anyhow::Error> {
    if call_expr.args.len() != 3 {
        anyhow::bail!("Conditional operator expects 3 arguments");
    }

    // Compile condition
    compile_expr(&call_expr.args[0].expr, body, env, ctx, module)?;

    // Store condition in local
    let cond_local = module.locals.add(ValType::I32);
    body.local_tee(cond_local); // Duplicate and store

    // Check if condition is error
    body.call(env.get(RuntimeFunction::IsError)); // Returns i32: 1 if error, 0 otherwise

    // Create sequences for error check
    let is_error_seq = body.dangling_instr_seq(Some(ValType::I32));
    let is_error_id = is_error_seq.id();
    let not_error_seq = body.dangling_instr_seq(Some(ValType::I32));
    let not_error_id = not_error_seq.id();

    body.instr(walrus::ir::IfElse {
        consequent: is_error_id,
        alternative: not_error_id,
    });

    // If condition is error, return it
    body.instr_seq(is_error_id).local_get(cond_local);

    // If condition is not error, convert to bool and branch
    let mut not_error_body = body.instr_seq(not_error_id);
    not_error_body.local_get(cond_local);
    not_error_body.call(env.get(RuntimeFunction::ValueToBool)); // Returns i64: 1 for true, 0 for false
    not_error_body.unop(walrus::ir::UnaryOp::I32WrapI64);

    // Create sequences for true/false branches
    let true_branch_seq = not_error_body.dangling_instr_seq(Some(ValType::I32));
    let true_branch_id = true_branch_seq.id();
    let false_branch_seq = not_error_body.dangling_instr_seq(Some(ValType::I32));
    let false_branch_id = false_branch_seq.id();

    not_error_body.instr(walrus::ir::IfElse {
        consequent: true_branch_id,
        alternative: false_branch_id,
    });

    // True branch: evaluate and return true_value
    let mut true_body = not_error_body.instr_seq(true_branch_id);
    compile_expr(&call_expr.args[1].expr, &mut true_body, env, ctx, module)?;

    // False branch: evaluate and return false_value
    let mut false_body = not_error_body.instr_seq(false_branch_id);
    compile_expr(&call_expr.args[2].expr, &mut false_body, env, ctx, module)?;

    Ok(())
}

/// Compile the index operator: container[index]
fn compile_index(
    call_expr: &CallExpr,
    body: &mut InstrSeqBuilder,
    env: &CompilerEnv,
    ctx: &CompilerContext,
    module: &mut walrus::Module,
) -> Result<(), anyhow::Error> {
    if call_expr.args.len() != 2 {
        anyhow::bail!("Index operator _[_] expects 2 arguments (container, index)");
    }
    // Compile container (array or map)
    compile_expr(&call_expr.args[0].expr, body, env, ctx, module)?;
    // Compile index (int for array, string for map)
    compile_expr(&call_expr.args[1].expr, body, env, ctx, module)?;
    // Call the polymorphic index function
    body.call(env.get(RuntimeFunction::ValueIndex));
    Ok(())
}

/// Compile the optional index operator: container[?index]
///
/// Returns `Optional(Some(value))` if the key/index exists,
/// `Optional(None)` if the key/index is absent (no error).
///
/// AST: `func_name = "_[?_]"`, `args = [container, index]`
fn compile_opt_index(
    call_expr: &CallExpr,
    body: &mut InstrSeqBuilder,
    env: &CompilerEnv,
    ctx: &CompilerContext,
    module: &mut walrus::Module,
) -> Result<(), anyhow::Error> {
    if call_expr.args.len() != 2 {
        anyhow::bail!("Optional index operator _[?_] expects 2 arguments (container, index)");
    }
    // Compile container, then key; delegate all logic to the runtime
    compile_expr(&call_expr.args[0].expr, body, env, ctx, module)?;
    compile_expr(&call_expr.args[1].expr, body, env, ctx, module)?;
    body.call(env.get(RuntimeFunction::OptionalIndex));
    Ok(())
}

/// Compile the optional select operator: receiver?.field
///
/// Delegates to `cel_optional_select(receiver, field_name_ptr, field_name_len)` which
/// handles all cases: Optional(None), Optional(Some(map/object)), plain map, plain object.
///
/// AST: `func_name = "_?._"`, `args = [receiver, field_as_string_literal_or_ident]`
fn compile_opt_select(
    call_expr: &CallExpr,
    body: &mut InstrSeqBuilder,
    env: &CompilerEnv,
    ctx: &CompilerContext,
    module: &mut walrus::Module,
) -> Result<(), anyhow::Error> {
    use cel::common::ast::Expr as CelExpr;

    if call_expr.args.len() != 2 {
        anyhow::bail!("Optional select operator _?._ expects 2 arguments");
    }

    // args[1] holds the field name.
    // The cel-rust parser emits it as a Literal(String) for `a?.b` (the field is quoted),
    // but other transformations may produce an Ident. Accept both.
    let field_name = match &call_expr.args[1].expr {
        CelExpr::Ident(name) => name.clone(),
        CelExpr::Literal(cel::common::ast::LiteralValue::String(s)) => s.to_string(),
        _ => anyhow::bail!("Optional select _?._ second argument must be a field name identifier"),
    };

    // Save receiver to a local so we can push arguments in the right order.
    compile_expr(&call_expr.args[0].expr, body, env, ctx, module)?;
    let receiver_local = module.locals.add(ValType::I32);
    body.local_set(receiver_local);

    // Write field name into Wasm memory, leaving (ptr, len) on the stack.
    let memory_id = helpers::get_memory_id(module)?;
    let field_ptr_local = module.locals.add(ValType::I32);
    helpers::emit_string_const(&field_name, body, env, memory_id, module);
    // emit_string_const leaves (ptr: i32, len: i32) on stack; store ptr for the call.
    let field_len_local = module.locals.add(ValType::I32);
    body.local_set(field_len_local);
    body.local_set(field_ptr_local);

    // Call cel_optional_select(receiver, field_ptr, field_len) → *mut CelValue
    body.local_get(receiver_local);
    body.local_get(field_ptr_local);
    body.local_get(field_len_local);
    body.call(env.get(RuntimeFunction::OptionalSelect));

    Ok(())
}

/// Top-level operator dispatcher. Returns `true` if the func_name was recognized as
/// an operator, `false` otherwise (so the caller can fall through to named functions).
pub fn compile_operator(
    func_name: &str,
    call_expr: &CallExpr,
    body: &mut InstrSeqBuilder,
    env: &CompilerEnv,
    ctx: &CompilerContext,
    module: &mut walrus::Module,
) -> Result<bool, anyhow::Error> {
    match func_name {
        // Arithmetic operators
        operators::ADD => compile_binary_op(
            call_expr,
            "Add",
            RuntimeFunction::ValueAdd,
            body,
            env,
            ctx,
            module,
        )?,
        operators::SUBSTRACT => compile_binary_op(
            call_expr,
            "Subtract",
            RuntimeFunction::ValueSub,
            body,
            env,
            ctx,
            module,
        )?,
        operators::MULTIPLY => compile_binary_op(
            call_expr,
            "Multiply",
            RuntimeFunction::ValueMul,
            body,
            env,
            ctx,
            module,
        )?,
        operators::DIVIDE => compile_binary_op(
            call_expr,
            "Divide",
            RuntimeFunction::ValueDiv,
            body,
            env,
            ctx,
            module,
        )?,
        operators::MODULO => compile_binary_op(
            call_expr,
            "Modulo",
            RuntimeFunction::ValueMod,
            body,
            env,
            ctx,
            module,
        )?,
        operators::NEGATE => compile_unary_op(
            call_expr,
            "Negation",
            RuntimeFunction::ValueNegate,
            body,
            env,
            ctx,
            module,
        )?,

        // Comparison operators
        operators::EQUALS => compile_binary_op(
            call_expr,
            "Equals",
            RuntimeFunction::ValueEq,
            body,
            env,
            ctx,
            module,
        )?,
        operators::NOT_EQUALS => compile_binary_op(
            call_expr,
            "Not equals",
            RuntimeFunction::ValueNe,
            body,
            env,
            ctx,
            module,
        )?,
        operators::GREATER => compile_binary_op(
            call_expr,
            "Greater than",
            RuntimeFunction::ValueGt,
            body,
            env,
            ctx,
            module,
        )?,
        operators::LESS => compile_binary_op(
            call_expr,
            "Less than",
            RuntimeFunction::ValueLt,
            body,
            env,
            ctx,
            module,
        )?,
        operators::GREATER_EQUALS => compile_binary_op(
            call_expr,
            "Greater or equal",
            RuntimeFunction::ValueGte,
            body,
            env,
            ctx,
            module,
        )?,
        operators::LESS_EQUALS => compile_binary_op(
            call_expr,
            "Less or equal",
            RuntimeFunction::ValueLte,
            body,
            env,
            ctx,
            module,
        )?,

        // Membership operator
        operators::IN => compile_binary_op(
            call_expr,
            "'in'",
            RuntimeFunction::ValueIn,
            body,
            env,
            ctx,
            module,
        )?,

        // Logical operators
        operators::LOGICAL_AND => compile_logical_and(call_expr, body, env, ctx, module)?,
        operators::LOGICAL_OR => compile_logical_or(call_expr, body, env, ctx, module)?,
        operators::LOGICAL_NOT => compile_unary_op(
            call_expr,
            "Logical NOT",
            RuntimeFunction::BoolNot,
            body,
            env,
            ctx,
            module,
        )?,
        operators::NOT_STRICTLY_FALSE => compile_unary_op(
            call_expr,
            "@not_strictly_false",
            RuntimeFunction::NotStrictlyFalse,
            body,
            env,
            ctx,
            module,
        )?,

        // Conditional (ternary) operator
        operators::CONDITIONAL => compile_conditional(call_expr, body, env, ctx, module)?,

        // Index operator
        operators::INDEX => compile_index(call_expr, body, env, ctx, module)?,

        // Optional index operator: container[?key]
        operators::OPT_INDEX => compile_opt_index(call_expr, body, env, ctx, module)?,

        // Optional select operator: receiver?.field
        operators::OPT_SELECT => compile_opt_select(call_expr, body, env, ctx, module)?,

        // Not an operator
        _ => return Ok(false),
    }

    Ok(true)
}