solution/cw2/lexer.sc
changeset 864 b5b1bc0a603b
equal deleted inserted replaced
863:d59bcff69998 864:b5b1bc0a603b
       
     1 import scala.language.implicitConversions    
       
     2 import scala.language.reflectiveCalls
       
     3 
       
     4 // Rexp
       
     5 abstract class Rexp
       
     6 case object ZERO extends Rexp
       
     7 case object ONE extends Rexp
       
     8 case class CHAR(c: Char) extends Rexp
       
     9 case class ALT(r1: Rexp, r2: Rexp) extends Rexp 
       
    10 case class SEQ(r1: Rexp, r2: Rexp) extends Rexp 
       
    11 case class STAR(r: Rexp) extends Rexp 
       
    12 case class RECD(x: String, r: Rexp) extends Rexp
       
    13 
       
    14 case class RANGE(s: Set[Char]) extends Rexp
       
    15 case class PLUS(r: Rexp) extends Rexp
       
    16 case class OPTIONAL(r: Rexp) extends Rexp
       
    17 case class NTIMES(r: Rexp, n: Int) extends Rexp 
       
    18 
       
    19 // Values
       
    20 abstract class Val
       
    21 case object Empty extends Val
       
    22 case class Chr(c: Char) extends Val
       
    23 case class Sequ(v1: Val, v2: Val) extends Val
       
    24 case class Left(v: Val) extends Val
       
    25 case class Right(v: Val) extends Val
       
    26 case class Stars(vs: List[Val]) extends Val
       
    27 case class Rec(x: String, v: Val) extends Val
       
    28 
       
    29 
       
    30 // Convenience typing
       
    31 def charlist2rexp(s : List[Char]): Rexp = s match {
       
    32   case Nil => ONE
       
    33   case c::Nil => CHAR(c)
       
    34   case c::s => SEQ(CHAR(c), charlist2rexp(s))
       
    35 }
       
    36 
       
    37 implicit def string2rexp(s : String) : Rexp = 
       
    38   charlist2rexp(s.toList)
       
    39 
       
    40 implicit def RexpOps(r: Rexp) = new {
       
    41   def | (s: Rexp) = ALT(r, s)
       
    42   def % = STAR(r)
       
    43   def ~ (s: Rexp) = SEQ(r, s)
       
    44 }
       
    45 
       
    46 implicit def stringOps(s: String) = new {
       
    47   def | (r: Rexp) = ALT(s, r)
       
    48   def | (r: String) = ALT(s, r)
       
    49   def % = STAR(s)
       
    50   def ~ (r: Rexp) = SEQ(s, r)
       
    51   def ~ (r: String) = SEQ(s, r)
       
    52   def $ (r: Rexp) = RECD(s, r)
       
    53 }
       
    54 
       
    55 // nullable
       
    56 def nullable(r: Rexp) : Boolean = r match {
       
    57   case ZERO => false
       
    58   case ONE => true
       
    59   case CHAR(_) => false
       
    60   case ALT(r1, r2) => nullable(r1) || nullable(r2)
       
    61   case SEQ(r1, r2) => nullable(r1) && nullable(r2)
       
    62   case STAR(_) => true
       
    63 
       
    64   case RECD(_, r1) => nullable(r1)
       
    65   case RANGE(_) => false
       
    66   case PLUS(r1) => nullable(r1)
       
    67   case OPTIONAL(_) => true
       
    68   case NTIMES(r1, i) => if (i == 0) true else nullable(r1)
       
    69 }
       
    70 
       
    71 // der
       
    72 def der(c: Char, r: Rexp) : Rexp = r match {
       
    73   case ZERO => ZERO
       
    74   case ONE => ZERO
       
    75   case CHAR(d) => if (c == d) ONE else ZERO
       
    76   case ALT(r1, r2) => ALT(der(c, r1), der(c, r2))
       
    77   case SEQ(r1, r2) => 
       
    78     if (nullable(r1)) ALT(SEQ(der(c, r1), r2), der(c, r2))
       
    79     else SEQ(der(c, r1), r2)
       
    80   case STAR(r) => SEQ(der(c, r), STAR(r))
       
    81 
       
    82   case RECD(_, r1) => der(c, r1)
       
    83   case RANGE(s) => if (s.contains(c)) ONE else ZERO 
       
    84   case PLUS(r1) => SEQ(der(c, r1), STAR(r1))
       
    85   case OPTIONAL(r1) => der(c, r1)
       
    86   case NTIMES(r, i) => 
       
    87     if (i == 0) ZERO else SEQ(der(c, r), NTIMES(r, i - 1))
       
    88 }
       
    89 
       
    90 // Flatten
       
    91 def flatten(v: Val) : String = v match {
       
    92   case Empty => ""
       
    93   case Chr(c) => c.toString
       
    94   case Left(v) => flatten(v)
       
    95   case Right(v) => flatten(v)
       
    96   case Sequ(v1, v2) => flatten(v1) + flatten(v2)
       
    97   case Stars(vs) => vs.map(flatten).mkString
       
    98   case Rec(_, v) => flatten(v)
       
    99 }
       
   100 
       
   101 // Env
       
   102 def env(v: Val) : List[(String, String)] = v match {
       
   103   case Empty => Nil
       
   104   case Chr(c) => Nil
       
   105   case Left(v) => env(v)
       
   106   case Right(v) => env(v)
       
   107   case Sequ(v1, v2) => env(v1) ::: env(v2)
       
   108   case Stars(vs) => vs.flatMap(env)
       
   109   case Rec(x, v) => (x, flatten(v))::env(v)
       
   110 }
       
   111 
       
   112 // Mkeps
       
   113 def mkeps(r: Rexp) : Val = r match {
       
   114   case ONE => Empty
       
   115   case ALT(r1, r2) => 
       
   116     if (nullable(r1)) Left(mkeps(r1)) else Right(mkeps(r2))
       
   117   case SEQ(r1, r2) => Sequ(mkeps(r1), mkeps(r2))
       
   118   case STAR(r) => Stars(Nil)
       
   119   case RECD(x, r) => Rec(x, mkeps(r))
       
   120 
       
   121   case PLUS(r) => Stars(List(mkeps(r)))   // the first copy must match the empty string
       
   122   case OPTIONAL(r) => if (nullable(r)) Stars(List(mkeps(r))) else Stars(Nil)
       
   123   case NTIMES(r, i) => Stars(List.fill(i)(mkeps(r)))
       
   124 }
       
   125 
       
   126 // Inj
       
   127 def inj(r: Rexp, c: Char, v: Val) : Val = (r, v) match {
       
   128   case (STAR(r), Sequ(v1, Stars(vs))) => Stars(inj(r, c, v1)::vs)
       
   129   case (SEQ(r1, r2), Sequ(v1, v2)) => Sequ(inj(r1, c, v1), v2)
       
   130   case (SEQ(r1, r2), Left(Sequ(v1, v2))) => Sequ(inj(r1, c, v1), v2)
       
   131   case (SEQ(r1, r2), Right(v2)) => Sequ(mkeps(r1), inj(r2, c, v2))
       
   132   case (ALT(r1, r2), Left(v1)) => Left(inj(r1, c, v1))
       
   133   case (ALT(r1, r2), Right(v2)) => Right(inj(r2, c, v2))
       
   134   case (CHAR(d), Empty) => Chr(c) 
       
   135   case (RECD(x, r1), _) => Rec(x, inj(r1, c, v))
       
   136 
       
   137   case (RANGE(_), Empty) => Chr(c)
       
   138   case (PLUS(r), Sequ(v1, Stars(vs))) => Stars(inj(r, c, v1)::vs)
       
   139   case (OPTIONAL(r), v1) => Stars(List(inj(r, c, v1)))
       
   140   case (NTIMES(r, n), Sequ(v1, Stars(vs))) => Stars(inj(r, c, v1)::vs)
       
   141 }
       
   142 
       
   143 // Rectification functions
       
   144 def F_ID(v: Val): Val = v
       
   145 def F_RIGHT(f: Val => Val) = (v:Val) => Right(f(v))
       
   146 def F_LEFT(f: Val => Val) = (v:Val) => Left(f(v))
       
   147 def F_ALT(f1: Val => Val, f2: Val => Val) = (v:Val) => v match {
       
   148   case Right(v) => Right(f2(v))
       
   149   case Left(v) => Left(f1(v))
       
   150 }
       
   151 def F_SEQ(f1: Val => Val, f2: Val => Val) = (v:Val) => v match {
       
   152   case Sequ(v1, v2) => Sequ(f1(v1), f2(v2))
       
   153 }
       
   154 def F_SEQ_Empty1(f1: Val => Val, f2: Val => Val) = 
       
   155   (v:Val) => Sequ(f1(Empty), f2(v))
       
   156 def F_SEQ_Empty2(f1: Val => Val, f2: Val => Val) = 
       
   157   (v:Val) => Sequ(f1(v), f2(Empty))
       
   158 def F_RECD(f: Val => Val) = (v:Val) => v match {
       
   159   case Rec(x, v) => Rec(x, f(v))
       
   160 }
       
   161 def F_ERROR(v: Val): Val = throw new Exception("error")
       
   162 
       
   163 // Simp
       
   164 def simp(r: Rexp): (Rexp, Val => Val) = r match {
       
   165   case ALT(r1, r2) => {
       
   166     val (r1s, f1s) = simp(r1)
       
   167     val (r2s, f2s) = simp(r2)
       
   168     (r1s, r2s) match {
       
   169       case (ZERO, _) => (r2s, F_RIGHT(f2s))
       
   170       case (_, ZERO) => (r1s, F_LEFT(f1s))
       
   171       case _ => if (r1s == r2s) (r1s, F_LEFT(f1s))
       
   172                 else (ALT (r1s, r2s), F_ALT(f1s, f2s)) 
       
   173     }
       
   174   }
       
   175   case SEQ(r1, r2) => {
       
   176     val (r1s, f1s) = simp(r1)
       
   177     val (r2s, f2s) = simp(r2)
       
   178     (r1s, r2s) match {
       
   179       case (ZERO, _) => (ZERO, F_ERROR)
       
   180       case (_, ZERO) => (ZERO, F_ERROR)
       
   181       case (ONE, _) => (r2s, F_SEQ_Empty1(f1s, f2s))
       
   182       case (_, ONE) => (r1s, F_SEQ_Empty2(f1s, f2s))
       
   183       case _ => (SEQ(r1s,r2s), F_SEQ(f1s, f2s))
       
   184     }
       
   185   }
       
   186   case r => (r, F_ID)
       
   187 }
       
   188 
       
   189 // Lex
       
   190 def lex_simp(r: Rexp, s: List[Char]) : Val = s match {
       
   191   case Nil => if (nullable(r)) mkeps(r) else 
       
   192     { throw new Exception("lexing error") } 
       
   193   case c::cs => {
       
   194     val (r_simp, f_simp) = simp(der(c, r))
       
   195     inj(r, c, f_simp(lex_simp(r_simp, cs)))
       
   196   }
       
   197 }
       
   198 
       
   199 def lexing_simp(r: Rexp, s: String) = env(lex_simp(r, s.toList))
       
   200 
       
   201 // Language specific code
       
   202 val KEYWORD : Rexp = "while" | "if" | "then" | "else" | "do" | "for" | "to" | "true" | "false" | "read" | "write" | "skip" 
       
   203 val OP : Rexp = "+" | "-" | "*" | "%" | "/" | "==" | "!=" | ">" | "<" | ">=" | "<=" | ":=" | "&&" | "||"
       
   204 val LET: Rexp = RANGE(('A' to 'Z').toSet ++ ('a' to 'z'))
       
   205 val SYM : Rexp = LET | RANGE(Set('.', '_', '>', '<', '=', ';', ',', ':', ')', '('))
       
   206 val PARENS : Rexp = "(" | "{" | ")" | "}"
       
   207 val SEMI : Rexp = ";"
       
   208 val WHITESPACE : Rexp = PLUS(" ") | "\n" | "\t" | "\r"
       
   209 val DIGIT : Rexp = RANGE(('0' to '9').toSet)
       
   210 val DIGIT1 : Rexp = RANGE(('1' to '9').toSet)
       
   211 val STRING : Rexp = "\"" ~ (SYM | " " | "\\n" | DIGIT).% ~ "\""
       
   212 val ID : Rexp = LET ~ (LET | "_" | DIGIT).%
       
   213 val NUM : Rexp = "0" | (DIGIT1 ~ DIGIT.%)
       
   214 val COMMENT : Rexp = "//" ~ (SYM | " " | DIGIT).% ~ ("\n" | "\r\n") 
       
   215 
       
   216 val WHILE_REGS = (("k" $ KEYWORD) | 
       
   217                   ("o" $ OP) | 
       
   218                   ("str" $ STRING) |
       
   219                   ("p" $ PARENS) |
       
   220                   ("s" $ SEMI) | 
       
   221                   ("w" $ WHITESPACE) | 
       
   222                   ("i" $ ID) | 
       
   223                   ("n" $ NUM) |
       
   224 		  ("c" $ COMMENT)).%
       
   225 
       
   226 def esc(raw: String): String = {
       
   227   import scala.reflect.runtime.universe._
       
   228   Literal(Constant(raw)).toString
       
   229 }
       
   230 
       
   231 def escape(tks: List[(String, String)]) =
       
   232   tks.map{ case (s1, s2) => (s1, esc(s2))}
       
   233 
       
   234 // Token
       
   235 abstract class Token extends Serializable 
       
   236 case class T_KEYWORD(s: String) extends Token
       
   237 case class T_OP(s: String) extends Token
       
   238 case class T_STRING(s: String) extends Token
       
   239 case class T_PAREN(s: String) extends Token
       
   240 case object T_SEMI extends Token
       
   241 case class T_ID(s: String) extends Token
       
   242 case class T_NUM(n: Int) extends Token
       
   243 
       
   244 val token : PartialFunction[(String, String), Token] = {
       
   245   case ("k", s) => T_KEYWORD(s)
       
   246   case ("o", s) => T_OP(s)
       
   247   case ("str", s) => T_STRING(s)
       
   248   case ("p", s) => T_PAREN(s)
       
   249   case ("s", _) => T_SEMI
       
   250   case ("i", s) => T_ID(s)
       
   251   case ("n", s) => T_NUM(s.toInt)
       
   252 }
       
   253 
       
   254 // Tokenise
       
   255 def tokenise(s: String) : List[Token] = 
       
   256   lexing_simp(WHILE_REGS, s).collect(token)
       
   257 
       
   258 
       
   259 // Q2 Tests
       
   260 lex_simp(NTIMES("a", 3), "aaa".toList)
       
   261 lex_simp(NTIMES(("a" | ONE), 3), "aa".toList)
       
   262 
       
   263 // Q3 Programs
       
   264 
       
   265 val prog1 = """write "Fib";
       
   266 read n;
       
   267 minus1 := 0;
       
   268 minus2 := 1;
       
   269 while n > 0 do {
       
   270 temp := minus2;
       
   271 minus2 := minus1 + minus2;
       
   272 minus1 := temp;
       
   273 n := n - 1
       
   274 };
       
   275 write "Result";
       
   276 write minus2"""
       
   277 
       
   278 val prog2 = """start := 1000;
       
   279 x := start;
       
   280 y := start;
       
   281 z := start;
       
   282 while 0 < x do {
       
   283 while 0 < y do {
       
   284 while 0 < z do { z := z - 1 };
       
   285 z := start;
       
   286 y := y - 1
       
   287 };
       
   288 y := start;
       
   289 x := x - 1
       
   290 }"""
       
   291 
       
   292 val prog3 = """write "Input n please";
       
   293 read n;
       
   294 write "The factors of n are";
       
   295 f := 2;
       
   296 while n != 1 do {
       
   297 while (n / f) * f == n do {
       
   298 write f;
       
   299 n := n / f
       
   300 };
       
   301 f := f + 1
       
   302 }"""
       
   303 
       
   304 println(tokenise(prog1))
       
   305 println(tokenise(prog2))
       
   306 println(tokenise(prog3))
       
   307 
       
   308 
       
   309 println("MY TESTS")
       
   310 
       
   311 println(lex_simp("x" $ OPTIONAL("a"), "a".toList))
       
   312 println(lex_simp("x" $ OPTIONAL("a"), "".toList))
       
   313 println(lex_simp("x" $ NTIMES(OPTIONAL("a"),4), "aa".toList))
       
   314 println(lex_simp("x" $ OPTIONAL("aa"), "aa".toList))
       
   315 println(lex_simp("x" $ OPTIONAL("aa"), "".toList))
       
   316 
       
   317 
       
   318 
       
   319 
       
   320 //===================
       
   321 println("Fib")
       
   322 println(tokenise(os.read(os.pwd / "fib.while")))
       
   323 
       
   324 println("Factors")
       
   325 println(tokenise(os.read(os.pwd / "factors.while")))
       
   326 
       
   327 println("Loops")
       
   328 println(tokenise(os.read(os.pwd / "loops.while")))
       
   329 
       
   330 println("Collatz")
       
   331 println(tokenise(os.read(os.pwd / "collatz.while")))
       
   332 
       
   333 println("Collatz 2")
       
   334 println(tokenise(os.read(os.pwd / "collatz2.while")))
       
   335 
       
   336 println("Primes")
       
   337 println(tokenise(os.read(os.pwd / "primes.while")))