blob: aa2db0ecdc8cb82d2bcd473abc8027f41c2c7015 [file] [log] [blame]
Colin Cross21fc9bb2019-01-18 15:05:09 -08001// 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
15package java
16
17import (
Colin Crossafbb1732019-01-17 15:42:52 -080018 "bytes"
19 "encoding/base64"
20 "encoding/binary"
Colin Cross6c6e6cd2019-05-08 14:30:12 -070021 "path/filepath"
Colin Cross21fc9bb2019-01-18 15:05:09 -080022 "strings"
23
Colin Crossafbb1732019-01-17 15:42:52 -080024 "android/soong/android"
25
Colin Cross21fc9bb2019-01-18 15:05:09 -080026 "github.com/google/blueprint"
27)
28
Ramy Medhat8ea054a2020-01-27 14:19:44 -050029var kotlinc = pctx.AndroidRemoteStaticRule("kotlinc", android.RemoteRuleSupports{Goma: true},
Colin Cross21fc9bb2019-01-18 15:05:09 -080030 blueprint.RuleParams{
Colin Cross220a9a12022-03-28 17:08:01 -070031 Command: `rm -rf "$classesDir" "$headerClassesDir" "$srcJarDir" "$kotlinBuildFile" "$emptyDir" && ` +
32 `mkdir -p "$classesDir" "$headerClassesDir" "$srcJarDir" "$emptyDir" && ` +
Zi Wang6a66e3d2023-06-13 10:40:52 -070033 `${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" -f "*.kt" $srcJars && ` +
Colin Cross9b1aa0c2020-06-25 17:12:28 -070034 `${config.GenKotlinBuildFileCmd} --classpath "$classpath" --name "$name"` +
35 ` --out_dir "$classesDir" --srcs "$out.rsp" --srcs "$srcJarDir/list"` +
Colin Crossa4c8cc62020-06-25 17:13:36 -070036 ` $commonSrcFilesArg --out "$kotlinBuildFile" && ` +
Colin Crossc2d50482022-03-17 12:01:27 -070037 `${config.KotlincCmd} ${config.KotlincGlobalFlags} ` +
Colin Cross220a9a12022-03-28 17:08:01 -070038 ` ${config.KotlincSuppressJDK9Warnings} ${config.JavacHeapFlags} ` +
39 ` $kotlincFlags -jvm-target $kotlinJvmTarget -Xbuild-file=$kotlinBuildFile ` +
40 ` -kotlin-home $emptyDir ` +
41 ` -Xplugin=${config.KotlinAbiGenPluginJar} ` +
42 ` -P plugin:org.jetbrains.kotlin.jvm.abi:outputDir=$headerClassesDir && ` +
43 `${config.SoongZipCmd} -jar -o $out -C $classesDir -D $classesDir -write_if_changed && ` +
44 `${config.SoongZipCmd} -jar -o $headerJar -C $headerClassesDir -D $headerClassesDir -write_if_changed && ` +
Colin Cross49889c02023-07-26 16:16:47 -070045 `rm -rf "$srcJarDir" "$classesDir" "$headerClassesDir"`,
Colin Cross21fc9bb2019-01-18 15:05:09 -080046 CommandDeps: []string{
47 "${config.KotlincCmd}",
48 "${config.KotlinCompilerJar}",
Dan Willemsenaad19602019-04-07 09:44:35 -070049 "${config.KotlinPreloaderJar}",
50 "${config.KotlinReflectJar}",
51 "${config.KotlinScriptRuntimeJar}",
52 "${config.KotlinStdlibJar}",
53 "${config.KotlinTrove4jJar}",
Dan Willemsen1cfbdbe2019-06-13 04:59:17 +000054 "${config.KotlinAnnotationJar}",
Colin Cross220a9a12022-03-28 17:08:01 -070055 "${config.KotlinAbiGenPluginJar}",
Colin Cross21fc9bb2019-01-18 15:05:09 -080056 "${config.GenKotlinBuildFileCmd}",
57 "${config.SoongZipCmd}",
58 "${config.ZipSyncCmd}",
59 },
60 Rspfile: "$out.rsp",
61 RspfileContent: `$in`,
Colin Cross220a9a12022-03-28 17:08:01 -070062 Restat: true,
Colin Cross21fc9bb2019-01-18 15:05:09 -080063 },
Colin Crossa4c8cc62020-06-25 17:13:36 -070064 "kotlincFlags", "classpath", "srcJars", "commonSrcFilesArg", "srcJarDir", "classesDir",
Colin Cross220a9a12022-03-28 17:08:01 -070065 "headerClassesDir", "headerJar", "kotlinJvmTarget", "kotlinBuildFile", "emptyDir", "name")
Colin Crossa4c8cc62020-06-25 17:13:36 -070066
67func kotlinCommonSrcsList(ctx android.ModuleContext, commonSrcFiles android.Paths) android.OptionalPath {
68 if len(commonSrcFiles) > 0 {
69 // The list of common_srcs may be too long to put on the command line, but
70 // we can't use the rsp file because it is already being used for srcs.
71 // Insert a second rule to write out the list of resources to a file.
72 commonSrcsList := android.PathForModuleOut(ctx, "kotlinc_common_srcs.list")
Colin Crossf1a035e2020-11-16 17:32:30 -080073 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross70c47412021-03-12 17:48:14 -080074 rule.Command().Text("cp").
75 FlagWithRspFileInputList("", commonSrcsList.ReplaceExtension(ctx, "rsp"), commonSrcFiles).
76 Output(commonSrcsList)
Colin Crossf1a035e2020-11-16 17:32:30 -080077 rule.Build("kotlin_common_srcs_list", "kotlin common_srcs list")
Colin Crossa4c8cc62020-06-25 17:13:36 -070078 return android.OptionalPathForPath(commonSrcsList)
79 }
80 return android.OptionalPath{}
81}
Colin Cross21fc9bb2019-01-18 15:05:09 -080082
Colin Crossafbb1732019-01-17 15:42:52 -080083// kotlinCompile takes .java and .kt sources and srcJars, and compiles the .kt sources into a classes jar in outputFile.
Colin Cross220a9a12022-03-28 17:08:01 -070084func kotlinCompile(ctx android.ModuleContext, outputFile, headerOutputFile android.WritablePath,
Colin Crossa4c8cc62020-06-25 17:13:36 -070085 srcFiles, commonSrcFiles, srcJars android.Paths,
Colin Cross21fc9bb2019-01-18 15:05:09 -080086 flags javaBuilderFlags) {
87
Colin Cross21fc9bb2019-01-18 15:05:09 -080088 var deps android.Paths
89 deps = append(deps, flags.kotlincClasspath...)
Colin Crossa1ff7c62021-09-17 14:11:52 -070090 deps = append(deps, flags.kotlincDeps...)
Colin Cross21fc9bb2019-01-18 15:05:09 -080091 deps = append(deps, srcJars...)
Colin Crossa4c8cc62020-06-25 17:13:36 -070092 deps = append(deps, commonSrcFiles...)
Colin Cross21fc9bb2019-01-18 15:05:09 -080093
Colin Cross6c6e6cd2019-05-08 14:30:12 -070094 kotlinName := filepath.Join(ctx.ModuleDir(), ctx.ModuleSubDir(), ctx.ModuleName())
95 kotlinName = strings.ReplaceAll(kotlinName, "/", "__")
96
Colin Crossa4c8cc62020-06-25 17:13:36 -070097 commonSrcsList := kotlinCommonSrcsList(ctx, commonSrcFiles)
98 commonSrcFilesArg := ""
99 if commonSrcsList.Valid() {
100 deps = append(deps, commonSrcsList.Path())
101 commonSrcFilesArg = "--common_srcs " + commonSrcsList.String()
102 }
103
Colin Cross21fc9bb2019-01-18 15:05:09 -0800104 ctx.Build(pctx, android.BuildParams{
Colin Cross220a9a12022-03-28 17:08:01 -0700105 Rule: kotlinc,
106 Description: "kotlinc",
107 Output: outputFile,
108 ImplicitOutput: headerOutputFile,
109 Inputs: srcFiles,
110 Implicits: deps,
Colin Cross21fc9bb2019-01-18 15:05:09 -0800111 Args: map[string]string{
Colin Crossa4c8cc62020-06-25 17:13:36 -0700112 "classpath": flags.kotlincClasspath.FormJavaClassPath(""),
113 "kotlincFlags": flags.kotlincFlags,
114 "commonSrcFilesArg": commonSrcFilesArg,
115 "srcJars": strings.Join(srcJars.Strings(), " "),
116 "classesDir": android.PathForModuleOut(ctx, "kotlinc", "classes").String(),
Colin Cross220a9a12022-03-28 17:08:01 -0700117 "headerClassesDir": android.PathForModuleOut(ctx, "kotlinc", "header_classes").String(),
118 "headerJar": headerOutputFile.String(),
Colin Crossa4c8cc62020-06-25 17:13:36 -0700119 "srcJarDir": android.PathForModuleOut(ctx, "kotlinc", "srcJars").String(),
120 "kotlinBuildFile": android.PathForModuleOut(ctx, "kotlinc-build.xml").String(),
121 "emptyDir": android.PathForModuleOut(ctx, "kotlinc", "empty").String(),
Cole Faustd96eebf2022-06-28 14:41:27 -0700122 "kotlinJvmTarget": flags.javaVersion.StringForKotlinc(),
123 "name": kotlinName,
Colin Cross21fc9bb2019-01-18 15:05:09 -0800124 },
125 })
126}
Colin Crossafbb1732019-01-17 15:42:52 -0800127
Colin Crossf61766e2022-03-16 18:06:48 -0700128var kaptStubs = pctx.AndroidRemoteStaticRule("kaptStubs", android.RemoteRuleSupports{Goma: true},
Colin Crossafbb1732019-01-17 15:42:52 -0800129 blueprint.RuleParams{
Colin Cross9ca38d22020-06-18 15:46:32 -0700130 Command: `rm -rf "$srcJarDir" "$kotlinBuildFile" "$kaptDir" && ` +
131 `mkdir -p "$srcJarDir" "$kaptDir/sources" "$kaptDir/classes" && ` +
Colin Crossafbb1732019-01-17 15:42:52 -0800132 `${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
Colin Cross9b1aa0c2020-06-25 17:12:28 -0700133 `${config.GenKotlinBuildFileCmd} --classpath "$classpath" --name "$name"` +
134 ` --srcs "$out.rsp" --srcs "$srcJarDir/list"` +
Colin Crossa4c8cc62020-06-25 17:13:36 -0700135 ` $commonSrcFilesArg --out "$kotlinBuildFile" && ` +
Colin Crossc2d50482022-03-17 12:01:27 -0700136 `${config.KotlincCmd} ${config.KotlincGlobalFlags} ` +
137 `${config.KaptSuppressJDK9Warnings} ${config.KotlincSuppressJDK9Warnings} ` +
Colin Crossd47f4ac2021-03-26 10:52:02 -0700138 `${config.JavacHeapFlags} $kotlincFlags -Xplugin=${config.KotlinKaptJar} ` +
Colin Crossafbb1732019-01-17 15:42:52 -0800139 `-P plugin:org.jetbrains.kotlin.kapt3:sources=$kaptDir/sources ` +
140 `-P plugin:org.jetbrains.kotlin.kapt3:classes=$kaptDir/classes ` +
141 `-P plugin:org.jetbrains.kotlin.kapt3:stubs=$kaptDir/stubs ` +
142 `-P plugin:org.jetbrains.kotlin.kapt3:correctErrorTypes=true ` +
Colin Crossf61766e2022-03-16 18:06:48 -0700143 `-P plugin:org.jetbrains.kotlin.kapt3:aptMode=stubs ` +
Colin Crossafbb1732019-01-17 15:42:52 -0800144 `-P plugin:org.jetbrains.kotlin.kapt3:javacArguments=$encodedJavacFlags ` +
145 `$kaptProcessorPath ` +
Colin Crossbe9cdb82019-01-21 21:37:16 -0800146 `$kaptProcessor ` +
Colin Crossafbb1732019-01-17 15:42:52 -0800147 `-Xbuild-file=$kotlinBuildFile && ` +
Colin Crossed273222023-09-15 15:16:12 -0700148 `${config.SoongZipCmd} -jar -write_if_changed -o $out -C $kaptDir/stubs -D $kaptDir/stubs && ` +
Colin Cross44c29a82019-01-24 16:36:57 -0800149 `rm -rf "$srcJarDir"`,
Colin Crossafbb1732019-01-17 15:42:52 -0800150 CommandDeps: []string{
151 "${config.KotlincCmd}",
152 "${config.KotlinCompilerJar}",
153 "${config.KotlinKaptJar}",
154 "${config.GenKotlinBuildFileCmd}",
155 "${config.SoongZipCmd}",
156 "${config.ZipSyncCmd}",
157 },
158 Rspfile: "$out.rsp",
159 RspfileContent: `$in`,
Colin Crossed273222023-09-15 15:16:12 -0700160 Restat: true,
Colin Crossafbb1732019-01-17 15:42:52 -0800161 },
Colin Crossbe9cdb82019-01-21 21:37:16 -0800162 "kotlincFlags", "encodedJavacFlags", "kaptProcessorPath", "kaptProcessor",
Colin Crossa4c8cc62020-06-25 17:13:36 -0700163 "classpath", "srcJars", "commonSrcFilesArg", "srcJarDir", "kaptDir", "kotlinJvmTarget",
164 "kotlinBuildFile", "name", "classesJarOut")
Colin Crossafbb1732019-01-17 15:42:52 -0800165
Isaac Chioua23d9942022-04-06 06:14:38 +0000166// kotlinKapt performs Kotlin-compatible annotation processing. It takes .kt and .java sources and srcjars, and runs
Colin Crossafbb1732019-01-17 15:42:52 -0800167// annotation processors over all of them, producing a srcjar of generated code in outputFile. The srcjar should be
168// added as an additional input to kotlinc and javac rules, and the javac rule should have annotation processing
169// disabled.
Isaac Chioua23d9942022-04-06 06:14:38 +0000170func kotlinKapt(ctx android.ModuleContext, srcJarOutputFile, resJarOutputFile android.WritablePath,
Colin Crossa4c8cc62020-06-25 17:13:36 -0700171 srcFiles, commonSrcFiles, srcJars android.Paths,
Colin Crossafbb1732019-01-17 15:42:52 -0800172 flags javaBuilderFlags) {
173
Colin Crossa4c8cc62020-06-25 17:13:36 -0700174 srcFiles = append(android.Paths(nil), srcFiles...)
175
Colin Crossafbb1732019-01-17 15:42:52 -0800176 var deps android.Paths
177 deps = append(deps, flags.kotlincClasspath...)
Colin Cross08b0a1c2022-05-02 13:59:33 -0700178 deps = append(deps, flags.kotlincDeps...)
Colin Crossafbb1732019-01-17 15:42:52 -0800179 deps = append(deps, srcJars...)
180 deps = append(deps, flags.processorPath...)
Colin Crossa4c8cc62020-06-25 17:13:36 -0700181 deps = append(deps, commonSrcFiles...)
182
183 commonSrcsList := kotlinCommonSrcsList(ctx, commonSrcFiles)
184 commonSrcFilesArg := ""
185 if commonSrcsList.Valid() {
186 deps = append(deps, commonSrcsList.Path())
187 commonSrcFilesArg = "--common_srcs " + commonSrcsList.String()
188 }
Colin Crossafbb1732019-01-17 15:42:52 -0800189
Colin Crossc2557d12019-10-31 15:22:57 -0700190 kaptProcessorPath := flags.processorPath.FormRepeatedClassPath("-P plugin:org.jetbrains.kotlin.kapt3:apclasspath=")
Colin Crossafbb1732019-01-17 15:42:52 -0800191
Colin Crossbe9cdb82019-01-21 21:37:16 -0800192 kaptProcessor := ""
Colin Cross5a116862020-04-22 11:44:34 -0700193 for i, p := range flags.processors {
194 if i > 0 {
195 kaptProcessor += " "
196 }
197 kaptProcessor += "-P plugin:org.jetbrains.kotlin.kapt3:processors=" + p
Colin Crossbe9cdb82019-01-21 21:37:16 -0800198 }
199
Colin Crossafbb1732019-01-17 15:42:52 -0800200 encodedJavacFlags := kaptEncodeFlags([][2]string{
Colin Cross1e743852019-10-28 11:37:20 -0700201 {"-source", flags.javaVersion.String()},
202 {"-target", flags.javaVersion.String()},
Colin Crossafbb1732019-01-17 15:42:52 -0800203 })
204
Colin Cross6c6e6cd2019-05-08 14:30:12 -0700205 kotlinName := filepath.Join(ctx.ModuleDir(), ctx.ModuleSubDir(), ctx.ModuleName())
206 kotlinName = strings.ReplaceAll(kotlinName, "/", "__")
207
Colin Crossf61766e2022-03-16 18:06:48 -0700208 // First run kapt to generate .java stubs from .kt files
209 kaptStubsJar := android.PathForModuleOut(ctx, "kapt", "stubs.jar")
Colin Crossafbb1732019-01-17 15:42:52 -0800210 ctx.Build(pctx, android.BuildParams{
Colin Crossf61766e2022-03-16 18:06:48 -0700211 Rule: kaptStubs,
212 Description: "kapt stubs",
213 Output: kaptStubsJar,
214 Inputs: srcFiles,
215 Implicits: deps,
Colin Crossafbb1732019-01-17 15:42:52 -0800216 Args: map[string]string{
Colin Cross9b1aa0c2020-06-25 17:12:28 -0700217 "classpath": flags.kotlincClasspath.FormJavaClassPath(""),
Colin Crossafbb1732019-01-17 15:42:52 -0800218 "kotlincFlags": flags.kotlincFlags,
Colin Crossa4c8cc62020-06-25 17:13:36 -0700219 "commonSrcFilesArg": commonSrcFilesArg,
Colin Crossafbb1732019-01-17 15:42:52 -0800220 "srcJars": strings.Join(srcJars.Strings(), " "),
221 "srcJarDir": android.PathForModuleOut(ctx, "kapt", "srcJars").String(),
222 "kotlinBuildFile": android.PathForModuleOut(ctx, "kapt", "build.xml").String(),
223 "kaptProcessorPath": strings.Join(kaptProcessorPath, " "),
Colin Crossbe9cdb82019-01-21 21:37:16 -0800224 "kaptProcessor": kaptProcessor,
Colin Crossafbb1732019-01-17 15:42:52 -0800225 "kaptDir": android.PathForModuleOut(ctx, "kapt/gen").String(),
226 "encodedJavacFlags": encodedJavacFlags,
Colin Cross6c6e6cd2019-05-08 14:30:12 -0700227 "name": kotlinName,
Colin Cross9ca38d22020-06-18 15:46:32 -0700228 "classesJarOut": resJarOutputFile.String(),
Colin Crossafbb1732019-01-17 15:42:52 -0800229 },
230 })
Colin Crossf61766e2022-03-16 18:06:48 -0700231
232 // Then run turbine to perform annotation processing on the stubs and any .java srcFiles.
233 javaSrcFiles := srcFiles.FilterByExt(".java")
234 turbineSrcJars := append(android.Paths{kaptStubsJar}, srcJars...)
Isaac Chioua23d9942022-04-06 06:14:38 +0000235 TurbineApt(ctx, srcJarOutputFile, resJarOutputFile, javaSrcFiles, turbineSrcJars, flags)
Colin Crossafbb1732019-01-17 15:42:52 -0800236}
237
238// kapt converts a list of key, value pairs into a base64 encoded Java serialization, which is what kapt expects.
239func kaptEncodeFlags(options [][2]string) string {
240 buf := &bytes.Buffer{}
241
242 binary.Write(buf, binary.BigEndian, uint32(len(options)))
243 for _, option := range options {
244 binary.Write(buf, binary.BigEndian, uint16(len(option[0])))
245 buf.WriteString(option[0])
246 binary.Write(buf, binary.BigEndian, uint16(len(option[1])))
247 buf.WriteString(option[1])
248 }
249
250 header := &bytes.Buffer{}
251 header.Write([]byte{0xac, 0xed, 0x00, 0x05}) // java serialization header
252
253 if buf.Len() < 256 {
254 header.WriteByte(0x77) // blockdata
255 header.WriteByte(byte(buf.Len()))
256 } else {
257 header.WriteByte(0x7a) // blockdatalong
258 binary.Write(header, binary.BigEndian, uint32(buf.Len()))
259 }
260
261 return base64.StdEncoding.EncodeToString(append(header.Bytes(), buf.Bytes()...))
262}