Macro generates an empty instance of a case class based on implicitly provided values for all the properties.
The current state of the solution can be found on GH: https://github.com/atais/empty/blob/main/empty-macro/src/main/scala/com/github/atais/empty/EmptyMacro.scala
Currently, the definition of the macro expands to:
implicit val emptyFoo0: Empty[Foo0] = {
...
override val value: com.github.atais.Foo0 = new com.github.atais.Foo0(implicitly[Empty[String]].value, implicitly[Empty[Boolean]].value, implicitly[Empty[Int]].value)
...
}
Which works fine, but I would like to inline the implicit values into the generated code. I believe it should be faster (will see about that). So I expect it to be:
implicit val emptyFoo0: Empty[Foo0] = {
...
override def value: com.github.atais.Foo0 = new com.github.atais.Foo0("", false, 0)
...
}
So I believe the code that requires improvement is:
weakTypeOf[A].decls
.collect {
case m: MethodSymbol if m.isCaseAccessor => m
}
.map(_.returnType)
.map { fieldType =>
val emptyImplicitType = tq"Empty[$fieldType]"
q"implicitly[$emptyImplicitType].value"
}
ChatGPT helped me to the point:
.map { fieldType =>
val empty = tq"Empty[$fieldType]"
val t = c.typecheck(empty, c.TYPEmode)
val i = c.inferImplicitValue(t.tpe)
val q = q"$i.value"
q
}
which gives
override val value: com.github.atais.empty.Foo30 = new com.github.atais.empty.Foo30(MacroEmptyInstances.this.emptyFoo28.value, MacroEmptyInstances.this.emptyFoo29.value)
But I don't know how to pull the values into generated code.
Try to use
c.eval. Replacewith
or
(*) https://docs.scala-lang.org/overviews/quasiquotes/lifting.html#standard-liftables
But you'll have to re-organize your project a little (implicit instances). Currently this fails with compile error
java.lang.ClassNotFoundException: atais.empty.MacroEmptyInstances$.The following code compiles:
macro project:
core project: