Skip to content

Instantly share code, notes, and snippets.

@vivekragunathan
Last active January 26, 2022 22:03
Show Gist options
  • Select an option

  • Save vivekragunathan/d05d904007237d6835540a14d4d23809 to your computer and use it in GitHub Desktop.

Select an option

Save vivekragunathan/d05d904007237d6835540a14d4d23809 to your computer and use it in GitHub Desktop.
// Real code is down below (scroll):
// Reading the scala 3 documentation on macros (https://docs.scala-lang.org/scala3/guides/macros/macros.html) and trying out this example in that page:
/*
// ----- inspect.scala
def inspectCode(x: Expr[Any])(using Quotes): Expr[Any] =
println(x.show)
x
inline def inspect(inline x: Any): Any = ${ inspectCode('x) }
// ------ main.scala
object main extends App { println(inspect(2+3)) }
**/
// The documentation says:
// The following macro implementation simply prints the expression of the provided argument...
// I was under the impression that the main code will print `2 + 3` instead of evaluating the
// expression and printing `5`. What am I missing?
// Same is the case with another example on the page:
// Calling our inspect macro inspect(sys error "abort") prints a string representation of the argument expression at compile time: scala.sys.error("abort")
// But passing `error("abort")` to `inspect` throws an exception and aborts.
import scala.quoted.*
object InspectCode:
inline def apply(inline x: Any) = ${ inspectCode('x) }
private def inspectCode(x: Expr[Any])(using Quotes): Expr[Any] =
println(x.show)
x
object InspectCodeByName:
inline def apply(inline x: => Any) = ${ inspectCodeByName('x) }
private def inspectCodeByName(x: Expr[Any])(using Quotes): Expr[Any] =
println(x.show)
x
@vivekragunathan

Copy link
Copy Markdown
Author
// Main.scala
def x: Int = 2 // Have also tried making the value non-constant (say via Random.nextInt())
def y: Int = 3

object main extends App { 
  println(InspectCode(x+y))
  println(InspectCodeByName(x+y))

  println(InspectCode(1 + 2))
  println(InspectCodeByName(1 + 2))  
}

All of the above calls evaluate the passed expression to a value instead of printing the expression as mentioned in the Scala 3 macros documentation. Or what am I reading wrong and misunderstanding?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment