|
| 1 | +package x |
| 2 | + |
| 3 | +import scala.quoted._ |
| 4 | + |
| 5 | +trait CB[T]: |
| 6 | + def map[S](f: T=>S): CB[S] = ??? |
| 7 | + |
| 8 | +class MyArr[A]: |
| 9 | + def map1[B](f: A=>B):MyArr[B] = ??? |
| 10 | + def map1Out[B](f: A=> CB[B]): CB[MyArr[B]] = ??? |
| 11 | + |
| 12 | +def await[T](x:CB[T]):T = ??? |
| 13 | + |
| 14 | +object CBM: |
| 15 | + def pure[T](t:T):CB[T] = ??? |
| 16 | + |
| 17 | +object X: |
| 18 | + |
| 19 | + inline def process[T](inline f:T) = ${ |
| 20 | + processImpl[T]('f) |
| 21 | + } |
| 22 | + |
| 23 | + def processImpl[T:Type](f:Expr[T])(using qctx: QuoteContext):Expr[CB[T]] = |
| 24 | + import qctx.reflect._ |
| 25 | + |
| 26 | + def transform(term:Term):Term = |
| 27 | + term match |
| 28 | + case ap@Apply(TypeApply(Select(obj,"map1"),targs),args) => |
| 29 | + val nArgs = args.map(x => shiftLambda(x)) |
| 30 | + val nSelect = Select.unique(obj, "map1Out") |
| 31 | + Apply(TypeApply(nSelect,targs),nArgs) |
| 32 | + //Apply.copy(ap)(TypeApply(nSelect,targs),nArgs) |
| 33 | + case Apply(TypeApply(Ident("await"),targs),args) => args.head |
| 34 | + case Apply(x,y) => |
| 35 | + Apply(x, y.map(transform)) |
| 36 | + case Block(stats, last) => Block(stats, transform(last)) |
| 37 | + case Inlined(x,List(),body) => transform(body) |
| 38 | + case l@Literal(x) => |
| 39 | + '{ CBM.pure(${term.seal}) }.unseal |
| 40 | + case other => |
| 41 | + throw RuntimeException(s"Not supported $other") |
| 42 | + |
| 43 | + def shiftLambda(term:Term): Term = |
| 44 | + term match |
| 45 | + case lt@Lambda(params, body) => |
| 46 | + val paramTypes = params.map(_.tpt.tpe) |
| 47 | + val paramNames = params.map(_.name) |
| 48 | + val mt = MethodType(paramNames)(_ => paramTypes, _ => Type[CB].unseal.tpe.appliedTo(body.tpe.widen) ) |
| 49 | + val r = Lambda(mt, args => changeArgs(params,args,transform(body)) ) |
| 50 | + r |
| 51 | + case _ => |
| 52 | + throw RuntimeException("lambda expected") |
| 53 | + |
| 54 | + def changeArgs(oldArgs:List[Tree], newArgs:List[Tree], body:Term):Term = |
| 55 | + val association: Map[Symbol, Term] = (oldArgs zip newArgs).foldLeft(Map.empty){ |
| 56 | + case (m, (oldParam, newParam: Term)) => m.updated(oldParam.symbol, newParam) |
| 57 | + case (m, (oldParam, newParam: Tree)) => throw RuntimeException("Term expected") |
| 58 | + } |
| 59 | + val changes = new TreeMap() { |
| 60 | + override def transformTerm(tree:Term)(using Context): Term = |
| 61 | + tree match |
| 62 | + case ident@Ident(name) => association.getOrElse(ident.symbol, super.transformTerm(tree)) |
| 63 | + case _ => super.transformTerm(tree) |
| 64 | + } |
| 65 | + changes.transformTerm(body) |
| 66 | + |
| 67 | + transform(f.unseal).seal.cast[CB[T]] |
0 commit comments