Kotlin Compilation Process Overview

2 阅读1分钟

本文基于 Kotlin 1.9.22 版本,对 JVM 编译流程进行分析,程序入口点为 K2JVMCompiler,源码位于 kotlin-compiler-embeddable,建议阅读本文前对 FE10(K1),FIR(K2) 有基本的了解

Kotlin 整体编译流程我个人将其分为以下几步:

  1. Create configuration,用于将 CLI 或其他渠道传给 kotlinc 的参数转化成 configuration
  2. Create environment,用于创建 KotlinLexer、Intellij Core Environment、VFS、Project、PsiFacade 以及将 SourceSet、Dependencies 等信息传递给编译器
  3. Compiler Frontend,用于分析和生成 KtFile + BindingContext 或 FIR(K2),同时也可以将这些事件分发到各个扩展点
  4. Compiler Backend,用于生成 Backend IR 和 generate code,比如在 JVM 平台会生成 bytecode

具体见下图,看不清的话可以去飞书文档画板:Kotlin Compilation Process Overview > 画板

image.png

一些可能用到的相关参考资料:

  1. Crash Course on the Kotlin Compiler | K1 + K2 Frontends, Backends | by mvndy | Google Developer Experts | Medium
  2. github.com/JetBrains/k…

飞书文档原文:Kotlin Compilation Process Overview