How to run official reflection example

Viewed 280

I have a problem to use the official code to try some reflection [https://docs.scala-lang.org/overviews/reflection/environment-universes-mirrors.html]

I used sbt to create 2 packages, the app package depends on the macro package, I put the macro code in the macro package and import the code to app package to call it, but it was not working well.

import scala.reflect.macros.Context

case class Location(filename: String, line: Int, column: Int)

object Macros {
  def currentLocation: Location = macro impl

  def impl(c: Context): c.Expr[Location] = {
    import c.universe._
    val pos = c.macroApplication.pos
    val clsLocation = c.mirror.staticModule("Location") // get symbol of "Location" object
    c.Expr(Apply(Ident(clsLocation), List(Literal(Constant(pos.source.path)), Literal(Constant(pos.line)), Literal(Constant(pos.column)))))
  }
}

[error] scala.ScalaReflectionException: object Location not found. [error] at scala.reflect.internal.Mirrors$RootsBase.staticModule(Mirrors.scala:168) [error] at scala.reflect.internal.Mirrors$RootsBase.staticModule(Mirrors.scala:29) [error] at sg.bigo.Macros$.impl(Macros.scala:61) [error] currentLocation.column

1 Answers

The following project compiles

App.scala

import Macros.currentLocation

object App {
  def main(args: Array[String]): Unit = {
    println(
      currentLocation //Location(/media/data/Projects/macrosdemo213/core/src/main/scala/App.scala,6,7)
    )
  }
}

Macros.scala

import scala.language.experimental.macros
import scala.reflect.macros.blackbox

case class Location(filename: String, line: Int, column: Int)

object Macros {
  def currentLocation: Location = macro impl

  def impl(c: blackbox.Context): c.Tree = {
    import c.universe._
    val pos = c.macroApplication.pos
    val clsLocation = c.mirror.staticModule("Location")
    q"$clsLocation(${pos.source.path}, ${pos.line}, ${pos.column})"
  }
}

build.sbt

name := "macrosdemo213"

lazy val commonSettings = Seq(
  scalaVersion := "2.13.0",
  organization := "com.example",
  version := "1.0.0",
)


lazy val macros: Project = (project in file("macros")).settings(
  commonSettings,
  libraryDependencies ++= Seq(
    scalaOrganization.value % "scala-reflect" % scalaVersion.value,
  )
)

lazy val core: Project = (project in file("core")).aggregate(macros).dependsOn(macros).settings(
  commonSettings
)

build.properties

sbt.version = 1.2.8

Project structure

enter image description here

Related