just-engine 0.1.0

A ground-up ES6 JavaScript engine with tree-walking interpreter, bytecode VMs, and Cranelift JIT compiler
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
//! Statement execution.
//!
//! This module provides statement execution logic for the JavaScript interpreter.

use crate::parser::ast::{
    ClassData, ExpressionPatternType, FunctionBodyData, FunctionData, LiteralType, NumberLiteralType,
    PatternType, StatementType, DeclarationType, VariableDeclarationData, VariableDeclarationKind,
    BlockStatementData, ExpressionType, SwitchCaseData, CatchClauseData, ForIteratorData,
    VariableDeclarationOrPattern,
};
use crate::runner::ds::error::JErrorType;
use crate::runner::ds::value::JsValue;
use crate::runner::plugin::types::EvalContext;

use super::types::{Completion, CompletionType, EvalResult};
use super::expression::{evaluate_expression, to_boolean, create_function_object, evaluate_class};

/// Execute a statement and return its completion.
pub fn execute_statement(
    stmt: &StatementType,
    ctx: &mut EvalContext,
) -> EvalResult {
    match stmt {
        StatementType::EmptyStatement { .. } => {
            Ok(Completion::normal())
        }

        StatementType::ExpressionStatement { expression, .. } => {
            let value = evaluate_expression(expression, ctx)?;
            Ok(Completion::normal_with_value(value))
        }

        StatementType::BlockStatement(block) => {
            execute_block_statement(block, ctx)
        }

        StatementType::DeclarationStatement(decl) => {
            execute_declaration(decl, ctx)
        }

        StatementType::IfStatement { test, consequent, alternate, .. } => {
            execute_if_statement(test, consequent, alternate.as_ref().map(|a| a.as_ref()), ctx)
        }

        StatementType::WhileStatement { test, body, .. } => {
            execute_while_statement(test, body, ctx)
        }

        StatementType::DoWhileStatement { test, body, .. } => {
            execute_do_while_statement(body, test, ctx)
        }

        StatementType::ForStatement { init, test, update, body, .. } => {
            execute_for_statement(init.as_ref(), test.as_ref().map(|t| t.as_ref()), update.as_ref().map(|u| u.as_ref()), body, ctx)
        }

        StatementType::ForInStatement(data) => {
            execute_for_in_statement(data, ctx)
        }

        StatementType::ForOfStatement(data) => {
            execute_for_of_statement(data, ctx)
        }

        StatementType::SwitchStatement { discriminant, cases, .. } => {
            execute_switch_statement(discriminant, cases, ctx)
        }

        StatementType::BreakStatement { .. } => {
            Ok(Completion::break_completion(None))
        }

        StatementType::ContinueStatement { .. } => {
            Ok(Completion::continue_completion(None))
        }

        StatementType::ReturnStatement { argument, .. } => {
            let value = if let Some(arg) = argument {
                evaluate_expression(arg, ctx)?
            } else {
                JsValue::Undefined
            };
            Ok(Completion::return_value(value))
        }

        StatementType::ThrowStatement { argument, .. } => {
            let value = evaluate_expression(argument, ctx)?;
            Ok(Completion {
                completion_type: CompletionType::Throw,
                value: Some(value),
                target: None,
            })
        }

        StatementType::TryStatement { block, handler, finalizer, .. } => {
            execute_try_statement(block, handler.as_ref(), finalizer.as_ref(), ctx)
        }

        StatementType::DebuggerStatement { .. } => {
            Ok(Completion::normal())
        }

        StatementType::FunctionBody(body) => {
            // Execute each statement in the function body
            execute_function_body(body, ctx)
        }
    }
}

/// Execute a block statement.
fn execute_block_statement(
    block: &BlockStatementData,
    ctx: &mut EvalContext,
) -> EvalResult {
    // Create a new block scope for let/const bindings
    ctx.push_block_scope();

    let mut completion = Completion::normal();

    for stmt in block.body.iter() {
        completion = execute_statement(stmt, ctx)?;

        if completion.is_abrupt() {
            ctx.pop_block_scope();
            return Ok(completion);
        }
    }

    // Pop the block scope
    ctx.pop_block_scope();

    Ok(completion)
}

/// Execute a declaration.
fn execute_declaration(
    decl: &DeclarationType,
    ctx: &mut EvalContext,
) -> EvalResult {
    match decl {
        DeclarationType::VariableDeclaration(var_decl) => {
            execute_variable_declaration(var_decl, ctx)
        }

        DeclarationType::FunctionOrGeneratorDeclaration(func_data) => {
            execute_function_declaration(func_data, ctx)
        }

        DeclarationType::ClassDeclaration(class_data) => {
            execute_class_declaration(class_data, ctx)
        }
    }
}

/// Execute a variable declaration.
fn execute_variable_declaration(
    var_decl: &VariableDeclarationData,
    ctx: &mut EvalContext,
) -> EvalResult {
    let is_const = matches!(var_decl.kind, VariableDeclarationKind::Const);
    let is_var = matches!(var_decl.kind, VariableDeclarationKind::Var);

    for declarator in &var_decl.declarations {
        // Evaluate initializer first (before potentially creating the binding)
        let value = if let Some(init) = &declarator.init {
            evaluate_expression(init, ctx)?
        } else {
            // const must have an initializer (checked by parser), var/let default to undefined
            JsValue::Undefined
        };

        // Bind the pattern to the value
        bind_pattern(&declarator.id, value, ctx, is_const, is_var)?;
    }

    Ok(Completion::normal())
}

/// Bind a pattern to a value, creating bindings for all identifiers in the pattern.
fn bind_pattern(
    pattern: &PatternType,
    value: JsValue,
    ctx: &mut EvalContext,
    is_const: bool,
    is_var: bool,
) -> Result<(), JErrorType> {
    match pattern {
        PatternType::PatternWhichCanBeExpression(ExpressionPatternType::Identifier(id)) => {
            // Simple identifier binding
            let name = &id.name;
            if is_var {
                if ctx.has_var_binding(name) {
                    ctx.set_var_binding(name, value)?;
                } else {
                    ctx.create_var_binding(name)?;
                    ctx.initialize_var_binding(name, value)?;
                }
            } else {
                ctx.create_binding(name, is_const)?;
                ctx.initialize_binding(name, value)?;
            }
            Ok(())
        }

        PatternType::ObjectPattern { properties, .. } => {
            // Object destructuring: { x, y } = obj or { x: renamed } = obj
            for prop in properties {
                let prop_data = &prop.0;

                // Get the property key name
                let key_name = get_property_key_name(&prop_data.key)?;

                // Get the value from the object
                let prop_value = get_property_value(&value, &key_name)?;

                // Bind the value to the pattern
                // For shorthand like { x }, value is the same pattern as key
                // For renamed like { x: renamed }, value is the renamed pattern
                bind_pattern(&prop_data.value, prop_value, ctx, is_const, is_var)?;
            }
            Ok(())
        }

        PatternType::ArrayPattern { elements, .. } => {
            // Array destructuring: [a, b] = arr
            for (index, element) in elements.iter().enumerate() {
                if let Some(elem_pattern) = element {
                    // Check if it's a rest element
                    if let PatternType::RestElement { argument, .. } = elem_pattern.as_ref() {
                        // Rest element collects remaining elements into an array
                        let rest_value = get_rest_elements(&value, index)?;
                        bind_pattern(argument, rest_value, ctx, is_const, is_var)?;
                    } else {
                        // Regular element
                        let elem_value = get_array_element(&value, index)?;
                        bind_pattern(elem_pattern, elem_value, ctx, is_const, is_var)?;
                    }
                }
                // None means hole/skip - do nothing
            }
            Ok(())
        }

        PatternType::AssignmentPattern { left, right, .. } => {
            // Default value pattern: x = default or { x = default } = obj
            // Use default if value is undefined
            let actual_value = if matches!(value, JsValue::Undefined) {
                evaluate_expression(right, ctx)?
            } else {
                value
            };
            bind_pattern(left, actual_value, ctx, is_const, is_var)
        }

        PatternType::RestElement { argument, .. } => {
            // Rest element should be handled in array context
            // If we get here directly, just bind the value as-is
            bind_pattern(argument, value, ctx, is_const, is_var)
        }
    }
}

/// Get the property key name from an expression (for destructuring).
fn get_property_key_name(key_expr: &ExpressionType) -> Result<String, JErrorType> {
    match key_expr {
        ExpressionType::ExpressionWhichCanBePattern(ExpressionPatternType::Identifier(id)) => {
            Ok(id.name.clone())
        }
        ExpressionType::Literal(lit_data) => {
            match &lit_data.value {
                LiteralType::StringLiteral(s) => Ok(s.clone()),
                LiteralType::NumberLiteral(num) => {
                    match num {
                        NumberLiteralType::IntegerLiteral(n) => Ok(n.to_string()),
                        NumberLiteralType::FloatLiteral(n) => Ok(n.to_string()),
                    }
                }
                _ => Err(JErrorType::TypeError("Invalid property key in destructuring".to_string())),
            }
        }
        _ => Err(JErrorType::TypeError("Computed property keys not yet supported in destructuring".to_string())),
    }
}

/// Get a property value from an object (for destructuring).
fn get_property_value(obj: &JsValue, key: &str) -> Result<JsValue, JErrorType> {
    use crate::runner::ds::object_property::{PropertyDescriptor, PropertyKey};

    match obj {
        JsValue::Object(obj_ref) => {
            let borrowed = obj_ref.borrow();
            let base = borrowed.as_js_object().get_object_base();
            let prop_key = PropertyKey::Str(key.to_string());

            if let Some(PropertyDescriptor::Data(data)) = base.properties.get(&prop_key) {
                Ok(data.value.clone())
            } else {
                Ok(JsValue::Undefined)
            }
        }
        _ => Err(JErrorType::TypeError("Cannot destructure non-object".to_string())),
    }
}

/// Get an element from an array by index (for destructuring).
fn get_array_element(arr: &JsValue, index: usize) -> Result<JsValue, JErrorType> {
    use crate::runner::ds::object_property::{PropertyDescriptor, PropertyKey};

    match arr {
        JsValue::Object(obj_ref) => {
            let borrowed = obj_ref.borrow();
            let base = borrowed.as_js_object().get_object_base();
            let prop_key = PropertyKey::Str(index.to_string());

            if let Some(PropertyDescriptor::Data(data)) = base.properties.get(&prop_key) {
                Ok(data.value.clone())
            } else {
                Ok(JsValue::Undefined)
            }
        }
        _ => Err(JErrorType::TypeError("Cannot destructure non-array".to_string())),
    }
}

/// Get remaining elements from an array starting at index (for rest patterns).
fn get_rest_elements(arr: &JsValue, start_index: usize) -> Result<JsValue, JErrorType> {
    use crate::runner::ds::object::{JsObject, JsObjectType, ObjectType};
    use crate::runner::ds::object_property::{PropertyDescriptor, PropertyDescriptorData, PropertyKey};
    use crate::runner::ds::value::JsNumberType;
    use crate::runner::plugin::types::SimpleObject;
    use std::cell::RefCell;
    use std::rc::Rc;

    match arr {
        JsValue::Object(obj_ref) => {
            let borrowed = obj_ref.borrow();
            let base = borrowed.as_js_object().get_object_base();

            // Get original array length
            let length = if let Some(PropertyDescriptor::Data(data)) =
                base.properties.get(&PropertyKey::Str("length".to_string()))
            {
                match &data.value {
                    JsValue::Number(JsNumberType::Integer(n)) => *n as usize,
                    JsValue::Number(JsNumberType::Float(n)) => *n as usize,
                    _ => 0,
                }
            } else {
                0
            };

            // Create a new array with remaining elements
            let mut rest_obj = SimpleObject::new();
            let mut rest_index = 0;

            for i in start_index..length {
                let prop_key = PropertyKey::Str(i.to_string());
                if let Some(PropertyDescriptor::Data(data)) = base.properties.get(&prop_key) {
                    rest_obj.get_object_base_mut().properties.insert(
                        PropertyKey::Str(rest_index.to_string()),
                        PropertyDescriptor::Data(PropertyDescriptorData {
                            value: data.value.clone(),
                            writable: true,
                            enumerable: true,
                            configurable: true,
                        }),
                    );
                    rest_index += 1;
                }
            }

            // Set length
            rest_obj.get_object_base_mut().properties.insert(
                PropertyKey::Str("length".to_string()),
                PropertyDescriptor::Data(PropertyDescriptorData {
                    value: JsValue::Number(JsNumberType::Integer(rest_index as i64)),
                    writable: true,
                    enumerable: false,
                    configurable: false,
                }),
            );

            let obj: JsObjectType = Rc::new(RefCell::new(ObjectType::Ordinary(Box::new(rest_obj))));
            Ok(JsValue::Object(obj))
        }
        _ => Err(JErrorType::TypeError("Cannot use rest with non-array".to_string())),
    }
}

/// Execute a function declaration.
fn execute_function_declaration(
    func_data: &FunctionData,
    ctx: &mut EvalContext,
) -> EvalResult {
    // Get the function name (id is mandatory for declarations)
    let name = func_data.id.as_ref()
        .ok_or_else(|| JErrorType::TypeError("Function declaration must have a name".to_string()))?
        .name.clone();

    // Create the function object
    let func_value = create_function_object(func_data, ctx)?;

    // Bind the function name in the variable environment (functions are hoisted like var)
    if ctx.has_var_binding(&name) {
        // Update existing binding
        ctx.set_var_binding(&name, func_value)?;
    } else {
        // Create and initialize new binding
        ctx.create_var_binding(&name)?;
        ctx.initialize_var_binding(&name, func_value)?;
    }

    Ok(Completion::normal())
}

/// Execute a class declaration.
fn execute_class_declaration(
    class_data: &ClassData,
    ctx: &mut EvalContext,
) -> EvalResult {
    // Get the class name (id is mandatory for declarations)
    let name = class_data.id.as_ref()
        .ok_or_else(|| JErrorType::TypeError("Class declaration must have a name".to_string()))?
        .name.clone();

    // Evaluate the class to get the constructor function
    let class_value = evaluate_class(class_data, ctx)?;

    // Bind the class name (classes are like let bindings - not hoisted to var scope)
    ctx.create_binding(&name, false)?;
    ctx.initialize_binding(&name, class_value)?;

    Ok(Completion::normal())
}

/// Get the binding name from a pattern.
fn get_binding_name(pattern: &PatternType) -> Result<String, JErrorType> {
    match pattern {
        PatternType::PatternWhichCanBeExpression(ExpressionPatternType::Identifier(id)) => {
            Ok(id.name.clone())
        }
        PatternType::ObjectPattern { .. } => {
            Err(JErrorType::TypeError("Object destructuring not yet supported".to_string()))
        }
        PatternType::ArrayPattern { .. } => {
            Err(JErrorType::TypeError("Array destructuring not yet supported".to_string()))
        }
        PatternType::RestElement { .. } => {
            Err(JErrorType::TypeError("Rest element not yet supported".to_string()))
        }
        PatternType::AssignmentPattern { .. } => {
            Err(JErrorType::TypeError("Default value patterns not yet supported".to_string()))
        }
    }
}

/// Execute an if statement.
fn execute_if_statement(
    test: &ExpressionType,
    consequent: &StatementType,
    alternate: Option<&StatementType>,
    ctx: &mut EvalContext,
) -> EvalResult {
    let test_value = evaluate_expression(test, ctx)?;

    if to_boolean(&test_value) {
        execute_statement(consequent, ctx)
    } else if let Some(alt) = alternate {
        execute_statement(alt, ctx)
    } else {
        Ok(Completion::normal())
    }
}

/// Execute a while statement.
fn execute_while_statement(
    test: &ExpressionType,
    body: &StatementType,
    ctx: &mut EvalContext,
) -> EvalResult {
    let mut completion = Completion::normal();

    loop {
        let test_value = evaluate_expression(test, ctx)?;

        if !to_boolean(&test_value) {
            break;
        }

        completion = execute_statement(body, ctx)?;

        match completion.completion_type {
            CompletionType::Break => {
                return Ok(Completion::normal_with_value(completion.get_value()));
            }
            CompletionType::Continue => {
                continue;
            }
            CompletionType::Return | CompletionType::Throw | CompletionType::Yield => {
                return Ok(completion);
            }
            CompletionType::Normal => {}
        }
    }

    Ok(completion)
}

/// Execute a do-while statement.
fn execute_do_while_statement(
    body: &StatementType,
    test: &ExpressionType,
    ctx: &mut EvalContext,
) -> EvalResult {
    loop {
        let completion = execute_statement(body, ctx)?;

        match completion.completion_type {
            CompletionType::Break => {
                return Ok(Completion::normal_with_value(completion.get_value()));
            }
            CompletionType::Continue => {}
            CompletionType::Return | CompletionType::Throw | CompletionType::Yield => {
                return Ok(completion);
            }
            CompletionType::Normal => {}
        }

        let test_value = evaluate_expression(test, ctx)?;
        if !to_boolean(&test_value) {
            break;
        }
    }

    Ok(Completion::normal())
}

