stator_jse 0.1.1

Stator JavaScript engine core — parser, bytecode compiler, Maglev JIT, interpreter, GC
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
//! ECMAScript §20.5 `Error` built-in and error hierarchy.
//!
//! This module provides [`JsError`], the Rust representation of a JavaScript
//! `Error` object, together with constructor helpers for every error type in
//! the ECMAScript standard hierarchy and the V8-compatible
//! `Error.captureStackTrace` / `Error.stackTraceLimit` extension.
//!
//! # Error kinds
//!
//! | Kind | JS constructor |
//! |---|---|
//! | [`ErrorKind::Error`] | `Error` |
//! | [`ErrorKind::TypeError`] | `TypeError` |
//! | [`ErrorKind::RangeError`] | `RangeError` |
//! | [`ErrorKind::ReferenceError`] | `ReferenceError` |
//! | [`ErrorKind::SyntaxError`] | `SyntaxError` |
//! | [`ErrorKind::URIError`] | `URIError` |
//! | [`ErrorKind::EvalError`] | `EvalError` |
//! | [`ErrorKind::AggregateError`] | `AggregateError` |
//!
//! # Stack traces
//!
//! Each error records the JavaScript call stack at the point of construction,
//! capped at [`STACK_TRACE_LIMIT`] frames.  The interpreter pushes and pops
//! frame names into the thread-local [`CALL_STACK`] before and after every
//! function call, so the captured trace is always meaningful.
//!
//! # V8 extensions
//!
//! [`error_capture_stack_trace`] and [`STACK_TRACE_LIMIT`] replicate the V8
//! `Error.captureStackTrace` / `Error.stackTraceLimit` API.

use std::cell::{Cell, RefCell};

use crate::error::{StatorError, StatorResult};
use crate::objects::property_map::PropertyMap;
use crate::objects::value::JsValue;

// ─────────────────────────────────────────────────────────────────────────────
// Stack-trace limit
// ─────────────────────────────────────────────────────────────────────────────

/// Maximum number of stack frames captured in an error's `stack` property
/// (mirrors V8's `Error.stackTraceLimit` default of 10).
///
/// Modify at runtime via [`set_stack_trace_limit`] /
/// [`get_stack_trace_limit`].
static STACK_TRACE_LIMIT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(10);

/// Return the current `Error.stackTraceLimit` value.
pub fn get_stack_trace_limit() -> usize {
    STACK_TRACE_LIMIT.load(std::sync::atomic::Ordering::Relaxed)
}

/// Set a new `Error.stackTraceLimit` value.
pub fn set_stack_trace_limit(limit: usize) {
    STACK_TRACE_LIMIT.store(limit, std::sync::atomic::Ordering::Relaxed);
}

// ─────────────────────────────────────────────────────────────────────────────
// Thread-local call stack for stack-trace capture
// ─────────────────────────────────────────────────────────────────────────────

