-
-
Save propensive/94ec18663a7535db45bb7e2ef37178ff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Unpack: | |
import scala.quoted._ | |
import scala.compiletime._ | |
private def tupleType(s: String)(using q: Quotes): q.reflect.TypeRepr = | |
import q.reflect._ | |
val typeParams = | |
s.map{ c => | |
TypeRepr.of(using ConstantType(CharConstant(c)).asType) | |
}.toList | |
assert(typeParams.length > 0) | |
assert(typeParams.length < 23) | |
typeParams.length match | |
case 1 => typeParams.head | |
case l => | |
TypeRepr.typeConstructorOf(Class.forName(s"scala.Tuple$l")) | |
.appliedTo(typeParams) | |
private def unpackImpl[S <: Singleton & String: Type](using q: Quotes): Expr[Any] = | |
import q.reflect._ | |
TypeRepr.of[S] match | |
case ConstantType(StringConstant("")) => | |
'{EmptyTuple} | |
case ConstantType(StringConstant(str)) => | |
tupleType(str).asType match | |
case '[tpe] => | |
'{ Tuple.fromArray(${Expr(str.toArray)}).asInstanceOf[tpe] } | |
transparent inline def unpack[T <: Singleton & String] = | |
${ unpackImpl[T] } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment