Compare commits

...

No commits in common. "interpreter" and "codecs" have entirely different histories.

10 changed files with 482 additions and 413 deletions

View File

@ -7,7 +7,7 @@ stages:
compile:
stage: build
image: registry.gitlab.com/fnux/cs210-grading-images/progfun2-interpreter-build:latest
image: lampepfl/moocs-dotty:2019-10-16
except:
- tags
tags:
@ -26,7 +26,7 @@ grade:
tags:
- cs210
image:
name: registry.gitlab.com/fnux/cs210-grading-images/progfun2-interpreter:20191205-066e2155681d802554c93c569bbf9871921a3ca1
name: registry.gitlab.com/fnux/cs210-grading-images/progfun2-codecs:20191027-dfbea8aed96096ed3af1cf1958549b97328d4c25
entrypoint: [""]
allow_failure: true
before_script:

View File

@ -1,6 +1,6 @@
# CS-210: Interpreter
# CS-210: Codecs
Please follow the [instructions from the main course
respository](https://gitlab.epfl.ch/lamp/cs-210-functional-programming-2019/blob/master/week12/00-homework9.md).
respository](https://gitlab.epfl.ch/lamp/cs-210-functional-programming-2019/blob/master/week11/00-homework8.md).
Grading and submission details can be found [here](https://gitlab.epfl.ch/lamp/cs-210-functional-programming-2019/blob/master/week1/02-grading-and-submission.md).

View File

@ -1,12 +1,16 @@
course := "progfun2"
assignment := "newInterpreter"
assignment := "codecs"
name := course.value + "-" + assignment.value
testSuite := "newInterpreter.RecursiveLanguageSuite"
testSuite := "codecs.CodecsSuite"
scalaVersion := "0.19.0-RC1"
scalacOptions ++= Seq("-deprecation")
libraryDependencies ++= Seq(
("org.scalacheck" %% "scalacheck" % "1.14.2" % Test).withDottyCompat(scalaVersion.value),
("org.typelevel" %% "jawn-parser" % "0.14.2").withDottyCompat(scalaVersion.value),
"com.novocode" % "junit-interface" % "0.11" % Test
)
testOptions in Test += Tests.Argument(TestFrameworks.JUnit, "-a", "-v", "-s")
initialCommands in console := """import codecs.{_, given}"""

Binary file not shown.

View File

@ -0,0 +1,283 @@
package codecs
/**
* A data type modeling JSON values.
*
* For example, the `42` integer JSON value can be modeled as `Json.Num(42)`
*/
sealed trait Json {
/**
* Try to decode this JSON value into a value of type `A` by using
* the given decoder.
*
* Note that you have to explicitly fix `A` type parameter when you call the method:
*
* {{{
* someJsonValue.decodeAs[User] // OK
* someJsonValue.decodeAs // Wrong!
* }}}
*/
def decodeAs[A](given decoder: Decoder[A]): Option[A] = decoder.decode(this)
}
object Json {
/** The JSON `null` value */
case object Null extends Json
/** JSON boolean values */
case class Bool(value: Boolean) extends Json
/** JSON numeric values */
case class Num(value: BigDecimal) extends Json
/** JSON string values */
case class Str(value: String) extends Json
/** JSON objects */
case class Obj(fields: Map[String, Json]) extends Json
/** JSON arrays */
case class Arr(items: List[Json]) extends Json
}
/**
* A type class that turns a value of type `A` into its JSON representation.
*/
trait Encoder[-A] {
def encode(value: A): Json
/**
* Transforms this `Encoder[A]` into an `Encoder[B]`, given a transformation function
* from `B` to `A`.
*
* For instance, given a `Encoder[String]`, we can get an `Encoder[UUID]`:
*
* {{{
* def uuidEncoder(given stringEncoder: Encoder[String]): Encoder[UUID] =
* stringEncoder.transform[UUID](uuid => uuid.toString)
* }}}
*
* This operation is also known as ?contramap?.
*/
def transform[B](f: B => A): Encoder[B] =
Encoder.fromFunction[B](value => this.encode(f(value)))
}
object Encoder extends GivenEncoders {
/**
* Convenient method for creating an instance of encoder from a function `f`
*/
def fromFunction[A](f: A => Json) = new Encoder[A] {
def encode(value: A): Json = f(value)
}
}
trait GivenEncoders {
/** An encoder for the `Unit` value */
given Encoder[Unit] = Encoder.fromFunction(_ => Json.Null)
/** An encoder for `Int` values */
given Encoder[Int] = Encoder.fromFunction(n => Json.Num(BigDecimal(n)))
/** An encoder for `String` values */
given Encoder[String] =
Encoder.fromFunction(str => Json.Str(str))
/** An encoder for `Boolean` values */
given Encoder[Boolean] =
Encoder.fromFunction(v => Json.Bool(v))
/**
* Encodes a list of values of type `A` into a JSON array containing
* the list elements encoded with the given `encoder`
*/
given [A](given encoder: Encoder[A]): Encoder[List[A]] =
Encoder.fromFunction(as => Json.Arr(as.map(encoder.encode)))
}
/**
* A specialization of `Encoder` that returns JSON objects only
*/
trait ObjectEncoder[-A] extends Encoder[A] {
// Refines the encoding result to `Json.Obj`
def encode(value: A): Json.Obj
/**
* Combines `this` encoder with `that` encoder.
* Returns an encoder producing a JSON object containing both
* fields of `this` encoder and fields of `that` encoder.
*/
def zip[B](that: ObjectEncoder[B]): ObjectEncoder[(A, B)] =
ObjectEncoder.fromFunction { (a, b) =>
Json.Obj(this.encode(a).fields ++ that.encode(b).fields)
}
}
object ObjectEncoder {
/**
* Convenient method for creating an instance of object encoder from a function `f`
*/
def fromFunction[A](f: A => Json.Obj): ObjectEncoder[A] = new ObjectEncoder[A] {
def encode(value: A): Json.Obj = f(value)
}
/**
* An encoder for values of type `A` that produces a JSON object with one field
* named according to the supplied `name` and containing the encoded value.
*/
def field[A](name: String)(given encoder: Encoder[A]): ObjectEncoder[A] =
ObjectEncoder.fromFunction(a => Json.Obj(Map(name -> encoder.encode(a))))
}
/**
* The dual of an encoder. Decodes a serialized value into its initial type `A`.
*/
trait Decoder[+A] {
/**
* @param data The data to de-serialize
* @return The decoded value wrapped in `Some`, or `None` if decoding failed
*/
def decode(data: Json): Option[A]
/**
* Combines `this` decoder with `that` decoder.
* Returns a decoder that invokes both `this` decoder and `that`
* decoder and returns a pair of decoded value in case both succeed,
* or `None` if at least one failed.
*/
def zip[B](that: Decoder[B]): Decoder[(A, B)] =
Decoder.fromFunction { json =>
this.decode(json).zip(that.decode(json))
}
/**
* Transforms this `Decoder[A]` into a `Decoder[B]`, given a transformation function
* from `A` to `B`.
*
* This operation is also known as ?map?.
*/
def transform[B](f: A => B): Decoder[B] =
Decoder.fromFunction(json => this.decode(json).map(f))
}
object Decoder extends GivenDecoders {
/**
* Convenient method to build a decoder instance from a function `f`
*/
def fromFunction[A](f: Json => Option[A]): Decoder[A] = new Decoder[A] {
def decode(data: Json): Option[A] = f(data)
}
/**
* Alternative method for creating decoder instances
*/
def fromPartialFunction[A](pf: PartialFunction[Json, A]): Decoder[A] =
fromFunction(pf.lift)
}
trait GivenDecoders {
/** A decoder for the `Unit` value */
given Decoder[Unit] =
Decoder.fromPartialFunction { case Json.Null => () }
/** A decoder for `Int` values. Hint: use the `isValidInt` method of `BigDecimal`. */
// TODO Define a given `Decoder[Int]` instance
given Decoder[Int] =
Decoder.fromFunction{ case Json.Num(v) => if v.isValidInt then Some(v.intValue) else None
case _ => None}
/** A decoder for `String` values */
// TODO Define a given `Decoder[String]` instance
given Decoder[String] =
Decoder.fromPartialFunction{ case Json.Str(str) => str}
/** A decoder for `Boolean` values */
// TODO Define a given `Decoder[Boolean]` instance
given Decoder[Boolean] =
Decoder.fromPartialFunction{ case Json.Bool(v) => v}
/**
* A decoder for JSON arrays. It decodes each item of the array
* using the given `decoder`. The resulting decoder succeeds only
* if all the JSON array items are successfully decoded.
*/
given [A](given decoder: Decoder[A]): Decoder[List[A]] =
Decoder.fromFunction {
case Json.Arr(items: List[Json]) => Some(items.map(v => decoder.decode(v).get))
case _ => None
}
/**
* A decoder for JSON objects. It decodes the value of a field of
* the supplied `name` using the given `decoder`.
*/
def field[A](name: String)(given decoder: Decoder[A]): Decoder[A] =
Decoder.fromFunction{
case Json.Obj(field: Map[String, Json]) => decoder.decode(field.get(name).get)
case _ => None
}
}
case class Person(name: String, age: Int)
object Person extends PersonCodecs
trait PersonCodecs {
/** The encoder for `Person` */
given Encoder[Person] =
ObjectEncoder.field[String]("name")
.zip(ObjectEncoder.field[Int]("age"))
.transform[Person](user => (user.name, user.age))
/** The corresponding decoder for `Person` */
given Decoder[Person] ={
Decoder.field[String]("name").zip(Decoder.field[Int]("age")).transform[Person](user => Person(user._1, user._2))
}
}
case class Contacts(people: List[Person])
object Contacts extends ContactsCodecs
trait ContactsCodecs {
// TODO Define the encoder and the decoder for `Contacts`
// The JSON representation of a value of type `Contacts` should be
// a JSON object with a single field named ?people? containing an
// array of values of type `Person` (reuse the `Person` codecs)
given Encoder[Contacts] =
ObjectEncoder.field[List[Person]]("people").transform[Contacts](c => c.people)
given Decoder[Contacts] =
Decoder.field[List[Person]]("people").transform[Contacts](p => Contacts(p))
}
// In case you want to try your code, here is a simple `Main`
// that can be used as a starting point. Otherwise, you can use
// the REPL (use the `console` sbt task).
object Main {
def main(args: Array[String]): Unit = {
println(renderJson(42))
println(renderJson("foo"))
val maybeJsonString = parseJson(""" "foo" """)
val maybeJsonObj = parseJson(""" { "name": "Alice", "age": 42 } """)
val maybeJsonObj2 = parseJson(""" { "name": "Alice", "age": "42" } """)
// Uncomment the following lines as you progress in the assignment
println(maybeJsonString.flatMap(_.decodeAs[Int]))
println(maybeJsonString.flatMap(_.decodeAs[String]))
println(maybeJsonObj.flatMap(_.decodeAs[Person]))
println(maybeJsonObj2.flatMap(_.decodeAs[Person]))
println(renderJson(Person("Bob", 66)))
}
}

View File

@ -0,0 +1,74 @@
package codecs
import org.typelevel.jawn.{ Parser, SimpleFacade }
import scala.collection.mutable
import scala.util.Try
// Utility methods that decode values from `String` JSON blobs, and
// render values to `String` JSON blobs
/**
* Parse a JSON document contained in a `String` value into a `Json` value, returns
* `None` in case the supplied `s` value is not a valid JSON document.
*/
def parseJson(s: String): Option[Json] = Parser.parseFromString[Json](s).toOption
/**
* Parse the JSON value from the supplied `s` parameter, and then try to decode
* it as a value of type `A` using the given `decoder`.
*
* Returns `None` if JSON parsing failed, or if decoding failed.
*/
def parseAndDecode[A](s: String)(given decoder: Decoder[A]): Option[A] =
for {
json <- parseJson(s)
a <- decoder.decode(json)
} yield a
/**
* Render the supplied `value` into JSON using the given `encoder`.
*/
def renderJson[A](value: A)(given encoder: Encoder[A]): String =
render(encoder.encode(value))
private def render(json: Json): String = json match {
case Json.Null => "null"
case Json.Bool(b) => b.toString
case Json.Num(n) => n.toString
case Json.Str(s) => renderString(s)
case Json.Arr(vs) => vs.map(render).mkString("[", ",", "]")
case Json.Obj(vs) => vs.map { case (k, v) => s"${renderString(k)}:${render(v)}" }.mkString("{", ",", "}")
}
private def renderString(s: String): String = {
val sb = new StringBuilder
sb.append('"')
var i = 0
val len = s.length
while (i < len) {
s.charAt(i) match {
case '"' => sb.append("\\\"")
case '\\' => sb.append("\\\\")
case '\b' => sb.append("\\b")
case '\f' => sb.append("\\f")
case '\n' => sb.append("\\n")
case '\r' => sb.append("\\r")
case '\t' => sb.append("\\t")
case c =>
if (c < ' ') sb.append("\\u%04x" format c.toInt)
else sb.append(c)
}
i += 1
}
sb.append('"').toString
}
given SimpleFacade[Json] {
def jnull() = Json.Null
def jtrue() = Json.Bool(true)
def jfalse() = Json.Bool(false)
def jnum(s: CharSequence, decIndex: Int, expIndex: Int) = Json.Num(BigDecimal(s.toString))
def jstring(s: CharSequence) = Json.Str(s.toString)
def jarray(vs: List[Json]) = Json.Arr(vs)
def jobject(vs: Map[String, Json]) = Json.Obj(vs)
}

View File

@ -1,16 +0,0 @@
package newInterpreter
object Logger
private var logging = false
private var indentation = 0
def on(): Unit =
logging = true
indentation = 0
def off(): Unit =
logging = false
def indent(): Unit =
indentation = indentation + 1
def unindent(): Unit =
indentation = indentation - 1
def log(s: => String): Unit =
if logging then println("| " * indentation + s)

View File

@ -1,265 +0,0 @@
package newInterpreter
object RecursiveLanguage {
/** Expression tree, also called Abstract Syntax Tree (AST) */
enum Expr
case Constant(value: Int)
case Name(name: String)
case BinOp(op: BinOps, arg1: Expr, arg2: Expr)
case IfNonzero(cond: Expr, caseTrue: Expr, caseFalse: Expr)
case Call(function: Expr, arg: Expr)
case Fun(param: String, body: Expr)
/** The empty list, also known as nil. */
case Empty
/** A compound data type composed of a head and a tail. */
case Cons(head: Expr, tail: Expr)
/** A pattern matching expression for Empty and Cons. */
case Match(scrutinee: Expr, caseEmpty: Expr, headName: String, tailName: String, caseCons: Expr)
import Expr._
/** Primitive operations that operation on constant values. */
enum BinOps
case Plus, Minus, Times, DividedBy, Modulo, LessEq
import BinOps._
def evalBinOp(op: BinOps)(ex: Expr, ey: Expr): Expr =
(op, ex, ey) match
case (Plus, Constant(x), Constant(y)) => Constant(x + y)
case (Minus, Constant(x), Constant(y)) => Constant(x - y)
case (Times, Constant(x), Constant(y)) => Constant(x * y)
case (LessEq, Constant(x), Constant(y)) => Constant(if x <= y then 1 else 0)
case (Modulo, Constant(x), Constant(y)) => if y == 0 then error("Division by zero") else Constant(x % y)
case (DividedBy, Constant(x), Constant(y)) => if y == 0 then error("Division by zero") else Constant(x / y)
case _ => error(s"Type error in ${show(BinOp(op, ex, ey))}")
type DefEnv = Map[String, Expr]
/** Evaluates a progam e given a set of top level definition defs */
def eval(e: Expr, defs: DefEnv): Expr =
e match
case Empty => Empty
case Cons(head, tail) => Cons(eval(head, defs), eval(tail, defs))
case Match(scrutinee, caseEmpty,hd,tl, caseCons) =>
eval(scrutinee, defs) match
case Empty => eval(caseEmpty, defs)
case Cons(head, tail) => eval(caseCons, defs ++ Map (hd -> head, tl -> tail))
case _ => error("Not a list")
case Constant(c) => e
case Name(n) =>
defs.get(n) match
case None => error(s"Unknown name $n")
case Some(body) => eval(body, defs)
case BinOp(op, e1, e2) =>
evalBinOp(op)(eval(e1, defs), eval(e2, defs))
case IfNonzero(cond, caseTrue, caseFalse) =>
if eval(cond, defs) != Constant(0) then eval(caseTrue, defs)
else eval(caseFalse, defs)
case Fun(n, body) => e
case Call(fun, arg) =>
Logger.log(show(e))
Logger.indent()
val eFun = eval(fun, defs)
val eArg = eval(arg, defs)
eFun match
case Fun(n, body) =>
Logger.unindent()
Logger.log(s"FUN: ${show(eFun)} ARG: ${show(eArg)}")
val bodySub = subst(body, n, eArg)
Logger.log(s"${show(bodySub)}")
Logger.indent()
val res = eval(bodySub, defs)
Logger.unindent()
Logger.log(s"+--> ${show(res)}")
res
case _ => error(s"Cannot apply non-function ${show(eFun)} in a call")
/** Substitutes Name(n) by r in e. */
def subst(e: Expr, n: String, r: Expr): Expr =
e match
case Constant(c) => e
case Name(s) => if s == n then r else e
case BinOp(op, e1, e2) =>
BinOp(op, subst(e1, n, r), subst(e2, n, r))
case IfNonzero(cond, trueE, falseE) =>
IfNonzero(subst(cond, n, r), subst(trueE, n, r), subst(falseE, n, r))
case Call(f, arg) =>
Call(subst(f, n, r), subst(arg, n, r))
case Fun(param, body) =>
// If n conflicts with param, there cannot be a reference to n in the
// function body, there is nothing so substite.
if param == n then e
else
val fvs = freeVars(r)
// If the free variables in r contain param the naive substitution would
// change the meaning of param to reference to the function parameter.
if fvs.contains(param) then
// Perform alpha conversion in body to eliminate the name collision.
val param1 = differentName(param, fvs)
val body1 = alphaConvert(body, param, param1)
Fun(param1, subst(body1, n, r))
else
// Otherwise, substitute in the function body anyway.
Fun(param, subst(body, n, r))
case Empty => Empty
case Cons(head, tail) => Cons(subst(head, n, r), subst(tail, n, r))
case Match(scrutinee, caseEmpty, headName, tailName, caseCons) =>
if headName == n || tailName == n then
// If n conflicts with headName or tailName, there cannot be a reference
// to n in caseCons. Simply substite n by r in scrutinee and caseEmpty.
Match(subst(scrutinee, n, r), subst(caseEmpty, n, r), headName, tailName, caseCons)
else
// If the free variables in r contain headName or tailName, the naive
// substitution would change their meaning to reference to pattern binds
val fvs = freeVars(r)
if fvs.contains(headName) || fvs.contains(tailName) then
// Perform alpha conversion in caseCons to eliminate the name collision.
val headName1 = differentName(headName, fvs)
val caseCons1 = alphaConvert(caseCons, headName, headName1)
val tailName1 = differentName(tailName,fvs)
val caseCons2 = alphaConvert(caseCons1, tailName, tailName1)
Match(scrutinee,caseEmpty, headName1, tailName1, subst(caseCons2,n,r))
else
// Otherwise, substitute in scrutinee, caseEmpty & caseCons anyway.
Match(subst(scrutinee, n, r), subst(caseEmpty, n, r), headName, tailName, subst(caseCons, n, r))
def differentName(n: String, s: Set[String]): String =
if s.contains(n) then differentName(n + "'", s)
else n
/** Computes the set of free variable in e. */
def freeVars(e: Expr): Set[String] =
e match
case Constant(c) => Set()
case Name(s) => Set(s)
case BinOp(op, e1, e2) => freeVars(e1) ++ freeVars(e2)
case IfNonzero(cond, trueE, falseE) => freeVars(cond) ++ freeVars(trueE) ++ freeVars(falseE)
case Call(f, arg) => freeVars(f) ++ freeVars(arg)
case Fun(param, body) => freeVars(body) - param
case Empty => Set()
case Cons(head, tail) => freeVars(head) ++ freeVars(tail)
case Match(scrutinee, caseEmpty,headName,tailName, caseCons) => scrutinee match
case Empty => freeVars(caseEmpty)
case Cons(head, tail) => freeVars(scrutinee) ++ freeVars(caseEmpty) ++ freeVars(caseCons)
/** Substitutes Name(n) by Name(m) in e. */
def alphaConvert(e: Expr, n: String, m: String): Expr =
e match
case Constant(c) => e
case Name(s) => if s == n then Name(m) else e
case BinOp(op, e1, e2) =>
BinOp(op, alphaConvert(e1, n, m), alphaConvert(e2, n, m))
case IfNonzero(cond, trueE, falseE) =>
IfNonzero(alphaConvert(cond, n, m), alphaConvert(trueE, n, m), alphaConvert(falseE, n, m))
case Call(f, arg) =>
Call(alphaConvert(f, n, m), alphaConvert(arg, n, m))
case Fun(param, body) =>
// If n conflicts with param, there cannot be references to n in body,
// as these would reference param instead.
if param == n then e
else Fun(param, alphaConvert(body, n, m))
case Empty => e
case Cons(head, tail) => Cons(alphaConvert(head, n,m), alphaConvert(tail, n,m))
case Match(scrutinee, caseEmpty,headName,tailName, caseCons) =>
if headName == n || tailName == n then Match(scrutinee, caseEmpty,headName,tailName, caseCons)
else Match(scrutinee, alphaConvert(caseEmpty,n,m),headName,tailName, alphaConvert(caseCons,n,m))
case class EvalException(msg: String) extends Exception(msg)
def error(msg: String) = throw EvalException(msg)
// Printing and displaying
/** Pretty print an expression as a String. */
def show(e: Expr): String =
e match
case Constant(c) => c.toString
case Name(n) => n
case BinOp(op, e1, e2) =>
val opString = op match
case Plus => "+"
case Minus => "-"
case Times => "*"
case DividedBy => "/"
case Modulo => "%"
case LessEq => "<="
s"($opString ${show(e1)} ${show(e2)})"
case IfNonzero(cond, caseTrue, caseFalse) =>
s"(if ${show(cond)} then ${show(caseTrue)} else ${show(caseFalse)})"
case Call(f, arg) => show(f) + "(" + show(arg) + ")"
case Fun(n, body) => s"($n => ${show(body)})"
case Empty => ""
case Cons(head, tail) => show(head) + "::" + show(tail)
case Match(scrutinee, caseEmpty, headName, tailName, caseCons) => show(scrutinee) + "Match " + "case Nil => " + show(caseEmpty) + "case " + headName + "::" + tailName + "=> " + show(caseCons)
/** Pretty print top-level definition as a String. */
def showEnv(env: Map[String, Expr]): String =
env.map { case (name, body) => s"def $name =\n ${show(body)}" }.mkString("\n\n") + "\n"
/** Evaluates an expression with the given top-level definitions with logging enabled. */
def tracingEval(e: Expr, defs: DefEnv): Expr =
Logger.on()
val evaluated = eval(e, defs)
println(s" ~~> $evaluated\n")
Logger.off()
evaluated
def minus(e1: Expr, e2: Expr) = BinOp(BinOps.Minus, e1, e2)
def plus(e1: Expr, e2: Expr) = BinOp(BinOps.Plus, e1, e2)
def leq(e1: Expr, e2: Expr) = BinOp(BinOps.LessEq, e1, e2)
def times(e1: Expr, e2: Expr) = BinOp(BinOps.Times, e1, e2)
def modulo(e1: Expr, e2: Expr) = BinOp(BinOps.Modulo, e1, e2)
def dividedBy(e1: Expr, e2: Expr) = BinOp(BinOps.DividedBy, e1, e2)
// The {Name => N} import syntax renames Name to N in this scope
import Expr.{Name => N, Constant => C, _}
/** Examples of top-level definitions (used in tests) */
val definitions: DefEnv = Map[String, Expr](
"fact" -> Fun("n",
IfNonzero(N("n"),
times(N("n"),
Call(N("fact"), minus(N("n"), C(1)))),
C(1))),
"square" -> Fun("x",
times(N("x"), N("x"))),
"twice" -> Fun("f", Fun("x",
Call(N("f"), Call(N("f"), N("x"))))),
// TODO Implement map (see recitation session)
"map" -> Fun("ls", Fun("f", Match( Name("ls"), Empty, "x", "xs", Cons( Call(Name("f"), Name("x") ), Call( Call ( Name("map"), Name("xs") ), Name("f") ) )))),
// TODO Implement gcd (see recitation session)
"gcd" -> Fun("a", Fun("b", IfNonzero( Name("b"), Call( Call ( Name("gcd"), Name ("b")), modulo ( Name("a") , Name("b"))), Name("a")))),
// TODO Implement foldLeft (see recitation session)
"foldLeft" -> Fun("ls", Fun("acc", Fun("f", Match( Name("ls"), Name("acc"), "x", "xs" ,
Call(
Call(
Call( Name("foldLeft"), Name("xs")) ,
Call(Call(Name("f"), Name("acc")), Name("x"))
), Name("f")
)
)))),
// TODO Implement foldRight (analogous to foldLeft, but operate right-to-left)
"foldRight" -> Fun("ls", Fun("z", Fun("fold", Match( Name("ls"), Name("z"), "x", "xs" ,
Call(Call(Name("fold"), Name("x")),
Call(Call(Call(Name("foldRight"), Name("xs")), Name("z")), Name("fold")))
)))),
)
def main(args: Array[String]): Unit =
println(showEnv(definitions))
tracingEval(Call(N("fact"), C(6)), definitions)
tracingEval(Call(Call(N("twice"), N("square")), C(3)), definitions)
}

View File

@ -0,0 +1,115 @@
package codecs
import org.scalacheck
import org.scalacheck.{ Gen, Prop }
import org.scalacheck.Prop.propBoolean
import org.junit.{ Assert, Test }
import scala.reflect.ClassTag
class CodecsSuite extends GivenEncoders, GivenDecoders, PersonCodecs, ContactsCodecs, TestEncoders, TestDecoders {
def checkProperty(prop: Prop): Unit = {
val result = scalacheck.Test.check(scalacheck.Test.Parameters.default, prop)
def fail(labels: Set[String], fallback: String): Nothing =
if labels.isEmpty then throw new AssertionError(fallback)
else throw new AssertionError(labels.mkString(". "))
result.status match {
case scalacheck.Test.Passed | _: scalacheck.Test.Proved => ()
case scalacheck.Test.Failed(_, labels) => fail(labels, "A property failed.")
case scalacheck.Test.PropException(_, e, labels) => fail(labels, s"An exception was thrown during property evaluation: $e.")
case scalacheck.Test.Exhausted => fail(Set.empty, "Unable to generate data.")
}
}
/**
* Check that a value of an arbitrary type `A` can be encoded and then successfully
* decoded with the given pair of encoder and decoder.
*/
def encodeAndThenDecodeProp[A](a: A)(given encA: Encoder[A], decA: Decoder[A]): Prop = {
val maybeDecoded = decA.decode(encA.encode(a))
maybeDecoded.contains(a) :| s"Encoded value '$a' was not successfully decoded. Got '$maybeDecoded'."
}
@Test def `it is possible to encode and decode the 'Unit' value (0pts)`(): Unit = {
checkProperty(Prop.forAll((unit: Unit) => encodeAndThenDecodeProp(unit)))
}
@Test def `it is possible to encode and decode 'Int' values (1pt)`(): Unit = {
checkProperty(Prop.forAll((x: Int) => encodeAndThenDecodeProp(x)))
}
@Test def `the 'Int' decoder should reject invalid 'Int' values (2pts)`(): Unit = {
val decoded = summon[Decoder[Int]].decode(Json.Num(4.2))
assert(decoded.isEmpty, "decoding 4.2 as an integer value should fail")
}
@Test def `a 'String' value should be encoded as a JSON string (1pt)`(): Unit = {
assert(summon[Encoder[String]].encode("foo") == Json.Str("foo"))
}
@Test def `it is possible to encode and decode 'String' values (1pt)`(): Unit = {
checkProperty(Prop.forAll((s: String) => encodeAndThenDecodeProp(s)))
}
@Test def `a 'Boolean' value should be encoded as a JSON boolean (1pt)`(): Unit = {
val encoder = summon[Encoder[Boolean]]
assert(encoder.encode(true) == Json.Bool(true))
assert(encoder.encode(false) == Json.Bool(false))
}
@Test def `it is possible to encode and decode 'Boolean' values (1pt)`(): Unit = {
checkProperty(Prop.forAll((b: Boolean) => encodeAndThenDecodeProp(b)))
}
@Test def `a 'List[A]' value should be encoded as a JSON array (0pts)`(): Unit = {
val xs = 1 :: 2 :: Nil
val encoder = summon[Encoder[List[Int]]]
assert(encoder.encode(xs) == Json.Arr(List(Json.Num(1), Json.Num(2))))
}
@Test def `it is possible to encode and decode lists (5pts)`(): Unit = {
checkProperty(Prop.forAll((xs: List[Int]) => encodeAndThenDecodeProp(xs)))
}
@Test def `a 'Person' value should be encoded as a JSON object (1pt)`(): Unit = {
val person = Person("Alice", 42)
val json = Json.Obj(Map("name" -> Json.Str("Alice"), "age" -> Json.Num(42)))
val encoder = summon[Encoder[Person]]
assert(encoder.encode(person) == json)
}
@Test def `it is possible to encode and decode people (4pts)`(): Unit = {
checkProperty(Prop.forAll((s: String, x: Int) => encodeAndThenDecodeProp(Person(s, x))))
}
@Test def `a 'Contacts' value should be encoded as a JSON object (1pt)`(): Unit = {
val contacts = Contacts(List(Person("Alice", 42)))
val json = Json.Obj(Map("people" ->
Json.Arr(List(Json.Obj(Map("name" -> Json.Str("Alice"), "age" -> Json.Num(42)))))
))
val encoder = summon[Encoder[Contacts]]
assert(encoder.encode(contacts) == json)
}
@Test def `it is possible to encode and decode contacts (4pts)`(): Unit = {
val peopleGenerator = Gen.listOf(Gen.resultOf((s: String, x: Int) => Person(s, x)))
checkProperty(Prop.forAll(peopleGenerator)(people => encodeAndThenDecodeProp(Contacts(people))))
}
}
trait TestEncoders extends EncoderFallbackInstance
trait EncoderFallbackInstance {
given [A](given ct: ClassTag[A]): Encoder[A] = throw new AssertionError(s"No given instance of `Encoder[${ct.runtimeClass.getSimpleName}]`")
}
trait TestDecoders extends DecoderFallbackInstance
trait DecoderFallbackInstance {
given [A](given ct: ClassTag[A]): Decoder[A] = throw new AssertionError(s"No given instance of `Decoder[${ct.runtimeClass.getSimpleName}]")
}

View File

@ -1,126 +0,0 @@
package newInterpreter
class RecursiveLanguageSuite {
import org.junit._
import org.junit.Assert.{assertEquals, fail}
import RecursiveLanguage._, Expr.{Constant => C, Name => N, _}
@Test def gcdTests(): Unit = {
def test(a: Int, b: Int, c: Int): Unit = {
val call = Call(Call(N("gcd"), C(a)), C(b))
val result = eval(call, definitions)
assertEquals(C(c), result)
}
test(60, 90, 30)
test(36, 48, 12)
test(25, 85, 5 )
test(12, 15, 3 )
test(60, 75, 15)
test(35, 56, 7 )
test(96, 128, 32)
test(120, 135, 15)
test(150, 225, 75)
}
@Test def evalTests: Unit = {
assertEquals(Empty, eval(Empty, Map()))
assertEquals(Cons(C(1), Empty), eval(Cons(C(1), Empty), Map()))
assertEquals(Cons(C(2), Empty), eval(Cons(BinOp(BinOps.Plus, C(1), C(1)), Empty), Map()))
assertEquals(C(0), eval(Match(Empty, C(0), "_", "_", C(1)), Map()))
assertEquals(C(1), eval(Match(Cons(Empty, Empty), C(0), "_", "_", C(1)), Map()))
assertEquals(C(2), eval(Match(Cons(C(2), Empty), C(0), "x", "xs", N("x")), Map()))
assertEquals(Empty, eval(Match(Cons(C(2), Empty), C(0), "x", "xs", N("xs")), Map()))
try {
eval(Match(C(0), C(0), "_", "_", C(1)), Map())
fail()
} catch {
case EvalException(msg) => // OK!
}
}
@Test def freeVarsTests: Unit = {
assertEquals(Set(), freeVars(Empty))
assertEquals(Set("a", "b"), freeVars(Cons(N("a"), N("b"))))
assertEquals(Set(), freeVars(Match(Empty, C(0), "a", "b", N("a"))))
assertEquals(Set(), freeVars(Match(Empty, C(0), "a", "b", N("b"))))
assertEquals(Set("c"), freeVars(Match(Empty, N("c"), "_", "_", C(1))))
}
@Test def alphaConvertTests: Unit = {
assertEquals(Cons(N("b"), N("b")), alphaConvert(Cons(N("a"), N("a")), "a", "b"))
assertEquals(Match(Empty, C(0), "a", "b", N("a")), alphaConvert(Match(Empty, C(0), "a", "b", N("a")), "a", "b"))
assertEquals(Match(Empty, C(0), "a", "b", N("b")), alphaConvert(Match(Empty, C(0), "a", "b", N("b")), "a", "b"))
assertEquals(Match(Empty, N("a"), "a", "b", C(1)), alphaConvert(Match(Empty, N("c"), "a", "b", C(1)), "c", "a"))
assertEquals(Match(Empty, N("b"), "a", "b", C(1)), alphaConvert(Match(Empty, N("c"), "a", "b", C(1)), "c", "b"))
assertEquals(Match(Empty, C(0), "a", "b", N("e")), alphaConvert(Match(Empty, C(0), "a", "b", N("d")), "d", "e"))
}
val sum = "sum" -> Fun("a", Fun("b", BinOp(BinOps.Plus, N("a"), N("b"))))
val div = "div" -> Fun("a", Fun("b", BinOp(BinOps.DividedBy, N("a"), N("b"))))
@Test def foldLeft: Unit = {
val list1 = Cons(C(1), Cons(C(2), Cons(C(3), Empty)))
val call1 = Call(Call(Call(N("foldLeft"), list1), C(100)), N("sum"))
assertEquals(C(106), eval(call1, definitions + sum))
val list2 = Cons(C(1), Cons(C(2), Cons(C(3), Cons(C(4), Cons(C(5), Cons(C(6), Empty))))))
val call2 = Call(Call(Call(N("foldLeft"), list2), C(100000)), N("div"))
assertEquals(C(138), eval(call2, definitions + div))
}
@Test def foldRight: Unit = {
val list1 = Cons(C(1), Cons(C(2), Cons(C(3), Empty)))
val call1 = Call(Call(Call(N("foldRight"), list1), C(100)), N("sum"))
assertEquals(C(106), eval(call1, definitions + sum))
val list2 = Cons(C(1000000), Cons(C(20000), Cons(C(3000), Cons(C(400), Cons(C(50), Cons(C(6), Empty))))))
val call2 = Call(Call(Call(N("foldRight"), list2), C(1)), N("div"))
assertEquals(C(3003), eval(call2, definitions + div))
}
@Test def substitutionSimple: Unit = {
// Substitution should happend everywhere in the Match. In scrutinee and in caseCons:
assertEquals(Cons(C(1), Empty), eval(
Call(N("bar"), Cons(C(1), Empty)),
Map("bar" -> Fun("x", Match(N("x"), C(0), "y", "z", N("x"))))
))
// In scrutinee and in caseEmpty:
assertEquals(Empty, eval(
Call(N("bar"), Empty),
Map("bar" -> Fun("x", Match(N("x"), N("x"), "y", "z", C(0))))
))
// But not inside caseCons when the binding name clashes with the functions name:
assertEquals(C(1), eval(
Call(N("bar"), Cons(C(1), Empty)),
Map("bar" -> Fun("x", Match(N("x"), C(0), "x", "z", N("x"))))
))
}
@Test def substitutionFunctionCapture: Unit = {
// Here comes the real fun, plus_one uses "map" as it's first argument name,
// incorrect implementation will accidentally capture the recursion in map
// turn into that name into a reference to first argument of plus_one.
val plus_one = "plus_one" -> Fun("map", BinOp(BinOps.Plus, C(1), N("map")))
val list1 = Cons(C(1), Cons(C(2), Cons(C(3), Empty)))
val list2 = Cons(C(2), Cons(C(3), Cons(C(4), Empty)))
assertEquals(list2, eval(Call(Call(N("map"), list1), N("plus_one")), definitions + plus_one))
}
@Test def substitutionMatchCapture: Unit = {
// More fun, this uses "fact" as a first binding in the pattern match:
val pairMap = "pairMap" -> Fun("pair", Fun("function",
Match(
N("pair"),
Empty,
"fact", "tcaf",
Cons(Call(N("function"), N("fact")), Call(N("function"), N("tcaf"))))
))
assertEquals(Cons(C(6), C(24)), eval(Call(Call(N("pairMap"), Cons(C(3), C(4))), N("fact")), definitions + pairMap))
}
@Rule def individualTestTimeout = new org.junit.rules.Timeout(200 * 1000)
}