kotlin - Kotlin是如何专门编译的?

标签 kotlin compilation kotlin-native kotlin-js

我试图了解Kotlin源代码在编译时所经历的旅程。 The documentation状态

When targeting the JVM, Kotlin produces Java compatible bytecode. When targeting JavaScript, Kotlin transpiles to ES5.1 and generates code which is compatible with module systems including AMD and CommonJS. When targeting native, Kotlin will produce platform-specific code (via LLVM).



我的理解是,当Kotlin以JVM为目标时,代码被编译/翻译为字节码,然后JVM将其解释为机器代码。这将是JIT(及时)编译的示例吗?

以javascript为目标时,会使用“transpiles”一词。代码到底被编译成什么内容,并且在任何步骤都被进一步解释或编译?

以 native 为目标时,代码是否直接编译为机器代码? LLVM需要采取什么步骤?

最后,这是否意味着Kotlin既是编译语言又是解释语言?

最佳答案

<...> the code is compiled/translated down to bytecode and then the JVM interprets(?) it down to machine code. Would this be an example of JIT(Just in time) compilation?



是的,在以JVM为目标时,Kotlin会编译为JVM *.class文件,这是一种字节码格式,以后可以由JVM解释,也可以由JVM在程序运行(JIT)期间编译为机器代码,甚至进行编译提前(AOT)到机器代码。在这里,Kotlin编译器不需要知道字节码的使用方式。

When targeting javascript the word "transpiles" is used. What exactly is the code compiled down to and is it interpreted or compiled further down at any step?



Kotlin/JS的目标格式是JavaScript源代码。您可以尝试构建任何Kotlin/JS示例和examine the *.js output files,其中包含将Kotlin代码转换为JS的源代码。我相信这里使用了transpile(翻译+编译)一词来强调目标格式是源代码,而不是二进制,而编译器仍然执行许多转换和优化。

同样,JavaScript源代码是经过解释的或JIT编译的,这取决于用于运行该程序的JavaScript引擎。

When targeting native, is code compiled directly to machine code? What steps does LLVM take it through?



Kotlin/Native有两种可能的目标形式:
  • 一个*.klib库,可以在另一个Kotlin/Native项目中重用。这是a ZIP archive containing LLVM bitcode along with some Kotlin-specific metadata
  • 一种特定于平台的二进制文件,采用多种格式之一,包括静态和动态库以及可执行文件。实际上,这是特定目标平台的机器代码,如果它是一个库,则可以用于链接;如果它是可执行文件,则可以直接运行。在这种情况下,Kotlin编译器将调用the LLVM linker lld 来链接LLVM位代码中的二进制文件。
  • 关于kotlin - Kotlin是如何专门编译的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53472710/

    相关文章:

    objective-c - 使用 vararg 格式化 Kotlin Native iOS 字符串

    android - 我的 RecyclerView 没有得到适当的通知

    android - anko logging方法无法解决

    enums - Kotlin:如何使用扩展函数扩展枚举类

    c++ - 头文件是如何连接到对应的.cpp文件的?

    ios - Kotlin/Native - 非法尝试访问非共享 <object>

    android - 为什么 Android+Kotlin 中 newStartIntent 的伴随对象?

    c++ - 与 const 相关的错误

    c++ - 为什么 RWDBManager::database 需要共享库名?

    ios - kotlin native 无法导入 khttp