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
extern crate just;

use just::parser::JsParser;
use just::runner::plugin::resolver::PluginResolver;
use just::runner::plugin::types::EvalContext;
use just::runner::plugin::registry::BuiltInRegistry;
use just::runner::ds::error::JErrorType;
use just::runner::ds::value::{JsValue, JsNumberType};
use just::runner::eval::statement::execute_statement;
use std::cell::RefCell;
use std::rc::Rc;

/// Helper to run code with the interpreter
fn run_interpreter(code: &str, ctx: &mut EvalContext) -> Result<JsValue, JErrorType> {
    let ast = JsParser::parse_to_ast_from_str(code)
        .map_err(|e| JErrorType::SyntaxError(format!("Parse error: {:?}", e)))?;
    let mut last_value = JsValue::Undefined;
    
    for stmt in &ast.body {
        let completion = execute_statement(stmt, ctx)?;
        if let Some(val) = completion.value {
            last_value = val;
        }
    }
    
    Ok(last_value)
}

/// Helper to get a variable from context
fn get_var(ctx: &mut EvalContext, name: &str) -> JsValue {
    ctx.get_binding(name).unwrap_or(JsValue::Undefined)
}

// ── Built-in method resolution tests ─────────────────────────────────

#[test]
fn test_interpreter_math_abs() {
    let mut ctx = EvalContext::new();
    ctx.install_core_builtins(BuiltInRegistry::with_core());
    
    let result = run_interpreter("Math.abs(-42)", &mut ctx).unwrap();
    assert_eq!(result, JsValue::Number(JsNumberType::Integer(42)));
}

#[test]
fn test_interpreter_math_max() {
    let mut ctx = EvalContext::new();
    ctx.install_core_builtins(BuiltInRegistry::with_core());
    
    let result = run_interpreter("Math.max(5, 10, 3)", &mut ctx).unwrap();
    assert_eq!(result, JsValue::Number(JsNumberType::Integer(10)));
}

#[test]
fn test_interpreter_math_floor() {
    let mut ctx = EvalContext::new();
    ctx.install_core_builtins(BuiltInRegistry::with_core());
    
    let result = run_interpreter("Math.floor(4.9)", &mut ctx).unwrap();
    assert_eq!(result, JsValue::Number(JsNumberType::Integer(4)));
}

#[test]
fn test_interpreter_console_log() {
    let mut ctx = EvalContext::new();
    ctx.install_core_builtins(BuiltInRegistry::with_core());
    
    // console.log returns undefined
    let result = run_interpreter("console.log('test message')", &mut ctx).unwrap();
    assert_eq!(result, JsValue::Undefined);
}

// Note: String primitive methods require additional infrastructure in the interpreter
// that's beyond super-global resolution. The VM handles these via type-based dispatch.

// ── Constructor tests ────────────────────────────────────────────────

#[test]
fn test_interpreter_string_constructor() {
    let mut ctx = EvalContext::new();
    ctx.install_core_builtins(BuiltInRegistry::with_core());
    
    let code = "var s = new String('hello world'); s";
    let result = run_interpreter(code, &mut ctx).unwrap();
    assert_eq!(result, JsValue::String("hello world".to_string()));
}

#[test]
fn test_interpreter_number_constructor() {
    let mut ctx = EvalContext::new();
    ctx.install_core_builtins(BuiltInRegistry::with_core());
    
    let code = "var n = new Number(42); n";
    let result = run_interpreter(code, &mut ctx).unwrap();
    assert_eq!(result, JsValue::Number(JsNumberType::Integer(42)));
}

#[test]
fn test_interpreter_number_constructor_float() {
    let mut ctx = EvalContext::new();
    ctx.install_core_builtins(BuiltInRegistry::with_core());
    
    let code = "var n = new Number(3.14); n";
    let result = run_interpreter(code, &mut ctx).unwrap();
    assert_eq!(result, JsValue::Number(JsNumberType::Float(3.14)));
}

#[test]
fn test_interpreter_string_constructor_empty() {
    let mut ctx = EvalContext::new();
    ctx.install_core_builtins(BuiltInRegistry::with_core());
    
    let code = "var s = new String(); s";
    let result = run_interpreter(code, &mut ctx).unwrap();
    assert_eq!(result, JsValue::String("".to_string()));
}

#[test]
fn test_interpreter_multiple_constructors() {
    let mut ctx = EvalContext::new();
    ctx.install_core_builtins(BuiltInRegistry::with_core());
    
    let code = r#"
        var s = new String("test");
        var n = new Number(100);
        var result = s;
        result
    "#;
    let result = run_interpreter(code, &mut ctx).unwrap();
    assert_eq!(result, JsValue::String("test".to_string()));
}

