scala - 如何运行官方反射示例

标签 scala macros scala-macros

我在使用官方代码尝试一些反射时遇到问题[ https://docs.scala-lang.org/overviews/reflection/environment-universes-mirrors.html]

我使用sbt创建了2个包,app包依赖于宏包,我将宏代码放在宏包中并将代码导入到app包中调用它,但效果不佳。

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)))))
  }
}

[错误] scala.ScalaReflectionException:找不到对象位置。 [错误] 在 scala.reflect.internal.Mirrors$RootsBase.staticModule(Mirrors.scala:168) [错误] 在 scala.reflect.internal.Mirrors$RootsBase.staticModule(Mirrors.scala:29) [错误] 在 sg.bigo.Macros$.impl(Macros.scala:61) [错误] currentLocation.column

最佳答案

编译以下项目

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)
    )
  }
}

宏.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

项目结构

enter image description here

关于scala - 如何运行官方反射示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56642599/

相关文章:

scala - 与不同类型但相同标签的无形状对齐

scala - Spark中的takeSample()函数

scala - spark中 "grouped"的替代

macros - 语法规则不完全卫生?

c - 使用宏的泛型编程 : tricks to determine type?

scala - 如何生成静态成员并将其添加到类型宏中的类?

scala - 如何在准引号中拼接各种类型的符号?

Scala/Akka 负载均衡

scala - Scala 中所有函数的父类(super class)型是什么?

c - 宏观参数