tsrun 0.1.23

A TypeScript interpreter designed for embedding in applications
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
//! Standard library implementations of platform traits.
//!
//! These implementations are only available when the `std` feature is enabled.

use super::{ConsoleLevel, ConsoleProvider, RandomProvider, TimeProvider};
use std::time::{Instant, SystemTime, UNIX_EPOCH};

#[cfg(feature = "regex")]
use super::{CompiledRegex, RegExpProvider, RegexMatch};
#[cfg(feature = "regex")]
use std::rc::Rc;

/// Time provider using std::time.
pub struct StdTimeProvider {
    /// Reference instant for timer calculations
    epoch: Instant,
}

impl StdTimeProvider {
    /// Create a new StdTimeProvider.
    pub fn new() -> Self {
        Self {
            epoch: Instant::now(),
        }
    }
}

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

impl TimeProvider for StdTimeProvider {
    fn now_millis(&self) -> i64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_millis() as i64)
            .unwrap_or(0)
    }

    fn elapsed_millis(&self, start: u64) -> u64 {
        let now = self.epoch.elapsed().as_millis() as u64;
        now.saturating_sub(start)
    }

    fn start_timer(&self) -> u64 {
        self.epoch.elapsed().as_millis() as u64
    }
}

/// Random provider using a simple xorshift64 PRNG.
///
/// This is a fast, decent-quality PRNG suitable for Math.random().
/// It's seeded from the current time on creation.
pub struct StdRandomProvider {
    state: u64,
}

impl StdRandomProvider {
    /// Create a new StdRandomProvider with time-based seed.
    pub fn new() -> Self {
        // Seed from current time
        let seed = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_nanos() as u64)
            .unwrap_or(0x12345678_9abcdef0);

        // Ensure non-zero seed
        let seed = if seed == 0 { 0x12345678_9abcdef0 } else { seed };

        Self { state: seed }
    }

    /// Create with a specific seed (for testing).
    #[allow(dead_code)]
    pub fn with_seed(seed: u64) -> Self {
        let seed = if seed == 0 { 1 } else { seed };
        Self { state: seed }
    }
}

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

impl RandomProvider for StdRandomProvider {
    fn random(&mut self) -> f64 {
        // xorshift64 algorithm
        let mut x = self.state;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.state = x;

        // Convert to f64 in [0, 1)
        // Use the upper 53 bits for better distribution
        let mantissa = x >> 11; // 53 bits
        (mantissa as f64) / ((1u64 << 53) as f64)
    }
}

/// Console provider using std print macros.
///
/// Writes to stdout for Log/Info/Debug and stderr for Warn/Error.
pub struct StdConsoleProvider;

impl StdConsoleProvider {
    /// Create a new StdConsoleProvider.
    pub fn new() -> Self {
        Self
    }
}

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

impl ConsoleProvider for StdConsoleProvider {
    fn write(&self, level: ConsoleLevel, message: &str) {
        match level {
            ConsoleLevel::Log | ConsoleLevel::Info | ConsoleLevel::Debug => {
                println!("{message}");
            }
            ConsoleLevel::Warn | ConsoleLevel::Error => {
                eprintln!("{message}");
            }
        }
    }

    fn clear(&self) {
        // Print some newlines as a visual separator
        println!("\n--- Console cleared ---\n");
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// FancyRegexProvider - RegExp implementation using fancy-regex crate
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(feature = "regex")]
mod regex_impl {
    use super::*;

    /// RegExp provider using the `fancy-regex` crate.
    ///
    /// This is the default provider for std builds with the `regex` feature enabled.
    /// It supports advanced regex features like lookahead, lookbehind, and backreferences.
    #[derive(Debug, Clone, Copy, Default)]
    pub struct FancyRegexProvider;

    impl FancyRegexProvider {
        /// Create a new FancyRegexProvider.
        pub fn new() -> Self {
            Self
        }
    }

    /// Compiled regex wrapping fancy_regex::Regex.
    #[derive(Debug)]
    pub struct FancyCompiledRegex {
        regex: fancy_regex::Regex,
        #[allow(dead_code)]
        flags: String,
    }

    impl CompiledRegex for FancyCompiledRegex {
        fn is_match(&self, input: &str) -> Result<bool, String> {
            self.regex.is_match(input).map_err(|e| e.to_string())
        }

        fn find(&self, input: &str, start_pos: usize) -> Result<Option<RegexMatch>, String> {
            let slice = input.get(start_pos..).unwrap_or("");
            match self.regex.captures(slice) {
                Ok(Some(caps)) => {
                    let full_match = caps.get(0).ok_or("No match found")?;
                    let captures: Vec<Option<(usize, usize)>> = caps
                        .iter()
                        .map(|m| m.map(|c| (start_pos + c.start(), start_pos + c.end())))
                        .collect();
                    Ok(Some(RegexMatch {
                        start: start_pos + full_match.start(),
                        end: start_pos + full_match.end(),
                        captures,
                    }))
                }
                Ok(None) => Ok(None),
                Err(e) => Err(e.to_string()),
            }
        }

        fn find_iter(&self, input: &str) -> Result<Vec<RegexMatch>, String> {
            let mut results = Vec::new();
            for caps_result in self.regex.captures_iter(input) {
                match caps_result {
                    Ok(caps) => {
                        let full_match = caps.get(0).ok_or("No match found")?;
                        let captures: Vec<Option<(usize, usize)>> = caps
                            .iter()
                            .map(|m| m.map(|c| (c.start(), c.end())))
                            .collect();
                        results.push(RegexMatch {
                            start: full_match.start(),
                            end: full_match.end(),
                            captures,
                        });
                    }
                    Err(e) => return Err(e.to_string()),
                }
            }
            Ok(results)
        }

        fn split(&self, input: &str) -> Result<Vec<String>, String> {
            let parts: Result<Vec<_>, _> = self
                .regex
                .split(input)
                .map(|r| r.map(|s| s.to_string()))
                .collect();
            parts.map_err(|e| e.to_string())
        }

        fn replace(&self, input: &str, replacement: &str) -> Result<String, String> {
            // fancy_regex doesn't support replacement patterns directly,
            // we need to handle $1, $2, etc. ourselves
            match self.regex.captures(input) {
                Ok(Some(caps)) => {
                    let full_match = caps.get(0).ok_or("No match found")?;
                    let replacement_str = expand_replacement(replacement, &caps);
                    let mut result = String::with_capacity(input.len());
                    result.push_str(input.get(..full_match.start()).unwrap_or(""));
                    result.push_str(&replacement_str);
                    result.push_str(input.get(full_match.end()..).unwrap_or(""));
                    Ok(result)
                }
                Ok(None) => Ok(input.to_string()),
                Err(e) => Err(e.to_string()),
            }
        }

        fn replace_all(&self, input: &str, replacement: &str) -> Result<String, String> {
            let mut result = String::with_capacity(input.len());
            let mut last_end = 0;

            for caps_result in self.regex.captures_iter(input) {
                match caps_result {
                    Ok(caps) => {
                        let full_match = caps.get(0).ok_or("No match found")?;
                        let replacement_str = expand_replacement(replacement, &caps);
                        result.push_str(input.get(last_end..full_match.start()).unwrap_or(""));
                        result.push_str(&replacement_str);
                        last_end = full_match.end();
                    }
                    Err(e) => return Err(e.to_string()),
                }
            }
            result.push_str(input.get(last_end..).unwrap_or(""));
            Ok(result)
        }
    }

