在 Kotlin 注解处理期间如何访问方法体?

Tag*_*agc 4 annotation-processing kotlin

概述

我想知道是否有一种方法可以将注释应用于函数并在注释处理期间访问这些函数的主体。如果无法通过检查Element注释处理器中的对象来直接获取方法主体,是否有其他方法可以访问应用这些注释的函数的源代码?

细节

作为我正在从事的项目的一部分,我尝试使用 kapt 来检查使用特定类型注释进行注释的 Kotlin 函数,并基于它们生成类。例如,给定一个带注释的函数,如下所示:

@ElementaryNode
fun addTwoNumbers(x: Int, y: Int) = x + y
Run Code Online (Sandbox Code Playgroud)

我的注释处理器当前生成以下内容:

class AddTwoNumbers : Node {
    val x: InputPort<Int> = TODO("implement node port property")

    val y: InputPort<Int> = TODO("implement node port property")

    val output: OutputPort<Int> = TODO("implement node port property")
}
Run Code Online (Sandbox Code Playgroud)

但是,我需要将原始函数本身包含在此类中,本质上就像将其作为私有函数复制/粘贴一样:

class AddTwoNumbers : Node {
    val x: InputPort<Int> = TODO("implement node port property")

    val y: InputPort<Int> = TODO("implement node port property")

    val output: OutputPort<Int> = TODO("implement node port property")

    private fun body(x: Int, y: Int) = x + y
}
Run Code Online (Sandbox Code Playgroud)

我尝试过的

基于这个答案,我尝试使用来访问与注释函数对应的com.sun.source.util.Trees方法体:ExecutableElement

override fun inspectElement(element: Element) {
    if (element !is ExecutableElement) {
        processingEnv.messager.printMessage(
            Diagnostic.Kind.ERROR,
            "Cannot generate elementary node from non-executable element"
        )

        return
    }

    val docComment = processingEnv.elementUtils.getDocComment(element)
    val trees = Trees.instance(processingEnv)
    val body = trees.getTree(element).body
    processingEnv.messager.printMessage(Diagnostic.Kind.WARNING, "Processing ${element.simpleName}: $body")
}
Run Code Online (Sandbox Code Playgroud)

然而,kapt 只生成方法体的存根,所以我为每个方法体得到的只是这样的东西:

@ElementaryNode
fun addTwoNumbers(x: Int, y: Int) = x + y
Run Code Online (Sandbox Code Playgroud)

更新

访问Element.enclosingElement代表ExecutableElement每个函数时,可以得到定义该函数的包/模块的限定名称。例如,addTwoNumbers被声明为 中的顶级函数Main.kt,并且在注释处理期间我得到以下输出:Processing addTwoNumbers: com.mycompany.testmaster.playground.MainKt

有没有办法可以Main.kt根据此信息访问原始源文件 ( )?

Tag*_*agc 6

这并不容易,但我最终设法找到了一个(相当古怪的)解决方案。

我发现在注释处理过程中,Kotlin 在临时构建输出目录下生成元数据文件。这些元数据文件包含序列化信息,其中包括包含我正在处理的注释的原始源文件的路径:

查看 Kapt 插件的源代码,我发现这个文件使我能够弄清楚如何反序列化这些文件中的信息,从而使我能够提取原始源代码的位置。

我创建了一个 Kotlin 对象SourceCodeLocator,将所有这些放在一起,这样我就可以向它传递一个Element表示函数的参数,并且它会返回包含它的源代码的字符串表示形式:

package com.mycompany.testmaster.nodegen.parsers

import com.mycompany.testmaster.nodegen.KAPT_KOTLIN_GENERATED_OPTION_NAME
import com.mycompany.testmaster.nodegen.KAPT_METADATA_EXTENSION
import java.io.ByteArrayInputStream
import java.io.File
import java.io.ObjectInputStream
import javax.annotation.processing.ProcessingEnvironment
import javax.lang.model.element.Element
import javax.lang.model.element.ElementKind
import javax.lang.model.element.ExecutableElement

internal object SourceCodeLocator {
    fun sourceOf(function: Element, environment: ProcessingEnvironment): String {
        if (function !is ExecutableElement)
            error("Cannot extract source code from non-executable element")

        return getSourceCodeContainingFunction(function, environment)
    }

    private fun getSourceCodeContainingFunction(function: Element, environment: ProcessingEnvironment): String {
        val metadataFile = getMetadataForFunction(function, environment)
        val path = deserializeMetadata(metadataFile.readBytes()).entries
            .single { it.key.contains(function.simpleName) }
            .value

        val sourceFile = File(path)
        assert(sourceFile.isFile) { "Source file does not exist at stated position within metadata" }

        return sourceFile.readText()
    }

    private fun getMetadataForFunction(element: Element, environment: ProcessingEnvironment): File {
        val enclosingClass = element.enclosingElement
        assert(enclosingClass.kind == ElementKind.CLASS)

        val stubDirectory = locateStubDirectory(environment)
        val metadataPath = enclosingClass.toString().replace(".", "/")
        val metadataFile = File("$stubDirectory/$metadataPath.$KAPT_METADATA_EXTENSION")

        if (!metadataFile.isFile) error("Cannot locate kapt metadata for function")
        return metadataFile
    }

    private fun deserializeMetadata(data: ByteArray): Map<String, String> {
        val metadata = mutableMapOf<String, String>()

        val ois = ObjectInputStream(ByteArrayInputStream(data))
        ois.readInt() // Discard version information

        val lineInfoCount = ois.readInt()
        repeat(lineInfoCount) {
            val fqName = ois.readUTF()
            val path = ois.readUTF()
            val isRelative = ois.readBoolean()
            ois.readInt() // Discard position information

            assert(!isRelative)

            metadata[fqName] = path
        }

        return metadata
    }

    private fun locateStubDirectory(environment: ProcessingEnvironment): File {
        val kaptKotlinGeneratedDir = environment.options[KAPT_KOTLIN_GENERATED_OPTION_NAME]
        val buildDirectory = File(kaptKotlinGeneratedDir).ancestors.firstOrNull { it.name == "build" }
        val stubDirectory = buildDirectory?.let { File("${buildDirectory.path}/tmp/kapt3/stubs/main") }

        if (stubDirectory == null || !stubDirectory.isDirectory)
            error("Could not locate kapt stub directory")

        return stubDirectory
    }

    // TODO: convert into generator for Kotlin 1.3
    private val File.ancestors: Iterable<File>
        get() {
            val ancestors = mutableListOf<File>()
            var currentAncestor: File? = this

            while (currentAncestor != null) {
                ancestors.add(currentAncestor)
                currentAncestor = currentAncestor.parentFile
            }

            return ancestors
        }
}
Run Code Online (Sandbox Code Playgroud)

注意事项

这个解决方案似乎对我有用,但我不能保证它在一般情况下有效。特别是,我通过Kapt Gradle 插件(当前版本为 1.3.0-rc-198)在项目中配置了 Kapt ,该插件确定了所有生成的文件(包括元数据文件)的存储目录。然后,我假设元数据文件存储在/tmp/kapt3/stubs/main项目构建输出文件夹下。

我在 JetBrain 的问题跟踪器中创建了一个功能请求,以使此过程更轻松、更可靠,因此不需要进行此类黑客攻击。

例子

就我而言,我已经能够使用它来转换源代码,如下所示:

最小和最大.kt

package com.mycompany.testmaster.playground.nodes

import com.mycompany.testmaster.nodegen.annotations.ElementaryNode

@ElementaryNode
private fun <T: Comparable<T>> minAndMax(values: Iterable<T>) =
    Output(values.min(), values.max())
private data class Output<T : Comparable<T>>(val min: T?, val max: T?)
Run Code Online (Sandbox Code Playgroud)

并生成这样的源代码,其中包含原始源代码的修改版本:

最小和最大.gen.kt

// This code was generated by the <Company> Test Master node generation tool at 2018-10-29T08:31:35.847.
//
// Do not modify this file. Any changes may be overwritten at a later time.
package com.mycompany.testmaster.playground.nodes.gen

import com.mycompany.testmaster.domain.ElementaryNode
import com.mycompany.testmaster.domain.InputPort
import com.mycompany.testmaster.domain.OutputPort
import com.mycompany.testmaster.domain.Port
import kotlin.collections.Set
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope

class MinAndMax<T : Comparable<in T>> : ElementaryNode() {
    private val _values: Port<Iterable<out T>> = Port<Iterable<out T>>()

    val values: InputPort<Iterable<out T>> = _values

    private val _min: Port<T?> = Port<T?>()

    val min: OutputPort<T?> = _min

    private val _max: Port<T?> = Port<T?>()

    val max: OutputPort<T?> = _max

    override val ports: Set<Port<*>> = setOf(_values, _min, _max)

    override suspend fun executeOnce() {
        coroutineScope {
            val values = async { _values.receive() }
            val output = _nodeBody(values.await())
            _min.forward(output.min)
            _max.forward(output.max)
        }
    }
}



private  fun <T: Comparable<T>> _nodeBody(values: Iterable<T>) =
    Output(values.min(), values.max())
private data class Output<T : Comparable<T>>(val min: T?, val max: T?)
Run Code Online (Sandbox Code Playgroud)