thread_local! {
    /// The JavaScript call stack, maintained by the interpreter.
    ///
    /// Only **named** frames (name ≠ `"<anonymous>"`) are pushed here;
    /// the vast majority of function calls use `"<anonymous>"` and are
    /// tracked via the lightweight [`CALL_DEPTH`] counter alone.
    /// [`capture_call_stack`] and [`capture_stack_trace`] reconstruct
    /// the full stack from both sources.
    static CALL_STACK: RefCell<Vec<(usize, &'static str)>> = const { RefCell::new(Vec::new()) };

    /// Depth counter for the JavaScript call stack.
    ///
    /// Incremented by `push_call_frame` and decremented by `pop_call_frame`.
    static CALL_DEPTH: Cell<usize> = const { Cell::new(0) };
}

/// Maximum JavaScript call-stack depth.
///
/// When the number of nested interpreter frames reaches this limit,
/// [`push_call_frame`] returns
/// `Err(StatorError::RangeError("Maximum call stack size exceeded"))`,
/// matching the behaviour of V8 and SpiderMonkey for infinite-recursion
/// programs.  Keeping this below the OS thread-stack size prevents a fatal
/// `stack overflow, aborting` abort that cannot be caught.
///
/// The interpreter uses `stacker::maybe_grow` to dynamically extend the
/// native stack via `mmap`/`VirtualAlloc` when headroom is low, so each
/// recursive `Interpreter::run` call is safe from a raw stack overflow.
/// A limit of 1024 is high enough for realistic JavaScript programs
/// (V8 and SpiderMonkey allow similar depths) while still catching
/// infinite-recursion bugs with a proper `RangeError` long before memory
/// is exhausted.
pub const MAX_CALL_STACK_DEPTH: usize = 128;

/// Push a frame name onto the thread-local call stack.
///
/// Returns `Err(StatorError::RangeError)` when the call stack would exceed
/// [`MAX_CALL_STACK_DEPTH`], so that the interpreter can surface a proper
/// JavaScript `RangeError` instead of aborting on a native stack overflow.
///
/// Call this immediately before entering a nested interpreter call.
pub fn push_call_frame(name: &'static str) -> StatorResult<()> {
    CALL_DEPTH.with(|d| {
        let depth = d.get();
        if depth >= MAX_CALL_STACK_DEPTH {
            return Err(StatorError::RangeError(
                "Maximum call stack size exceeded".to_string(),
            ));
        }
        d.set(depth + 1);
        // Only record named frames (skip the hot-path "<anonymous>" case).
        if name != "<anonymous>" {
            CALL_STACK.with(|cs| cs.borrow_mut().push((depth + 1, name)));
        }
        Ok(())
    })
}

/// Return the current depth of the thread-local call stack.
///
/// The depth is 0 at the top-level script, 1 inside the first function call,
/// and so on.  The debugger uses this to implement step-over and step-out:
/// step-over pauses when the depth returns to (or below) the depth at the
/// time the step was requested; step-out pauses when the depth drops *below*
/// the saved depth.
pub fn call_stack_depth() -> usize {
    CALL_DEPTH.with(Cell::get)
}

/// Pop the most recently pushed frame name from the thread-local call stack.
///
/// Call this immediately after returning from a nested interpreter call.
/// When `named` is `false` (the common anonymous-closure path), the
/// expensive `CALL_STACK` TLS access is skipped entirely.
pub fn pop_call_frame_ex(named: bool) {
    CALL_DEPTH.with(|d| {
        let cur = d.get();
        d.set(cur.saturating_sub(1));
        if named {
            CALL_STACK.with(|cs| {
                let mut stack = cs.borrow_mut();
                if stack.last().is_some_and(|&(depth, _)| depth == cur) {
                    stack.pop();
                }
            });
        }
    });
}

/// Execute a closure within a pushed anonymous call frame using a single
/// TLS access instead of the 3 separate accesses needed by
/// `push_call_frame` + `call_stack_depth` + `pop_call_frame_ex`.
///
/// The closure receives the new call depth so it can decide whether to
/// guard against native stack overflow (e.g. via `stacker::maybe_grow`).
///
/// On stack overflow (depth ≥ [`MAX_CALL_STACK_DEPTH`]) returns
/// `Err(RangeError)` without invoking the closure.
#[inline(always)]
pub fn with_anon_call_frame<R, F>(f: F) -> StatorResult<R>
where
    F: FnOnce(usize) -> StatorResult<R>,
{
    CALL_DEPTH.with(|d| {
        let depth = d.get();
        if depth >= MAX_CALL_STACK_DEPTH {
            return Err(StatorError::RangeError(
                "Maximum call stack size exceeded".to_string(),
            ));
        }
        d.set(depth + 1);
        let result = f(depth + 1);
        d.set(depth);
        result
    })
}

/// Pop the most recently pushed frame name from the thread-local call stack.
///
/// Call this immediately after returning from a nested interpreter call.
pub fn pop_call_frame() {
    pop_call_frame_ex(true);
}

/// Return a snapshot of the current JS call stack as a `Vec<String>`.
///
/// Each entry is a function-frame name (or `"<anonymous>"`).  The outermost
/// caller is at index 0; the most-recently-entered frame is last.
///
/// Used by the CPU profiler to record samples at safe points.
pub fn capture_call_stack() -> Vec<&'static str> {
    let depth = CALL_DEPTH.with(Cell::get);
    CALL_STACK.with(|cs| {
        let named = cs.borrow();
        let mut result = Vec::with_capacity(depth);
        let mut named_idx = 0;
        for d in 1..=depth {
            if named_idx < named.len() && named[named_idx].0 == d {
                result.push(named[named_idx].1);
                named_idx += 1;
            } else {
                result.push("<anonymous>");
            }
        }
        result
    })
}

/// Clear the thread-local call stack entirely.
///
/// This is used by the Test262 runner (and similar harnesses) to reset the
/// call-stack state between test cases.  A `catch_unwind`-caught panic inside
/// the interpreter may leave frames on the stack (because the panic bypasses
/// the normal `pop_call_frame` calls), which would cause every subsequent test
/// to fail immediately with "Maximum call stack size exceeded".  Calling this
/// function after each test guarantees a clean starting state.
pub fn clear_call_stack() {
    CALL_DEPTH.with(|d| d.set(0));
    CALL_STACK.with(|cs| cs.borrow_mut().clear());
}

/// Capture the current call stack as a formatted `stack` property string.
///
/// The returned string has the format:
/// ```text
/// ErrorName: message
///     at frame1
///     at frame2
////// ```
///
/// The number of frames is capped at [`get_stack_trace_limit`].
pub fn capture_stack_trace(error_name: &str, message: &str) -> String {
    let limit = get_stack_trace_limit();
    let mut result = format!("{error_name}: {message}");
    let stack = capture_call_stack();
    // Most-recent frame is at the end; iterate in reverse order.
    for frame in stack.iter().rev().take(limit) {
        result.push_str("\n    at ");
        result.push_str(frame);
    }
    result
}

/// V8 extension: `Error.captureStackTrace(targetObject, constructorOpt)`.
///
/// Attaches a formatted stack trace string to `target`'s `stack` field.  The
/// optional `constructor_name` argument is used to strip frames up to (and
/// including) the named constructor from the trace, but the current
/// implementation ignores it and always captures the full current stack.
///
/// # Example
///
/// ```
/// use stator_jse::builtins::error::{error_capture_stack_trace, JsError};
/// let mut err = JsError::new(stator_jse::builtins::error::ErrorKind::Error, "oops".to_string());
/// error_capture_stack_trace(&mut err, None);
/// assert!(err.stack().starts_with("Error: oops"));
/// ```
pub fn error_capture_stack_trace(target: &mut JsError, _constructor_name: Option<&str>) {
    let new_stack = capture_stack_trace(target.name(), &target.message);
    target.stack = new_stack;
}

// ─────────────────────────────────────────────────────────────────────────────
// ErrorKind
// ─────────────────────────────────────────────────────────────────────────────

/// The kind (class name) of a JavaScript `Error` object.
///
/// Each variant maps to one of the standard ECMAScript error constructors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorKind {
    /// Generic `Error`.
    Error,
    /// `TypeError` — a value is not of the expected type.
    TypeError,
    /// `RangeError` — a value is out of the allowed range.
    RangeError,
    /// `ReferenceError` — a variable that does not exist was accessed.
    ReferenceError,
    /// `SyntaxError` — the source text could not be parsed.
    SyntaxError,
    /// `URIError` — a URI handling function received a malformed URI.
    URIError,
    /// `EvalError` — an error related to the global `eval` function.
    EvalError,
    /// `AggregateError` — wraps multiple errors (e.g. from `Promise.any`).
    AggregateError,
}

