while1.scala
changeset 75 898c25a4e399
parent 74 8f85d1f61663
child 76 373cf55a3ca5
equal deleted inserted replaced
74:8f85d1f61663 75:898c25a4e399
       
     1 // A parser and evaluator for teh while language
       
     2 // 
       
     3 //:load matcher.scala
       
     4 //:load parser3.scala
       
     5 
       
     6 // some regular expressions
       
     7 val SYM = RANGE("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz_")
       
     8 val DIGIT = RANGE("0123456789")
       
     9 val ID = SEQ(SYM, STAR(ALT(SYM, DIGIT))) 
       
    10 val NUM = PLUS(DIGIT)
       
    11 val KEYWORD = ALTS("skip", "while", "do", "if", "then", "else", "true", "false", "print") 
       
    12 val SEMI: Rexp = ";"
       
    13 val OP: Rexp = ALTS(":=", "=", "-", "+", "*", "!", "<", ">")
       
    14 val WHITESPACE = PLUS(RANGE(" \n"))
       
    15 val RPAREN: Rexp = ")"
       
    16 val LPAREN: Rexp = "("
       
    17 val BEGIN: Rexp = "{"
       
    18 val END: Rexp = "}"
       
    19 val COMMENT = SEQS("/*", NOT(SEQS(STAR(ALLC), "*/", STAR(ALLC))), "*/")
       
    20 
       
    21 // tokens for classifying the strings that have been recognised
       
    22 abstract class Token
       
    23 case object T_WHITESPACE extends Token
       
    24 case object T_COMMENT extends Token
       
    25 case object T_SEMI extends Token
       
    26 case object T_LPAREN extends Token
       
    27 case object T_RPAREN extends Token
       
    28 case object T_BEGIN extends Token
       
    29 case object T_END extends Token
       
    30 case class T_ID(s: String) extends Token
       
    31 case class T_OP(s: String) extends Token
       
    32 case class T_NUM(s: String) extends Token
       
    33 case class T_KWD(s: String) extends Token
       
    34 
       
    35 val lexing_rules: List[Rule[Token]] = 
       
    36   List((KEYWORD, (s) => T_KWD(s.mkString)),
       
    37        (ID, (s) => T_ID(s.mkString)),
       
    38        (OP, (s) => T_OP(s.mkString)),
       
    39        (NUM, (s) => T_NUM(s.mkString)),
       
    40        (SEMI, (s) => T_SEMI),
       
    41        (LPAREN, (s) => T_LPAREN),
       
    42        (RPAREN, (s) => T_RPAREN),
       
    43        (BEGIN, (s) => T_BEGIN),
       
    44        (END, (s) => T_END),
       
    45        (WHITESPACE, (s) => T_WHITESPACE),
       
    46        (COMMENT, (s) => T_COMMENT))
       
    47 
       
    48 // the tokenizer
       
    49 val Tok = Tokenizer(lexing_rules, List(T_WHITESPACE, T_COMMENT))
       
    50 
       
    51 // the abstract syntax trees
       
    52 abstract class Stmt
       
    53 abstract class AExp
       
    54 abstract class BExp 
       
    55 type Block = List[Stmt]
       
    56 case object Skip extends Stmt
       
    57 case class If(a: BExp, bl1: Block, bl2: Block) extends Stmt
       
    58 case class While(b: BExp, bl: Block) extends Stmt
       
    59 case class Assign(s: String, a: AExp) extends Stmt
       
    60 case class Print(s: String) extends Stmt
       
    61 
       
    62 case class Var(s: String) extends AExp
       
    63 case class Num(i: Int) extends AExp
       
    64 case class Aop(o: String, a1: AExp, a2: AExp) extends AExp
       
    65 
       
    66 case object True extends BExp
       
    67 case object False extends BExp
       
    68 case class Bop(o: String, a1: AExp, a2: AExp) extends BExp
       
    69 
       
    70 // atomic parsers
       
    71 case class TokParser(tok: Token) extends Parser[List[Token], Token] {
       
    72   def parse(ts: List[Token]) = ts match {
       
    73     case t::ts if (t == tok) => Set((t, ts)) 
       
    74     case _ => Set ()
       
    75   }
       
    76 }
       
    77 implicit def token2tparser(t: Token) = TokParser(t)
       
    78 
       
    79 case object NumParser extends Parser[List[Token], Int] {
       
    80   def parse(ts: List[Token]) = ts match {
       
    81     case T_NUM(s)::ts => Set((s.toInt, ts)) 
       
    82     case _ => Set ()
       
    83   }
       
    84 }
       
    85 
       
    86 case object IdParser extends Parser[List[Token], String] {
       
    87   def parse(ts: List[Token]) = ts match {
       
    88     case T_ID(s)::ts => Set((s, ts)) 
       
    89     case _ => Set ()
       
    90   }
       
    91 }
       
    92 
       
    93 
       
    94 // arithmetic expressions
       
    95 lazy val AExp: Parser[List[Token], AExp] = 
       
    96   (T ~ T_OP("+") ~ AExp) ==> { case ((x, y), z) => Aop("+", x, z): AExp } ||
       
    97   (T ~ T_OP("-") ~ AExp) ==> { case ((x, y), z) => Aop("-", x, z): AExp } || T  
       
    98 lazy val T: Parser[List[Token], AExp] = 
       
    99   (F ~ T_OP("*") ~ T) ==> { case ((x, y), z) => Aop("*", x, z): AExp } || F
       
   100 lazy val F: Parser[List[Token], AExp] = 
       
   101   (T_LPAREN ~> AExp <~ T_RPAREN) || 
       
   102   IdParser ==> Var || 
       
   103   NumParser ==> Num
       
   104 
       
   105 // boolean expressions
       
   106 lazy val BExp: Parser[List[Token], BExp] = 
       
   107   (AExp ~ T_OP("=") ~ AExp) ==> { case ((x, y), z) => Bop("=", x, z): BExp } || 
       
   108   (AExp ~ T_OP("!=") ~ AExp) ==> { case ((x, y), z) => Bop("!=", x, z): BExp } || 
       
   109   (AExp ~ T_OP("<") ~ AExp) ==> { case ((x, y), z) => Bop("<", x, z): BExp } || 
       
   110   (AExp ~ T_OP(">") ~ AExp) ==> { case ((x, y), z) => Bop(">", x, z): BExp } || 
       
   111   (T_KWD("true") ==> ((_) => True)) || 
       
   112   (T_KWD("false") ==> ((_) => False: BExp))
       
   113 
       
   114 lazy val Stmt: Parser[List[Token], Stmt] =
       
   115   (T_KWD("skip") ==> ((_) => Skip: Stmt)) ||
       
   116   (IdParser ~ T_OP(":=") ~ AExp) ==> { case ((x, y), z) => Assign(x, z): Stmt } ||
       
   117   (T_KWD("if") ~ BExp ~ T_KWD("then") ~ Block ~ T_KWD("else") ~ Block) ==>
       
   118     { case (((((x,y),z),u),v),w) => If(y, u, w): Stmt } ||
       
   119   (T_KWD("while") ~ BExp ~ T_KWD("do") ~ Block) ==> { case (((x, y), z), w) => While(y, w) } || 
       
   120   (T_KWD("print") ~ IdParser) ==> { case (x, y) => Print(y) } 
       
   121 
       
   122 lazy val Stmts: Parser[List[Token], Block] =
       
   123   (Stmt ~ T_SEMI ~ Stmts) ==> { case ((x, y), z) => x :: z : Block } ||
       
   124   (Stmt ==> ((s) => List(s) : Block))
       
   125 
       
   126 lazy val Block: Parser[List[Token], Block] =
       
   127   (T_BEGIN ~> Stmts <~ T_END) || 
       
   128   (Stmt ==> ((s) => List(s)))
       
   129 
       
   130 // interpreter
       
   131 type Env = Map[String, Int]
       
   132 
       
   133 def eval_bexp(b: BExp, env: Env) : Boolean = b match {
       
   134   case True => true
       
   135   case False => false
       
   136   case Bop("=", a1, a2) => eval_aexp(a1, env) == eval_aexp(a2, env)
       
   137   case Bop("!=", a1, a2) => !(eval_aexp(a1, env) == eval_aexp(a2, env))
       
   138   case Bop(">", a1, a2) => eval_aexp(a1, env) > eval_aexp(a2, env)
       
   139   case Bop("<", a1, a2) => eval_aexp(a1, env) < eval_aexp(a2, env)
       
   140 }
       
   141 
       
   142 def eval_aexp(a: AExp, env : Env) : Int = a match {
       
   143   case Num(i) => i
       
   144   case Var(s) => env(s)
       
   145   case Aop("+", a1, a2) => eval_aexp(a1, env) + eval_aexp(a2, env)
       
   146   case Aop("-", a1, a2) => eval_aexp(a1, env) - eval_aexp(a2, env)
       
   147   case Aop("*", a1, a2) => eval_aexp(a1, env) * eval_aexp(a2, env)
       
   148 }
       
   149 
       
   150 def eval_stmt(s: Stmt, env: Env) : Env = s match {
       
   151   case Skip => env
       
   152   case Assign(x, a) => env + (x -> eval_aexp(a, env))
       
   153   case If(b, bl1, bl2) => if (eval_bexp(b, env)) eval_bl(bl1, env) else eval_bl(bl2, env) 
       
   154   case While(b, bl) => 
       
   155     if (eval_bexp(b, env)) eval_stmt(While(b, bl), eval_bl(bl, env))
       
   156     else env
       
   157   case Print(x) => { println(env(x)); env }
       
   158 }
       
   159 
       
   160 def eval_bl(bl: Block, env: Env) : Env = bl match {
       
   161   case Nil => env
       
   162   case s::bl => eval_bl(bl, eval_stmt(s, env))
       
   163 }
       
   164 
       
   165 def eval_prog(name: String) : Env = {
       
   166   val tks = Tok.fromFile(name)
       
   167   val ast = Stmts.parse_all(tks).head
       
   168   eval_bl(ast, Map.empty)
       
   169 }
       
   170 
       
   171 
       
   172 //examples
       
   173 
       
   174 eval_prog("fib.while")