blob: 6f41f3763feb415f71f66e2b16894447974c2ef7 [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"
Liz Kammer2dd9ca42020-11-25 16:06:39 -080032 "github.com/google/blueprint"
Spandan Dasea2abba2023-06-14 21:30:38 +000033 "github.com/google/blueprint/bootstrap"
Liz Kammer2dd9ca42020-11-25 16:06:39 -080034 "github.com/google/blueprint/proptools"
35)
36
37type BazelAttributes struct {
38 Attrs map[string]string
39}
40
41type BazelTarget struct {
Jingwen Chen40067de2021-01-26 21:58:43 -050042 name string
Jingwen Chenc63677b2021-06-17 05:43:19 +000043 packageName string
Jingwen Chen40067de2021-01-26 21:58:43 -050044 content string
45 ruleClass string
46 bzlLoadLocation string
47}
48
49// IsLoadedFromStarlark determines if the BazelTarget's rule class is loaded from a .bzl file,
50// as opposed to a native rule built into Bazel.
51func (t BazelTarget) IsLoadedFromStarlark() bool {
52 return t.bzlLoadLocation != ""
53}
54
Jingwen Chenc63677b2021-06-17 05:43:19 +000055// Label is the fully qualified Bazel label constructed from the BazelTarget's
56// package name and target name.
57func (t BazelTarget) Label() string {
58 if t.packageName == "." {
59 return "//:" + t.name
60 } else {
61 return "//" + t.packageName + ":" + t.name
62 }
63}
64
Spandan Dasabedff02023-03-07 19:24:34 +000065// PackageName returns the package of the Bazel target.
66// Defaults to root of tree.
67func (t BazelTarget) PackageName() string {
68 if t.packageName == "" {
69 return "."
70 }
71 return t.packageName
72}
73
Jingwen Chen40067de2021-01-26 21:58:43 -050074// BazelTargets is a typedef for a slice of BazelTarget objects.
75type BazelTargets []BazelTarget
76
Sasha Smundak8bea2672022-08-04 13:31:14 -070077func (targets BazelTargets) packageRule() *BazelTarget {
78 for _, target := range targets {
79 if target.ruleClass == "package" {
80 return &target
81 }
82 }
83 return nil
84}
85
86// sort a list of BazelTargets in-place, by name, and by generated/handcrafted types.
Jingwen Chen49109762021-05-25 05:16:48 +000087func (targets BazelTargets) sort() {
88 sort.Slice(targets, func(i, j int) bool {
Jingwen Chen49109762021-05-25 05:16:48 +000089 return targets[i].name < targets[j].name
90 })
91}
92
Jingwen Chen40067de2021-01-26 21:58:43 -050093// String returns the string representation of BazelTargets, without load
94// statements (use LoadStatements for that), since the targets are usually not
95// adjacent to the load statements at the top of the BUILD file.
96func (targets BazelTargets) String() string {
97 var res string
98 for i, target := range targets {
Sasha Smundak8bea2672022-08-04 13:31:14 -070099 if target.ruleClass != "package" {
100 res += target.content
101 }
Jingwen Chen40067de2021-01-26 21:58:43 -0500102 if i != len(targets)-1 {
103 res += "\n\n"
104 }
105 }
106 return res
107}
108
109// LoadStatements return the string representation of the sorted and deduplicated
110// Starlark rule load statements needed by a group of BazelTargets.
111func (targets BazelTargets) LoadStatements() string {
112 bzlToLoadedSymbols := map[string][]string{}
113 for _, target := range targets {
114 if target.IsLoadedFromStarlark() {
115 bzlToLoadedSymbols[target.bzlLoadLocation] =
116 append(bzlToLoadedSymbols[target.bzlLoadLocation], target.ruleClass)
117 }
118 }
119
120 var loadStatements []string
121 for bzl, ruleClasses := range bzlToLoadedSymbols {
122 loadStatement := "load(\""
123 loadStatement += bzl
124 loadStatement += "\", "
125 ruleClasses = android.SortedUniqueStrings(ruleClasses)
126 for i, ruleClass := range ruleClasses {
127 loadStatement += "\"" + ruleClass + "\""
128 if i != len(ruleClasses)-1 {
129 loadStatement += ", "
130 }
131 }
132 loadStatement += ")"
133 loadStatements = append(loadStatements, loadStatement)
134 }
135 return strings.Join(android.SortedUniqueStrings(loadStatements), "\n")
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800136}
137
138type bpToBuildContext interface {
139 ModuleName(module blueprint.Module) string
140 ModuleDir(module blueprint.Module) string
141 ModuleSubDir(module blueprint.Module) string
142 ModuleType(module blueprint.Module) string
143
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500144 VisitAllModules(visit func(blueprint.Module))
145 VisitDirectDeps(module blueprint.Module, visit func(blueprint.Module))
146}
147
148type CodegenContext struct {
Jingwen Chen16d90a82021-09-17 07:16:13 +0000149 config android.Config
Paul Duffinc6390592022-11-04 13:35:21 +0000150 context *android.Context
Jingwen Chen16d90a82021-09-17 07:16:13 +0000151 mode CodegenMode
152 additionalDeps []string
Liz Kammer6eff3232021-08-26 08:37:59 -0400153 unconvertedDepMode unconvertedDepsMode
Cole Faustb85d1a12022-11-08 18:14:01 -0800154 topDir string
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500155}
156
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400157func (ctx *CodegenContext) Mode() CodegenMode {
158 return ctx.mode
Jingwen Chen164e0862021-02-19 00:48:40 -0500159}
160
Jingwen Chen33832f92021-01-24 22:55:54 -0500161// CodegenMode is an enum to differentiate code-generation modes.
162type CodegenMode int
163
164const (
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400165 // Bp2Build - generate BUILD files with targets buildable by Bazel directly.
Jingwen Chen33832f92021-01-24 22:55:54 -0500166 //
167 // This mode is used for the Soong->Bazel build definition conversion.
168 Bp2Build CodegenMode = iota
169
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400170 // QueryView - generate BUILD files with targets representing fully mutated
Jingwen Chen33832f92021-01-24 22:55:54 -0500171 // Soong modules, representing the fully configured Soong module graph with
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400172 // variants and dependency edges.
Jingwen Chen33832f92021-01-24 22:55:54 -0500173 //
174 // This mode is used for discovering and introspecting the existing Soong
175 // module graph.
176 QueryView
Spandan Das5af0bd32022-09-28 20:43:08 +0000177
178 // ApiBp2build - generate BUILD files for API contribution targets
179 ApiBp2build
Jingwen Chen33832f92021-01-24 22:55:54 -0500180)
181
Liz Kammer6eff3232021-08-26 08:37:59 -0400182type unconvertedDepsMode int
183
184const (
185 // Include a warning in conversion metrics about converted modules with unconverted direct deps
186 warnUnconvertedDeps unconvertedDepsMode = iota
187 // Error and fail conversion if encountering a module with unconverted direct deps
188 // Enabled by setting environment variable `BP2BUILD_ERROR_UNCONVERTED`
189 errorModulesUnconvertedDeps
190)
191
Jingwen Chendcc329a2021-01-26 02:49:03 -0500192func (mode CodegenMode) String() string {
193 switch mode {
194 case Bp2Build:
195 return "Bp2Build"
196 case QueryView:
197 return "QueryView"
Spandan Das5af0bd32022-09-28 20:43:08 +0000198 case ApiBp2build:
199 return "ApiBp2build"
Jingwen Chendcc329a2021-01-26 02:49:03 -0500200 default:
201 return fmt.Sprintf("%d", mode)
202 }
203}
204
Liz Kammerba3ea162021-02-17 13:22:03 -0500205// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
206// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
207// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
208// call AdditionalNinjaDeps and add them manually to the ninja file.
209func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
210 ctx.additionalDeps = append(ctx.additionalDeps, deps...)
211}
212
213// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
214func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
215 return ctx.additionalDeps
216}
217
Paul Duffinc6390592022-11-04 13:35:21 +0000218func (ctx *CodegenContext) Config() android.Config { return ctx.config }
219func (ctx *CodegenContext) Context() *android.Context { return ctx.context }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500220
221// NewCodegenContext creates a wrapper context that conforms to PathContext for
222// writing BUILD files in the output directory.
Cole Faustb85d1a12022-11-08 18:14:01 -0800223func NewCodegenContext(config android.Config, context *android.Context, mode CodegenMode, topDir string) *CodegenContext {
Liz Kammer6eff3232021-08-26 08:37:59 -0400224 var unconvertedDeps unconvertedDepsMode
225 if config.IsEnvTrue("BP2BUILD_ERROR_UNCONVERTED") {
226 unconvertedDeps = errorModulesUnconvertedDeps
227 }
Liz Kammerba3ea162021-02-17 13:22:03 -0500228 return &CodegenContext{
Liz Kammer6eff3232021-08-26 08:37:59 -0400229 context: context,
230 config: config,
231 mode: mode,
232 unconvertedDepMode: unconvertedDeps,
Cole Faustb85d1a12022-11-08 18:14:01 -0800233 topDir: topDir,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500234 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800235}
236
237// props is an unsorted map. This function ensures that
238// the generated attributes are sorted to ensure determinism.
239func propsToAttributes(props map[string]string) string {
240 var attributes string
Cole Faust18994c72023-02-28 16:02:16 -0800241 for _, propName := range android.SortedKeys(props) {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400242 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800243 }
244 return attributes
245}
246
Liz Kammer6eff3232021-08-26 08:37:59 -0400247type conversionResults struct {
248 buildFileToTargets map[string]BazelTargets
249 metrics CodegenMetrics
Liz Kammer6eff3232021-08-26 08:37:59 -0400250}
251
252func (r conversionResults) BuildDirToTargets() map[string]BazelTargets {
253 return r.buildFileToTargets
254}
255
Spandan Dasea2abba2023-06-14 21:30:38 +0000256// struct to store state of go bazel targets
257// this implements bp2buildModule interface and is passed to generateBazelTargets
258type goBazelTarget struct {
259 targetName string
260 targetPackage string
261 bazelRuleClass string
262 bazelRuleLoadLocation string
263 bazelAttributes []interface{}
264}
265
266var _ bp2buildModule = (*goBazelTarget)(nil)
267
268func (g goBazelTarget) TargetName() string {
269 return g.targetName
270}
271
272func (g goBazelTarget) TargetPackage() string {
273 return g.targetPackage
274}
275
276func (g goBazelTarget) BazelRuleClass() string {
277 return g.bazelRuleClass
278}
279
280func (g goBazelTarget) BazelRuleLoadLocation() string {
281 return g.bazelRuleLoadLocation
282}
283
284func (g goBazelTarget) BazelAttributes() []interface{} {
285 return g.bazelAttributes
286}
287
288// Creates a target_compatible_with entry that is *not* compatible with android
289func targetNotCompatibleWithAndroid() bazel.LabelListAttribute {
290 ret := bazel.LabelListAttribute{}
291 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsAndroid,
292 bazel.MakeLabelList(
293 []bazel.Label{
294 bazel.Label{
295 Label: "@platforms//:incompatible",
296 },
297 },
298 ),
299 )
300 return ret
301}
302
303// helper function to return labels for srcs used in bootstrap_go_package and bootstrap_go_binary
304// this function has the following limitations which make it unsuitable for widespread use
Spandan Das0a8a2752023-06-21 01:50:33 +0000305// - wildcard patterns in srcs
306// This is ok for go since build/blueprint does not support it.
Spandan Dasea2abba2023-06-14 21:30:38 +0000307//
308// Prefer to use `BazelLabelForModuleSrc` instead
Spandan Das0a8a2752023-06-21 01:50:33 +0000309func goSrcLabels(cfg android.Config, moduleDir string, srcs []string, linuxSrcs, darwinSrcs []string) bazel.LabelListAttribute {
Spandan Dasea2abba2023-06-14 21:30:38 +0000310 labels := func(srcs []string) bazel.LabelList {
311 ret := []bazel.Label{}
312 for _, src := range srcs {
313 srcLabel := bazel.Label{
Spandan Das0a8a2752023-06-21 01:50:33 +0000314 Label: src,
Spandan Dasea2abba2023-06-14 21:30:38 +0000315 }
316 ret = append(ret, srcLabel)
317 }
Spandan Das0a8a2752023-06-21 01:50:33 +0000318 // Respect package boundaries
319 return android.TransformSubpackagePaths(
320 cfg,
321 moduleDir,
322 bazel.MakeLabelList(ret),
323 )
Spandan Dasea2abba2023-06-14 21:30:38 +0000324 }
325
326 ret := bazel.LabelListAttribute{}
327 // common
328 ret.SetSelectValue(bazel.NoConfigAxis, "", labels(srcs))
329 // linux
330 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsLinux, labels(linuxSrcs))
331 // darwin
332 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsDarwin, labels(darwinSrcs))
333 return ret
334}
335
336func goDepLabels(deps []string, goModulesMap nameToGoLibraryModule) bazel.LabelListAttribute {
337 labels := []bazel.Label{}
338 for _, dep := range deps {
339 moduleDir := goModulesMap[dep].Dir
340 if moduleDir == "." {
341 moduleDir = ""
342 }
343 label := bazel.Label{
344 Label: fmt.Sprintf("//%s:%s", moduleDir, dep),
345 }
346 labels = append(labels, label)
347 }
348 return bazel.MakeLabelListAttribute(bazel.MakeLabelList(labels))
349}
350
351// attributes common to blueprint_go_binary and bootstap_go_package
352type goAttributes struct {
353 Importpath bazel.StringAttribute
354 Srcs bazel.LabelListAttribute
355 Deps bazel.LabelListAttribute
Spandan Das682e7862023-06-22 22:22:11 +0000356 Data bazel.LabelListAttribute
Spandan Dasea2abba2023-06-14 21:30:38 +0000357 Target_compatible_with bazel.LabelListAttribute
Spandan Das682e7862023-06-22 22:22:11 +0000358
359 // attributes for the dynamically generated go_test target
360 Embed bazel.LabelListAttribute
Spandan Dasea2abba2023-06-14 21:30:38 +0000361}
362
Spandan Das682e7862023-06-22 22:22:11 +0000363type goTestProperties struct {
364 name string
365 dir string
366 testSrcs []string
367 linuxTestSrcs []string
368 darwinTestSrcs []string
369 testData []string
370 // Name of the target that should be compiled together with the test
371 embedName string
372}
373
374// Creates a go_test target for bootstrap_go_package / blueprint_go_binary
375func generateBazelTargetsGoTest(ctx *android.Context, goModulesMap nameToGoLibraryModule, gp goTestProperties) (BazelTarget, error) {
376 ca := android.CommonAttributes{
377 Name: gp.name,
378 }
379 ga := goAttributes{
380 Srcs: goSrcLabels(ctx.Config(), gp.dir, gp.testSrcs, gp.linuxTestSrcs, gp.darwinTestSrcs),
381 Data: goSrcLabels(ctx.Config(), gp.dir, gp.testData, []string{}, []string{}),
382 Embed: bazel.MakeLabelListAttribute(
383 bazel.MakeLabelList(
384 []bazel.Label{bazel.Label{Label: ":" + gp.embedName}},
385 ),
386 ),
387 Target_compatible_with: targetNotCompatibleWithAndroid(),
388 }
389
390 libTest := goBazelTarget{
391 targetName: gp.name,
392 targetPackage: gp.dir,
393 bazelRuleClass: "go_test",
394 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
395 bazelAttributes: []interface{}{&ca, &ga},
396 }
397 return generateBazelTarget(ctx, libTest)
398}
399
400// TODO - b/288491147: testSrcs of certain bootstrap_go_package/blueprint_go_binary are not hermetic and depend on
401// testdata checked into the filesystem.
402// Denylist the generation of go_test targets for these Soong modules.
403// The go_library/go_binary will still be generated, since those are hermitic.
404var (
405 goTestsDenylist = []string{
406 "android-archive-zip",
407 "bazel_notice_gen",
408 "blueprint-bootstrap-bpdoc",
409 "blueprint-microfactory",
410 "blueprint-pathtools",
411 "bssl_ar",
412 "compliance_checkmetadata",
413 "compliance_checkshare",
414 "compliance_dumpgraph",
415 "compliance_dumpresolutions",
416 "compliance_listshare",
417 "compliance-module",
418 "compliancenotice_bom",
419 "compliancenotice_shippedlibs",
420 "compliance_rtrace",
421 "compliance_sbom",
422 "golang-protobuf-internal-fuzz-jsonfuzz",
423 "golang-protobuf-internal-fuzz-textfuzz",
424 "golang-protobuf-internal-fuzz-wirefuzz",
425 "htmlnotice",
426 "protoc-gen-go",
427 "rbcrun-module",
428 "spdx-tools-builder",
429 "spdx-tools-builder2v1",
430 "spdx-tools-builder2v2",
431 "spdx-tools-builder2v3",
432 "spdx-tools-idsearcher",
433 "spdx-tools-spdx-json",
434 "spdx-tools-utils",
435 "soong-ui-build",
436 "textnotice",
437 "xmlnotice",
438 }
439)
440
Spandan Das89aa0f72023-06-30 20:18:39 +0000441func testOfGoPackageIsIncompatible(g *bootstrap.GoPackage) bool {
442 return android.InList(g.Name(), goTestsDenylist) ||
443 // Denylist tests of soong_build
444 // Theses tests have a guard that prevent usage outside a test environment
445 // The guard (`ensureTestOnly`) looks for a `-test` in os.Args, which is present in soong's gotestrunner, but missing in `b test`
446 g.IsPluginFor("soong_build") ||
447 // soong-android is a dep of soong_build
448 // 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`
449 g.Name() == "soong-android"
450}
451
452func testOfGoBinaryIsIncompatible(g *bootstrap.GoBinary) bool {
453 return android.InList(g.Name(), goTestsDenylist)
454}
455
Spandan Dasea2abba2023-06-14 21:30:38 +0000456func generateBazelTargetsGoPackage(ctx *android.Context, g *bootstrap.GoPackage, goModulesMap nameToGoLibraryModule) ([]BazelTarget, []error) {
457 ca := android.CommonAttributes{
458 Name: g.Name(),
459 }
Spandan Dasde623292023-06-14 21:30:38 +0000460
461 // For this bootstrap_go_package dep chain,
462 // A --> B --> C ( ---> depends on)
463 // Soong provides the convenience of only listing B as deps of A even if a src file of A imports C
464 // Bazel OTOH
465 // 1. requires C to be listed in `deps` expllicity.
466 // 2. does not require C to be listed if src of A does not import C
467 //
468 // 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
469 transitiveDeps := transitiveGoDeps(g.Deps(), goModulesMap)
470
Spandan Dasea2abba2023-06-14 21:30:38 +0000471 ga := goAttributes{
472 Importpath: bazel.StringAttribute{
473 Value: proptools.StringPtr(g.GoPkgPath()),
474 },
Spandan Das0a8a2752023-06-21 01:50:33 +0000475 Srcs: goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs()),
476 Deps: goDepLabels(
477 android.FirstUniqueStrings(transitiveDeps),
478 goModulesMap,
479 ),
Spandan Dasea2abba2023-06-14 21:30:38 +0000480 Target_compatible_with: targetNotCompatibleWithAndroid(),
481 }
482
483 lib := goBazelTarget{
484 targetName: g.Name(),
485 targetPackage: ctx.ModuleDir(g),
486 bazelRuleClass: "go_library",
487 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
488 bazelAttributes: []interface{}{&ca, &ga},
489 }
Spandan Das682e7862023-06-22 22:22:11 +0000490 retTargets := []BazelTarget{}
491 var retErrs []error
492 if libTarget, err := generateBazelTarget(ctx, lib); err == nil {
493 retTargets = append(retTargets, libTarget)
494 } else {
495 retErrs = []error{err}
Spandan Dasea2abba2023-06-14 21:30:38 +0000496 }
Spandan Das682e7862023-06-22 22:22:11 +0000497
498 // If the library contains test srcs, create an additional go_test target
Spandan Das89aa0f72023-06-30 20:18:39 +0000499 if !testOfGoPackageIsIncompatible(g) && (len(g.TestSrcs()) > 0 || len(g.LinuxTestSrcs()) > 0 || len(g.DarwinTestSrcs()) > 0) {
Spandan Das682e7862023-06-22 22:22:11 +0000500 gp := goTestProperties{
501 name: g.Name() + "-test",
502 dir: ctx.ModuleDir(g),
503 testSrcs: g.TestSrcs(),
504 linuxTestSrcs: g.LinuxTestSrcs(),
505 darwinTestSrcs: g.DarwinTestSrcs(),
506 testData: g.TestData(),
507 embedName: g.Name(), // embed the source go_library in the test so that its .go files are included in the compilation unit
508 }
509 if libTestTarget, err := generateBazelTargetsGoTest(ctx, goModulesMap, gp); err == nil {
510 retTargets = append(retTargets, libTestTarget)
511 } else {
512 retErrs = append(retErrs, err)
513 }
514 }
515
516 return retTargets, retErrs
Spandan Dasea2abba2023-06-14 21:30:38 +0000517}
518
519type goLibraryModule struct {
520 Dir string
521 Deps []string
522}
523
524type nameToGoLibraryModule map[string]goLibraryModule
525
526// Visit each module in the graph
527// If a module is of type `bootstrap_go_package`, return a map containing metadata like its dir and deps
528func createGoLibraryModuleMap(ctx *android.Context) nameToGoLibraryModule {
529 ret := nameToGoLibraryModule{}
530 ctx.VisitAllModules(func(m blueprint.Module) {
531 moduleType := ctx.ModuleType(m)
532 // We do not need to store information about blueprint_go_binary since it does not have any rdeps
533 if moduleType == "bootstrap_go_package" {
534 ret[m.Name()] = goLibraryModule{
535 Dir: ctx.ModuleDir(m),
536 Deps: m.(*bootstrap.GoPackage).Deps(),
537 }
538 }
539 })
540 return ret
541}
542
Spandan Dasde623292023-06-14 21:30:38 +0000543// Returns the deps in the transitive closure of a go target
544func transitiveGoDeps(directDeps []string, goModulesMap nameToGoLibraryModule) []string {
545 allDeps := directDeps
546 i := 0
547 for i < len(allDeps) {
548 curr := allDeps[i]
549 allDeps = append(allDeps, goModulesMap[curr].Deps...)
550 i += 1
551 }
552 allDeps = android.SortedUniqueStrings(allDeps)
553 return allDeps
554}
555
556func generateBazelTargetsGoBinary(ctx *android.Context, g *bootstrap.GoBinary, goModulesMap nameToGoLibraryModule) ([]BazelTarget, []error) {
557 ca := android.CommonAttributes{
558 Name: g.Name(),
559 }
560
Spandan Das682e7862023-06-22 22:22:11 +0000561 retTargets := []BazelTarget{}
562 var retErrs []error
563
Spandan Dasde623292023-06-14 21:30:38 +0000564 // For this bootstrap_go_package dep chain,
565 // A --> B --> C ( ---> depends on)
566 // Soong provides the convenience of only listing B as deps of A even if a src file of A imports C
567 // Bazel OTOH
568 // 1. requires C to be listed in `deps` expllicity.
569 // 2. does not require C to be listed if src of A does not import C
570 //
571 // 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
572 transitiveDeps := transitiveGoDeps(g.Deps(), goModulesMap)
573
Spandan Das682e7862023-06-22 22:22:11 +0000574 goSource := ""
575 // If the library contains test srcs, create an additional go_test target
576 // The go_test target will embed a go_source containining the source .go files it tests
Spandan Das89aa0f72023-06-30 20:18:39 +0000577 if !testOfGoBinaryIsIncompatible(g) && (len(g.TestSrcs()) > 0 || len(g.LinuxTestSrcs()) > 0 || len(g.DarwinTestSrcs()) > 0) {
Spandan Das682e7862023-06-22 22:22:11 +0000578 // Create a go_source containing the source .go files of go_library
579 // This target will be an `embed` of the go_binary and go_test
580 goSource = g.Name() + "-source"
581 ca := android.CommonAttributes{
582 Name: goSource,
583 }
584 ga := goAttributes{
585 Srcs: goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs()),
586 Deps: goDepLabels(transitiveDeps, goModulesMap),
587 Target_compatible_with: targetNotCompatibleWithAndroid(),
588 }
589 libTestSource := goBazelTarget{
590 targetName: goSource,
591 targetPackage: ctx.ModuleDir(g),
592 bazelRuleClass: "go_source",
593 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
594 bazelAttributes: []interface{}{&ca, &ga},
595 }
596 if libSourceTarget, err := generateBazelTarget(ctx, libTestSource); err == nil {
597 retTargets = append(retTargets, libSourceTarget)
598 } else {
599 retErrs = append(retErrs, err)
600 }
601
602 // Create a go_test target
603 gp := goTestProperties{
604 name: g.Name() + "-test",
605 dir: ctx.ModuleDir(g),
606 testSrcs: g.TestSrcs(),
607 linuxTestSrcs: g.LinuxTestSrcs(),
608 darwinTestSrcs: g.DarwinTestSrcs(),
609 testData: g.TestData(),
610 // embed the go_source in the test
611 embedName: g.Name() + "-source",
612 }
613 if libTestTarget, err := generateBazelTargetsGoTest(ctx, goModulesMap, gp); err == nil {
614 retTargets = append(retTargets, libTestTarget)
615 } else {
616 retErrs = append(retErrs, err)
617 }
618
619 }
620
621 // Create a go_binary target
Spandan Dasde623292023-06-14 21:30:38 +0000622 ga := goAttributes{
Spandan Dasde623292023-06-14 21:30:38 +0000623 Deps: goDepLabels(transitiveDeps, goModulesMap),
624 Target_compatible_with: targetNotCompatibleWithAndroid(),
625 }
626
Spandan Das682e7862023-06-22 22:22:11 +0000627 // If the binary has testSrcs, embed the common `go_source`
628 if goSource != "" {
629 ga.Embed = bazel.MakeLabelListAttribute(
630 bazel.MakeLabelList(
631 []bazel.Label{bazel.Label{Label: ":" + goSource}},
632 ),
633 )
634 } else {
635 ga.Srcs = goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs())
636 }
637
Spandan Dasde623292023-06-14 21:30:38 +0000638 bin := goBazelTarget{
639 targetName: g.Name(),
640 targetPackage: ctx.ModuleDir(g),
641 bazelRuleClass: "go_binary",
642 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
643 bazelAttributes: []interface{}{&ca, &ga},
644 }
Spandan Das682e7862023-06-22 22:22:11 +0000645
646 if binTarget, err := generateBazelTarget(ctx, bin); err == nil {
647 retTargets = append(retTargets, binTarget)
648 } else {
649 retErrs = []error{err}
Spandan Dasde623292023-06-14 21:30:38 +0000650 }
Spandan Das682e7862023-06-22 22:22:11 +0000651
652 return retTargets, retErrs
Spandan Dasde623292023-06-14 21:30:38 +0000653}
654
Liz Kammer6eff3232021-08-26 08:37:59 -0400655func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (conversionResults, []error) {
ustaaaf2fd12023-07-01 11:40:36 -0400656 ctx.Context().BeginEvent("GenerateBazelTargets")
657 defer ctx.Context().EndEvent("GenerateBazelTargets")
Jingwen Chen40067de2021-01-26 21:58:43 -0500658 buildFileToTargets := make(map[string]BazelTargets)
Jingwen Chen164e0862021-02-19 00:48:40 -0500659
660 // Simple metrics tracking for bp2build
usta4f5d2c12022-10-28 23:32:01 -0400661 metrics := CreateCodegenMetrics()
Jingwen Chen164e0862021-02-19 00:48:40 -0500662
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400663 dirs := make(map[string]bool)
664
Liz Kammer6eff3232021-08-26 08:37:59 -0400665 var errs []error
666
Spandan Dasea2abba2023-06-14 21:30:38 +0000667 // Visit go libraries in a pre-run and store its state in a map
668 // The time complexity remains O(N), and this does not add significant wall time.
669 nameToGoLibMap := createGoLibraryModuleMap(ctx.Context())
670
Jingwen Chen164e0862021-02-19 00:48:40 -0500671 bpCtx := ctx.Context()
672 bpCtx.VisitAllModules(func(m blueprint.Module) {
673 dir := bpCtx.ModuleDir(m)
Chris Parsons492bd912022-01-20 12:55:05 -0500674 moduleType := bpCtx.ModuleType(m)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400675 dirs[dir] = true
676
Liz Kammer2ada09a2021-08-11 00:17:36 -0400677 var targets []BazelTarget
Spandan Dasea2abba2023-06-14 21:30:38 +0000678 var targetErrs []error
Jingwen Chen73850672020-12-14 08:25:34 -0500679
Jingwen Chen164e0862021-02-19 00:48:40 -0500680 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500681 case Bp2Build:
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000682 // There are two main ways of converting a Soong module to Bazel:
683 // 1) Manually handcrafting a Bazel target and associating the module with its label
684 // 2) Automatically generating with bp2build converters
685 //
686 // bp2build converters are used for the majority of modules.
Liz Kammerba3ea162021-02-17 13:22:03 -0500687 if b, ok := m.(android.Bazelable); ok && b.HasHandcraftedLabel() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000688 // Handle modules converted to handcrafted targets.
689 //
690 // Since these modules are associated with some handcrafted
Cole Faustea602c52022-08-31 14:48:26 -0700691 // target in a BUILD file, we don't autoconvert them.
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000692
693 // Log the module.
Chris Parsons39a16972023-06-08 14:28:51 +0000694 metrics.AddUnconvertedModule(m, moduleType, dir,
695 android.UnconvertedReason{
696 ReasonType: int(bp2build_metrics_proto.UnconvertedReasonType_DEFINED_IN_BUILD_FILE),
697 })
Liz Kammer2ada09a2021-08-11 00:17:36 -0400698 } else if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000699 // Handle modules converted to generated targets.
700
701 // Log the module.
Chris Parsons39a16972023-06-08 14:28:51 +0000702 metrics.AddConvertedModule(aModule, moduleType, dir)
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000703
704 // Handle modules with unconverted deps. By default, emit a warning.
Liz Kammer6eff3232021-08-26 08:37:59 -0400705 if unconvertedDeps := aModule.GetUnconvertedBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700706 msg := fmt.Sprintf("%s %s:%s depends on unconverted modules: %s",
707 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400708 switch ctx.unconvertedDepMode {
709 case warnUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400710 metrics.moduleWithUnconvertedDepsMsgs = append(metrics.moduleWithUnconvertedDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400711 case errorModulesUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400712 errs = append(errs, fmt.Errorf(msg))
713 return
714 }
715 }
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500716 if unconvertedDeps := aModule.GetMissingBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700717 msg := fmt.Sprintf("%s %s:%s depends on missing modules: %s",
718 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400719 switch ctx.unconvertedDepMode {
720 case warnUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500721 metrics.moduleWithMissingDepsMsgs = append(metrics.moduleWithMissingDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400722 case errorModulesUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500723 errs = append(errs, fmt.Errorf(msg))
724 return
725 }
726 }
Alix94e26032022-08-16 20:37:33 +0000727 targets, targetErrs = generateBazelTargets(bpCtx, aModule)
728 errs = append(errs, targetErrs...)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400729 for _, t := range targets {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000730 // A module can potentially generate more than 1 Bazel
731 // target, each of a different rule class.
732 metrics.IncrementRuleClassCount(t.ruleClass)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400733 }
MarkDacek9c094ca2023-03-16 19:15:19 +0000734 } else if _, ok := ctx.Config().BazelModulesForceEnabledByFlag()[m.Name()]; ok && m.Name() != "" {
735 err := fmt.Errorf("Force Enabled Module %s not converted", m.Name())
736 errs = append(errs, err)
Chris Parsons39a16972023-06-08 14:28:51 +0000737 } else if aModule, ok := m.(android.Module); ok {
738 reason := aModule.GetUnconvertedReason()
739 if reason == nil {
740 panic(fmt.Errorf("module '%s' was neither converted nor marked unconvertible with bp2build", aModule.Name()))
741 } else {
742 metrics.AddUnconvertedModule(m, moduleType, dir, *reason)
743 }
744 return
Spandan Dasea2abba2023-06-14 21:30:38 +0000745 } else if glib, ok := m.(*bootstrap.GoPackage); ok {
746 targets, targetErrs = generateBazelTargetsGoPackage(bpCtx, glib, nameToGoLibMap)
747 errs = append(errs, targetErrs...)
748 metrics.IncrementRuleClassCount("go_library")
Spandan Das41f1eee2023-08-01 22:28:16 +0000749 metrics.AddConvertedModule(glib, "go_library", dir)
Spandan Das2a55cea2023-06-14 17:56:10 +0000750 } else if gbin, ok := m.(*bootstrap.GoBinary); ok {
Spandan Dasde623292023-06-14 21:30:38 +0000751 targets, targetErrs = generateBazelTargetsGoBinary(bpCtx, gbin, nameToGoLibMap)
752 errs = append(errs, targetErrs...)
753 metrics.IncrementRuleClassCount("go_binary")
Spandan Das41f1eee2023-08-01 22:28:16 +0000754 metrics.AddConvertedModule(gbin, "go_binary", dir)
Liz Kammerfc46bc12021-02-19 11:06:17 -0500755 } else {
Chris Parsons39a16972023-06-08 14:28:51 +0000756 metrics.AddUnconvertedModule(m, moduleType, dir, android.UnconvertedReason{
757 ReasonType: int(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED),
758 })
Liz Kammerba3ea162021-02-17 13:22:03 -0500759 return
Jingwen Chen73850672020-12-14 08:25:34 -0500760 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500761 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500762 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500763 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500764 // package module name contain slashes, and thus cannot
765 // be mapped cleanly to a bazel label.
766 return
767 }
Alix94e26032022-08-16 20:37:33 +0000768 t, err := generateSoongModuleTarget(bpCtx, m)
769 if err != nil {
770 errs = append(errs, err)
771 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400772 targets = append(targets, t)
Spandan Das5af0bd32022-09-28 20:43:08 +0000773 case ApiBp2build:
774 if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
775 targets, errs = generateBazelTargets(bpCtx, aModule)
776 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500777 default:
Liz Kammer6eff3232021-08-26 08:37:59 -0400778 errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
779 return
Jingwen Chen73850672020-12-14 08:25:34 -0500780 }
781
Spandan Dasabedff02023-03-07 19:24:34 +0000782 for _, target := range targets {
783 targetDir := target.PackageName()
784 buildFileToTargets[targetDir] = append(buildFileToTargets[targetDir], target)
785 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800786 })
Liz Kammer6eff3232021-08-26 08:37:59 -0400787
788 if len(errs) > 0 {
789 return conversionResults{}, errs
790 }
791
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400792 if generateFilegroups {
793 // Add a filegroup target that exposes all sources in the subtree of this package
794 // 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 -0700795 //
796 // This works because: https://bazel.build/reference/be/functions#exports_files
797 // "As a legacy behaviour, also files mentioned as input to a rule are exported with the
798 // default visibility until the flag --incompatible_no_implicit_file_export is flipped. However, this behavior
799 // should not be relied upon and actively migrated away from."
800 //
801 // TODO(b/198619163): We should change this to export_files(glob(["**/*"])) instead, but doing that causes these errors:
802 // "Error in exports_files: generated label '//external/avb:avbtool' conflicts with existing py_binary rule"
803 // So we need to solve all the "target ... is both a rule and a file" warnings first.
Usta Shresthac6057152022-09-24 00:23:31 -0400804 for dir := range dirs {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400805 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
806 name: "bp2build_all_srcs",
807 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]))`,
808 ruleClass: "filegroup",
809 })
810 }
811 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500812
Liz Kammer6eff3232021-08-26 08:37:59 -0400813 return conversionResults{
814 buildFileToTargets: buildFileToTargets,
815 metrics: metrics,
Liz Kammer6eff3232021-08-26 08:37:59 -0400816 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500817}
818
Alix94e26032022-08-16 20:37:33 +0000819func generateBazelTargets(ctx bpToBuildContext, m android.Module) ([]BazelTarget, []error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400820 var targets []BazelTarget
Alix94e26032022-08-16 20:37:33 +0000821 var errs []error
Liz Kammer2ada09a2021-08-11 00:17:36 -0400822 for _, m := range m.Bp2buildTargets() {
Alix94e26032022-08-16 20:37:33 +0000823 target, err := generateBazelTarget(ctx, m)
824 if err != nil {
825 errs = append(errs, err)
826 return targets, errs
827 }
828 targets = append(targets, target)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400829 }
Alix94e26032022-08-16 20:37:33 +0000830 return targets, errs
Liz Kammer2ada09a2021-08-11 00:17:36 -0400831}
832
833type bp2buildModule interface {
834 TargetName() string
835 TargetPackage() string
836 BazelRuleClass() string
837 BazelRuleLoadLocation() string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000838 BazelAttributes() []interface{}
Liz Kammer2ada09a2021-08-11 00:17:36 -0400839}
840
Alix94e26032022-08-16 20:37:33 +0000841func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) (BazelTarget, error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400842 ruleClass := m.BazelRuleClass()
843 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500844
Jingwen Chen73850672020-12-14 08:25:34 -0500845 // extract the bazel attributes from the module.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000846 attrs := m.BazelAttributes()
Alix94e26032022-08-16 20:37:33 +0000847 props, err := extractModuleProperties(attrs, true)
848 if err != nil {
849 return BazelTarget{}, err
850 }
Jingwen Chen73850672020-12-14 08:25:34 -0500851
Liz Kammer0eae52e2021-10-06 10:32:26 -0400852 // name is handled in a special manner
853 delete(props.Attrs, "name")
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500854
Jingwen Chen73850672020-12-14 08:25:34 -0500855 // Return the Bazel target with rule class and attributes, ready to be
856 // code-generated.
857 attributes := propsToAttributes(props.Attrs)
Sasha Smundakfb589492022-08-04 11:13:27 -0700858 var content string
Liz Kammer2ada09a2021-08-11 00:17:36 -0400859 targetName := m.TargetName()
Sasha Smundakfb589492022-08-04 11:13:27 -0700860 if targetName != "" {
861 content = fmt.Sprintf(ruleTargetTemplate, ruleClass, targetName, attributes)
862 } else {
863 content = fmt.Sprintf(unnamedRuleTargetTemplate, ruleClass, attributes)
864 }
Jingwen Chen73850672020-12-14 08:25:34 -0500865 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500866 name: targetName,
Liz Kammer2ada09a2021-08-11 00:17:36 -0400867 packageName: m.TargetPackage(),
Jingwen Chen40067de2021-01-26 21:58:43 -0500868 ruleClass: ruleClass,
869 bzlLoadLocation: bzlLoadLocation,
Sasha Smundakfb589492022-08-04 11:13:27 -0700870 content: content,
Alix94e26032022-08-16 20:37:33 +0000871 }, nil
Jingwen Chen73850672020-12-14 08:25:34 -0500872}
873
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800874// Convert a module and its deps and props into a Bazel macro/rule
875// representation in the BUILD file.
Alix94e26032022-08-16 20:37:33 +0000876func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) (BazelTarget, error) {
877 props, err := getBuildProperties(ctx, m)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800878
879 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
880 // items, if the modules are added using different DependencyTag. Figure
881 // out the implications of that.
882 depLabels := map[string]bool{}
883 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500884 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800885 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
886 })
887 }
Liz Kammer0eae52e2021-10-06 10:32:26 -0400888
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400889 for p := range ignoredPropNames {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400890 delete(props.Attrs, p)
891 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800892 attributes := propsToAttributes(props.Attrs)
893
894 depLabelList := "[\n"
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400895 for depLabel := range depLabels {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800896 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
897 }
898 depLabelList += " ]"
899
900 targetName := targetNameWithVariant(ctx, m)
901 return BazelTarget{
Spandan Dasabedff02023-03-07 19:24:34 +0000902 name: targetName,
903 packageName: ctx.ModuleDir(m),
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800904 content: fmt.Sprintf(
Sasha Smundakfb589492022-08-04 11:13:27 -0700905 soongModuleTargetTemplate,
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800906 targetName,
907 ctx.ModuleName(m),
908 canonicalizeModuleType(ctx.ModuleType(m)),
909 ctx.ModuleSubDir(m),
910 depLabelList,
911 attributes),
Alix94e26032022-08-16 20:37:33 +0000912 }, err
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800913}
914
Alix94e26032022-08-16 20:37:33 +0000915func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800916 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
917 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
918 if aModule, ok := m.(android.Module); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000919 return extractModuleProperties(aModule.GetProperties(), false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800920 }
921
Alix94e26032022-08-16 20:37:33 +0000922 return BazelAttributes{}, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800923}
924
925// Generically extract module properties and types into a map, keyed by the module property name.
Alix94e26032022-08-16 20:37:33 +0000926func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800927 ret := map[string]string{}
928
929 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400930 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800931 propertiesValue := reflect.ValueOf(properties)
932 // Check that propertiesValue is a pointer to the Properties struct, like
933 // *cc.BaseLinkerProperties or *java.CompilerProperties.
934 //
935 // propertiesValue can also be type-asserted to the structs to
936 // manipulate internal props, if needed.
937 if isStructPtr(propertiesValue.Type()) {
938 structValue := propertiesValue.Elem()
Alix94e26032022-08-16 20:37:33 +0000939 ok, err := extractStructProperties(structValue, 0)
940 if err != nil {
941 return BazelAttributes{}, err
942 }
943 for k, v := range ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000944 if existing, exists := ret[k]; checkForDuplicateProperties && exists {
Alix94e26032022-08-16 20:37:33 +0000945 return BazelAttributes{}, fmt.Errorf(
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000946 "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes",
Alix94e26032022-08-16 20:37:33 +0000947 k, existing)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000948 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800949 ret[k] = v
950 }
951 } else {
Alix94e26032022-08-16 20:37:33 +0000952 return BazelAttributes{},
953 fmt.Errorf(
954 "properties must be a pointer to a struct, got %T",
955 propertiesValue.Interface())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800956 }
957 }
958
Liz Kammer2ada09a2021-08-11 00:17:36 -0400959 return BazelAttributes{
960 Attrs: ret,
Alix94e26032022-08-16 20:37:33 +0000961 }, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800962}
963
964func isStructPtr(t reflect.Type) bool {
965 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
966}
967
968// prettyPrint a property value into the equivalent Starlark representation
969// recursively.
Jingwen Chen58ff6802021-11-17 12:14:41 +0000970func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) {
971 if !emitZeroValues && isZero(propertyValue) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800972 // A property value being set or unset actually matters -- Soong does set default
973 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
974 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
975 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +0000976 // In Bazel-parlance, we would use "attr.<type>(default = <default
977 // value>)" to set the default value of unset attributes. In the cases
978 // where the bp2build converter didn't set the default value within the
979 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -0400980 // value. For those cases, we return an empty string so we don't
981 // unnecessarily generate empty values.
982 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800983 }
984
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800985 switch propertyValue.Kind() {
986 case reflect.String:
Liz Kammer72beb342022-02-03 08:42:10 -0500987 return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800988 case reflect.Bool:
Liz Kammer72beb342022-02-03 08:42:10 -0500989 return starlark_fmt.PrintBool(propertyValue.Bool()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800990 case reflect.Int, reflect.Uint, reflect.Int64:
Liz Kammer72beb342022-02-03 08:42:10 -0500991 return fmt.Sprintf("%v", propertyValue.Interface()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800992 case reflect.Ptr:
Jingwen Chen58ff6802021-11-17 12:14:41 +0000993 return prettyPrint(propertyValue.Elem(), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800994 case reflect.Slice:
Liz Kammer72beb342022-02-03 08:42:10 -0500995 elements := make([]string, 0, propertyValue.Len())
996 for i := 0; i < propertyValue.Len(); i++ {
997 val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800998 if err != nil {
999 return "", err
1000 }
Liz Kammer72beb342022-02-03 08:42:10 -05001001 if val != "" {
1002 elements = append(elements, val)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001003 }
1004 }
Sam Delmerico932c01c2022-03-25 16:33:26 +00001005 return starlark_fmt.PrintList(elements, indent, func(s string) string {
1006 return "%s"
1007 }), nil
Jingwen Chenb4628eb2021-04-08 14:40:57 +00001008
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001009 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -05001010 // Special cases where the bp2build sends additional information to the codegenerator
1011 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +00001012 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
1013 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -05001014 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
1015 return fmt.Sprintf("%q", label.Label), nil
1016 }
1017
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001018 // Sort and print the struct props by the key.
Alix94e26032022-08-16 20:37:33 +00001019 structProps, err := extractStructProperties(propertyValue, indent)
1020
1021 if err != nil {
1022 return "", err
1023 }
1024
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001025 if len(structProps) == 0 {
1026 return "", nil
1027 }
Liz Kammer72beb342022-02-03 08:42:10 -05001028 return starlark_fmt.PrintDict(structProps, indent), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001029 case reflect.Interface:
1030 // TODO(b/164227191): implement pretty print for interfaces.
1031 // Interfaces are used for for arch, multilib and target properties.
1032 return "", nil
Spandan Das6a448ec2023-04-19 17:36:12 +00001033 case reflect.Map:
1034 if v, ok := propertyValue.Interface().(bazel.StringMapAttribute); ok {
1035 return starlark_fmt.PrintStringStringDict(v, indent), nil
1036 }
1037 return "", fmt.Errorf("bp2build expects map of type map[string]string for field: %s", propertyValue)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001038 default:
1039 return "", fmt.Errorf(
1040 "unexpected kind for property struct field: %s", propertyValue.Kind())
1041 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001042}
1043
1044// Converts a reflected property struct value into a map of property names and property values,
1045// which each property value correctly pretty-printed and indented at the right nest level,
1046// since property structs can be nested. In Starlark, nested structs are represented as nested
1047// dicts: https://docs.bazel.build/skylark/lib/dict.html
Alix94e26032022-08-16 20:37:33 +00001048func extractStructProperties(structValue reflect.Value, indent int) (map[string]string, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001049 if structValue.Kind() != reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001050 return map[string]string{}, fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind())
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001051 }
1052
Alix94e26032022-08-16 20:37:33 +00001053 var err error
1054
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001055 ret := map[string]string{}
1056 structType := structValue.Type()
1057 for i := 0; i < structValue.NumField(); i++ {
1058 field := structType.Field(i)
1059 if shouldSkipStructField(field) {
1060 continue
1061 }
1062
1063 fieldValue := structValue.Field(i)
1064 if isZero(fieldValue) {
1065 // Ignore zero-valued fields
1066 continue
1067 }
Liz Kammer7a210ac2021-09-22 15:52:58 -04001068
Liz Kammer32a03392021-09-14 11:17:21 -04001069 // if the struct is embedded (anonymous), flatten the properties into the containing struct
1070 if field.Anonymous {
1071 if field.Type.Kind() == reflect.Ptr {
1072 fieldValue = fieldValue.Elem()
1073 }
1074 if fieldValue.Type().Kind() == reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001075 propsToMerge, err := extractStructProperties(fieldValue, indent)
1076 if err != nil {
1077 return map[string]string{}, err
1078 }
Liz Kammer32a03392021-09-14 11:17:21 -04001079 for prop, value := range propsToMerge {
1080 ret[prop] = value
1081 }
1082 continue
1083 }
1084 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001085
1086 propertyName := proptools.PropertyNameForField(field.Name)
Alix94e26032022-08-16 20:37:33 +00001087 var prettyPrintedValue string
1088 prettyPrintedValue, err = prettyPrint(fieldValue, indent+1, false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001089 if err != nil {
Alix94e26032022-08-16 20:37:33 +00001090 return map[string]string{}, fmt.Errorf(
1091 "Error while parsing property: %q. %s",
1092 propertyName,
1093 err)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001094 }
1095 if prettyPrintedValue != "" {
1096 ret[propertyName] = prettyPrintedValue
1097 }
1098 }
1099
Alix94e26032022-08-16 20:37:33 +00001100 return ret, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001101}
1102
1103func isZero(value reflect.Value) bool {
1104 switch value.Kind() {
1105 case reflect.Func, reflect.Map, reflect.Slice:
1106 return value.IsNil()
1107 case reflect.Array:
1108 valueIsZero := true
1109 for i := 0; i < value.Len(); i++ {
1110 valueIsZero = valueIsZero && isZero(value.Index(i))
1111 }
1112 return valueIsZero
1113 case reflect.Struct:
1114 valueIsZero := true
1115 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +02001116 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001117 }
1118 return valueIsZero
1119 case reflect.Ptr:
1120 if !value.IsNil() {
1121 return isZero(reflect.Indirect(value))
1122 } else {
1123 return true
1124 }
Liz Kammer46fb7ab2021-12-01 10:09:34 -05001125 // Always print bool/strings, if you want a bool/string attribute to be able to take the default value, use a
1126 // pointer instead
1127 case reflect.Bool, reflect.String:
Liz Kammerd366c902021-06-03 13:43:01 -04001128 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001129 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -04001130 if !value.IsValid() {
1131 return true
1132 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001133 zeroValue := reflect.Zero(value.Type())
1134 result := value.Interface() == zeroValue.Interface()
1135 return result
1136 }
1137}
1138
1139func escapeString(s string) string {
1140 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +00001141
1142 // b/184026959: Reverse the application of some common control sequences.
1143 // These must be generated literally in the BUILD file.
1144 s = strings.ReplaceAll(s, "\t", "\\t")
1145 s = strings.ReplaceAll(s, "\n", "\\n")
1146 s = strings.ReplaceAll(s, "\r", "\\r")
1147
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001148 return strings.ReplaceAll(s, "\"", "\\\"")
1149}
1150
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001151func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
1152 name := ""
1153 if c.ModuleSubDir(logicModule) != "" {
1154 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
1155 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
1156 } else {
1157 name = c.ModuleName(logicModule)
1158 }
1159
1160 return strings.Replace(name, "//", "", 1)
1161}
1162
1163func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
1164 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
1165}