#[test]
fn test_interpreter_builtin_in_expression() {
    let mut ctx = EvalContext::new();
    ctx.install_core_builtins(BuiltInRegistry::with_core());
    
    let code = "var x = Math.abs(-10) + Math.abs(-5);";
    run_interpreter(code, &mut ctx).unwrap();
    
    let x = get_var(&mut ctx, "x");
    assert_eq!(x, JsValue::Number(JsNumberType::Integer(15)));
}

#[test]
fn test_interpreter_local_shadows_builtin() {
    let mut ctx = EvalContext::new();
    ctx.install_core_builtins(BuiltInRegistry::with_core());
    
    let code = r#"
        var Math = 99;
        var x = Math;
        x
    "#;
    
    let result = run_interpreter(code, &mut ctx).unwrap();
    assert_eq!(result, JsValue::Number(JsNumberType::Integer(99)));
}

// ── Custom plugin tests ──────────────────────────────────────────────

/// A test plugin that provides a "TestLib" object with methods
struct TestLibPlugin {
    console_output: Rc<RefCell<Vec<String>>>,
}

impl TestLibPlugin {
    fn new() -> Self {
        Self {
            console_output: Rc::new(RefCell::new(Vec::new())),
        }
    }
    
    fn get_output(&self) -> Vec<String> {
        self.console_output.borrow().clone()
    }
}

impl PluginResolver for TestLibPlugin {
    fn has_binding(&self, name: &str) -> bool {
        name == "TestLib" || name == "CustomObject"
    }
    
    fn resolve(&self, name: &str, _ctx: &mut EvalContext) -> Result<JsValue, JErrorType> {
        if name == "TestLib" || name == "CustomObject" {
            // Return a sentinel value to indicate the object exists
            Ok(JsValue::Number(JsNumberType::Integer(42)))
        } else {
            Err(JErrorType::ReferenceError(format!("{} is not defined", name)))
        }
    }
    
    fn call_method(
        &self,
        object_name: &str,
        method_name: &str,
        _ctx: &mut EvalContext,
        _this: JsValue,
        args: Vec<JsValue>,
    ) -> Option<Result<JsValue, JErrorType>> {
        if object_name != "TestLib" {
            return None;
        }
        
        match method_name {
            "double" => {
                let n = match args.first() {
                    Some(JsValue::Number(JsNumberType::Integer(n))) => *n,
                    Some(JsValue::Number(JsNumberType::Float(f))) => *f as i64,
                    _ => 0,
                };
                Some(Ok(JsValue::Number(JsNumberType::Integer(n * 2))))
            }
            "greet" => {
                let name = match args.first() {
                    Some(JsValue::String(s)) => s.clone(),
                    _ => "World".to_string(),
                };
                let message = format!("Hello, {}!", name);
                
                // Store the message
                self.console_output.borrow_mut().push(message.clone());
                
                // Also print to stdout for visibility
                println!("{}", message);
                
                Some(Ok(JsValue::String(message)))
            }
            "add" => {
                let a = match args.get(0) {
                    Some(JsValue::Number(JsNumberType::Integer(n))) => *n,
                    _ => 0,
                };
                let b = match args.get(1) {
                    Some(JsValue::Number(JsNumberType::Integer(n))) => *n,
                    _ => 0,
                };
                Some(Ok(JsValue::Number(JsNumberType::Integer(a + b))))
            }
            _ => None,
        }
    }
    
    fn call_constructor(
        &self,
        object_name: &str,
        _ctx: &mut EvalContext,
        args: Vec<JsValue>,
    ) -> Option<Result<JsValue, JErrorType>> {
        if object_name == "CustomObject" {
            // Create a custom object with a value property
            let value = match args.first() {
                Some(JsValue::Number(JsNumberType::Integer(n))) => *n,
                Some(JsValue::Number(JsNumberType::Float(f))) => *f as i64,
                _ => 0,
            };
            
            // For simplicity, return a number representing the constructed object
            // In a real implementation, this would return a proper object
            Some(Ok(JsValue::Number(JsNumberType::Integer(value * 10))))
        } else {
            None
        }
    }
    
    fn name(&self) -> &str {
        "test_lib_plugin"
    }
}

#[test]
fn test_custom_plugin_variable_access() {
    let mut ctx = EvalContext::new();
    ctx.add_resolver(Box::new(TestLibPlugin::new()));
    
    let code = "var x = TestLib;";
    run_interpreter(code, &mut ctx).unwrap();
    
    let x = get_var(&mut ctx, "x");
    assert_eq!(x, JsValue::Number(JsNumberType::Integer(42)));
}

#[test]
fn test_custom_plugin_method_double() {
    let mut ctx = EvalContext::new();
    ctx.add_resolver(Box::new(TestLibPlugin::new()));
    
    let code = "var result = TestLib.double(21);";
    run_interpreter(code, &mut ctx).unwrap();
    
    let result = get_var(&mut ctx, "result");
    assert_eq!(result, JsValue::Number(JsNumberType::Integer(42)));
}

#[test]
fn test_custom_plugin_method_greet_prints_to_console() {
    let plugin = TestLibPlugin::new();
    let output_ref = plugin.console_output.clone();
    
    let mut ctx = EvalContext::new();
    ctx.add_resolver(Box::new(plugin));
    
    let code = r#"
        var greeting = TestLib.greet("Alice");
        greeting
    "#;
    
    let result = run_interpreter(code, &mut ctx).unwrap();
    
    // Check the return value
    assert_eq!(result, JsValue::String("Hello, Alice!".to_string()));
    
    // Check that the message was captured
    let output = output_ref.borrow();
    assert_eq!(output.len(), 1);
    assert_eq!(output[0], "Hello, Alice!");
}

#[test]
fn test_custom_plugin_method_add() {
    let mut ctx = EvalContext::new();
    ctx.add_resolver(Box::new(TestLibPlugin::new()));
    
    let code = "var sum = TestLib.add(10, 32);";
    run_interpreter(code, &mut ctx).unwrap();
    
    let sum = get_var(&mut ctx, "sum");
    assert_eq!(sum, JsValue::Number(JsNumberType::Integer(42)));
}

#[test]
fn test_custom_plugin_in_expression() {
    let mut ctx = EvalContext::new();
    ctx.add_resolver(Box::new(TestLibPlugin::new()));
    
    let code = "var result = TestLib.double(5) + TestLib.add(3, 7);";
    run_interpreter(code, &mut ctx).unwrap();
    
    let result = get_var(&mut ctx, "result");
    // double(5) = 10, add(3, 7) = 10, total = 20
    assert_eq!(result, JsValue::Number(JsNumberType::Integer(20)));
}

#[test]
fn test_custom_plugin_with_core_builtins() {
    let mut ctx = EvalContext::new();
    ctx.install_core_builtins(BuiltInRegistry::with_core());
    ctx.add_resolver(Box::new(TestLibPlugin::new()));
    
    let code = r#"
        var a = Math.abs(-5);
        var b = TestLib.double(10);
        var result = a + b;
        result
    "#;
    
    let result = run_interpreter(code, &mut ctx).unwrap();
    // abs(-5) = 5, double(10) = 20, total = 25
    assert_eq!(result, JsValue::Number(JsNumberType::Integer(25)));
}

#[test]
fn test_custom_plugin_multiple_calls() {
    let plugin = TestLibPlugin::new();
    let output_ref = plugin.console_output.clone();
    
    let mut ctx = EvalContext::new();
    ctx.add_resolver(Box::new(plugin));
    
    let code = r#"
        TestLib.greet("Alice");
        TestLib.greet("Bob");
        TestLib.greet("Charlie");
    "#;
    
    run_interpreter(code, &mut ctx).unwrap();
    
    let output = output_ref.borrow();
    assert_eq!(output.len(), 3);
    assert_eq!(output[0], "Hello, Alice!");
    assert_eq!(output[1], "Hello, Bob!");
    assert_eq!(output[2], "Hello, Charlie!");
}

#[test]
fn test_custom_plugin_undefined_method() {
    let mut ctx = EvalContext::new();
    ctx.add_resolver(Box::new(TestLibPlugin::new()));
    
    // This should fall through to normal property lookup and return undefined
    // since TestLib doesn't have a "nonexistent" method
    let code = "var x = TestLib.nonexistent;";
    let result = run_interpreter(code, &mut ctx);
    
    // The call will fail because TestLib.nonexistent is undefined
    // and we try to call it, which should error
    assert!(result.is_ok()); // Getting the property succeeds
}

#[test]
fn test_custom_plugin_constructor() {
    let mut ctx = EvalContext::new();
    ctx.add_resolver(Box::new(TestLibPlugin::new()));
    
    let code = "var obj = new CustomObject(5);";
    run_interpreter(code, &mut ctx).unwrap();
    
    let obj = get_var(&mut ctx, "obj");
    // CustomObject constructor multiplies by 10
    assert_eq!(obj, JsValue::Number(JsNumberType::Integer(50)));
}

#[test]
fn test_custom_plugin_constructor_with_builtin() {
    let mut ctx = EvalContext::new();
    ctx.install_core_builtins(BuiltInRegistry::with_core());
    ctx.add_resolver(Box::new(TestLibPlugin::new()));
    
    let code = r#"
        var s = new String("test");
        var custom = new CustomObject(7);
        custom
    "#;
    
    let result = run_interpreter(code, &mut ctx).unwrap();
    assert_eq!(result, JsValue::Number(JsNumberType::Integer(70)));
}