Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto enum field derivation [Scala 3] #1834

Merged
merged 4 commits into from
Aug 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions core/src/main/scala-3/caliban/schema/ArgBuilderDerivation.scala
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,21 @@ import scala.compiletime.*
import scala.util.NotGiven

trait CommonArgBuilderDerivation {
inline def recurse[Label, A <: Tuple](
inline def recurse[P, Label, A <: Tuple](
inline values: List[(String, List[Any], ArgBuilder[Any])] = Nil
): List[(String, List[Any], ArgBuilder[Any])] =
inline erasedValue[(Label, A)] match {
case (_: EmptyTuple, _) => values.reverse
case (_: (name *: names), _: (t *: ts)) =>
recurse[names, ts](
recurse[P, names, ts](
(
constValue[name].toString,
Macros.annotations[t],
summonInline[ArgBuilder[t]].asInstanceOf[ArgBuilder[Any]]
Macros.annotations[t], {
if (Macros.isEnumField[P, t])
if (!Macros.implicitExists[ArgBuilder[t]]) derived[t]
else summonInline[ArgBuilder[t]]
else summonInline[ArgBuilder[t]]
}.asInstanceOf[ArgBuilder[Any]]
) :: values
)
}
Expand All @@ -31,13 +35,13 @@ trait CommonArgBuilderDerivation {
inline summonInline[Mirror.Of[A]] match {
case m: Mirror.SumOf[A] =>
makeSumArgBuilder[A](
recurse[m.MirroredElemLabels, m.MirroredElemTypes](),
recurse[A, m.MirroredElemLabels, m.MirroredElemTypes](),
constValue[m.MirroredLabel]
)

case m: Mirror.ProductOf[A] =>
makeProductArgBuilder(
recurse[m.MirroredElemLabels, m.MirroredElemTypes](),
recurse[A, m.MirroredElemLabels, m.MirroredElemTypes](),
Macros.paramAnnotations[A].to(Map)
)(m.fromProduct)
}
Expand Down
8 changes: 6 additions & 2 deletions core/src/main/scala-3/caliban/schema/SchemaDerivation.scala
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,12 @@ trait CommonSchemaDerivation {
else
(
constValue[name].toString,
Macros.annotations[t],
summonInline[Schema[R, t]].asInstanceOf[Schema[R, Any]],
Macros.annotations[t], {
if (Macros.isEnumField[P, t])
if (!Macros.implicitExists[Schema[R, t]]) derived[R, t]
else summonInline[Schema[R, t]]
else summonInline[Schema[R, t]]
}.asInstanceOf[Schema[R, Any]],
index
) :: values
}(index + 1)
Expand Down
16 changes: 16 additions & 0 deletions core/src/main/scala-3/caliban/schema/macros/Macros.scala
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ private[caliban] object Macros {
inline def paramAnnotations[T]: List[(String, List[Any])] = ${ paramAnnotationsImpl[T] }
inline def typeInfo[T]: TypeInfo = ${ typeInfoImpl[T] }
inline def isFieldExcluded[P, T]: Boolean = ${ isFieldExcludedImpl[P, T] }
inline def isEnumField[P, T]: Boolean = ${ isEnumFieldImpl[P, T] }
inline def implicitExists[T]: Boolean = ${ implicitExistsImpl[T] }

def annotationsImpl[T: Type](using qctx: Quotes): Expr[List[Any]] = {
import qctx.reflect.*
Expand Down Expand Up @@ -72,4 +74,18 @@ private[caliban] object Macros {
&& v.annotations.exists(_.tpe =:= TypeRepr.of[GQLExcluded])
})
}

def implicitExistsImpl[T: Type](using q: Quotes): Expr[Boolean] = {
import quotes.reflect._
Implicits.search(TypeRepr.of[T]) match {
case _: ImplicitSearchSuccess => Expr(true)
case _: ImplicitSearchFailure => Expr(false)
}
}

def isEnumFieldImpl[P: Type, T: Type](using q: Quotes): Expr[Boolean] = {
import q.reflect.*
Expr(TypeRepr.of[P].typeSymbol.flags.is(Flags.Enum) && TypeRepr.of[T].typeSymbol.flags.is(Flags.Enum))
}

}
96 changes: 96 additions & 0 deletions core/src/test/scala-3/caliban/schema/EnumFieldAutoDerivation.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package caliban.schema

import caliban.{ graphQL, RootResolver }
import zio.ZIO
import zio.test.*

object EnumFieldAutoDerivation extends ZIOSpecDefault {
import caliban.schema.Schema.*

override def spec = suite("EnumFieldAutoDerivation")(
test("A schema & argbuilder is created automatically for enums") {
val expected =
"""schema {
| query: Query
|}
|
|enum Bar {
| BarA
| BarB
|}
|
|enum Foo {
| FooA
| FooB
|}
|
|type Query {
| foo(value: Bar): Value!
|}
|
|type Value {
| value: Foo!
|}""".stripMargin

given Schema[Any, Foo] = Schema.derived
given Schema[Any, Bar] = Schema.derived
given Schema[Any, Value] = Schema.derived
given ArgBuilder[Bar] = ArgBuilder.derived

given Schema[Any, Query] = Schema.Auto.derived

val resolver = RootResolver(Query(_ => Value(Foo.FooA)))
val gql = graphQL(resolver)

assertTrue(gql.render == expected)
},
test("A provided Schema take priority over auto-derivation") {
given Schema[Any, Foo.FooB.type] = throw TestError
given Schema[Any, Foo] = Schema.derived
given Schema[Any, Value] = Schema.derived
given Schema[Any, Bar] = Schema.derived
given ArgBuilder[Bar] = ArgBuilder.derived
given Schema[Any, Query] = Schema.derived
val resolver = RootResolver(Query(_ => Value(Foo.FooA)))

try {
graphQL(resolver).render
assertNever("Should have errored")
} catch {
case TestError => assertCompletes
case _ => assertNever("Invalid error")
}
},
test("A provided ArgBuilder take priority over auto-derivation") {
given Schema[Any, Foo] = Schema.derived
given Schema[Any, Bar] = Schema.derived
given Schema[Any, Value] = Schema.derived
given ArgBuilder[Bar.BarA.type] = throw TestError
given ArgBuilder[Bar] = ArgBuilder.derived
given Schema[Any, Query] = Schema.derived

val resolver = RootResolver(Query(_ => Value(Foo.FooA)))
val gql = graphQL(resolver)

val q = """query { foo(value: BarB) { value } }"""
gql.interpreter.flatMap(_.execute(q)).catchAllDefect(ZIO.fail(_)).either.flatMap {
case Right(_) => assertNever("Should have errored")
case Left(e) if e.getMessage.contains("boom") => assertCompletes
case _ => assertNever("wrong error")
}
}
)

enum Foo {
case FooA, FooB
}

enum Bar {
case BarA, BarB
}

case class Value(value: Foo)
case class Query(foo: Option[Bar] => Value)

case object TestError extends Throwable("boom")
}