• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
15package java
16
17import (
18	"bytes"
19	"encoding/base64"
20	"encoding/binary"
21	"path/filepath"
22	"strings"
23
24	"android/soong/android"
25
26	"github.com/google/blueprint"
27)
28
29var kotlinc = pctx.AndroidRemoteStaticRule("kotlinc", android.RemoteRuleSupports{Goma: true},
30	blueprint.RuleParams{
31		Command: `rm -rf "$classesDir" "$srcJarDir" "$kotlinBuildFile" "$emptyDir" && ` +
32			`mkdir -p "$classesDir" "$srcJarDir" "$emptyDir" && ` +
33			`${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
34			`${config.GenKotlinBuildFileCmd} $classpath "$name" $classesDir $out.rsp $srcJarDir/list > $kotlinBuildFile &&` +
35			`${config.KotlincCmd} ${config.JavacHeapFlags} $kotlincFlags ` +
36			`-jvm-target $kotlinJvmTarget -Xbuild-file=$kotlinBuildFile -kotlin-home $emptyDir && ` +
37			`${config.SoongZipCmd} -jar -o $out -C $classesDir -D $classesDir && ` +
38			`rm -rf "$srcJarDir"`,
39		CommandDeps: []string{
40			"${config.KotlincCmd}",
41			"${config.KotlinCompilerJar}",
42			"${config.KotlinPreloaderJar}",
43			"${config.KotlinReflectJar}",
44			"${config.KotlinScriptRuntimeJar}",
45			"${config.KotlinStdlibJar}",
46			"${config.KotlinTrove4jJar}",
47			"${config.KotlinAnnotationJar}",
48			"${config.GenKotlinBuildFileCmd}",
49			"${config.SoongZipCmd}",
50			"${config.ZipSyncCmd}",
51		},
52		Rspfile:        "$out.rsp",
53		RspfileContent: `$in`,
54	},
55	"kotlincFlags", "classpath", "srcJars", "srcJarDir", "classesDir", "kotlinJvmTarget", "kotlinBuildFile",
56	"emptyDir", "name")
57
58// kotlinCompile takes .java and .kt sources and srcJars, and compiles the .kt sources into a classes jar in outputFile.
59func kotlinCompile(ctx android.ModuleContext, outputFile android.WritablePath,
60	srcFiles, srcJars android.Paths,
61	flags javaBuilderFlags) {
62
63	var deps android.Paths
64	deps = append(deps, flags.kotlincClasspath...)
65	deps = append(deps, srcJars...)
66
67	kotlinName := filepath.Join(ctx.ModuleDir(), ctx.ModuleSubDir(), ctx.ModuleName())
68	kotlinName = strings.ReplaceAll(kotlinName, "/", "__")
69
70	ctx.Build(pctx, android.BuildParams{
71		Rule:        kotlinc,
72		Description: "kotlinc",
73		Output:      outputFile,
74		Inputs:      srcFiles,
75		Implicits:   deps,
76		Args: map[string]string{
77			"classpath":       flags.kotlincClasspath.FormJavaClassPath("-classpath"),
78			"kotlincFlags":    flags.kotlincFlags,
79			"srcJars":         strings.Join(srcJars.Strings(), " "),
80			"classesDir":      android.PathForModuleOut(ctx, "kotlinc", "classes").String(),
81			"srcJarDir":       android.PathForModuleOut(ctx, "kotlinc", "srcJars").String(),
82			"kotlinBuildFile": android.PathForModuleOut(ctx, "kotlinc-build.xml").String(),
83			"emptyDir":        android.PathForModuleOut(ctx, "kotlinc", "empty").String(),
84			// http://b/69160377 kotlinc only supports -jvm-target 1.6 and 1.8
85			"kotlinJvmTarget": "1.8",
86			"name":            kotlinName,
87		},
88	})
89}
90
91var kapt = pctx.AndroidRemoteStaticRule("kapt", android.RemoteRuleSupports{Goma: true},
92	blueprint.RuleParams{
93		Command: `rm -rf "$srcJarDir" "$kotlinBuildFile" "$kaptDir" && ` +
94			`mkdir -p "$srcJarDir" "$kaptDir/sources" "$kaptDir/classes" && ` +
95			`${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
96			`${config.GenKotlinBuildFileCmd} $classpath "$name" "" $out.rsp $srcJarDir/list > $kotlinBuildFile &&` +
97			`${config.KotlincCmd} ${config.KotlincSuppressJDK9Warnings} ${config.JavacHeapFlags} $kotlincFlags ` +
98			`-Xplugin=${config.KotlinKaptJar} ` +
99			`-P plugin:org.jetbrains.kotlin.kapt3:sources=$kaptDir/sources ` +
100			`-P plugin:org.jetbrains.kotlin.kapt3:classes=$kaptDir/classes ` +
101			`-P plugin:org.jetbrains.kotlin.kapt3:stubs=$kaptDir/stubs ` +
102			`-P plugin:org.jetbrains.kotlin.kapt3:correctErrorTypes=true ` +
103			`-P plugin:org.jetbrains.kotlin.kapt3:aptMode=stubsAndApt ` +
104			`-P plugin:org.jetbrains.kotlin.kapt3:javacArguments=$encodedJavacFlags ` +
105			`$kaptProcessorPath ` +
106			`$kaptProcessor ` +
107			`-Xbuild-file=$kotlinBuildFile && ` +
108			`${config.SoongZipCmd} -jar -o $out -C $kaptDir/sources -D $kaptDir/sources && ` +
109			`${config.SoongZipCmd} -jar -o $classesJarOut -C $kaptDir/classes -D $kaptDir/classes && ` +
110			`rm -rf "$srcJarDir"`,
111		CommandDeps: []string{
112			"${config.KotlincCmd}",
113			"${config.KotlinCompilerJar}",
114			"${config.KotlinKaptJar}",
115			"${config.GenKotlinBuildFileCmd}",
116			"${config.SoongZipCmd}",
117			"${config.ZipSyncCmd}",
118		},
119		Rspfile:        "$out.rsp",
120		RspfileContent: `$in`,
121	},
122	"kotlincFlags", "encodedJavacFlags", "kaptProcessorPath", "kaptProcessor",
123	"classpath", "srcJars", "srcJarDir", "kaptDir", "kotlinJvmTarget", "kotlinBuildFile", "name",
124	"classesJarOut")
125
126// kotlinKapt performs Kotlin-compatible annotation processing.  It takes .kt and .java sources and srcjars, and runs
127// annotation processors over all of them, producing a srcjar of generated code in outputFile.  The srcjar should be
128// added as an additional input to kotlinc and javac rules, and the javac rule should have annotation processing
129// disabled.
130func kotlinKapt(ctx android.ModuleContext, srcJarOutputFile, resJarOutputFile android.WritablePath,
131	srcFiles, srcJars android.Paths,
132	flags javaBuilderFlags) {
133
134	var deps android.Paths
135	deps = append(deps, flags.kotlincClasspath...)
136	deps = append(deps, srcJars...)
137	deps = append(deps, flags.processorPath...)
138
139	kaptProcessorPath := flags.processorPath.FormRepeatedClassPath("-P plugin:org.jetbrains.kotlin.kapt3:apclasspath=")
140
141	kaptProcessor := ""
142	for i, p := range flags.processors {
143		if i > 0 {
144			kaptProcessor += " "
145		}
146		kaptProcessor += "-P plugin:org.jetbrains.kotlin.kapt3:processors=" + p
147	}
148
149	encodedJavacFlags := kaptEncodeFlags([][2]string{
150		{"-source", flags.javaVersion.String()},
151		{"-target", flags.javaVersion.String()},
152	})
153
154	kotlinName := filepath.Join(ctx.ModuleDir(), ctx.ModuleSubDir(), ctx.ModuleName())
155	kotlinName = strings.ReplaceAll(kotlinName, "/", "__")
156
157	ctx.Build(pctx, android.BuildParams{
158		Rule:           kapt,
159		Description:    "kapt",
160		Output:         srcJarOutputFile,
161		ImplicitOutput: resJarOutputFile,
162		Inputs:         srcFiles,
163		Implicits:      deps,
164		Args: map[string]string{
165			"classpath":         flags.kotlincClasspath.FormJavaClassPath("-classpath"),
166			"kotlincFlags":      flags.kotlincFlags,
167			"srcJars":           strings.Join(srcJars.Strings(), " "),
168			"srcJarDir":         android.PathForModuleOut(ctx, "kapt", "srcJars").String(),
169			"kotlinBuildFile":   android.PathForModuleOut(ctx, "kapt", "build.xml").String(),
170			"kaptProcessorPath": strings.Join(kaptProcessorPath, " "),
171			"kaptProcessor":     kaptProcessor,
172			"kaptDir":           android.PathForModuleOut(ctx, "kapt/gen").String(),
173			"encodedJavacFlags": encodedJavacFlags,
174			"name":              kotlinName,
175			"classesJarOut":     resJarOutputFile.String(),
176		},
177	})
178}
179
180// kapt converts a list of key, value pairs into a base64 encoded Java serialization, which is what kapt expects.
181func kaptEncodeFlags(options [][2]string) string {
182	buf := &bytes.Buffer{}
183
184	binary.Write(buf, binary.BigEndian, uint32(len(options)))
185	for _, option := range options {
186		binary.Write(buf, binary.BigEndian, uint16(len(option[0])))
187		buf.WriteString(option[0])
188		binary.Write(buf, binary.BigEndian, uint16(len(option[1])))
189		buf.WriteString(option[1])
190	}
191
192	header := &bytes.Buffer{}
193	header.Write([]byte{0xac, 0xed, 0x00, 0x05}) // java serialization header
194
195	if buf.Len() < 256 {
196		header.WriteByte(0x77) // blockdata
197		header.WriteByte(byte(buf.Len()))
198	} else {
199		header.WriteByte(0x7a) // blockdatalong
200		binary.Write(header, binary.BigEndian, uint32(buf.Len()))
201	}
202
203	return base64.StdEncoding.EncodeToString(append(header.Bytes(), buf.Bytes()...))
204}
205