|
| 1 | +package derivation |
| 2 | +import scala.quoted.* |
| 3 | + |
| 4 | +import scala.annotation.tailrec |
| 5 | + |
| 6 | +object Helpers: |
| 7 | + |
| 8 | + // file a.scala |
| 9 | + inline def summonAllOptimized[T <: Tuple]: T = |
| 10 | + ${ summonAllOptimizedImpl[T] } |
| 11 | + |
| 12 | + inline def summon23[E]: (E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E) = |
| 13 | + ${ summon23Impl[E] } |
| 14 | + |
| 15 | + private def summonAllOptimizedImpl[T <: Tuple: Type](using q: Quotes): Expr[T] = { |
| 16 | + import q.reflect.* |
| 17 | + |
| 18 | + Expr |
| 19 | + .ofTupleFromSeq(typesOfTuple(TypeRepr.of[T], Nil).map { tpe => |
| 20 | + tpe.asType match { |
| 21 | + case '[t] => |
| 22 | + Expr.summon[t].getOrElse(report.errorAndAbort(s"Unable to to find implicit instance for ${tpe.show}")) |
| 23 | + } |
| 24 | + }) |
| 25 | + .asExprOf[T] |
| 26 | + } |
| 27 | + |
| 28 | + private def summon23Impl[E: Type](using q: Quotes): Expr[(E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E)] = { |
| 29 | + import q.reflect.* |
| 30 | + |
| 31 | + val e = Expr.summon[E].getOrElse(report.errorAndAbort(s"Unable to to find implicit instance for ${TypeRepr.of[E].show}")) |
| 32 | + |
| 33 | + val tuple = (e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e) |
| 34 | + |
| 35 | + assert(tuple.size == 23) |
| 36 | + |
| 37 | + Expr.ofTuple(tuple) |
| 38 | + } |
| 39 | + |
| 40 | + @tailrec |
| 41 | + private[derivation] def typesOfTuple( |
| 42 | + using q: Quotes |
| 43 | + )(tpe: q.reflect.TypeRepr, acc: List[q.reflect.TypeRepr]): List[q.reflect.TypeRepr] = |
| 44 | + import q.reflect.* |
| 45 | + val cons = Symbol.classSymbol("scala.*:") |
| 46 | + tpe.widenTermRefByName.dealias match |
| 47 | + case AppliedType(fn, tpes) if defn.isTupleClass(fn.typeSymbol) => |
| 48 | + tpes.reverse_:::(acc) |
| 49 | + case AppliedType(tp, List(headType, tailType)) if tp.derivesFrom(cons) => |
| 50 | + typesOfTuple(tailType, headType :: acc) |
| 51 | + case tpe => |
| 52 | + if tpe.derivesFrom(Symbol.classSymbol("scala.EmptyTuple")) then acc.reverse |
| 53 | + else report.errorAndAbort(s"Unknown type encountered in tuple ${tpe.show}") |
0 commit comments