blob: fde9b6949760537f2dff88f1b2edd3b44462d4a5 [file] [log] [blame]
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001// Copyright 2020 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 bp2build
16
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux0da7ce62021-08-23 17:04:20 +000017/*
18For shareable/common functionality for conversion from soong-module to build files
19for queryview/bp2build
20*/
21
Liz Kammer2dd9ca42020-11-25 16:06:39 -080022import (
Liz Kammer2dd9ca42020-11-25 16:06:39 -080023 "fmt"
24 "reflect"
Jingwen Chen49109762021-05-25 05:16:48 +000025 "sort"
Liz Kammer2dd9ca42020-11-25 16:06:39 -080026 "strings"
27
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux0da7ce62021-08-23 17:04:20 +000028 "android/soong/android"
29 "android/soong/bazel"
Liz Kammer72beb342022-02-03 08:42:10 -050030 "android/soong/starlark_fmt"
Liz Kammer2dd9ca42020-11-25 16:06:39 -080031 "github.com/google/blueprint"
32 "github.com/google/blueprint/proptools"
33)
34
35type BazelAttributes struct {
36 Attrs map[string]string
37}
38
39type BazelTarget struct {
Jingwen Chen40067de2021-01-26 21:58:43 -050040 name string
Jingwen Chenc63677b2021-06-17 05:43:19 +000041 packageName string
Jingwen Chen40067de2021-01-26 21:58:43 -050042 content string
43 ruleClass string
44 bzlLoadLocation string
45}
46
47// IsLoadedFromStarlark determines if the BazelTarget's rule class is loaded from a .bzl file,
48// as opposed to a native rule built into Bazel.
49func (t BazelTarget) IsLoadedFromStarlark() bool {
50 return t.bzlLoadLocation != ""
51}
52
Jingwen Chenc63677b2021-06-17 05:43:19 +000053// Label is the fully qualified Bazel label constructed from the BazelTarget's
54// package name and target name.
55func (t BazelTarget) Label() string {
56 if t.packageName == "." {
57 return "//:" + t.name
58 } else {
59 return "//" + t.packageName + ":" + t.name
60 }
61}
62
Spandan Dasabedff02023-03-07 19:24:34 +000063// PackageName returns the package of the Bazel target.
64// Defaults to root of tree.
65func (t BazelTarget) PackageName() string {
66 if t.packageName == "" {
67 return "."
68 }
69 return t.packageName
70}
71
Jingwen Chen40067de2021-01-26 21:58:43 -050072// BazelTargets is a typedef for a slice of BazelTarget objects.
73type BazelTargets []BazelTarget
74
Sasha Smundak8bea2672022-08-04 13:31:14 -070075func (targets BazelTargets) packageRule() *BazelTarget {
76 for _, target := range targets {
77 if target.ruleClass == "package" {
78 return &target
79 }
80 }
81 return nil
82}
83
84// sort a list of BazelTargets in-place, by name, and by generated/handcrafted types.
Jingwen Chen49109762021-05-25 05:16:48 +000085func (targets BazelTargets) sort() {
86 sort.Slice(targets, func(i, j int) bool {
Jingwen Chen49109762021-05-25 05:16:48 +000087 return targets[i].name < targets[j].name
88 })
89}
90
Jingwen Chen40067de2021-01-26 21:58:43 -050091// String returns the string representation of BazelTargets, without load
92// statements (use LoadStatements for that), since the targets are usually not
93// adjacent to the load statements at the top of the BUILD file.
94func (targets BazelTargets) String() string {
95 var res string
96 for i, target := range targets {
Sasha Smundak8bea2672022-08-04 13:31:14 -070097 if target.ruleClass != "package" {
98 res += target.content
99 }
Jingwen Chen40067de2021-01-26 21:58:43 -0500100 if i != len(targets)-1 {
101 res += "\n\n"
102 }
103 }
104 return res
105}
106
107// LoadStatements return the string representation of the sorted and deduplicated
108// Starlark rule load statements needed by a group of BazelTargets.
109func (targets BazelTargets) LoadStatements() string {
110 bzlToLoadedSymbols := map[string][]string{}
111 for _, target := range targets {
112 if target.IsLoadedFromStarlark() {
113 bzlToLoadedSymbols[target.bzlLoadLocation] =
114 append(bzlToLoadedSymbols[target.bzlLoadLocation], target.ruleClass)
115 }
116 }
117
118 var loadStatements []string
119 for bzl, ruleClasses := range bzlToLoadedSymbols {
120 loadStatement := "load(\""
121 loadStatement += bzl
122 loadStatement += "\", "
123 ruleClasses = android.SortedUniqueStrings(ruleClasses)
124 for i, ruleClass := range ruleClasses {
125 loadStatement += "\"" + ruleClass + "\""
126 if i != len(ruleClasses)-1 {
127 loadStatement += ", "
128 }
129 }
130 loadStatement += ")"
131 loadStatements = append(loadStatements, loadStatement)
132 }
133 return strings.Join(android.SortedUniqueStrings(loadStatements), "\n")
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800134}
135
136type bpToBuildContext interface {
137 ModuleName(module blueprint.Module) string
138 ModuleDir(module blueprint.Module) string
139 ModuleSubDir(module blueprint.Module) string
140 ModuleType(module blueprint.Module) string
141
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500142 VisitAllModules(visit func(blueprint.Module))
143 VisitDirectDeps(module blueprint.Module, visit func(blueprint.Module))
144}
145
146type CodegenContext struct {
Jingwen Chen16d90a82021-09-17 07:16:13 +0000147 config android.Config
Paul Duffinc6390592022-11-04 13:35:21 +0000148 context *android.Context
Jingwen Chen16d90a82021-09-17 07:16:13 +0000149 mode CodegenMode
150 additionalDeps []string
Liz Kammer6eff3232021-08-26 08:37:59 -0400151 unconvertedDepMode unconvertedDepsMode
Cole Faustb85d1a12022-11-08 18:14:01 -0800152 topDir string
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500153}
154
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400155func (ctx *CodegenContext) Mode() CodegenMode {
156 return ctx.mode
Jingwen Chen164e0862021-02-19 00:48:40 -0500157}
158
Jingwen Chen33832f92021-01-24 22:55:54 -0500159// CodegenMode is an enum to differentiate code-generation modes.
160type CodegenMode int
161
162const (
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400163 // Bp2Build - generate BUILD files with targets buildable by Bazel directly.
Jingwen Chen33832f92021-01-24 22:55:54 -0500164 //
165 // This mode is used for the Soong->Bazel build definition conversion.
166 Bp2Build CodegenMode = iota
167
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400168 // QueryView - generate BUILD files with targets representing fully mutated
Jingwen Chen33832f92021-01-24 22:55:54 -0500169 // Soong modules, representing the fully configured Soong module graph with
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400170 // variants and dependency edges.
Jingwen Chen33832f92021-01-24 22:55:54 -0500171 //
172 // This mode is used for discovering and introspecting the existing Soong
173 // module graph.
174 QueryView
Spandan Das5af0bd32022-09-28 20:43:08 +0000175
176 // ApiBp2build - generate BUILD files for API contribution targets
177 ApiBp2build
Jingwen Chen33832f92021-01-24 22:55:54 -0500178)
179
Liz Kammer6eff3232021-08-26 08:37:59 -0400180type unconvertedDepsMode int
181
182const (
183 // Include a warning in conversion metrics about converted modules with unconverted direct deps
184 warnUnconvertedDeps unconvertedDepsMode = iota
185 // Error and fail conversion if encountering a module with unconverted direct deps
186 // Enabled by setting environment variable `BP2BUILD_ERROR_UNCONVERTED`
187 errorModulesUnconvertedDeps
188)
189
Jingwen Chendcc329a2021-01-26 02:49:03 -0500190func (mode CodegenMode) String() string {
191 switch mode {
192 case Bp2Build:
193 return "Bp2Build"
194 case QueryView:
195 return "QueryView"
Spandan Das5af0bd32022-09-28 20:43:08 +0000196 case ApiBp2build:
197 return "ApiBp2build"
Jingwen Chendcc329a2021-01-26 02:49:03 -0500198 default:
199 return fmt.Sprintf("%d", mode)
200 }
201}
202
Liz Kammerba3ea162021-02-17 13:22:03 -0500203// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
204// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
205// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
206// call AdditionalNinjaDeps and add them manually to the ninja file.
207func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
208 ctx.additionalDeps = append(ctx.additionalDeps, deps...)
209}
210
211// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
212func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
213 return ctx.additionalDeps
214}
215
Paul Duffinc6390592022-11-04 13:35:21 +0000216func (ctx *CodegenContext) Config() android.Config { return ctx.config }
217func (ctx *CodegenContext) Context() *android.Context { return ctx.context }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500218
219// NewCodegenContext creates a wrapper context that conforms to PathContext for
220// writing BUILD files in the output directory.
Cole Faustb85d1a12022-11-08 18:14:01 -0800221func NewCodegenContext(config android.Config, context *android.Context, mode CodegenMode, topDir string) *CodegenContext {
Liz Kammer6eff3232021-08-26 08:37:59 -0400222 var unconvertedDeps unconvertedDepsMode
223 if config.IsEnvTrue("BP2BUILD_ERROR_UNCONVERTED") {
224 unconvertedDeps = errorModulesUnconvertedDeps
225 }
Liz Kammerba3ea162021-02-17 13:22:03 -0500226 return &CodegenContext{
Liz Kammer6eff3232021-08-26 08:37:59 -0400227 context: context,
228 config: config,
229 mode: mode,
230 unconvertedDepMode: unconvertedDeps,
Cole Faustb85d1a12022-11-08 18:14:01 -0800231 topDir: topDir,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500232 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800233}
234
235// props is an unsorted map. This function ensures that
236// the generated attributes are sorted to ensure determinism.
237func propsToAttributes(props map[string]string) string {
238 var attributes string
Cole Faust18994c72023-02-28 16:02:16 -0800239 for _, propName := range android.SortedKeys(props) {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400240 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800241 }
242 return attributes
243}
244
Liz Kammer6eff3232021-08-26 08:37:59 -0400245type conversionResults struct {
246 buildFileToTargets map[string]BazelTargets
247 metrics CodegenMetrics
Liz Kammer6eff3232021-08-26 08:37:59 -0400248}
249
250func (r conversionResults) BuildDirToTargets() map[string]BazelTargets {
251 return r.buildFileToTargets
252}
253
254func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (conversionResults, []error) {
Jingwen Chen40067de2021-01-26 21:58:43 -0500255 buildFileToTargets := make(map[string]BazelTargets)
Jingwen Chen164e0862021-02-19 00:48:40 -0500256
257 // Simple metrics tracking for bp2build
usta4f5d2c12022-10-28 23:32:01 -0400258 metrics := CreateCodegenMetrics()
Jingwen Chen164e0862021-02-19 00:48:40 -0500259
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400260 dirs := make(map[string]bool)
261
Liz Kammer6eff3232021-08-26 08:37:59 -0400262 var errs []error
263
Jingwen Chen164e0862021-02-19 00:48:40 -0500264 bpCtx := ctx.Context()
265 bpCtx.VisitAllModules(func(m blueprint.Module) {
266 dir := bpCtx.ModuleDir(m)
Chris Parsons492bd912022-01-20 12:55:05 -0500267 moduleType := bpCtx.ModuleType(m)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400268 dirs[dir] = true
269
Liz Kammer2ada09a2021-08-11 00:17:36 -0400270 var targets []BazelTarget
Jingwen Chen73850672020-12-14 08:25:34 -0500271
Jingwen Chen164e0862021-02-19 00:48:40 -0500272 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500273 case Bp2Build:
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000274 // There are two main ways of converting a Soong module to Bazel:
275 // 1) Manually handcrafting a Bazel target and associating the module with its label
276 // 2) Automatically generating with bp2build converters
277 //
278 // bp2build converters are used for the majority of modules.
Liz Kammerba3ea162021-02-17 13:22:03 -0500279 if b, ok := m.(android.Bazelable); ok && b.HasHandcraftedLabel() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000280 // Handle modules converted to handcrafted targets.
281 //
282 // Since these modules are associated with some handcrafted
Cole Faustea602c52022-08-31 14:48:26 -0700283 // target in a BUILD file, we don't autoconvert them.
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000284
285 // Log the module.
Kevin Dagostino60f562a2022-09-20 03:54:47 +0000286 metrics.AddConvertedModule(m, moduleType, dir, Handcrafted)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400287 } else if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000288 // Handle modules converted to generated targets.
289
290 // Log the module.
Kevin Dagostino60f562a2022-09-20 03:54:47 +0000291 metrics.AddConvertedModule(aModule, moduleType, dir, Generated)
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000292
293 // Handle modules with unconverted deps. By default, emit a warning.
Liz Kammer6eff3232021-08-26 08:37:59 -0400294 if unconvertedDeps := aModule.GetUnconvertedBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700295 msg := fmt.Sprintf("%s %s:%s depends on unconverted modules: %s",
296 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400297 switch ctx.unconvertedDepMode {
298 case warnUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400299 metrics.moduleWithUnconvertedDepsMsgs = append(metrics.moduleWithUnconvertedDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400300 case errorModulesUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400301 errs = append(errs, fmt.Errorf(msg))
302 return
303 }
304 }
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500305 if unconvertedDeps := aModule.GetMissingBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700306 msg := fmt.Sprintf("%s %s:%s depends on missing modules: %s",
307 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400308 switch ctx.unconvertedDepMode {
309 case warnUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500310 metrics.moduleWithMissingDepsMsgs = append(metrics.moduleWithMissingDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400311 case errorModulesUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500312 errs = append(errs, fmt.Errorf(msg))
313 return
314 }
315 }
Alix94e26032022-08-16 20:37:33 +0000316 var targetErrs []error
317 targets, targetErrs = generateBazelTargets(bpCtx, aModule)
318 errs = append(errs, targetErrs...)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400319 for _, t := range targets {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000320 // A module can potentially generate more than 1 Bazel
321 // target, each of a different rule class.
322 metrics.IncrementRuleClassCount(t.ruleClass)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400323 }
Liz Kammerfc46bc12021-02-19 11:06:17 -0500324 } else {
Chris Parsons492bd912022-01-20 12:55:05 -0500325 metrics.AddUnconvertedModule(moduleType)
Liz Kammerba3ea162021-02-17 13:22:03 -0500326 return
Jingwen Chen73850672020-12-14 08:25:34 -0500327 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500328 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500329 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500330 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500331 // package module name contain slashes, and thus cannot
332 // be mapped cleanly to a bazel label.
333 return
334 }
Alix94e26032022-08-16 20:37:33 +0000335 t, err := generateSoongModuleTarget(bpCtx, m)
336 if err != nil {
337 errs = append(errs, err)
338 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400339 targets = append(targets, t)
Spandan Das5af0bd32022-09-28 20:43:08 +0000340 case ApiBp2build:
341 if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
342 targets, errs = generateBazelTargets(bpCtx, aModule)
343 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500344 default:
Liz Kammer6eff3232021-08-26 08:37:59 -0400345 errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
346 return
Jingwen Chen73850672020-12-14 08:25:34 -0500347 }
348
Spandan Dasabedff02023-03-07 19:24:34 +0000349 for _, target := range targets {
350 targetDir := target.PackageName()
351 buildFileToTargets[targetDir] = append(buildFileToTargets[targetDir], target)
352 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800353 })
Liz Kammer6eff3232021-08-26 08:37:59 -0400354
355 if len(errs) > 0 {
356 return conversionResults{}, errs
357 }
358
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400359 if generateFilegroups {
360 // Add a filegroup target that exposes all sources in the subtree of this package
361 // NOTE: This also means we generate a BUILD file for every Android.bp file (as long as it has at least one module)
Cole Faust324a92e2022-08-23 15:29:05 -0700362 //
363 // This works because: https://bazel.build/reference/be/functions#exports_files
364 // "As a legacy behaviour, also files mentioned as input to a rule are exported with the
365 // default visibility until the flag --incompatible_no_implicit_file_export is flipped. However, this behavior
366 // should not be relied upon and actively migrated away from."
367 //
368 // TODO(b/198619163): We should change this to export_files(glob(["**/*"])) instead, but doing that causes these errors:
369 // "Error in exports_files: generated label '//external/avb:avbtool' conflicts with existing py_binary rule"
370 // So we need to solve all the "target ... is both a rule and a file" warnings first.
Usta Shresthac6057152022-09-24 00:23:31 -0400371 for dir := range dirs {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400372 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
373 name: "bp2build_all_srcs",
374 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]))`,
375 ruleClass: "filegroup",
376 })
377 }
378 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500379
Liz Kammer6eff3232021-08-26 08:37:59 -0400380 return conversionResults{
381 buildFileToTargets: buildFileToTargets,
382 metrics: metrics,
Liz Kammer6eff3232021-08-26 08:37:59 -0400383 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500384}
385
Alix94e26032022-08-16 20:37:33 +0000386func generateBazelTargets(ctx bpToBuildContext, m android.Module) ([]BazelTarget, []error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400387 var targets []BazelTarget
Alix94e26032022-08-16 20:37:33 +0000388 var errs []error
Liz Kammer2ada09a2021-08-11 00:17:36 -0400389 for _, m := range m.Bp2buildTargets() {
Alix94e26032022-08-16 20:37:33 +0000390 target, err := generateBazelTarget(ctx, m)
391 if err != nil {
392 errs = append(errs, err)
393 return targets, errs
394 }
395 targets = append(targets, target)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400396 }
Alix94e26032022-08-16 20:37:33 +0000397 return targets, errs
Liz Kammer2ada09a2021-08-11 00:17:36 -0400398}
399
400type bp2buildModule interface {
401 TargetName() string
402 TargetPackage() string
403 BazelRuleClass() string
404 BazelRuleLoadLocation() string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000405 BazelAttributes() []interface{}
Liz Kammer2ada09a2021-08-11 00:17:36 -0400406}
407
Alix94e26032022-08-16 20:37:33 +0000408func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) (BazelTarget, error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400409 ruleClass := m.BazelRuleClass()
410 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500411
Jingwen Chen73850672020-12-14 08:25:34 -0500412 // extract the bazel attributes from the module.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000413 attrs := m.BazelAttributes()
Alix94e26032022-08-16 20:37:33 +0000414 props, err := extractModuleProperties(attrs, true)
415 if err != nil {
416 return BazelTarget{}, err
417 }
Jingwen Chen73850672020-12-14 08:25:34 -0500418
Liz Kammer0eae52e2021-10-06 10:32:26 -0400419 // name is handled in a special manner
420 delete(props.Attrs, "name")
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500421
Jingwen Chen73850672020-12-14 08:25:34 -0500422 // Return the Bazel target with rule class and attributes, ready to be
423 // code-generated.
424 attributes := propsToAttributes(props.Attrs)
Sasha Smundakfb589492022-08-04 11:13:27 -0700425 var content string
Liz Kammer2ada09a2021-08-11 00:17:36 -0400426 targetName := m.TargetName()
Sasha Smundakfb589492022-08-04 11:13:27 -0700427 if targetName != "" {
428 content = fmt.Sprintf(ruleTargetTemplate, ruleClass, targetName, attributes)
429 } else {
430 content = fmt.Sprintf(unnamedRuleTargetTemplate, ruleClass, attributes)
431 }
Jingwen Chen73850672020-12-14 08:25:34 -0500432 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500433 name: targetName,
Liz Kammer2ada09a2021-08-11 00:17:36 -0400434 packageName: m.TargetPackage(),
Jingwen Chen40067de2021-01-26 21:58:43 -0500435 ruleClass: ruleClass,
436 bzlLoadLocation: bzlLoadLocation,
Sasha Smundakfb589492022-08-04 11:13:27 -0700437 content: content,
Alix94e26032022-08-16 20:37:33 +0000438 }, nil
Jingwen Chen73850672020-12-14 08:25:34 -0500439}
440
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800441// Convert a module and its deps and props into a Bazel macro/rule
442// representation in the BUILD file.
Alix94e26032022-08-16 20:37:33 +0000443func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) (BazelTarget, error) {
444 props, err := getBuildProperties(ctx, m)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800445
446 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
447 // items, if the modules are added using different DependencyTag. Figure
448 // out the implications of that.
449 depLabels := map[string]bool{}
450 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500451 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800452 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
453 })
454 }
Liz Kammer0eae52e2021-10-06 10:32:26 -0400455
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400456 for p := range ignoredPropNames {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400457 delete(props.Attrs, p)
458 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800459 attributes := propsToAttributes(props.Attrs)
460
461 depLabelList := "[\n"
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400462 for depLabel := range depLabels {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800463 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
464 }
465 depLabelList += " ]"
466
467 targetName := targetNameWithVariant(ctx, m)
468 return BazelTarget{
Spandan Dasabedff02023-03-07 19:24:34 +0000469 name: targetName,
470 packageName: ctx.ModuleDir(m),
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800471 content: fmt.Sprintf(
Sasha Smundakfb589492022-08-04 11:13:27 -0700472 soongModuleTargetTemplate,
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800473 targetName,
474 ctx.ModuleName(m),
475 canonicalizeModuleType(ctx.ModuleType(m)),
476 ctx.ModuleSubDir(m),
477 depLabelList,
478 attributes),
Alix94e26032022-08-16 20:37:33 +0000479 }, err
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800480}
481
Alix94e26032022-08-16 20:37:33 +0000482func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800483 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
484 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
485 if aModule, ok := m.(android.Module); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000486 return extractModuleProperties(aModule.GetProperties(), false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800487 }
488
Alix94e26032022-08-16 20:37:33 +0000489 return BazelAttributes{}, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800490}
491
492// Generically extract module properties and types into a map, keyed by the module property name.
Alix94e26032022-08-16 20:37:33 +0000493func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800494 ret := map[string]string{}
495
496 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400497 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800498 propertiesValue := reflect.ValueOf(properties)
499 // Check that propertiesValue is a pointer to the Properties struct, like
500 // *cc.BaseLinkerProperties or *java.CompilerProperties.
501 //
502 // propertiesValue can also be type-asserted to the structs to
503 // manipulate internal props, if needed.
504 if isStructPtr(propertiesValue.Type()) {
505 structValue := propertiesValue.Elem()
Alix94e26032022-08-16 20:37:33 +0000506 ok, err := extractStructProperties(structValue, 0)
507 if err != nil {
508 return BazelAttributes{}, err
509 }
510 for k, v := range ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000511 if existing, exists := ret[k]; checkForDuplicateProperties && exists {
Alix94e26032022-08-16 20:37:33 +0000512 return BazelAttributes{}, fmt.Errorf(
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000513 "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes",
Alix94e26032022-08-16 20:37:33 +0000514 k, existing)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000515 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800516 ret[k] = v
517 }
518 } else {
Alix94e26032022-08-16 20:37:33 +0000519 return BazelAttributes{},
520 fmt.Errorf(
521 "properties must be a pointer to a struct, got %T",
522 propertiesValue.Interface())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800523 }
524 }
525
Liz Kammer2ada09a2021-08-11 00:17:36 -0400526 return BazelAttributes{
527 Attrs: ret,
Alix94e26032022-08-16 20:37:33 +0000528 }, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800529}
530
531func isStructPtr(t reflect.Type) bool {
532 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
533}
534
535// prettyPrint a property value into the equivalent Starlark representation
536// recursively.
Jingwen Chen58ff6802021-11-17 12:14:41 +0000537func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) {
538 if !emitZeroValues && isZero(propertyValue) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800539 // A property value being set or unset actually matters -- Soong does set default
540 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
541 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
542 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +0000543 // In Bazel-parlance, we would use "attr.<type>(default = <default
544 // value>)" to set the default value of unset attributes. In the cases
545 // where the bp2build converter didn't set the default value within the
546 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -0400547 // value. For those cases, we return an empty string so we don't
548 // unnecessarily generate empty values.
549 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800550 }
551
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800552 switch propertyValue.Kind() {
553 case reflect.String:
Liz Kammer72beb342022-02-03 08:42:10 -0500554 return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800555 case reflect.Bool:
Liz Kammer72beb342022-02-03 08:42:10 -0500556 return starlark_fmt.PrintBool(propertyValue.Bool()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800557 case reflect.Int, reflect.Uint, reflect.Int64:
Liz Kammer72beb342022-02-03 08:42:10 -0500558 return fmt.Sprintf("%v", propertyValue.Interface()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800559 case reflect.Ptr:
Jingwen Chen58ff6802021-11-17 12:14:41 +0000560 return prettyPrint(propertyValue.Elem(), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800561 case reflect.Slice:
Liz Kammer72beb342022-02-03 08:42:10 -0500562 elements := make([]string, 0, propertyValue.Len())
563 for i := 0; i < propertyValue.Len(); i++ {
564 val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800565 if err != nil {
566 return "", err
567 }
Liz Kammer72beb342022-02-03 08:42:10 -0500568 if val != "" {
569 elements = append(elements, val)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800570 }
571 }
Sam Delmerico932c01c2022-03-25 16:33:26 +0000572 return starlark_fmt.PrintList(elements, indent, func(s string) string {
573 return "%s"
574 }), nil
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000575
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800576 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -0500577 // Special cases where the bp2build sends additional information to the codegenerator
578 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +0000579 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
580 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -0500581 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
582 return fmt.Sprintf("%q", label.Label), nil
583 }
584
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800585 // Sort and print the struct props by the key.
Alix94e26032022-08-16 20:37:33 +0000586 structProps, err := extractStructProperties(propertyValue, indent)
587
588 if err != nil {
589 return "", err
590 }
591
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000592 if len(structProps) == 0 {
593 return "", nil
594 }
Liz Kammer72beb342022-02-03 08:42:10 -0500595 return starlark_fmt.PrintDict(structProps, indent), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800596 case reflect.Interface:
597 // TODO(b/164227191): implement pretty print for interfaces.
598 // Interfaces are used for for arch, multilib and target properties.
599 return "", nil
600 default:
601 return "", fmt.Errorf(
602 "unexpected kind for property struct field: %s", propertyValue.Kind())
603 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800604}
605
606// Converts a reflected property struct value into a map of property names and property values,
607// which each property value correctly pretty-printed and indented at the right nest level,
608// since property structs can be nested. In Starlark, nested structs are represented as nested
609// dicts: https://docs.bazel.build/skylark/lib/dict.html
Alix94e26032022-08-16 20:37:33 +0000610func extractStructProperties(structValue reflect.Value, indent int) (map[string]string, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800611 if structValue.Kind() != reflect.Struct {
Alix94e26032022-08-16 20:37:33 +0000612 return map[string]string{}, fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800613 }
614
Alix94e26032022-08-16 20:37:33 +0000615 var err error
616
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800617 ret := map[string]string{}
618 structType := structValue.Type()
619 for i := 0; i < structValue.NumField(); i++ {
620 field := structType.Field(i)
621 if shouldSkipStructField(field) {
622 continue
623 }
624
625 fieldValue := structValue.Field(i)
626 if isZero(fieldValue) {
627 // Ignore zero-valued fields
628 continue
629 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400630
Liz Kammer32a03392021-09-14 11:17:21 -0400631 // if the struct is embedded (anonymous), flatten the properties into the containing struct
632 if field.Anonymous {
633 if field.Type.Kind() == reflect.Ptr {
634 fieldValue = fieldValue.Elem()
635 }
636 if fieldValue.Type().Kind() == reflect.Struct {
Alix94e26032022-08-16 20:37:33 +0000637 propsToMerge, err := extractStructProperties(fieldValue, indent)
638 if err != nil {
639 return map[string]string{}, err
640 }
Liz Kammer32a03392021-09-14 11:17:21 -0400641 for prop, value := range propsToMerge {
642 ret[prop] = value
643 }
644 continue
645 }
646 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800647
648 propertyName := proptools.PropertyNameForField(field.Name)
Alix94e26032022-08-16 20:37:33 +0000649 var prettyPrintedValue string
650 prettyPrintedValue, err = prettyPrint(fieldValue, indent+1, false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800651 if err != nil {
Alix94e26032022-08-16 20:37:33 +0000652 return map[string]string{}, fmt.Errorf(
653 "Error while parsing property: %q. %s",
654 propertyName,
655 err)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800656 }
657 if prettyPrintedValue != "" {
658 ret[propertyName] = prettyPrintedValue
659 }
660 }
661
Alix94e26032022-08-16 20:37:33 +0000662 return ret, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800663}
664
665func isZero(value reflect.Value) bool {
666 switch value.Kind() {
667 case reflect.Func, reflect.Map, reflect.Slice:
668 return value.IsNil()
669 case reflect.Array:
670 valueIsZero := true
671 for i := 0; i < value.Len(); i++ {
672 valueIsZero = valueIsZero && isZero(value.Index(i))
673 }
674 return valueIsZero
675 case reflect.Struct:
676 valueIsZero := true
677 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +0200678 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800679 }
680 return valueIsZero
681 case reflect.Ptr:
682 if !value.IsNil() {
683 return isZero(reflect.Indirect(value))
684 } else {
685 return true
686 }
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500687 // Always print bool/strings, if you want a bool/string attribute to be able to take the default value, use a
688 // pointer instead
689 case reflect.Bool, reflect.String:
Liz Kammerd366c902021-06-03 13:43:01 -0400690 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800691 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -0400692 if !value.IsValid() {
693 return true
694 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800695 zeroValue := reflect.Zero(value.Type())
696 result := value.Interface() == zeroValue.Interface()
697 return result
698 }
699}
700
701func escapeString(s string) string {
702 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +0000703
704 // b/184026959: Reverse the application of some common control sequences.
705 // These must be generated literally in the BUILD file.
706 s = strings.ReplaceAll(s, "\t", "\\t")
707 s = strings.ReplaceAll(s, "\n", "\\n")
708 s = strings.ReplaceAll(s, "\r", "\\r")
709
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800710 return strings.ReplaceAll(s, "\"", "\\\"")
711}
712
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800713func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
714 name := ""
715 if c.ModuleSubDir(logicModule) != "" {
716 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
717 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
718 } else {
719 name = c.ModuleName(logicModule)
720 }
721
722 return strings.Replace(name, "//", "", 1)
723}
724
725func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
726 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
727}