Description
I'm reading the Dotty document to learn the metaprogramming of Dotty.
I tried the code in https://dotty.epfl.ch/docs/reference/metaprogramming/macros.html by pasting them into a file I created in the dotty-example-project:
import scala.quoted._
def to[T, R](f: Expr[T] => Expr[R])(using QuoteContext): Expr[T => R] =
'{ (x: T) => ${ f('x) } }
def from[T, R](f: Expr[T => R])(using QuoteContext): Expr[T] => Expr[R] =
(x: Expr[T]) => '{ $f($x) }
They can't compile with 0.24-RC and 0.25-RC2.
Output
[error] -- Error: /home/shapeless-cat/IdeaProjects/dotty-example-project/src/main/scala/Macros.scala:4:10
[error] 4 | '{ (x: T) => ${ f('x) } }
[error] | ^
[error] | access to type T from wrong staging level:
[error] | - the definition is at level 0,
[error] | - but the access is at level 1.
[error] |
[error] | The access would be accepted with a given scala.quoted.Type[T]
[error] -- Error: /home/shapeless-cat/IdeaProjects/dotty-example-project/src/main/scala/Macros.scala:4:15
[error] 4 | '{ (x: T) => ${ f('x) } }
[error] | ^^^^^^^^^^
[error] | access to type R from wrong staging level:
[error] | - the definition is at level 0,
[error] | - but the access is at level 1.
[error] |
[error] | The access would be accepted with a given scala.quoted.Type[R]
[error] -- Error: /home/shapeless-cat/IdeaProjects/dotty-example-project/src/main/scala/Macros.scala:7:21
[error] 7 | (x: Expr[T]) => '{ $f($x) }
[error] | ^^
[error] | access to type T from wrong staging level:
[error] | - the definition is at level 0,
[error] | - but the access is at level 1.
[error] |
[error] | The access would be accepted with a given scala.quoted.Type[T]
[error] -- Error: /home/shapeless-cat/IdeaProjects/dotty-example-project/src/main/scala/Macros.scala:7:24
[error] 7 | (x: Expr[T]) => '{ $f($x) }
[error] | ^^
[error] | access to type T from wrong staging level:
[error] | - the definition is at level 0,
[error] | - but the access is at level 1.
[error] |
[error] | The access would be accepted with a given scala.quoted.Type[T]
[error] four errors found
[error] (Compile / compileIncremental) Compilation failed
[error] Total time: 6 s, completed Jun 17, 2020 12:37:32 PM
It seems add context bound Type
to the type parameters T
and R
can make the compilation succeed.
This is the document issue I want to report.
I also have a question related to this:
I read the document, maybe I didn't pay enough attention for some parts, I can't run some example code about macros. The reason is I don't know how to create a QuoteContext given instance -- I can't find a of how to do it in the document. For example, could someone tell me how to create a QuoteContext given instance to make this example code work:
val f1: Expr[Int => String] = to((x: Expr[Int]) => '{ $x.toString }) // '{ (x: Int) => x.toString }
val f2: Expr[Int] => Expr[String] = from('{ (x: Int) => x.toString }) // (x: Expr[Int]) => '{ ((x: Int) => x.toString)($x) }
f2('{2}) // '{ ((x: Int) => x.toString)(2) }
Thanks!