blob: f5983323c69fcea2cd8ecac9736339f7a84c9387 [file] [log] [blame]
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001package bp2build
2
3import (
Cole Fausteb644cf2023-04-11 13:48:17 -07004 "android/soong/starlark_fmt"
Jingwen Chen0ee88a62022-01-07 14:55:29 +00005 "encoding/json"
Cole Fausteb644cf2023-04-11 13:48:17 -07006 "fmt"
Liz Kammer2dd9ca42020-11-25 16:06:39 -08007 "reflect"
Cole Faust37d27c42023-04-12 10:27:45 -07008 "strconv"
Liz Kammer2dd9ca42020-11-25 16:06:39 -08009 "strings"
10
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +000011 "android/soong/android"
Trevor Radcliffe4f95ee92023-01-19 16:02:47 +000012 "android/soong/cc"
Sam Delmerico932c01c2022-03-25 16:33:26 +000013 cc_config "android/soong/cc/config"
14 java_config "android/soong/java/config"
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +000015
Jingwen Chen7810e172022-07-29 02:25:34 +000016 "android/soong/apex"
17
Liz Kammer2dd9ca42020-11-25 16:06:39 -080018 "github.com/google/blueprint/proptools"
19)
20
21type BazelFile struct {
22 Dir string
23 Basename string
24 Contents string
25}
26
Spandan Das83e787e2023-01-11 02:50:00 +000027// PRIVATE: Use CreateSoongInjectionDirFiles instead
Cole Faust9e384e22023-02-08 17:43:09 -080028func soongInjectionFiles(cfg android.Config, metrics CodegenMetrics) ([]BazelFile, error) {
Jingwen Chenbf61afb2021-05-06 13:31:18 +000029 var files []BazelFile
30
Sam Delmerico46d08b42022-11-15 15:51:04 -050031 files = append(files, newFile("android", GeneratedBuildFileName, "")) // Creates a //cc_toolchain package.
32 files = append(files, newFile("android", "constants.bzl", android.BazelCcToolchainVars(cfg)))
33
Jingwen Chenc63677b2021-06-17 05:43:19 +000034 files = append(files, newFile("cc_toolchain", GeneratedBuildFileName, "")) // Creates a //cc_toolchain package.
Trevor Radcliffe4f95ee92023-01-19 16:02:47 +000035 files = append(files, newFile("cc_toolchain", "config_constants.bzl", cc_config.BazelCcToolchainVars(cfg)))
36 files = append(files, newFile("cc_toolchain", "sanitizer_constants.bzl", cc.BazelCcSanitizerToolchainVars(cfg)))
Sam Delmerico932c01c2022-03-25 16:33:26 +000037
38 files = append(files, newFile("java_toolchain", GeneratedBuildFileName, "")) // Creates a //java_toolchain package.
39 files = append(files, newFile("java_toolchain", "constants.bzl", java_config.BazelJavaToolchainVars(cfg)))
Jingwen Chenbf61afb2021-05-06 13:31:18 +000040
Jingwen Chen7810e172022-07-29 02:25:34 +000041 files = append(files, newFile("apex_toolchain", GeneratedBuildFileName, "")) // Creates a //apex_toolchain package.
Cole Faust9e384e22023-02-08 17:43:09 -080042 apexToolchainVars, err := apex.BazelApexToolchainVars()
43 if err != nil {
44 return nil, err
45 }
46 files = append(files, newFile("apex_toolchain", "constants.bzl", apexToolchainVars))
Jingwen Chen7810e172022-07-29 02:25:34 +000047
usta4f5d2c12022-10-28 23:32:01 -040048 files = append(files, newFile("metrics", "converted_modules.txt", strings.Join(metrics.Serialize().ConvertedModules, "\n")))
Jingwen Chenc63677b2021-06-17 05:43:19 +000049
Kevin Dagostino60f562a2022-09-20 03:54:47 +000050 convertedModulePathMap, err := json.MarshalIndent(metrics.convertedModulePathMap, "", "\t")
51 if err != nil {
52 panic(err)
53 }
Jingwen Chen61342112023-04-11 08:49:01 +000054 files = append(files, newFile("metrics", GeneratedBuildFileName, "")) // Creates a //metrics package.
Kevin Dagostino60f562a2022-09-20 03:54:47 +000055 files = append(files, newFile("metrics", "converted_modules_path_map.json", string(convertedModulePathMap)))
Jingwen Chen61342112023-04-11 08:49:01 +000056 files = append(files, newFile("metrics", "converted_modules_path_map.bzl", "modules = "+strings.ReplaceAll(string(convertedModulePathMap), "\\", "\\\\")))
Kevin Dagostino60f562a2022-09-20 03:54:47 +000057
Jingwen Chen01812022021-11-19 14:29:43 +000058 files = append(files, newFile("product_config", "soong_config_variables.bzl", cfg.Bp2buildSoongConfigDefinitions.String()))
59
Liz Kammere8303bd2022-02-16 09:02:48 -050060 files = append(files, newFile("product_config", "arch_configuration.bzl", android.StarlarkArchConfigurations()))
61
Cole Faust34867402023-04-28 12:32:27 -070062 apiLevelsMap, err := android.GetApiLevelsMap(cfg)
63 if err != nil {
64 return nil, err
65 }
66 apiLevelsContent, err := json.Marshal(apiLevelsMap)
Jingwen Chen0ee88a62022-01-07 14:55:29 +000067 if err != nil {
Cole Faust9e384e22023-02-08 17:43:09 -080068 return nil, err
Jingwen Chen0ee88a62022-01-07 14:55:29 +000069 }
70 files = append(files, newFile("api_levels", GeneratedBuildFileName, `exports_files(["api_levels.json"])`))
Alix Espino4fd7e742023-02-24 14:46:43 +000071 // TODO(b/269691302) value of apiLevelsContent is product variable dependent and should be avoided for soong injection
Jingwen Chen0ee88a62022-01-07 14:55:29 +000072 files = append(files, newFile("api_levels", "api_levels.json", string(apiLevelsContent)))
Cole Fausteb644cf2023-04-11 13:48:17 -070073 files = append(files, newFile("api_levels", "platform_versions.bzl", platformVersionContents(cfg)))
Jingwen Chen0ee88a62022-01-07 14:55:29 +000074
Sam Delmericocb3c52c2023-02-03 17:40:08 -050075 files = append(files, newFile("allowlists", GeneratedBuildFileName, ""))
76 files = append(files, newFile("allowlists", "env.bzl", android.EnvironmentVarsFile(cfg)))
Cole Faust705968d2022-12-14 11:32:05 -080077 // TODO(b/262781701): Create an alternate soong_build entrypoint for writing out these files only when requested
78 files = append(files, newFile("allowlists", "mixed_build_prod_allowlist.txt", strings.Join(android.GetBazelEnabledModules(android.BazelProdMode), "\n")+"\n"))
79 files = append(files, newFile("allowlists", "mixed_build_staging_allowlist.txt", strings.Join(android.GetBazelEnabledModules(android.BazelStagingMode), "\n")+"\n"))
80
Cole Faust9e384e22023-02-08 17:43:09 -080081 return files, nil
Jingwen Chenbf61afb2021-05-06 13:31:18 +000082}
83
Cole Fausteb644cf2023-04-11 13:48:17 -070084func platformVersionContents(cfg android.Config) string {
85 // Despite these coming from cfg.productVariables, they are actually hardcoded in global
86 // makefiles, not set in individual product config makesfiles, so they're safe to just export
87 // and load() directly.
88
89 platformVersionActiveCodenames := make([]string, 0, len(cfg.PlatformVersionActiveCodenames()))
90 for _, codename := range cfg.PlatformVersionActiveCodenames() {
91 platformVersionActiveCodenames = append(platformVersionActiveCodenames, fmt.Sprintf("%q", codename))
92 }
93
Cole Faust37d27c42023-04-12 10:27:45 -070094 platformSdkVersion := "None"
95 if cfg.RawPlatformSdkVersion() != nil {
96 platformSdkVersion = strconv.Itoa(*cfg.RawPlatformSdkVersion())
97 }
98
Cole Fausteb644cf2023-04-11 13:48:17 -070099 return fmt.Sprintf(`
100platform_versions = struct(
101 platform_sdk_final = %s,
Cole Faust37d27c42023-04-12 10:27:45 -0700102 platform_sdk_version = %s,
Cole Fausteb644cf2023-04-11 13:48:17 -0700103 platform_sdk_codename = %q,
104 platform_version_active_codenames = [%s],
105)
Cole Faust37d27c42023-04-12 10:27:45 -0700106`, starlark_fmt.PrintBool(cfg.PlatformSdkFinal()), platformSdkVersion, cfg.PlatformSdkCodename(), strings.Join(platformVersionActiveCodenames, ", "))
Cole Fausteb644cf2023-04-11 13:48:17 -0700107}
108
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800109func CreateBazelFiles(
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700110 cfg android.Config,
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800111 ruleShims map[string]RuleShim,
Jingwen Chen40067de2021-01-26 21:58:43 -0500112 buildToTargets map[string]BazelTargets,
Jingwen Chen33832f92021-01-24 22:55:54 -0500113 mode CodegenMode) []BazelFile {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800114
Jingwen Chen6c309cd2021-04-01 07:11:11 +0000115 var files []BazelFile
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800116
Jingwen Chen33832f92021-01-24 22:55:54 -0500117 if mode == QueryView {
Jingwen Chen6c309cd2021-04-01 07:11:11 +0000118 // Write top level WORKSPACE.
119 files = append(files, newFile("", "WORKSPACE", ""))
120
Jingwen Chen12b4c272021-03-10 02:05:59 -0500121 // Used to denote that the top level directory is a package.
122 files = append(files, newFile("", GeneratedBuildFileName, ""))
123
124 files = append(files, newFile(bazelRulesSubDir, GeneratedBuildFileName, ""))
125
Jingwen Chen73850672020-12-14 08:25:34 -0500126 // These files are only used for queryview.
127 files = append(files, newFile(bazelRulesSubDir, "providers.bzl", providersBzl))
128
129 for bzlFileName, ruleShim := range ruleShims {
130 files = append(files, newFile(bazelRulesSubDir, bzlFileName+".bzl", ruleShim.content))
131 }
132 files = append(files, newFile(bazelRulesSubDir, "soong_module.bzl", generateSoongModuleBzl(ruleShims)))
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800133 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800134
Cole Faust324a92e2022-08-23 15:29:05 -0700135 files = append(files, createBuildFiles(buildToTargets, mode)...)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800136
137 return files
138}
139
Cole Faust324a92e2022-08-23 15:29:05 -0700140func createBuildFiles(buildToTargets map[string]BazelTargets, mode CodegenMode) []BazelFile {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800141 files := make([]BazelFile, 0, len(buildToTargets))
Cole Faust18994c72023-02-28 16:02:16 -0800142 for _, dir := range android.SortedKeys(buildToTargets) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800143 targets := buildToTargets[dir]
Jingwen Chen49109762021-05-25 05:16:48 +0000144 targets.sort()
145
146 var content string
Spandan Das5af0bd32022-09-28 20:43:08 +0000147 if mode == Bp2Build || mode == ApiBp2build {
Jingwen Chen49109762021-05-25 05:16:48 +0000148 content = `# READ THIS FIRST:
149# This file was automatically generated by bp2build for the Bazel migration project.
150# Feel free to edit or test it, but do *not* check it into your version control system.
151`
Jingwen Chen1c231732021-02-05 09:38:15 -0500152 content += targets.LoadStatements()
Sasha Smundak8bea2672022-08-04 13:31:14 -0700153 content += "\n\n"
154 // Get package rule from the handcrafted BUILD file, otherwise emit the default one.
155 prText := "package(default_visibility = [\"//visibility:public\"])\n"
156 if pr := targets.packageRule(); pr != nil {
157 prText = pr.content
158 }
159 content += prText
Jingwen Chen49109762021-05-25 05:16:48 +0000160 } else if mode == QueryView {
161 content = soongModuleLoad
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800162 }
Jingwen Chen40067de2021-01-26 21:58:43 -0500163 if content != "" {
164 // If there are load statements, add a couple of newlines.
165 content += "\n\n"
166 }
167 content += targets.String()
Liz Kammerba3ea162021-02-17 13:22:03 -0500168 files = append(files, newFile(dir, GeneratedBuildFileName, content))
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800169 }
170 return files
171}
172
173func newFile(dir, basename, content string) BazelFile {
174 return BazelFile{
175 Dir: dir,
176 Basename: basename,
177 Contents: content,
178 }
179}
180
181const (
182 bazelRulesSubDir = "build/bazel/queryview_rules"
183
184 // additional files:
185 // * workspace file
186 // * base BUILD file
187 // * rules BUILD file
188 // * rules providers.bzl file
189 // * rules soong_module.bzl file
190 numAdditionalFiles = 5
191)
192
193var (
194 // Certain module property names are blocklisted/ignored here, for the reasons commented.
195 ignoredPropNames = map[string]bool{
Sam Delmerico263efde2022-09-08 10:43:42 -0400196 "name": true, // redundant, since this is explicitly generated for every target
197 "from": true, // reserved keyword
198 "in": true, // reserved keyword
199 "size": true, // reserved for tests
200 "arch": true, // interface prop type is not supported yet.
201 "multilib": true, // interface prop type is not supported yet.
202 "target": true, // interface prop type is not supported yet.
203 "visibility": true, // Bazel has native visibility semantics. Handle later.
204 "features": true, // There is already a built-in attribute 'features' which cannot be overridden.
205 "for": true, // reserved keyword, b/233579439
206 "versions_with_info": true, // TODO(b/245730552) struct properties not fully supported
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800207 }
208)
209
210func shouldGenerateAttribute(prop string) bool {
211 return !ignoredPropNames[prop]
212}
213
214func shouldSkipStructField(field reflect.StructField) bool {
Liz Kammer7a210ac2021-09-22 15:52:58 -0400215 if field.PkgPath != "" && !field.Anonymous {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800216 // Skip unexported fields. Some properties are
217 // internal to Soong only, and these fields do not have PkgPath.
218 return true
219 }
Sasha Smundak8bea2672022-08-04 13:31:14 -0700220 // fields with tag `blueprint:"mutated"` are exported to enable modification in mutators, etc.
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800221 // but cannot be set in a .bp file
222 if proptools.HasTag(field, "blueprint", "mutated") {
223 return true
224 }
225 return false
226}
227
228// FIXME(b/168089390): In Bazel, rules ending with "_test" needs to be marked as
229// testonly = True, forcing other rules that depend on _test rules to also be
230// marked as testonly = True. This semantic constraint is not present in Soong.
231// To work around, rename "*_test" rules to "*_test_".
232func canonicalizeModuleType(moduleName string) string {
233 if strings.HasSuffix(moduleName, "_test") {
234 return moduleName + "_"
235 }
236
237 return moduleName
238}