Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package miniscala
- import miniscala.Ast._
- import miniscala.Interpreter._
- import miniscala.TypeChecker.{TypeEnv, TypeError, typeCheck}
- import miniscala.parser.Parser.parse
- object Test {
- def main(args: Array[String]): Unit = {
- test("{ def f(x: Int): Int = x; f(2) }", IntVal(2), IntType())
- testFail("{ def f(x: Int): Int = x; f(2, 3) }")
- testFail("{ def f(x: Int): Int = x; f(true) }")
- testTypeFail("{ def f(x: Int): Int = false; 2}")
- testVal("{def f(x: Int): Int = false; 2}", IntVal(2))
- testValFail("{def f(x: Int): Int = false; f(2)}")
- // Mutual recursion
- test(
- """{ def even(x: Int): Boolean =
- | if (x == 0) true else odd(x-1);
- | def odd(x: Int): Boolean =
- | if (x == 0) false else even(x-1);
- | even(5) }""".stripMargin, BoolVal(false), BoolType())
- // Static scoping:
- test(
- """{ val x = 2;
- | { def p(): Int = x * 2;
- | { def q(): Int = p();
- | { val x = 5;
- | { def p(): Boolean = true;
- | q() } } } } }""".stripMargin, IntVal(4), IntType())
- test("(i: Int) => i", ClosureVal(List(FunParam("i", Some(IntType()))), None, VarExp("i"), Map()), FunType(List(IntType()), IntType()))
- test("((i: Int) => i * 2)(2)", IntVal(4), IntType())
- test("{ val f = (i: Int) => i * 2; val i = 6; f(2) }", IntVal(4), IntType())
- test("(() => ((i: Int) => i))()", ClosureVal(List(FunParam("i", Some(IntType()))), None, VarExp("i"), Map()), FunType(List(IntType()), IntType()))
- test(
- """{ val x = 2;
- | def f(i: Int, g: Int => Int): Boolean = g(i) == 2;
- | f(4, (i: Int) => i / 2) }
- """.stripMargin, BoolVal(true), BoolType())
- test("((f: Int => Int => Int) => f(2)(3))((i: Int) => ((j: Int) => i * j))", IntVal(6), IntType())
- testFail("((i: Int) => i * 2)(false)")
- testFail("(() => 5)(1)")
- testFail("{ val x = 12; x(2) }")
- testVal("((i) => i * 2)(2)", IntVal(4))
- testTypeFail("((i) => i * 2)")
- }
- def test(prg: String, rval: Val, rtype: Type) = {
- testVal(prg, rval)
- testType(prg, rtype)
- }
- def testFail(prg: String) = {
- testValFail(prg)
- testTypeFail(prg)
- }
- def testVal(prg: String, value: Val, env: Env = Map[Id, Val]()) = {
- assert(eval(parse(prg), env) == value)
- }
- def testType(prg: String, out: Type, tenv: TypeEnv = Map[Id, Type]()) = {
- assert(typeCheck(parse(prg), tenv) == out)
- }
- def testValFail(prg: String) = {
- try {
- eval(parse(prg), Map[Id, Val]())
- assert(false)
- } catch {
- case _: InterpreterError => assert(true)
- }
- }
- def testTypeFail(prg: String) = {
- try {
- typeCheck(parse(prg), Map[Id, Type]())
- assert(false)
- } catch {
- case _: TypeError => assert(true)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement