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
434
435
436
437
438
439
440
441
442
443
444
445
//! Error constructor built-in methods

use crate::error::JsError;
use crate::gc::{Gc, Guard};
use crate::interpreter::Interpreter;
use crate::prelude::{String, ToString, format};
use crate::value::{Guarded, JsObject, JsString, JsValue, PropertyKey};

/// Initialize Error and all derived error constructors and add them to globals
pub fn init_error(interp: &mut Interpreter) {
    // Use the pre-created error prototypes from the Interpreter
    let error_proto = interp.error_prototype.clone();
    let type_error_proto = interp.type_error_prototype.clone();
    let reference_error_proto = interp.reference_error_prototype.clone();
    let range_error_proto = interp.range_error_prototype.clone();
    let syntax_error_proto = interp.syntax_error_prototype.clone();

    // Pre-intern all property keys
    let name_key = PropertyKey::String(interp.intern("name"));
    let message_key = PropertyKey::String(interp.intern("message"));
    let proto_key = PropertyKey::String(interp.intern("prototype"));
    let constructor_key = PropertyKey::String(interp.intern("constructor"));
    let error_key = PropertyKey::String(interp.intern("Error"));
    let type_error_key = PropertyKey::String(interp.intern("TypeError"));
    let reference_error_key = PropertyKey::String(interp.intern("ReferenceError"));
    let range_error_key = PropertyKey::String(interp.intern("RangeError"));
    let syntax_error_key = PropertyKey::String(interp.intern("SyntaxError"));
    let uri_error_key = PropertyKey::String(interp.intern("URIError"));
    let eval_error_key = PropertyKey::String(interp.intern("EvalError"));
    {
        let mut p = error_proto.borrow_mut();
        p.set_property(name_key.clone(), JsValue::String(JsString::from("Error")));
        p.set_property(message_key.clone(), JsValue::String(JsString::from("")));
    }

    // Add toString method to Error.prototype
    interp.register_method(&error_proto, "toString", error_to_string, 0);

    // Create Error constructor function
    let error_fn = interp.create_native_function("Error", error_constructor, 1);
    interp.root_guard.guard(error_fn.clone());

    // Set up prototype chain
    error_fn
        .borrow_mut()
        .set_property(proto_key.clone(), JsValue::Object(error_proto.clone()));

    // Set constructor property on Error.prototype
    error_proto
        .borrow_mut()
        .set_property(constructor_key.clone(), JsValue::Object(error_fn.clone()));

    // Register Error globally
    interp
        .global
        .borrow_mut()
        .set_property(error_key, JsValue::Object(error_fn));

    // Initialize derived error types using pre-created prototypes
    // TypeError
    {
        let mut p = type_error_proto.borrow_mut();
        p.set_property(
            name_key.clone(),
            JsValue::String(JsString::from("TypeError")),
        );
        p.set_property(message_key.clone(), JsValue::String(JsString::from("")));
    }
    let type_error_fn = interp.create_native_function("TypeError", type_error_constructor, 1);
    interp.root_guard.guard(type_error_fn.clone());
    type_error_fn
        .borrow_mut()
        .set_property(proto_key.clone(), JsValue::Object(type_error_proto.clone()));
    type_error_proto.borrow_mut().set_property(
        constructor_key.clone(),
        JsValue::Object(type_error_fn.clone()),
    );
    interp
        .global
        .borrow_mut()
        .set_property(type_error_key, JsValue::Object(type_error_fn));

    // ReferenceError
    {
        let mut p = reference_error_proto.borrow_mut();
        p.set_property(
            name_key.clone(),
            JsValue::String(JsString::from("ReferenceError")),
        );
        p.set_property(message_key.clone(), JsValue::String(JsString::from("")));
    }
    let reference_error_fn =
        interp.create_native_function("ReferenceError", reference_error_constructor, 1);
    interp.root_guard.guard(reference_error_fn.clone());
    reference_error_fn.borrow_mut().set_property(
        proto_key.clone(),
        JsValue::Object(reference_error_proto.clone()),
    );
    reference_error_proto.borrow_mut().set_property(
        constructor_key.clone(),
        JsValue::Object(reference_error_fn.clone()),
    );
    interp
        .global
        .borrow_mut()
        .set_property(reference_error_key, JsValue::Object(reference_error_fn));

    // RangeError
    {
        let mut p = range_error_proto.borrow_mut();
        p.set_property(
            name_key.clone(),
            JsValue::String(JsString::from("RangeError")),
        );
        p.set_property(message_key.clone(), JsValue::String(JsString::from("")));
    }
    let range_error_fn = interp.create_native_function("RangeError", range_error_constructor, 1);
    interp.root_guard.guard(range_error_fn.clone());
    range_error_fn.borrow_mut().set_property(
        proto_key.clone(),
        JsValue::Object(range_error_proto.clone()),
    );
    range_error_proto.borrow_mut().set_property(
        constructor_key.clone(),
        JsValue::Object(range_error_fn.clone()),
    );
    interp
        .global
        .borrow_mut()
        .set_property(range_error_key, JsValue::Object(range_error_fn));

    // SyntaxError
    {
        let mut p = syntax_error_proto.borrow_mut();
        p.set_property(
            name_key.clone(),
            JsValue::String(JsString::from("SyntaxError")),
        );
        p.set_property(message_key.clone(), JsValue::String(JsString::from("")));
    }
    let syntax_error_fn = interp.create_native_function("SyntaxError", syntax_error_constructor, 1);
    interp.root_guard.guard(syntax_error_fn.clone());
    syntax_error_fn.borrow_mut().set_property(
        proto_key.clone(),
        JsValue::Object(syntax_error_proto.clone()),
    );
    syntax_error_proto.borrow_mut().set_property(
        constructor_key.clone(),
        JsValue::Object(syntax_error_fn.clone()),
    );
    interp
        .global
        .borrow_mut()
        .set_property(syntax_error_key, JsValue::Object(syntax_error_fn));

    // URIError (uses error_prototype since we don't have a dedicated prototype)
    let uri_error_proto = interp.root_guard.alloc();
    uri_error_proto.borrow_mut().prototype = Some(interp.error_prototype.clone());
    {
        let mut p = uri_error_proto.borrow_mut();
        p.set_property(
            name_key.clone(),
            JsValue::String(JsString::from("URIError")),
        );
        p.set_property(message_key.clone(), JsValue::String(JsString::from("")));
    }
    let uri_error_fn = interp.create_native_function("URIError", uri_error_constructor, 1);
    interp.root_guard.guard(uri_error_fn.clone());
    uri_error_fn
        .borrow_mut()
        .set_property(proto_key.clone(), JsValue::Object(uri_error_proto.clone()));
    uri_error_proto.borrow_mut().set_property(
        constructor_key.clone(),
        JsValue::Object(uri_error_fn.clone()),
    );
    interp
        .global
        .borrow_mut()
        .set_property(uri_error_key, JsValue::Object(uri_error_fn));

    // EvalError (uses error_prototype since we don't have a dedicated prototype)
    let eval_error_proto = interp.root_guard.alloc();
    eval_error_proto.borrow_mut().prototype = Some(interp.error_prototype.clone());
    {
        let mut p = eval_error_proto.borrow_mut();
        p.set_property(name_key, JsValue::String(JsString::from("EvalError")));
        p.set_property(message_key, JsValue::String(JsString::from("")));
    }
    let eval_error_fn = interp.create_native_function("EvalError", eval_error_constructor, 1);
    interp.root_guard.guard(eval_error_fn.clone());
    eval_error_fn
        .borrow_mut()
        .set_property(proto_key, JsValue::Object(eval_error_proto.clone()));
    eval_error_proto
        .borrow_mut()
        .set_property(constructor_key, JsValue::Object(eval_error_fn.clone()));
    interp
        .global
        .borrow_mut()
        .set_property(eval_error_key, JsValue::Object(eval_error_fn));
}

