From f4a6e9f133097986cd59cc2206e9c35d2f320071 Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Thu, 14 Jan 2021 03:48:10 +0300 Subject: test(tazjin/rlox): Add a handful of interpreter tests Change-Id: I32dd896d42cc73d68d73093e9cbb74b48d95e041 Reviewed-on: https://cl.tvl.fyi/c/depot/+/2386 Reviewed-by: tazjin Tested-by: BuildkiteCI --- users/tazjin/rlox/src/interpreter.rs | 3 ++ users/tazjin/rlox/src/interpreter/tests.rs | 63 ++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 users/tazjin/rlox/src/interpreter/tests.rs diff --git a/users/tazjin/rlox/src/interpreter.rs b/users/tazjin/rlox/src/interpreter.rs index 744e6ea89552..cccc381b3258 100644 --- a/users/tazjin/rlox/src/interpreter.rs +++ b/users/tazjin/rlox/src/interpreter.rs @@ -8,6 +8,9 @@ use std::sync::RwLock; // Implementation of built-in functions. mod builtins; +#[cfg(test)] +mod tests; + // Tree-walk interpreter // Representation of all callables, including builtins & user-defined diff --git a/users/tazjin/rlox/src/interpreter/tests.rs b/users/tazjin/rlox/src/interpreter/tests.rs new file mode 100644 index 000000000000..3aaea707d64b --- /dev/null +++ b/users/tazjin/rlox/src/interpreter/tests.rs @@ -0,0 +1,63 @@ +use super::*; + +/// Evaluate a code snippet, returning a value. +fn parse_eval(code: &str) -> Value { + let chars: Vec = code.chars().collect(); + 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 result = parse_eval( + r#" +if (42 > 23) + "pass"; +else + "fail"; +"#, + ); + + assert_eq!(Value::Literal(Literal::String("pass".into())), result); +} + +#[test] +fn test_scope() { + let result = parse_eval( + 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())), + result + ); +} + +#[test] +fn test_binary_operators() { + assert_eq!(Value::Literal(Literal::Number(42.0)), parse_eval("40 + 2;")); + + assert_eq!( + Value::Literal(Literal::String("foobar".into())), + parse_eval("\"foo\" + \"bar\";") + ); +} -- cgit 1.4.1