Adding implicits to expression's scope #18705
Unanswered
kciesielski
asked this question in
Metaprogramming
Replies: 1 comment 3 replies
-
Maybe something like this could help import scala.quoted.*
def givenExpression[T: Type, U: Type](e: Expr[T])(f: Expr[T ?=> U])(using Quotes): Expr[U] =
'{ implicit val x: T = $e; $f(using x) }
def fun(using a: Int): Int = a
def test(using Quotes) =
givenExpression('{23})('{ fun }) // generates: { implicit val x = 123; fun(using x) } |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm working on a problem (Scala 3 only), where my generated code has to call library code for typeclass derivation, but this derivation needs some implicits in scope. My inline method on top of this process first dynamically constructs these dependencies, and then I'd like to turn them into
givens
, to achieve something like:In my macro, the givens are generated as a list of expressions. Then I create the result expression with
Expr.block
, but myderive
call can't see the givens. I also tried to construct a tree using Symbols, Apply, etc., and convert it to Expr afterwards, but the final effect is the same. The result expression can be printed as a code and it looks like the example shown above, which works as expected when copied and pasted in isolation.The problem can be showcased in this minimal example:
Generated code printed with
TreeAnsiCode
is:and works as expected when just copied and pasted (prints
123
). However, it doesn't work whentestMacro
is called - summon returns None.(BTW I used
implicit
instead ofgiven
to make sure generated code indeed creates an implicit. For some reason usinggiven
and printing generated code givesfinal lazy val given_Int: scala.Int = 123
without thegiven
keyword.)I suspect that there's some limitation which doesn't allow the implicit scopes of expressions to be dynamically generated or altered in a macro, like I'm trying to. Could someone confirm this?
Beta Was this translation helpful? Give feedback.
All reactions