jeudi 18 juin 2020

How to use quasiquotes with previously defined object

I just started studying scala compile-time reflection, and I got introduced to quasiquotes by the Scala official guides.

One concept I'm still struggling with is how am I supposed to work with quasiquotes (or reify, for that matter) if I want to generate the AST for an already defined object. Suppose I have an Object:

object MyObject {
  def method1() = "m1"
}

In order to get a tree, I know I can do

q"""{object MyObject {
  def method1() = "m1"
}}
"""

Doing this, however, prevents me from having the object actually defined in my scope (and I also need to define it entirely inside a String, throwing all code safety out of the window).

What I'd like to do to get that tree is something like this:

object MyObject {
  def method1() = "m1"
}

q"$MyObject" // or q"{MyObject}", I still don't fully understand the table on the Scala guide

I want to define the object, and, afterwards, use that definition to perform some checks over it (and throw some exception in compile-time, if need be), using a macro. To use a macro, I'll need to tree (or, at least, the expression), as far as I understood.

I already know how to do the checks I want using Scala reflection in run-time, but I thought using ASTs could be a good idea (and, on the process, I would learn something). I'm getting the feeling that I'm misunderstanding some basic concept on how to use ASTs, though - it seems like one can generate ASTs based on code declared on the call site only. I'm confused.

What am I misunderstanding here?





Aucun commentaire:

Enregistrer un commentaire