impl ErrorKind {
    /// Return the ECMAScript `name` property string for this error kind.
    ///
    /// ```
    /// use stator_jse::builtins::error::ErrorKind;
    /// assert_eq!(ErrorKind::TypeError.as_name(), "TypeError");
    /// assert_eq!(ErrorKind::AggregateError.as_name(), "AggregateError");
    /// ```
    pub fn as_name(self) -> &'static str {
        match self {
            Self::Error => "Error",
            Self::TypeError => "TypeError",
            Self::RangeError => "RangeError",
            Self::ReferenceError => "ReferenceError",
            Self::SyntaxError => "SyntaxError",
            Self::URIError => "URIError",
            Self::EvalError => "EvalError",
            Self::AggregateError => "AggregateError",
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// JsError
// ─────────────────────────────────────────────────────────────────────────────

/// A JavaScript `Error` object.
///
/// Holds the error `kind` (which determines the `name` property), the
/// human-readable `message`, and the captured `stack` trace string.
///
/// For `AggregateError`, the inner `errors` field holds the list of
/// constituent errors.
///
/// # ECMAScript properties
///
/// | Property | Accessor |
/// |---|---|
/// | `name` | [`JsError::name`] |
/// | `message` | [`JsError::message`] |
/// | `stack` | [`JsError::stack`] |
/// | `cause` | [`JsError::cause`] (ES2022) |
/// | `errors` | [`JsError::errors`] (`AggregateError` only) |
#[derive(Debug, Clone, PartialEq)]
pub struct JsError {
    /// The kind of this error (determines the `name` property).
    pub kind: ErrorKind,
    /// The human-readable error description.
    pub message: String,
    /// The formatted stack trace string (captured at construction time).
    pub stack: String,
    /// Inner errors for `AggregateError` (empty for all other kinds).
    ///
    /// Per §20.5.7.1 the values are stored as-is from the iterable argument,
    /// so arbitrary [`JsValue`]s are kept rather than wrapping in `JsError`.
    pub errors: Vec<JsValue>,
    /// The ES2022 `cause` property — the underlying reason for this error.
    ///
    /// Set when the constructor receives an options object with a `cause`
    /// property, e.g. `new Error("msg", { cause: originalError })`.
    pub cause: Option<JsValue>,
    /// User-set property overlay.
    ///
    /// Stores values written by JS code (e.g. `err.message = "new"`).
    /// [`proto_lookup`](crate::interpreter::Interpreter) checks this map
    /// first, falling back to the built-in fields above when a key is absent.
    pub props: RefCell<PropertyMap>,
}

impl JsError {
    /// Create a new `JsError` with the given kind and message.
    ///
    /// The `stack` property is populated by capturing the current thread-local
    /// call stack at the point of this call.
    ///
    /// # Examples
    ///
    /// ```
    /// use stator_jse::builtins::error::{JsError, ErrorKind};
    ///
    /// let e = JsError::new(ErrorKind::TypeError, "not a function".to_string());
    /// assert_eq!(e.name(), "TypeError");
    /// assert_eq!(e.message(), "not a function");
    /// assert!(e.stack().starts_with("TypeError: not a function"));
    /// ```
    pub fn new(kind: ErrorKind, message: String) -> Self {
        let stack = capture_stack_trace(kind.as_name(), &message);
        Self {
            kind,
            message,
            stack,
            errors: Vec::new(),
            cause: None,
            props: RefCell::new(PropertyMap::new()),
        }
    }

    /// Create a new `AggregateError` wrapping `errors` with the given message.
    ///
    /// The `errors` values are stored as-is per §20.5.7.1 — they do not need
    /// to be `JsError` instances.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::rc::Rc;
    /// use stator_jse::builtins::error::{JsError, ErrorKind};
    /// use stator_jse::objects::value::JsValue;
    ///
    /// let e1 = JsValue::Error(Rc::new(JsError::new(ErrorKind::TypeError, "bad type".to_string())));
    /// let e2 = JsValue::Smi(42);
    /// let agg = JsError::new_aggregate(vec![e1, e2], "All promises rejected".to_string());
    /// assert_eq!(agg.name(), "AggregateError");
    /// assert_eq!(agg.errors.len(), 2);
    /// ```
    pub fn new_aggregate(errors: Vec<JsValue>, message: String) -> Self {
        let stack = capture_stack_trace("AggregateError", &message);
        Self {
            kind: ErrorKind::AggregateError,
            message,
            stack,
            errors,
            cause: None,
            props: RefCell::new(PropertyMap::new()),
        }
    }

    /// The ECMAScript `name` property — the error constructor name.
    pub fn name(&self) -> &str {
        self.kind.as_name()
    }

    /// The ECMAScript `message` property — the human-readable description.
    pub fn message(&self) -> &str {
        &self.message
    }

    /// The ECMAScript `stack` property — the formatted stack trace.
    pub fn stack(&self) -> &str {
        &self.stack
    }

    /// The ES2022 `cause` property — the underlying error cause, if any.
    ///
    /// Returns `None` when the error was constructed without a `cause` option.
    pub fn cause(&self) -> Option<&JsValue> {
        self.cause.as_ref()
    }

    /// Builder: set the `cause` property on this error.
    ///
    /// # Examples
    ///
    /// ```
    /// use stator_jse::builtins::error::{JsError, ErrorKind};
    /// use stator_jse::objects::value::JsValue;
    ///
    /// let inner = JsValue::String("disk full".to_string().into());
    /// let e = JsError::new(ErrorKind::Error, "write failed".to_string())
    ///     .with_cause(inner.clone());
    /// assert_eq!(e.cause(), Some(&inner));
    /// ```
    pub fn with_cause(mut self, cause: JsValue) -> Self {
        self.cause = Some(cause);
        self
    }

    /// ECMAScript §20.5.3.4 `Error.prototype.toString()`.
    ///
    /// Returns `"name: message"`, or just `"name"` when `message` is empty,
    /// or just `"message"` when `name` is empty.
    /// Respects user-set overrides in the property overlay.
    ///
    /// ```
    /// use stator_jse::builtins::error::{JsError, ErrorKind};
    ///
    /// let e = JsError::new(ErrorKind::RangeError, "index out of bounds".to_string());
    /// assert_eq!(e.to_error_string(), "RangeError: index out of bounds");
    ///
    /// let e2 = JsError::new(ErrorKind::Error, String::new());
    /// assert_eq!(e2.to_error_string(), "Error");
    /// ```
    pub fn to_error_string(&self) -> String {
        let props = self.props.borrow();
        let name = match props.get("name") {
            Some(JsValue::String(s)) => s.to_string(),
            Some(JsValue::Undefined) => "Error".to_string(),
            Some(v) => v.to_js_string().unwrap_or_else(|_| "Error".to_string()),
            _ => self.kind.as_name().to_string(),
        };
        let msg = match props.get("message") {
            Some(JsValue::String(s)) => s.to_string(),
            Some(JsValue::Undefined) => String::new(),
            Some(v) => v.to_js_string().unwrap_or_default(),
            _ => self.message.clone(),
        };
        drop(props);

        if name.is_empty() {
            return msg;
        }
        if msg.is_empty() {
            return name;
        }
        format!("{name}: {msg}")
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Convenience constructors
// ─────────────────────────────────────────────────────────────────────────────

/// Create a new `Error` object.
///
/// ```
/// use stator_jse::builtins::error::{error_new, ErrorKind};
/// let e = error_new("something went wrong".to_string());
/// assert_eq!(e.kind, ErrorKind::Error);
/// ```
pub fn error_new(message: String) -> JsError {
    JsError::new(ErrorKind::Error, message)
}

/// Create a new `TypeError` object.
///
/// ```
/// use stator_jse::builtins::error::{type_error_new, ErrorKind};
/// let e = type_error_new("not a function".to_string());
/// assert_eq!(e.kind, ErrorKind::TypeError);
/// ```
pub fn type_error_new(message: String) -> JsError {
    JsError::new(ErrorKind::TypeError, message)
}

/// Create a new `RangeError` object.
///
/// ```
/// use stator_jse::builtins::error::{range_error_new, ErrorKind};
/// let e = range_error_new("stack overflow".to_string());
/// assert_eq!(e.kind, ErrorKind::RangeError);
/// ```
pub fn range_error_new(message: String) -> JsError {
    JsError::new(ErrorKind::RangeError, message)
}

/// Create a new `ReferenceError` object.
///
/// ```
/// use stator_jse::builtins::error::{reference_error_new, ErrorKind};
/// let e = reference_error_new("x is not defined".to_string());
/// assert_eq!(e.kind, ErrorKind::ReferenceError);
/// ```
pub fn reference_error_new(message: String) -> JsError {
    JsError::new(ErrorKind::ReferenceError, message)
}

/// Create a new `SyntaxError` object.
///
/// ```
/// use stator_jse::builtins::error::{syntax_error_new, ErrorKind};
/// let e = syntax_error_new("unexpected token '}'".to_string());
/// assert_eq!(e.kind, ErrorKind::SyntaxError);
/// ```
pub fn syntax_error_new(message: String) -> JsError {
    JsError::new(ErrorKind::SyntaxError, message)
}

/// Create a new `URIError` object.
///
/// ```
/// use stator_jse::builtins::error::{uri_error_new, ErrorKind};
/// let e = uri_error_new("malformed URI sequence".to_string());
/// assert_eq!(e.kind, ErrorKind::URIError);
/// ```
pub fn uri_error_new(message: String) -> JsError {
    JsError::new(ErrorKind::URIError, message)
}

/// Create a new `EvalError` object.
///
/// ```
/// use stator_jse::builtins::error::{eval_error_new, ErrorKind};
/// let e = eval_error_new("eval is not supported".to_string());
/// assert_eq!(e.kind, ErrorKind::EvalError);
/// ```
pub fn eval_error_new(message: String) -> JsError {
    JsError::new(ErrorKind::EvalError, message)
}

/// Create a new `AggregateError` wrapping `errors` with the given message.
///
/// ```
/// use std::rc::Rc;
/// use stator_jse::builtins::error::{aggregate_error_new, type_error_new, ErrorKind};
/// use stator_jse::objects::value::JsValue;
/// let inner = JsValue::Error(Rc::new(type_error_new("bad type".to_string())));
/// let e = aggregate_error_new(vec![inner], "All promises rejected".to_string());
/// assert_eq!(e.kind, ErrorKind::AggregateError);
/// assert_eq!(e.errors.len(), 1);
/// ```
pub fn aggregate_error_new(errors: Vec<JsValue>, message: String) -> JsError {
    JsError::new_aggregate(errors, message)
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

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

    // ── ErrorKind ────────────────────────────────────────────────────────────

    #[test]
    fn test_error_kind_names() {
        assert_eq!(ErrorKind::Error.as_name(), "Error");
        assert_eq!(ErrorKind::TypeError.as_name(), "TypeError");
        assert_eq!(ErrorKind::RangeError.as_name(), "RangeError");
        assert_eq!(ErrorKind::ReferenceError.as_name(), "ReferenceError");
        assert_eq!(ErrorKind::SyntaxError.as_name(), "SyntaxError");
        assert_eq!(ErrorKind::URIError.as_name(), "URIError");
        assert_eq!(ErrorKind::EvalError.as_name(), "EvalError");
        assert_eq!(ErrorKind::AggregateError.as_name(), "AggregateError");
    }

    // ── JsError::new ─────────────────────────────────────────────────────────

    #[test]
    fn test_error_new_type_error() {
        let e = JsError::new(ErrorKind::TypeError, "not a function".to_string());
        assert_eq!(e.kind, ErrorKind::TypeError);
        assert_eq!(e.message(), "not a function");
        assert_eq!(e.name(), "TypeError");
        assert!(e.stack().starts_with("TypeError: not a function"));
        assert!(e.errors.is_empty());
    }

    #[test]
    fn test_error_new_range_error() {
        let e = range_error_new("index out of range".to_string());
        assert_eq!(e.kind, ErrorKind::RangeError);
        assert_eq!(e.to_error_string(), "RangeError: index out of range");
    }

    #[test]
    fn test_error_new_reference_error() {
        let e = reference_error_new("x is not defined".to_string());
        assert_eq!(e.name(), "ReferenceError");
        assert_eq!(e.message(), "x is not defined");
    }

    #[test]
    fn test_error_new_syntax_error() {
        let e = syntax_error_new("unexpected token".to_string());
        assert_eq!(e.name(), "SyntaxError");
        assert_eq!(e.to_error_string(), "SyntaxError: unexpected token");
    }

    #[test]
    fn test_error_new_uri_error() {
        let e = uri_error_new("malformed URI".to_string());
        assert_eq!(e.name(), "URIError");
    }

    #[test]
    fn test_error_new_eval_error() {
        let e = eval_error_new("eval is not supported".to_string());
        assert_eq!(e.name(), "EvalError");
    }

    #[test]
    fn test_error_empty_message() {
        let e = error_new(String::new());
        assert_eq!(e.to_error_string(), "Error");
        assert!(e.stack().starts_with("Error"));
    }

    // ── AggregateError ───────────────────────────────────────────────────────

    #[test]
    fn test_aggregate_error_new() {
        let e1 = JsValue::Error(Rc::new(type_error_new("bad type".to_string())));
        let e2 = JsValue::Error(Rc::new(range_error_new("out of range".to_string())));
        let agg = aggregate_error_new(
            vec![e1.clone(), e2.clone()],
            "multiple failures".to_string(),
        );
        assert_eq!(agg.kind, ErrorKind::AggregateError);
        assert_eq!(agg.message(), "multiple failures");
        assert_eq!(agg.name(), "AggregateError");
        assert_eq!(agg.errors.len(), 2);
        assert!(matches!(&agg.errors[0], JsValue::Error(e) if e.kind == ErrorKind::TypeError));
        assert!(matches!(&agg.errors[1], JsValue::Error(e) if e.kind == ErrorKind::RangeError));
    }

    // ── to_error_string ──────────────────────────────────────────────────────

    #[test]
    fn test_to_error_string_with_message() {
        let e = JsError::new(ErrorKind::Error, "something failed".to_string());
        assert_eq!(e.to_error_string(), "Error: something failed");
    }

    #[test]
    fn test_to_error_string_empty_message() {
        let e = JsError::new(ErrorKind::TypeError, String::new());
        assert_eq!(e.to_error_string(), "TypeError");
    }

    // ── property overlay (settable name/message) ─────────────────────────────

    #[test]
    fn test_to_error_string_overridden_message() {
        let e = JsError::new(ErrorKind::Error, "original".to_string());
        e.props
            .borrow_mut()
            .insert("message".to_string(), JsValue::String("overridden".into()));
        assert_eq!(e.to_error_string(), "Error: overridden");
    }

    #[test]
    fn test_to_error_string_overridden_name() {
        let e = JsError::new(ErrorKind::Error, "msg".to_string());
        e.props
            .borrow_mut()
            .insert("name".to_string(), JsValue::String("CustomError".into()));
        assert_eq!(e.to_error_string(), "CustomError: msg");
    }

    #[test]
    fn test_to_error_string_overridden_name_empty() {
        let e = JsError::new(ErrorKind::Error, "msg".to_string());
        e.props
            .borrow_mut()
            .insert("name".to_string(), JsValue::String(String::new().into()));
        assert_eq!(e.to_error_string(), "msg");
    }

    #[test]
    fn test_props_overlay_custom_property() {
        let e = JsError::new(ErrorKind::Error, "test".to_string());
        e.props
            .borrow_mut()
            .insert("code".to_string(), JsValue::Smi(42));
        assert_eq!(e.props.borrow().get("code"), Some(&JsValue::Smi(42)));
    }

    // ── stack traces ─────────────────────────────────────────────────────────

    #[test]
    fn test_stack_trace_no_frames() {
        // Outside any interpreter call — call stack is empty.
        let e = JsError::new(ErrorKind::Error, "test".to_string());
        assert_eq!(e.stack(), "Error: test");
    }

    #[test]
    fn test_stack_trace_with_frames() {
        push_call_frame("outer");
        push_call_frame("inner");
        let e = JsError::new(ErrorKind::TypeError, "oops".to_string());
        pop_call_frame();
        pop_call_frame();

        assert!(e.stack().starts_with("TypeError: oops"));
        assert!(e.stack().contains("inner"));
        assert!(e.stack().contains("outer"));
    }

    #[test]
    fn test_stack_trace_limit() {
        // Clear any residual frames from other parallel tests.
        clear_call_stack();
        let old_limit = get_stack_trace_limit();
        set_stack_trace_limit(2);

        push_call_frame("frameA");
        push_call_frame("frameB");
        push_call_frame("frameC");
        push_call_frame("frameD");
        let e = JsError::new(ErrorKind::Error, "limited".to_string());
        pop_call_frame();
        pop_call_frame();
        pop_call_frame();
        pop_call_frame();

        // Only the 2 most-recent frames should appear.
        let stack = e.stack();
        assert!(
            stack.contains("frameD"),
            "most recent frame 'frameD' missing: {stack}"
        );
        assert!(
            stack.contains("frameC"),
            "second frame 'frameC' missing: {stack}"
        );
        assert!(
            !stack.contains("frameB"),
            "frame 'frameB' should be truncated: {stack}"
        );
        assert!(
            !stack.contains("frameA"),
            "frame 'frameA' should be truncated: {stack}"
        );

        set_stack_trace_limit(old_limit);
    }

    // ── Error.captureStackTrace ──────────────────────────────────────────────

    #[test]
    fn test_capture_stack_trace() {
        push_call_frame("myFunction");
        let mut e = JsError::new(ErrorKind::Error, "captured".to_string());
        // Re-capture the stack trace on the existing error.
        error_capture_stack_trace(&mut e, None);
        pop_call_frame();

        assert!(e.stack().starts_with("Error: captured"));
        assert!(e.stack().contains("myFunction"));
    }

    // ── stack_trace_limit getter/setter ──────────────────────────────────────

    #[test]
    fn test_stack_trace_limit_getter_setter() {
        let original = get_stack_trace_limit();
        set_stack_trace_limit(5);
        assert_eq!(get_stack_trace_limit(), 5);
        set_stack_trace_limit(original);
    }

    // ── call-depth guard ─────────────────────────────────────────────────────

    #[test]
    fn test_push_call_frame_exceeds_limit_returns_range_error() {
        // Push MAX_CALL_STACK_DEPTH frames, then verify the next push fails.
        for _ in 0..MAX_CALL_STACK_DEPTH {
            push_call_frame("<test>").expect("should not fail below the limit");
        }
        let result = push_call_frame("<test>");
        // Clean up: pop all the frames we pushed.
        for _ in 0..MAX_CALL_STACK_DEPTH {
            pop_call_frame();
        }
        assert!(
            matches!(result, Err(crate::error::StatorError::RangeError(_))),
            "expected RangeError when call stack is full, got {result:?}"
        );
    }

    // ── cause property (ES2022) ──────────────────────────────────────────────

    #[test]
    fn test_error_cause_none_by_default() {
        let e = JsError::new(ErrorKind::Error, "no cause".to_string());
        assert!(e.cause().is_none());
    }

    #[test]
    fn test_error_with_cause() {
        let cause = JsValue::String("disk full".to_string().into());
        let e =
            JsError::new(ErrorKind::Error, "write failed".to_string()).with_cause(cause.clone());
        assert_eq!(e.cause(), Some(&cause));
    }

    #[test]
    fn test_error_cause_can_be_error_value() {
        let inner = JsValue::Error(Rc::new(type_error_new("bad type".to_string())));
        let outer = JsError::new(ErrorKind::Error, "wrapper".to_string()).with_cause(inner.clone());
        assert_eq!(outer.cause(), Some(&inner));
    }

    #[test]
    fn test_aggregate_error_cause_none_by_default() {
        let agg = aggregate_error_new(vec![], "agg".to_string());
        assert!(agg.cause().is_none());
    }

    #[test]
    fn test_aggregate_error_with_cause() {
        let cause = JsValue::Smi(42);
        let mut agg = aggregate_error_new(vec![], "agg".to_string());
        agg.cause = Some(cause.clone());
        assert_eq!(agg.cause(), Some(&cause));
    }

    // ── name/message inheritance ─────────────────────────────────────────────

    #[test]
    fn test_all_error_kinds_have_correct_names() {
        let kinds = [
            (ErrorKind::Error, "Error"),
            (ErrorKind::TypeError, "TypeError"),
            (ErrorKind::RangeError, "RangeError"),
            (ErrorKind::ReferenceError, "ReferenceError"),
            (ErrorKind::SyntaxError, "SyntaxError"),
            (ErrorKind::URIError, "URIError"),
            (ErrorKind::EvalError, "EvalError"),
            (ErrorKind::AggregateError, "AggregateError"),
        ];
        for (kind, expected_name) in kinds {
            let e = JsError::new(kind, "test".to_string());
            assert_eq!(e.name(), expected_name, "wrong name for {kind:?}");
            assert_eq!(e.message(), "test");
            assert!(
                e.stack().starts_with(&format!("{expected_name}: test")),
                "stack should start with error string for {kind:?}"
            );
        }
    }
}