blob: 6ca4bb441957e5d67fbc33d28db8ed11d3a9cd21 [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
42type BazelTarget struct {
Jingwen Chen40067de2021-01-26 21:58:43 -050043 name string
Jingwen Chenc63677b2021-06-17 05:43:19 +000044 packageName string
Jingwen Chen40067de2021-01-26 21:58:43 -050045 content string
46 ruleClass string
47 bzlLoadLocation string
48}
49
50// IsLoadedFromStarlark determines if the BazelTarget's rule class is loaded from a .bzl file,
51// as opposed to a native rule built into Bazel.
52func (t BazelTarget) IsLoadedFromStarlark() bool {
53 return t.bzlLoadLocation != ""
54}
55
Jingwen Chenc63677b2021-06-17 05:43:19 +000056// Label is the fully qualified Bazel label constructed from the BazelTarget's
57// package name and target name.
58func (t BazelTarget) Label() string {
59 if t.packageName == "." {
60 return "//:" + t.name
61 } else {
62 return "//" + t.packageName + ":" + t.name
63 }
64}
65
Spandan Dasabedff02023-03-07 19:24:34 +000066// PackageName returns the package of the Bazel target.
67// Defaults to root of tree.
68func (t BazelTarget) PackageName() string {
69 if t.packageName == "" {
70 return "."
71 }
72 return t.packageName
73}
74
Jingwen Chen40067de2021-01-26 21:58:43 -050075// BazelTargets is a typedef for a slice of BazelTarget objects.
76type BazelTargets []BazelTarget
77
Sasha Smundak8bea2672022-08-04 13:31:14 -070078func (targets BazelTargets) packageRule() *BazelTarget {
79 for _, target := range targets {
80 if target.ruleClass == "package" {
81 return &target
82 }
83 }
84 return nil
85}
86
87// sort a list of BazelTargets in-place, by name, and by generated/handcrafted types.
Jingwen Chen49109762021-05-25 05:16:48 +000088func (targets BazelTargets) sort() {
89 sort.Slice(targets, func(i, j int) bool {
Jingwen Chen49109762021-05-25 05:16:48 +000090 return targets[i].name < targets[j].name
91 })
92}
93
Jingwen Chen40067de2021-01-26 21:58:43 -050094// String returns the string representation of BazelTargets, without load
95// statements (use LoadStatements for that), since the targets are usually not
96// adjacent to the load statements at the top of the BUILD file.
97func (targets BazelTargets) String() string {
ustada2a2112023-08-08 00:29:08 -040098 var res strings.Builder
Jingwen Chen40067de2021-01-26 21:58:43 -050099 for i, target := range targets {
Sasha Smundak8bea2672022-08-04 13:31:14 -0700100 if target.ruleClass != "package" {
ustada2a2112023-08-08 00:29:08 -0400101 res.WriteString(target.content)
Sasha Smundak8bea2672022-08-04 13:31:14 -0700102 }
Jingwen Chen40067de2021-01-26 21:58:43 -0500103 if i != len(targets)-1 {
ustada2a2112023-08-08 00:29:08 -0400104 res.WriteString("\n\n")
Jingwen Chen40067de2021-01-26 21:58:43 -0500105 }
106 }
ustada2a2112023-08-08 00:29:08 -0400107 return res.String()
Jingwen Chen40067de2021-01-26 21:58:43 -0500108}
109
110// LoadStatements return the string representation of the sorted and deduplicated
111// Starlark rule load statements needed by a group of BazelTargets.
112func (targets BazelTargets) LoadStatements() string {
113 bzlToLoadedSymbols := map[string][]string{}
114 for _, target := range targets {
115 if target.IsLoadedFromStarlark() {
116 bzlToLoadedSymbols[target.bzlLoadLocation] =
117 append(bzlToLoadedSymbols[target.bzlLoadLocation], target.ruleClass)
118 }
119 }
120
121 var loadStatements []string
122 for bzl, ruleClasses := range bzlToLoadedSymbols {
123 loadStatement := "load(\""
124 loadStatement += bzl
125 loadStatement += "\", "
126 ruleClasses = android.SortedUniqueStrings(ruleClasses)
127 for i, ruleClass := range ruleClasses {
128 loadStatement += "\"" + ruleClass + "\""
129 if i != len(ruleClasses)-1 {
130 loadStatement += ", "
131 }
132 }
133 loadStatement += ")"
134 loadStatements = append(loadStatements, loadStatement)
135 }
136 return strings.Join(android.SortedUniqueStrings(loadStatements), "\n")
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800137}
138
139type bpToBuildContext interface {
140 ModuleName(module blueprint.Module) string
141 ModuleDir(module blueprint.Module) string
142 ModuleSubDir(module blueprint.Module) string
143 ModuleType(module blueprint.Module) string
144
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500145 VisitAllModules(visit func(blueprint.Module))
146 VisitDirectDeps(module blueprint.Module, visit func(blueprint.Module))
147}
148
149type CodegenContext struct {
Jingwen Chen16d90a82021-09-17 07:16:13 +0000150 config android.Config
Paul Duffinc6390592022-11-04 13:35:21 +0000151 context *android.Context
Jingwen Chen16d90a82021-09-17 07:16:13 +0000152 mode CodegenMode
153 additionalDeps []string
Liz Kammer6eff3232021-08-26 08:37:59 -0400154 unconvertedDepMode unconvertedDepsMode
Cole Faustb85d1a12022-11-08 18:14:01 -0800155 topDir string
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500156}
157
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400158func (ctx *CodegenContext) Mode() CodegenMode {
159 return ctx.mode
Jingwen Chen164e0862021-02-19 00:48:40 -0500160}
161
Jingwen Chen33832f92021-01-24 22:55:54 -0500162// CodegenMode is an enum to differentiate code-generation modes.
163type CodegenMode int
164
165const (
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400166 // Bp2Build - generate BUILD files with targets buildable by Bazel directly.
Jingwen Chen33832f92021-01-24 22:55:54 -0500167 //
168 // This mode is used for the Soong->Bazel build definition conversion.
169 Bp2Build CodegenMode = iota
170
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400171 // QueryView - generate BUILD files with targets representing fully mutated
Jingwen Chen33832f92021-01-24 22:55:54 -0500172 // Soong modules, representing the fully configured Soong module graph with
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400173 // variants and dependency edges.
Jingwen Chen33832f92021-01-24 22:55:54 -0500174 //
175 // This mode is used for discovering and introspecting the existing Soong
176 // module graph.
177 QueryView
Spandan Das5af0bd32022-09-28 20:43:08 +0000178
179 // ApiBp2build - generate BUILD files for API contribution targets
180 ApiBp2build
Jingwen Chen33832f92021-01-24 22:55:54 -0500181)
182
Liz Kammer6eff3232021-08-26 08:37:59 -0400183type unconvertedDepsMode int
184
185const (
186 // Include a warning in conversion metrics about converted modules with unconverted direct deps
187 warnUnconvertedDeps unconvertedDepsMode = iota
188 // Error and fail conversion if encountering a module with unconverted direct deps
189 // Enabled by setting environment variable `BP2BUILD_ERROR_UNCONVERTED`
190 errorModulesUnconvertedDeps
191)
192
Jingwen Chendcc329a2021-01-26 02:49:03 -0500193func (mode CodegenMode) String() string {
194 switch mode {
195 case Bp2Build:
196 return "Bp2Build"
197 case QueryView:
198 return "QueryView"
Spandan Das5af0bd32022-09-28 20:43:08 +0000199 case ApiBp2build:
200 return "ApiBp2build"
Jingwen Chendcc329a2021-01-26 02:49:03 -0500201 default:
202 return fmt.Sprintf("%d", mode)
203 }
204}
205
Liz Kammerba3ea162021-02-17 13:22:03 -0500206// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
207// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
208// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
209// call AdditionalNinjaDeps and add them manually to the ninja file.
210func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
211 ctx.additionalDeps = append(ctx.additionalDeps, deps...)
212}
213
214// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
215func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
216 return ctx.additionalDeps
217}
218
Paul Duffinc6390592022-11-04 13:35:21 +0000219func (ctx *CodegenContext) Config() android.Config { return ctx.config }
220func (ctx *CodegenContext) Context() *android.Context { return ctx.context }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500221
222// NewCodegenContext creates a wrapper context that conforms to PathContext for
223// writing BUILD files in the output directory.
Cole Faustb85d1a12022-11-08 18:14:01 -0800224func NewCodegenContext(config android.Config, context *android.Context, mode CodegenMode, topDir string) *CodegenContext {
Liz Kammer6eff3232021-08-26 08:37:59 -0400225 var unconvertedDeps unconvertedDepsMode
226 if config.IsEnvTrue("BP2BUILD_ERROR_UNCONVERTED") {
227 unconvertedDeps = errorModulesUnconvertedDeps
228 }
Liz Kammerba3ea162021-02-17 13:22:03 -0500229 return &CodegenContext{
Liz Kammer6eff3232021-08-26 08:37:59 -0400230 context: context,
231 config: config,
232 mode: mode,
233 unconvertedDepMode: unconvertedDeps,
Cole Faustb85d1a12022-11-08 18:14:01 -0800234 topDir: topDir,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500235 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800236}
237
238// props is an unsorted map. This function ensures that
239// the generated attributes are sorted to ensure determinism.
240func propsToAttributes(props map[string]string) string {
241 var attributes string
Cole Faust18994c72023-02-28 16:02:16 -0800242 for _, propName := range android.SortedKeys(props) {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400243 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800244 }
245 return attributes
246}
247
Liz Kammer6eff3232021-08-26 08:37:59 -0400248type conversionResults struct {
249 buildFileToTargets map[string]BazelTargets
250 metrics CodegenMetrics
Liz Kammer6eff3232021-08-26 08:37:59 -0400251}
252
253func (r conversionResults) BuildDirToTargets() map[string]BazelTargets {
254 return r.buildFileToTargets
255}
256
Spandan Dasea2abba2023-06-14 21:30:38 +0000257// struct to store state of go bazel targets
258// this implements bp2buildModule interface and is passed to generateBazelTargets
259type goBazelTarget struct {
260 targetName string
261 targetPackage string
262 bazelRuleClass string
263 bazelRuleLoadLocation string
264 bazelAttributes []interface{}
265}
266
267var _ bp2buildModule = (*goBazelTarget)(nil)
268
269func (g goBazelTarget) TargetName() string {
270 return g.targetName
271}
272
273func (g goBazelTarget) TargetPackage() string {
274 return g.targetPackage
275}
276
277func (g goBazelTarget) BazelRuleClass() string {
278 return g.bazelRuleClass
279}
280
281func (g goBazelTarget) BazelRuleLoadLocation() string {
282 return g.bazelRuleLoadLocation
283}
284
285func (g goBazelTarget) BazelAttributes() []interface{} {
286 return g.bazelAttributes
287}
288
289// Creates a target_compatible_with entry that is *not* compatible with android
290func targetNotCompatibleWithAndroid() bazel.LabelListAttribute {
291 ret := bazel.LabelListAttribute{}
292 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsAndroid,
293 bazel.MakeLabelList(
294 []bazel.Label{
295 bazel.Label{
296 Label: "@platforms//:incompatible",
297 },
298 },
299 ),
300 )
301 return ret
302}
303
304// helper function to return labels for srcs used in bootstrap_go_package and bootstrap_go_binary
305// this function has the following limitations which make it unsuitable for widespread use
Spandan Das0a8a2752023-06-21 01:50:33 +0000306// - wildcard patterns in srcs
307// This is ok for go since build/blueprint does not support it.
Spandan Dasea2abba2023-06-14 21:30:38 +0000308//
309// Prefer to use `BazelLabelForModuleSrc` instead
Spandan Das0a8a2752023-06-21 01:50:33 +0000310func goSrcLabels(cfg android.Config, moduleDir string, srcs []string, linuxSrcs, darwinSrcs []string) bazel.LabelListAttribute {
Spandan Dasea2abba2023-06-14 21:30:38 +0000311 labels := func(srcs []string) bazel.LabelList {
312 ret := []bazel.Label{}
313 for _, src := range srcs {
314 srcLabel := bazel.Label{
Spandan Das0a8a2752023-06-21 01:50:33 +0000315 Label: src,
Spandan Dasea2abba2023-06-14 21:30:38 +0000316 }
317 ret = append(ret, srcLabel)
318 }
Spandan Das0a8a2752023-06-21 01:50:33 +0000319 // Respect package boundaries
320 return android.TransformSubpackagePaths(
321 cfg,
322 moduleDir,
323 bazel.MakeLabelList(ret),
324 )
Spandan Dasea2abba2023-06-14 21:30:38 +0000325 }
326
327 ret := bazel.LabelListAttribute{}
328 // common
329 ret.SetSelectValue(bazel.NoConfigAxis, "", labels(srcs))
330 // linux
331 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsLinux, labels(linuxSrcs))
332 // darwin
333 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsDarwin, labels(darwinSrcs))
334 return ret
335}
336
337func goDepLabels(deps []string, goModulesMap nameToGoLibraryModule) bazel.LabelListAttribute {
338 labels := []bazel.Label{}
339 for _, dep := range deps {
340 moduleDir := goModulesMap[dep].Dir
341 if moduleDir == "." {
342 moduleDir = ""
343 }
344 label := bazel.Label{
345 Label: fmt.Sprintf("//%s:%s", moduleDir, dep),
346 }
347 labels = append(labels, label)
348 }
349 return bazel.MakeLabelListAttribute(bazel.MakeLabelList(labels))
350}
351
352// attributes common to blueprint_go_binary and bootstap_go_package
353type goAttributes struct {
354 Importpath bazel.StringAttribute
355 Srcs bazel.LabelListAttribute
356 Deps bazel.LabelListAttribute
Spandan Das682e7862023-06-22 22:22:11 +0000357 Data bazel.LabelListAttribute
Spandan Dasea2abba2023-06-14 21:30:38 +0000358 Target_compatible_with bazel.LabelListAttribute
Spandan Das682e7862023-06-22 22:22:11 +0000359
360 // attributes for the dynamically generated go_test target
361 Embed bazel.LabelListAttribute
Spandan Dasea2abba2023-06-14 21:30:38 +0000362}
363
Spandan Das682e7862023-06-22 22:22:11 +0000364type goTestProperties struct {
365 name string
366 dir string
367 testSrcs []string
368 linuxTestSrcs []string
369 darwinTestSrcs []string
370 testData []string
371 // Name of the target that should be compiled together with the test
372 embedName string
373}
374
375// Creates a go_test target for bootstrap_go_package / blueprint_go_binary
376func generateBazelTargetsGoTest(ctx *android.Context, goModulesMap nameToGoLibraryModule, gp goTestProperties) (BazelTarget, error) {
377 ca := android.CommonAttributes{
378 Name: gp.name,
379 }
380 ga := goAttributes{
381 Srcs: goSrcLabels(ctx.Config(), gp.dir, gp.testSrcs, gp.linuxTestSrcs, gp.darwinTestSrcs),
382 Data: goSrcLabels(ctx.Config(), gp.dir, gp.testData, []string{}, []string{}),
383 Embed: bazel.MakeLabelListAttribute(
384 bazel.MakeLabelList(
385 []bazel.Label{bazel.Label{Label: ":" + gp.embedName}},
386 ),
387 ),
388 Target_compatible_with: targetNotCompatibleWithAndroid(),
389 }
390
391 libTest := goBazelTarget{
392 targetName: gp.name,
393 targetPackage: gp.dir,
394 bazelRuleClass: "go_test",
395 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
396 bazelAttributes: []interface{}{&ca, &ga},
397 }
398 return generateBazelTarget(ctx, libTest)
399}
400
401// TODO - b/288491147: testSrcs of certain bootstrap_go_package/blueprint_go_binary are not hermetic and depend on
402// testdata checked into the filesystem.
403// Denylist the generation of go_test targets for these Soong modules.
404// The go_library/go_binary will still be generated, since those are hermitic.
405var (
406 goTestsDenylist = []string{
407 "android-archive-zip",
408 "bazel_notice_gen",
409 "blueprint-bootstrap-bpdoc",
410 "blueprint-microfactory",
411 "blueprint-pathtools",
412 "bssl_ar",
413 "compliance_checkmetadata",
414 "compliance_checkshare",
415 "compliance_dumpgraph",
416 "compliance_dumpresolutions",
417 "compliance_listshare",
418 "compliance-module",
419 "compliancenotice_bom",
420 "compliancenotice_shippedlibs",
421 "compliance_rtrace",
422 "compliance_sbom",
423 "golang-protobuf-internal-fuzz-jsonfuzz",
424 "golang-protobuf-internal-fuzz-textfuzz",
425 "golang-protobuf-internal-fuzz-wirefuzz",
426 "htmlnotice",
427 "protoc-gen-go",
428 "rbcrun-module",
429 "spdx-tools-builder",
430 "spdx-tools-builder2v1",
431 "spdx-tools-builder2v2",
432 "spdx-tools-builder2v3",
433 "spdx-tools-idsearcher",
434 "spdx-tools-spdx-json",
435 "spdx-tools-utils",
436 "soong-ui-build",
437 "textnotice",
438 "xmlnotice",
439 }
440)
441
Spandan Das89aa0f72023-06-30 20:18:39 +0000442func testOfGoPackageIsIncompatible(g *bootstrap.GoPackage) bool {
443 return android.InList(g.Name(), goTestsDenylist) ||
444 // Denylist tests of soong_build
445 // Theses tests have a guard that prevent usage outside a test environment
446 // The guard (`ensureTestOnly`) looks for a `-test` in os.Args, which is present in soong's gotestrunner, but missing in `b test`
447 g.IsPluginFor("soong_build") ||
448 // soong-android is a dep of soong_build
449 // 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`
450 g.Name() == "soong-android"
451}
452
453func testOfGoBinaryIsIncompatible(g *bootstrap.GoBinary) bool {
454 return android.InList(g.Name(), goTestsDenylist)
455}
456
Spandan Dasea2abba2023-06-14 21:30:38 +0000457func generateBazelTargetsGoPackage(ctx *android.Context, g *bootstrap.GoPackage, goModulesMap nameToGoLibraryModule) ([]BazelTarget, []error) {
458 ca := android.CommonAttributes{
459 Name: g.Name(),
460 }
Spandan Dasde623292023-06-14 21:30:38 +0000461
462 // For this bootstrap_go_package dep chain,
463 // A --> B --> C ( ---> depends on)
464 // Soong provides the convenience of only listing B as deps of A even if a src file of A imports C
465 // Bazel OTOH
466 // 1. requires C to be listed in `deps` expllicity.
467 // 2. does not require C to be listed if src of A does not import C
468 //
469 // 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
470 transitiveDeps := transitiveGoDeps(g.Deps(), goModulesMap)
471
Spandan Dasea2abba2023-06-14 21:30:38 +0000472 ga := goAttributes{
473 Importpath: bazel.StringAttribute{
474 Value: proptools.StringPtr(g.GoPkgPath()),
475 },
Spandan Das0a8a2752023-06-21 01:50:33 +0000476 Srcs: goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs()),
477 Deps: goDepLabels(
478 android.FirstUniqueStrings(transitiveDeps),
479 goModulesMap,
480 ),
Spandan Dasea2abba2023-06-14 21:30:38 +0000481 Target_compatible_with: targetNotCompatibleWithAndroid(),
482 }
483
484 lib := goBazelTarget{
485 targetName: g.Name(),
486 targetPackage: ctx.ModuleDir(g),
487 bazelRuleClass: "go_library",
488 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
489 bazelAttributes: []interface{}{&ca, &ga},
490 }
Spandan Das682e7862023-06-22 22:22:11 +0000491 retTargets := []BazelTarget{}
492 var retErrs []error
493 if libTarget, err := generateBazelTarget(ctx, lib); err == nil {
494 retTargets = append(retTargets, libTarget)
495 } else {
496 retErrs = []error{err}
Spandan Dasea2abba2023-06-14 21:30:38 +0000497 }
Spandan Das682e7862023-06-22 22:22:11 +0000498
499 // If the library contains test srcs, create an additional go_test target
Spandan Das89aa0f72023-06-30 20:18:39 +0000500 if !testOfGoPackageIsIncompatible(g) && (len(g.TestSrcs()) > 0 || len(g.LinuxTestSrcs()) > 0 || len(g.DarwinTestSrcs()) > 0) {
Spandan Das682e7862023-06-22 22:22:11 +0000501 gp := goTestProperties{
502 name: g.Name() + "-test",
503 dir: ctx.ModuleDir(g),
504 testSrcs: g.TestSrcs(),
505 linuxTestSrcs: g.LinuxTestSrcs(),
506 darwinTestSrcs: g.DarwinTestSrcs(),
507 testData: g.TestData(),
508 embedName: g.Name(), // embed the source go_library in the test so that its .go files are included in the compilation unit
509 }
510 if libTestTarget, err := generateBazelTargetsGoTest(ctx, goModulesMap, gp); err == nil {
511 retTargets = append(retTargets, libTestTarget)
512 } else {
513 retErrs = append(retErrs, err)
514 }
515 }
516
517 return retTargets, retErrs
Spandan Dasea2abba2023-06-14 21:30:38 +0000518}
519
520type goLibraryModule struct {
521 Dir string
522 Deps []string
523}
524
525type nameToGoLibraryModule map[string]goLibraryModule
526
527// Visit each module in the graph
528// If a module is of type `bootstrap_go_package`, return a map containing metadata like its dir and deps
529func createGoLibraryModuleMap(ctx *android.Context) nameToGoLibraryModule {
530 ret := nameToGoLibraryModule{}
531 ctx.VisitAllModules(func(m blueprint.Module) {
532 moduleType := ctx.ModuleType(m)
533 // We do not need to store information about blueprint_go_binary since it does not have any rdeps
534 if moduleType == "bootstrap_go_package" {
535 ret[m.Name()] = goLibraryModule{
536 Dir: ctx.ModuleDir(m),
537 Deps: m.(*bootstrap.GoPackage).Deps(),
538 }
539 }
540 })
541 return ret
542}
543
Spandan Dasde623292023-06-14 21:30:38 +0000544// Returns the deps in the transitive closure of a go target
545func transitiveGoDeps(directDeps []string, goModulesMap nameToGoLibraryModule) []string {
546 allDeps := directDeps
547 i := 0
548 for i < len(allDeps) {
549 curr := allDeps[i]
550 allDeps = append(allDeps, goModulesMap[curr].Deps...)
551 i += 1
552 }
553 allDeps = android.SortedUniqueStrings(allDeps)
554 return allDeps
555}
556
557func generateBazelTargetsGoBinary(ctx *android.Context, g *bootstrap.GoBinary, goModulesMap nameToGoLibraryModule) ([]BazelTarget, []error) {
558 ca := android.CommonAttributes{
559 Name: g.Name(),
560 }
561
Spandan Das682e7862023-06-22 22:22:11 +0000562 retTargets := []BazelTarget{}
563 var retErrs []error
564
Spandan Dasde623292023-06-14 21:30:38 +0000565 // For this bootstrap_go_package dep chain,
566 // A --> B --> C ( ---> depends on)
567 // Soong provides the convenience of only listing B as deps of A even if a src file of A imports C
568 // Bazel OTOH
569 // 1. requires C to be listed in `deps` expllicity.
570 // 2. does not require C to be listed if src of A does not import C
571 //
572 // 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
573 transitiveDeps := transitiveGoDeps(g.Deps(), goModulesMap)
574
Spandan Das682e7862023-06-22 22:22:11 +0000575 goSource := ""
576 // If the library contains test srcs, create an additional go_test target
577 // The go_test target will embed a go_source containining the source .go files it tests
Spandan Das89aa0f72023-06-30 20:18:39 +0000578 if !testOfGoBinaryIsIncompatible(g) && (len(g.TestSrcs()) > 0 || len(g.LinuxTestSrcs()) > 0 || len(g.DarwinTestSrcs()) > 0) {
Spandan Das682e7862023-06-22 22:22:11 +0000579 // Create a go_source containing the source .go files of go_library
580 // This target will be an `embed` of the go_binary and go_test
581 goSource = g.Name() + "-source"
582 ca := android.CommonAttributes{
583 Name: goSource,
584 }
585 ga := goAttributes{
586 Srcs: goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs()),
587 Deps: goDepLabels(transitiveDeps, goModulesMap),
588 Target_compatible_with: targetNotCompatibleWithAndroid(),
589 }
590 libTestSource := goBazelTarget{
591 targetName: goSource,
592 targetPackage: ctx.ModuleDir(g),
593 bazelRuleClass: "go_source",
594 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
595 bazelAttributes: []interface{}{&ca, &ga},
596 }
597 if libSourceTarget, err := generateBazelTarget(ctx, libTestSource); err == nil {
598 retTargets = append(retTargets, libSourceTarget)
599 } else {
600 retErrs = append(retErrs, err)
601 }
602
603 // Create a go_test target
604 gp := goTestProperties{
605 name: g.Name() + "-test",
606 dir: ctx.ModuleDir(g),
607 testSrcs: g.TestSrcs(),
608 linuxTestSrcs: g.LinuxTestSrcs(),
609 darwinTestSrcs: g.DarwinTestSrcs(),
610 testData: g.TestData(),
611 // embed the go_source in the test
612 embedName: g.Name() + "-source",
613 }
614 if libTestTarget, err := generateBazelTargetsGoTest(ctx, goModulesMap, gp); err == nil {
615 retTargets = append(retTargets, libTestTarget)
616 } else {
617 retErrs = append(retErrs, err)
618 }
619
620 }
621
622 // Create a go_binary target
Spandan Dasde623292023-06-14 21:30:38 +0000623 ga := goAttributes{
Spandan Dasde623292023-06-14 21:30:38 +0000624 Deps: goDepLabels(transitiveDeps, goModulesMap),
625 Target_compatible_with: targetNotCompatibleWithAndroid(),
626 }
627
Spandan Das682e7862023-06-22 22:22:11 +0000628 // If the binary has testSrcs, embed the common `go_source`
629 if goSource != "" {
630 ga.Embed = bazel.MakeLabelListAttribute(
631 bazel.MakeLabelList(
632 []bazel.Label{bazel.Label{Label: ":" + goSource}},
633 ),
634 )
635 } else {
636 ga.Srcs = goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs())
637 }
638
Spandan Dasde623292023-06-14 21:30:38 +0000639 bin := goBazelTarget{
640 targetName: g.Name(),
641 targetPackage: ctx.ModuleDir(g),
642 bazelRuleClass: "go_binary",
643 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
644 bazelAttributes: []interface{}{&ca, &ga},
645 }
Spandan Das682e7862023-06-22 22:22:11 +0000646
647 if binTarget, err := generateBazelTarget(ctx, bin); err == nil {
648 retTargets = append(retTargets, binTarget)
649 } else {
650 retErrs = []error{err}
Spandan Dasde623292023-06-14 21:30:38 +0000651 }
Spandan Das682e7862023-06-22 22:22:11 +0000652
653 return retTargets, retErrs
Spandan Dasde623292023-06-14 21:30:38 +0000654}
655
Liz Kammer6eff3232021-08-26 08:37:59 -0400656func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (conversionResults, []error) {
ustaaaf2fd12023-07-01 11:40:36 -0400657 ctx.Context().BeginEvent("GenerateBazelTargets")
658 defer ctx.Context().EndEvent("GenerateBazelTargets")
Jingwen Chen40067de2021-01-26 21:58:43 -0500659 buildFileToTargets := make(map[string]BazelTargets)
Jingwen Chen164e0862021-02-19 00:48:40 -0500660
661 // Simple metrics tracking for bp2build
usta4f5d2c12022-10-28 23:32:01 -0400662 metrics := CreateCodegenMetrics()
Jingwen Chen164e0862021-02-19 00:48:40 -0500663
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400664 dirs := make(map[string]bool)
665
Liz Kammer6eff3232021-08-26 08:37:59 -0400666 var errs []error
667
Spandan Dasea2abba2023-06-14 21:30:38 +0000668 // Visit go libraries in a pre-run and store its state in a map
669 // The time complexity remains O(N), and this does not add significant wall time.
670 nameToGoLibMap := createGoLibraryModuleMap(ctx.Context())
671
Jingwen Chen164e0862021-02-19 00:48:40 -0500672 bpCtx := ctx.Context()
673 bpCtx.VisitAllModules(func(m blueprint.Module) {
674 dir := bpCtx.ModuleDir(m)
Chris Parsons492bd912022-01-20 12:55:05 -0500675 moduleType := bpCtx.ModuleType(m)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400676 dirs[dir] = true
677
Liz Kammer2ada09a2021-08-11 00:17:36 -0400678 var targets []BazelTarget
Spandan Dasea2abba2023-06-14 21:30:38 +0000679 var targetErrs []error
Jingwen Chen73850672020-12-14 08:25:34 -0500680
Jingwen Chen164e0862021-02-19 00:48:40 -0500681 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500682 case Bp2Build:
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000683 // There are two main ways of converting a Soong module to Bazel:
684 // 1) Manually handcrafting a Bazel target and associating the module with its label
685 // 2) Automatically generating with bp2build converters
686 //
687 // bp2build converters are used for the majority of modules.
Liz Kammerba3ea162021-02-17 13:22:03 -0500688 if b, ok := m.(android.Bazelable); ok && b.HasHandcraftedLabel() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000689 // Handle modules converted to handcrafted targets.
690 //
691 // Since these modules are associated with some handcrafted
Cole Faustea602c52022-08-31 14:48:26 -0700692 // target in a BUILD file, we don't autoconvert them.
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000693
694 // Log the module.
Chris Parsons39a16972023-06-08 14:28:51 +0000695 metrics.AddUnconvertedModule(m, moduleType, dir,
696 android.UnconvertedReason{
697 ReasonType: int(bp2build_metrics_proto.UnconvertedReasonType_DEFINED_IN_BUILD_FILE),
698 })
Liz Kammer2ada09a2021-08-11 00:17:36 -0400699 } else if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000700 // Handle modules converted to generated targets.
701
702 // Log the module.
Chris Parsons39a16972023-06-08 14:28:51 +0000703 metrics.AddConvertedModule(aModule, moduleType, dir)
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000704
705 // Handle modules with unconverted deps. By default, emit a warning.
Liz Kammer6eff3232021-08-26 08:37:59 -0400706 if unconvertedDeps := aModule.GetUnconvertedBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700707 msg := fmt.Sprintf("%s %s:%s depends on unconverted modules: %s",
708 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400709 switch ctx.unconvertedDepMode {
710 case warnUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400711 metrics.moduleWithUnconvertedDepsMsgs = append(metrics.moduleWithUnconvertedDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400712 case errorModulesUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400713 errs = append(errs, fmt.Errorf(msg))
714 return
715 }
716 }
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500717 if unconvertedDeps := aModule.GetMissingBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700718 msg := fmt.Sprintf("%s %s:%s depends on missing modules: %s",
719 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400720 switch ctx.unconvertedDepMode {
721 case warnUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500722 metrics.moduleWithMissingDepsMsgs = append(metrics.moduleWithMissingDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400723 case errorModulesUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500724 errs = append(errs, fmt.Errorf(msg))
725 return
726 }
727 }
Alix94e26032022-08-16 20:37:33 +0000728 targets, targetErrs = generateBazelTargets(bpCtx, aModule)
729 errs = append(errs, targetErrs...)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400730 for _, t := range targets {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000731 // A module can potentially generate more than 1 Bazel
732 // target, each of a different rule class.
733 metrics.IncrementRuleClassCount(t.ruleClass)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400734 }
MarkDacek9c094ca2023-03-16 19:15:19 +0000735 } else if _, ok := ctx.Config().BazelModulesForceEnabledByFlag()[m.Name()]; ok && m.Name() != "" {
736 err := fmt.Errorf("Force Enabled Module %s not converted", m.Name())
737 errs = append(errs, err)
Chris Parsons39a16972023-06-08 14:28:51 +0000738 } else if aModule, ok := m.(android.Module); ok {
739 reason := aModule.GetUnconvertedReason()
740 if reason == nil {
741 panic(fmt.Errorf("module '%s' was neither converted nor marked unconvertible with bp2build", aModule.Name()))
742 } else {
743 metrics.AddUnconvertedModule(m, moduleType, dir, *reason)
744 }
745 return
Spandan Dasea2abba2023-06-14 21:30:38 +0000746 } else if glib, ok := m.(*bootstrap.GoPackage); ok {
747 targets, targetErrs = generateBazelTargetsGoPackage(bpCtx, glib, nameToGoLibMap)
748 errs = append(errs, targetErrs...)
749 metrics.IncrementRuleClassCount("go_library")
Spandan Das41f1eee2023-08-01 22:28:16 +0000750 metrics.AddConvertedModule(glib, "go_library", dir)
Spandan Das2a55cea2023-06-14 17:56:10 +0000751 } else if gbin, ok := m.(*bootstrap.GoBinary); ok {
Spandan Dasde623292023-06-14 21:30:38 +0000752 targets, targetErrs = generateBazelTargetsGoBinary(bpCtx, gbin, nameToGoLibMap)
753 errs = append(errs, targetErrs...)
754 metrics.IncrementRuleClassCount("go_binary")
Spandan Das41f1eee2023-08-01 22:28:16 +0000755 metrics.AddConvertedModule(gbin, "go_binary", dir)
Liz Kammerfc46bc12021-02-19 11:06:17 -0500756 } else {
Chris Parsons39a16972023-06-08 14:28:51 +0000757 metrics.AddUnconvertedModule(m, moduleType, dir, android.UnconvertedReason{
758 ReasonType: int(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED),
759 })
Liz Kammerba3ea162021-02-17 13:22:03 -0500760 return
Jingwen Chen73850672020-12-14 08:25:34 -0500761 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500762 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500763 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500764 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500765 // package module name contain slashes, and thus cannot
766 // be mapped cleanly to a bazel label.
767 return
768 }
Alix94e26032022-08-16 20:37:33 +0000769 t, err := generateSoongModuleTarget(bpCtx, m)
770 if err != nil {
771 errs = append(errs, err)
772 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400773 targets = append(targets, t)
Spandan Das5af0bd32022-09-28 20:43:08 +0000774 case ApiBp2build:
775 if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
776 targets, errs = generateBazelTargets(bpCtx, aModule)
777 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500778 default:
Liz Kammer6eff3232021-08-26 08:37:59 -0400779 errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
780 return
Jingwen Chen73850672020-12-14 08:25:34 -0500781 }
782
Spandan Dasabedff02023-03-07 19:24:34 +0000783 for _, target := range targets {
784 targetDir := target.PackageName()
785 buildFileToTargets[targetDir] = append(buildFileToTargets[targetDir], target)
786 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800787 })
Liz Kammer6eff3232021-08-26 08:37:59 -0400788
789 if len(errs) > 0 {
790 return conversionResults{}, errs
791 }
792
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400793 if generateFilegroups {
794 // Add a filegroup target that exposes all sources in the subtree of this package
795 // 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 -0700796 //
797 // This works because: https://bazel.build/reference/be/functions#exports_files
798 // "As a legacy behaviour, also files mentioned as input to a rule are exported with the
799 // default visibility until the flag --incompatible_no_implicit_file_export is flipped. However, this behavior
800 // should not be relied upon and actively migrated away from."
801 //
802 // TODO(b/198619163): We should change this to export_files(glob(["**/*"])) instead, but doing that causes these errors:
803 // "Error in exports_files: generated label '//external/avb:avbtool' conflicts with existing py_binary rule"
804 // So we need to solve all the "target ... is both a rule and a file" warnings first.
Usta Shresthac6057152022-09-24 00:23:31 -0400805 for dir := range dirs {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400806 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
807 name: "bp2build_all_srcs",
808 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]))`,
809 ruleClass: "filegroup",
810 })
811 }
812 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500813
Liz Kammer6eff3232021-08-26 08:37:59 -0400814 return conversionResults{
815 buildFileToTargets: buildFileToTargets,
816 metrics: metrics,
Liz Kammer6eff3232021-08-26 08:37:59 -0400817 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500818}
819
Alix94e26032022-08-16 20:37:33 +0000820func generateBazelTargets(ctx bpToBuildContext, m android.Module) ([]BazelTarget, []error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400821 var targets []BazelTarget
Alix94e26032022-08-16 20:37:33 +0000822 var errs []error
Liz Kammer2ada09a2021-08-11 00:17:36 -0400823 for _, m := range m.Bp2buildTargets() {
Alix94e26032022-08-16 20:37:33 +0000824 target, err := generateBazelTarget(ctx, m)
825 if err != nil {
826 errs = append(errs, err)
827 return targets, errs
828 }
829 targets = append(targets, target)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400830 }
Alix94e26032022-08-16 20:37:33 +0000831 return targets, errs
Liz Kammer2ada09a2021-08-11 00:17:36 -0400832}
833
834type bp2buildModule interface {
835 TargetName() string
836 TargetPackage() string
837 BazelRuleClass() string
838 BazelRuleLoadLocation() string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000839 BazelAttributes() []interface{}
Liz Kammer2ada09a2021-08-11 00:17:36 -0400840}
841
Alix94e26032022-08-16 20:37:33 +0000842func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) (BazelTarget, error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400843 ruleClass := m.BazelRuleClass()
844 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500845
Jingwen Chen73850672020-12-14 08:25:34 -0500846 // extract the bazel attributes from the module.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000847 attrs := m.BazelAttributes()
Alix94e26032022-08-16 20:37:33 +0000848 props, err := extractModuleProperties(attrs, true)
849 if err != nil {
850 return BazelTarget{}, err
851 }
Jingwen Chen73850672020-12-14 08:25:34 -0500852
Liz Kammer0eae52e2021-10-06 10:32:26 -0400853 // name is handled in a special manner
854 delete(props.Attrs, "name")
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500855
Jingwen Chen73850672020-12-14 08:25:34 -0500856 // Return the Bazel target with rule class and attributes, ready to be
857 // code-generated.
858 attributes := propsToAttributes(props.Attrs)
Sasha Smundakfb589492022-08-04 11:13:27 -0700859 var content string
Liz Kammer2ada09a2021-08-11 00:17:36 -0400860 targetName := m.TargetName()
Sasha Smundakfb589492022-08-04 11:13:27 -0700861 if targetName != "" {
862 content = fmt.Sprintf(ruleTargetTemplate, ruleClass, targetName, attributes)
863 } else {
864 content = fmt.Sprintf(unnamedRuleTargetTemplate, ruleClass, attributes)
865 }
Jingwen Chen73850672020-12-14 08:25:34 -0500866 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500867 name: targetName,
Liz Kammer2ada09a2021-08-11 00:17:36 -0400868 packageName: m.TargetPackage(),
Jingwen Chen40067de2021-01-26 21:58:43 -0500869 ruleClass: ruleClass,
870 bzlLoadLocation: bzlLoadLocation,
Sasha Smundakfb589492022-08-04 11:13:27 -0700871 content: content,
Alix94e26032022-08-16 20:37:33 +0000872 }, nil
Jingwen Chen73850672020-12-14 08:25:34 -0500873}
874
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800875// Convert a module and its deps and props into a Bazel macro/rule
876// representation in the BUILD file.
Alix94e26032022-08-16 20:37:33 +0000877func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) (BazelTarget, error) {
878 props, err := getBuildProperties(ctx, m)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800879
880 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
881 // items, if the modules are added using different DependencyTag. Figure
882 // out the implications of that.
883 depLabels := map[string]bool{}
884 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500885 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800886 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
887 })
888 }
Liz Kammer0eae52e2021-10-06 10:32:26 -0400889
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400890 for p := range ignoredPropNames {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400891 delete(props.Attrs, p)
892 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800893 attributes := propsToAttributes(props.Attrs)
894
895 depLabelList := "[\n"
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400896 for depLabel := range depLabels {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800897 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
898 }
899 depLabelList += " ]"
900
901 targetName := targetNameWithVariant(ctx, m)
902 return BazelTarget{
Spandan Dasabedff02023-03-07 19:24:34 +0000903 name: targetName,
904 packageName: ctx.ModuleDir(m),
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800905 content: fmt.Sprintf(
Sasha Smundakfb589492022-08-04 11:13:27 -0700906 soongModuleTargetTemplate,
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800907 targetName,
908 ctx.ModuleName(m),
909 canonicalizeModuleType(ctx.ModuleType(m)),
910 ctx.ModuleSubDir(m),
911 depLabelList,
912 attributes),
Alix94e26032022-08-16 20:37:33 +0000913 }, err
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800914}
915
Alix94e26032022-08-16 20:37:33 +0000916func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800917 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
918 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
919 if aModule, ok := m.(android.Module); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000920 return extractModuleProperties(aModule.GetProperties(), false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800921 }
922
Alix94e26032022-08-16 20:37:33 +0000923 return BazelAttributes{}, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800924}
925
926// Generically extract module properties and types into a map, keyed by the module property name.
Alix94e26032022-08-16 20:37:33 +0000927func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800928 ret := map[string]string{}
929
930 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400931 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800932 propertiesValue := reflect.ValueOf(properties)
933 // Check that propertiesValue is a pointer to the Properties struct, like
934 // *cc.BaseLinkerProperties or *java.CompilerProperties.
935 //
936 // propertiesValue can also be type-asserted to the structs to
937 // manipulate internal props, if needed.
938 if isStructPtr(propertiesValue.Type()) {
939 structValue := propertiesValue.Elem()
Alix94e26032022-08-16 20:37:33 +0000940 ok, err := extractStructProperties(structValue, 0)
941 if err != nil {
942 return BazelAttributes{}, err
943 }
944 for k, v := range ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000945 if existing, exists := ret[k]; checkForDuplicateProperties && exists {
Alix94e26032022-08-16 20:37:33 +0000946 return BazelAttributes{}, fmt.Errorf(
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000947 "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes",
Alix94e26032022-08-16 20:37:33 +0000948 k, existing)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000949 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800950 ret[k] = v
951 }
952 } else {
Alix94e26032022-08-16 20:37:33 +0000953 return BazelAttributes{},
954 fmt.Errorf(
955 "properties must be a pointer to a struct, got %T",
956 propertiesValue.Interface())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800957 }
958 }
959
Liz Kammer2ada09a2021-08-11 00:17:36 -0400960 return BazelAttributes{
961 Attrs: ret,
Alix94e26032022-08-16 20:37:33 +0000962 }, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800963}
964
965func isStructPtr(t reflect.Type) bool {
966 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
967}
968
969// prettyPrint a property value into the equivalent Starlark representation
970// recursively.
Jingwen Chen58ff6802021-11-17 12:14:41 +0000971func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) {
972 if !emitZeroValues && isZero(propertyValue) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800973 // A property value being set or unset actually matters -- Soong does set default
974 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
975 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
976 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +0000977 // In Bazel-parlance, we would use "attr.<type>(default = <default
978 // value>)" to set the default value of unset attributes. In the cases
979 // where the bp2build converter didn't set the default value within the
980 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -0400981 // value. For those cases, we return an empty string so we don't
982 // unnecessarily generate empty values.
983 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800984 }
985
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800986 switch propertyValue.Kind() {
987 case reflect.String:
Liz Kammer72beb342022-02-03 08:42:10 -0500988 return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800989 case reflect.Bool:
Liz Kammer72beb342022-02-03 08:42:10 -0500990 return starlark_fmt.PrintBool(propertyValue.Bool()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800991 case reflect.Int, reflect.Uint, reflect.Int64:
Liz Kammer72beb342022-02-03 08:42:10 -0500992 return fmt.Sprintf("%v", propertyValue.Interface()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800993 case reflect.Ptr:
Jingwen Chen58ff6802021-11-17 12:14:41 +0000994 return prettyPrint(propertyValue.Elem(), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800995 case reflect.Slice:
Liz Kammer72beb342022-02-03 08:42:10 -0500996 elements := make([]string, 0, propertyValue.Len())
997 for i := 0; i < propertyValue.Len(); i++ {
998 val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800999 if err != nil {
1000 return "", err
1001 }
Liz Kammer72beb342022-02-03 08:42:10 -05001002 if val != "" {
1003 elements = append(elements, val)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001004 }
1005 }
Sam Delmerico932c01c2022-03-25 16:33:26 +00001006 return starlark_fmt.PrintList(elements, indent, func(s string) string {
1007 return "%s"
1008 }), nil
Jingwen Chenb4628eb2021-04-08 14:40:57 +00001009
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001010 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -05001011 // Special cases where the bp2build sends additional information to the codegenerator
1012 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +00001013 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
1014 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -05001015 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
1016 return fmt.Sprintf("%q", label.Label), nil
1017 }
1018
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001019 // Sort and print the struct props by the key.
Alix94e26032022-08-16 20:37:33 +00001020 structProps, err := extractStructProperties(propertyValue, indent)
1021
1022 if err != nil {
1023 return "", err
1024 }
1025
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001026 if len(structProps) == 0 {
1027 return "", nil
1028 }
Liz Kammer72beb342022-02-03 08:42:10 -05001029 return starlark_fmt.PrintDict(structProps, indent), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001030 case reflect.Interface:
1031 // TODO(b/164227191): implement pretty print for interfaces.
1032 // Interfaces are used for for arch, multilib and target properties.
1033 return "", nil
Spandan Das6a448ec2023-04-19 17:36:12 +00001034 case reflect.Map:
1035 if v, ok := propertyValue.Interface().(bazel.StringMapAttribute); ok {
1036 return starlark_fmt.PrintStringStringDict(v, indent), nil
1037 }
1038 return "", fmt.Errorf("bp2build expects map of type map[string]string for field: %s", propertyValue)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001039 default:
1040 return "", fmt.Errorf(
1041 "unexpected kind for property struct field: %s", propertyValue.Kind())
1042 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001043}
1044
1045// Converts a reflected property struct value into a map of property names and property values,
1046// which each property value correctly pretty-printed and indented at the right nest level,
1047// since property structs can be nested. In Starlark, nested structs are represented as nested
1048// dicts: https://docs.bazel.build/skylark/lib/dict.html
Alix94e26032022-08-16 20:37:33 +00001049func extractStructProperties(structValue reflect.Value, indent int) (map[string]string, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001050 if structValue.Kind() != reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001051 return map[string]string{}, fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind())
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001052 }
1053
Alix94e26032022-08-16 20:37:33 +00001054 var err error
1055
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001056 ret := map[string]string{}
1057 structType := structValue.Type()
1058 for i := 0; i < structValue.NumField(); i++ {
1059 field := structType.Field(i)
1060 if shouldSkipStructField(field) {
1061 continue
1062 }
1063
1064 fieldValue := structValue.Field(i)
1065 if isZero(fieldValue) {
1066 // Ignore zero-valued fields
1067 continue
1068 }
Liz Kammer7a210ac2021-09-22 15:52:58 -04001069
Liz Kammer32a03392021-09-14 11:17:21 -04001070 // if the struct is embedded (anonymous), flatten the properties into the containing struct
1071 if field.Anonymous {
1072 if field.Type.Kind() == reflect.Ptr {
1073 fieldValue = fieldValue.Elem()
1074 }
1075 if fieldValue.Type().Kind() == reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001076 propsToMerge, err := extractStructProperties(fieldValue, indent)
1077 if err != nil {
1078 return map[string]string{}, err
1079 }
Liz Kammer32a03392021-09-14 11:17:21 -04001080 for prop, value := range propsToMerge {
1081 ret[prop] = value
1082 }
1083 continue
1084 }
1085 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001086
1087 propertyName := proptools.PropertyNameForField(field.Name)
Alix94e26032022-08-16 20:37:33 +00001088 var prettyPrintedValue string
1089 prettyPrintedValue, err = prettyPrint(fieldValue, indent+1, false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001090 if err != nil {
Alix94e26032022-08-16 20:37:33 +00001091 return map[string]string{}, fmt.Errorf(
1092 "Error while parsing property: %q. %s",
1093 propertyName,
1094 err)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001095 }
1096 if prettyPrintedValue != "" {
1097 ret[propertyName] = prettyPrintedValue
1098 }
1099 }
1100
Alix94e26032022-08-16 20:37:33 +00001101 return ret, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001102}
1103
1104func isZero(value reflect.Value) bool {
1105 switch value.Kind() {
1106 case reflect.Func, reflect.Map, reflect.Slice:
1107 return value.IsNil()
1108 case reflect.Array:
1109 valueIsZero := true
1110 for i := 0; i < value.Len(); i++ {
1111 valueIsZero = valueIsZero && isZero(value.Index(i))
1112 }
1113 return valueIsZero
1114 case reflect.Struct:
1115 valueIsZero := true
1116 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +02001117 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001118 }
1119 return valueIsZero
1120 case reflect.Ptr:
1121 if !value.IsNil() {
1122 return isZero(reflect.Indirect(value))
1123 } else {
1124 return true
1125 }
Liz Kammer46fb7ab2021-12-01 10:09:34 -05001126 // Always print bool/strings, if you want a bool/string attribute to be able to take the default value, use a
1127 // pointer instead
1128 case reflect.Bool, reflect.String:
Liz Kammerd366c902021-06-03 13:43:01 -04001129 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001130 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -04001131 if !value.IsValid() {
1132 return true
1133 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001134 zeroValue := reflect.Zero(value.Type())
1135 result := value.Interface() == zeroValue.Interface()
1136 return result
1137 }
1138}
1139
1140func escapeString(s string) string {
1141 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +00001142
1143 // b/184026959: Reverse the application of some common control sequences.
1144 // These must be generated literally in the BUILD file.
1145 s = strings.ReplaceAll(s, "\t", "\\t")
1146 s = strings.ReplaceAll(s, "\n", "\\n")
1147 s = strings.ReplaceAll(s, "\r", "\\r")
1148
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001149 return strings.ReplaceAll(s, "\"", "\\\"")
1150}
1151
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001152func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
1153 name := ""
1154 if c.ModuleSubDir(logicModule) != "" {
1155 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
1156 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
1157 } else {
1158 name = c.ModuleName(logicModule)
1159 }
1160
1161 return strings.Replace(name, "//", "", 1)
1162}
1163
1164func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
1165 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
1166}