Not scala starting position with scala macros

I have a scala macro that depends on an arbitrary xml file that is specified through a static string containing its location.

def myMacro(path: String) = macro myMacroImpl

def myMacroImpl(c: Context)(path: c.Expr[String]): c.Expr[Any] = {
  // load file specified by path and generate some code
  ...
}

This means that if the xml file is distorted, the macro will not be able to expand. At that moment, when I provide an error message containing a textual representation of the location of the error in the XML file. This, however, is obviously not the most pleasant solution.

Is it possible to provide the source locations in different (maybe not scala) files for my generated code so that errors point to the xml file instead of the scala file where the xml file was included? I don’t see how I can create locations myself, and not modify existing ones.

+4
1

, , API . , API , , , , .

import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
import scala.reflect.io.AbstractFile
import scala.reflect.internal.util.BatchSourceFile
import scala.reflect.internal.util.OffsetPosition

class Impl(val c: Context) {
  def impl: c.Tree = {
    val filePath = "foo.txt"
    val af = AbstractFile.getFile(filePath)
    val content = scala.io.Source.fromFile(filePath).mkString
    val sf = new BatchSourceFile(af, content)
    val pos = new OffsetPosition(sf, 3).asInstanceOf[c.universe.Position]
    c.abort(pos, "it works")
  }
}

object Macros {
  def foo: Any = macro Impl.impl
}

object Test extends App {
  Macros.foo
}

:

20:56 ~/Projects/Master/sandbox (master)$ cat foo.txt
hello
world
20:56 ~/Projects/Master/sandbox (master)$ scalac Test.scala
foo.txt:1: error: it works
hello
   ^
one error found

, scala.reflect.internal ( , scala-reflect.jar), , .

+4

Source: https://habr.com/ru/post/1537509/


All Articles