scalascala-macrosscala-3

Scala 3 macro: creating a path-dependent method signature


In Scala 3, I'm trying to generate a method within a macro that has a path-dependent type, but I can't find an API that lets me create such a signature.

Given the following definition:

trait Foo:
  type Out

I want to generate a def of the following shape:

def bar(x: Foo): x.Out

So I use Symbol.newMethod like so:

Symbol.newMethod(
  Symbol.spliceOwner,
  "bar",
  MethodType(List("x"))(_ => List(TypeRepr.of[Foo]), mt => ???))

But how do I specify the ???? I need to reference x there somehow, but there doesn't seem to be an API for that.

Looking at the generated Tree for such code, I see the following:

TypeSelect(Ident("x"), "Out"))

But Ident requires a TermRef, is there a way to acquire one for the method's argument?

Thanks


Solution

  • Try

    MethodType(List("x"))(_ => List(TypeRepr.of[Foo]), mt =>
      mt.param(0).select(TypeRepr.of[Foo].typeSymbol.typeMember("Out"))
    )
    

    (Scala 3 macros: create a new polynmorphic function using the reflect api def apply[X](a: X): X = a)