# HG changeset patch # User Christian Urban # Date 1572183135 0 # Node ID e0a41a1f24cf1525316a2fb136ebf4072a7d67b7 # Parent 715b46eee1029cf912e0cd2051de0955db7527e1 updated diff -r 715b46eee102 -r e0a41a1f24cf progs/compile.scala --- a/progs/compile.scala Sun Oct 27 13:03:58 2019 +0000 +++ b/progs/compile.scala Sun Oct 27 13:32:15 2019 +0000 @@ -1,5 +1,5 @@ // A Small Compiler for the WHILE Language -// (it does not use a parser and lexer) +// (it does not use a parser nor lexer) // the abstract syntax trees @@ -122,16 +122,19 @@ // environments type Env = Map[String, Int] + +def compile_op(op: String) = op match { + case "+" => i"iadd" + case "-" => i"isub" + case "*" => i"imul" +} + // arithmetic expression compilation def compile_aexp(a: AExp, env : Env) : String = a match { case Num(i) => i"ldc $i" case Var(s) => i"iload ${env(s)}" - case Aop("+", a1, a2) => - compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ i"iadd" - case Aop("-", a1, a2) => - compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ i"isub" - case Aop("*", a1, a2) => - compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ i"imul" + case Aop(op, a1, a2) => + compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ compile_op(op) } // boolean expression compilation @@ -248,7 +251,7 @@ } -// Fibonacci numbers as a test-case +// Fibonacci numbers as a bare-bone test-case val fib_test = List(Assign("n", Num(10)), // n := 10; Assign("minus1",Num(0)), // minus1 := 0; diff -r 715b46eee102 -r e0a41a1f24cf progs/primes.while --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/progs/primes.while Sun Oct 27 13:32:15 2019 +0000 @@ -0,0 +1,15 @@ +// prints out prime numbers from +// 2 to 100 (end) + +end := 100; +n := 2; +while (n < end) do { + f := 2; + tmp := 0; + while ((f < n / 2 + 1) && (tmp == 0)) do { + if ((n / f) * f == n) then { tmp := 1 } else { skip }; + f := f + 1 + }; + if (tmp == 0) then { write(n) } else { skip }; + n := n + 1 +} \ No newline at end of file