rs-jsonnet 0.1.22

Pure Rust implementation of Jsonnet 0.21.0 compatible with Google Jsonnet
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//! Pure Jsonnet evaluator - no side effects, fully deterministic
//!
//! This module provides a pure functional implementation of Jsonnet evaluation.
//! All evaluation is deterministic: same input always produces same output.

use crate::ast::{Expr, StringPart};
use crate::error::{JsonnetError, Result};
use crate::lexer::Lexer;
use crate::parser::Parser;
use crate::value::{JsonnetBuiltin, JsonnetFunction, JsonnetValue};
use std::collections::HashMap;

/// Pure Jsonnet evaluator - performs only deterministic computations
#[derive(Debug, Clone)]
pub struct PureEvaluator {
    /// Top-level arguments (immutable configuration)
    tla_args: HashMap<String, String>,
    /// External variables (immutable configuration)
    ext_vars: HashMap<String, String>,
    /// Current evaluation context (variables in scope)
    context: EvaluationContext,
}

#[derive(Debug, Clone)]
struct EvaluationContext {
    /// Variables currently in scope
    variables: HashMap<String, JsonnetValue>,
}

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

impl PureEvaluator {
    /// Create a new pure evaluator with no external configuration
    pub fn new() -> Self {
        let mut context = EvaluationContext {
            variables: HashMap::new(),
        };

        // Initialize std object with builtin functions
        let mut std_obj = HashMap::new();
        std_obj.insert("length".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Length));
        std_obj.insert("toString".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::ToString));
        std_obj.insert("join".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Join));
        std_obj.insert("substr".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Substr));
        std_obj.insert("split".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Split));
        std_obj.insert("startsWith".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::StartsWith));
        std_obj.insert("endsWith".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::EndsWith));
        std_obj.insert("stringChars".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::StringChars));
        std_obj.insert("asciiLower".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::AsciiLower));
        std_obj.insert("asciiUpper".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::AsciiUpper));
        std_obj.insert("flatMap".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::FlatMap));
        std_obj.insert("mapWithIndex".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::MapWithIndex));
        std_obj.insert("lstripChars".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::LstripChars));
        std_obj.insert("rstripChars".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::RstripChars));
        std_obj.insert("stripChars".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::StripChars));
        std_obj.insert("findSubstr".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::FindSubstr));
        std_obj.insert("repeat".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Repeat));
        std_obj.insert("set".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Set));
        std_obj.insert("setMember".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::SetMember));
        std_obj.insert("setInter".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::SetInter));
        std_obj.insert("setUnion".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::SetUnion));
        std_obj.insert("setDiff".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::SetDiff));
        context.variables.insert("std".to_string(), JsonnetValue::Object(std_obj));

        Self {
            tla_args: HashMap::new(),
            ext_vars: HashMap::new(),
            context,
        }
    }

    /// Create a pure evaluator with top-level arguments
    pub fn with_tla_args(tla_args: HashMap<String, String>) -> Self {
        let mut context = EvaluationContext {
            variables: HashMap::new(),
        };

        // Initialize std object
        let mut std_obj = HashMap::new();
        std_obj.insert("length".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Length));
        std_obj.insert("toString".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::ToString));
        std_obj.insert("join".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Join));
        std_obj.insert("substr".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Substr));
        std_obj.insert("split".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Split));
        std_obj.insert("startsWith".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::StartsWith));
        std_obj.insert("endsWith".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::EndsWith));
        std_obj.insert("stringChars".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::StringChars));
        std_obj.insert("asciiLower".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::AsciiLower));
        std_obj.insert("asciiUpper".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::AsciiUpper));
        std_obj.insert("flatMap".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::FlatMap));
        std_obj.insert("mapWithIndex".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::MapWithIndex));
        std_obj.insert("lstripChars".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::LstripChars));
        std_obj.insert("rstripChars".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::RstripChars));
        std_obj.insert("stripChars".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::StripChars));
        std_obj.insert("findSubstr".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::FindSubstr));
        std_obj.insert("repeat".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Repeat));
        std_obj.insert("set".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Set));
        std_obj.insert("setMember".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::SetMember));
        std_obj.insert("setInter".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::SetInter));
        std_obj.insert("setUnion".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::SetUnion));
        std_obj.insert("setDiff".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::SetDiff));
        context.variables.insert("std".to_string(), JsonnetValue::Object(std_obj));

        // Add TLA variables to context
        for (key, value_str) in &tla_args {
            // Parse the TLA value as Jsonnet
            if let Ok(value) = Self::parse_and_eval_simple(value_str) {
                context.variables.insert(key.clone(), value);
            }
        }

        Self {
            tla_args,
            ext_vars: HashMap::new(),
            context,
        }
    }

    /// Create a pure evaluator with both TLA and external variables
    pub fn with_config(tla_args: HashMap<String, String>, ext_vars: HashMap<String, String>) -> Self {
        let mut context = EvaluationContext {
            variables: HashMap::new(),
        };

        // Initialize std object
        let mut std_obj = HashMap::new();
        std_obj.insert("length".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Length));
        std_obj.insert("toString".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::ToString));
        std_obj.insert("join".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Join));
        std_obj.insert("substr".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Substr));
        std_obj.insert("split".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Split));
        std_obj.insert("startsWith".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::StartsWith));
        std_obj.insert("endsWith".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::EndsWith));
        std_obj.insert("stringChars".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::StringChars));
        std_obj.insert("asciiLower".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::AsciiLower));
        std_obj.insert("asciiUpper".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::AsciiUpper));
        std_obj.insert("flatMap".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::FlatMap));
        std_obj.insert("mapWithIndex".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::MapWithIndex));
        std_obj.insert("lstripChars".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::LstripChars));
        std_obj.insert("rstripChars".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::RstripChars));
        std_obj.insert("stripChars".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::StripChars));
        std_obj.insert("findSubstr".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::FindSubstr));
        std_obj.insert("repeat".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Repeat));
        std_obj.insert("set".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::Set));
        std_obj.insert("setMember".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::SetMember));
        std_obj.insert("setInter".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::SetInter));
        std_obj.insert("setUnion".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::SetUnion));
        std_obj.insert("setDiff".to_string(), JsonnetValue::Builtin(JsonnetBuiltin::SetDiff));
        context.variables.insert("std".to_string(), JsonnetValue::Object(std_obj));

        // Add TLA variables to context
        for (key, value_str) in &tla_args {
            if let Ok(value) = Self::parse_and_eval_simple(value_str) {
                context.variables.insert(key.clone(), value);
            }
        }

        // Add external variables to context
        for (key, value_str) in &ext_vars {
            if let Ok(value) = Self::parse_and_eval_simple(value_str) {
                context.variables.insert(key.clone(), value);
            }
        }

        Self {
            tla_args,
            ext_vars,
            context,
        }
    }

    /// Simple helper to parse and evaluate a basic Jsonnet value
    fn parse_and_eval_simple(source: &str) -> Result<JsonnetValue> {
        let tokens = Lexer::new(source.to_string()).tokenize()?;
        let mut parser = Parser::new(tokens);
        let expr = parser.parse()?;
        let mut temp_eval = PureEvaluator::new();
        temp_eval.evaluate_expression(expr)
    }

    /// Pure evaluation of Jsonnet source code
    ///
    /// This function is PURE: it performs only deterministic computations
    /// and has no side effects. Same input always produces same output.
    pub fn evaluate(&mut self, source: &str) -> Result<JsonnetValue> {
        self.evaluate_with_context(source)
    }

    /// Pure evaluation with explicit context (no longer used, kept for compatibility)
    fn evaluate_with_context(&mut self, source: &str) -> Result<JsonnetValue> {
        // Parse the Jsonnet source using the real parser
        let tokens = Lexer::new(source.to_string()).tokenize()?;
        let mut parser = Parser::new(tokens);
        let parsed = parser.parse()?;

        // Evaluate the expression
        self.evaluate_expression(parsed)
    }


    /// Evaluate the parsed expression (simplified)
    fn evaluate_expression(&mut self, expr: Expr) -> Result<JsonnetValue> {
        match expr {
            Expr::String(s) => Ok(JsonnetValue::String(s)),
            Expr::Number(n) => Ok(JsonnetValue::Number(n)),
            Expr::Boolean(b) => Ok(JsonnetValue::Boolean(b)),
            Expr::Null => Ok(JsonnetValue::Null),
            Expr::Object(fields) => {
                let mut obj = std::collections::HashMap::new();
                for (key, value_expr) in fields {
                    let value = self.evaluate_expression(value_expr)?;
                    obj.insert(key, value);
                }
                Ok(JsonnetValue::Object(obj))
            }
            Expr::Array(elements) => {
                let mut arr = Vec::new();
                for element_expr in elements {
                    let element = self.evaluate_expression(element_expr)?;
                    arr.push(element);
                }
                Ok(JsonnetValue::Array(arr))
            }
            Expr::BinaryOp(op, left, right) => {
                let left_val = self.evaluate_expression(*left)?;
                let right_val = self.evaluate_expression(*right)?;
                self.evaluate_binary_op(op, left_val, right_val)
            }
            Expr::UnaryOp(op, expr) => {
                let val = self.evaluate_expression(*expr)?;
                self.evaluate_unary_op(op, val)
            }
            Expr::ArrayAccess(target, index) => {
                let target_val = self.evaluate_expression(*target)?;
                let index_val = self.evaluate_expression(*index)?;

                match (&target_val, &index_val) {
                    (JsonnetValue::Array(arr), JsonnetValue::Number(idx)) => {
                        let idx = *idx as i64;
                        if idx < 0 {
                            return Err(JsonnetError::runtime_error("Negative array index"));
                        }
                        let idx = idx as usize;
                        if idx >= arr.len() {
                            return Err(JsonnetError::index_out_of_bounds(idx as i64));
                        }
                        Ok(arr[idx].clone())
                    }
                    (JsonnetValue::Object(fields), JsonnetValue::String(field)) => {
                        match fields.get(field) {
                            Some(value) => Ok(value.clone()),
                            None => Err(JsonnetError::undefined_field(field)),
                        }
                    }
                    (JsonnetValue::Array(_), _) => Err(JsonnetError::type_error("Array index must be a number")),
                    (JsonnetValue::Object(_), _) => Err(JsonnetError::type_error("Object index must be a string")),
                    _ => Err(JsonnetError::type_error("Cannot index into this type")),
                }
            }
            Expr::FieldAccess(obj, field) => {
                let obj_val = self.evaluate_expression(*obj)?;

                match obj_val {
                    JsonnetValue::Object(fields) => {
                        match fields.get(&field) {
                            Some(value) => Ok(value.clone()),
                            None => Err(JsonnetError::undefined_field(&field)),
                        }
                    }
                    _ => Err(JsonnetError::type_error("Field access requires object")),
                }
            }
            Expr::Local(bindings, body) => {
                // Create a new scope for local variables
                let mut local_vars = self.context.variables.clone();

                // Evaluate and bind each local variable
                for (name, value_expr) in bindings {
                    let value = self.evaluate_expression(value_expr)?;
                    local_vars.insert(name, value);
                }

                // Evaluate body in the extended scope
                let old_context = std::mem::replace(&mut self.context.variables, local_vars);
                let result = self.evaluate_expression(*body);
                self.context.variables = old_context;

                result
            }
            Expr::Function(params, body) => {
                // Create a function value that captures the current environment
                let environment = self.context.variables.clone();
                Ok(JsonnetValue::Function(JsonnetFunction {
                    parameters: params.clone(),
                    body: body.clone(),
                    environment,
                }))
            }
            Expr::Conditional(condition, then_branch, else_branch) => {
                let cond_val = self.evaluate_expression(*condition)?;
                match cond_val {
                    JsonnetValue::Boolean(true) => self.evaluate_expression(*then_branch),
                    JsonnetValue::Boolean(false) => self.evaluate_expression(*else_branch),
                    _ => Err(JsonnetError::type_error("Condition must evaluate to boolean")),
                }
            }
            Expr::Call(func_expr, args) => {
                // Evaluate the function expression
                let func_val = self.evaluate_expression(*func_expr)?;

                match func_val {
                    JsonnetValue::Function(func) => {
                        // Evaluate arguments
                        let mut arg_vals = Vec::new();
                        for arg in args {
                            arg_vals.push(self.evaluate_expression(arg)?);
                        }

                        // Create new scope with function parameters
                        let mut func_scope = func.environment.clone();

                        // Bind parameters to arguments
                        if func.parameters.len() != arg_vals.len() {
                            return Err(JsonnetError::runtime_error(
                                format!("Expected {} arguments, got {}", func.parameters.len(), arg_vals.len())
                            ));
                        }

                        for (param, arg_val) in func.parameters.iter().zip(arg_vals) {
                            func_scope.insert(param.clone(), arg_val);
                        }

                        // Evaluate function body in the new scope
                        let old_context = std::mem::replace(&mut self.context.variables, func_scope);
                        let result = self.evaluate_expression(*func.body.clone());
                        self.context.variables = old_context;

                        result
                    }
                    JsonnetValue::Builtin(builtin) => {
                        // Handle builtin functions
                        let mut arg_vals = Vec::new();
                        for arg in args {
                            arg_vals.push(self.evaluate_expression(arg)?);
                        }
                        self.call_builtin_function(&builtin, arg_vals)
                    }
                    _ => Err(JsonnetError::type_error("Cannot call non-function value")),
                }
            }
            Expr::ArrayComprehension { expr, var_name, array_expr, condition } => {
                // Basic array comprehension implementation
                let array_val = self.evaluate_expression(*array_expr)?;
                let array = array_val.as_array()?;

                let mut result = Vec::new();

                for item in array {
                    // Bind the loop variable
                    let original_value = self.context.variables.insert(var_name.clone(), item.clone());

                    // Evaluate the expression
                    let expr_result = self.evaluate_expression((*expr).clone());

                    // Restore original value
                    if let Some(orig) = original_value {
                        self.context.variables.insert(var_name.clone(), orig);
                    } else {
                        self.context.variables.remove(&var_name);
                    }

                    match expr_result {
                        Ok(value) => {
                            // Check condition if present
                            let include = if let Some(ref cond_expr) = condition {
                                // Bind the loop variable for condition evaluation
                                let cond_result = self.evaluate_expression((**cond_expr).clone());
                                match cond_result {
                                    Ok(JsonnetValue::Boolean(true)) => true,
                                    Ok(JsonnetValue::Boolean(false)) => false,
                                    _ => false, // Condition must evaluate to boolean
                                }
                            } else {
                                true
                            };

                            if include {
                                result.push(value);
                            }
                        }
                        Err(e) => return Err(e),
                    }
                }

                Ok(JsonnetValue::Array(result))
            }
            Expr::StringInterpolation(parts) => {
                let mut result = String::new();
                for part in parts {
                    match part {
                        crate::ast::StringPart::Literal(text) => {
                            result.push_str(&text);
                        }
                        crate::ast::StringPart::Interpolation(expr) => {
                            let value = self.evaluate_expression(expr)?;
                            result.push_str(&self.value_to_string(&value));
                        }
                    }
                }
                Ok(JsonnetValue::String(result))
            }
            Expr::Identifier(name) => {
                // Look up variable in current context
                match self.context.variables.get(&name) {
                    Some(value) => Ok(value.clone()),
                    None => Err(JsonnetError::undefined_variable(&name)),
                }
            }
        }
    }

    /// Convert a JsonnetValue to its string representation
    fn value_to_string(&self, value: &JsonnetValue) -> String {
        match value {
            JsonnetValue::String(s) => s.clone(),
            JsonnetValue::Number(n) => n.to_string(),
            JsonnetValue::Boolean(b) => b.to_string(),
            JsonnetValue::Null => "null".to_string(),
            JsonnetValue::Array(_) => "[array]".to_string(), // TODO: proper array to string
            JsonnetValue::Object(_) => "{object}".to_string(), // TODO: proper object to string
            JsonnetValue::Function(_) => "[function]".to_string(),
            JsonnetValue::Builtin(_) => "[builtin]".to_string(),
        }
    }

    /// Call a builtin function
    fn call_builtin_function(&self, builtin: &JsonnetBuiltin, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        builtin.call(args)
    }

    fn evaluate_binary_op(&self, op: crate::ast::BinaryOp, left: JsonnetValue, right: JsonnetValue) -> Result<JsonnetValue> {
        use crate::ast::BinaryOp::*;
        match op {
            Add => {
                // String concatenation (Jsonnet allows concatenating anything with strings)
                if let JsonnetValue::String(l) = &left {
                    let right_str = self.value_to_string(&right);
                    return Ok(JsonnetValue::String(l.clone() + &right_str));
                }
                if let JsonnetValue::String(r) = &right {
                    let left_str = self.value_to_string(&left);
                    return Ok(JsonnetValue::String(left_str + r));
                }
                // Numeric addition
                match (&left, &right) {
                    (JsonnetValue::Number(l), JsonnetValue::Number(r)) => Ok(JsonnetValue::Number(l + r)),
                    _ => Err(JsonnetError::type_error("Invalid operands for +")),
                }
            },
            Sub => match (left, right) {
                (JsonnetValue::Number(l), JsonnetValue::Number(r)) => Ok(JsonnetValue::Number(l - r)),
                _ => Err(JsonnetError::type_error("Invalid operands for -")),
            },
            Mul => match (left, right) {
                (JsonnetValue::Number(l), JsonnetValue::Number(r)) => Ok(JsonnetValue::Number(l * r)),
                _ => Err(JsonnetError::type_error("Invalid operands for *")),
            },
            Div => match (left, right) {
                (JsonnetValue::Number(l), JsonnetValue::Number(r)) => {
                    if r == 0.0 {
                        Err(JsonnetError::DivisionByZero)
                    } else {
                        Ok(JsonnetValue::Number(l / r))
                    }
                }
                _ => Err(JsonnetError::type_error("Invalid operands for /")),
            },
            Mod => match (left, right) {
                (JsonnetValue::Number(l), JsonnetValue::Number(r)) => Ok(JsonnetValue::Number(l % r)),
                _ => Err(JsonnetError::type_error("Invalid operands for %")),
            },
            Eq => Ok(JsonnetValue::Boolean(left == right)),
            Ne => Ok(JsonnetValue::Boolean(left != right)),
            Lt => match (left, right) {
                (JsonnetValue::Number(l), JsonnetValue::Number(r)) => Ok(JsonnetValue::Boolean(l < r)),
                _ => Err(JsonnetError::type_error("Invalid operands for <")),
            },
            Le => match (left, right) {
                (JsonnetValue::Number(l), JsonnetValue::Number(r)) => Ok(JsonnetValue::Boolean(l <= r)),
                _ => Err(JsonnetError::type_error("Invalid operands for <=")),
            },
            Gt => match (left, right) {
                (JsonnetValue::Number(l), JsonnetValue::Number(r)) => Ok(JsonnetValue::Boolean(l > r)),
                _ => Err(JsonnetError::type_error("Invalid operands for >")),
            },
            Ge => match (left, right) {
                (JsonnetValue::Number(l), JsonnetValue::Number(r)) => Ok(JsonnetValue::Boolean(l >= r)),
                _ => Err(JsonnetError::type_error("Invalid operands for >=")),
            },
            And => match (left, right) {
                (JsonnetValue::Boolean(l), JsonnetValue::Boolean(r)) => Ok(JsonnetValue::Boolean(l && r)),
                _ => Err(JsonnetError::type_error("Invalid operands for &&")),
            },
            Or => match (left, right) {
                (JsonnetValue::Boolean(l), JsonnetValue::Boolean(r)) => Ok(JsonnetValue::Boolean(l || r)),
                _ => Err(JsonnetError::type_error("Invalid operands for ||")),
            },
        }
    }

    fn evaluate_unary_op(&self, op: crate::ast::UnaryOp, val: JsonnetValue) -> Result<JsonnetValue> {
        use crate::ast::UnaryOp::*;
        match op {
            Neg => match val {
                JsonnetValue::Number(n) => Ok(JsonnetValue::Number(-n)),
                _ => Err(JsonnetError::type_error("Invalid operand for unary -")),
            },
            Not => match val {
                JsonnetValue::Boolean(b) => Ok(JsonnetValue::Boolean(!b)),
                _ => Err(JsonnetError::type_error("Invalid operand for !")),
            },
            Plus => match val {
                JsonnetValue::Number(n) => Ok(JsonnetValue::Number(n)),
                _ => Err(JsonnetError::type_error("Invalid operand for unary +")),
            },
        }
    }
}



#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_pure_evaluation_is_deterministic() {
        let mut evaluator = PureEvaluator::new();
        let source = r#" "hello" + " world" "#;

        // Same input should always produce same output
        let result1 = evaluator.evaluate(source).unwrap();
        let result2 = evaluator.evaluate(source).unwrap();
        let result3 = evaluator.evaluate(source).unwrap();

        assert_eq!(result1, result2);
        assert_eq!(result2, result3);
    }

    #[test]
    fn test_pure_evaluation_with_tla() {
        let tla_args = HashMap::from([
            ("name".to_string(), r#""Alice""#.to_string()),
            ("age".to_string(), "30".to_string()),
        ]);

        let mut evaluator = PureEvaluator::with_tla_args(tla_args);
        let source = r#" "Hello, " + name + "!" "#;

        let result = evaluator.evaluate(source).unwrap();
        // In real implementation, this would evaluate to "Hello, Alice!"
        // For now, just check that evaluation succeeds
        assert!(matches!(result, JsonnetValue::String(_)));
    }

    #[test]
    fn test_pure_evaluator_clone() {
        let mut evaluator1 = PureEvaluator::new();
        let mut evaluator2 = evaluator1.clone();

        let source = r#" "test" "#;
        let result1 = evaluator1.evaluate(source).unwrap();
        let result2 = evaluator2.evaluate(source).unwrap();

        assert_eq!(result1, result2);
    }

    #[test]
    fn test_pure_evaluator_immutability() {
        // Pure Kernel: PureEvaluatorは不変、設定は作成時に固定
        let mut evaluator = PureEvaluator::new();

        // TLA引数付きの新しいevaluatorを作成
        let tla_args = HashMap::from([("greeting".to_string(), r#""Hello""#.to_string())]);
        let evaluator_with_tla = PureEvaluator::with_tla_args(tla_args.clone());

        // 元のevaluatorは変更されていない
        assert!(evaluator.tla_args.is_empty());
        assert!(evaluator.ext_vars.is_empty());

        // 新しいevaluatorにはTLA引数がある
        assert_eq!(evaluator_with_tla.tla_args.len(), 1);
        assert_eq!(evaluator_with_tla.tla_args.get("greeting").unwrap(), r#""Hello""#);

        // さらに外部変数を追加
        let ext_vars = HashMap::from([("env".to_string(), r#""production""#.to_string())]);
        let evaluator_with_both = PureEvaluator::with_config(tla_args, ext_vars);

        assert_eq!(evaluator_with_both.tla_args.len(), 1);
        assert_eq!(evaluator_with_both.ext_vars.len(), 1);
        assert_eq!(evaluator_with_both.ext_vars.get("env").unwrap(), r#""production""#);
    }

    #[test]
    fn test_pure_evaluator_deterministic_with_config() {
        // Pure Kernel: 設定が同じなら常に同じ結果
        let tla_args1 = HashMap::from([
            ("name".to_string(), r#""World""#.to_string()),
            ("count".to_string(), "42".to_string()),
        ]);

        let tla_args2 = HashMap::from([
            ("name".to_string(), r#""World""#.to_string()),
            ("count".to_string(), "42".to_string()),
        ]);

        let mut evaluator1 = PureEvaluator::with_tla_args(tla_args1);
        let mut evaluator2 = PureEvaluator::with_tla_args(tla_args2);

        let source = r#" "Result: " + name + " - " + count "#;

        let result1 = evaluator1.evaluate(source).unwrap();
        let result2 = evaluator2.evaluate(source).unwrap();

        assert_eq!(result1, result2);

        // 複数回の評価でも同じ結果
        for _ in 0..5 {
            let result_n = evaluator1.evaluate(source).unwrap();
            assert_eq!(result1, result_n);
        }
    }

    #[test]
    fn test_pure_evaluator_external_vars() {
        // Pure Kernel: 外部変数も決定論的
        let ext_vars = HashMap::from([
            ("version".to_string(), r#""1.0.0""#.to_string()),
            ("debug".to_string(), "false".to_string()),
        ]);

        let tla_args = HashMap::from([
            ("app".to_string(), r#""myapp""#.to_string()),
        ]);

        let mut evaluator = PureEvaluator::with_config(tla_args, ext_vars);
        let source = r#" "App: " + app + " v" + version + " debug=" + debug "#;

        // 同じ設定で作成したevaluatorは同じ結果を返す
        let mut evaluator2 = PureEvaluator::with_config(
            HashMap::from([("app".to_string(), r#""myapp""#.to_string())]),
            HashMap::from([
                ("version".to_string(), r#""1.0.0""#.to_string()),
                ("debug".to_string(), "false".to_string()),
            ])
        );

        let result1 = evaluator.evaluate(source).unwrap();
        let result2 = evaluator2.evaluate(source).unwrap();

        assert_eq!(result1, result2);
    }

    #[test]
    fn test_pure_evaluator_no_side_effects() {
        // Pure Kernel: 評価に副作用がないことを確認
        let mut evaluator = PureEvaluator::new();
        let source = r#" "side effect test" "#;

        // 評価前の状態を記録
        let tla_before = evaluator.tla_args.len();
        let ext_before = evaluator.ext_vars.len();

        // 評価実行
        let _result = evaluator.evaluate(source).unwrap();

        // 評価後も状態が変わっていない
        assert_eq!(evaluator.tla_args.len(), tla_before);
        assert_eq!(evaluator.ext_vars.len(), ext_before);

        // 複数回評価しても状態は変わらない
        for _ in 0..10 {
            let _result = evaluator.evaluate(source).unwrap();
            assert_eq!(evaluator.tla_args.len(), tla_before);
            assert_eq!(evaluator.ext_vars.len(), ext_before);
        }
    }
}