/// Execute a for statement.
fn execute_for_statement(
    init: Option<&crate::parser::ast::VariableDeclarationOrExpression>,
    test: Option<&ExpressionType>,
    update: Option<&ExpressionType>,
    body: &StatementType,
    ctx: &mut EvalContext,
) -> EvalResult {
    use crate::parser::ast::VariableDeclarationOrExpression;

    if let Some(init) = init {
        match init {
            VariableDeclarationOrExpression::VariableDeclaration(decl) => {
                execute_variable_declaration(decl, ctx)?;
            }
            VariableDeclarationOrExpression::Expression(expr) => {
                evaluate_expression(expr, ctx)?;
            }
        }
    }

    let mut completion = Completion::normal();

    loop {
        if let Some(test) = test {
            let test_value = evaluate_expression(test, ctx)?;
            if !to_boolean(&test_value) {
                break;
            }
        }

        completion = execute_statement(body, ctx)?;

        match completion.completion_type {
            CompletionType::Break => {
                return Ok(Completion::normal_with_value(completion.get_value()));
            }
            CompletionType::Continue => {}
            CompletionType::Return | CompletionType::Throw | CompletionType::Yield => {
                return Ok(completion);
            }
            CompletionType::Normal => {}
        }

        if let Some(update) = update {
            evaluate_expression(update, ctx)?;
        }
    }

    Ok(completion)
}

/// Execute a function body.
fn execute_function_body(
    body: &FunctionBodyData,
    ctx: &mut EvalContext,
) -> EvalResult {
    let mut completion = Completion::normal();

    for stmt in body.body.iter() {
        completion = execute_statement(stmt, ctx)?;

        // Handle abrupt completions
        match completion.completion_type {
            CompletionType::Return | CompletionType::Throw | CompletionType::Yield => {
                return Ok(completion);
            }
            CompletionType::Break | CompletionType::Continue => {
                // Break/continue inside a function body without a loop is an error
                // but for now we just return the completion
                return Ok(completion);
            }
            CompletionType::Normal => {}
        }
    }

    Ok(completion)
}

/// Execute a switch statement.
fn execute_switch_statement(
    discriminant: &ExpressionType,
    cases: &[SwitchCaseData],
    ctx: &mut EvalContext,
) -> EvalResult {
    use super::expression::strict_equality;

    // Evaluate the discriminant
    let switch_value = evaluate_expression(discriminant, ctx)?;

    // Find the matching case (or default)
    let mut found_match = false;
    let mut default_index: Option<usize> = None;
    let mut start_index: Option<usize> = None;

    // First pass: find the matching case
    for (i, case) in cases.iter().enumerate() {
        if let Some(test) = &case.test {
            // This is a case clause
            let case_value = evaluate_expression(test, ctx)?;
            if strict_equality(&switch_value, &case_value) {
                start_index = Some(i);
                found_match = true;
                break;
            }
        } else {
            // This is the default clause
            default_index = Some(i);
        }
    }

    // If no match found, use default if available
    if !found_match {
        start_index = default_index;
    }

    // Execute statements starting from the matched case (fall-through behavior)
    let mut completion = Completion::normal();

    if let Some(start) = start_index {
        for case in cases.iter().skip(start) {
            for stmt in &case.consequent {
                completion = execute_statement(stmt, ctx)?;

                match completion.completion_type {
                    CompletionType::Break => {
                        // Break exits the switch
                        return Ok(Completion::normal_with_value(completion.get_value()));
                    }
                    CompletionType::Return | CompletionType::Throw | CompletionType::Continue | CompletionType::Yield => {
                        // These propagate up
                        return Ok(completion);
                    }
                    CompletionType::Normal => {}
                }
            }
        }
    }

    Ok(completion)
}

