Skip to content

Commit

Permalink
Fix DeriveSchema for parameterized enums (#607)
Browse files Browse the repository at this point in the history
* fix enum derive

* fix test
  • Loading branch information
pablf authored Sep 15, 2023
1 parent 0e06f98 commit 952fae3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -324,11 +324,12 @@ private case class DeriveSchema()(using val ctx: Quotes) extends ReflectionUtils

val cases = typesAndLabels.map { case (tpe, label) => deriveCase[T](tpe, label, newStack) }

val isSimpleEnum: Boolean = !TypeRepr.of[T].typeSymbol.children.map(_.declaredFields.length).exists( _ > 0 )
val numParentFields: Int = TypeRepr.of[T].typeSymbol.declaredFields.length
val isSimpleEnum: Boolean = !TypeRepr.of[T].typeSymbol.children.map(_.declaredFields.length).exists( _ > numParentFields )
val hasSimpleEnumAnn: Boolean = TypeRepr.of[T].typeSymbol.hasAnnotation(TypeRepr.of[_root_.zio.schema.annotation.simpleEnum].typeSymbol)

val annotationExprs = (isSimpleEnum, hasSimpleEnumAnn) match {
case (true, false) => TypeRepr.of[T].typeSymbol.annotations.filter(filterAnnotation).map(_.asExpr).+:('{_root_.zio.schema.annotation.simpleEnum(true)})
case (true, false) => TypeRepr.of[T].typeSymbol.annotations.filter(filterAnnotation).map(_.asExpr).+:('{zio.schema.annotation.simpleEnum(true)})
case (false, true) => throw new Exception(s"${TypeRepr.of[T].typeSymbol.name} must be a simple Enum")
case _ => TypeRepr.of[T].typeSymbol.annotations.filter(filterAnnotation).map(_.asExpr)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package zio.schema

import zio.Chunk
import zio.test.*
import zio.schema.annotation.simpleEnum

trait VersionSpecificDeriveSchemaSpec extends ZIOSpecDefault {
case class ContainerFields(field1: Option[String])
Expand All @@ -20,6 +22,12 @@ trait VersionSpecificDeriveSchemaSpec extends ZIOSpecDefault {

final case class AutoDerives(i: Int) derives Schema

enum Colour(val rgb: Int) {
case Red extends Colour(0xff0000)
case Green extends Colour(0x00ff00)
case Blue extends Colour(0x0000ff)
}

def versionSpecificSuite = Spec.labeled(
"Scala 3 specific tests",
suite("Derivation")(
Expand All @@ -35,6 +43,10 @@ trait VersionSpecificDeriveSchemaSpec extends ZIOSpecDefault {
AutoDerives.apply
)
assert(Schema[AutoDerives])(hasSameSchema(expected))
},
test("correctly assigns simpleEnum to enum") {
val derived: Schema[Colour] = DeriveSchema.gen[Colour]
assertTrue(derived.annotations == Chunk(simpleEnum(true)))
}
)
)
Expand Down

0 comments on commit 952fae3

Please sign in to comment.