I’m writing a Kotlin compiler plugin and I’d like ...
# compiler
j
I’m writing a Kotlin compiler plugin and I’d like to get a
CompilerMessageSourceLocation
from my
IrElement
, which happens to be an
IrCallImpl
so that I can call
MessageCollector.report
with a useful source location. Is there an API somewhere to extract a source location from an element?
I’m failing on some of the nearby candidates
I’m in a transformer so I think I might be able to get something from the currentDeclarationParent?
z
Take a look at what Anvil does for its error messages? I know it's pretty good about this
j
Yeah! That was my first step. It throws CompilerExceptions which works great in PSI-mode but doesn’t work when I do an IR compile with Gradle
I ended up using this:
Copy code
/** Finds the line and column of [irElement] within this file. */
fun IrFile.locationOf(irElement: IrElement?): CompilerMessageSourceLocation {
  val sourceRangeInfo = fileEntry.getSourceRangeInfo(
    beginOffset = irElement?.startOffset ?: UNDEFINED_OFFSET,
    endOffset = irElement?.endOffset ?: UNDEFINED_OFFSET
  )
  return CompilerMessageLocationWithRange.create(
    path = sourceRangeInfo.filePath,
    lineStart = sourceRangeInfo.startLineNumber + 1,
    columnStart = sourceRangeInfo.startColumnNumber + 1,
    lineEnd = sourceRangeInfo.endLineNumber + 1,
    columnEnd = sourceRangeInfo.endColumnNumber + 1,
    lineContent = null
  )!!
}
passing the file obtained through other means
a
Two years later and this suggestion is still useful!