61 def ~[S](q : => Parser[String, S]) = |
61 def ~[S](q : => Parser[String, S]) = |
62 new SeqParser[String, String, S](s, q) |
62 new SeqParser[String, String, S](s, q) |
63 def ~ (r: String) = |
63 def ~ (r: String) = |
64 new SeqParser[String, String, String](s, r) |
64 new SeqParser[String, String, String](s, r) |
65 } |
65 } |
66 |
|
67 lazy val E: Parser[String, Int] = |
|
68 (T ~ "+" ~ E) ==> { case ((x, y), z) => x + z} || T |
|
69 lazy val T: Parser[String, Int] = |
|
70 (F ~ "*" ~ T) ==> { case ((x, y), z) => x * z} || F |
|
71 lazy val F: Parser[String, Int] = |
|
72 ("(" ~ E ~ ")") ==> { case ((x, y), z) => y} || NumParser |
|
73 |
|
74 println(E.parse_all("123")) |
|
75 println(E.parse_all("1*2+3")) |
|
76 println(E.parse_all("1+2*3")) |
|
77 println(E.parse_all("1+2+3")) |
|
78 println(E.parse_all("1+2+3")) |
|
79 println(E.parse_all("1+2*3+1")) |
|
80 |
|
81 |
|
82 // no left-recursion allowed |
|
83 lazy val EL: Parser[String, Int] = |
|
84 ((EL ~ "+" ~ EL) ==> { case ((x, y), z) => x + z} || |
|
85 (EL ~ "*" ~ EL) ==> { case ((x, y), z) => x * z} || |
|
86 ("(" ~ EL ~ ")") ==> { case ((x, y), z) => y} || |
|
87 NumParser) |
|
88 |
|
89 //println(E.parse_all("1+2+3")) |
|
90 |
66 |
91 |
67 |
92 // the abstract syntax trees for the WHILE language |
68 // the abstract syntax trees for the WHILE language |
93 abstract class Stmt |
69 abstract class Stmt |
94 abstract class AExp |
70 abstract class AExp |
152 lazy val Block: Parser[String, Block] = |
128 lazy val Block: Parser[String, Block] = |
153 (("{" ~ Stmts ~ "}") ==> { case ((x, y), z) => y} || |
129 (("{" ~ Stmts ~ "}") ==> { case ((x, y), z) => y} || |
154 (Stmt ==> ((s) => List(s)))) |
130 (Stmt ==> ((s) => List(s)))) |
155 |
131 |
156 |
132 |
157 Stmt.parse_all("x2:=5") |
133 Stmt.parse_all("x2:=5+3") |
158 Block.parse_all("{x:=5;y:=8}") |
134 Block.parse_all("{x:=5;y:=8}") |
159 Block.parse_all("if(false)then{x:=5}else{x:=10}") |
135 Block.parse_all("if(false)then{x:=5}else{x:=10}") |
160 |
136 |
161 val fib = """{n:=10;minus1:=0;minus2:=1;temp:=0;while(n>0)do{temp:=minus2;minus2:=minus1+minus2;minus1:=temp;n:=n-1};result:=minus2}""" |
137 val fib = """{n:=10;minus1:=0;minus2:=1;temp:=0;while(n>0)do{temp:=minus2;minus2:=minus1+minus2;minus1:=temp;n:=n-1};result:=minus2}""" |
162 |
138 |