/// Error.prototype.toString()
/// Returns "name: message" or just "name" if message is empty
pub fn error_to_string(
    interp: &mut Interpreter,
    this: JsValue,
    _args: &[JsValue],
) -> Result<Guarded, JsError> {
    let JsValue::Object(obj) = this else {
        return Ok(Guarded::unguarded(JsValue::String(JsString::from("Error"))));
    };

    // Pre-intern keys
    let name_key = interp.property_key("name");
    let message_key = interp.property_key("message");

    let obj_ref = obj.borrow();
    let name_val = obj_ref.get_property(&name_key);
    let message_val = obj_ref.get_property(&message_key);
    drop(obj_ref);

    // Get name, default to "Error"
    let name = match name_val {
        Some(v) => interp.to_js_string(&v).to_string(),
        None => "Error".to_string(),
    };

    // Get message, default to ""
    let message = match message_val {
        Some(v) => interp.to_js_string(&v).to_string(),
        None => String::new(),
    };

    if message.is_empty() {
        Ok(Guarded::unguarded(JsValue::String(JsString::from(name))))
    } else {
        Ok(Guarded::unguarded(JsValue::String(JsString::from(
            format!("{}: {}", name, message),
        ))))
    }
}

/// Initialize error properties on an existing object
fn initialize_error_on_this(
    interp: &mut Interpreter,
    obj: &Gc<JsObject>,
    name: &str,
    message: JsValue,
) {
    let msg_str = match &message {
        JsValue::Undefined => interp.intern(""),
        other => interp.to_js_string(other),
    };

    // Build a simple stack trace
    let stack = if msg_str.is_empty() {
        JsString::from(name)
    } else {
        JsString::from(format!("{}: {}", name, msg_str))
    };

    let name_key = interp.property_key("name");
    let message_key = interp.property_key("message");
    let stack_key = interp.property_key("stack");

    let mut obj_ref = obj.borrow_mut();
    obj_ref.set_property(name_key, JsValue::String(JsString::from(name)));
    obj_ref.set_property(message_key, JsValue::String(msg_str.clone()));
    obj_ref.set_property(stack_key, JsValue::String(stack));
}

/// Error constructor - sets name and message on `this`
pub fn error_constructor(
    interp: &mut Interpreter,
    this: JsValue,
    args: &[JsValue],
) -> Result<Guarded, JsError> {
    let message = args.first().cloned().unwrap_or(JsValue::Undefined);

    // When called via `new Error()`, this is the newly created object
    if let JsValue::Object(ref this_obj) = this {
        initialize_error_on_this(interp, this_obj, "Error", message);
    }

    // Return undefined - new handler will return the created object
    Ok(Guarded::unguarded(JsValue::Undefined))
}

/// TypeError constructor
pub fn type_error_constructor(
    interp: &mut Interpreter,
    this: JsValue,
    args: &[JsValue],
) -> Result<Guarded, JsError> {
    let message = args.first().cloned().unwrap_or(JsValue::Undefined);
    if let JsValue::Object(ref this_obj) = this {
        initialize_error_on_this(interp, this_obj, "TypeError", message);
    }
    Ok(Guarded::unguarded(JsValue::Undefined))
}

/// RangeError constructor
pub fn range_error_constructor(
    interp: &mut Interpreter,
    this: JsValue,
    args: &[JsValue],
) -> Result<Guarded, JsError> {
    let message = args.first().cloned().unwrap_or(JsValue::Undefined);
    if let JsValue::Object(ref this_obj) = this {
        initialize_error_on_this(interp, this_obj, "RangeError", message);
    }
    Ok(Guarded::unguarded(JsValue::Undefined))
}

/// ReferenceError constructor
pub fn reference_error_constructor(
    interp: &mut Interpreter,
    this: JsValue,
    args: &[JsValue],
) -> Result<Guarded, JsError> {
    let message = args.first().cloned().unwrap_or(JsValue::Undefined);
    if let JsValue::Object(ref this_obj) = this {
        initialize_error_on_this(interp, this_obj, "ReferenceError", message);
    }
    Ok(Guarded::unguarded(JsValue::Undefined))
}

