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