blob: e6941df30755f801aae9bb214ad337be624243be [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"
Chris Parsons39a16972023-06-08 14:28:51 +000031 "android/soong/ui/metrics/bp2build_metrics_proto"
ustada2a2112023-08-08 00:29:08 -040032
Liz Kammer2dd9ca42020-11-25 16:06:39 -080033 "github.com/google/blueprint"
Spandan Dasea2abba2023-06-14 21:30:38 +000034 "github.com/google/blueprint/bootstrap"
Liz Kammer2dd9ca42020-11-25 16:06:39 -080035 "github.com/google/blueprint/proptools"
36)
37
38type BazelAttributes struct {
39 Attrs map[string]string
40}
41
Cole Faustb4cb0c82023-09-14 15:16:58 -070042type BazelLoadSymbol struct {
43 // The name of the symbol in the file being loaded
44 symbol string
45 // The name the symbol wil have in this file. Can be left blank to use the same name as symbol.
46 alias string
Jingwen Chen40067de2021-01-26 21:58:43 -050047}
48
Cole Faustb4cb0c82023-09-14 15:16:58 -070049type BazelLoad struct {
50 file string
51 symbols []BazelLoadSymbol
52}
53
54type BazelTarget struct {
55 name string
56 packageName string
57 content string
58 ruleClass string
59 loads []BazelLoad
Jingwen Chen40067de2021-01-26 21:58:43 -050060}
61
Jingwen Chenc63677b2021-06-17 05:43:19 +000062// Label is the fully qualified Bazel label constructed from the BazelTarget's
63// package name and target name.
64func (t BazelTarget) Label() string {
65 if t.packageName == "." {
66 return "//:" + t.name
67 } else {
68 return "//" + t.packageName + ":" + t.name
69 }
70}
71
Spandan Dasabedff02023-03-07 19:24:34 +000072// PackageName returns the package of the Bazel target.
73// Defaults to root of tree.
74func (t BazelTarget) PackageName() string {
75 if t.packageName == "" {
76 return "."
77 }
78 return t.packageName
79}
80
Jingwen Chen40067de2021-01-26 21:58:43 -050081// BazelTargets is a typedef for a slice of BazelTarget objects.
82type BazelTargets []BazelTarget
83
Sasha Smundak8bea2672022-08-04 13:31:14 -070084func (targets BazelTargets) packageRule() *BazelTarget {
85 for _, target := range targets {
86 if target.ruleClass == "package" {
87 return &target
88 }
89 }
90 return nil
91}
92
93// sort a list of BazelTargets in-place, by name, and by generated/handcrafted types.
Jingwen Chen49109762021-05-25 05:16:48 +000094func (targets BazelTargets) sort() {
95 sort.Slice(targets, func(i, j int) bool {
Jingwen Chen49109762021-05-25 05:16:48 +000096 return targets[i].name < targets[j].name
97 })
98}
99
Jingwen Chen40067de2021-01-26 21:58:43 -0500100// String returns the string representation of BazelTargets, without load
101// statements (use LoadStatements for that), since the targets are usually not
102// adjacent to the load statements at the top of the BUILD file.
103func (targets BazelTargets) String() string {
ustada2a2112023-08-08 00:29:08 -0400104 var res strings.Builder
Jingwen Chen40067de2021-01-26 21:58:43 -0500105 for i, target := range targets {
Sasha Smundak8bea2672022-08-04 13:31:14 -0700106 if target.ruleClass != "package" {
ustada2a2112023-08-08 00:29:08 -0400107 res.WriteString(target.content)
Sasha Smundak8bea2672022-08-04 13:31:14 -0700108 }
Jingwen Chen40067de2021-01-26 21:58:43 -0500109 if i != len(targets)-1 {
ustada2a2112023-08-08 00:29:08 -0400110 res.WriteString("\n\n")
Jingwen Chen40067de2021-01-26 21:58:43 -0500111 }
112 }
ustada2a2112023-08-08 00:29:08 -0400113 return res.String()
Jingwen Chen40067de2021-01-26 21:58:43 -0500114}
115
116// LoadStatements return the string representation of the sorted and deduplicated
117// Starlark rule load statements needed by a group of BazelTargets.
118func (targets BazelTargets) LoadStatements() string {
Cole Faustb4cb0c82023-09-14 15:16:58 -0700119 // First, merge all the load statements from all the targets onto one list
120 bzlToLoadedSymbols := map[string][]BazelLoadSymbol{}
Jingwen Chen40067de2021-01-26 21:58:43 -0500121 for _, target := range targets {
Cole Faustb4cb0c82023-09-14 15:16:58 -0700122 for _, load := range target.loads {
123 outer:
124 for _, symbol := range load.symbols {
125 alias := symbol.alias
126 if alias == "" {
127 alias = symbol.symbol
128 }
129 for _, otherSymbol := range bzlToLoadedSymbols[load.file] {
130 otherAlias := otherSymbol.alias
131 if otherAlias == "" {
132 otherAlias = otherSymbol.symbol
133 }
134 if symbol.symbol == otherSymbol.symbol && alias == otherAlias {
135 continue outer
136 } else if alias == otherAlias {
137 panic(fmt.Sprintf("Conflicting destination (%s) for loads of %s and %s", alias, symbol.symbol, otherSymbol.symbol))
138 }
139 }
140 bzlToLoadedSymbols[load.file] = append(bzlToLoadedSymbols[load.file], symbol)
141 }
Jingwen Chen40067de2021-01-26 21:58:43 -0500142 }
143 }
144
Cole Faustb4cb0c82023-09-14 15:16:58 -0700145 var loadStatements strings.Builder
146 for i, bzl := range android.SortedKeys(bzlToLoadedSymbols) {
147 symbols := bzlToLoadedSymbols[bzl]
148 loadStatements.WriteString("load(\"")
149 loadStatements.WriteString(bzl)
150 loadStatements.WriteString("\", ")
151 sort.Slice(symbols, func(i, j int) bool {
152 if symbols[i].symbol < symbols[j].symbol {
153 return true
154 }
155 return symbols[i].alias < symbols[j].alias
156 })
157 for j, symbol := range symbols {
158 if symbol.alias != "" && symbol.alias != symbol.symbol {
159 loadStatements.WriteString(symbol.alias)
160 loadStatements.WriteString(" = ")
161 }
162 loadStatements.WriteString("\"")
163 loadStatements.WriteString(symbol.symbol)
164 loadStatements.WriteString("\"")
165 if j != len(symbols)-1 {
166 loadStatements.WriteString(", ")
Jingwen Chen40067de2021-01-26 21:58:43 -0500167 }
168 }
Cole Faustb4cb0c82023-09-14 15:16:58 -0700169 loadStatements.WriteString(")")
170 if i != len(bzlToLoadedSymbols)-1 {
171 loadStatements.WriteString("\n")
172 }
Jingwen Chen40067de2021-01-26 21:58:43 -0500173 }
Cole Faustb4cb0c82023-09-14 15:16:58 -0700174 return loadStatements.String()
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800175}
176
177type bpToBuildContext interface {
178 ModuleName(module blueprint.Module) string
179 ModuleDir(module blueprint.Module) string
180 ModuleSubDir(module blueprint.Module) string
181 ModuleType(module blueprint.Module) string
182
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500183 VisitAllModules(visit func(blueprint.Module))
184 VisitDirectDeps(module blueprint.Module, visit func(blueprint.Module))
185}
186
187type CodegenContext struct {
Jingwen Chen16d90a82021-09-17 07:16:13 +0000188 config android.Config
Paul Duffinc6390592022-11-04 13:35:21 +0000189 context *android.Context
Jingwen Chen16d90a82021-09-17 07:16:13 +0000190 mode CodegenMode
191 additionalDeps []string
Liz Kammer6eff3232021-08-26 08:37:59 -0400192 unconvertedDepMode unconvertedDepsMode
Cole Faustb85d1a12022-11-08 18:14:01 -0800193 topDir string
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500194}
195
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400196func (ctx *CodegenContext) Mode() CodegenMode {
197 return ctx.mode
Jingwen Chen164e0862021-02-19 00:48:40 -0500198}
199
Jingwen Chen33832f92021-01-24 22:55:54 -0500200// CodegenMode is an enum to differentiate code-generation modes.
201type CodegenMode int
202
203const (
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400204 // Bp2Build - generate BUILD files with targets buildable by Bazel directly.
Jingwen Chen33832f92021-01-24 22:55:54 -0500205 //
206 // This mode is used for the Soong->Bazel build definition conversion.
207 Bp2Build CodegenMode = iota
208
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400209 // QueryView - generate BUILD files with targets representing fully mutated
Jingwen Chen33832f92021-01-24 22:55:54 -0500210 // Soong modules, representing the fully configured Soong module graph with
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400211 // variants and dependency edges.
Jingwen Chen33832f92021-01-24 22:55:54 -0500212 //
213 // This mode is used for discovering and introspecting the existing Soong
214 // module graph.
215 QueryView
216)
217
Liz Kammer6eff3232021-08-26 08:37:59 -0400218type unconvertedDepsMode int
219
220const (
221 // Include a warning in conversion metrics about converted modules with unconverted direct deps
222 warnUnconvertedDeps unconvertedDepsMode = iota
223 // Error and fail conversion if encountering a module with unconverted direct deps
224 // Enabled by setting environment variable `BP2BUILD_ERROR_UNCONVERTED`
225 errorModulesUnconvertedDeps
226)
227
Jingwen Chendcc329a2021-01-26 02:49:03 -0500228func (mode CodegenMode) String() string {
229 switch mode {
230 case Bp2Build:
231 return "Bp2Build"
232 case QueryView:
233 return "QueryView"
234 default:
235 return fmt.Sprintf("%d", mode)
236 }
237}
238
Liz Kammerba3ea162021-02-17 13:22:03 -0500239// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
240// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
241// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
242// call AdditionalNinjaDeps and add them manually to the ninja file.
243func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
244 ctx.additionalDeps = append(ctx.additionalDeps, deps...)
245}
246
247// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
248func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
249 return ctx.additionalDeps
250}
251
Paul Duffinc6390592022-11-04 13:35:21 +0000252func (ctx *CodegenContext) Config() android.Config { return ctx.config }
253func (ctx *CodegenContext) Context() *android.Context { return ctx.context }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500254
255// NewCodegenContext creates a wrapper context that conforms to PathContext for
256// writing BUILD files in the output directory.
Cole Faustb85d1a12022-11-08 18:14:01 -0800257func NewCodegenContext(config android.Config, context *android.Context, mode CodegenMode, topDir string) *CodegenContext {
Liz Kammer6eff3232021-08-26 08:37:59 -0400258 var unconvertedDeps unconvertedDepsMode
259 if config.IsEnvTrue("BP2BUILD_ERROR_UNCONVERTED") {
260 unconvertedDeps = errorModulesUnconvertedDeps
261 }
Liz Kammerba3ea162021-02-17 13:22:03 -0500262 return &CodegenContext{
Liz Kammer6eff3232021-08-26 08:37:59 -0400263 context: context,
264 config: config,
265 mode: mode,
266 unconvertedDepMode: unconvertedDeps,
Cole Faustb85d1a12022-11-08 18:14:01 -0800267 topDir: topDir,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500268 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800269}
270
271// props is an unsorted map. This function ensures that
272// the generated attributes are sorted to ensure determinism.
273func propsToAttributes(props map[string]string) string {
274 var attributes string
Cole Faust18994c72023-02-28 16:02:16 -0800275 for _, propName := range android.SortedKeys(props) {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400276 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800277 }
278 return attributes
279}
280
Liz Kammer6eff3232021-08-26 08:37:59 -0400281type conversionResults struct {
282 buildFileToTargets map[string]BazelTargets
283 metrics CodegenMetrics
Liz Kammer6eff3232021-08-26 08:37:59 -0400284}
285
286func (r conversionResults) BuildDirToTargets() map[string]BazelTargets {
287 return r.buildFileToTargets
288}
289
Spandan Dasea2abba2023-06-14 21:30:38 +0000290// struct to store state of go bazel targets
291// this implements bp2buildModule interface and is passed to generateBazelTargets
292type goBazelTarget struct {
293 targetName string
294 targetPackage string
295 bazelRuleClass string
296 bazelRuleLoadLocation string
297 bazelAttributes []interface{}
298}
299
300var _ bp2buildModule = (*goBazelTarget)(nil)
301
302func (g goBazelTarget) TargetName() string {
303 return g.targetName
304}
305
306func (g goBazelTarget) TargetPackage() string {
307 return g.targetPackage
308}
309
310func (g goBazelTarget) BazelRuleClass() string {
311 return g.bazelRuleClass
312}
313
314func (g goBazelTarget) BazelRuleLoadLocation() string {
315 return g.bazelRuleLoadLocation
316}
317
318func (g goBazelTarget) BazelAttributes() []interface{} {
319 return g.bazelAttributes
320}
321
322// Creates a target_compatible_with entry that is *not* compatible with android
323func targetNotCompatibleWithAndroid() bazel.LabelListAttribute {
324 ret := bazel.LabelListAttribute{}
325 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsAndroid,
326 bazel.MakeLabelList(
327 []bazel.Label{
328 bazel.Label{
329 Label: "@platforms//:incompatible",
330 },
331 },
332 ),
333 )
334 return ret
335}
336
337// helper function to return labels for srcs used in bootstrap_go_package and bootstrap_go_binary
338// this function has the following limitations which make it unsuitable for widespread use
Spandan Das0a8a2752023-06-21 01:50:33 +0000339// - wildcard patterns in srcs
340// This is ok for go since build/blueprint does not support it.
Spandan Dasea2abba2023-06-14 21:30:38 +0000341//
342// Prefer to use `BazelLabelForModuleSrc` instead
Spandan Das0a8a2752023-06-21 01:50:33 +0000343func goSrcLabels(cfg android.Config, moduleDir string, srcs []string, linuxSrcs, darwinSrcs []string) bazel.LabelListAttribute {
Spandan Dasea2abba2023-06-14 21:30:38 +0000344 labels := func(srcs []string) bazel.LabelList {
345 ret := []bazel.Label{}
346 for _, src := range srcs {
347 srcLabel := bazel.Label{
Spandan Das0a8a2752023-06-21 01:50:33 +0000348 Label: src,
Spandan Dasea2abba2023-06-14 21:30:38 +0000349 }
350 ret = append(ret, srcLabel)
351 }
Spandan Das0a8a2752023-06-21 01:50:33 +0000352 // Respect package boundaries
353 return android.TransformSubpackagePaths(
354 cfg,
355 moduleDir,
356 bazel.MakeLabelList(ret),
357 )
Spandan Dasea2abba2023-06-14 21:30:38 +0000358 }
359
360 ret := bazel.LabelListAttribute{}
361 // common
362 ret.SetSelectValue(bazel.NoConfigAxis, "", labels(srcs))
363 // linux
364 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsLinux, labels(linuxSrcs))
365 // darwin
366 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsDarwin, labels(darwinSrcs))
367 return ret
368}
369
370func goDepLabels(deps []string, goModulesMap nameToGoLibraryModule) bazel.LabelListAttribute {
371 labels := []bazel.Label{}
372 for _, dep := range deps {
373 moduleDir := goModulesMap[dep].Dir
374 if moduleDir == "." {
375 moduleDir = ""
376 }
377 label := bazel.Label{
378 Label: fmt.Sprintf("//%s:%s", moduleDir, dep),
379 }
380 labels = append(labels, label)
381 }
382 return bazel.MakeLabelListAttribute(bazel.MakeLabelList(labels))
383}
384
385// attributes common to blueprint_go_binary and bootstap_go_package
386type goAttributes struct {
387 Importpath bazel.StringAttribute
388 Srcs bazel.LabelListAttribute
389 Deps bazel.LabelListAttribute
Spandan Das682e7862023-06-22 22:22:11 +0000390 Data bazel.LabelListAttribute
Spandan Dasea2abba2023-06-14 21:30:38 +0000391 Target_compatible_with bazel.LabelListAttribute
Spandan Das682e7862023-06-22 22:22:11 +0000392
393 // attributes for the dynamically generated go_test target
394 Embed bazel.LabelListAttribute
Spandan Dasea2abba2023-06-14 21:30:38 +0000395}
396
Spandan Das682e7862023-06-22 22:22:11 +0000397type goTestProperties struct {
398 name string
399 dir string
400 testSrcs []string
401 linuxTestSrcs []string
402 darwinTestSrcs []string
403 testData []string
404 // Name of the target that should be compiled together with the test
405 embedName string
406}
407
408// Creates a go_test target for bootstrap_go_package / blueprint_go_binary
409func generateBazelTargetsGoTest(ctx *android.Context, goModulesMap nameToGoLibraryModule, gp goTestProperties) (BazelTarget, error) {
410 ca := android.CommonAttributes{
411 Name: gp.name,
412 }
413 ga := goAttributes{
414 Srcs: goSrcLabels(ctx.Config(), gp.dir, gp.testSrcs, gp.linuxTestSrcs, gp.darwinTestSrcs),
415 Data: goSrcLabels(ctx.Config(), gp.dir, gp.testData, []string{}, []string{}),
416 Embed: bazel.MakeLabelListAttribute(
417 bazel.MakeLabelList(
418 []bazel.Label{bazel.Label{Label: ":" + gp.embedName}},
419 ),
420 ),
421 Target_compatible_with: targetNotCompatibleWithAndroid(),
422 }
423
424 libTest := goBazelTarget{
425 targetName: gp.name,
426 targetPackage: gp.dir,
427 bazelRuleClass: "go_test",
428 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
429 bazelAttributes: []interface{}{&ca, &ga},
430 }
431 return generateBazelTarget(ctx, libTest)
432}
433
434// TODO - b/288491147: testSrcs of certain bootstrap_go_package/blueprint_go_binary are not hermetic and depend on
435// testdata checked into the filesystem.
436// Denylist the generation of go_test targets for these Soong modules.
437// The go_library/go_binary will still be generated, since those are hermitic.
438var (
439 goTestsDenylist = []string{
440 "android-archive-zip",
441 "bazel_notice_gen",
442 "blueprint-bootstrap-bpdoc",
443 "blueprint-microfactory",
444 "blueprint-pathtools",
445 "bssl_ar",
446 "compliance_checkmetadata",
447 "compliance_checkshare",
448 "compliance_dumpgraph",
449 "compliance_dumpresolutions",
450 "compliance_listshare",
451 "compliance-module",
452 "compliancenotice_bom",
453 "compliancenotice_shippedlibs",
454 "compliance_rtrace",
455 "compliance_sbom",
456 "golang-protobuf-internal-fuzz-jsonfuzz",
457 "golang-protobuf-internal-fuzz-textfuzz",
458 "golang-protobuf-internal-fuzz-wirefuzz",
459 "htmlnotice",
460 "protoc-gen-go",
461 "rbcrun-module",
462 "spdx-tools-builder",
463 "spdx-tools-builder2v1",
464 "spdx-tools-builder2v2",
465 "spdx-tools-builder2v3",
466 "spdx-tools-idsearcher",
467 "spdx-tools-spdx-json",
468 "spdx-tools-utils",
469 "soong-ui-build",
470 "textnotice",
471 "xmlnotice",
472 }
473)
474
Spandan Das89aa0f72023-06-30 20:18:39 +0000475func testOfGoPackageIsIncompatible(g *bootstrap.GoPackage) bool {
476 return android.InList(g.Name(), goTestsDenylist) ||
477 // Denylist tests of soong_build
478 // Theses tests have a guard that prevent usage outside a test environment
479 // The guard (`ensureTestOnly`) looks for a `-test` in os.Args, which is present in soong's gotestrunner, but missing in `b test`
480 g.IsPluginFor("soong_build") ||
481 // soong-android is a dep of soong_build
482 // This dependency is created by soong_build by listing it in its deps explicitly in Android.bp, and not via `plugin_for` in `soong-android`
483 g.Name() == "soong-android"
484}
485
486func testOfGoBinaryIsIncompatible(g *bootstrap.GoBinary) bool {
487 return android.InList(g.Name(), goTestsDenylist)
488}
489
Spandan Dasea2abba2023-06-14 21:30:38 +0000490func generateBazelTargetsGoPackage(ctx *android.Context, g *bootstrap.GoPackage, goModulesMap nameToGoLibraryModule) ([]BazelTarget, []error) {
491 ca := android.CommonAttributes{
492 Name: g.Name(),
493 }
Spandan Dasde623292023-06-14 21:30:38 +0000494
495 // For this bootstrap_go_package dep chain,
496 // A --> B --> C ( ---> depends on)
497 // Soong provides the convenience of only listing B as deps of A even if a src file of A imports C
498 // Bazel OTOH
499 // 1. requires C to be listed in `deps` expllicity.
500 // 2. does not require C to be listed if src of A does not import C
501 //
502 // bp2build does not have sufficient info on whether C is a direct dep of A or not, so for now collect all transitive deps and add them to deps
503 transitiveDeps := transitiveGoDeps(g.Deps(), goModulesMap)
504
Spandan Dasea2abba2023-06-14 21:30:38 +0000505 ga := goAttributes{
506 Importpath: bazel.StringAttribute{
507 Value: proptools.StringPtr(g.GoPkgPath()),
508 },
Spandan Das0a8a2752023-06-21 01:50:33 +0000509 Srcs: goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs()),
510 Deps: goDepLabels(
511 android.FirstUniqueStrings(transitiveDeps),
512 goModulesMap,
513 ),
Spandan Dasea2abba2023-06-14 21:30:38 +0000514 Target_compatible_with: targetNotCompatibleWithAndroid(),
515 }
516
517 lib := goBazelTarget{
518 targetName: g.Name(),
519 targetPackage: ctx.ModuleDir(g),
520 bazelRuleClass: "go_library",
521 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
522 bazelAttributes: []interface{}{&ca, &ga},
523 }
Spandan Das682e7862023-06-22 22:22:11 +0000524 retTargets := []BazelTarget{}
525 var retErrs []error
526 if libTarget, err := generateBazelTarget(ctx, lib); err == nil {
527 retTargets = append(retTargets, libTarget)
528 } else {
529 retErrs = []error{err}
Spandan Dasea2abba2023-06-14 21:30:38 +0000530 }
Spandan Das682e7862023-06-22 22:22:11 +0000531
532 // If the library contains test srcs, create an additional go_test target
Spandan Das89aa0f72023-06-30 20:18:39 +0000533 if !testOfGoPackageIsIncompatible(g) && (len(g.TestSrcs()) > 0 || len(g.LinuxTestSrcs()) > 0 || len(g.DarwinTestSrcs()) > 0) {
Spandan Das682e7862023-06-22 22:22:11 +0000534 gp := goTestProperties{
535 name: g.Name() + "-test",
536 dir: ctx.ModuleDir(g),
537 testSrcs: g.TestSrcs(),
538 linuxTestSrcs: g.LinuxTestSrcs(),
539 darwinTestSrcs: g.DarwinTestSrcs(),
540 testData: g.TestData(),
541 embedName: g.Name(), // embed the source go_library in the test so that its .go files are included in the compilation unit
542 }
543 if libTestTarget, err := generateBazelTargetsGoTest(ctx, goModulesMap, gp); err == nil {
544 retTargets = append(retTargets, libTestTarget)
545 } else {
546 retErrs = append(retErrs, err)
547 }
548 }
549
550 return retTargets, retErrs
Spandan Dasea2abba2023-06-14 21:30:38 +0000551}
552
553type goLibraryModule struct {
554 Dir string
555 Deps []string
556}
557
558type nameToGoLibraryModule map[string]goLibraryModule
559
560// Visit each module in the graph
561// If a module is of type `bootstrap_go_package`, return a map containing metadata like its dir and deps
562func createGoLibraryModuleMap(ctx *android.Context) nameToGoLibraryModule {
563 ret := nameToGoLibraryModule{}
564 ctx.VisitAllModules(func(m blueprint.Module) {
565 moduleType := ctx.ModuleType(m)
566 // We do not need to store information about blueprint_go_binary since it does not have any rdeps
567 if moduleType == "bootstrap_go_package" {
568 ret[m.Name()] = goLibraryModule{
569 Dir: ctx.ModuleDir(m),
570 Deps: m.(*bootstrap.GoPackage).Deps(),
571 }
572 }
573 })
574 return ret
575}
576
Spandan Dasde623292023-06-14 21:30:38 +0000577// Returns the deps in the transitive closure of a go target
578func transitiveGoDeps(directDeps []string, goModulesMap nameToGoLibraryModule) []string {
579 allDeps := directDeps
580 i := 0
581 for i < len(allDeps) {
582 curr := allDeps[i]
583 allDeps = append(allDeps, goModulesMap[curr].Deps...)
584 i += 1
585 }
586 allDeps = android.SortedUniqueStrings(allDeps)
587 return allDeps
588}
589
590func generateBazelTargetsGoBinary(ctx *android.Context, g *bootstrap.GoBinary, goModulesMap nameToGoLibraryModule) ([]BazelTarget, []error) {
591 ca := android.CommonAttributes{
592 Name: g.Name(),
593 }
594
Spandan Das682e7862023-06-22 22:22:11 +0000595 retTargets := []BazelTarget{}
596 var retErrs []error
597
Spandan Dasde623292023-06-14 21:30:38 +0000598 // For this bootstrap_go_package dep chain,
599 // A --> B --> C ( ---> depends on)
600 // Soong provides the convenience of only listing B as deps of A even if a src file of A imports C
601 // Bazel OTOH
602 // 1. requires C to be listed in `deps` expllicity.
603 // 2. does not require C to be listed if src of A does not import C
604 //
605 // bp2build does not have sufficient info on whether C is a direct dep of A or not, so for now collect all transitive deps and add them to deps
606 transitiveDeps := transitiveGoDeps(g.Deps(), goModulesMap)
607
Spandan Das682e7862023-06-22 22:22:11 +0000608 goSource := ""
609 // If the library contains test srcs, create an additional go_test target
610 // The go_test target will embed a go_source containining the source .go files it tests
Spandan Das89aa0f72023-06-30 20:18:39 +0000611 if !testOfGoBinaryIsIncompatible(g) && (len(g.TestSrcs()) > 0 || len(g.LinuxTestSrcs()) > 0 || len(g.DarwinTestSrcs()) > 0) {
Spandan Das682e7862023-06-22 22:22:11 +0000612 // Create a go_source containing the source .go files of go_library
613 // This target will be an `embed` of the go_binary and go_test
614 goSource = g.Name() + "-source"
615 ca := android.CommonAttributes{
616 Name: goSource,
617 }
618 ga := goAttributes{
619 Srcs: goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs()),
620 Deps: goDepLabels(transitiveDeps, goModulesMap),
621 Target_compatible_with: targetNotCompatibleWithAndroid(),
622 }
623 libTestSource := goBazelTarget{
624 targetName: goSource,
625 targetPackage: ctx.ModuleDir(g),
626 bazelRuleClass: "go_source",
627 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
628 bazelAttributes: []interface{}{&ca, &ga},
629 }
630 if libSourceTarget, err := generateBazelTarget(ctx, libTestSource); err == nil {
631 retTargets = append(retTargets, libSourceTarget)
632 } else {
633 retErrs = append(retErrs, err)
634 }
635
636 // Create a go_test target
637 gp := goTestProperties{
638 name: g.Name() + "-test",
639 dir: ctx.ModuleDir(g),
640 testSrcs: g.TestSrcs(),
641 linuxTestSrcs: g.LinuxTestSrcs(),
642 darwinTestSrcs: g.DarwinTestSrcs(),
643 testData: g.TestData(),
644 // embed the go_source in the test
645 embedName: g.Name() + "-source",
646 }
647 if libTestTarget, err := generateBazelTargetsGoTest(ctx, goModulesMap, gp); err == nil {
648 retTargets = append(retTargets, libTestTarget)
649 } else {
650 retErrs = append(retErrs, err)
651 }
652
653 }
654
655 // Create a go_binary target
Spandan Dasde623292023-06-14 21:30:38 +0000656 ga := goAttributes{
Spandan Dasde623292023-06-14 21:30:38 +0000657 Deps: goDepLabels(transitiveDeps, goModulesMap),
658 Target_compatible_with: targetNotCompatibleWithAndroid(),
659 }
660
Spandan Das682e7862023-06-22 22:22:11 +0000661 // If the binary has testSrcs, embed the common `go_source`
662 if goSource != "" {
663 ga.Embed = bazel.MakeLabelListAttribute(
664 bazel.MakeLabelList(
665 []bazel.Label{bazel.Label{Label: ":" + goSource}},
666 ),
667 )
668 } else {
669 ga.Srcs = goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs())
670 }
671
Spandan Dasde623292023-06-14 21:30:38 +0000672 bin := goBazelTarget{
673 targetName: g.Name(),
674 targetPackage: ctx.ModuleDir(g),
675 bazelRuleClass: "go_binary",
676 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
677 bazelAttributes: []interface{}{&ca, &ga},
678 }
Spandan Das682e7862023-06-22 22:22:11 +0000679
680 if binTarget, err := generateBazelTarget(ctx, bin); err == nil {
681 retTargets = append(retTargets, binTarget)
682 } else {
683 retErrs = []error{err}
Spandan Dasde623292023-06-14 21:30:38 +0000684 }
Spandan Das682e7862023-06-22 22:22:11 +0000685
686 return retTargets, retErrs
Spandan Dasde623292023-06-14 21:30:38 +0000687}
688
Liz Kammer6eff3232021-08-26 08:37:59 -0400689func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (conversionResults, []error) {
ustaaaf2fd12023-07-01 11:40:36 -0400690 ctx.Context().BeginEvent("GenerateBazelTargets")
691 defer ctx.Context().EndEvent("GenerateBazelTargets")
Jingwen Chen40067de2021-01-26 21:58:43 -0500692 buildFileToTargets := make(map[string]BazelTargets)
Jingwen Chen164e0862021-02-19 00:48:40 -0500693
694 // Simple metrics tracking for bp2build
usta4f5d2c12022-10-28 23:32:01 -0400695 metrics := CreateCodegenMetrics()
Jingwen Chen164e0862021-02-19 00:48:40 -0500696
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400697 dirs := make(map[string]bool)
698
Liz Kammer6eff3232021-08-26 08:37:59 -0400699 var errs []error
700
Spandan Dasea2abba2023-06-14 21:30:38 +0000701 // Visit go libraries in a pre-run and store its state in a map
702 // The time complexity remains O(N), and this does not add significant wall time.
703 nameToGoLibMap := createGoLibraryModuleMap(ctx.Context())
704
Jingwen Chen164e0862021-02-19 00:48:40 -0500705 bpCtx := ctx.Context()
706 bpCtx.VisitAllModules(func(m blueprint.Module) {
707 dir := bpCtx.ModuleDir(m)
Chris Parsons492bd912022-01-20 12:55:05 -0500708 moduleType := bpCtx.ModuleType(m)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400709 dirs[dir] = true
710
Liz Kammer2ada09a2021-08-11 00:17:36 -0400711 var targets []BazelTarget
Spandan Dasea2abba2023-06-14 21:30:38 +0000712 var targetErrs []error
Jingwen Chen73850672020-12-14 08:25:34 -0500713
Jingwen Chen164e0862021-02-19 00:48:40 -0500714 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500715 case Bp2Build:
Chris Parsons0c4de1f2023-09-21 20:36:35 +0000716 if aModule, ok := m.(android.Module); ok {
717 reason := aModule.GetUnconvertedReason()
718 if reason != nil {
719 // If this module was force-enabled, cause an error.
720 if _, ok := ctx.Config().BazelModulesForceEnabledByFlag()[m.Name()]; ok && m.Name() != "" {
721 err := fmt.Errorf("Force Enabled Module %s not converted", m.Name())
722 errs = append(errs, err)
723 }
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000724
Chris Parsons0c4de1f2023-09-21 20:36:35 +0000725 // Log the module isn't to be converted by bp2build.
726 // TODO: b/291598248 - Log handcrafted modules differently than other unconverted modules.
727 metrics.AddUnconvertedModule(m, moduleType, dir, *reason)
728 return
729 }
730 if len(aModule.Bp2buildTargets()) == 0 {
731 panic(fmt.Errorf("illegal bp2build invariant: module '%s' was neither converted nor marked unconvertible", aModule.Name()))
732 }
733
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000734 // Handle modules converted to generated targets.
Chris Parsons0c4de1f2023-09-21 20:36:35 +0000735 targets, targetErrs = generateBazelTargets(bpCtx, aModule)
736 errs = append(errs, targetErrs...)
737 for _, t := range targets {
738 // A module can potentially generate more than 1 Bazel
739 // target, each of a different rule class.
740 metrics.IncrementRuleClassCount(t.ruleClass)
741 }
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000742
743 // Log the module.
Chris Parsons39a16972023-06-08 14:28:51 +0000744 metrics.AddConvertedModule(aModule, moduleType, dir)
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000745
746 // Handle modules with unconverted deps. By default, emit a warning.
Liz Kammer6eff3232021-08-26 08:37:59 -0400747 if unconvertedDeps := aModule.GetUnconvertedBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700748 msg := fmt.Sprintf("%s %s:%s depends on unconverted modules: %s",
749 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400750 switch ctx.unconvertedDepMode {
751 case warnUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400752 metrics.moduleWithUnconvertedDepsMsgs = append(metrics.moduleWithUnconvertedDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400753 case errorModulesUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400754 errs = append(errs, fmt.Errorf(msg))
755 return
756 }
757 }
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500758 if unconvertedDeps := aModule.GetMissingBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700759 msg := fmt.Sprintf("%s %s:%s depends on missing modules: %s",
760 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400761 switch ctx.unconvertedDepMode {
762 case warnUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500763 metrics.moduleWithMissingDepsMsgs = append(metrics.moduleWithMissingDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400764 case errorModulesUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500765 errs = append(errs, fmt.Errorf(msg))
766 return
767 }
768 }
Spandan Dasea2abba2023-06-14 21:30:38 +0000769 } else if glib, ok := m.(*bootstrap.GoPackage); ok {
770 targets, targetErrs = generateBazelTargetsGoPackage(bpCtx, glib, nameToGoLibMap)
771 errs = append(errs, targetErrs...)
772 metrics.IncrementRuleClassCount("go_library")
Spandan Das41f1eee2023-08-01 22:28:16 +0000773 metrics.AddConvertedModule(glib, "go_library", dir)
Spandan Das2a55cea2023-06-14 17:56:10 +0000774 } else if gbin, ok := m.(*bootstrap.GoBinary); ok {
Spandan Dasde623292023-06-14 21:30:38 +0000775 targets, targetErrs = generateBazelTargetsGoBinary(bpCtx, gbin, nameToGoLibMap)
776 errs = append(errs, targetErrs...)
777 metrics.IncrementRuleClassCount("go_binary")
Spandan Das41f1eee2023-08-01 22:28:16 +0000778 metrics.AddConvertedModule(gbin, "go_binary", dir)
Liz Kammerfc46bc12021-02-19 11:06:17 -0500779 } else {
Chris Parsons39a16972023-06-08 14:28:51 +0000780 metrics.AddUnconvertedModule(m, moduleType, dir, android.UnconvertedReason{
781 ReasonType: int(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED),
782 })
Liz Kammerba3ea162021-02-17 13:22:03 -0500783 return
Jingwen Chen73850672020-12-14 08:25:34 -0500784 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500785 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500786 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500787 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500788 // package module name contain slashes, and thus cannot
789 // be mapped cleanly to a bazel label.
790 return
791 }
Alix94e26032022-08-16 20:37:33 +0000792 t, err := generateSoongModuleTarget(bpCtx, m)
793 if err != nil {
794 errs = append(errs, err)
795 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400796 targets = append(targets, t)
Jingwen Chen33832f92021-01-24 22:55:54 -0500797 default:
Liz Kammer6eff3232021-08-26 08:37:59 -0400798 errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
799 return
Jingwen Chen73850672020-12-14 08:25:34 -0500800 }
801
Spandan Dasabedff02023-03-07 19:24:34 +0000802 for _, target := range targets {
803 targetDir := target.PackageName()
804 buildFileToTargets[targetDir] = append(buildFileToTargets[targetDir], target)
805 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800806 })
Liz Kammer6eff3232021-08-26 08:37:59 -0400807
808 if len(errs) > 0 {
809 return conversionResults{}, errs
810 }
811
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400812 if generateFilegroups {
813 // Add a filegroup target that exposes all sources in the subtree of this package
814 // 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 -0700815 //
816 // This works because: https://bazel.build/reference/be/functions#exports_files
817 // "As a legacy behaviour, also files mentioned as input to a rule are exported with the
818 // default visibility until the flag --incompatible_no_implicit_file_export is flipped. However, this behavior
819 // should not be relied upon and actively migrated away from."
820 //
821 // TODO(b/198619163): We should change this to export_files(glob(["**/*"])) instead, but doing that causes these errors:
822 // "Error in exports_files: generated label '//external/avb:avbtool' conflicts with existing py_binary rule"
823 // So we need to solve all the "target ... is both a rule and a file" warnings first.
Usta Shresthac6057152022-09-24 00:23:31 -0400824 for dir := range dirs {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400825 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
826 name: "bp2build_all_srcs",
Jingwen Chen5802d072023-09-20 10:25:09 +0000827 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]), tags = ["manual"])`,
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400828 ruleClass: "filegroup",
829 })
830 }
831 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500832
Liz Kammer6eff3232021-08-26 08:37:59 -0400833 return conversionResults{
834 buildFileToTargets: buildFileToTargets,
835 metrics: metrics,
Liz Kammer6eff3232021-08-26 08:37:59 -0400836 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500837}
838
Alix94e26032022-08-16 20:37:33 +0000839func generateBazelTargets(ctx bpToBuildContext, m android.Module) ([]BazelTarget, []error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400840 var targets []BazelTarget
Alix94e26032022-08-16 20:37:33 +0000841 var errs []error
Liz Kammer2ada09a2021-08-11 00:17:36 -0400842 for _, m := range m.Bp2buildTargets() {
Alix94e26032022-08-16 20:37:33 +0000843 target, err := generateBazelTarget(ctx, m)
844 if err != nil {
845 errs = append(errs, err)
846 return targets, errs
847 }
848 targets = append(targets, target)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400849 }
Alix94e26032022-08-16 20:37:33 +0000850 return targets, errs
Liz Kammer2ada09a2021-08-11 00:17:36 -0400851}
852
853type bp2buildModule interface {
854 TargetName() string
855 TargetPackage() string
856 BazelRuleClass() string
857 BazelRuleLoadLocation() string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000858 BazelAttributes() []interface{}
Liz Kammer2ada09a2021-08-11 00:17:36 -0400859}
860
Alix94e26032022-08-16 20:37:33 +0000861func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) (BazelTarget, error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400862 ruleClass := m.BazelRuleClass()
863 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500864
Jingwen Chen73850672020-12-14 08:25:34 -0500865 // extract the bazel attributes from the module.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000866 attrs := m.BazelAttributes()
Alix94e26032022-08-16 20:37:33 +0000867 props, err := extractModuleProperties(attrs, true)
868 if err != nil {
869 return BazelTarget{}, err
870 }
Jingwen Chen73850672020-12-14 08:25:34 -0500871
Liz Kammer0eae52e2021-10-06 10:32:26 -0400872 // name is handled in a special manner
873 delete(props.Attrs, "name")
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500874
Jingwen Chen73850672020-12-14 08:25:34 -0500875 // Return the Bazel target with rule class and attributes, ready to be
876 // code-generated.
877 attributes := propsToAttributes(props.Attrs)
Sasha Smundakfb589492022-08-04 11:13:27 -0700878 var content string
Liz Kammer2ada09a2021-08-11 00:17:36 -0400879 targetName := m.TargetName()
Sasha Smundakfb589492022-08-04 11:13:27 -0700880 if targetName != "" {
881 content = fmt.Sprintf(ruleTargetTemplate, ruleClass, targetName, attributes)
882 } else {
883 content = fmt.Sprintf(unnamedRuleTargetTemplate, ruleClass, attributes)
884 }
Cole Faustb4cb0c82023-09-14 15:16:58 -0700885 var loads []BazelLoad
886 if bzlLoadLocation != "" {
887 loads = append(loads, BazelLoad{
888 file: bzlLoadLocation,
889 symbols: []BazelLoadSymbol{{symbol: ruleClass}},
890 })
891 }
Jingwen Chen73850672020-12-14 08:25:34 -0500892 return BazelTarget{
Cole Faustb4cb0c82023-09-14 15:16:58 -0700893 name: targetName,
894 packageName: m.TargetPackage(),
895 ruleClass: ruleClass,
896 loads: loads,
897 content: content,
Alix94e26032022-08-16 20:37:33 +0000898 }, nil
Jingwen Chen73850672020-12-14 08:25:34 -0500899}
900
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800901// Convert a module and its deps and props into a Bazel macro/rule
902// representation in the BUILD file.
Alix94e26032022-08-16 20:37:33 +0000903func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) (BazelTarget, error) {
904 props, err := getBuildProperties(ctx, m)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800905
906 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
907 // items, if the modules are added using different DependencyTag. Figure
908 // out the implications of that.
909 depLabels := map[string]bool{}
910 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500911 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800912 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
913 })
914 }
Liz Kammer0eae52e2021-10-06 10:32:26 -0400915
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400916 for p := range ignoredPropNames {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400917 delete(props.Attrs, p)
918 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800919 attributes := propsToAttributes(props.Attrs)
920
921 depLabelList := "[\n"
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400922 for depLabel := range depLabels {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800923 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
924 }
925 depLabelList += " ]"
926
927 targetName := targetNameWithVariant(ctx, m)
928 return BazelTarget{
Spandan Dasabedff02023-03-07 19:24:34 +0000929 name: targetName,
930 packageName: ctx.ModuleDir(m),
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800931 content: fmt.Sprintf(
Sasha Smundakfb589492022-08-04 11:13:27 -0700932 soongModuleTargetTemplate,
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800933 targetName,
934 ctx.ModuleName(m),
935 canonicalizeModuleType(ctx.ModuleType(m)),
936 ctx.ModuleSubDir(m),
937 depLabelList,
938 attributes),
Alix94e26032022-08-16 20:37:33 +0000939 }, err
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800940}
941
Alix94e26032022-08-16 20:37:33 +0000942func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800943 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
944 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
945 if aModule, ok := m.(android.Module); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000946 return extractModuleProperties(aModule.GetProperties(), false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800947 }
948
Alix94e26032022-08-16 20:37:33 +0000949 return BazelAttributes{}, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800950}
951
952// Generically extract module properties and types into a map, keyed by the module property name.
Alix94e26032022-08-16 20:37:33 +0000953func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800954 ret := map[string]string{}
955
956 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400957 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800958 propertiesValue := reflect.ValueOf(properties)
959 // Check that propertiesValue is a pointer to the Properties struct, like
960 // *cc.BaseLinkerProperties or *java.CompilerProperties.
961 //
962 // propertiesValue can also be type-asserted to the structs to
963 // manipulate internal props, if needed.
964 if isStructPtr(propertiesValue.Type()) {
965 structValue := propertiesValue.Elem()
Alix94e26032022-08-16 20:37:33 +0000966 ok, err := extractStructProperties(structValue, 0)
967 if err != nil {
968 return BazelAttributes{}, err
969 }
970 for k, v := range ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000971 if existing, exists := ret[k]; checkForDuplicateProperties && exists {
Alix94e26032022-08-16 20:37:33 +0000972 return BazelAttributes{}, fmt.Errorf(
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000973 "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes",
Alix94e26032022-08-16 20:37:33 +0000974 k, existing)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000975 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800976 ret[k] = v
977 }
978 } else {
Alix94e26032022-08-16 20:37:33 +0000979 return BazelAttributes{},
980 fmt.Errorf(
981 "properties must be a pointer to a struct, got %T",
982 propertiesValue.Interface())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800983 }
984 }
985
Liz Kammer2ada09a2021-08-11 00:17:36 -0400986 return BazelAttributes{
987 Attrs: ret,
Alix94e26032022-08-16 20:37:33 +0000988 }, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800989}
990
991func isStructPtr(t reflect.Type) bool {
992 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
993}
994
995// prettyPrint a property value into the equivalent Starlark representation
996// recursively.
Jingwen Chen58ff6802021-11-17 12:14:41 +0000997func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) {
998 if !emitZeroValues && isZero(propertyValue) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800999 // A property value being set or unset actually matters -- Soong does set default
1000 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
1001 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
1002 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +00001003 // In Bazel-parlance, we would use "attr.<type>(default = <default
1004 // value>)" to set the default value of unset attributes. In the cases
1005 // where the bp2build converter didn't set the default value within the
1006 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -04001007 // value. For those cases, we return an empty string so we don't
1008 // unnecessarily generate empty values.
1009 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001010 }
1011
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001012 switch propertyValue.Kind() {
1013 case reflect.String:
Liz Kammer72beb342022-02-03 08:42:10 -05001014 return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001015 case reflect.Bool:
Liz Kammer72beb342022-02-03 08:42:10 -05001016 return starlark_fmt.PrintBool(propertyValue.Bool()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001017 case reflect.Int, reflect.Uint, reflect.Int64:
Liz Kammer72beb342022-02-03 08:42:10 -05001018 return fmt.Sprintf("%v", propertyValue.Interface()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001019 case reflect.Ptr:
Jingwen Chen58ff6802021-11-17 12:14:41 +00001020 return prettyPrint(propertyValue.Elem(), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001021 case reflect.Slice:
Liz Kammer72beb342022-02-03 08:42:10 -05001022 elements := make([]string, 0, propertyValue.Len())
1023 for i := 0; i < propertyValue.Len(); i++ {
1024 val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001025 if err != nil {
1026 return "", err
1027 }
Liz Kammer72beb342022-02-03 08:42:10 -05001028 if val != "" {
1029 elements = append(elements, val)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001030 }
1031 }
Sam Delmerico932c01c2022-03-25 16:33:26 +00001032 return starlark_fmt.PrintList(elements, indent, func(s string) string {
1033 return "%s"
1034 }), nil
Jingwen Chenb4628eb2021-04-08 14:40:57 +00001035
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001036 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -05001037 // Special cases where the bp2build sends additional information to the codegenerator
1038 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +00001039 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
1040 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -05001041 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
1042 return fmt.Sprintf("%q", label.Label), nil
1043 }
1044
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001045 // Sort and print the struct props by the key.
Alix94e26032022-08-16 20:37:33 +00001046 structProps, err := extractStructProperties(propertyValue, indent)
1047
1048 if err != nil {
1049 return "", err
1050 }
1051
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001052 if len(structProps) == 0 {
1053 return "", nil
1054 }
Liz Kammer72beb342022-02-03 08:42:10 -05001055 return starlark_fmt.PrintDict(structProps, indent), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001056 case reflect.Interface:
1057 // TODO(b/164227191): implement pretty print for interfaces.
1058 // Interfaces are used for for arch, multilib and target properties.
1059 return "", nil
Spandan Das6a448ec2023-04-19 17:36:12 +00001060 case reflect.Map:
1061 if v, ok := propertyValue.Interface().(bazel.StringMapAttribute); ok {
1062 return starlark_fmt.PrintStringStringDict(v, indent), nil
1063 }
1064 return "", fmt.Errorf("bp2build expects map of type map[string]string for field: %s", propertyValue)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001065 default:
1066 return "", fmt.Errorf(
1067 "unexpected kind for property struct field: %s", propertyValue.Kind())
1068 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001069}
1070
1071// Converts a reflected property struct value into a map of property names and property values,
1072// which each property value correctly pretty-printed and indented at the right nest level,
1073// since property structs can be nested. In Starlark, nested structs are represented as nested
1074// dicts: https://docs.bazel.build/skylark/lib/dict.html
Alix94e26032022-08-16 20:37:33 +00001075func extractStructProperties(structValue reflect.Value, indent int) (map[string]string, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001076 if structValue.Kind() != reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001077 return map[string]string{}, fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind())
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001078 }
1079
Alix94e26032022-08-16 20:37:33 +00001080 var err error
1081
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001082 ret := map[string]string{}
1083 structType := structValue.Type()
1084 for i := 0; i < structValue.NumField(); i++ {
1085 field := structType.Field(i)
1086 if shouldSkipStructField(field) {
1087 continue
1088 }
1089
1090 fieldValue := structValue.Field(i)
1091 if isZero(fieldValue) {
1092 // Ignore zero-valued fields
1093 continue
1094 }
Liz Kammer7a210ac2021-09-22 15:52:58 -04001095
Liz Kammer32a03392021-09-14 11:17:21 -04001096 // if the struct is embedded (anonymous), flatten the properties into the containing struct
1097 if field.Anonymous {
1098 if field.Type.Kind() == reflect.Ptr {
1099 fieldValue = fieldValue.Elem()
1100 }
1101 if fieldValue.Type().Kind() == reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001102 propsToMerge, err := extractStructProperties(fieldValue, indent)
1103 if err != nil {
1104 return map[string]string{}, err
1105 }
Liz Kammer32a03392021-09-14 11:17:21 -04001106 for prop, value := range propsToMerge {
1107 ret[prop] = value
1108 }
1109 continue
1110 }
1111 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001112
1113 propertyName := proptools.PropertyNameForField(field.Name)
Alix94e26032022-08-16 20:37:33 +00001114 var prettyPrintedValue string
1115 prettyPrintedValue, err = prettyPrint(fieldValue, indent+1, false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001116 if err != nil {
Alix94e26032022-08-16 20:37:33 +00001117 return map[string]string{}, fmt.Errorf(
1118 "Error while parsing property: %q. %s",
1119 propertyName,
1120 err)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001121 }
1122 if prettyPrintedValue != "" {
1123 ret[propertyName] = prettyPrintedValue
1124 }
1125 }
1126
Alix94e26032022-08-16 20:37:33 +00001127 return ret, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001128}
1129
1130func isZero(value reflect.Value) bool {
1131 switch value.Kind() {
1132 case reflect.Func, reflect.Map, reflect.Slice:
1133 return value.IsNil()
1134 case reflect.Array:
1135 valueIsZero := true
1136 for i := 0; i < value.Len(); i++ {
1137 valueIsZero = valueIsZero && isZero(value.Index(i))
1138 }
1139 return valueIsZero
1140 case reflect.Struct:
1141 valueIsZero := true
1142 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +02001143 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001144 }
1145 return valueIsZero
1146 case reflect.Ptr:
1147 if !value.IsNil() {
1148 return isZero(reflect.Indirect(value))
1149 } else {
1150 return true
1151 }
Liz Kammer46fb7ab2021-12-01 10:09:34 -05001152 // Always print bool/strings, if you want a bool/string attribute to be able to take the default value, use a
1153 // pointer instead
1154 case reflect.Bool, reflect.String:
Liz Kammerd366c902021-06-03 13:43:01 -04001155 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001156 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -04001157 if !value.IsValid() {
1158 return true
1159 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001160 zeroValue := reflect.Zero(value.Type())
1161 result := value.Interface() == zeroValue.Interface()
1162 return result
1163 }
1164}
1165
1166func escapeString(s string) string {
1167 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +00001168
1169 // b/184026959: Reverse the application of some common control sequences.
1170 // These must be generated literally in the BUILD file.
1171 s = strings.ReplaceAll(s, "\t", "\\t")
1172 s = strings.ReplaceAll(s, "\n", "\\n")
1173 s = strings.ReplaceAll(s, "\r", "\\r")
1174
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001175 return strings.ReplaceAll(s, "\"", "\\\"")
1176}
1177
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001178func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
1179 name := ""
1180 if c.ModuleSubDir(logicModule) != "" {
1181 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
1182 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
1183 } else {
1184 name = c.ModuleName(logicModule)
1185 }
1186
1187 return strings.Replace(name, "//", "", 1)
1188}
1189
1190func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
1191 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
1192}