Skip to content

Commit

Permalink
refactor: scala 3 const enum: simplify and cleanup (#1126)
Browse files Browse the repository at this point in the history
  • Loading branch information
ThijsBroersen authored Jun 17, 2024
1 parent 5773f6c commit 4930439
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 29 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,4 @@ trait DecoderLowPriorityVersionSpecific {
case _ => Left("expected one of: " + values.toList.mkString(", "))
}
)

inline given constStringToEnum[T <: String](using IsConst[T] =:= true): JsonDecoder[T] =
JsonDecoder.string.mapOrFail(
{
case raw if raw == constValue[T] => Right(constValue[T])
case _ => Left("expected one of: " + constValue[T])
}
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,4 @@ private[json] trait EncoderLowPriorityVersionSpecific {

inline given unionOfStringEnumeration[T](using IsUnionOf[String, T]): JsonEncoder[T] =
JsonEncoder.string.asInstanceOf[JsonEncoder[T]]

inline given constStringToEnum[T <: String](using IsConst[T] =:= true): JsonEncoder[T] =
JsonEncoder.string.narrow[T]
}
22 changes: 4 additions & 18 deletions zio-json/shared/src/main/scala-3/zio/json/union_derivation.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,6 @@ import scala.compiletime.*
import scala.deriving.*
import scala.quoted.*

@scala.annotation.implicitNotFound("${A} is not a union type")
sealed trait IsUnion[A]

object IsUnion:

private val singleton: IsUnion[Any] = new IsUnion[Any] {}

transparent inline given derived[A]: IsUnion[A] = ${ deriveImpl[A] }

private def deriveImpl[A](using quotes: Quotes, t: Type[A]): Expr[IsUnion[A]] =
import quotes.reflect.*
val tpe: TypeRepr = TypeRepr.of[A]
tpe.dealias match
case o: OrType => ('{ IsUnion.singleton.asInstanceOf[IsUnion[A]] }).asExprOf[IsUnion[A]]
case other => report.errorAndAbort(s"${tpe.show} is not a Union")

@scala.annotation.implicitNotFound("${A} is not a union of ${T}")
sealed trait IsUnionOf[T, A]

Expand All @@ -44,10 +28,12 @@ object IsUnionOf:
else report.errorAndAbort(s"${o.show} is not a subtype of ${bound.show}")

tpe.dealias match
case o: OrType =>
case o: OrType =>
validateTypes(o)
('{ IsUnionOf.singleton.asInstanceOf[IsUnionOf[T, A]] }).asExprOf[IsUnionOf[T, A]]
case other => report.errorAndAbort(s"${tpe.show} is not a Union")
case o =>
if o <:< bound then ('{ IsUnionOf.singleton.asInstanceOf[IsUnionOf[T, A]] }).asExprOf[IsUnionOf[T, A]]
else report.errorAndAbort(s"${tpe.show} is not a Union")

object UnionDerivation:
transparent inline def constValueUnionTuple[T, A](using IsUnionOf[T, A]): Tuple = ${ constValueUnionTupleImpl[T, A] }
Expand Down

0 comments on commit 4930439

Please sign in to comment.