about summary refs log tree commit diff
path: root/users/tazjin/rlox/src/interpreter/tests.rs
blob: bf2cf61b0a7695f27c49458c4303a56e882d9757 (plain) (blame)
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
use super::*;

fn code(code: &str) -> Vec<char> {
    code.chars().collect()
}

/// Evaluate a code snippet, returning a value.
fn parse_eval<'a>(chars: &'a [char]) -> Value<'a> {
    let tokens = scanner::scan(&chars).expect("could not scan code");
    let program = parser::parse(tokens).expect("could not parse code");
    Interpreter::create()
        .interpret(&program)
        .expect("could not eval code")
}

#[test]
fn test_if() {
    let code = code(
        r#"
if (42 > 23)
  "pass";
else
  "fail";
"#,
    );

    assert_eq!(
        Value::Literal(Literal::String("pass".into())),
        parse_eval(&code)
    );
}

#[test]
fn test_scope() {
    let code = code(
        r#"
var result = "";

var a = "global a, ";
var b = "global b, ";
var c = "global c";

{
  var a = "outer a, ";
  var b = "outer b, ";

  {
    var a = "inner a, ";
    result = a + b + c;
  }
}
"#,
    );

    assert_eq!(
        Value::Literal(Literal::String("inner a, outer b, global c".into())),
        parse_eval(&code),
    );
}

#[test]
fn test_binary_operators() {
    assert_eq!(
        Value::Literal(Literal::Number(42.0)),
        parse_eval(&code("40 + 2;"))
    );

    assert_eq!(
        Value::Literal(Literal::String("foobar".into())),
        parse_eval(&code("\"foo\" + \"bar\";"))
    );
}

#[test]
fn test_functions() {
    let code = code(
        r#"
fun add(a, b, c) {
  a + b + c;
}

add(1, 2, 3);
"#,
    );

    assert_eq!(Value::Literal(Literal::Number(6.0)), parse_eval(&code));
}