# HG changeset patch # User Christian Urban # Date 1593897138 -3600 # Node ID 5d860ff0193833af943be57ed1697763ecd2fedc # Parent 022e2cb1668dbb4a69907e5f7c2d03be09d1d2ce updated diff -r 022e2cb1668d -r 5d860ff01938 progs/comb1.scala --- a/progs/comb1.scala Sat Jul 04 21:57:33 2020 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,226 +0,0 @@ -import scala.language.implicitConversions -import scala.language.reflectiveCalls - -/* Note, in the lectures I did not show the implicit type - * constraint IsSeq, which means that the input type 'I' needs - * to be a sequence. */ - -type IsSeq[A] = A => Seq[_] - -abstract class Parser[I : IsSeq, T] { - def parse(ts: I): Set[(T, I)] - - def parse_all(ts: I) : Set[T] = - for ((head, tail) <- parse(ts); - if tail.isEmpty) yield head -} - -class SeqParser[I : IsSeq, T, S](p: => Parser[I, T], - q: => Parser[I, S]) extends Parser[I, (T, S)] { - def parse(sb: I) = - for ((head1, tail1) <- p.parse(sb); - (head2, tail2) <- q.parse(tail1)) yield ((head1, head2), tail2) -} - -class AltParser[I : IsSeq, T](p: => Parser[I, T], - q: => Parser[I, T]) extends Parser[I, T] { - def parse(sb: I) = p.parse(sb) ++ q.parse(sb) -} - -class FunParser[I : IsSeq, T, S](p: => Parser[I, T], - f: T => S) extends Parser[I, S] { - def parse(sb: I) = - for ((head, tail) <- p.parse(sb)) yield (f(head), tail) -} - -// atomic parsers for characters, numbers and strings -case class CharParser(c: Char) extends Parser[String, Char] { - def parse(sb: String) = - if (sb != "" && sb.head == c) Set((c, sb.tail)) else Set() -} - -import scala.util.matching.Regex -case class RegexParser(reg: Regex) extends Parser[String, String] { - def parse(sb: String) = reg.findPrefixMatchOf(sb) match { - case None => Set() - case Some(m) => Set((m.matched, m.after.toString)) - } -} - -val NumParser = RegexParser("[0-9]+".r) -def StringParser(s: String) = RegexParser(Regex.quote(s).r) - -// NumParserInt2 transforms a "string integer" into an actual Int; -// needs new, because FunParser is not a case class -val NumParserInt2 = new FunParser(NumParser, (s: String) => s.toInt) - - -// convenience -implicit def string2parser(s: String) = StringParser(s) -implicit def char2parser(c: Char) = CharParser(c) - -implicit def ParserOps[I, T](p: Parser[I, T])(implicit ev: I => Seq[_]) = new { - def ||(q : => Parser[I, T]) = new AltParser[I, T](p, q) - def ==>[S] (f: => T => S) = new FunParser[I, T, S](p, f) - def ~[S] (q : => Parser[I, S]) = new SeqParser[I, T, S](p, q) -} - -implicit def StringOps(s: String) = new { - def ||(q : => Parser[String, String]) = new AltParser[String, String](s, q) - def ||(r: String) = new AltParser[String, String](s, r) - def ==>[S] (f: => String => S) = new FunParser[String, String, S](s, f) - def ~[S](q : => Parser[String, S]) = - new SeqParser[String, String, S](s, q) - def ~(r: String) = - new SeqParser[String, String, String](s, r) -} - -// NumParserInt can now be written as _ ===> _ -// the first part is the parser, and the second the -// semantic action -val NumParserInt = NumParser ==> (s => s.toInt) - - -// palindromes -lazy val Pal : Parser[String, String] = - (("a" ~ Pal ~ "a") ==> { case ((x, y), z) => x + y + z } || - ("b" ~ Pal ~ "b") ==> { case ((x, y), z) => x + y + z } || "a" || "b" || "") - -Pal.parse_all("abaaaba") -Pal.parse_all("abacba") -Pal.parse("abaaaba") - -println("Palindrome: " + Pal.parse_all("abaaaba")) - -// parser for well-nested parentheses (transforms '(' -> '{' , ')' -> '}' ) -lazy val P : Parser[String, String] = - "(" ~ P ~ ")" ~ P ==> { case (((_, x), _), y) => "{" + x + "}" + y } || "" - -P.parse_all("(((()()))())") -P.parse_all("(((()()))()))") -P.parse_all(")(") -P.parse_all("()") - -// just counts parentheses -lazy val P2 : Parser[String, Int] = - ("(" ~ P2 ~ ")" ~ P2 ==> { case (((_, x), _), y) => x + y + 2 } || - "" ==> { _ => 0 }) - -P2.parse_all("(((()()))())") -P2.parse_all("(((()()))()))") - -// counts opening and closing parentheses -lazy val P3 : Parser[String, Int] = - ("(" ~ P3 ==> { case (_, x) => x + 1 } || - ")" ~ P3 ==> { case (_, x) => x - 1 } || - "" ==> { _ => 0 }) - -P3.parse_all("(((()()))())") -P3.parse_all("(((()()))()))") -P3.parse_all(")(") - -// Arithmetic Expressions (Terms and Factors) -// (because it is mutually recursive, you need :paste -// for munching this definition in the REPL) - -lazy val E: Parser[String, Int] = - (T ~ "+" ~ E) ==> { case ((x, y), z) => x + z } || - (T ~ "-" ~ E) ==> { case ((x, y), z) => x - z } || T -lazy val T: Parser[String, Int] = - (F ~ "*" ~ T) ==> { case ((x, y), z) => x * z } || F -lazy val F: Parser[String, Int] = - ("(" ~ E ~ ")") ==> { case ((x, y), z) => y } || NumParserInt - -println(E.parse_all("1+3+4")) -println(E.parse("1+3+4")) -println(E.parse_all("4*2+3")) -println(E.parse_all("4*(2+3)")) -println(E.parse_all("(4)*((2+3))")) -println(E.parse_all("4/2+3")) -println(E.parse("1 + 2 * 3")) -println(E.parse_all("(1+2)+3")) -println(E.parse_all("1+2+3")) - -/* same parser but producing a string -lazy val E: Parser[String, String] = - (T ~ "+" ~ E) ==> { case ((x, y), z) => "(" + x + ")+(" + z + ")"} || T -lazy val T: Parser[String, String] = - (F ~ "*" ~ T) ==> { case ((x, y), z) => "(" + x + ")*("+ z + ")"} || F -lazy val F: Parser[String, String] = - ("(" ~ E ~ ")") ==> { case ((x, y), z) => y } || NumParser -*/ - -// no left-recursion allowed, otherwise will loop -lazy val EL: Parser[String, Int] = - (EL ~ "+" ~ EL ==> { case ((x, y), z) => x + z} || - EL ~ "*" ~ EL ==> { case ((x, y), z) => x * z} || - "(" ~ EL ~ ")" ==> { case ((x, y), z) => y} || - NumParserInt) - -//println(EL.parse_all("1+2+3")) - - -// non-ambiguous vs ambiguous grammars - -// ambiguous -lazy val S : Parser[String, String] = - ("1" ~ S ~ S ~ S) ==> { case (((x, y), z), v) => x + y + z } || "" - -S.parse("1" * 10) - -// non-ambiguous -lazy val U : Parser[String, String] = - ("1" ~ U) ==> { case (x, y) => x + y } || "" - -U.parse("1" * 25) - -U.parse("11") -U.parse("11111") -U.parse("11011") - -U.parse_all("1" * 100) -U.parse_all("1" * 100 + "0") - -lazy val UCount : Parser[String, Int] = - ("1" ~ UCount) ==> { case (x, y) => y + 1 } || "" ==> { x => 0 } - -UCount.parse("11111") -UCount.parse_all("11111") - - - -// Single Character parser -lazy val One : Parser[String, String] = "1" -lazy val Two : Parser[String, String] = "2" - -One.parse("1") -One.parse("111") - -(One ~ One).parse("111") -(One ~ One ~ One).parse("1111") -(One ~ One ~ One ~ One).parse("1111") - -(One || Two).parse("111") - - -// a problem with the arithmetic expression parser -> gets -// slow with deeply nested parentheses -E.parse("1") -E.parse("(1)") -E.parse("((1))") -E.parse("(((1)))") -E.parse("((((1))))") -E.parse("((((((1))))))") -E.parse("(((((((1)))))))") - - - - -/* - -starting symbols -tokenise/detokenise -:paste -pairs in sequences - -*/ \ No newline at end of file diff -r 022e2cb1668d -r 5d860ff01938 progs/comb1a.scala --- a/progs/comb1a.scala Sat Jul 04 21:57:33 2020 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,203 +0,0 @@ -import scala.language.implicitConversions -import scala.language.reflectiveCalls - -// more convenience for the semantic actions later on -case class ~[+A, +B](_1: A, _2: B) - - -/* Note, in the lectures I did not show the implicit type consraint - * I => Seq[_], which means that the input type 'I' needs to be - * a sequence. */ - -type IsSeq[A] = A => Seq[_] - -abstract class Parser[I : IsSeq, T] { - def parse(ts: I): Set[(T, I)] - - def parse_all(ts: I) : Set[T] = - for ((head, tail) <- parse(ts); - if tail.isEmpty) yield head -} - - -class SeqParser[I : IsSeq, T, S](p: => Parser[I, T], - q: => Parser[I, S]) extends Parser[I, ~[T, S]] { - def parse(sb: I) = - for ((head1, tail1) <- p.parse(sb); - (head2, tail2) <- q.parse(tail1)) yield (new ~(head1, head2), tail2) -} - -class AltParser[I : IsSeq, T](p: => Parser[I, T], - q: => Parser[I, T]) extends Parser[I, T] { - def parse(sb: I) = p.parse(sb) ++ q.parse(sb) -} - -class FunParser[I : IsSeq, T, S](p: => Parser[I, T], - f: T => S) extends Parser[I, S] { - def parse(sb: I) = - for ((head, tail) <- p.parse(sb)) yield (f(head), tail) -} - -// atomic parsers for characters, numbers and strings -case class CharParser(c: Char) extends Parser[String, Char] { - def parse(sb: String) = - if (sb != "" && sb.head == c) Set((c, sb.tail)) else Set() -} - -import scala.util.matching.Regex -case class RegexParser(reg: Regex) extends Parser[String, String] { - def parse(sb: String) = reg.findPrefixMatchOf(sb) match { - case None => Set() - case Some(m) => Set((m.matched, m.after.toString)) - } -} - -val NumParser = RegexParser("[0-9]+".r) -def StringParser(s: String) = RegexParser(Regex.quote(s).r) - -// NumParserInt2 transforms a "string integer" into an Int; -// needs new, because FunParser is not a case class - -val NumParserInt2 = new FunParser(NumParser, (s: String) => s.toInt) - - -// convenience -implicit def string2parser(s: String) = StringParser(s) -implicit def char2parser(c: Char) = CharParser(c) - -implicit def ParserOps[I : IsSeq, T](p: Parser[I, T]) = new { - def ||(q : => Parser[I, T]) = new AltParser[I, T](p, q) - def ==>[S] (f: => T => S) = new FunParser[I, T, S](p, f) - def ~[S] (q : => Parser[I, S]) = new SeqParser[I, T, S](p, q) -} - -implicit def StringOps(s: String) = new { - def ||(q : => Parser[String, String]) = new AltParser[String, String](s, q) - def ||(r: String) = new AltParser[String, String](s, r) - def ==>[S] (f: => String => S) = new FunParser[String, String, S](s, f) - def ~[S](q : => Parser[String, S]) = - new SeqParser[String, String, S](s, q) - def ~(r: String) = - new SeqParser[String, String, String](s, r) -} - -// NumParserInt can now be written as -val NumParserInt = NumParser ==> (s => s.toInt) - - -lazy val Pal : Parser[String, String] = - (("a" ~ Pal ~ "a") ==> { case x ~ y ~ z => x + y + z } || - ("b" ~ Pal ~ "b") ==> { case x ~ y ~ z => x + y + z } || "a" || "b" || "") - -Pal.parse_all("abaaaba") -Pal.parse("abaaaba") - -println("Palindrome: " + Pal.parse_all("abaaaba")) - -// well-nested parentheses parser (transforms '(' -> '{' , ')' -> '}' ) -lazy val P : Parser[String, String] = - "(" ~ P ~ ")" ~ P ==> { case _ ~ x ~ _ ~ y => "{" + x + "}" + y } || "" - -P.parse_all("(((()()))())") -P.parse_all("(((()()))()))") -P.parse_all(")(") -P.parse_all("()") - -// Arithmetic Expressions (Terms and Factors) - -lazy val E: Parser[String, Int] = - (T ~ "+" ~ E) ==> { case x ~ _ ~ z => x + z } || - (T ~ "-" ~ E) ==> { case x ~ _ ~ z => x - z } || T -lazy val T: Parser[String, Int] = - (F ~ "*" ~ T) ==> { case x ~ _ ~ z => x * z } || F -lazy val F: Parser[String, Int] = - ("(" ~ E ~ ")") ==> { case _ ~ y ~ _ => y } || NumParserInt - -/* same parser but producing a string -lazy val E: Parser[String, String] = - (T ~ "+" ~ E) ==> { case x ~ y ~ z => "(" + x + ")+(" + z + ")"} || T -lazy val T: Parser[String, String] = - (F ~ "*" ~ T) ==> { case x ~ y ~ z => "(" + x + ")*("+ z + ")"} || F -lazy val F: Parser[String, String] = - ("(" ~ E ~ ")") ==> { case x ~ y ~ z => y } || NumParser -*/ - -println(E.parse_all("1+3+4")) -println(E.parse("1+3+4")) -println(E.parse_all("4*2+3")) -println(E.parse_all("4*(2+3)")) -println(E.parse_all("(4)*((2+3))")) -println(E.parse_all("4/2+3")) -println(E.parse("1 + 2 * 3")) -println(E.parse_all("(1+2)+3")) -println(E.parse_all("1+2+3")) - - - -// no left-recursion allowed, otherwise will loop -lazy val EL: Parser[String, Int] = - (EL ~ "+" ~ EL ==> { case x ~ y ~ z => x + z} || - EL ~ "*" ~ EL ==> { case x ~ y ~ z => x * z} || - "(" ~ EL ~ ")" ==> { case x ~ y ~ z => y} || - NumParserInt) - -//println(EL.parse_all("1+2+3")) - - - - -// non-ambiguous vs ambiguous grammars - -// ambiguous -lazy val S : Parser[String, String] = - ("1" ~ S ~ S) ==> { case x ~ y ~ z => x + y + z } || "" - -S.parse("1" * 10) - -// non-ambiguous -lazy val U : Parser[String, String] = - ("1" ~ U) ==> { case x ~ y => x + y } || "" - -U.parse("1" * 25) - -U.parse("11") -U.parse("11111") -U.parse("11011") - -U.parse_all("1" * 100) -U.parse_all("1" * 100 + "0") - -lazy val UCount : Parser[String, Int] = - ("1" ~ UCount) ==> { case x ~ y => y + 1 } || "" ==> { x => 0 } - -UCount.parse("11111") -UCount.parse_all("11111") - - - -// Single Character parser -lazy val One : Parser[String, String] = "1" -lazy val Two : Parser[String, String] = "2" - -One.parse("1") -One.parse("111") - -(One ~ One).parse("111") -(One ~ One ~ One).parse("111") -(One ~ One ~ One ~ One).parse("1111") - -(One || Two).parse("111") - - - -// a problem with the arithmetic expression parser -> gets -// slow with deeply nested parentheses -println("Runtime problem") -E.parse("1") -E.parse("(1)") -E.parse("((1))") -E.parse("(((1)))") -E.parse("((((1))))") -E.parse("((((((1))))))") -E.parse("(((((((1)))))))") -E.parse("((((((((1)))))))") diff -r 022e2cb1668d -r 5d860ff01938 progs/comb2.scala --- a/progs/comb2.scala Sat Jul 04 21:57:33 2020 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,245 +0,0 @@ -// A parser and interpreter for the While language -// - -import scala.language.implicitConversions -import scala.language.reflectiveCalls - -// more convenience for the semantic actions later on -case class ~[+A, +B](_1: A, _2: B) - - -type IsSeq[A] = A => Seq[_] - -abstract class Parser[I : IsSeq, T] { - def parse(ts: I): Set[(T, I)] - - def parse_all(ts: I) : Set[T] = - for ((head, tail) <- parse(ts); if tail.isEmpty) yield head -} - -class SeqParser[I : IsSeq, T, S](p: => Parser[I, T], q: => Parser[I, S]) extends Parser[I, ~[T, S]] { - def parse(sb: I) = - for ((head1, tail1) <- p.parse(sb); - (head2, tail2) <- q.parse(tail1)) yield (new ~(head1, head2), tail2) -} - -class AltParser[I : IsSeq, T](p: => Parser[I, T], q: => Parser[I, T]) extends Parser[I, T] { - def parse(sb: I) = p.parse(sb) ++ q.parse(sb) -} - -class FunParser[I : IsSeq, T, S](p: => Parser[I, T], f: T => S) extends Parser[I, S] { - def parse(sb: I) = - for ((head, tail) <- p.parse(sb)) yield (f(head), tail) -} - -case class StringParser(s: String) extends Parser[String, String] { - def parse(sb: String) = { - val (prefix, suffix) = sb.splitAt(s.length) - if (prefix == s) Set((prefix, suffix)) else Set() - } -} - -case object NumParser extends Parser[String, Int] { - val reg = "[0-9]+".r - def parse(sb: String) = reg.findPrefixOf(sb) match { - case None => Set() - case Some(s) => { - val (head, tail) = sb.splitAt(s.length) - Set((head.toInt, tail)) - } - } -} - - -implicit def string2parser(s : String) = StringParser(s) - -implicit def ParserOps[I : IsSeq, T](p: Parser[I, T]) = new { - def ||(q : => Parser[I, T]) = new AltParser[I, T](p, q) - def ==>[S] (f: => T => S) = new FunParser[I, T, S](p, f) - def ~[S](q : => Parser[I, S]) = new SeqParser[I, T, S](p, q) -} - -implicit def StringOps(s: String) = new { - def ||(q : => Parser[String, String]) = new AltParser[String, String](s, q) - def ||(r: String) = new AltParser[String, String](s, r) - def ==>[S] (f: => String => S) = new FunParser[String, String, S](s, f) - def ~[S](q : => Parser[String, S]) = - new SeqParser[String, String, S](s, q) - def ~(r: String) = - new SeqParser[String, String, String](s, r) -} - - -// the abstract syntax trees for the WHILE language -abstract class Stmt -abstract class AExp -abstract class BExp - -type Block = List[Stmt] - -case object Skip extends Stmt -case class If(a: BExp, bl1: Block, bl2: Block) extends Stmt -case class While(b: BExp, bl: Block) extends Stmt -case class Assign(s: String, a: AExp) extends Stmt -case class Write(s: String) extends Stmt - - -case class Var(s: String) extends AExp -case class Num(i: Int) extends AExp -case class Aop(o: String, a1: AExp, a2: AExp) extends AExp - -case object True extends BExp -case object False extends BExp -case class Bop(o: String, a1: AExp, a2: AExp) extends BExp -case class And(b1: BExp, b2: BExp) extends BExp -case class Or(b1: BExp, b2: BExp) extends BExp - -case object IdParser extends Parser[String, String] { - val reg = "[a-z][a-z,0-9]*".r - def parse(sb: String) = reg.findPrefixOf(sb) match { - case None => Set() - case Some(s) => Set(sb.splitAt(s.length)) - } -} - -// arithmetic expressions -lazy val AExp: Parser[String, AExp] = - (Te ~ "+" ~ AExp) ==> { case x ~ _ ~ z => Aop("+", x, z): AExp } || - (Te ~ "-" ~ AExp) ==> { case x ~ _ ~ z => Aop("-", x, z): AExp } || Te -lazy val Te: Parser[String, AExp] = - (Fa ~ "*" ~ Te) ==> { case x ~ _ ~ z => Aop("*", x, z): AExp } || - (Fa ~ "/" ~ Te) ==> { case x ~ _ ~ z => Aop("/", x, z): AExp } || Fa -lazy val Fa: Parser[String, AExp] = - ("(" ~ AExp ~ ")") ==> { case _ ~ y ~ _ => y } || - IdParser ==> Var || - NumParser ==> Num - -// boolean expressions with some simple nesting -lazy val BExp: Parser[String, BExp] = - (AExp ~ "==" ~ AExp) ==> { case x ~ _ ~ z => Bop("==", x, z): BExp } || - (AExp ~ "!=" ~ AExp) ==> { case x ~ _ ~ z => Bop("!=", x, z): BExp } || - (AExp ~ "<" ~ AExp) ==> { case x ~ _ ~ z => Bop("<", x, z): BExp } || - (AExp ~ ">" ~ AExp) ==> { case x ~ _ ~ z => Bop(">", x, z): BExp } || - ("(" ~ BExp ~ ")" ~ "&&" ~ BExp) ==> { case _ ~ y ~ _ ~ _ ~ v => And(y, v): BExp } || - ("(" ~ BExp ~ ")" ~ "||" ~ BExp) ==> { case _ ~ y ~ _ ~ _ ~ v => Or(y, v): BExp } || - ("true" ==> (_ => True: BExp )) || - ("false" ==> (_ => False: BExp )) || - ("(" ~ BExp ~ ")") ==> { case _ ~ x ~ _ => x } - -// statement / statements -lazy val Stmt: Parser[String, Stmt] = - (("skip" ==> (_ => Skip: Stmt)) || - (IdParser ~ ":=" ~ AExp) ==> { case x ~ _ ~ z => Assign(x, z): Stmt } || - ("write(" ~ IdParser ~ ")") ==> { case _ ~ y ~ _ => Write(y): Stmt } || - ("if" ~ BExp ~ "then" ~ Block ~ "else" ~ Block) ==> - { case _ ~ y ~ _ ~ u ~ _ ~ w => If(y, u, w): Stmt } || - ("while" ~ BExp ~ "do" ~ Block) ==> { case _ ~ y ~ _ ~ w => While(y, w) }) - -lazy val Stmts: Parser[String, Block] = - (Stmt ~ ";" ~ Stmts) ==> { case x ~ _ ~ z => x :: z : Block } || - (Stmt ==> ( s => List(s) : Block)) - -// blocks (enclosed in curly braces) -lazy val Block: Parser[String, Block] = - (("{" ~ Stmts ~ "}") ==> { case _ ~ y ~ _ => y } || - (Stmt ==> (s => List(s)))) - - -Stmts.parse_all("x2:=5+3;") -Block.parse_all("{x:=5;y:=8}") -Block.parse_all("if(false)then{x:=5}else{x:=10}") - -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""".replaceAll("\\s+", "") - -Stmts.parse_all(fib) - - -// an interpreter for the WHILE language -type Env = Map[String, Int] - -def eval_aexp(a: AExp, env: Env) : Int = a match { - case Num(i) => i - case Var(s) => env(s) - case Aop("+", a1, a2) => eval_aexp(a1, env) + eval_aexp(a2, env) - case Aop("-", a1, a2) => eval_aexp(a1, env) - eval_aexp(a2, env) - case Aop("*", a1, a2) => eval_aexp(a1, env) * eval_aexp(a2, env) - case Aop("/", a1, a2) => eval_aexp(a1, env) / eval_aexp(a2, env) -} - -def eval_bexp(b: BExp, env: Env) : Boolean = b match { - case True => true - case False => false - case Bop("==", a1, a2) => eval_aexp(a1, env) == eval_aexp(a2, env) - case Bop("!=", a1, a2) => !(eval_aexp(a1, env) == eval_aexp(a2, env)) - case Bop(">", a1, a2) => eval_aexp(a1, env) > eval_aexp(a2, env) - case Bop("<", a1, a2) => eval_aexp(a1, env) < eval_aexp(a2, env) - case And(b1, b2) => eval_bexp(b1, env) && eval_bexp(b2, env) - case Or(b1, b2) => eval_bexp(b1, env) || eval_bexp(b2, env) -} - -def eval_stmt(s: Stmt, env: Env) : Env = s match { - case Skip => env - case Assign(x, a) => env + (x -> eval_aexp(a, env)) - case If(b, bl1, bl2) => if (eval_bexp(b, env)) eval_bl(bl1, env) else eval_bl(bl2, env) - case While(b, bl) => - if (eval_bexp(b, env)) eval_stmt(While(b, bl), eval_bl(bl, env)) - else env - case Write(x) => { println(env(x)) ; env } -} - -def eval_bl(bl: Block, env: Env) : Env = bl match { - case Nil => env - case s::bl => eval_bl(bl, eval_stmt(s, env)) -} - -def eval(bl: Block) : Env = eval_bl(bl, Map()) - -// parse + evaluate fib program; then lookup what is -// stored under the variable result -println(eval(Stmts.parse_all(fib).head)("result")) - - -// more examles - -// calculate and print all factors bigger -// than 1 and smaller than n -println("Factors") - -val factors = - """n := 12; - f := 2; - while (f < n / 2 + 1) do { - if ((n / f) * f == n) then { write(f) } else { skip }; - f := f + 1 - }""".replaceAll("\\s+", "") - -eval(Stmts.parse_all(factors).head) - -// calculate all prime numbers up to a number -println("Primes") - -val primes = - """end := 100; - n := 2; - while (n < end) do { - f := 2; - tmp := 0; - while ((f < n / 2 + 1) && (tmp == 0)) do { - if ((n / f) * f == n) then { tmp := 1 } else { skip }; - f := f + 1 - }; - if (tmp == 0) then { write(n) } else { skip }; - n := n + 1 - }""".replaceAll("\\s+", "") - -eval(Stmts.parse_all(primes).head) diff -r 022e2cb1668d -r 5d860ff01938 progs/fun-bare.scala --- a/progs/fun-bare.scala Sat Jul 04 21:57:33 2020 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,187 +0,0 @@ -// A Small Compiler for a Simple Functional Language -// (it does not include a parser and lexer) - -// abstract syntax trees -abstract class Exp -abstract class BExp -abstract class Decl - -// functions and declarations -case class Def(name: String, args: List[String], body: Exp) extends Decl -case class Main(e: Exp) extends Decl - -// expressions -case class Call(name: String, args: List[Exp]) extends Exp -case class If(a: BExp, e1: Exp, e2: Exp) extends Exp -case class Write(e: Exp) extends Exp -case class Var(s: String) extends Exp -case class Num(i: Int) extends Exp -case class Aop(o: String, a1: Exp, a2: Exp) extends Exp -case class Sequ(e1: Exp, e2: Exp) extends Exp - -// boolean expressions -case class Bop(o: String, a1: Exp, a2: Exp) extends BExp - -// calculating the maximal needed stack size -def max_stack_exp(e: Exp): Int = e match { - case Call(_, args) => args.map(max_stack_exp).sum - case If(a, e1, e2) => max_stack_bexp(a) + (List(max_stack_exp(e1), max_stack_exp(e2)).max) - case Write(e) => max_stack_exp(e) + 1 - case Var(_) => 1 - case Num(_) => 1 - case Aop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2) - case Sequ(e1, e2) => List(max_stack_exp(e1), max_stack_exp(e2)).max -} -def max_stack_bexp(e: BExp): Int = e match { - case Bop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2) -} - -// compiler - built-in functions -// copied from http://www.ceng.metu.edu.tr/courses/ceng444/link/jvm-cpm.html -// - -val library = """ -.class public XXX.XXX -.super java/lang/Object - -.method public static write(I)V - .limit locals 5 - .limit stack 5 - iload 0 - getstatic java/lang/System/out Ljava/io/PrintStream; - swap - invokevirtual java/io/PrintStream/println(I)V - return -.end method - -""" - -// for generating new labels -var counter = -1 - -def Fresh(x: String) = { - counter += 1 - x ++ "_" ++ counter.toString() -} - -// convenient string interpolations for -// generating instructions, labels etc -import scala.language.implicitConversions -import scala.language.reflectiveCalls - -// convenience for code-generation (string interpolations) -implicit def sring_inters(sc: StringContext) = new { - def i(args: Any*): String = " " ++ sc.s(args:_*) ++ "\n" // instructions - def l(args: Any*): String = sc.s(args:_*) ++ ":\n" // labels - def m(args: Any*): String = sc.s(args:_*) ++ "\n" // methods -} - -// variable / index environments -type Env = Map[String, Int] - -// compile expressions -def compile_exp(a: Exp, env : Env) : String = a match { - case Num(i) => i"ldc $i" - case Var(s) => i"iload ${env(s)}" - case Aop("+", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"iadd" - case Aop("-", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"isub" - case Aop("*", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"imul" - case Aop("/", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"idiv" - case Aop("%", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"irem" - case If(b, a1, a2) => { - val if_else = Fresh("If_else") - val if_end = Fresh("If_end") - compile_bexp(b, env, if_else) ++ - compile_exp(a1, env) ++ - i"goto $if_end" ++ - l"$if_else" ++ - compile_exp(a2, env) ++ - l"$if_end" - } - case Call(name, args) => { - val is = "I" * args.length - args.map(a => compile_exp(a, env)).mkString ++ - i"invokestatic XXX/XXX/$name($is)I" - } - case Sequ(a1, a2) => { - compile_exp(a1, env) ++ i"pop" ++ compile_exp(a2, env) - } - case Write(a1) => { - compile_exp(a1, env) ++ - i"dup" ++ - i"invokestatic XXX/XXX/write(I)V" - } -} - -// compile boolean expressions -def compile_bexp(b: BExp, env : Env, jmp: String) : String = b match { - case Bop("==", a1, a2) => - compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpne $jmp" - case Bop("!=", a1, a2) => - compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpeq $jmp" - case Bop("<", a1, a2) => - compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpge $jmp" - case Bop("<=", a1, a2) => - compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpgt $jmp" -} - -// compile functions and declarations -def compile_decl(d: Decl) : String = d match { - case Def(name, args, a) => { - val env = args.zipWithIndex.toMap - val is = "I" * args.length - m".method public static $name($is)I" ++ - m".limit locals ${args.length.toString}" ++ - m".limit stack ${1 + max_stack_exp(a)}" ++ - l"${name}_Start" ++ - compile_exp(a, env) ++ - i"ireturn" ++ - m".end method\n" - } - case Main(a) => { - m".method public static main([Ljava/lang/String;)V" ++ - m".limit locals 200" ++ - m".limit stack 200" ++ - compile_exp(a, Map()) ++ - i"invokestatic XXX/XXX/write(I)V" ++ - i"return" ++ - m".end method\n" - } -} - -// the main compilation function -def compile(prog: List[Decl], class_name: String) : String = { - val instructions = prog.map(compile_decl).mkString - (library + instructions).replaceAllLiterally("XXX", class_name) -} - - - - -// An example program (factorials) -// -// def fact(n) = if n == 0 then 1 else n * fact(n - 1); -// def facT(n, acc) = if n == 0 then acc else facT(n - 1, n * acc); -// -// fact(10) ; facT(15, 1) -// - - -val test_prog = - List(Def("fact", List("n"), - If(Bop("==",Var("n"),Num(0)), - Num(1), - Aop("*",Var("n"), - Call("fact",List(Aop("-",Var("n"),Num(1))))))), - - Def("facT",List("n", "acc"), - If(Bop("==",Var("n"),Num(0)), - Var("acc"), - Call("facT",List(Aop("-",Var("n"),Num(1)), - Aop("*",Var("n"),Var("acc")))))), - - Main(Sequ(Write(Call("fact",List(Num(10)))), - Write(Call("facT",List(Num(10), Num(1))))))) - -// prints out the JVM instructions -println(compile(test_prog, "fact")) diff -r 022e2cb1668d -r 5d860ff01938 progs/fun.scala --- a/progs/fun.scala Sat Jul 04 21:57:33 2020 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,213 +0,0 @@ -// A Small Compiler for a Simple Functional Language -// (includes an external lexer and parser) -// -// call with -// -// scala fun.scala fact -// -// scala fun.scala defs -// -// this will generate a .j file and run the jasmin -// assembler (installed at jvm/jasmin-2.4/jasmin.jar) -// it runs the resulting JVM file twice for timing -// purposes. - - - - -object Compiler { - -import java.io._ -import scala.util._ -import scala.sys.process._ - -// Abstract syntax trees for the Fun language -abstract class Exp extends Serializable -abstract class BExp extends Serializable -abstract class Decl extends Serializable - -case class Def(name: String, args: List[String], body: Exp) extends Decl -case class Main(e: Exp) extends Decl - -case class Call(name: String, args: List[Exp]) extends Exp -case class If(a: BExp, e1: Exp, e2: Exp) extends Exp -case class Write(e: Exp) extends Exp -case class Var(s: String) extends Exp -case class Num(i: Int) extends Exp -case class Aop(o: String, a1: Exp, a2: Exp) extends Exp -case class Sequence(e1: Exp, e2: Exp) extends Exp -case class Bop(o: String, a1: Exp, a2: Exp) extends BExp - - -// compiler - built-in functions -// copied from http://www.ceng.metu.edu.tr/courses/ceng444/link/jvm-cpm.html -// - -val library = """ -.class public XXX.XXX -.super java/lang/Object - -.method public static write(I)V - .limit locals 1 - .limit stack 2 - getstatic java/lang/System/out Ljava/io/PrintStream; - iload 0 - invokevirtual java/io/PrintStream/println(I)V - return -.end method - -""" - -// calculating the maximal needed stack size -def max_stack_exp(e: Exp): Int = e match { - case Call(_, args) => args.map(max_stack_exp).sum - case If(a, e1, e2) => max_stack_bexp(a) + (List(max_stack_exp(e1), max_stack_exp(e2)).max) - case Write(e) => max_stack_exp(e) + 1 - case Var(_) => 1 - case Num(_) => 1 - case Aop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2) - case Sequence(e1, e2) => List(max_stack_exp(e1), max_stack_exp(e2)).max -} - -def max_stack_bexp(e: BExp): Int = e match { - case Bop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2) -} - - -// for generating new labels -var counter = -1 - -def Fresh(x: String) = { - counter += 1 - x ++ "_" ++ counter.toString() -} - -// convenient string interpolations -// for instructions, labels and methods -import scala.language.implicitConversions -import scala.language.reflectiveCalls - -implicit def sring_inters(sc: StringContext) = new { - def i(args: Any*): String = " " ++ sc.s(args:_*) ++ "\n" - def l(args: Any*): String = sc.s(args:_*) ++ ":\n" - def m(args: Any*): String = sc.s(args:_*) ++ "\n" -} - - -type Env = Map[String, Int] - -// compile expressions -def compile_exp(a: Exp, env : Env) : String = a match { - case Num(i) => i"ldc $i" - case Var(s) => i"iload ${env(s)}" - case Aop("+", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"iadd" - case Aop("-", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"isub" - case Aop("*", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"imul" - case Aop("/", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"idiv" - case Aop("%", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"irem" - case If(b, a1, a2) => { - val if_else = Fresh("If_else") - val if_end = Fresh("If_end") - compile_bexp(b, env, if_else) ++ - compile_exp(a1, env) ++ - i"goto $if_end" ++ - l"$if_else" ++ - compile_exp(a2, env) ++ - l"$if_end" - } - case Call(name, args) => { - val is = "I" * args.length - args.map(a => compile_exp(a, env)).mkString ++ - i"invokestatic XXX/XXX/$name($is)I" - } - case Sequence(a1, a2) => { - compile_exp(a1, env) ++ i"pop" ++ compile_exp(a2, env) - } - case Write(a1) => { - compile_exp(a1, env) ++ - i"dup" ++ - i"invokestatic XXX/XXX/write(I)V" - } -} - -// compile boolean expressions -def compile_bexp(b: BExp, env : Env, jmp: String) : String = b match { - case Bop("==", a1, a2) => - compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpne $jmp" - case Bop("!=", a1, a2) => - compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpeq $jmp" - case Bop("<", a1, a2) => - compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpge $jmp" - case Bop("<=", a1, a2) => - compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpgt $jmp" -} - -// compile function for declarations and main -def compile_decl(d: Decl) : String = d match { - case Def(name, args, a) => { - val env = args.zipWithIndex.toMap - val is = "I" * args.length - m".method public static $name($is)I" ++ - m".limit locals ${args.length}" ++ - m".limit stack ${1 + max_stack_exp(a)}" ++ - l"${name}_Start" ++ - compile_exp(a, env) ++ - i"ireturn" ++ - m".end method\n" - } - case Main(a) => { - m".method public static main([Ljava/lang/String;)V" ++ - m".limit locals 200" ++ - m".limit stack 200" ++ - compile_exp(a, Map()) ++ - i"invokestatic XXX/XXX/write(I)V" ++ - i"return" ++ - m".end method\n" - } -} - -// main compiler functions - -def time_needed[T](i: Int, code: => T) = { - val start = System.nanoTime() - for (j <- 1 to i) code - val end = System.nanoTime() - (end - start)/(i * 1.0e9) -} - -def deserialise[T](fname: String) : Try[T] = { - import scala.util.Using - Using(new ObjectInputStream(new FileInputStream(fname))) { - in => in.readObject.asInstanceOf[T] - } -} - -def compile(class_name: String) : String = { - val ast = deserialise[List[Decl]](class_name ++ ".prs").getOrElse(Nil) - val instructions = ast.map(compile_decl).mkString - (library + instructions).replaceAllLiterally("XXX", class_name) -} - -def compile_to_file(class_name: String) = { - val output = compile(class_name) - scala.tools.nsc.io.File(s"${class_name}.j").writeAll(output) -} - -def compile_and_run(class_name: String) : Unit = { - compile_to_file(class_name) - (s"java -jar jvm/jasmin-2.4/jasmin.jar ${class_name}.j").!! - println("Time: " + time_needed(1, (s"java ${class_name}/${class_name}").!)) -} - - -// some examples of .fun files -//compile_to_file("fact") -//compile_and_run("fact") -//compile_and_run("defs") - - -def main(args: Array[String]) : Unit = - compile_and_run(args(0)) - - -} diff -r 022e2cb1668d -r 5d860ff01938 progs/fun/fun-bare.scala --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/progs/fun/fun-bare.scala Sat Jul 04 22:12:18 2020 +0100 @@ -0,0 +1,187 @@ +// A Small Compiler for a Simple Functional Language +// (it does not include a parser and lexer) + +// abstract syntax trees +abstract class Exp +abstract class BExp +abstract class Decl + +// functions and declarations +case class Def(name: String, args: List[String], body: Exp) extends Decl +case class Main(e: Exp) extends Decl + +// expressions +case class Call(name: String, args: List[Exp]) extends Exp +case class If(a: BExp, e1: Exp, e2: Exp) extends Exp +case class Write(e: Exp) extends Exp +case class Var(s: String) extends Exp +case class Num(i: Int) extends Exp +case class Aop(o: String, a1: Exp, a2: Exp) extends Exp +case class Sequ(e1: Exp, e2: Exp) extends Exp + +// boolean expressions +case class Bop(o: String, a1: Exp, a2: Exp) extends BExp + +// calculating the maximal needed stack size +def max_stack_exp(e: Exp): Int = e match { + case Call(_, args) => args.map(max_stack_exp).sum + case If(a, e1, e2) => max_stack_bexp(a) + (List(max_stack_exp(e1), max_stack_exp(e2)).max) + case Write(e) => max_stack_exp(e) + 1 + case Var(_) => 1 + case Num(_) => 1 + case Aop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2) + case Sequ(e1, e2) => List(max_stack_exp(e1), max_stack_exp(e2)).max +} +def max_stack_bexp(e: BExp): Int = e match { + case Bop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2) +} + +// compiler - built-in functions +// copied from http://www.ceng.metu.edu.tr/courses/ceng444/link/jvm-cpm.html +// + +val library = """ +.class public XXX.XXX +.super java/lang/Object + +.method public static write(I)V + .limit locals 5 + .limit stack 5 + iload 0 + getstatic java/lang/System/out Ljava/io/PrintStream; + swap + invokevirtual java/io/PrintStream/println(I)V + return +.end method + +""" + +// for generating new labels +var counter = -1 + +def Fresh(x: String) = { + counter += 1 + x ++ "_" ++ counter.toString() +} + +// convenient string interpolations for +// generating instructions, labels etc +import scala.language.implicitConversions +import scala.language.reflectiveCalls + +// convenience for code-generation (string interpolations) +implicit def sring_inters(sc: StringContext) = new { + def i(args: Any*): String = " " ++ sc.s(args:_*) ++ "\n" // instructions + def l(args: Any*): String = sc.s(args:_*) ++ ":\n" // labels + def m(args: Any*): String = sc.s(args:_*) ++ "\n" // methods +} + +// variable / index environments +type Env = Map[String, Int] + +// compile expressions +def compile_exp(a: Exp, env : Env) : String = a match { + case Num(i) => i"ldc $i" + case Var(s) => i"iload ${env(s)}" + case Aop("+", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"iadd" + case Aop("-", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"isub" + case Aop("*", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"imul" + case Aop("/", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"idiv" + case Aop("%", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"irem" + case If(b, a1, a2) => { + val if_else = Fresh("If_else") + val if_end = Fresh("If_end") + compile_bexp(b, env, if_else) ++ + compile_exp(a1, env) ++ + i"goto $if_end" ++ + l"$if_else" ++ + compile_exp(a2, env) ++ + l"$if_end" + } + case Call(name, args) => { + val is = "I" * args.length + args.map(a => compile_exp(a, env)).mkString ++ + i"invokestatic XXX/XXX/$name($is)I" + } + case Sequ(a1, a2) => { + compile_exp(a1, env) ++ i"pop" ++ compile_exp(a2, env) + } + case Write(a1) => { + compile_exp(a1, env) ++ + i"dup" ++ + i"invokestatic XXX/XXX/write(I)V" + } +} + +// compile boolean expressions +def compile_bexp(b: BExp, env : Env, jmp: String) : String = b match { + case Bop("==", a1, a2) => + compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpne $jmp" + case Bop("!=", a1, a2) => + compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpeq $jmp" + case Bop("<", a1, a2) => + compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpge $jmp" + case Bop("<=", a1, a2) => + compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpgt $jmp" +} + +// compile functions and declarations +def compile_decl(d: Decl) : String = d match { + case Def(name, args, a) => { + val env = args.zipWithIndex.toMap + val is = "I" * args.length + m".method public static $name($is)I" ++ + m".limit locals ${args.length.toString}" ++ + m".limit stack ${1 + max_stack_exp(a)}" ++ + l"${name}_Start" ++ + compile_exp(a, env) ++ + i"ireturn" ++ + m".end method\n" + } + case Main(a) => { + m".method public static main([Ljava/lang/String;)V" ++ + m".limit locals 200" ++ + m".limit stack 200" ++ + compile_exp(a, Map()) ++ + i"invokestatic XXX/XXX/write(I)V" ++ + i"return" ++ + m".end method\n" + } +} + +// the main compilation function +def compile(prog: List[Decl], class_name: String) : String = { + val instructions = prog.map(compile_decl).mkString + (library + instructions).replaceAllLiterally("XXX", class_name) +} + + + + +// An example program (factorials) +// +// def fact(n) = if n == 0 then 1 else n * fact(n - 1); +// def facT(n, acc) = if n == 0 then acc else facT(n - 1, n * acc); +// +// fact(10) ; facT(15, 1) +// + + +val test_prog = + List(Def("fact", List("n"), + If(Bop("==",Var("n"),Num(0)), + Num(1), + Aop("*",Var("n"), + Call("fact",List(Aop("-",Var("n"),Num(1))))))), + + Def("facT",List("n", "acc"), + If(Bop("==",Var("n"),Num(0)), + Var("acc"), + Call("facT",List(Aop("-",Var("n"),Num(1)), + Aop("*",Var("n"),Var("acc")))))), + + Main(Sequ(Write(Call("fact",List(Num(10)))), + Write(Call("facT",List(Num(10), Num(1))))))) + +// prints out the JVM instructions +println(compile(test_prog, "fact")) diff -r 022e2cb1668d -r 5d860ff01938 progs/fun/fun.scala --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/progs/fun/fun.scala Sat Jul 04 22:12:18 2020 +0100 @@ -0,0 +1,213 @@ +// A Small Compiler for a Simple Functional Language +// (includes an external lexer and parser) +// +// call with +// +// scala fun.scala fact +// +// scala fun.scala defs +// +// this will generate a .j file and run the jasmin +// assembler (installed at jvm/jasmin-2.4/jasmin.jar) +// it runs the resulting JVM file twice for timing +// purposes. + + + + +object Compiler { + +import java.io._ +import scala.util._ +import scala.sys.process._ + +// Abstract syntax trees for the Fun language +abstract class Exp extends Serializable +abstract class BExp extends Serializable +abstract class Decl extends Serializable + +case class Def(name: String, args: List[String], body: Exp) extends Decl +case class Main(e: Exp) extends Decl + +case class Call(name: String, args: List[Exp]) extends Exp +case class If(a: BExp, e1: Exp, e2: Exp) extends Exp +case class Write(e: Exp) extends Exp +case class Var(s: String) extends Exp +case class Num(i: Int) extends Exp +case class Aop(o: String, a1: Exp, a2: Exp) extends Exp +case class Sequence(e1: Exp, e2: Exp) extends Exp +case class Bop(o: String, a1: Exp, a2: Exp) extends BExp + + +// compiler - built-in functions +// copied from http://www.ceng.metu.edu.tr/courses/ceng444/link/jvm-cpm.html +// + +val library = """ +.class public XXX.XXX +.super java/lang/Object + +.method public static write(I)V + .limit locals 1 + .limit stack 2 + getstatic java/lang/System/out Ljava/io/PrintStream; + iload 0 + invokevirtual java/io/PrintStream/println(I)V + return +.end method + +""" + +// calculating the maximal needed stack size +def max_stack_exp(e: Exp): Int = e match { + case Call(_, args) => args.map(max_stack_exp).sum + case If(a, e1, e2) => max_stack_bexp(a) + (List(max_stack_exp(e1), max_stack_exp(e2)).max) + case Write(e) => max_stack_exp(e) + 1 + case Var(_) => 1 + case Num(_) => 1 + case Aop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2) + case Sequence(e1, e2) => List(max_stack_exp(e1), max_stack_exp(e2)).max +} + +def max_stack_bexp(e: BExp): Int = e match { + case Bop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2) +} + + +// for generating new labels +var counter = -1 + +def Fresh(x: String) = { + counter += 1 + x ++ "_" ++ counter.toString() +} + +// convenient string interpolations +// for instructions, labels and methods +import scala.language.implicitConversions +import scala.language.reflectiveCalls + +implicit def sring_inters(sc: StringContext) = new { + def i(args: Any*): String = " " ++ sc.s(args:_*) ++ "\n" + def l(args: Any*): String = sc.s(args:_*) ++ ":\n" + def m(args: Any*): String = sc.s(args:_*) ++ "\n" +} + + +type Env = Map[String, Int] + +// compile expressions +def compile_exp(a: Exp, env : Env) : String = a match { + case Num(i) => i"ldc $i" + case Var(s) => i"iload ${env(s)}" + case Aop("+", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"iadd" + case Aop("-", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"isub" + case Aop("*", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"imul" + case Aop("/", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"idiv" + case Aop("%", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"irem" + case If(b, a1, a2) => { + val if_else = Fresh("If_else") + val if_end = Fresh("If_end") + compile_bexp(b, env, if_else) ++ + compile_exp(a1, env) ++ + i"goto $if_end" ++ + l"$if_else" ++ + compile_exp(a2, env) ++ + l"$if_end" + } + case Call(name, args) => { + val is = "I" * args.length + args.map(a => compile_exp(a, env)).mkString ++ + i"invokestatic XXX/XXX/$name($is)I" + } + case Sequence(a1, a2) => { + compile_exp(a1, env) ++ i"pop" ++ compile_exp(a2, env) + } + case Write(a1) => { + compile_exp(a1, env) ++ + i"dup" ++ + i"invokestatic XXX/XXX/write(I)V" + } +} + +// compile boolean expressions +def compile_bexp(b: BExp, env : Env, jmp: String) : String = b match { + case Bop("==", a1, a2) => + compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpne $jmp" + case Bop("!=", a1, a2) => + compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpeq $jmp" + case Bop("<", a1, a2) => + compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpge $jmp" + case Bop("<=", a1, a2) => + compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpgt $jmp" +} + +// compile function for declarations and main +def compile_decl(d: Decl) : String = d match { + case Def(name, args, a) => { + val env = args.zipWithIndex.toMap + val is = "I" * args.length + m".method public static $name($is)I" ++ + m".limit locals ${args.length}" ++ + m".limit stack ${1 + max_stack_exp(a)}" ++ + l"${name}_Start" ++ + compile_exp(a, env) ++ + i"ireturn" ++ + m".end method\n" + } + case Main(a) => { + m".method public static main([Ljava/lang/String;)V" ++ + m".limit locals 200" ++ + m".limit stack 200" ++ + compile_exp(a, Map()) ++ + i"invokestatic XXX/XXX/write(I)V" ++ + i"return" ++ + m".end method\n" + } +} + +// main compiler functions + +def time_needed[T](i: Int, code: => T) = { + val start = System.nanoTime() + for (j <- 1 to i) code + val end = System.nanoTime() + (end - start)/(i * 1.0e9) +} + +def deserialise[T](fname: String) : Try[T] = { + import scala.util.Using + Using(new ObjectInputStream(new FileInputStream(fname))) { + in => in.readObject.asInstanceOf[T] + } +} + +def compile(class_name: String) : String = { + val ast = deserialise[List[Decl]](class_name ++ ".prs").getOrElse(Nil) + val instructions = ast.map(compile_decl).mkString + (library + instructions).replaceAllLiterally("XXX", class_name) +} + +def compile_to_file(class_name: String) = { + val output = compile(class_name) + scala.tools.nsc.io.File(s"${class_name}.j").writeAll(output) +} + +def compile_and_run(class_name: String) : Unit = { + compile_to_file(class_name) + (s"java -jar jvm/jasmin-2.4/jasmin.jar ${class_name}.j").!! + println("Time: " + time_needed(1, (s"java ${class_name}/${class_name}").!)) +} + + +// some examples of .fun files +//compile_to_file("fact") +//compile_and_run("fact") +//compile_and_run("defs") + + +def main(args: Array[String]) : Unit = + compile_and_run(args(0)) + + +} diff -r 022e2cb1668d -r 5d860ff01938 progs/fun/fun_llvm.scala --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/progs/fun/fun_llvm.scala Sat Jul 04 22:12:18 2020 +0100 @@ -0,0 +1,290 @@ +// A Small LLVM Compiler for a Simple Functional Language +// (includes an external lexer and parser) +// +// call with +// +// scala fun_llvm.scala fact +// +// scala fun_llvm.scala defs +// +// this will generate a .ll file. You can interpret this file +// using lli. +// +// The optimiser can be invoked as +// +// opt -O1 -S in_file.ll > out_file.ll +// opt -O3 -S in_file.ll > out_file.ll +// +// The code produced for the various architectures can be obtains with +// +// llc -march=x86 -filetype=asm in_file.ll -o - +// llc -march=arm -filetype=asm in_file.ll -o - +// +// Producing an executable can be achieved by +// +// llc -filetype=obj in_file.ll +// gcc in_file.o -o a.out +// ./a.out + + + +object Compiler { + +import java.io._ +import scala.util._ +import scala.sys.process._ + +// Abstract syntax trees for the Fun language +abstract class Exp extends Serializable +abstract class BExp extends Serializable +abstract class Decl extends Serializable + +case class Def(name: String, args: List[String], body: Exp) extends Decl +case class Main(e: Exp) extends Decl + +case class Call(name: String, args: List[Exp]) extends Exp +case class If(a: BExp, e1: Exp, e2: Exp) extends Exp +case class Write(e: Exp) extends Exp +case class Var(s: String) extends Exp +case class Num(i: Int) extends Exp +case class Aop(o: String, a1: Exp, a2: Exp) extends Exp +case class Sequence(e1: Exp, e2: Exp) extends Exp +case class Bop(o: String, a1: Exp, a2: Exp) extends BExp + + +// for generating new labels +var counter = -1 + +def Fresh(x: String) = { + counter += 1 + x ++ "_" ++ counter.toString() +} + +// Internal CPS language for FUN +abstract class KExp +abstract class KVal + +case class KVar(s: String) extends KVal +case class KNum(i: Int) extends KVal +case class Kop(o: String, v1: KVal, v2: KVal) extends KVal +case class KCall(o: String, vrs: List[KVal]) extends KVal +case class KWrite(v: KVal) extends KVal + +case class KIf(x1: String, e1: KExp, e2: KExp) extends KExp { + override def toString = s"KIf $x1\nIF\n$e1\nELSE\n$e2" +} +case class KLet(x: String, e1: KVal, e2: KExp) extends KExp { + override def toString = s"let $x = $e1 in \n$e2" +} +case class KReturn(v: KVal) extends KExp + + +// CPS translation from Exps to KExps using a +// continuation k. +def CPS(e: Exp)(k: KVal => KExp) : KExp = e match { + case Var(s) => k(KVar(s)) + case Num(i) => k(KNum(i)) + case Aop(o, e1, e2) => { + val z = Fresh("tmp") + CPS(e1)(y1 => + CPS(e2)(y2 => KLet(z, Kop(o, y1, y2), k(KVar(z))))) + } + case If(Bop(o, b1, b2), e1, e2) => { + val z = Fresh("tmp") + CPS(b1)(y1 => + CPS(b2)(y2 => + KLet(z, Kop(o, y1, y2), KIf(z, CPS(e1)(k), CPS(e2)(k))))) + } + case Call(name, args) => { + def aux(args: List[Exp], vs: List[KVal]) : KExp = args match { + case Nil => { + val z = Fresh("tmp") + KLet(z, KCall(name, vs), k(KVar(z))) + } + case e::es => CPS(e)(y => aux(es, vs ::: List(y))) + } + aux(args, Nil) + } + case Sequence(e1, e2) => + CPS(e1)(_ => CPS(e2)(y2 => k(y2))) + case Write(e) => { + val z = Fresh("tmp") + CPS(e)(y => KLet(z, KWrite(y), k(KVar(z)))) + } +} + +//initial continuation +def CPSi(e: Exp) = CPS(e)(KReturn) + +// some testcases +val e1 = Aop("*", Var("a"), Num(3)) +CPSi(e1) + +val e2 = Aop("+", Aop("*", Var("a"), Num(3)), Num(4)) +CPSi(e2) + +val e3 = Aop("+", Num(2), Aop("*", Var("a"), Num(3))) +CPSi(e3) + +val e4 = Aop("+", Aop("-", Num(1), Num(2)), Aop("*", Var("a"), Num(3))) +CPSi(e4) + +val e5 = If(Bop("==", Num(1), Num(1)), Num(3), Num(4)) +CPSi(e5) + +val e6 = If(Bop("!=", Num(10), Num(10)), e5, Num(40)) +CPSi(e6) + +val e7 = Call("foo", List(Num(3))) +CPSi(e7) + +val e8 = Call("foo", List(Aop("*", Num(3), Num(1)), Num(4), Aop("+", Num(5), Num(6)))) +CPSi(e8) + +val e9 = Sequence(Aop("*", Var("a"), Num(3)), Aop("+", Var("b"), Num(6))) +CPSi(e9) + +val e = Aop("*", Aop("+", Num(1), Call("foo", List(Var("a"), Num(3)))), Num(4)) +CPSi(e) + + + + +// convenient string interpolations +// for instructions, labels and methods +import scala.language.implicitConversions +import scala.language.reflectiveCalls + +implicit def sring_inters(sc: StringContext) = new { + def i(args: Any*): String = " " ++ sc.s(args:_*) ++ "\n" + def l(args: Any*): String = sc.s(args:_*) ++ ":\n" + def m(args: Any*): String = sc.s(args:_*) ++ "\n" +} + +// mathematical and boolean operations +def compile_op(op: String) = op match { + case "+" => "add i32 " + case "*" => "mul i32 " + case "-" => "sub i32 " + case "/" => "sdiv i32 " + case "%" => "srem i32 " + case "==" => "icmp eq i32 " + case "<=" => "icmp sle i32 " // signed less or equal + case "<" => "icmp slt i32 " // signed less than +} + +def compile_val(v: KVal) : String = v match { + case KNum(i) => s"$i" + case KVar(s) => s"%$s" + case Kop(op, x1, x2) => + s"${compile_op(op)} ${compile_val(x1)}, ${compile_val(x2)}" + case KCall(x1, args) => + s"call i32 @$x1 (${args.map(compile_val).mkString("i32 ", ", i32 ", "")})" + case KWrite(x1) => + s"call i32 @printInt (i32 ${compile_val(x1)})" +} + +// compile K expressions +def compile_exp(a: KExp) : String = a match { + case KReturn(v) => + i"ret i32 ${compile_val(v)}" + case KLet(x: String, v: KVal, e: KExp) => + i"%$x = ${compile_val(v)}" ++ compile_exp(e) + case KIf(x, e1, e2) => { + val if_br = Fresh("if_branch") + val else_br = Fresh("else_branch") + i"br i1 %$x, label %$if_br, label %$else_br" ++ + l"\n$if_br" ++ + compile_exp(e1) ++ + l"\n$else_br" ++ + compile_exp(e2) + } +} + + +val prelude = """ +@.str = private constant [4 x i8] c"%d\0A\00" + +declare i32 @printf(i8*, ...) + +define i32 @printInt(i32 %x) { + %t0 = getelementptr [4 x i8], [4 x i8]* @.str, i32 0, i32 0 + call i32 (i8*, ...) @printf(i8* %t0, i32 %x) + ret i32 %x +} + +""" + + +// compile function for declarations and main +def compile_decl(d: Decl) : String = d match { + case Def(name, args, body) => { + m"define i32 @$name (${args.mkString("i32 %", ", i32 %", "")}) {" ++ + compile_exp(CPSi(body)) ++ + m"}\n" + } + case Main(body) => { + m"define i32 @main() {" ++ + compile_exp(CPSi(body)) ++ + m"}\n" + } +} + +// main compiler functions + +def time_needed[T](i: Int, code: => T) = { + val start = System.nanoTime() + for (j <- 1 to i) code + val end = System.nanoTime() + (end - start)/(i * 1.0e9) +} + +// for Scala 2.12 +/* +def deserialise[T](file: String) : Try[T] = { + val in = new ObjectInputStream(new FileInputStream(new File(file))) + val obj = Try(in.readObject().asInstanceOf[T]) + in.close() + obj +} +*/ + +def deserialise[T](fname: String) : Try[T] = { + import scala.util.Using + Using(new ObjectInputStream(new FileInputStream(fname))) { + in => in.readObject.asInstanceOf[T] + } +} + +def compile(fname: String) : String = { + val ast = deserialise[List[Decl]](fname ++ ".prs").getOrElse(Nil) + prelude ++ (ast.map(compile_decl).mkString) +} + +def compile_to_file(fname: String) = { + val output = compile(fname) + scala.tools.nsc.io.File(s"${fname}.ll").writeAll(output) +} + +def compile_and_run(fname: String) : Unit = { + compile_to_file(fname) + (s"llc -filetype=obj ${fname}.ll").!! + (s"gcc ${fname}.o -o a.out").!! + println("Time: " + time_needed(2, (s"./a.out").!)) +} + +// some examples of .fun files +//compile_to_file("fact") +//compile_and_run("fact") +//compile_and_run("defs") + + +def main(args: Array[String]) : Unit = + //println(compile(args(0))) + compile_and_run(args(0)) +} + + + + + diff -r 022e2cb1668d -r 5d860ff01938 progs/fun/fun_parser.scala --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/progs/fun/fun_parser.scala Sat Jul 04 22:12:18 2020 +0100 @@ -0,0 +1,199 @@ +// A parser for the Fun language +//================================ +// +// call with +// +// scala fun_parser.scala fact.tks +// +// scala fun_parser.scala defs.tks +// +// this will generate a .prs file that can be deserialised back +// into a list of declarations + +object Fun_Parser { + +import scala.language.implicitConversions +import scala.language.reflectiveCalls +import scala.util._ +import java.io._ + +abstract class Token extends Serializable +case object T_SEMI extends Token +case object T_COMMA 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_OP(s: String) extends Token +case class T_NUM(n: Int) extends Token +case class T_KWD(s: String) extends Token + + +// Parser combinators +// type parameter I needs to be of Seq-type +// +abstract class Parser[I, T](implicit ev: I => Seq[_]) { + def parse(ts: I): Set[(T, I)] + + def parse_single(ts: I) : T = + parse(ts).partition(_._2.isEmpty) match { + case (good, _) if !good.isEmpty => good.head._1 + case (_, err) => { + println (s"Parse Error\n${err.minBy(_._2.length)}") ; sys.exit(-1) } + } +} + +// convenience for writing grammar rules +case class ~[+A, +B](_1: A, _2: B) + +class SeqParser[I, T, S](p: => Parser[I, T], + q: => Parser[I, S])(implicit ev: I => Seq[_]) extends Parser[I, ~[T, S]] { + def parse(sb: I) = + for ((head1, tail1) <- p.parse(sb); + (head2, tail2) <- q.parse(tail1)) yield (new ~(head1, head2), tail2) +} + +class AltParser[I, T](p: => Parser[I, T], + q: => Parser[I, T])(implicit ev: I => Seq[_]) extends Parser[I, T] { + def parse(sb: I) = p.parse(sb) ++ q.parse(sb) +} + +class FunParser[I, T, S](p: => Parser[I, T], + f: T => S)(implicit ev: I => Seq[_]) extends Parser[I, S] { + def parse(sb: I) = + for ((head, tail) <- p.parse(sb)) yield (f(head), tail) +} + +// convenient combinators +implicit def ParserOps[I, T](p: Parser[I, T])(implicit ev: I => Seq[_]) = new { + def || (q : => Parser[I, T]) = new AltParser[I, T](p, q) + def ==>[S] (f: => T => S) = new FunParser[I, T, S](p, f) + def ~[S] (q : => Parser[I, S]) = new SeqParser[I, T, S](p, q) +} + +def ListParser[I, T, S](p: => Parser[I, T], + q: => Parser[I, S])(implicit ev: I => Seq[_]): Parser[I, List[T]] = { + (p ~ q ~ ListParser(p, q)) ==> { case x ~ _ ~ z => x :: z : List[T] } || + (p ==> ((s) => List(s))) +} + +case class TokParser(tok: Token) extends Parser[List[Token], Token] { + def parse(ts: List[Token]) = ts match { + case t::ts if (t == tok) => Set((t, ts)) + case _ => Set () + } +} + +implicit def token2tparser(t: Token) = TokParser(t) + +implicit def TokOps(t: Token) = new { + def || (q : => Parser[List[Token], Token]) = new AltParser[List[Token], Token](t, q) + def ==>[S] (f: => Token => S) = new FunParser[List[Token], Token, S](t, f) + def ~[S](q : => Parser[List[Token], S]) = new SeqParser[List[Token], Token, S](t, q) +} + +case object NumParser extends Parser[List[Token], Int] { + def parse(ts: List[Token]) = ts match { + case T_NUM(n)::ts => Set((n, ts)) + case _ => Set () + } +} + +case object IdParser extends Parser[List[Token], String] { + def parse(ts: List[Token]) = ts match { + case T_ID(s)::ts => Set((s, ts)) + case _ => Set () + } +} + + + +// Abstract syntax trees for the Fun language +abstract class Exp extends Serializable +abstract class BExp extends Serializable +abstract class Decl extends Serializable + +case class Def(name: String, args: List[String], body: Exp) extends Decl +case class Main(e: Exp) extends Decl + +case class Call(name: String, args: List[Exp]) extends Exp +case class If(a: BExp, e1: Exp, e2: Exp) extends Exp +case class Write(e: Exp) extends Exp +case class Var(s: String) extends Exp +case class Num(i: Int) extends Exp +case class Aop(o: String, a1: Exp, a2: Exp) extends Exp +case class Sequence(e1: Exp, e2: Exp) extends Exp +case class Bop(o: String, a1: Exp, a2: Exp) extends BExp + + + +// Grammar Rules for the Fun language + +// arithmetic expressions +lazy val Exp: Parser[List[Token], Exp] = + (T_KWD("if") ~ BExp ~ T_KWD("then") ~ Exp ~ T_KWD("else") ~ Exp) ==> + { case _ ~ x ~ _ ~ y ~ _ ~ z => If(x, y, z): Exp } || + (M ~ T_SEMI ~ Exp) ==> { case x ~ _ ~ y => Sequence(x, y): Exp } || M +lazy val M: Parser[List[Token], Exp] = + (T_KWD("write") ~ L) ==> { case _ ~ y => Write(y): Exp } || L +lazy val L: Parser[List[Token], Exp] = + (T ~ T_OP("+") ~ Exp) ==> { case x ~ _ ~ z => Aop("+", x, z): Exp } || + (T ~ T_OP("-") ~ Exp) ==> { case x ~ _ ~ z => Aop("-", x, z): Exp } || T +lazy val T: Parser[List[Token], Exp] = + (F ~ T_OP("*") ~ T) ==> { case x ~ _ ~ z => Aop("*", x, z): Exp } || + (F ~ T_OP("/") ~ T) ==> { case x ~ _ ~ z => Aop("/", x, z): Exp } || + (F ~ T_OP("%") ~ T) ==> { case x ~ _ ~ z => Aop("%", x, z): Exp } || F +lazy val F: Parser[List[Token], Exp] = + (IdParser ~ T_LPAREN ~ ListParser(Exp, T_COMMA) ~ T_RPAREN) ==> + { case x ~ _ ~ z ~ _ => Call(x, z): Exp } || + (T_LPAREN ~ Exp ~ T_RPAREN) ==> { case _ ~ y ~ _ => y: Exp } || + IdParser ==> { case x => Var(x): Exp } || + NumParser ==> { case x => Num(x): Exp } + +// boolean expressions +lazy val BExp: Parser[List[Token], BExp] = + (Exp ~ T_OP("==") ~ Exp) ==> { case x ~ _ ~ z => Bop("==", x, z): BExp } || + (Exp ~ T_OP("!=") ~ Exp) ==> { case x ~ _ ~ z => Bop("!=", x, z): BExp } || + (Exp ~ T_OP("<") ~ Exp) ==> { case x ~ _ ~ z => Bop("<", x, z): BExp } || + (Exp ~ T_OP(">") ~ Exp) ==> { case x ~ _ ~ z => Bop("<", z, x): BExp } || + (Exp ~ T_OP("<=") ~ Exp) ==> { case x ~ _ ~ z => Bop("<=", x, z): BExp } || + (Exp ~ T_OP("=>") ~ Exp) ==> { case x ~ _ ~ z => Bop("<=", z, x): BExp } + +lazy val Defn: Parser[List[Token], Decl] = + (T_KWD("def") ~ IdParser ~ T_LPAREN ~ ListParser(IdParser, T_COMMA) ~ T_RPAREN ~ T_OP("=") ~ Exp) ==> + { case _ ~ y ~ _ ~ w ~ _ ~ _ ~ r => Def(y, w, r): Decl } + +lazy val Prog: Parser[List[Token], List[Decl]] = + (Defn ~ T_SEMI ~ Prog) ==> { case x ~ _ ~ z => x :: z : List[Decl] } || + (Exp ==> ((s) => List(Main(s)) : List[Decl])) + + + +// Reading tokens and Writing parse trees + +def serialise[T](fname: String, data: T) = { + import scala.util.Using + Using(new ObjectOutputStream(new FileOutputStream(fname))) { + out => out.writeObject(data) + } +} + +def deserialise[T](fname: String) : Try[T] = { + import scala.util.Using + Using(new ObjectInputStream(new FileInputStream(fname))) { + in => in.readObject.asInstanceOf[T] + } +} + + +def main(args: Array[String]) : Unit= { + val fname = args(0) + val pname = fname.stripSuffix(".tks") ++ ".prs" + val tks = deserialise[List[Token]](fname).getOrElse(Nil) + serialise(pname, Prog.parse_single(tks)) + + // testing whether read-back is working + //val ptree = deserialise[List[Decl]](pname).get + //println(s"Reading back from ${pname}:\n${ptree.mkString("\n")}") +} + +} diff -r 022e2cb1668d -r 5d860ff01938 progs/fun/fun_tokens.scala --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/progs/fun/fun_tokens.scala Sat Jul 04 22:12:18 2020 +0100 @@ -0,0 +1,273 @@ +// A tokeniser for the Fun language +//================================== +// +// call with +// +// scala fun_tokens.scala fact.fun +// +// scala fun_tokens.scala defs.fun +// +// this will generate a .tks file that can be deserialised back +// into a list of tokens +// you can add -Xno-patmat-analysis in order to get rid of the +// match-not-exhaustive warning + +object Fun_Tokens { + +import scala.language.implicitConversions +import scala.language.reflectiveCalls + +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 + +abstract class Val +case object Empty extends Val +case class Chr(c: Char) extends Val +case class Sequ(v1: Val, v2: Val) extends Val +case class Left(v: Val) extends Val +case class Right(v: Val) extends Val +case class Stars(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)) +} +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 ~ (s: Rexp) = SEQ(r, s) +} + +implicit def stringOps(s: String) = new { + def | (r: Rexp) = ALT(s, r) + def | (r: String) = ALT(s, r) + def % = STAR(s) + 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 { + case ZERO => false + case ONE => true + case CHAR(_) => false + case ALT(r1, r2) => nullable(r1) || nullable(r2) + case SEQ(r1, r2) => nullable(r1) && nullable(r2) + case STAR(_) => true + case RECD(_, r1) => nullable(r1) +} + +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 ALT(r1, r2) => ALT(der(c, r1), der(c, 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 RECD(_, r1) => der(c, r1) +} + + +// extracts a string from 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 Stars(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 { + 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 Rec(x, v) => (x, flatten(v))::env(v) +} + +// The Injection Part of the lexer + +def mkeps(r: Rexp) : Val = r match { + case ONE => Empty + 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 RECD(x, r) => Rec(x, mkeps(r)) +} + +def inj(r: Rexp, c: Char, v: Val) : Val = (r, v) match { + case (STAR(r), Sequ(v1, Stars(vs))) => Stars(inj(r, c, v1)::vs) + case (SEQ(r1, r2), Sequ(v1, v2)) => Sequ(inj(r1, c, v1), v2) + case (SEQ(r1, r2), Left(Sequ(v1, v2))) => Sequ(inj(r1, c, v1), v2) + 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 (RECD(x, r1), _) => Rec(x, inj(r1, c, v)) + case _ => { println ("Injection error") ; sys.exit(-1) } +} + +// some "rectification" functions for simplification +def F_ID(v: Val): Val = v +def F_RIGHT(f: Val => Val) = (v:Val) => Right(f(v)) +def F_LEFT(f: Val => Val) = (v:Val) => Left(f(v)) +def F_ALT(f1: Val => Val, f2: Val => Val) = (v:Val) => v match { + case Right(v) => Right(f2(v)) + case Left(v) => Left(f1(v)) +} +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) = + (v:Val) => Sequ(f1(Empty), f2(v)) +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") + +def simp(r: Rexp): (Rexp, Val => Val) = r match { + case ALT(r1, r2) => { + val (r1s, f1s) = simp(r1) + val (r2s, f2s) = simp(r2) + (r1s, r2s) match { + 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)) + } + } + case SEQ(r1, r2) => { + val (r1s, f1s) = simp(r1) + val (r2s, f2s) = simp(r2) + (r1s, r2s) match { + case (ZERO, _) => (ZERO, F_ERROR) + case (_, ZERO) => (ZERO, F_ERROR) + case (ONE, _) => (r2s, F_SEQ_Empty1(f1s, f2s)) + case (_, ONE) => (r1s, F_SEQ_Empty2(f1s, f2s)) + 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 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)) + + +// The Lexing Rules for the Fun Language + +def PLUS(r: Rexp) = r ~ r.% + +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" | "T" | "_" +val DIGIT = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" +val ID = SYM ~ (SYM | DIGIT).% +val NUM = PLUS(DIGIT) +val KEYWORD : Rexp = "if" | "then" | "else" | "write" | "def" +val SEMI: Rexp = ";" +val OP: Rexp = "=" | "==" | "-" | "+" | "*" | "!=" | "<" | ">" | "<=" | ">=" | "%" | "/" +val WHITESPACE = PLUS(" " | "\n" | "\t") +val RPAREN: Rexp = ")" +val LPAREN: Rexp = "(" +val COMMA: Rexp = "," +val ALL = SYM | DIGIT | OP | " " | ":" | ";" | "\"" | "=" | "," | "(" | ")" +val ALL2 = ALL | "\n" +val COMMENT = ("/*" ~ ALL2.% ~ "*/") | ("//" ~ ALL.% ~ "\n") + + +val FUN_REGS = (("k" $ KEYWORD) | + ("i" $ ID) | + ("o" $ OP) | + ("n" $ NUM) | + ("s" $ SEMI) | + ("c" $ COMMA) | + ("pl" $ LPAREN) | + ("pr" $ RPAREN) | + ("w" $ (WHITESPACE | COMMENT))).% + + + +// The tokens for the Fun language + +import java.io._ + +abstract class Token extends Serializable +case object T_SEMI extends Token +case object T_COMMA 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_OP(s: String) extends Token +case class T_NUM(n: Int) extends Token +case class T_KWD(s: String) extends Token + +val token : PartialFunction[(String, String), Token] = { + case ("k", s) => T_KWD(s) + case ("i", s) => T_ID(s) + case ("o", s) => T_OP(s) + case ("n", s) => T_NUM(s.toInt) + case ("s", _) => T_SEMI + case ("c", _) => T_COMMA + case ("pl", _) => T_LPAREN + case ("pr", _) => T_RPAREN +} + + +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 serialise[T](fname: String, data: T) = { + import scala.util.Using + Using(new ObjectOutputStream(new FileOutputStream(fname))) { + out => out.writeObject(data) + } +} + +def main(args: Array[String]) : Unit = { + val fname = args(0) + val tname = fname.stripSuffix(".fun") ++ ".tks" + val file = io.Source.fromFile(fname).mkString + serialise(tname, tokenise(file)) +} + + +} diff -r 022e2cb1668d -r 5d860ff01938 progs/fun/funt.scala --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/progs/fun/funt.scala Sat Jul 04 22:12:18 2020 +0100 @@ -0,0 +1,543 @@ +// A Small Compiler for a Simple Functional Language +// (includes a lexer and a parser) + +import scala.language.implicitConversions +import scala.language.reflectiveCalls + +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 + +abstract class Val +case object Empty extends Val +case class Chr(c: Char) extends Val +case class Sequ(v1: Val, v2: Val) extends Val +case class Left(v: Val) extends Val +case class Right(v: Val) extends Val +case class Stars(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)) +} +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 ~ (s: Rexp) = SEQ(r, s) +} + +implicit def stringOps(s: String) = new { + def | (r: Rexp) = ALT(s, r) + def | (r: String) = ALT(s, r) + def % = STAR(s) + 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 { + case ZERO => false + case ONE => true + case CHAR(_) => false + case ALT(r1, r2) => nullable(r1) || nullable(r2) + case SEQ(r1, r2) => nullable(r1) && nullable(r2) + case STAR(_) => true + case RECD(_, r1) => nullable(r1) +} + +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 ALT(r1, r2) => ALT(der(c, r1), der(c, 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 RECD(_, r1) => der(c, r1) +} + + +// extracts a string from 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 Stars(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 { + 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 Rec(x, v) => (x, flatten(v))::env(v) +} + +// The Injection Part of the lexer + +def mkeps(r: Rexp) : Val = r match { + case ONE => Empty + 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 RECD(x, r) => Rec(x, mkeps(r)) +} + +def inj(r: Rexp, c: Char, v: Val) : Val = (r, v) match { + case (STAR(r), Sequ(v1, Stars(vs))) => Stars(inj(r, c, v1)::vs) + case (SEQ(r1, r2), Sequ(v1, v2)) => Sequ(inj(r1, c, v1), v2) + case (SEQ(r1, r2), Left(Sequ(v1, v2))) => Sequ(inj(r1, c, v1), v2) + 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 (RECD(x, r1), _) => Rec(x, inj(r1, c, v)) + case _ => { println ("Injection error") ; sys.exit(-1) } +} + +// some "rectification" functions for simplification +def F_ID(v: Val): Val = v +def F_RIGHT(f: Val => Val) = (v:Val) => Right(f(v)) +def F_LEFT(f: Val => Val) = (v:Val) => Left(f(v)) +def F_ALT(f1: Val => Val, f2: Val => Val) = (v:Val) => v match { + case Right(v) => Right(f2(v)) + case Left(v) => Left(f1(v)) +} +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) = + (v:Val) => Sequ(f1(Empty), f2(v)) +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") + +def simp(r: Rexp): (Rexp, Val => Val) = r match { + case ALT(r1, r2) => { + val (r1s, f1s) = simp(r1) + val (r2s, f2s) = simp(r2) + (r1s, r2s) match { + 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)) + } + } + case SEQ(r1, r2) => { + val (r1s, f1s) = simp(r1) + val (r2s, f2s) = simp(r2) + (r1s, r2s) match { + case (ZERO, _) => (ZERO, F_ERROR) + case (_, ZERO) => (ZERO, F_ERROR) + case (ONE, _) => (r2s, F_SEQ_Empty1(f1s, f2s)) + case (_, ONE) => (r1s, F_SEQ_Empty2(f1s, f2s)) + 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 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)) + + +// The Lexing Rules for the Fun Language + +def PLUS(r: Rexp) = r ~ r.% + +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" | "T" | "_" +val DIGIT = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" +val ID = SYM ~ (SYM | DIGIT).% +val NUM = PLUS(DIGIT) +val KEYWORD : Rexp = "if" | "then" | "else" | "write" | "def" +val SEMI: Rexp = ";" +val OP: Rexp = "=" | "==" | "-" | "+" | "*" | "!=" | "<" | ">" | "<=" | ">=" | "%" | "/" +val WHITESPACE = PLUS(" " | "\n" | "\t") +val RPAREN: Rexp = ")" +val LPAREN: Rexp = "(" +val COMMA: Rexp = "," +val ALL = SYM | DIGIT | OP | " " | ":" | ";" | "\"" | "=" | "," | "(" | ")" +val ALL2 = ALL | "\n" +val COMMENT = ("/*" ~ ALL2.% ~ "*/") | ("//" ~ ALL.% ~ "\n") + + +val WHILE_REGS = (("k" $ KEYWORD) | + ("i" $ ID) | + ("o" $ OP) | + ("n" $ NUM) | + ("s" $ SEMI) | + ("c" $ COMMA) | + ("pl" $ LPAREN) | + ("pr" $ RPAREN) | + ("w" $ (WHITESPACE | COMMENT))).% + + + +// The tokens for the Fun language + +abstract class Token +case object T_SEMI extends Token +case object T_COMMA 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_OP(s: String) extends Token +case class T_NUM(n: Int) extends Token +case class T_KWD(s: String) extends Token + +val token : PartialFunction[(String, String), Token] = { + case ("k", s) => T_KWD(s) + case ("i", s) => T_ID(s) + case ("o", s) => T_OP(s) + case ("n", s) => T_NUM(s.toInt) + case ("s", _) => T_SEMI + case ("c", _) => T_COMMA + case ("pl", _) => T_LPAREN + case ("pr", _) => T_RPAREN +} + + +def tokenise(s: String) : List[Token] = + lexing_simp(WHILE_REGS, s).collect(token) + + + +// Parser combinators +abstract class Parser[I, T](implicit ev: I => Seq[_]) { + def parse(ts: I): Set[(T, I)] + + def parse_all(ts: I) : Set[T] = + for ((head, tail) <- parse(ts); if (tail.isEmpty)) yield head + + def parse_single(ts: I) : T = parse_all(ts).toList match { + case List(t) => t + case _ => { println ("Parse Error\n") ; sys.exit(-1) } + } +} + +// convenience for matching later on +case class ~[+A, +B](_1: A, _2: B) + + +class SeqParser[I, T, S](p: => Parser[I, T], + q: => Parser[I, S])(implicit ev: I => Seq[_]) extends Parser[I, ~[T, S]] { + def parse(sb: I) = + for ((head1, tail1) <- p.parse(sb); + (head2, tail2) <- q.parse(tail1)) yield (new ~(head1, head2), tail2) +} + +class AltParser[I, T](p: => Parser[I, T], + q: => Parser[I, T])(implicit ev: I => Seq[_]) extends Parser[I, T] { + def parse(sb: I) = p.parse(sb) ++ q.parse(sb) +} + +class FunParser[I, T, S](p: => Parser[I, T], + f: T => S)(implicit ev: I => Seq[_]) extends Parser[I, S] { + def parse(sb: I) = + for ((head, tail) <- p.parse(sb)) yield (f(head), tail) +} + +implicit def ParserOps[I, T](p: Parser[I, T])(implicit ev: I => Seq[_]) = new { + def || (q : => Parser[I, T]) = new AltParser[I, T](p, q) + def ==>[S] (f: => T => S) = new FunParser[I, T, S](p, f) + def ~[S] (q : => Parser[I, S]) = new SeqParser[I, T, S](p, q) +} + +def ListParser[I, T, S](p: => Parser[I, T], + q: => Parser[I, S])(implicit ev: I => Seq[_]): Parser[I, List[T]] = { + (p ~ q ~ ListParser(p, q)) ==> { case x ~ _ ~ z => x :: z : List[T] } || + (p ==> ((s) => List(s))) +} + +case class TokParser(tok: Token) extends Parser[List[Token], Token] { + def parse(ts: List[Token]) = ts match { + case t::ts if (t == tok) => Set((t, ts)) + case _ => Set () + } +} + +implicit def token2tparser(t: Token) = TokParser(t) + +implicit def TokOps(t: Token) = new { + def || (q : => Parser[List[Token], Token]) = new AltParser[List[Token], Token](t, q) + def ==>[S] (f: => Token => S) = new FunParser[List[Token], Token, S](t, f) + def ~[S](q : => Parser[List[Token], S]) = new SeqParser[List[Token], Token, S](t, q) +} + +case object NumParser extends Parser[List[Token], Int] { + def parse(ts: List[Token]) = ts match { + case T_NUM(n)::ts => Set((n, ts)) + case _ => Set () + } +} + +case object IdParser extends Parser[List[Token], String] { + def parse(ts: List[Token]) = ts match { + case T_ID(s)::ts => Set((s, ts)) + case _ => Set () + } +} + + + +// Abstract syntax trees for Fun +abstract class Exp +abstract class BExp +abstract class Decl + +case class Def(name: String, args: List[String], body: Exp) extends Decl +case class Main(e: Exp) extends Decl + +case class Call(name: String, args: List[Exp]) extends Exp +case class If(a: BExp, e1: Exp, e2: Exp) extends Exp +case class Write(e: Exp) extends Exp +case class Var(s: String) extends Exp +case class Num(i: Int) extends Exp +case class Aop(o: String, a1: Exp, a2: Exp) extends Exp +case class Sequence(e1: Exp, e2: Exp) extends Exp +case class Bop(o: String, a1: Exp, a2: Exp) extends BExp + + + +// Grammar Rules for Fun + +// arithmetic expressions +lazy val Exp: Parser[List[Token], Exp] = + (T_KWD("if") ~ BExp ~ T_KWD("then") ~ Exp ~ T_KWD("else") ~ Exp) ==> + { case _ ~ y ~ _ ~ u ~ _ ~ w => If(y, u, w): Exp } || + (M ~ T_SEMI ~ Exp) ==> { case x ~ _ ~ z => Sequence(x, z): Exp } || M +lazy val M: Parser[List[Token], Exp] = + (T_KWD("write") ~ L) ==> { case _ ~ y => Write(y): Exp } || L +lazy val L: Parser[List[Token], Exp] = + (T ~ T_OP("+") ~ Exp) ==> { case x ~ _ ~ z => Aop("+", x, z): Exp } || + (T ~ T_OP("-") ~ Exp) ==> { case x ~ _ ~ z => Aop("-", x, z): Exp } || T +lazy val T: Parser[List[Token], Exp] = + (F ~ T_OP("*") ~ T) ==> { case x ~ _ ~ z => Aop("*", x, z): Exp } || + (F ~ T_OP("/") ~ T) ==> { case x ~ _ ~ z => Aop("/", x, z): Exp } || + (F ~ T_OP("%") ~ T) ==> { case x ~ _ ~ z => Aop("%", x, z): Exp } || F +lazy val F: Parser[List[Token], Exp] = + (IdParser ~ T_LPAREN ~ ListParser(Exp, T_COMMA) ~ T_RPAREN) ==> + { case x ~ _ ~ z ~ _ => Call(x, z): Exp } || + (T_LPAREN ~ Exp ~ T_RPAREN) ==> { case _ ~ y ~ _ => y: Exp } || + IdParser ==> { case x => Var(x): Exp } || + NumParser ==> { case x => Num(x): Exp } + +// boolean expressions +lazy val BExp: Parser[List[Token], BExp] = + (Exp ~ T_OP("==") ~ Exp) ==> { case x ~ _ ~ z => Bop("==", x, z): BExp } || + (Exp ~ T_OP("!=") ~ Exp) ==> { case x ~ _ ~ z => Bop("!=", x, z): BExp } || + (Exp ~ T_OP("<") ~ Exp) ==> { case x ~ _ ~ z => Bop("<", x, z): BExp } || + (Exp ~ T_OP(">") ~ Exp) ==> { case x ~ _ ~ z => Bop("<", z, x): BExp } || + (Exp ~ T_OP("<=") ~ Exp) ==> { case x ~ _ ~ z => Bop("<=", x, z): BExp } || + (Exp ~ T_OP("=>") ~ Exp) ==> { case x ~ _ ~ z => Bop("<=", z, x): BExp } + +lazy val Defn: Parser[List[Token], Decl] = + (T_KWD("def") ~ IdParser ~ T_LPAREN ~ ListParser(IdParser, T_COMMA) ~ T_RPAREN ~ T_OP("=") ~ Exp) ==> + { case x ~ y ~ z ~ w ~ u ~ v ~ r => Def(y, w, r): Decl } + +lazy val Prog: Parser[List[Token], List[Decl]] = + (Defn ~ T_SEMI ~ Prog) ==> { case x ~ _ ~ z => x :: z : List[Decl] } || + (Exp ==> ((s) => List(Main(s)) : List[Decl])) + + +// compiler - built-in functions +// copied from http://www.ceng.metu.edu.tr/courses/ceng444/link/jvm-cpm.html +// + +val library = """ +.class public XXX.XXX +.super java/lang/Object + +.method public static write(I)V + .limit locals 1 + .limit stack 2 + getstatic java/lang/System/out Ljava/io/PrintStream; + iload 0 + invokevirtual java/io/PrintStream/println(I)V + return +.end method + +""" + +// calculating the maximal needed stack size +def max_stack_exp(e: Exp): Int = e match { + case Call(_, args) => args.map(max_stack_exp).sum + case If(a, e1, e2) => max_stack_bexp(a) + (List(max_stack_exp(e1), max_stack_exp(e2)).max) + case Write(e) => max_stack_exp(e) + 1 + case Var(_) => 1 + case Num(_) => 1 + case Aop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2) + case Sequence(e1, e2) => List(max_stack_exp(e1), max_stack_exp(e2)).max +} +def max_stack_bexp(e: BExp): Int = e match { + case Bop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2) +} + + +// for generating new labels +var counter = -1 + +def Fresh(x: String) = { + counter += 1 + x ++ "_" ++ counter.toString() +} + +// convenient string interpolations +// for instructions, labels and methods +import scala.language.implicitConversions +import scala.language.reflectiveCalls + +implicit def sring_inters(sc: StringContext) = new { + def i(args: Any*): String = " " ++ sc.s(args:_*) ++ "\n" + def l(args: Any*): String = sc.s(args:_*) ++ ":\n" + def m(args: Any*): String = sc.s(args:_*) ++ "\n" +} + + +type Env = Map[String, Int] + + +def compile_expT(a: Exp, env : Env, name: String) : String = a match { + case Num(i) => i"ldc $i" + case Var(s) => i"iload ${env(s)}" + case Aop("+", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"iadd" + case Aop("-", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"isub" + case Aop("*", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"imul" + case Aop("/", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"idiv" + case Aop("%", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"irem" + case If(b, a1, a2) => { + val if_else = Fresh("If_else") + val if_end = Fresh("If_end") + compile_bexpT(b, env, if_else) ++ + compile_expT(a1, env, name) ++ + i"goto $if_end" ++ + l"$if_else" ++ + compile_expT(a2, env, name) ++ + l"$if_end" + } + case Call(n, args) => if (name == n) { + val stores = args.zipWithIndex.map { case (x, y) => i"istore $y" } + args.map(a => compile_expT(a, env, "")).mkString ++ + stores.reverse.mkString ++ + i"goto ${n}_Start" + } else { + val is = "I" * args.length + args.map(a => compile_expT(a, env, "")).mkString ++ + i"invokestatic XXX/XXX/${n}(${is})I" + } + case Sequence(a1, a2) => { + compile_expT(a1, env, "") ++ i"pop" ++ compile_expT(a2, env, name) + } + case Write(a1) => { + compile_expT(a1, env, "") ++ + i"dup" ++ + i"invokestatic XXX/XXX/write(I)V" + } +} + +def compile_bexpT(b: BExp, env : Env, jmp: String) : String = b match { + case Bop("==", a1, a2) => + compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"if_icmpne $jmp" + case Bop("!=", a1, a2) => + compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"if_icmpeq $jmp" + case Bop("<", a1, a2) => + compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"if_icmpge $jmp" + case Bop("<=", a1, a2) => + compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"if_icmpgt $jmp" +} + + +def compile_decl(d: Decl) : String = d match { + case Def(name, args, a) => { + val env = args.zipWithIndex.toMap + val is = "I" * args.length + m".method public static $name($is)I" ++ + m".limit locals ${args.length}" ++ + m".limit stack ${1 + max_stack_exp(a)}" ++ + l"${name}_Start" ++ + compile_expT(a, env, name) ++ + i"ireturn" ++ + m".end method\n" + } + case Main(a) => { + m".method public static main([Ljava/lang/String;)V" ++ + m".limit locals 200" ++ + m".limit stack 200" ++ + compile_expT(a, Map(), "") ++ + i"invokestatic XXX/XXX/write(I)V" ++ + i"return\n" ++ + m".end method\n" + } +} + +// main compiler functions + +def time_needed[T](i: Int, code: => T) = { + val start = System.nanoTime() + for (j <- 1 to i) code + val end = System.nanoTime() + (end - start)/(i * 1.0e9) +} + +def compile(class_name: String, input: String) : String = { + val tks = tokenise(input) + val ast = Prog.parse_single(tks) + val instructions = ast.map(compile_decl).mkString + (library + instructions).replaceAllLiterally("XXX", class_name) +} + +def compile_file(class_name: String) = { + val input = io.Source.fromFile(s"${class_name}.fun").mkString + val output = compile(class_name, input) + scala.tools.nsc.io.File(s"${class_name}.j").writeAll(output) +} + +import scala.sys.process._ + +def compile_run(class_name: String) : Unit = { + compile_file(class_name) + (s"java -jar jvm/jasmin-2.4/jasmin.jar ${class_name}.j").!! + println("Time: " + time_needed(2, (s"java ${class_name}/${class_name}").!)) +} + + +//examples +compile_run("defs") +compile_run("fact") diff -r 022e2cb1668d -r 5d860ff01938 progs/fun_llvm.scala --- a/progs/fun_llvm.scala Sat Jul 04 21:57:33 2020 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,290 +0,0 @@ -// A Small LLVM Compiler for a Simple Functional Language -// (includes an external lexer and parser) -// -// call with -// -// scala fun_llvm.scala fact -// -// scala fun_llvm.scala defs -// -// this will generate a .ll file. You can interpret this file -// using lli. -// -// The optimiser can be invoked as -// -// opt -O1 -S in_file.ll > out_file.ll -// opt -O3 -S in_file.ll > out_file.ll -// -// The code produced for the various architectures can be obtains with -// -// llc -march=x86 -filetype=asm in_file.ll -o - -// llc -march=arm -filetype=asm in_file.ll -o - -// -// Producing an executable can be achieved by -// -// llc -filetype=obj in_file.ll -// gcc in_file.o -o a.out -// ./a.out - - - -object Compiler { - -import java.io._ -import scala.util._ -import scala.sys.process._ - -// Abstract syntax trees for the Fun language -abstract class Exp extends Serializable -abstract class BExp extends Serializable -abstract class Decl extends Serializable - -case class Def(name: String, args: List[String], body: Exp) extends Decl -case class Main(e: Exp) extends Decl - -case class Call(name: String, args: List[Exp]) extends Exp -case class If(a: BExp, e1: Exp, e2: Exp) extends Exp -case class Write(e: Exp) extends Exp -case class Var(s: String) extends Exp -case class Num(i: Int) extends Exp -case class Aop(o: String, a1: Exp, a2: Exp) extends Exp -case class Sequence(e1: Exp, e2: Exp) extends Exp -case class Bop(o: String, a1: Exp, a2: Exp) extends BExp - - -// for generating new labels -var counter = -1 - -def Fresh(x: String) = { - counter += 1 - x ++ "_" ++ counter.toString() -} - -// Internal CPS language for FUN -abstract class KExp -abstract class KVal - -case class KVar(s: String) extends KVal -case class KNum(i: Int) extends KVal -case class Kop(o: String, v1: KVal, v2: KVal) extends KVal -case class KCall(o: String, vrs: List[KVal]) extends KVal -case class KWrite(v: KVal) extends KVal - -case class KIf(x1: String, e1: KExp, e2: KExp) extends KExp { - override def toString = s"KIf $x1\nIF\n$e1\nELSE\n$e2" -} -case class KLet(x: String, e1: KVal, e2: KExp) extends KExp { - override def toString = s"let $x = $e1 in \n$e2" -} -case class KReturn(v: KVal) extends KExp - - -// CPS translation from Exps to KExps using a -// continuation k. -def CPS(e: Exp)(k: KVal => KExp) : KExp = e match { - case Var(s) => k(KVar(s)) - case Num(i) => k(KNum(i)) - case Aop(o, e1, e2) => { - val z = Fresh("tmp") - CPS(e1)(y1 => - CPS(e2)(y2 => KLet(z, Kop(o, y1, y2), k(KVar(z))))) - } - case If(Bop(o, b1, b2), e1, e2) => { - val z = Fresh("tmp") - CPS(b1)(y1 => - CPS(b2)(y2 => - KLet(z, Kop(o, y1, y2), KIf(z, CPS(e1)(k), CPS(e2)(k))))) - } - case Call(name, args) => { - def aux(args: List[Exp], vs: List[KVal]) : KExp = args match { - case Nil => { - val z = Fresh("tmp") - KLet(z, KCall(name, vs), k(KVar(z))) - } - case e::es => CPS(e)(y => aux(es, vs ::: List(y))) - } - aux(args, Nil) - } - case Sequence(e1, e2) => - CPS(e1)(_ => CPS(e2)(y2 => k(y2))) - case Write(e) => { - val z = Fresh("tmp") - CPS(e)(y => KLet(z, KWrite(y), k(KVar(z)))) - } -} - -//initial continuation -def CPSi(e: Exp) = CPS(e)(KReturn) - -// some testcases -val e1 = Aop("*", Var("a"), Num(3)) -CPSi(e1) - -val e2 = Aop("+", Aop("*", Var("a"), Num(3)), Num(4)) -CPSi(e2) - -val e3 = Aop("+", Num(2), Aop("*", Var("a"), Num(3))) -CPSi(e3) - -val e4 = Aop("+", Aop("-", Num(1), Num(2)), Aop("*", Var("a"), Num(3))) -CPSi(e4) - -val e5 = If(Bop("==", Num(1), Num(1)), Num(3), Num(4)) -CPSi(e5) - -val e6 = If(Bop("!=", Num(10), Num(10)), e5, Num(40)) -CPSi(e6) - -val e7 = Call("foo", List(Num(3))) -CPSi(e7) - -val e8 = Call("foo", List(Aop("*", Num(3), Num(1)), Num(4), Aop("+", Num(5), Num(6)))) -CPSi(e8) - -val e9 = Sequence(Aop("*", Var("a"), Num(3)), Aop("+", Var("b"), Num(6))) -CPSi(e9) - -val e = Aop("*", Aop("+", Num(1), Call("foo", List(Var("a"), Num(3)))), Num(4)) -CPSi(e) - - - - -// convenient string interpolations -// for instructions, labels and methods -import scala.language.implicitConversions -import scala.language.reflectiveCalls - -implicit def sring_inters(sc: StringContext) = new { - def i(args: Any*): String = " " ++ sc.s(args:_*) ++ "\n" - def l(args: Any*): String = sc.s(args:_*) ++ ":\n" - def m(args: Any*): String = sc.s(args:_*) ++ "\n" -} - -// mathematical and boolean operations -def compile_op(op: String) = op match { - case "+" => "add i32 " - case "*" => "mul i32 " - case "-" => "sub i32 " - case "/" => "sdiv i32 " - case "%" => "srem i32 " - case "==" => "icmp eq i32 " - case "<=" => "icmp sle i32 " // signed less or equal - case "<" => "icmp slt i32 " // signed less than -} - -def compile_val(v: KVal) : String = v match { - case KNum(i) => s"$i" - case KVar(s) => s"%$s" - case Kop(op, x1, x2) => - s"${compile_op(op)} ${compile_val(x1)}, ${compile_val(x2)}" - case KCall(x1, args) => - s"call i32 @$x1 (${args.map(compile_val).mkString("i32 ", ", i32 ", "")})" - case KWrite(x1) => - s"call i32 @printInt (i32 ${compile_val(x1)})" -} - -// compile K expressions -def compile_exp(a: KExp) : String = a match { - case KReturn(v) => - i"ret i32 ${compile_val(v)}" - case KLet(x: String, v: KVal, e: KExp) => - i"%$x = ${compile_val(v)}" ++ compile_exp(e) - case KIf(x, e1, e2) => { - val if_br = Fresh("if_branch") - val else_br = Fresh("else_branch") - i"br i1 %$x, label %$if_br, label %$else_br" ++ - l"\n$if_br" ++ - compile_exp(e1) ++ - l"\n$else_br" ++ - compile_exp(e2) - } -} - - -val prelude = """ -@.str = private constant [4 x i8] c"%d\0A\00" - -declare i32 @printf(i8*, ...) - -define i32 @printInt(i32 %x) { - %t0 = getelementptr [4 x i8], [4 x i8]* @.str, i32 0, i32 0 - call i32 (i8*, ...) @printf(i8* %t0, i32 %x) - ret i32 %x -} - -""" - - -// compile function for declarations and main -def compile_decl(d: Decl) : String = d match { - case Def(name, args, body) => { - m"define i32 @$name (${args.mkString("i32 %", ", i32 %", "")}) {" ++ - compile_exp(CPSi(body)) ++ - m"}\n" - } - case Main(body) => { - m"define i32 @main() {" ++ - compile_exp(CPSi(body)) ++ - m"}\n" - } -} - -// main compiler functions - -def time_needed[T](i: Int, code: => T) = { - val start = System.nanoTime() - for (j <- 1 to i) code - val end = System.nanoTime() - (end - start)/(i * 1.0e9) -} - -// for Scala 2.12 -/* -def deserialise[T](file: String) : Try[T] = { - val in = new ObjectInputStream(new FileInputStream(new File(file))) - val obj = Try(in.readObject().asInstanceOf[T]) - in.close() - obj -} -*/ - -def deserialise[T](fname: String) : Try[T] = { - import scala.util.Using - Using(new ObjectInputStream(new FileInputStream(fname))) { - in => in.readObject.asInstanceOf[T] - } -} - -def compile(fname: String) : String = { - val ast = deserialise[List[Decl]](fname ++ ".prs").getOrElse(Nil) - prelude ++ (ast.map(compile_decl).mkString) -} - -def compile_to_file(fname: String) = { - val output = compile(fname) - scala.tools.nsc.io.File(s"${fname}.ll").writeAll(output) -} - -def compile_and_run(fname: String) : Unit = { - compile_to_file(fname) - (s"llc -filetype=obj ${fname}.ll").!! - (s"gcc ${fname}.o -o a.out").!! - println("Time: " + time_needed(2, (s"./a.out").!)) -} - -// some examples of .fun files -//compile_to_file("fact") -//compile_and_run("fact") -//compile_and_run("defs") - - -def main(args: Array[String]) : Unit = - //println(compile(args(0))) - compile_and_run(args(0)) -} - - - - - diff -r 022e2cb1668d -r 5d860ff01938 progs/fun_parser.scala --- a/progs/fun_parser.scala Sat Jul 04 21:57:33 2020 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,199 +0,0 @@ -// A parser for the Fun language -//================================ -// -// call with -// -// scala fun_parser.scala fact.tks -// -// scala fun_parser.scala defs.tks -// -// this will generate a .prs file that can be deserialised back -// into a list of declarations - -object Fun_Parser { - -import scala.language.implicitConversions -import scala.language.reflectiveCalls -import scala.util._ -import java.io._ - -abstract class Token extends Serializable -case object T_SEMI extends Token -case object T_COMMA 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_OP(s: String) extends Token -case class T_NUM(n: Int) extends Token -case class T_KWD(s: String) extends Token - - -// Parser combinators -// type parameter I needs to be of Seq-type -// -abstract class Parser[I, T](implicit ev: I => Seq[_]) { - def parse(ts: I): Set[(T, I)] - - def parse_single(ts: I) : T = - parse(ts).partition(_._2.isEmpty) match { - case (good, _) if !good.isEmpty => good.head._1 - case (_, err) => { - println (s"Parse Error\n${err.minBy(_._2.length)}") ; sys.exit(-1) } - } -} - -// convenience for writing grammar rules -case class ~[+A, +B](_1: A, _2: B) - -class SeqParser[I, T, S](p: => Parser[I, T], - q: => Parser[I, S])(implicit ev: I => Seq[_]) extends Parser[I, ~[T, S]] { - def parse(sb: I) = - for ((head1, tail1) <- p.parse(sb); - (head2, tail2) <- q.parse(tail1)) yield (new ~(head1, head2), tail2) -} - -class AltParser[I, T](p: => Parser[I, T], - q: => Parser[I, T])(implicit ev: I => Seq[_]) extends Parser[I, T] { - def parse(sb: I) = p.parse(sb) ++ q.parse(sb) -} - -class FunParser[I, T, S](p: => Parser[I, T], - f: T => S)(implicit ev: I => Seq[_]) extends Parser[I, S] { - def parse(sb: I) = - for ((head, tail) <- p.parse(sb)) yield (f(head), tail) -} - -// convenient combinators -implicit def ParserOps[I, T](p: Parser[I, T])(implicit ev: I => Seq[_]) = new { - def || (q : => Parser[I, T]) = new AltParser[I, T](p, q) - def ==>[S] (f: => T => S) = new FunParser[I, T, S](p, f) - def ~[S] (q : => Parser[I, S]) = new SeqParser[I, T, S](p, q) -} - -def ListParser[I, T, S](p: => Parser[I, T], - q: => Parser[I, S])(implicit ev: I => Seq[_]): Parser[I, List[T]] = { - (p ~ q ~ ListParser(p, q)) ==> { case x ~ _ ~ z => x :: z : List[T] } || - (p ==> ((s) => List(s))) -} - -case class TokParser(tok: Token) extends Parser[List[Token], Token] { - def parse(ts: List[Token]) = ts match { - case t::ts if (t == tok) => Set((t, ts)) - case _ => Set () - } -} - -implicit def token2tparser(t: Token) = TokParser(t) - -implicit def TokOps(t: Token) = new { - def || (q : => Parser[List[Token], Token]) = new AltParser[List[Token], Token](t, q) - def ==>[S] (f: => Token => S) = new FunParser[List[Token], Token, S](t, f) - def ~[S](q : => Parser[List[Token], S]) = new SeqParser[List[Token], Token, S](t, q) -} - -case object NumParser extends Parser[List[Token], Int] { - def parse(ts: List[Token]) = ts match { - case T_NUM(n)::ts => Set((n, ts)) - case _ => Set () - } -} - -case object IdParser extends Parser[List[Token], String] { - def parse(ts: List[Token]) = ts match { - case T_ID(s)::ts => Set((s, ts)) - case _ => Set () - } -} - - - -// Abstract syntax trees for the Fun language -abstract class Exp extends Serializable -abstract class BExp extends Serializable -abstract class Decl extends Serializable - -case class Def(name: String, args: List[String], body: Exp) extends Decl -case class Main(e: Exp) extends Decl - -case class Call(name: String, args: List[Exp]) extends Exp -case class If(a: BExp, e1: Exp, e2: Exp) extends Exp -case class Write(e: Exp) extends Exp -case class Var(s: String) extends Exp -case class Num(i: Int) extends Exp -case class Aop(o: String, a1: Exp, a2: Exp) extends Exp -case class Sequence(e1: Exp, e2: Exp) extends Exp -case class Bop(o: String, a1: Exp, a2: Exp) extends BExp - - - -// Grammar Rules for the Fun language - -// arithmetic expressions -lazy val Exp: Parser[List[Token], Exp] = - (T_KWD("if") ~ BExp ~ T_KWD("then") ~ Exp ~ T_KWD("else") ~ Exp) ==> - { case _ ~ x ~ _ ~ y ~ _ ~ z => If(x, y, z): Exp } || - (M ~ T_SEMI ~ Exp) ==> { case x ~ _ ~ y => Sequence(x, y): Exp } || M -lazy val M: Parser[List[Token], Exp] = - (T_KWD("write") ~ L) ==> { case _ ~ y => Write(y): Exp } || L -lazy val L: Parser[List[Token], Exp] = - (T ~ T_OP("+") ~ Exp) ==> { case x ~ _ ~ z => Aop("+", x, z): Exp } || - (T ~ T_OP("-") ~ Exp) ==> { case x ~ _ ~ z => Aop("-", x, z): Exp } || T -lazy val T: Parser[List[Token], Exp] = - (F ~ T_OP("*") ~ T) ==> { case x ~ _ ~ z => Aop("*", x, z): Exp } || - (F ~ T_OP("/") ~ T) ==> { case x ~ _ ~ z => Aop("/", x, z): Exp } || - (F ~ T_OP("%") ~ T) ==> { case x ~ _ ~ z => Aop("%", x, z): Exp } || F -lazy val F: Parser[List[Token], Exp] = - (IdParser ~ T_LPAREN ~ ListParser(Exp, T_COMMA) ~ T_RPAREN) ==> - { case x ~ _ ~ z ~ _ => Call(x, z): Exp } || - (T_LPAREN ~ Exp ~ T_RPAREN) ==> { case _ ~ y ~ _ => y: Exp } || - IdParser ==> { case x => Var(x): Exp } || - NumParser ==> { case x => Num(x): Exp } - -// boolean expressions -lazy val BExp: Parser[List[Token], BExp] = - (Exp ~ T_OP("==") ~ Exp) ==> { case x ~ _ ~ z => Bop("==", x, z): BExp } || - (Exp ~ T_OP("!=") ~ Exp) ==> { case x ~ _ ~ z => Bop("!=", x, z): BExp } || - (Exp ~ T_OP("<") ~ Exp) ==> { case x ~ _ ~ z => Bop("<", x, z): BExp } || - (Exp ~ T_OP(">") ~ Exp) ==> { case x ~ _ ~ z => Bop("<", z, x): BExp } || - (Exp ~ T_OP("<=") ~ Exp) ==> { case x ~ _ ~ z => Bop("<=", x, z): BExp } || - (Exp ~ T_OP("=>") ~ Exp) ==> { case x ~ _ ~ z => Bop("<=", z, x): BExp } - -lazy val Defn: Parser[List[Token], Decl] = - (T_KWD("def") ~ IdParser ~ T_LPAREN ~ ListParser(IdParser, T_COMMA) ~ T_RPAREN ~ T_OP("=") ~ Exp) ==> - { case _ ~ y ~ _ ~ w ~ _ ~ _ ~ r => Def(y, w, r): Decl } - -lazy val Prog: Parser[List[Token], List[Decl]] = - (Defn ~ T_SEMI ~ Prog) ==> { case x ~ _ ~ z => x :: z : List[Decl] } || - (Exp ==> ((s) => List(Main(s)) : List[Decl])) - - - -// Reading tokens and Writing parse trees - -def serialise[T](fname: String, data: T) = { - import scala.util.Using - Using(new ObjectOutputStream(new FileOutputStream(fname))) { - out => out.writeObject(data) - } -} - -def deserialise[T](fname: String) : Try[T] = { - import scala.util.Using - Using(new ObjectInputStream(new FileInputStream(fname))) { - in => in.readObject.asInstanceOf[T] - } -} - - -def main(args: Array[String]) : Unit= { - val fname = args(0) - val pname = fname.stripSuffix(".tks") ++ ".prs" - val tks = deserialise[List[Token]](fname).getOrElse(Nil) - serialise(pname, Prog.parse_single(tks)) - - // testing whether read-back is working - //val ptree = deserialise[List[Decl]](pname).get - //println(s"Reading back from ${pname}:\n${ptree.mkString("\n")}") -} - -} diff -r 022e2cb1668d -r 5d860ff01938 progs/fun_tokens.scala --- a/progs/fun_tokens.scala Sat Jul 04 21:57:33 2020 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,273 +0,0 @@ -// A tokeniser for the Fun language -//================================== -// -// call with -// -// scala fun_tokens.scala fact.fun -// -// scala fun_tokens.scala defs.fun -// -// this will generate a .tks file that can be deserialised back -// into a list of tokens -// you can add -Xno-patmat-analysis in order to get rid of the -// match-not-exhaustive warning - -object Fun_Tokens { - -import scala.language.implicitConversions -import scala.language.reflectiveCalls - -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 - -abstract class Val -case object Empty extends Val -case class Chr(c: Char) extends Val -case class Sequ(v1: Val, v2: Val) extends Val -case class Left(v: Val) extends Val -case class Right(v: Val) extends Val -case class Stars(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)) -} -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 ~ (s: Rexp) = SEQ(r, s) -} - -implicit def stringOps(s: String) = new { - def | (r: Rexp) = ALT(s, r) - def | (r: String) = ALT(s, r) - def % = STAR(s) - 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 { - case ZERO => false - case ONE => true - case CHAR(_) => false - case ALT(r1, r2) => nullable(r1) || nullable(r2) - case SEQ(r1, r2) => nullable(r1) && nullable(r2) - case STAR(_) => true - case RECD(_, r1) => nullable(r1) -} - -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 ALT(r1, r2) => ALT(der(c, r1), der(c, 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 RECD(_, r1) => der(c, r1) -} - - -// extracts a string from 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 Stars(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 { - 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 Rec(x, v) => (x, flatten(v))::env(v) -} - -// The Injection Part of the lexer - -def mkeps(r: Rexp) : Val = r match { - case ONE => Empty - 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 RECD(x, r) => Rec(x, mkeps(r)) -} - -def inj(r: Rexp, c: Char, v: Val) : Val = (r, v) match { - case (STAR(r), Sequ(v1, Stars(vs))) => Stars(inj(r, c, v1)::vs) - case (SEQ(r1, r2), Sequ(v1, v2)) => Sequ(inj(r1, c, v1), v2) - case (SEQ(r1, r2), Left(Sequ(v1, v2))) => Sequ(inj(r1, c, v1), v2) - 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 (RECD(x, r1), _) => Rec(x, inj(r1, c, v)) - case _ => { println ("Injection error") ; sys.exit(-1) } -} - -// some "rectification" functions for simplification -def F_ID(v: Val): Val = v -def F_RIGHT(f: Val => Val) = (v:Val) => Right(f(v)) -def F_LEFT(f: Val => Val) = (v:Val) => Left(f(v)) -def F_ALT(f1: Val => Val, f2: Val => Val) = (v:Val) => v match { - case Right(v) => Right(f2(v)) - case Left(v) => Left(f1(v)) -} -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) = - (v:Val) => Sequ(f1(Empty), f2(v)) -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") - -def simp(r: Rexp): (Rexp, Val => Val) = r match { - case ALT(r1, r2) => { - val (r1s, f1s) = simp(r1) - val (r2s, f2s) = simp(r2) - (r1s, r2s) match { - 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)) - } - } - case SEQ(r1, r2) => { - val (r1s, f1s) = simp(r1) - val (r2s, f2s) = simp(r2) - (r1s, r2s) match { - case (ZERO, _) => (ZERO, F_ERROR) - case (_, ZERO) => (ZERO, F_ERROR) - case (ONE, _) => (r2s, F_SEQ_Empty1(f1s, f2s)) - case (_, ONE) => (r1s, F_SEQ_Empty2(f1s, f2s)) - 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 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)) - - -// The Lexing Rules for the Fun Language - -def PLUS(r: Rexp) = r ~ r.% - -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" | "T" | "_" -val DIGIT = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" -val ID = SYM ~ (SYM | DIGIT).% -val NUM = PLUS(DIGIT) -val KEYWORD : Rexp = "if" | "then" | "else" | "write" | "def" -val SEMI: Rexp = ";" -val OP: Rexp = "=" | "==" | "-" | "+" | "*" | "!=" | "<" | ">" | "<=" | ">=" | "%" | "/" -val WHITESPACE = PLUS(" " | "\n" | "\t") -val RPAREN: Rexp = ")" -val LPAREN: Rexp = "(" -val COMMA: Rexp = "," -val ALL = SYM | DIGIT | OP | " " | ":" | ";" | "\"" | "=" | "," | "(" | ")" -val ALL2 = ALL | "\n" -val COMMENT = ("/*" ~ ALL2.% ~ "*/") | ("//" ~ ALL.% ~ "\n") - - -val FUN_REGS = (("k" $ KEYWORD) | - ("i" $ ID) | - ("o" $ OP) | - ("n" $ NUM) | - ("s" $ SEMI) | - ("c" $ COMMA) | - ("pl" $ LPAREN) | - ("pr" $ RPAREN) | - ("w" $ (WHITESPACE | COMMENT))).% - - - -// The tokens for the Fun language - -import java.io._ - -abstract class Token extends Serializable -case object T_SEMI extends Token -case object T_COMMA 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_OP(s: String) extends Token -case class T_NUM(n: Int) extends Token -case class T_KWD(s: String) extends Token - -val token : PartialFunction[(String, String), Token] = { - case ("k", s) => T_KWD(s) - case ("i", s) => T_ID(s) - case ("o", s) => T_OP(s) - case ("n", s) => T_NUM(s.toInt) - case ("s", _) => T_SEMI - case ("c", _) => T_COMMA - case ("pl", _) => T_LPAREN - case ("pr", _) => T_RPAREN -} - - -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 serialise[T](fname: String, data: T) = { - import scala.util.Using - Using(new ObjectOutputStream(new FileOutputStream(fname))) { - out => out.writeObject(data) - } -} - -def main(args: Array[String]) : Unit = { - val fname = args(0) - val tname = fname.stripSuffix(".fun") ++ ".tks" - val file = io.Source.fromFile(fname).mkString - serialise(tname, tokenise(file)) -} - - -} diff -r 022e2cb1668d -r 5d860ff01938 progs/funt.scala --- a/progs/funt.scala Sat Jul 04 21:57:33 2020 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,543 +0,0 @@ -// A Small Compiler for a Simple Functional Language -// (includes a lexer and a parser) - -import scala.language.implicitConversions -import scala.language.reflectiveCalls - -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 - -abstract class Val -case object Empty extends Val -case class Chr(c: Char) extends Val -case class Sequ(v1: Val, v2: Val) extends Val -case class Left(v: Val) extends Val -case class Right(v: Val) extends Val -case class Stars(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)) -} -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 ~ (s: Rexp) = SEQ(r, s) -} - -implicit def stringOps(s: String) = new { - def | (r: Rexp) = ALT(s, r) - def | (r: String) = ALT(s, r) - def % = STAR(s) - 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 { - case ZERO => false - case ONE => true - case CHAR(_) => false - case ALT(r1, r2) => nullable(r1) || nullable(r2) - case SEQ(r1, r2) => nullable(r1) && nullable(r2) - case STAR(_) => true - case RECD(_, r1) => nullable(r1) -} - -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 ALT(r1, r2) => ALT(der(c, r1), der(c, 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 RECD(_, r1) => der(c, r1) -} - - -// extracts a string from 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 Stars(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 { - 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 Rec(x, v) => (x, flatten(v))::env(v) -} - -// The Injection Part of the lexer - -def mkeps(r: Rexp) : Val = r match { - case ONE => Empty - 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 RECD(x, r) => Rec(x, mkeps(r)) -} - -def inj(r: Rexp, c: Char, v: Val) : Val = (r, v) match { - case (STAR(r), Sequ(v1, Stars(vs))) => Stars(inj(r, c, v1)::vs) - case (SEQ(r1, r2), Sequ(v1, v2)) => Sequ(inj(r1, c, v1), v2) - case (SEQ(r1, r2), Left(Sequ(v1, v2))) => Sequ(inj(r1, c, v1), v2) - 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 (RECD(x, r1), _) => Rec(x, inj(r1, c, v)) - case _ => { println ("Injection error") ; sys.exit(-1) } -} - -// some "rectification" functions for simplification -def F_ID(v: Val): Val = v -def F_RIGHT(f: Val => Val) = (v:Val) => Right(f(v)) -def F_LEFT(f: Val => Val) = (v:Val) => Left(f(v)) -def F_ALT(f1: Val => Val, f2: Val => Val) = (v:Val) => v match { - case Right(v) => Right(f2(v)) - case Left(v) => Left(f1(v)) -} -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) = - (v:Val) => Sequ(f1(Empty), f2(v)) -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") - -def simp(r: Rexp): (Rexp, Val => Val) = r match { - case ALT(r1, r2) => { - val (r1s, f1s) = simp(r1) - val (r2s, f2s) = simp(r2) - (r1s, r2s) match { - 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)) - } - } - case SEQ(r1, r2) => { - val (r1s, f1s) = simp(r1) - val (r2s, f2s) = simp(r2) - (r1s, r2s) match { - case (ZERO, _) => (ZERO, F_ERROR) - case (_, ZERO) => (ZERO, F_ERROR) - case (ONE, _) => (r2s, F_SEQ_Empty1(f1s, f2s)) - case (_, ONE) => (r1s, F_SEQ_Empty2(f1s, f2s)) - 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 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)) - - -// The Lexing Rules for the Fun Language - -def PLUS(r: Rexp) = r ~ r.% - -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" | "T" | "_" -val DIGIT = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" -val ID = SYM ~ (SYM | DIGIT).% -val NUM = PLUS(DIGIT) -val KEYWORD : Rexp = "if" | "then" | "else" | "write" | "def" -val SEMI: Rexp = ";" -val OP: Rexp = "=" | "==" | "-" | "+" | "*" | "!=" | "<" | ">" | "<=" | ">=" | "%" | "/" -val WHITESPACE = PLUS(" " | "\n" | "\t") -val RPAREN: Rexp = ")" -val LPAREN: Rexp = "(" -val COMMA: Rexp = "," -val ALL = SYM | DIGIT | OP | " " | ":" | ";" | "\"" | "=" | "," | "(" | ")" -val ALL2 = ALL | "\n" -val COMMENT = ("/*" ~ ALL2.% ~ "*/") | ("//" ~ ALL.% ~ "\n") - - -val WHILE_REGS = (("k" $ KEYWORD) | - ("i" $ ID) | - ("o" $ OP) | - ("n" $ NUM) | - ("s" $ SEMI) | - ("c" $ COMMA) | - ("pl" $ LPAREN) | - ("pr" $ RPAREN) | - ("w" $ (WHITESPACE | COMMENT))).% - - - -// The tokens for the Fun language - -abstract class Token -case object T_SEMI extends Token -case object T_COMMA 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_OP(s: String) extends Token -case class T_NUM(n: Int) extends Token -case class T_KWD(s: String) extends Token - -val token : PartialFunction[(String, String), Token] = { - case ("k", s) => T_KWD(s) - case ("i", s) => T_ID(s) - case ("o", s) => T_OP(s) - case ("n", s) => T_NUM(s.toInt) - case ("s", _) => T_SEMI - case ("c", _) => T_COMMA - case ("pl", _) => T_LPAREN - case ("pr", _) => T_RPAREN -} - - -def tokenise(s: String) : List[Token] = - lexing_simp(WHILE_REGS, s).collect(token) - - - -// Parser combinators -abstract class Parser[I, T](implicit ev: I => Seq[_]) { - def parse(ts: I): Set[(T, I)] - - def parse_all(ts: I) : Set[T] = - for ((head, tail) <- parse(ts); if (tail.isEmpty)) yield head - - def parse_single(ts: I) : T = parse_all(ts).toList match { - case List(t) => t - case _ => { println ("Parse Error\n") ; sys.exit(-1) } - } -} - -// convenience for matching later on -case class ~[+A, +B](_1: A, _2: B) - - -class SeqParser[I, T, S](p: => Parser[I, T], - q: => Parser[I, S])(implicit ev: I => Seq[_]) extends Parser[I, ~[T, S]] { - def parse(sb: I) = - for ((head1, tail1) <- p.parse(sb); - (head2, tail2) <- q.parse(tail1)) yield (new ~(head1, head2), tail2) -} - -class AltParser[I, T](p: => Parser[I, T], - q: => Parser[I, T])(implicit ev: I => Seq[_]) extends Parser[I, T] { - def parse(sb: I) = p.parse(sb) ++ q.parse(sb) -} - -class FunParser[I, T, S](p: => Parser[I, T], - f: T => S)(implicit ev: I => Seq[_]) extends Parser[I, S] { - def parse(sb: I) = - for ((head, tail) <- p.parse(sb)) yield (f(head), tail) -} - -implicit def ParserOps[I, T](p: Parser[I, T])(implicit ev: I => Seq[_]) = new { - def || (q : => Parser[I, T]) = new AltParser[I, T](p, q) - def ==>[S] (f: => T => S) = new FunParser[I, T, S](p, f) - def ~[S] (q : => Parser[I, S]) = new SeqParser[I, T, S](p, q) -} - -def ListParser[I, T, S](p: => Parser[I, T], - q: => Parser[I, S])(implicit ev: I => Seq[_]): Parser[I, List[T]] = { - (p ~ q ~ ListParser(p, q)) ==> { case x ~ _ ~ z => x :: z : List[T] } || - (p ==> ((s) => List(s))) -} - -case class TokParser(tok: Token) extends Parser[List[Token], Token] { - def parse(ts: List[Token]) = ts match { - case t::ts if (t == tok) => Set((t, ts)) - case _ => Set () - } -} - -implicit def token2tparser(t: Token) = TokParser(t) - -implicit def TokOps(t: Token) = new { - def || (q : => Parser[List[Token], Token]) = new AltParser[List[Token], Token](t, q) - def ==>[S] (f: => Token => S) = new FunParser[List[Token], Token, S](t, f) - def ~[S](q : => Parser[List[Token], S]) = new SeqParser[List[Token], Token, S](t, q) -} - -case object NumParser extends Parser[List[Token], Int] { - def parse(ts: List[Token]) = ts match { - case T_NUM(n)::ts => Set((n, ts)) - case _ => Set () - } -} - -case object IdParser extends Parser[List[Token], String] { - def parse(ts: List[Token]) = ts match { - case T_ID(s)::ts => Set((s, ts)) - case _ => Set () - } -} - - - -// Abstract syntax trees for Fun -abstract class Exp -abstract class BExp -abstract class Decl - -case class Def(name: String, args: List[String], body: Exp) extends Decl -case class Main(e: Exp) extends Decl - -case class Call(name: String, args: List[Exp]) extends Exp -case class If(a: BExp, e1: Exp, e2: Exp) extends Exp -case class Write(e: Exp) extends Exp -case class Var(s: String) extends Exp -case class Num(i: Int) extends Exp -case class Aop(o: String, a1: Exp, a2: Exp) extends Exp -case class Sequence(e1: Exp, e2: Exp) extends Exp -case class Bop(o: String, a1: Exp, a2: Exp) extends BExp - - - -// Grammar Rules for Fun - -// arithmetic expressions -lazy val Exp: Parser[List[Token], Exp] = - (T_KWD("if") ~ BExp ~ T_KWD("then") ~ Exp ~ T_KWD("else") ~ Exp) ==> - { case _ ~ y ~ _ ~ u ~ _ ~ w => If(y, u, w): Exp } || - (M ~ T_SEMI ~ Exp) ==> { case x ~ _ ~ z => Sequence(x, z): Exp } || M -lazy val M: Parser[List[Token], Exp] = - (T_KWD("write") ~ L) ==> { case _ ~ y => Write(y): Exp } || L -lazy val L: Parser[List[Token], Exp] = - (T ~ T_OP("+") ~ Exp) ==> { case x ~ _ ~ z => Aop("+", x, z): Exp } || - (T ~ T_OP("-") ~ Exp) ==> { case x ~ _ ~ z => Aop("-", x, z): Exp } || T -lazy val T: Parser[List[Token], Exp] = - (F ~ T_OP("*") ~ T) ==> { case x ~ _ ~ z => Aop("*", x, z): Exp } || - (F ~ T_OP("/") ~ T) ==> { case x ~ _ ~ z => Aop("/", x, z): Exp } || - (F ~ T_OP("%") ~ T) ==> { case x ~ _ ~ z => Aop("%", x, z): Exp } || F -lazy val F: Parser[List[Token], Exp] = - (IdParser ~ T_LPAREN ~ ListParser(Exp, T_COMMA) ~ T_RPAREN) ==> - { case x ~ _ ~ z ~ _ => Call(x, z): Exp } || - (T_LPAREN ~ Exp ~ T_RPAREN) ==> { case _ ~ y ~ _ => y: Exp } || - IdParser ==> { case x => Var(x): Exp } || - NumParser ==> { case x => Num(x): Exp } - -// boolean expressions -lazy val BExp: Parser[List[Token], BExp] = - (Exp ~ T_OP("==") ~ Exp) ==> { case x ~ _ ~ z => Bop("==", x, z): BExp } || - (Exp ~ T_OP("!=") ~ Exp) ==> { case x ~ _ ~ z => Bop("!=", x, z): BExp } || - (Exp ~ T_OP("<") ~ Exp) ==> { case x ~ _ ~ z => Bop("<", x, z): BExp } || - (Exp ~ T_OP(">") ~ Exp) ==> { case x ~ _ ~ z => Bop("<", z, x): BExp } || - (Exp ~ T_OP("<=") ~ Exp) ==> { case x ~ _ ~ z => Bop("<=", x, z): BExp } || - (Exp ~ T_OP("=>") ~ Exp) ==> { case x ~ _ ~ z => Bop("<=", z, x): BExp } - -lazy val Defn: Parser[List[Token], Decl] = - (T_KWD("def") ~ IdParser ~ T_LPAREN ~ ListParser(IdParser, T_COMMA) ~ T_RPAREN ~ T_OP("=") ~ Exp) ==> - { case x ~ y ~ z ~ w ~ u ~ v ~ r => Def(y, w, r): Decl } - -lazy val Prog: Parser[List[Token], List[Decl]] = - (Defn ~ T_SEMI ~ Prog) ==> { case x ~ _ ~ z => x :: z : List[Decl] } || - (Exp ==> ((s) => List(Main(s)) : List[Decl])) - - -// compiler - built-in functions -// copied from http://www.ceng.metu.edu.tr/courses/ceng444/link/jvm-cpm.html -// - -val library = """ -.class public XXX.XXX -.super java/lang/Object - -.method public static write(I)V - .limit locals 1 - .limit stack 2 - getstatic java/lang/System/out Ljava/io/PrintStream; - iload 0 - invokevirtual java/io/PrintStream/println(I)V - return -.end method - -""" - -// calculating the maximal needed stack size -def max_stack_exp(e: Exp): Int = e match { - case Call(_, args) => args.map(max_stack_exp).sum - case If(a, e1, e2) => max_stack_bexp(a) + (List(max_stack_exp(e1), max_stack_exp(e2)).max) - case Write(e) => max_stack_exp(e) + 1 - case Var(_) => 1 - case Num(_) => 1 - case Aop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2) - case Sequence(e1, e2) => List(max_stack_exp(e1), max_stack_exp(e2)).max -} -def max_stack_bexp(e: BExp): Int = e match { - case Bop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2) -} - - -// for generating new labels -var counter = -1 - -def Fresh(x: String) = { - counter += 1 - x ++ "_" ++ counter.toString() -} - -// convenient string interpolations -// for instructions, labels and methods -import scala.language.implicitConversions -import scala.language.reflectiveCalls - -implicit def sring_inters(sc: StringContext) = new { - def i(args: Any*): String = " " ++ sc.s(args:_*) ++ "\n" - def l(args: Any*): String = sc.s(args:_*) ++ ":\n" - def m(args: Any*): String = sc.s(args:_*) ++ "\n" -} - - -type Env = Map[String, Int] - - -def compile_expT(a: Exp, env : Env, name: String) : String = a match { - case Num(i) => i"ldc $i" - case Var(s) => i"iload ${env(s)}" - case Aop("+", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"iadd" - case Aop("-", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"isub" - case Aop("*", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"imul" - case Aop("/", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"idiv" - case Aop("%", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"irem" - case If(b, a1, a2) => { - val if_else = Fresh("If_else") - val if_end = Fresh("If_end") - compile_bexpT(b, env, if_else) ++ - compile_expT(a1, env, name) ++ - i"goto $if_end" ++ - l"$if_else" ++ - compile_expT(a2, env, name) ++ - l"$if_end" - } - case Call(n, args) => if (name == n) { - val stores = args.zipWithIndex.map { case (x, y) => i"istore $y" } - args.map(a => compile_expT(a, env, "")).mkString ++ - stores.reverse.mkString ++ - i"goto ${n}_Start" - } else { - val is = "I" * args.length - args.map(a => compile_expT(a, env, "")).mkString ++ - i"invokestatic XXX/XXX/${n}(${is})I" - } - case Sequence(a1, a2) => { - compile_expT(a1, env, "") ++ i"pop" ++ compile_expT(a2, env, name) - } - case Write(a1) => { - compile_expT(a1, env, "") ++ - i"dup" ++ - i"invokestatic XXX/XXX/write(I)V" - } -} - -def compile_bexpT(b: BExp, env : Env, jmp: String) : String = b match { - case Bop("==", a1, a2) => - compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"if_icmpne $jmp" - case Bop("!=", a1, a2) => - compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"if_icmpeq $jmp" - case Bop("<", a1, a2) => - compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"if_icmpge $jmp" - case Bop("<=", a1, a2) => - compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"if_icmpgt $jmp" -} - - -def compile_decl(d: Decl) : String = d match { - case Def(name, args, a) => { - val env = args.zipWithIndex.toMap - val is = "I" * args.length - m".method public static $name($is)I" ++ - m".limit locals ${args.length}" ++ - m".limit stack ${1 + max_stack_exp(a)}" ++ - l"${name}_Start" ++ - compile_expT(a, env, name) ++ - i"ireturn" ++ - m".end method\n" - } - case Main(a) => { - m".method public static main([Ljava/lang/String;)V" ++ - m".limit locals 200" ++ - m".limit stack 200" ++ - compile_expT(a, Map(), "") ++ - i"invokestatic XXX/XXX/write(I)V" ++ - i"return\n" ++ - m".end method\n" - } -} - -// main compiler functions - -def time_needed[T](i: Int, code: => T) = { - val start = System.nanoTime() - for (j <- 1 to i) code - val end = System.nanoTime() - (end - start)/(i * 1.0e9) -} - -def compile(class_name: String, input: String) : String = { - val tks = tokenise(input) - val ast = Prog.parse_single(tks) - val instructions = ast.map(compile_decl).mkString - (library + instructions).replaceAllLiterally("XXX", class_name) -} - -def compile_file(class_name: String) = { - val input = io.Source.fromFile(s"${class_name}.fun").mkString - val output = compile(class_name, input) - scala.tools.nsc.io.File(s"${class_name}.j").writeAll(output) -} - -import scala.sys.process._ - -def compile_run(class_name: String) : Unit = { - compile_file(class_name) - (s"java -jar jvm/jasmin-2.4/jasmin.jar ${class_name}.j").!! - println("Time: " + time_needed(2, (s"java ${class_name}/${class_name}").!)) -} - - -//examples -compile_run("defs") -compile_run("fact")