/// SyntaxError constructor
pub fn syntax_error_constructor(
    interp: &mut Interpreter,
    this: JsValue,
    args: &[JsValue],
) -> Result<Guarded, JsError> {
    let message = args.first().cloned().unwrap_or(JsValue::Undefined);
    if let JsValue::Object(ref this_obj) = this {
        initialize_error_on_this(interp, this_obj, "SyntaxError", message);
    }
    Ok(Guarded::unguarded(JsValue::Undefined))
}

/// URIError constructor
pub fn uri_error_constructor(
    interp: &mut Interpreter,
    this: JsValue,
    args: &[JsValue],
) -> Result<Guarded, JsError> {
    let message = args.first().cloned().unwrap_or(JsValue::Undefined);
    if let JsValue::Object(ref this_obj) = this {
        initialize_error_on_this(interp, this_obj, "URIError", message);
    }
    Ok(Guarded::unguarded(JsValue::Undefined))
}

/// EvalError constructor
pub fn eval_error_constructor(
    interp: &mut Interpreter,
    this: JsValue,
    args: &[JsValue],
) -> Result<Guarded, JsError> {
    let message = args.first().cloned().unwrap_or(JsValue::Undefined);
    if let JsValue::Object(ref this_obj) = this {
        initialize_error_on_this(interp, this_obj, "EvalError", message);
    }
    Ok(Guarded::unguarded(JsValue::Undefined))
}

/// Create an error object from a JsError
/// Returns the error object and a guard to keep it alive
pub fn create_error_object(
    interp: &mut Interpreter,
    error: &JsError,
) -> (JsValue, Option<Guard<JsObject>>) {
    let guard = interp.heap.create_guard();

    let (prototype, name, message) = match error {
        JsError::TypeError { message, .. } => (
            interp.type_error_prototype.clone(),
            "TypeError",
            message.clone(),
        ),
        JsError::ReferenceError { name } => (
            interp.reference_error_prototype.clone(),
            "ReferenceError",
            format!("{} is not defined", name),
        ),
        JsError::RangeError { message } => (
            interp.range_error_prototype.clone(),
            "RangeError",
            message.clone(),
        ),
        JsError::SyntaxError { message, location } => (
            interp.syntax_error_prototype.clone(),
            "SyntaxError",
            format!("{} at {}", message, location),
        ),
        JsError::RuntimeError { kind, message, .. } => {
            // Map to appropriate prototype based on kind
            let proto = match kind.as_str() {
                "TypeError" => interp.type_error_prototype.clone(),
                "ReferenceError" => interp.reference_error_prototype.clone(),
                "RangeError" => interp.range_error_prototype.clone(),
                "SyntaxError" => interp.syntax_error_prototype.clone(),
                _ => interp.error_prototype.clone(),
            };
            (proto, kind.as_str(), message.clone())
        }
        JsError::ModuleError { message } => {
            (interp.error_prototype.clone(), "Error", message.clone())
        }
        JsError::Internal(msg) => (interp.error_prototype.clone(), "Error", msg.clone()),
        // These should not reach here, but handle them anyway
        JsError::Thrown
        | JsError::ThrownValue { .. }
        | JsError::GeneratorYield { .. }
        | JsError::OptionalChainShortCircuit => {
            return (JsValue::Undefined, None);
        }
    };

    // Create the error object
    let error_obj = guard.alloc();
    error_obj.borrow_mut().prototype = Some(prototype);

    // Set name, message, and stack properties
    let msg_str = JsString::from(message.as_str());
    let stack_str = if msg_str.is_empty() {
        JsString::from(name)
    } else {
        JsString::from(format!("{}: {}", name, msg_str))
    };

    let name_key = interp.property_key("name");
    let message_key = interp.property_key("message");
    let stack_key = interp.property_key("stack");

    {
        let mut obj = error_obj.borrow_mut();
        obj.set_property(name_key, JsValue::String(JsString::from(name)));
        obj.set_property(message_key, JsValue::String(msg_str));
        obj.set_property(stack_key, JsValue::String(stack_str));
    }

    (JsValue::Object(error_obj), Some(guard))
}