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
    }
   }
}
user
  • 7,435
  • 3
  • 14
  • 44
Lin Lee
  • 213
  • 2
  • 8
  • I guess it makes sense that you can't just splice a `Seq` (or `Vector`) of `Expr`s. You might have to do some lower-level stuff with the `Quotes` instance. – user Aug 03 '21 at 15:54
  • 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. – gianluca aguzzi Aug 04 '21 at 07:40
  • @gianlucaaguzzi this will generate a block. If place it in a class body, it actually in constructor instead of definitions of class. – Lin Lee Aug 04 '21 at 14:29
  • I see... What you want to do with `new StructuralTypeRoot { ${expr} }`? Have you already tried with a single expression?? – gianluca aguzzi Aug 05 '21 at 07:09
  • 1
    @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 body – Lin Lee Aug 05 '21 at 07:24
  • 1
    Have you read this [article](https://softwaremill.com/scala-3-macros-tips-and-tricks/#:~:text=Scala%203%20offers%20two%20basic%20metaprogramming%20modes%3A%20inlines,inline%20summon%20%28looking%20up%20given%20%2F%20implicit%20values%29.)? I think that to do the "dynamical" method injection you should leverage also `qouted.reflect.*`. – gianluca aguzzi Aug 06 '21 at 08:10
  • @gianlucaaguzzi Yes, It's a way to manipulate Trees, but not friendly enough. Thanks for your answer. I'll try to use it. – Lin Lee Aug 06 '21 at 10:17
  • https://stackoverflow.com/questions/68550985/method-override-with-scala-3-macros – Dmytro Mitin Sep 12 '22 at 13:55

0 Answers0