diff -r fddf099a82f8 -r 64ec1884d860 solutions/cw4/compiler.sc --- a/solutions/cw4/compiler.sc Sat Dec 02 21:37:04 2023 +0000 +++ b/solutions/cw4/compiler.sc Wed Feb 21 09:14:12 2024 +0000 @@ -119,6 +119,8 @@ case "!=" => "if_icmpeq" case "<" => "if_icmpge" case ">" => "if_icmple" + case "<=" => "if_icmpgt" + case "=>" => "if_icmplt" } def compile_bexp(b: BExp, env : Env, jmp: String) : String = b match { @@ -233,6 +235,8 @@ println(s"done.") } +//compile_run(Stmts.parse_all(tokenise(os.read(os.pwd / "pr.while"))).head, "pr") + // ---- Q1 // Fibonacci @@ -250,7 +254,7 @@ write "Result"; write minus2""" -compile_all(Stmts.parse_all(tokenise(fibonacciProgram)).head, "fib") +//compile_all(Stmts.parse_all(tokenise(fibonacciProgram)).head, "fib") val factorialProgram = """write "Factorial"; read n; @@ -265,7 +269,7 @@ write fact """ -compile_all(Stmts.parse_all(tokenise(factorialProgram)).head, "factorial") +//compile_all(Stmts.parse_all(tokenise(factorialProgram)).head, "factorial") // ---- Q3 @@ -279,9 +283,13 @@ //compile_run(Stmts.parse_all(tokenise(os.read(os.pwd / "collatz2.while"))).head, "collatz2") -println(tokenise(os.read(os.pwd / "forloop.while"))) -compile_all(Stmts.parse_all(tokenise(os.read(os.pwd / "forloop.while"))).head, "forloop") +//println(tokenise(os.read(os.pwd / "forloop.while"))) +//compile_all(Stmts.parse_all(tokenise(os.read(os.pwd / "forloop.while"))).head, "forloop") + +//compile_all(Stmts.parse_all(tokenise(os.read(os.pwd / "primes.while"))).head, "primes") + +//compile_run(Stmts.parse_all(tokenise(os.read(os.pwd / "pr.while"))).head, "pr") // for automated testing @@ -292,11 +300,40 @@ } @main -def test(file: String) = { +def run(file: String) = { val contents = os.read(os.pwd / file) - val class_name = file.stripSuffix(".") - compile_all(Stmts.parse_all(tokenise(os.read(os.pwd / file))).head, class_name) - tokenise(contents) + val class_name = file.stripSuffix(".while") + val tks = tokenise(os.read(os.pwd / file)) + //println(tks) + //println(Stmts.parse(tks)) + compile_run(Stmts.parse_all(tks).head, class_name) + //tokenise(contents) + //println(Stmts.parse_all(tokenise(os.read(os.pwd / file))).head) } +//println("TEST") +//println(tokenise(os.read(os.pwd / "pr.while"))) +//println(Stmts.parse_all(tokenise(os.read(os.pwd / "pr.while"))).head) + + + + +/* For with scopes + +case For(x,a,b,bl) => { + val loop_begin = Fresh("Loop_begin") + val loop_end = Fresh("Loop_end") + + val ind = env.getOrElse(x, -1) + val new_ind = Fresh_index() + val (assign,env1) = (compile_aexp(a, env) ++ i"istore $new_ind \t\t; ${x}-new", env + (x -> new_ind)) + + val bool = l"$loop_begin" ++ compile_aexp(Var(x), env1) ++ compile_aexp(b, env1) ++ i"if_icmpgt $loop_end" + val (block, env2) = compile_block(bl,env1,loop_end) + val inc = compile_stmt(Assign(x,Aop("+", Var(x), Num(1))),env2, "")._1 ++ i"goto $loop_begin" ++ l"$loop_end" + (assign ++ bool ++ block ++ inc, if (ind != -1){env2 + (x -> ind)} else {env2 - x}) + } + + +*/