solutions/cw5/fun_tokens.sc
changeset 903 2f86ebda3629
parent 894 02ef5c3abc51
child 920 7af2eea19646
--- a/solutions/cw5/fun_tokens.sc	Sat Dec 03 21:58:47 2022 +0000
+++ b/solutions/cw5/fun_tokens.sc	Fri Dec 09 11:00:05 2022 +0000
@@ -1,27 +1,31 @@
-// A tokeniser for the Fun language
-//==================================
+// Author: Zhuo Ying Jiang Li
+// Starting code by Dr Christian Urban
+
+// lexer
+
 //
-// call with 
-//
-//     amm fun_tokens.sc fact.fun
-//
-//     amm fun_tokens.sc defs.fun
+// Use this command to print the list of tokens:
+// amm fun_token.sc <name>.fun
 //
 
-
+type Token = (String, String)
+type Tokens = List[Token]
 
-import scala.language.implicitConversions    
-import scala.language.reflectiveCalls 
-
-abstract class Rexp 
+// regular expressions including records
+abstract class Rexp
 case object ZERO extends Rexp
 case object ONE extends Rexp
 case class CHAR(c: Char) extends Rexp
-case class ALT(r1: Rexp, r2: Rexp) extends Rexp 
-case class SEQ(r1: Rexp, r2: Rexp) extends Rexp 
-case class STAR(r: Rexp) extends Rexp 
-case class RECD(x: String, r: Rexp) extends Rexp
-  
+case class RANGE(chars: List[Char]) extends Rexp
+case class ALT(r1: Rexp, r2: Rexp) extends Rexp
+case class SEQ(r1: Rexp, r2: Rexp) extends Rexp
+case class STAR(r: Rexp) extends Rexp
+case class OPTIONAL(r: Rexp) extends Rexp
+case class PLUS(r: Rexp) extends Rexp
+case class NTIMES(r: Rexp, n: Int) extends Rexp
+case class RECD(x: String, r: Rexp) extends Rexp  // records for extracting strings or tokens
+
+// values
 abstract class Val
 case object Empty extends Val
 case class Chr(c: Char) extends Val
@@ -29,20 +33,27 @@
 case class Left(v: Val) extends Val
 case class Right(v: Val) extends Val
 case class Stars(vs: List[Val]) extends Val
+case class Opt(v: Val) extends Val
+case class Pls(vs: List[Val]) extends Val
+case class Nt(vs: List[Val]) extends Val
 case class Rec(x: String, v: Val) extends Val
-   
+
 // some convenience for typing in regular expressions
 def charlist2rexp(s : List[Char]): Rexp = s match {
   case Nil => ONE
   case c::Nil => CHAR(c)
-  case c::s => SEQ(CHAR(c), charlist2rexp(s))
+  case c::vs => SEQ(CHAR(c), charlist2rexp(vs))
 }
-implicit def string2rexp(s : String) : Rexp = 
+
+implicit def string2rexp(s : String) : Rexp =
   charlist2rexp(s.toList)
 
 implicit def RexpOps(r: Rexp) = new {
   def | (s: Rexp) = ALT(r, s)
   def % = STAR(r)
+  def ? = OPTIONAL(r)
+  def + = PLUS(r)
+  def ^ (n: Int) = NTIMES(r, n)
   def ~ (s: Rexp) = SEQ(r, s)
 }
 
@@ -50,66 +61,89 @@
   def | (r: Rexp) = ALT(s, r)
   def | (r: String) = ALT(s, r)
   def % = STAR(s)
+  def ? = OPTIONAL(s)
+  def + = PLUS(s)
+  def ^ (n: Int) = NTIMES(s, n)
   def ~ (r: Rexp) = SEQ(s, r)
   def ~ (r: String) = SEQ(s, r)
   def $ (r: Rexp) = RECD(s, r)
 }
 
-def nullable (r: Rexp) : Boolean = r match {
+def nullable(r: Rexp) : Boolean = r match {
   case ZERO => false
   case ONE => true
   case CHAR(_) => false
+  case RANGE(_) => false
   case ALT(r1, r2) => nullable(r1) || nullable(r2)
   case SEQ(r1, r2) => nullable(r1) && nullable(r2)
   case STAR(_) => true
+  case OPTIONAL(r1) => true
+  case PLUS(r1) => nullable(r1)
+  case NTIMES(r1, n) => if (n == 0) true else nullable(r1)
   case RECD(_, r1) => nullable(r1)
 }
 
-def der (c: Char, r: Rexp) : Rexp = r match {
+def der(c: Char, r: Rexp) : Rexp = r match {
   case ZERO => ZERO
   case ONE => ZERO
   case CHAR(d) => if (c == d) ONE else ZERO
+  case RANGE(chars) => if (chars.contains(c)) ONE else ZERO
   case ALT(r1, r2) => ALT(der(c, r1), der(c, r2))
-  case SEQ(r1, r2) => 
+  case SEQ(r1, r2) =>
     if (nullable(r1)) ALT(SEQ(der(c, r1), r2), der(c, r2))
     else SEQ(der(c, r1), r2)
   case STAR(r) => SEQ(der(c, r), STAR(r))
+  case OPTIONAL(r) => der(c, r)
+  case PLUS(r) => SEQ(der(c, r), STAR(r))
+  case NTIMES(r1, n) => if (n == 0) ZERO else SEQ(der(c, r1), NTIMES(r1, n - 1))
   case RECD(_, r1) => der(c, r1)
 }
 
-
-// extracts a string from value
+// extracts a string from a value
 def flatten(v: Val) : String = v match {
   case Empty => ""
   case Chr(c) => c.toString
   case Left(v) => flatten(v)
   case Right(v) => flatten(v)
-  case Sequ(v1, v2) => flatten(v1) + flatten(v2)
+  case Sequ(v1, v2) => flatten(v1) ++ flatten(v2)
   case Stars(vs) => vs.map(flatten).mkString
+  case Opt(v) => flatten(v)
+  case Pls(vs) => vs.map(flatten).mkString
+  case Nt(vs) => vs.map(flatten).mkString
   case Rec(_, v) => flatten(v)
 }
 
 // extracts an environment from a value;
-// used for tokenise a string
-def env(v: Val) : List[(String, String)] = v match {
+// used for tokenising a string
+def env(v: Val) : Tokens = v match {
   case Empty => Nil
   case Chr(c) => Nil
   case Left(v) => env(v)
   case Right(v) => env(v)
   case Sequ(v1, v2) => env(v1) ::: env(v2)
   case Stars(vs) => vs.flatMap(env)
+  case Opt(v) => env(v)
+  case Pls(vs) => vs.flatMap(env)
+  case Nt(vs) => vs.flatMap(env)
   case Rec(x, v) => (x, flatten(v))::env(v)
 }
 
-// The Injection Part of the lexer
+
+// The injection and mkeps part of the lexer
+//===========================================
 
 def mkeps(r: Rexp) : Val = r match {
   case ONE => Empty
-  case ALT(r1, r2) => 
+  case RANGE(chars) => throw new Exception("lexing error")  // this will never be called but the coursework asks for it so...
+  case ALT(r1, r2) =>
     if (nullable(r1)) Left(mkeps(r1)) else Right(mkeps(r2))
   case SEQ(r1, r2) => Sequ(mkeps(r1), mkeps(r2))
   case STAR(r) => Stars(Nil)
+  case OPTIONAL(r) => Opt(Empty)
+  case PLUS(r) => Pls(List(mkeps(r))) // scala define a list with one element
+  case NTIMES(r, n) => if (n == 0) Nt(Nil) else Nt(List.fill(n)(mkeps(r))) // wrong
   case RECD(x, r) => Rec(x, mkeps(r))
+  case _ => throw new Exception("lexing error")
 }
 
 def inj(r: Rexp, c: Char, v: Val) : Val = (r, v) match {
@@ -119,9 +153,12 @@
   case (SEQ(r1, r2), Right(v2)) => Sequ(mkeps(r1), inj(r2, c, v2))
   case (ALT(r1, r2), Left(v1)) => Left(inj(r1, c, v1))
   case (ALT(r1, r2), Right(v2)) => Right(inj(r2, c, v2))
-  case (CHAR(d), Empty) => Chr(c) 
+  case (CHAR(d), Empty) => Chr(c)
+  case (RANGE(chars), Empty) => Chr(c)
+  case (OPTIONAL(r1), v) => Opt(inj(r1, c, v))
+  case (PLUS(r1), Sequ(v1, Stars(vs))) => Pls(inj(r1, c, v1)::vs)
+  case (NTIMES(r1, n), Sequ(v1, Nt(vs))) => Nt(inj(r1, c, v1)::vs)
   case (RECD(x, r1), _) => Rec(x, inj(r1, c, v))
-  case _ => { println ("Injection error") ; sys.exit(-1) } 
 }
 
 // some "rectification" functions for simplification
@@ -135,15 +172,14 @@
 def F_SEQ(f1: Val => Val, f2: Val => Val) = (v:Val) => v match {
   case Sequ(v1, v2) => Sequ(f1(v1), f2(v2))
 }
-def F_SEQ_Empty1(f1: Val => Val, f2: Val => Val) = 
+def F_SEQ_Empty1(f1: Val => Val, f2: Val => Val) =
   (v:Val) => Sequ(f1(Empty), f2(v))
-def F_SEQ_Empty2(f1: Val => Val, f2: Val => Val) = 
+def F_SEQ_Empty2(f1: Val => Val, f2: Val => Val) =
   (v:Val) => Sequ(f1(v), f2(Empty))
-def F_RECD(f: Val => Val) = (v:Val) => v match {
-  case Rec(x, v) => Rec(x, f(v))
-}
+
 def F_ERROR(v: Val): Val = throw new Exception("error")
 
+// simplification
 def simp(r: Rexp): (Rexp, Val => Val) = r match {
   case ALT(r1, r2) => {
     val (r1s, f1s) = simp(r1)
@@ -152,7 +188,7 @@
       case (ZERO, _) => (r2s, F_RIGHT(f2s))
       case (_, ZERO) => (r1s, F_LEFT(f1s))
       case _ => if (r1s == r2s) (r1s, F_LEFT(f1s))
-                else (ALT (r1s, r2s), F_ALT(f1s, f2s)) 
+                else (ALT (r1s, r2s), F_ALT(f1s, f2s))
     }
   }
   case SEQ(r1, r2) => {
@@ -166,115 +202,75 @@
       case _ => (SEQ(r1s,r2s), F_SEQ(f1s, f2s))
     }
   }
-  case RECD(x, r1) => {
-    val (r1s, f1s) = simp(r1)
-    (RECD(x, r1s), F_RECD(f1s))
-  }
   case r => (r, F_ID)
 }
 
 // lexing functions including simplification
 def lex_simp(r: Rexp, s: List[Char]) : Val = s match {
-  case Nil => if (nullable(r)) mkeps(r) else { println ("Lexing Error") ; sys.exit(-1) } 
+  case Nil => if (nullable(r)) mkeps(r) else
+    { throw new Exception("lexing error") }
   case c::cs => {
     val (r_simp, f_simp) = simp(der(c, r))
     inj(r, c, f_simp(lex_simp(r_simp, cs)))
   }
 }
 
-def lexing_simp(r: Rexp, s: String) = env(lex_simp(r, s.toList))
+def lexing_simp(r: Rexp, s: String) =
+  env(lex_simp(r, s.toList))
 
 
-// The Lexing Rules for the Fun Language
-
-def PLUS(r: Rexp) = r ~ r.%
-def OPT(r: Rexp) = r | ONE
+// FUN language lexer
 
-val SYM = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | 
-          "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | 
-          "w" | "x" | "y" | "z" | "A" | "B" | "C" | "D" |"E" | "F" | "G" |
-          "H" | "I" | "J" | "K" |"L" | "M" | "N" |
-          "O" | "P" | "Q" | "R" |"S" | "T" | "U" |
-          "V" | "W" | "X" | "Y" | "Z" | "_" | ":"
-val DIGIT = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
-val ID = SYM ~ (SYM | DIGIT).% 
-val NUM = PLUS(DIGIT)
-val FNUM = OPT("-") ~ NUM ~ "." ~ NUM 
-val KEYWORD : Rexp = "if" | "then" | "else" | "def" | "val"
-val TYPE : Rexp = "Void" | "Int" | "Double" 
-val SEMI: Rexp = ";"
-val COLON: Rexp = ":"
-val COMMA: Rexp = ","
-val OP: Rexp = "=" | "==" | "-" | "+" | "*" | "!=" | "<" | ">" | "<=" | ">=" | "%" | "/"
-val WHITESPACE = PLUS(" " | "\n" | "\t" | "\r")
-val RPAREN: Rexp = ")" | "}"
-val LPAREN: Rexp = "(" | "{"
-val ALL = SYM | DIGIT | OP | " " | ":" | ";" | "-" | "." | "\"" | "=" | "," | "(" | ")" | "{" | "}"
-val ALL2 = ALL | "\n"
-val COMMENT = ("/*" ~ ALL2.% ~ "*/") | ("//" ~ ALL.% ~ "\n")
-
-val CHR :Rexp = "'" ~ (ALL | "\\n") ~ "'" 
+val DIGIT = RANGE("0123456789".toList)
+val LOWERCASE = RANGE("abcdefghijklmnopqrstuvwxyz".toList)
+val UPPERCASE = RANGE("ABCDEFGHIJKLMNOPQRSTUVWXYZ".toList)
+val SYM = RANGE("!\"#$%&'()*+,-./:;<>=?`@[]\\^_{}|~".toList)  // I referenced the CPP ASCII table https://en.cppreference.com/w/cpp/language/ascii
 
 
-val FUN_REGS = (("k" $ KEYWORD) | 
-                ("t" $ TYPE) |
-                ("i" $ ID) | 
-                ("ch" $ CHR) | 
-                ("o" $ OP) | 
-                ("n" $ NUM) | 
-                ("f" $ FNUM) | 
-                ("s" $ SEMI) | 
-                ("co" $ COLON) |
-                ("c" $ COMMA) |
-                ("pl" $ LPAREN) |
-                ("pr" $ RPAREN) |
-                ("w" $ (WHITESPACE | COMMENT))).%
-
-
-
-// The tokens for the Fun language
+val KEYWORD : Rexp = "val" | "if" | "then" | "else" | "def" | "skip" // "skip" is hardcoded because hanoi.fun calls skip() without parentheses
+val TYPE : Rexp = "Int" | "Double" | "Void"
+val GLOBAL_ID : Rexp = UPPERCASE ~ ("_" | LOWERCASE | DIGIT | UPPERCASE).% // start with capital letter and followed by any case
+val ID : Rexp = LOWERCASE ~ ("_" | UPPERCASE | LOWERCASE | DIGIT).% // start with lowercase 
+val SEMI : Rexp = ";"
+val COLON : Rexp = ":"
+val OP : Rexp = "=" | "==" | "-" | "+" | "*" | "!=" | "<" | ">" | "<=" | ">=" | "%" | "/" // no && and || operators
+val INT : Rexp = DIGIT.+
+val DOUBLE : Rexp = DIGIT.+ ~ "." ~ DIGIT.+  // negative numbers sign is lexed as operator, but the parser will identify negative numbers
+val COMMA : Rexp = "," 
+val WHITESPACES: Rexp = (" " | "\n" | "\t" | "\r").+ // whitespaces are either " " or \n or \t or \r
+val LPAREN : Rexp = RANGE("({".toList)
+val RPAREN : Rexp = RANGE(")}".toList)
+val CH : Rexp = "'" ~ (LOWERCASE | UPPERCASE | DIGIT | SYM | " " | "\\n" | "\\t" | "\\r") ~ "'"  // \n, \t and \r should also be tokenized, any character should be, whitespaces too
+val COMMENT : Rexp = ("//" ~ (LOWERCASE | UPPERCASE | SYM | DIGIT | RANGE(" \t\r".toList)).% ~ "\n") | ("/*" ~ (LOWERCASE | UPPERCASE | SYM | DIGIT | RANGE(" \n\t\r".toList)).% ~ "*/")
 
-abstract class Token extends Serializable 
-case object T_SEMI extends Token
-case object T_COMMA extends Token
-case object T_COLON extends Token
-case object T_LPAREN extends Token
-case object T_RPAREN extends Token
-case class T_ID(s: String) extends Token
-case class T_FID(s: String) extends Token
-case class T_OP(s: String) extends Token
-case class T_NUM(n: Int) extends Token
-case class T_FNUM(x: Double) extends Token
-case class T_KWD(s: String) extends Token
-case class T_TY(s: String) extends Token
-case class T_CHR(i: Int) extends Token
+val FUN_REGS = (("keyword" $ KEYWORD) |
+                ("type" $ TYPE) |
+                ("global" $ GLOBAL_ID) |
+                ("id" $ ID) |
+                ("op" $ OP) |
+                ("double" $ DOUBLE) |
+                ("int" $ INT) |
+                ("semi" $ SEMI) |
+                ("colon" $ COLON) |
+                ("comma" $ COMMA) |
+                ("ch" $ CH) |
+                ("par" $ (LPAREN | RPAREN)) |
+                COMMENT | WHITESPACES).%
 
-val token : PartialFunction[(String, String), Token] = {
-  case ("k", s) => T_KWD(s)
-  case ("t", s) => T_TY(s)
-  case ("i", s) => T_ID(s)
-  case ("o", s) => T_OP(s)
-  case ("n", s) => T_NUM(s.toInt)
-  case ("ch", s) => if (s == "'\\n'") T_CHR(10) else T_CHR(s(1).toInt)
-  case ("f", s) => T_FNUM(s.toDouble) 
-  case ("s", _) => T_SEMI
-  case ("c", _) => T_COMMA
-  case ("co", _) => T_COLON
-  case ("pl", _) => T_LPAREN
-  case ("pr", _) => T_RPAREN
+def fun_lex(program: String) : Tokens = {
+  lexing_simp(FUN_REGS, program)
 }
 
-
-def tokenise(s: String) : List[Token] = {
-  val tks = lexing_simp(FUN_REGS, s).collect(token)
-  if (tks.length != 0) tks
-  else { println (s"Tokenise Error") ; sys.exit(-1) }     
+def tokenise(program: String) : Tokens = {
+  lexing_simp(FUN_REGS, program)
 }
 
-//import ammonite.ops._
+import scala.io.Source._
 
-//@doc("Tokenising a file.")
 @main
-def main(fname: String) = {
-  println(tokenise(os.read(os.pwd / fname)))
+def lex(filename: String) = {
+  // read file
+  val fun_code = fromFile(filename).getLines.mkString("\n")
+  // print tokens to screen
+  println(fun_lex(fun_code).mkString("\n"))
 }