How to splice multiple expressions in quote syntax of scala 3 macros?
Asked Answered
S

0

3

I learned how to splice expr in quotes now. But I didn't find how to splice multiple exprs in a quote. I have a selectable trait and a macro impl function:

trait StructuralTypeRoot extends Selectable

def macroImpl(using q: Quotes): Expr[Any] = {
  val exprs: Vector[Expr[Any]] = Vector(
    '{def f = 1},
    '{def g = 2}) /*make some method def exprs here*/

  '{
    new StructuralTypeRoot{
      ${exprs} // can't do this. How can i splice exprs here
    }
   }
}
Sparid answered 3/8, 2021 at 14:29 Comment(8)
I guess it makes sense that you can't just splice a Seq (or Vector) of Exprs. You might have to do some lower-level stuff with the Quotes instance.Nagana
If each expression is independent, a way to do that could be combined expression with ;. For example, you can write: val combinedExpression : Expr[Any] = exprs.reduce((a, b) => '{$a;$b}) In this way, combinedExpression is an Expr[Any] (not a Vector). BTW I don't know if it is possible to do what you want with splicing, namely adding method to an anonymous object.Olsewski
@gianlucaaguzzi this will generate a block. If place it in a class body, it actually in constructor instead of definitions of class.Sparid
I see... What you want to do with new StructuralTypeRoot { ${expr} }? Have you already tried with a single expression??Olsewski
@gianlucaaguzzi I don't know how to splice it. So the code in question is just my intention: dynamically create a set of methods from a list in a class or trait bodySparid
Have you read this article? I think that to do the "dynamical" method injection you should leverage also qouted.reflect.*.Olsewski
@gianlucaaguzzi Yes, It's a way to manipulate Trees, but not friendly enough. Thanks for your answer. I'll try to use it.Sparid
#68551485Nicolnicola

© 2022 - 2024 — McMap. All rights reserved.