-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Macros: Create Function type of arbitrary arity via the reflect API #23326
-
Currently, it is not possible (to the best of my knowledge) to create a function type (like Function3
or Function52
) whose number and types of parameters become known only at macro expansion time.
There is the Closure(meth: Term, tpe: Option[TypeRepr])
method to construct such functions as terms, but I'm lacking a way to explicitly assign a type to such functions (via the tpe
parameter), as I'm unable to construct such function type.
My use case is to preserve the parameter names of the method the Closure
is closing over. I.e., I don't want parameters to be named v1
, v2
, ... as in FunctionN
, but use custom names.
As an unstable workaround, I'm tapping into compiler-internal APIs to achieve that:
// XXX: relying on compiler internals to obtain the corresponding FunctionN type. val functionType = methodType .asInstanceOf[dotty.tools.dotc.core.Types.Type] .toFunctionType()(using quotes.asInstanceOf[scala.quoted.runtime.impl.QuotesImpl].ctx) .asInstanceOf[TypeRepr] // refine the `apply` method in order to preserve parameter names val refinedFunctionType = Refinement( functionType, "apply", methodType, ) // explicitly specify the type of the closure Closure(Ident(methodSym.termRef), tpe = Some(refinedFunctionType))
This is a request to provide a public API to create function types, something like
trait FunctionTypeModule { def apply(params: List[(String, TypeRepr)], returnType: TypeRepr): TypeRepr }
Beta Was this translation helpful? Give feedback.