/// Execute a try statement.
fn execute_try_statement(
    block: &BlockStatementData,
    handler: Option<&CatchClauseData>,
    finalizer: Option<&BlockStatementData>,
    ctx: &mut EvalContext,
) -> EvalResult {
    // Execute the try block
    let try_result = execute_block_statement(block, ctx);

    let mut completion = match try_result {
        Ok(comp) => {
            // Check if it's a throw completion
            if comp.completion_type == CompletionType::Throw {
                // Handle the throw in catch if available
                if let Some(catch_clause) = handler {
                    handle_catch(comp, catch_clause, ctx)?
                } else {
                    comp
                }
            } else {
                comp
            }
        }
        Err(err) => {
            // Runtime error - treat as throw
            if let Some(catch_clause) = handler {
                let throw_completion = Completion {
                    completion_type: CompletionType::Throw,
                    value: Some(error_to_js_value(&err)),
                    target: None,
                };
                handle_catch(throw_completion, catch_clause, ctx)?
            } else {
                return Err(err);
            }
        }
    };

    // Execute the finally block if present
    if let Some(finally_block) = finalizer {
        let finally_result = execute_block_statement(finally_block, ctx)?;

        // If finally has an abrupt completion, it overrides the try/catch result
        if finally_result.is_abrupt() {
            completion = finally_result;
        }
    }

    Ok(completion)
}

/// Handle a catch clause.
fn handle_catch(
    thrown: Completion,
    catch_clause: &CatchClauseData,
    ctx: &mut EvalContext,
) -> EvalResult {
    // Create a new block scope for the catch clause
    ctx.push_block_scope();

    // Bind the error to the catch parameter
    let param_name = get_binding_name(&catch_clause.param)?;
    let error_value = thrown.value.unwrap_or(JsValue::Undefined);

    ctx.create_binding(&param_name, false)?;
    ctx.initialize_binding(&param_name, error_value)?;

    // Execute the catch block
    let result = execute_block_statement(&catch_clause.body, ctx);

    // Pop the catch scope
    ctx.pop_block_scope();

    result
}

/// Convert a JErrorType to a JsValue for catching.
fn error_to_js_value(err: &JErrorType) -> JsValue {
    match err {
        JErrorType::TypeError(msg) => JsValue::String(format!("TypeError: {}", msg)),
        JErrorType::ReferenceError(msg) => JsValue::String(format!("ReferenceError: {}", msg)),
        JErrorType::SyntaxError(msg) => JsValue::String(format!("SyntaxError: {}", msg)),
        JErrorType::RangeError(msg) => JsValue::String(format!("RangeError: {}", msg)),
        JErrorType::YieldValue(v) => v.clone(),
    }
}

/// Execute a for-in statement (iterate over enumerable property keys).
fn execute_for_in_statement(
    data: &ForIteratorData,
    ctx: &mut EvalContext,
) -> EvalResult {
    // Evaluate the right-hand side to get the object
    let obj_value = evaluate_expression(&data.right, ctx)?;

    // Get the property keys to iterate over
    let keys: Vec<String> = match &obj_value {
        JsValue::Object(obj) => {
            let obj_ref = obj.borrow();
            obj_ref.as_js_object().get_object_base().properties
                .keys()
                .filter_map(|k| match k {
                    crate::runner::ds::object_property::PropertyKey::Str(s) => Some(s.clone()),
                    _ => None,
                })
                .collect()
        }
        JsValue::String(s) => {
            // For strings, iterate over indices
            (0..s.len()).map(|i| i.to_string()).collect()
        }
        JsValue::Null | JsValue::Undefined => {
            // for-in over null/undefined produces no iterations
            return Ok(Completion::normal());
        }
        _ => Vec::new(),
    };

    // Execute the loop body for each key
    let mut completion = Completion::normal();

    for key in keys {
        // Bind the key to the loop variable
        bind_for_iterator_variable(&data.left, JsValue::String(key), ctx)?;

        // Execute the body
        completion = execute_statement(&data.body, ctx)?;

        match completion.completion_type {
            CompletionType::Break => {
                return Ok(Completion::normal_with_value(completion.get_value()));
            }
            CompletionType::Continue => {
                continue;
            }
            CompletionType::Return | CompletionType::Throw | CompletionType::Yield => {
                return Ok(completion);
            }
            CompletionType::Normal => {}
        }
    }

    Ok(completion)
}

/// Execute a for-of statement (iterate over iterable values).
fn execute_for_of_statement(
    data: &ForIteratorData,
    ctx: &mut EvalContext,
) -> EvalResult {
    use crate::runner::ds::value::JsNumberType;
    use crate::runner::ds::object_property::PropertyKey;

    // Evaluate the right-hand side to get the iterable
    let iterable_value = evaluate_expression(&data.right, ctx)?;

    // Get the values to iterate over
    let values: Vec<JsValue> = match &iterable_value {
        JsValue::Object(obj) => {
            let obj_ref = obj.borrow();
            let base = obj_ref.as_js_object().get_object_base();

            // Check for length property (array-like)
            if let Some(prop) = base.properties.get(&PropertyKey::Str("length".to_string())) {
                if let crate::runner::ds::object_property::PropertyDescriptor::Data(length_data) = prop {
                    if let JsValue::Number(JsNumberType::Integer(len)) = &length_data.value {
                        let len = *len as usize;
                        let mut vals = Vec::with_capacity(len);
                        for i in 0..len {
                            let key = PropertyKey::Str(i.to_string());
                            if let Some(prop) = base.properties.get(&key) {
                                if let crate::runner::ds::object_property::PropertyDescriptor::Data(d) = prop {
                                    vals.push(d.value.clone());
                                } else {
                                    vals.push(JsValue::Undefined);
                                }
                            } else {
                                vals.push(JsValue::Undefined);
                            }
                        }
                        drop(obj_ref);
                        return execute_for_of_with_values(data, vals, ctx);
                    }
                }
            }

            // Otherwise, iterate over enumerable properties' values
            base.properties
                .values()
                .filter_map(|prop| {
                    if let crate::runner::ds::object_property::PropertyDescriptor::Data(d) = prop {
                        if d.enumerable {
                            Some(d.value.clone())
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                })
                .collect()
        }
        JsValue::String(s) => {
            // Iterate over characters
            s.chars().map(|c| JsValue::String(c.to_string())).collect()
        }
        JsValue::Null | JsValue::Undefined => {
            return Err(JErrorType::TypeError(
                "Cannot iterate over null or undefined".to_string(),
            ));
        }
        _ => {
            return Err(JErrorType::TypeError(
                "Object is not iterable".to_string(),
            ));
        }
    };

    execute_for_of_with_values(data, values, ctx)
}

/// Helper to execute for-of with a list of values.
fn execute_for_of_with_values(
    data: &ForIteratorData,
    values: Vec<JsValue>,
    ctx: &mut EvalContext,
) -> EvalResult {
    let mut completion = Completion::normal();

    for value in values {
        // Bind the value to the loop variable
        bind_for_iterator_variable(&data.left, value, ctx)?;

        // Execute the body
        completion = execute_statement(&data.body, ctx)?;

        match completion.completion_type {
            CompletionType::Break => {
                return Ok(Completion::normal_with_value(completion.get_value()));
            }
            CompletionType::Continue => {
                continue;
            }
            CompletionType::Return | CompletionType::Throw | CompletionType::Yield => {
                return Ok(completion);
            }
            CompletionType::Normal => {}
        }
    }

    Ok(completion)
}

/// Bind a value to a for-in/for-of loop variable.
fn bind_for_iterator_variable(
    left: &VariableDeclarationOrPattern,
    value: JsValue,
    ctx: &mut EvalContext,
) -> Result<(), JErrorType> {
    match left {
        VariableDeclarationOrPattern::VariableDeclaration(var_decl) => {
            // Create and initialize the variable
            for declarator in &var_decl.declarations {
                let name = get_binding_name(&declarator.id)?;
                let is_var = matches!(var_decl.kind, VariableDeclarationKind::Var);

                if is_var {
                    // Check if already exists
                    if !ctx.has_binding(&name) {
                        ctx.create_var_binding(&name)?;
                    }
                    ctx.initialize_var_binding(&name, value.clone())?;
                } else {
                    // let/const - create new binding each iteration
                    if !ctx.has_binding(&name) {
                        ctx.create_binding(&name, matches!(var_decl.kind, VariableDeclarationKind::Const))?;
                        ctx.initialize_binding(&name, value.clone())?;
                    } else {
                        ctx.set_binding(&name, value.clone())?;
                    }
                }
            }
        }
        VariableDeclarationOrPattern::Pattern(pattern) => {
            // Simple pattern assignment
            let name = get_binding_name(pattern)?;
            ctx.set_binding(&name, value)?;
        }
    }
    Ok(())
}