从Scala宏访问代码文件和行号? [英] Access code file and line number from Scala macro?

查看:128
本文介绍了从Scala宏访问代码文件和行号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Scala宏中访问代码文件的名称和行号?我看了 SIP-19 ,它说这很容易使用宏来实现...

How can I access the name of the code file and line number in a Scala macro? I looked at SIP-19 and it says it can be easily implemented using macros...

为了明确起见,我需要调用者的代码文件和行号.我已经有一个

To clarify, I want the code file and line number of the caller. I already have a debug macro and I want to modify it to print the line number and file name of whoever calls debug

推荐答案

您要c.macroApplication.pos,其中c用于Context.

c.enclosingPosition在堆栈上找到具有位置的最近的宏. (请参见另一个答案.)例如,如果您的assert宏为F"%p: $msg"生成树但未分配位置,则F宏将是无位置的.

c.enclosingPosition finds the nearest macro on the stack that has a position. (See the other answer.) For instance, if your assert macro generates a tree for F"%p: $msg" but doesn't assign a position, the F macro would be positionless.

来自字符串插值器宏F"%p"的示例:

Example from a string interpolator macro, F"%p":

  /* Convert enhanced conversions to something format likes.
   * %Q for quotes, %p for position, %Pf for file, %Pn line number,
   * %Pc column %Po offset.
   */
  private def downConvert(parts: List[Tree]): List[Tree] = {
    def fixup(t: Tree): Tree = {
      val Literal(Constant(s: String)) = t
      val r = "(?<!%)%(p|Q|Pf|Po|Pn|Pc)".r
      def p = c.macroApplication.pos
      def f(m: Match): String = m group 1 match {
        case "p"  => p.toString
        case "Pf" => p.source.file.name
        case "Po" => p.point.toString
        case "Pn" => p.line.toString
        case "Pc" => p.column.toString
        case "Q"  => "\""
      }
      val z = r.replaceAllIn(s, f _)
      Literal(Constant(z)) //setPos t.pos
    }
    parts map fixup
  }

这篇关于从Scala宏访问代码文件和行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