aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJon Pretty <jon.pretty@propensive.com>2017-11-07 00:54:13 +0000
committerJon Pretty <jon.pretty@propensive.com>2017-11-07 00:54:13 +0000
commit1f49e614b1a2e363adbbea6ec510f094e195ace8 (patch)
tree809eaeee6468610be46e6aa454d72e33ebbb446d
parenta42cceae99ca8517ecff77fecdb23eba4d2c1036 (diff)
downloadmagnolia-1f49e614b1a2e363adbbea6ec510f094e195ace8.tar.gz
magnolia-1f49e614b1a2e363adbbea6ec510f094e195ace8.tar.bz2
magnolia-1f49e614b1a2e363adbbea6ec510f094e195ace8.zip
API improvements and better examples
-rw-r--r--build.sbt2
-rw-r--r--core/src/main/scala/magnolia.scala34
-rw-r--r--examples/src/main/scala/decode.scala65
-rw-r--r--examples/src/main/scala/default.scala24
-rw-r--r--examples/src/main/scala/eq.scala25
-rw-r--r--examples/src/main/scala/show.scala26
-rw-r--r--examples/src/main/scala/typeclasses.scala127
-rw-r--r--tests/src/main/scala/adt.scala7
-rw-r--r--tests/src/main/scala/tests.scala55
9 files changed, 202 insertions, 163 deletions
diff --git a/build.sbt b/build.sbt
index 0b97238..5353b03 100644
--- a/build.sbt
+++ b/build.sbt
@@ -150,7 +150,7 @@ lazy val scalaMacroDependencies: Seq[Setting[_]] = Seq(
lazy val examplesDependencies: Seq[Setting[_]] = Seq(
libraryDependencies += "org.typelevel" %% "cats-core" % "0.9.0",
- libraryDependencies += "com.propensive" %% "estrapade" % "1.0.2",
+ libraryDependencies += "com.propensive" %% "estrapade" % "1.0.3",
libraryDependencies += "com.propensive" %% "contextual-data" % "1.0.3"
)
diff --git a/core/src/main/scala/magnolia.scala b/core/src/main/scala/magnolia.scala
index 50d3ab5..1ad919f 100644
--- a/core/src/main/scala/magnolia.scala
+++ b/core/src/main/scala/magnolia.scala
@@ -6,15 +6,15 @@ import language.existentials
import language.higherKinds
import language.experimental.macros
-trait Subclass[Tc[_], T] {
+trait Subtype[Tc[_], T] {
type S <: T
def label: String
def typeclass: Tc[S]
def cast: PartialFunction[T, S]
}
-object Subclass {
- def apply[Tc[_], T, S1 <: T](name: String, tc: => Tc[S1], isType: T => Boolean, asType: T => S1) = new Subclass[Tc, T] {
+object Subtype {
+ def apply[Tc[_], T, S1 <: T](name: String, tc: => Tc[S1], isType: T => Boolean, asType: T => S1) = new Subtype[Tc, T] {
type S = S1
def label: String = name
def typeclass: Tc[S] = tc
@@ -53,6 +53,15 @@ abstract class JoinContext[Tc[_], T](val typeName: String, val isObject: Boolean
def parameters: Seq[Param[Tc, T]] = params
}
+class DispatchContext[Tc[_], T](val typeName: String, subs: Array[Subtype[Tc, T]]) {
+ def subtypes: Seq[Subtype[Tc, T]] = subs
+ def dispatch[R](value: T)(fn: Subtype[Tc, T] => R): R =
+ subtypes.map { sub => sub.cast.andThen { v =>
+ fn(sub)
+ } }.reduce(_ orElse _)(value)
+
+}
+
object Magnolia {
import CompileTimeState._
@@ -141,10 +150,11 @@ object Magnolia {
// FIXME: Handle AnyVals
val result = if(isCaseObject) {
- val obj = genericType.typeSymbol.companion.asTerm
+ // FIXME: look for an alternative which isn't deprecated on Scala 2.12+
+ val obj = genericType.typeSymbol.companionSymbol.asTerm
val className = obj.name.toString
val impl = q"""
- ${c.prefix}.join(_root_.magnolia.JoinContext[$typeConstructor, $genericType]($className, true, new _root_.scala.Array(0), $obj))
+ ${c.prefix}.join(_root_.magnolia.JoinContext[$typeConstructor, $genericType]($className, true, new _root_.scala.Array(0), _ => $obj))
"""
Some(Typeclass(genericType, impl))
} else if(isCaseClass) {
@@ -218,7 +228,7 @@ object Magnolia {
c.abort(c.enclosingPosition, "")
}
- val subclassesVal: TermName = TermName(c.freshName("subclasses"))
+ val subtypesVal: TermName = TermName(c.freshName("subtypes"))
val assignments = subtypes.map { searchType =>
recurse(CoproductType(genericType.toString), genericType, assignedName) {
@@ -227,7 +237,7 @@ object Magnolia {
c.abort(c.enclosingPosition, s"failed to get implicit for type $searchType")
}
}.zipWithIndex.map { case ((typ, typeclass), idx) =>
- q"""$subclassesVal($idx) = _root_.magnolia.Subclass[$typeConstructor, $genericType, $typ](
+ q"""$subtypesVal($idx) = _root_.magnolia.Subtype[$typeConstructor, $genericType, $typ](
${typ.typeSymbol.name.toString},
$typeclass,
(t: $genericType) => t.isInstanceOf[$typ],
@@ -237,12 +247,12 @@ object Magnolia {
Some {
Typeclass(genericType, q"""{
- val $subclassesVal: _root_.scala.Array[_root_.magnolia.Subclass[$typeConstructor, $genericType]] =
+ val $subtypesVal: _root_.scala.Array[_root_.magnolia.Subtype[$typeConstructor, $genericType]] =
new _root_.scala.Array(${assignments.size})
..$assignments
- ${c.prefix}.dispatch($subclassesVal: _root_.scala.Seq[_root_.magnolia.Subclass[$typeConstructor, $genericType]])
+ ${c.prefix}.dispatch(new _root_.magnolia.DispatchContext($genericTypeName, $subtypesVal: _root_.scala.Array[_root_.magnolia.Subtype[$typeConstructor, $genericType]])): $resultType
}""")
}
} else None
@@ -290,11 +300,7 @@ object Magnolia {
if(currentStack.frames.isEmpty) recursionStack = ListMap()
result.map { tree =>
- if(currentStack.frames.isEmpty) {
- val out = c.untypecheck(removeDeferred.transform(tree))
- println(s"Bytes: ${out.toString.size}")
- out
- } else tree
+ if(currentStack.frames.isEmpty) c.untypecheck(removeDeferred.transform(tree)) else tree
}.getOrElse {
c.abort(c.enclosingPosition, s"magnolia: could not infer typeclass for type $genericType")
}
diff --git a/examples/src/main/scala/decode.scala b/examples/src/main/scala/decode.scala
new file mode 100644
index 0000000..1cc8a12
--- /dev/null
+++ b/examples/src/main/scala/decode.scala
@@ -0,0 +1,65 @@
+package magnolia.examples
+
+import scala.language.existentials
+import scala.language.higherKinds
+
+import magnolia._
+import scala.language.experimental.macros
+
+trait Decoder[T] { def decode(str: String): T }
+
+object Decoder {
+
+ implicit val string: Decoder[String] = new Decoder[String] { def decode(str: String): String = str }
+ implicit val int: Decoder[Int] = new Decoder[Int] { def decode(str: String): Int = str.toInt }
+ implicit def generic[T]: Decoder[T] = macro Magnolia.generic[T]
+
+ type Typeclass[T] = Decoder[T]
+
+ def join[T](ctx: JoinContext[Decoder, T]): Decoder[T] = new Decoder[T] {
+ def decode(value: String) = {
+ val (name, values) = parse(value)
+ ctx.construct { param => param.typeclass.decode(values(param.label)) }
+ }
+ }
+
+ def dispatch[T](ctx: DispatchContext[Decoder, T]): Decoder[T] = new Decoder[T] {
+ def decode(param: String) = {
+ val (name, values) = parse(param)
+ val subtype = ctx.subtypes.find(_.label == name).get
+ subtype.typeclass.decode(param)
+ }
+ }
+
+ private def parse(value: String): (String, Map[String, String]) = {
+ val end = value.indexOf('(')
+ val name = value.substring(0, end)
+
+ def parts(value: String, idx: Int = 0, depth: Int = 0, collected: List[String] = List("")): List[String] = {
+ def plus(char: Char): List[String] = collected.head+char :: collected.tail
+
+ if(idx == value.length) collected
+ else value(idx) match {
+ case '(' =>
+ parts(value, idx + 1, depth + 1, plus('('))
+ case ')' =>
+ if(depth == 1) plus(')')
+ else parts(value, idx + 1, depth - 1, plus(')'))
+ case ',' =>
+ if(depth == 0) parts(value, idx + 1, depth, "" :: collected)
+ else parts(value, idx + 1, depth, plus(','))
+ case char =>
+ parts(value, idx + 1, depth, plus(char))
+ }
+ }
+
+ def keyValue(str: String): (String, String) = {
+ val List(label, value) = str.split("=", 2).to[List]
+ (label, value)
+ }
+
+ (name, parts(value.substring(end + 1, value.length - 1)).map(keyValue).toMap)
+ }
+
+}
+
diff --git a/examples/src/main/scala/default.scala b/examples/src/main/scala/default.scala
new file mode 100644
index 0000000..1f602f9
--- /dev/null
+++ b/examples/src/main/scala/default.scala
@@ -0,0 +1,24 @@
+package magnolia.examples
+
+import scala.language.existentials
+import scala.language.higherKinds
+
+import magnolia._
+import scala.language.experimental.macros
+
+trait Default[T] { def default: T }
+
+object Default {
+ type Typeclass[T] = Default[T]
+ def join[T](ctx: JoinContext[Default, T]): Default[T] = new Default[T] {
+ def default = ctx.construct { param => param.typeclass.default }
+ }
+
+ def dispatch[T](ctx: DispatchContext[Default, T])(): Default[T] = new Default[T] {
+ def default: T = ctx.subtypes.head.typeclass.default
+ }
+
+ implicit val string: Default[String] = new Default[String] { def default = "" }
+ implicit val int: Default[Int] = new Default[Int] { def default = 0 }
+ implicit def generic[T]: Default[T] = macro Magnolia.generic[T]
+}
diff --git a/examples/src/main/scala/eq.scala b/examples/src/main/scala/eq.scala
new file mode 100644
index 0000000..ec9be14
--- /dev/null
+++ b/examples/src/main/scala/eq.scala
@@ -0,0 +1,25 @@
+package magnolia.examples
+
+import scala.language.higherKinds
+
+import magnolia._
+import scala.language.experimental.macros
+
+trait Eq[T] { def equal(value: T, value2: T): Boolean }
+
+object Eq {
+ type Typeclass[T] = Eq[T]
+ def join[T](ctx: JoinContext[Eq, T]): Eq[T] = new Eq[T] {
+ def equal(value1: T, value2: T) =
+ ctx.parameters.forall { param => param.typeclass.equal(param.dereference(value1), param.dereference(value2)) }
+ }
+
+ def dispatch[T](ctx: DispatchContext[Eq, T]): Eq[T] = new Eq[T] {
+ def equal(value1: T, value2: T): Boolean =
+ ctx.dispatch(value1) { case sub => sub.typeclass.equal(sub.cast(value1), sub.cast(value2)) }
+ }
+
+ implicit val string: Eq[String] = new Eq[String] { def equal(v1: String, v2: String) = v1 == v2 }
+ implicit val int: Eq[Int] = new Eq[Int] { def equal(v1: Int, v2: Int) = v1 == v2 }
+ implicit def generic[T]: Eq[T] = macro Magnolia.generic[T]
+}
diff --git a/examples/src/main/scala/show.scala b/examples/src/main/scala/show.scala
new file mode 100644
index 0000000..9af828e
--- /dev/null
+++ b/examples/src/main/scala/show.scala
@@ -0,0 +1,26 @@
+package magnolia.examples
+
+import scala.language.existentials
+import scala.language.higherKinds
+
+import magnolia._
+import scala.language.experimental.macros
+
+trait Show[Out, T] { def show(value: T): Out }
+
+object Show {
+ type Typeclass[T] = Show[String, T]
+ def join[T](ctx: JoinContext[Typeclass, T]): Show[String, T] = new Show[String, T] {
+ def show(value: T) = ctx.parameters.map { param =>
+ s"${param.label}=${param.typeclass.show(param.dereference(value))}"
+ }.mkString(s"${ctx.typeName.split("\\.").last}(", ",", ")")
+ }
+
+ def dispatch[T](ctx: DispatchContext[Typeclass, T]): Show[String, T] = new Show[String, T] {
+ def show(value: T): String = ctx.dispatch(value) { sub => sub.typeclass.show(sub.cast(value)) }
+ }
+
+ implicit val string: Show[String, String] = new Show[String, String] { def show(s: String): String = s }
+ implicit val int: Show[String, Int] = new Show[String, Int] { def show(s: Int): String = s.toString }
+ implicit def generic[T]: Show[String, T] = macro Magnolia.generic[T]
+}
diff --git a/examples/src/main/scala/typeclasses.scala b/examples/src/main/scala/typeclasses.scala
deleted file mode 100644
index aaa74fd..0000000
--- a/examples/src/main/scala/typeclasses.scala
+++ /dev/null
@@ -1,127 +0,0 @@
-package magnolia.examples
-
-import scala.collection.immutable.ListMap
-import scala.language.existentials
-import scala.language.higherKinds
-
-import magnolia._
-import scala.reflect._
-import scala.reflect.macros._
-import scala.language.experimental.macros
-import scala.annotation.unchecked.uncheckedVariance
-
-
-object Show {
- type Typeclass[T] = Show[String, T]
- def join[T](context: JoinContext[Typeclass, T]): Show[String, T] = new Show[String, T] {
- def show(value: T) = context.parameters.map { param =>
- s"${param.label}=${param.typeclass.show(param.dereference(value))}"
- }.mkString(s"${context.typeName.split("\\.").last}(", ",", ")")
- }
-
- def dispatch[T](subclasses: Seq[Subclass[Typeclass, T]])(value: T): String =
- subclasses.map { sub => sub.cast.andThen { value =>
- sub.typeclass.show(sub.cast(value))
- } }.reduce(_ orElse _)(value)
-
- implicit val string: Show[String, String] = identity
- implicit val int: Show[String, Int] = new Show[String, Int] { def show(s: Int): String = s.toString }
- implicit def generic[T]: Show[String, T] = macro Magnolia.generic[T]
-}
-
-trait Show[Out, T] { def show(value: T): Out }
-
-object Eq {
- type Typeclass[T] = Eq[T]
- def join[T](context: JoinContext[Eq, T]): Eq[T] = new Eq[T] {
- def equal(value1: T, value2: T) =
- context.parameters.forall { param => param.typeclass.equal(param.dereference(value1), param.dereference(value2)) }
- }
-
- def dispatch[T](subclasses: Seq[Subclass[Eq, T]]): Eq[T] = new Eq[T] {
- def equal(value1: T, value2: T) =
- subclasses.map { case subclass =>
- subclass.cast.andThen { value => subclass.typeclass.equal(subclass.cast(value1), subclass.cast(value2)) }
- }.reduce(_ orElse _)(value1)
- }
-
- implicit val string: Eq[String] = _ == _
- implicit val int: Eq[Int] = _ == _
- implicit def generic[T]: Eq[T] = macro Magnolia.generic[T]
-}
-
-trait Eq[T] { def equal(value: T, value2: T): Boolean }
-
-object Default {
- type Typeclass[T] = Default[T]
- def join[T](context: JoinContext[Default, T]): Default[T] = new Default[T] {
- def default = context.construct { param => param.typeclass.default }
- }
-
- def dispatch[T](subclasses: Seq[Subclass[Default, T]])(): Default[T] = new Default[T] {
- def default = subclasses.head.typeclass.default
- }
-
- implicit val string: Default[String] = new Default[String] { def default = "" }
- implicit val int: Default[Int] = new Default[Int] { def default = 0 }
- implicit def generic[T]: Default[T] = macro Magnolia.generic[T]
-}
-
-trait Default[T] { def default: T }
-
-object Decoder {
- def join[T](context: JoinContext[Decoder, T])(value: String): T =
- context.construct { param => param.typeclass.decode(value) }
-
- def dispatch[T](subclasses: Seq[Subclass[Decoder, T]])(param: String): T =
- subclasses.map { subclass =>
- { case _ if decodes(subclass.typeclass, param) => subclass.typeclass.decode(param) }: PartialFunction[String, T]
- }.reduce(_ orElse _)(param)
-
- def decodes[T](tc: Decoder[T], s: String): Boolean = try { tc.decode(s); true } catch { case e: Exception => false }
-
- implicit val string: Decoder[String] = new Decoder[String] { def decode(str: String): String = str }
- implicit val int: Decoder[Int] = new Decoder[Int] { def decode(str: String): Int = str.toInt }
- implicit def generic[T]: Decoder[T] = macro Magnolia.generic[T]
-}
-
-trait Decoder[T] { def decode(str: String): T }
-
-sealed trait Tree[+T]
-case class Leaf[+L](value: L) extends Tree[L]
-case class Branch[+B](left: Tree[B], right: Tree[B]) extends Tree[B]
-
-sealed trait Entity
-
-case class Company(name: String) extends Entity
-case class Person(name: String, age: Int) extends Entity
-case class Address(line1: String, occupant: Person)
-
-
-
-sealed trait Alphabet
-
-case class Greek(άλφα: Letter, βήτα: Letter, γάμα: Letter, δέλτα: Letter, έψιλον: Letter, ζήτα: Letter, ήτα: Letter, θήτα: Letter) extends Alphabet
-case class Cyrillic(б: Letter, в: Letter, г: Letter, д: Letter, ж: Letter, з: Letter) extends Alphabet
-case class Latin(a: Letter, b: Letter, c: Letter, d: Letter, e: Letter, f: Letter, g: Letter, h: Letter, i: Letter, j: Letter, k: Letter, l: Letter, m: Letter) extends Alphabet
-
-case class Letter(name: String, phonetic: String)
-case class Country(name: String, language: Language, leader: Person)
-case class Language(name: String, code: String, alphabet: Alphabet)
-//case class Person(name: String, dateOfBirth: Date)
-case class Date(year: Int, month: Month, day: Int)
-
-sealed trait Month
-case object Jan extends Month
-case object Feb extends Month
-case object Mar extends Month
-case object Apr extends Month
-case object May extends Month
-case object Jun extends Month
-case object Jul extends Month
-case object Aug extends Month
-case object Sep extends Month
-case object Oct extends Month
-case object Nov extends Month
-case object Dec extends Month
-
diff --git a/tests/src/main/scala/adt.scala b/tests/src/main/scala/adt.scala
deleted file mode 100644
index 6d8a276..0000000
--- a/tests/src/main/scala/adt.scala
+++ /dev/null
@@ -1,7 +0,0 @@
-package adt
-
-import magnolia._, examples._
-
-object Gen {
- Show.generic[Alphabet]
-}
diff --git a/tests/src/main/scala/tests.scala b/tests/src/main/scala/tests.scala
index 3245e1b..06ccd30 100644
--- a/tests/src/main/scala/tests.scala
+++ b/tests/src/main/scala/tests.scala
@@ -8,13 +8,26 @@ import contextual.data.txt._
import scala.util._
+sealed trait Tree[+T]
+case class Leaf[+L](value: L) extends Tree[L]
+case class Branch[+B](left: Tree[B], right: Tree[B]) extends Tree[B]
+
+sealed trait Entity
+
+case class Company(name: String) extends Entity
+case class Person(name: String, age: Int) extends Entity
+case class Address(line1: String, occupant: Person)
+
+sealed trait Color
+case object Red extends Color
+case object Green extends Color
+case object Blue extends Color
+
object Tests extends TestApp {
- def tests() = {
+ def tests() = for(i <- 1 to 10000) {
import examples._
- compileTimeRestart()
-
test("construct a Show product instance") {
import examples._
Show.generic[Person].show(Person("John Smith", 34))
@@ -47,21 +60,21 @@ object Tests extends TestApp {
test("construct a default value") {
Default.generic[Entity].default
- }.assert(_ == (Company(""): Entity))
+ }.assert(_ == Company(""))
test("construction of Show instance for Leaf") {
scalac"""
import magnolia.examples._
implicitly[Show[String, Leaf[java.lang.String]]]
"""
- }.assert(_ == (Returns(fqt"magnolia.examples.Show[String,magnolia.examples.Leaf[String]]"): Compilation))
+ }.assert(_ == Returns(fqt"magnolia.examples.Show[String,magnolia.tests.Leaf[String]]"))
test("construction of Show instance for Tree") {
scalac"""
import magnolia.examples._
implicitly[Show[String, Tree[String]]]
"""
- }.assert(_ == (Returns(fqt"magnolia.examples.Show[String,magnolia.examples.Tree[String]]"): Compilation))
+ }.assert(_ == Returns(fqt"magnolia.examples.Show[String,magnolia.tests.Tree[String]]"))
test("serialize a Leaf") {
implicitly[Show[String, Leaf[String]]].show(Leaf("testing"))
@@ -70,6 +83,26 @@ object Tests extends TestApp {
test("serialize a Branch as a Tree") {
implicitly[Show[String, Tree[String]]].show(Branch(Leaf("LHS"), Leaf("RHS")))
}.assert(_ == "Branch[String](left=Leaf[String](value=LHS),right=Leaf[String](value=RHS))")
+
+ test("serialize case object") {
+ implicitly[Show[String, Red.type]].show(Red)
+ }.assert(_ == "Red()")
+
+ test("serialize case object as a sealed trait") {
+ implicitly[Show[String, Color]].show(Blue)
+ }.assert(_ == "Blue()")
+
+ test("decode a company") {
+ implicitly[Decoder[Company]].decode("""Company(name=Acme Inc)""")
+ }.assert(_ == Company("Acme Inc"))
+
+ test("decode a Person as an Entity") {
+ implicitly[Decoder[Entity]].decode("""Person(name=John Smith,age=32)""")
+ }.assert(_ == Person("John Smith", 32))
+
+ test("decode a nested product") {
+ implicitly[Decoder[Address]].decode("""Address(line1=53 High Street,occupant=Person(name=Richard Jones,age=44))""")
+ }.assert(_ == Address("53 High Street", Person("Richard Jones", 44)))
test("show error stack") {
scalac"""
@@ -78,16 +111,10 @@ object Tests extends TestApp {
case class Beta(alpha: Alpha)
Show.generic[Beta]
"""
- }.assert(_ == (TypecheckError(txt"""magnolia: could not find typeclass for type Double
+ }.assert(_ == TypecheckError(txt"""magnolia: could not find typeclass for type Double
| in parameter 'integer' of product type Alpha
| in parameter 'alpha' of product type Beta
- |"""): Compilation))
-
- //test("construct a decoder") {
- //Decoder.generic[Tree[String]].decode("string")
- //}.assert(_ == (Leaf("something"): Tree[String]))
+ |"""))
- compileTimeReport()
-
}
}