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

refactor: scala 3 const enum: simplify and cleanup #1126

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
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]
}
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
Loading