1 // A parser and interpreter for the While language |
|
2 // |
|
3 |
|
4 import scala.language.implicitConversions |
|
5 import scala.language.reflectiveCalls |
|
6 |
|
7 // more convenience for the semantic actions later on |
|
8 case class ~[+A, +B](_1: A, _2: B) |
|
9 |
|
10 |
|
11 type IsSeq[A] = A => Seq[_] |
|
12 |
|
13 abstract class Parser[I : IsSeq, T] { |
|
14 def parse(ts: I): Set[(T, I)] |
|
15 |
|
16 def parse_all(ts: I) : Set[T] = |
|
17 for ((head, tail) <- parse(ts); if tail.isEmpty) yield head |
|
18 } |
|
19 |
|
20 class SeqParser[I : IsSeq, T, S](p: => Parser[I, T], q: => Parser[I, S]) extends Parser[I, ~[T, S]] { |
|
21 def parse(sb: I) = |
|
22 for ((head1, tail1) <- p.parse(sb); |
|
23 (head2, tail2) <- q.parse(tail1)) yield (new ~(head1, head2), tail2) |
|
24 } |
|
25 |
|
26 class AltParser[I : IsSeq, T](p: => Parser[I, T], q: => Parser[I, T]) extends Parser[I, T] { |
|
27 def parse(sb: I) = p.parse(sb) ++ q.parse(sb) |
|
28 } |
|
29 |
|
30 class FunParser[I : IsSeq, T, S](p: => Parser[I, T], f: T => S) extends Parser[I, S] { |
|
31 def parse(sb: I) = |
|
32 for ((head, tail) <- p.parse(sb)) yield (f(head), tail) |
|
33 } |
|
34 |
|
35 case class StringParser(s: String) extends Parser[String, String] { |
|
36 def parse(sb: String) = { |
|
37 val (prefix, suffix) = sb.splitAt(s.length) |
|
38 if (prefix == s) Set((prefix, suffix)) else Set() |
|
39 } |
|
40 } |
|
41 |
|
42 case object NumParser extends Parser[String, Int] { |
|
43 val reg = "[0-9]+".r |
|
44 def parse(sb: String) = reg.findPrefixOf(sb) match { |
|
45 case None => Set() |
|
46 case Some(s) => { |
|
47 val (head, tail) = sb.splitAt(s.length) |
|
48 Set((head.toInt, tail)) |
|
49 } |
|
50 } |
|
51 } |
|
52 |
|
53 |
|
54 implicit def string2parser(s : String) = StringParser(s) |
|
55 |
|
56 implicit def ParserOps[I : IsSeq, T](p: Parser[I, T]) = new { |
|
57 def ||(q : => Parser[I, T]) = new AltParser[I, T](p, q) |
|
58 def ==>[S] (f: => T => S) = new FunParser[I, T, S](p, f) |
|
59 def ~[S](q : => Parser[I, S]) = new SeqParser[I, T, S](p, q) |
|
60 } |
|
61 |
|
62 implicit def StringOps(s: String) = new { |
|
63 def ||(q : => Parser[String, String]) = new AltParser[String, String](s, q) |
|
64 def ||(r: String) = new AltParser[String, String](s, r) |
|
65 def ==>[S] (f: => String => S) = new FunParser[String, String, S](s, f) |
|
66 def ~[S](q : => Parser[String, S]) = |
|
67 new SeqParser[String, String, S](s, q) |
|
68 def ~(r: String) = |
|
69 new SeqParser[String, String, String](s, r) |
|
70 } |
|
71 |
|
72 |
|
73 // the abstract syntax trees for the WHILE language |
|
74 abstract class Stmt |
|
75 abstract class AExp |
|
76 abstract class BExp |
|
77 |
|
78 type Block = List[Stmt] |
|
79 |
|
80 case object Skip extends Stmt |
|
81 case class If(a: BExp, bl1: Block, bl2: Block) extends Stmt |
|
82 case class While(b: BExp, bl: Block) extends Stmt |
|
83 case class Assign(s: String, a: AExp) extends Stmt |
|
84 case class Write(s: String) extends Stmt |
|
85 |
|
86 |
|
87 case class Var(s: String) extends AExp |
|
88 case class Num(i: Int) extends AExp |
|
89 case class Aop(o: String, a1: AExp, a2: AExp) extends AExp |
|
90 |
|
91 case object True extends BExp |
|
92 case object False extends BExp |
|
93 case class Bop(o: String, a1: AExp, a2: AExp) extends BExp |
|
94 case class And(b1: BExp, b2: BExp) extends BExp |
|
95 case class Or(b1: BExp, b2: BExp) extends BExp |
|
96 |
|
97 case object IdParser extends Parser[String, String] { |
|
98 val reg = "[a-z][a-z,0-9]*".r |
|
99 def parse(sb: String) = reg.findPrefixOf(sb) match { |
|
100 case None => Set() |
|
101 case Some(s) => Set(sb.splitAt(s.length)) |
|
102 } |
|
103 } |
|
104 |
|
105 // arithmetic expressions |
|
106 lazy val AExp: Parser[String, AExp] = |
|
107 (Te ~ "+" ~ AExp) ==> { case x ~ _ ~ z => Aop("+", x, z): AExp } || |
|
108 (Te ~ "-" ~ AExp) ==> { case x ~ _ ~ z => Aop("-", x, z): AExp } || Te |
|
109 lazy val Te: Parser[String, AExp] = |
|
110 (Fa ~ "*" ~ Te) ==> { case x ~ _ ~ z => Aop("*", x, z): AExp } || |
|
111 (Fa ~ "/" ~ Te) ==> { case x ~ _ ~ z => Aop("/", x, z): AExp } || Fa |
|
112 lazy val Fa: Parser[String, AExp] = |
|
113 ("(" ~ AExp ~ ")") ==> { case _ ~ y ~ _ => y } || |
|
114 IdParser ==> Var || |
|
115 NumParser ==> Num |
|
116 |
|
117 // boolean expressions with some simple nesting |
|
118 lazy val BExp: Parser[String, BExp] = |
|
119 (AExp ~ "==" ~ AExp) ==> { case x ~ _ ~ z => Bop("==", x, z): BExp } || |
|
120 (AExp ~ "!=" ~ AExp) ==> { case x ~ _ ~ z => Bop("!=", x, z): BExp } || |
|
121 (AExp ~ "<" ~ AExp) ==> { case x ~ _ ~ z => Bop("<", x, z): BExp } || |
|
122 (AExp ~ ">" ~ AExp) ==> { case x ~ _ ~ z => Bop(">", x, z): BExp } || |
|
123 ("(" ~ BExp ~ ")" ~ "&&" ~ BExp) ==> { case _ ~ y ~ _ ~ _ ~ v => And(y, v): BExp } || |
|
124 ("(" ~ BExp ~ ")" ~ "||" ~ BExp) ==> { case _ ~ y ~ _ ~ _ ~ v => Or(y, v): BExp } || |
|
125 ("true" ==> (_ => True: BExp )) || |
|
126 ("false" ==> (_ => False: BExp )) || |
|
127 ("(" ~ BExp ~ ")") ==> { case _ ~ x ~ _ => x } |
|
128 |
|
129 // statement / statements |
|
130 lazy val Stmt: Parser[String, Stmt] = |
|
131 (("skip" ==> (_ => Skip: Stmt)) || |
|
132 (IdParser ~ ":=" ~ AExp) ==> { case x ~ _ ~ z => Assign(x, z): Stmt } || |
|
133 ("write(" ~ IdParser ~ ")") ==> { case _ ~ y ~ _ => Write(y): Stmt } || |
|
134 ("if" ~ BExp ~ "then" ~ Block ~ "else" ~ Block) ==> |
|
135 { case _ ~ y ~ _ ~ u ~ _ ~ w => If(y, u, w): Stmt } || |
|
136 ("while" ~ BExp ~ "do" ~ Block) ==> { case _ ~ y ~ _ ~ w => While(y, w) }) |
|
137 |
|
138 lazy val Stmts: Parser[String, Block] = |
|
139 (Stmt ~ ";" ~ Stmts) ==> { case x ~ _ ~ z => x :: z : Block } || |
|
140 (Stmt ==> ( s => List(s) : Block)) |
|
141 |
|
142 // blocks (enclosed in curly braces) |
|
143 lazy val Block: Parser[String, Block] = |
|
144 (("{" ~ Stmts ~ "}") ==> { case _ ~ y ~ _ => y } || |
|
145 (Stmt ==> (s => List(s)))) |
|
146 |
|
147 |
|
148 Stmts.parse_all("x2:=5+3;") |
|
149 Block.parse_all("{x:=5;y:=8}") |
|
150 Block.parse_all("if(false)then{x:=5}else{x:=10}") |
|
151 |
|
152 val fib = """n := 10; |
|
153 minus1 := 0; |
|
154 minus2 := 1; |
|
155 temp := 0; |
|
156 while (n > 0) do { |
|
157 temp := minus2; |
|
158 minus2 := minus1 + minus2; |
|
159 minus1 := temp; |
|
160 n := n - 1 |
|
161 }; |
|
162 result := minus2""".replaceAll("\\s+", "") |
|
163 |
|
164 Stmts.parse_all(fib) |
|
165 |
|
166 |
|
167 // an interpreter for the WHILE language |
|
168 type Env = Map[String, Int] |
|
169 |
|
170 def eval_aexp(a: AExp, env: Env) : Int = a match { |
|
171 case Num(i) => i |
|
172 case Var(s) => env(s) |
|
173 case Aop("+", a1, a2) => eval_aexp(a1, env) + eval_aexp(a2, env) |
|
174 case Aop("-", a1, a2) => eval_aexp(a1, env) - eval_aexp(a2, env) |
|
175 case Aop("*", a1, a2) => eval_aexp(a1, env) * eval_aexp(a2, env) |
|
176 case Aop("/", a1, a2) => eval_aexp(a1, env) / eval_aexp(a2, env) |
|
177 } |
|
178 |
|
179 def eval_bexp(b: BExp, env: Env) : Boolean = b match { |
|
180 case True => true |
|
181 case False => false |
|
182 case Bop("==", a1, a2) => eval_aexp(a1, env) == eval_aexp(a2, env) |
|
183 case Bop("!=", a1, a2) => !(eval_aexp(a1, env) == eval_aexp(a2, env)) |
|
184 case Bop(">", a1, a2) => eval_aexp(a1, env) > eval_aexp(a2, env) |
|
185 case Bop("<", a1, a2) => eval_aexp(a1, env) < eval_aexp(a2, env) |
|
186 case And(b1, b2) => eval_bexp(b1, env) && eval_bexp(b2, env) |
|
187 case Or(b1, b2) => eval_bexp(b1, env) || eval_bexp(b2, env) |
|
188 } |
|
189 |
|
190 def eval_stmt(s: Stmt, env: Env) : Env = s match { |
|
191 case Skip => env |
|
192 case Assign(x, a) => env + (x -> eval_aexp(a, env)) |
|
193 case If(b, bl1, bl2) => if (eval_bexp(b, env)) eval_bl(bl1, env) else eval_bl(bl2, env) |
|
194 case While(b, bl) => |
|
195 if (eval_bexp(b, env)) eval_stmt(While(b, bl), eval_bl(bl, env)) |
|
196 else env |
|
197 case Write(x) => { println(env(x)) ; env } |
|
198 } |
|
199 |
|
200 def eval_bl(bl: Block, env: Env) : Env = bl match { |
|
201 case Nil => env |
|
202 case s::bl => eval_bl(bl, eval_stmt(s, env)) |
|
203 } |
|
204 |
|
205 def eval(bl: Block) : Env = eval_bl(bl, Map()) |
|
206 |
|
207 // parse + evaluate fib program; then lookup what is |
|
208 // stored under the variable result |
|
209 println(eval(Stmts.parse_all(fib).head)("result")) |
|
210 |
|
211 |
|
212 // more examles |
|
213 |
|
214 // calculate and print all factors bigger |
|
215 // than 1 and smaller than n |
|
216 println("Factors") |
|
217 |
|
218 val factors = |
|
219 """n := 12; |
|
220 f := 2; |
|
221 while (f < n / 2 + 1) do { |
|
222 if ((n / f) * f == n) then { write(f) } else { skip }; |
|
223 f := f + 1 |
|
224 }""".replaceAll("\\s+", "") |
|
225 |
|
226 eval(Stmts.parse_all(factors).head) |
|
227 |
|
228 // calculate all prime numbers up to a number |
|
229 println("Primes") |
|
230 |
|
231 val primes = |
|
232 """end := 100; |
|
233 n := 2; |
|
234 while (n < end) do { |
|
235 f := 2; |
|
236 tmp := 0; |
|
237 while ((f < n / 2 + 1) && (tmp == 0)) do { |
|
238 if ((n / f) * f == n) then { tmp := 1 } else { skip }; |
|
239 f := f + 1 |
|
240 }; |
|
241 if (tmp == 0) then { write(n) } else { skip }; |
|
242 n := n + 1 |
|
243 }""".replaceAll("\\s+", "") |
|
244 |
|
245 eval(Stmts.parse_all(primes).head) |
|