    /// Expand replacement string with capture group references.
    ///
    /// Supports: $1-$99, $&, $$
    fn expand_replacement(replacement: &str, caps: &fancy_regex::Captures) -> String {
        let mut result = String::with_capacity(replacement.len());
        let chars: Vec<char> = replacement.chars().collect();
        let mut i = 0;

        while i < chars.len() {
            let Some(&c) = chars.get(i) else { break };
            let Some(&next) = chars.get(i + 1) else {
                result.push(c);
                i += 1;
                continue;
            };

            if c == '$' {
                if next == '$' {
                    // $$ -> literal $
                    result.push('$');
                    i += 2;
                } else if next == '&' {
                    // $& -> full match
                    if let Some(m) = caps.get(0) {
                        result.push_str(m.as_str());
                    }
                    i += 2;
                } else if next.is_ascii_digit() {
                    // $1-$99
                    let mut num_str = String::new();
                    let mut j = i + 1;
                    while let Some(&ch) = chars.get(j) {
                        if !ch.is_ascii_digit() || num_str.len() >= 2 {
                            break;
                        }
                        num_str.push(ch);
                        j += 1;
                    }
                    if let Ok(group_num) = num_str.parse::<usize>()
                        && let Some(m) = caps.get(group_num)
                    {
                        result.push_str(m.as_str());
                    }
                    // If group doesn't exist, replace with empty string
                    i = j;
                } else {
                    // Not a special sequence, keep the $
                    result.push('$');
                    i += 1;
                }
            } else {
                result.push(c);
                i += 1;
            }
        }
        result
    }

    impl RegExpProvider for FancyRegexProvider {
        fn compile(&self, pattern: &str, flags: &str) -> Result<Rc<dyn CompiledRegex>, String> {
            // Convert JS regex syntax to Rust regex syntax
            let mut regex_pattern = js_regex_to_rust(pattern);

            // Build flags prefix
            let mut prefix = String::new();

            if flags.contains('i') {
                prefix.push('i');
            }
            if flags.contains('m') {
                prefix.push('m');
            }
            if flags.contains('s') {
                prefix.push('s');
            }

            if !prefix.is_empty() {
                regex_pattern = format!("(?{}){}", prefix, regex_pattern);
            }

            let regex = fancy_regex::Regex::new(&regex_pattern)
                .map_err(|e| format!("Invalid regular expression: {}", e))?;

            Ok(Rc::new(FancyCompiledRegex {
                regex,
                flags: flags.to_string(),
            }))
        }
    }

    /// Convert a JavaScript regex pattern to a Rust regex pattern.
    ///
    /// Handles differences between JS and Rust regex syntax:
    /// - In JS, `[` inside a character class is a literal character
    /// - In Rust, `[` inside a character class needs to be escaped as `\[`
    fn js_regex_to_rust(pattern: &str) -> String {
        let mut result = String::with_capacity(pattern.len() + 16);
        let chars: Vec<char> = pattern.chars().collect();
        let len = chars.len();
        let mut i = 0;
        let mut in_char_class = false;
        let mut char_class_start = false; // True right after [ or [^

        while i < len {
            let Some(c) = chars.get(i).copied() else {
                break;
            };

            if c == '\\'
                && let Some(next) = chars.get(i + 1).copied()
            {
                // Escaped character - copy both chars and skip
                result.push(c);
                result.push(next);
                i += 2;
                char_class_start = false;
                continue;
            }

            if !in_char_class {
                if c == '[' {
                    in_char_class = true;
                    char_class_start = true;
                    result.push(c);
                } else {
                    result.push(c);
                }
            } else {
                // Inside character class
                if char_class_start {
                    // First char(s) after [ have special meaning
                    if c == '^' {
                        result.push(c);
                        // Still in char_class_start mode - next char could be ]
                    } else if c == ']' {
                        // ] right after [ or [^ is a literal ]
                        result.push(c);
                        char_class_start = false;
                    } else if c == '[' {
                        // [ at start of class - needs escaping for Rust
                        result.push('\\');
                        result.push('[');
                        char_class_start = false;
                    } else {
                        result.push(c);
                        char_class_start = false;
                    }
                } else if c == ']' {
                    // End of character class
                    in_char_class = false;
                    result.push(c);
                } else if c == '[' {
                    // Unescaped [ inside character class - escape it for Rust
                    result.push('\\');
                    result.push('[');
                } else {
                    result.push(c);
                }
            }
            i += 1;
        }

        result
    }
}

#[cfg(feature = "regex")]
pub use regex_impl::FancyRegexProvider;