kotlin.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. // Copyright 2019 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package java
  15. import (
  16. "bytes"
  17. "encoding/base64"
  18. "encoding/binary"
  19. "path/filepath"
  20. "strings"
  21. "android/soong/android"
  22. "github.com/google/blueprint"
  23. )
  24. var kotlinc = pctx.AndroidRemoteStaticRule("kotlinc", android.RemoteRuleSupports{Goma: true},
  25. blueprint.RuleParams{
  26. Command: `rm -rf "$classesDir" "$headerClassesDir" "$srcJarDir" "$kotlinBuildFile" "$emptyDir" && ` +
  27. `mkdir -p "$classesDir" "$headerClassesDir" "$srcJarDir" "$emptyDir" && ` +
  28. `${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" -f "*.kt" $srcJars && ` +
  29. `${config.GenKotlinBuildFileCmd} --classpath "$classpath" --name "$name"` +
  30. ` --out_dir "$classesDir" --srcs "$out.rsp" --srcs "$srcJarDir/list"` +
  31. ` $commonSrcFilesArg --out "$kotlinBuildFile" && ` +
  32. `${config.KotlincCmd} ${config.KotlincGlobalFlags} ` +
  33. ` ${config.KotlincSuppressJDK9Warnings} ${config.JavacHeapFlags} ` +
  34. ` $kotlincFlags -jvm-target $kotlinJvmTarget -Xbuild-file=$kotlinBuildFile ` +
  35. ` -kotlin-home $emptyDir ` +
  36. ` -Xplugin=${config.KotlinAbiGenPluginJar} ` +
  37. ` -P plugin:org.jetbrains.kotlin.jvm.abi:outputDir=$headerClassesDir && ` +
  38. `${config.SoongZipCmd} -jar -o $out -C $classesDir -D $classesDir -write_if_changed && ` +
  39. `${config.SoongZipCmd} -jar -o $headerJar -C $headerClassesDir -D $headerClassesDir -write_if_changed && ` +
  40. `rm -rf "$srcJarDir"`,
  41. CommandDeps: []string{
  42. "${config.KotlincCmd}",
  43. "${config.KotlinCompilerJar}",
  44. "${config.KotlinPreloaderJar}",
  45. "${config.KotlinReflectJar}",
  46. "${config.KotlinScriptRuntimeJar}",
  47. "${config.KotlinStdlibJar}",
  48. "${config.KotlinTrove4jJar}",
  49. "${config.KotlinAnnotationJar}",
  50. "${config.KotlinAbiGenPluginJar}",
  51. "${config.GenKotlinBuildFileCmd}",
  52. "${config.SoongZipCmd}",
  53. "${config.ZipSyncCmd}",
  54. },
  55. Rspfile: "$out.rsp",
  56. RspfileContent: `$in`,
  57. Restat: true,
  58. },
  59. "kotlincFlags", "classpath", "srcJars", "commonSrcFilesArg", "srcJarDir", "classesDir",
  60. "headerClassesDir", "headerJar", "kotlinJvmTarget", "kotlinBuildFile", "emptyDir", "name")
  61. func kotlinCommonSrcsList(ctx android.ModuleContext, commonSrcFiles android.Paths) android.OptionalPath {
  62. if len(commonSrcFiles) > 0 {
  63. // The list of common_srcs may be too long to put on the command line, but
  64. // we can't use the rsp file because it is already being used for srcs.
  65. // Insert a second rule to write out the list of resources to a file.
  66. commonSrcsList := android.PathForModuleOut(ctx, "kotlinc_common_srcs.list")
  67. rule := android.NewRuleBuilder(pctx, ctx)
  68. rule.Command().Text("cp").
  69. FlagWithRspFileInputList("", commonSrcsList.ReplaceExtension(ctx, "rsp"), commonSrcFiles).
  70. Output(commonSrcsList)
  71. rule.Build("kotlin_common_srcs_list", "kotlin common_srcs list")
  72. return android.OptionalPathForPath(commonSrcsList)
  73. }
  74. return android.OptionalPath{}
  75. }
  76. // kotlinCompile takes .java and .kt sources and srcJars, and compiles the .kt sources into a classes jar in outputFile.
  77. func kotlinCompile(ctx android.ModuleContext, outputFile, headerOutputFile android.WritablePath,
  78. srcFiles, commonSrcFiles, srcJars android.Paths,
  79. flags javaBuilderFlags) {
  80. var deps android.Paths
  81. deps = append(deps, flags.kotlincClasspath...)
  82. deps = append(deps, flags.kotlincDeps...)
  83. deps = append(deps, srcJars...)
  84. deps = append(deps, commonSrcFiles...)
  85. kotlinName := filepath.Join(ctx.ModuleDir(), ctx.ModuleSubDir(), ctx.ModuleName())
  86. kotlinName = strings.ReplaceAll(kotlinName, "/", "__")
  87. commonSrcsList := kotlinCommonSrcsList(ctx, commonSrcFiles)
  88. commonSrcFilesArg := ""
  89. if commonSrcsList.Valid() {
  90. deps = append(deps, commonSrcsList.Path())
  91. commonSrcFilesArg = "--common_srcs " + commonSrcsList.String()
  92. }
  93. ctx.Build(pctx, android.BuildParams{
  94. Rule: kotlinc,
  95. Description: "kotlinc",
  96. Output: outputFile,
  97. ImplicitOutput: headerOutputFile,
  98. Inputs: srcFiles,
  99. Implicits: deps,
  100. Args: map[string]string{
  101. "classpath": flags.kotlincClasspath.FormJavaClassPath(""),
  102. "kotlincFlags": flags.kotlincFlags,
  103. "commonSrcFilesArg": commonSrcFilesArg,
  104. "srcJars": strings.Join(srcJars.Strings(), " "),
  105. "classesDir": android.PathForModuleOut(ctx, "kotlinc", "classes").String(),
  106. "headerClassesDir": android.PathForModuleOut(ctx, "kotlinc", "header_classes").String(),
  107. "headerJar": headerOutputFile.String(),
  108. "srcJarDir": android.PathForModuleOut(ctx, "kotlinc", "srcJars").String(),
  109. "kotlinBuildFile": android.PathForModuleOut(ctx, "kotlinc-build.xml").String(),
  110. "emptyDir": android.PathForModuleOut(ctx, "kotlinc", "empty").String(),
  111. "kotlinJvmTarget": flags.javaVersion.StringForKotlinc(),
  112. "name": kotlinName,
  113. },
  114. })
  115. }
  116. var kaptStubs = pctx.AndroidRemoteStaticRule("kaptStubs", android.RemoteRuleSupports{Goma: true},
  117. blueprint.RuleParams{
  118. Command: `rm -rf "$srcJarDir" "$kotlinBuildFile" "$kaptDir" && ` +
  119. `mkdir -p "$srcJarDir" "$kaptDir/sources" "$kaptDir/classes" && ` +
  120. `${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
  121. `${config.GenKotlinBuildFileCmd} --classpath "$classpath" --name "$name"` +
  122. ` --srcs "$out.rsp" --srcs "$srcJarDir/list"` +
  123. ` $commonSrcFilesArg --out "$kotlinBuildFile" && ` +
  124. `${config.KotlincCmd} ${config.KotlincGlobalFlags} ` +
  125. `${config.KaptSuppressJDK9Warnings} ${config.KotlincSuppressJDK9Warnings} ` +
  126. `${config.JavacHeapFlags} $kotlincFlags -Xplugin=${config.KotlinKaptJar} ` +
  127. `-P plugin:org.jetbrains.kotlin.kapt3:sources=$kaptDir/sources ` +
  128. `-P plugin:org.jetbrains.kotlin.kapt3:classes=$kaptDir/classes ` +
  129. `-P plugin:org.jetbrains.kotlin.kapt3:stubs=$kaptDir/stubs ` +
  130. `-P plugin:org.jetbrains.kotlin.kapt3:correctErrorTypes=true ` +
  131. `-P plugin:org.jetbrains.kotlin.kapt3:aptMode=stubs ` +
  132. `-P plugin:org.jetbrains.kotlin.kapt3:javacArguments=$encodedJavacFlags ` +
  133. `$kaptProcessorPath ` +
  134. `$kaptProcessor ` +
  135. `-Xbuild-file=$kotlinBuildFile && ` +
  136. `${config.SoongZipCmd} -jar -o $out -C $kaptDir/stubs -D $kaptDir/stubs && ` +
  137. `rm -rf "$srcJarDir"`,
  138. CommandDeps: []string{
  139. "${config.KotlincCmd}",
  140. "${config.KotlinCompilerJar}",
  141. "${config.KotlinKaptJar}",
  142. "${config.GenKotlinBuildFileCmd}",
  143. "${config.SoongZipCmd}",
  144. "${config.ZipSyncCmd}",
  145. },
  146. Rspfile: "$out.rsp",
  147. RspfileContent: `$in`,
  148. },
  149. "kotlincFlags", "encodedJavacFlags", "kaptProcessorPath", "kaptProcessor",
  150. "classpath", "srcJars", "commonSrcFilesArg", "srcJarDir", "kaptDir", "kotlinJvmTarget",
  151. "kotlinBuildFile", "name", "classesJarOut")
  152. // kotlinKapt performs Kotlin-compatible annotation processing. It takes .kt and .java sources and srcjars, and runs
  153. // annotation processors over all of them, producing a srcjar of generated code in outputFile. The srcjar should be
  154. // added as an additional input to kotlinc and javac rules, and the javac rule should have annotation processing
  155. // disabled.
  156. func kotlinKapt(ctx android.ModuleContext, srcJarOutputFile, resJarOutputFile android.WritablePath,
  157. srcFiles, commonSrcFiles, srcJars android.Paths,
  158. flags javaBuilderFlags) {
  159. srcFiles = append(android.Paths(nil), srcFiles...)
  160. var deps android.Paths
  161. deps = append(deps, flags.kotlincClasspath...)
  162. deps = append(deps, flags.kotlincDeps...)
  163. deps = append(deps, srcJars...)
  164. deps = append(deps, flags.processorPath...)
  165. deps = append(deps, commonSrcFiles...)
  166. commonSrcsList := kotlinCommonSrcsList(ctx, commonSrcFiles)
  167. commonSrcFilesArg := ""
  168. if commonSrcsList.Valid() {
  169. deps = append(deps, commonSrcsList.Path())
  170. commonSrcFilesArg = "--common_srcs " + commonSrcsList.String()
  171. }
  172. kaptProcessorPath := flags.processorPath.FormRepeatedClassPath("-P plugin:org.jetbrains.kotlin.kapt3:apclasspath=")
  173. kaptProcessor := ""
  174. for i, p := range flags.processors {
  175. if i > 0 {
  176. kaptProcessor += " "
  177. }
  178. kaptProcessor += "-P plugin:org.jetbrains.kotlin.kapt3:processors=" + p
  179. }
  180. encodedJavacFlags := kaptEncodeFlags([][2]string{
  181. {"-source", flags.javaVersion.String()},
  182. {"-target", flags.javaVersion.String()},
  183. })
  184. kotlinName := filepath.Join(ctx.ModuleDir(), ctx.ModuleSubDir(), ctx.ModuleName())
  185. kotlinName = strings.ReplaceAll(kotlinName, "/", "__")
  186. // First run kapt to generate .java stubs from .kt files
  187. kaptStubsJar := android.PathForModuleOut(ctx, "kapt", "stubs.jar")
  188. ctx.Build(pctx, android.BuildParams{
  189. Rule: kaptStubs,
  190. Description: "kapt stubs",
  191. Output: kaptStubsJar,
  192. Inputs: srcFiles,
  193. Implicits: deps,
  194. Args: map[string]string{
  195. "classpath": flags.kotlincClasspath.FormJavaClassPath(""),
  196. "kotlincFlags": flags.kotlincFlags,
  197. "commonSrcFilesArg": commonSrcFilesArg,
  198. "srcJars": strings.Join(srcJars.Strings(), " "),
  199. "srcJarDir": android.PathForModuleOut(ctx, "kapt", "srcJars").String(),
  200. "kotlinBuildFile": android.PathForModuleOut(ctx, "kapt", "build.xml").String(),
  201. "kaptProcessorPath": strings.Join(kaptProcessorPath, " "),
  202. "kaptProcessor": kaptProcessor,
  203. "kaptDir": android.PathForModuleOut(ctx, "kapt/gen").String(),
  204. "encodedJavacFlags": encodedJavacFlags,
  205. "name": kotlinName,
  206. "classesJarOut": resJarOutputFile.String(),
  207. },
  208. })
  209. // Then run turbine to perform annotation processing on the stubs and any .java srcFiles.
  210. javaSrcFiles := srcFiles.FilterByExt(".java")
  211. turbineSrcJars := append(android.Paths{kaptStubsJar}, srcJars...)
  212. TurbineApt(ctx, srcJarOutputFile, resJarOutputFile, javaSrcFiles, turbineSrcJars, flags)
  213. }
  214. // kapt converts a list of key, value pairs into a base64 encoded Java serialization, which is what kapt expects.
  215. func kaptEncodeFlags(options [][2]string) string {
  216. buf := &bytes.Buffer{}
  217. binary.Write(buf, binary.BigEndian, uint32(len(options)))
  218. for _, option := range options {
  219. binary.Write(buf, binary.BigEndian, uint16(len(option[0])))
  220. buf.WriteString(option[0])
  221. binary.Write(buf, binary.BigEndian, uint16(len(option[1])))
  222. buf.WriteString(option[1])
  223. }
  224. header := &bytes.Buffer{}
  225. header.Write([]byte{0xac, 0xed, 0x00, 0x05}) // java serialization header
  226. if buf.Len() < 256 {
  227. header.WriteByte(0x77) // blockdata
  228. header.WriteByte(byte(buf.Len()))
  229. } else {
  230. header.WriteByte(0x7a) // blockdatalong
  231. binary.Write(header, binary.BigEndian, uint32(buf.Len()))
  232. }
  233. return base64.StdEncoding.EncodeToString(append(header.Bytes(), buf.Bytes()...))
  234. }