blob: cd1bc7f19c3847ad2b78d7c089d05428bb4ad6df [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() {
Liz Kammerc86e0942023-08-11 16:15:12 -0400689 if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
690 panic(fmt.Errorf("module %q [%s] [%s] was both converted with bp2build and has a handcrafted label", bpCtx.ModuleName(m), moduleType, dir))
691 }
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000692 // Handle modules converted to handcrafted targets.
693 //
694 // Since these modules are associated with some handcrafted
Cole Faustea602c52022-08-31 14:48:26 -0700695 // target in a BUILD file, we don't autoconvert them.
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000696
697 // Log the module.
Chris Parsons39a16972023-06-08 14:28:51 +0000698 metrics.AddUnconvertedModule(m, moduleType, dir,
699 android.UnconvertedReason{
700 ReasonType: int(bp2build_metrics_proto.UnconvertedReasonType_DEFINED_IN_BUILD_FILE),
701 })
Liz Kammer2ada09a2021-08-11 00:17:36 -0400702 } else if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000703 // Handle modules converted to generated targets.
704
705 // Log the module.
Chris Parsons39a16972023-06-08 14:28:51 +0000706 metrics.AddConvertedModule(aModule, moduleType, dir)
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000707
708 // Handle modules with unconverted deps. By default, emit a warning.
Liz Kammer6eff3232021-08-26 08:37:59 -0400709 if unconvertedDeps := aModule.GetUnconvertedBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700710 msg := fmt.Sprintf("%s %s:%s depends on unconverted modules: %s",
711 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400712 switch ctx.unconvertedDepMode {
713 case warnUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400714 metrics.moduleWithUnconvertedDepsMsgs = append(metrics.moduleWithUnconvertedDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400715 case errorModulesUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400716 errs = append(errs, fmt.Errorf(msg))
717 return
718 }
719 }
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500720 if unconvertedDeps := aModule.GetMissingBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700721 msg := fmt.Sprintf("%s %s:%s depends on missing modules: %s",
722 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400723 switch ctx.unconvertedDepMode {
724 case warnUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500725 metrics.moduleWithMissingDepsMsgs = append(metrics.moduleWithMissingDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400726 case errorModulesUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500727 errs = append(errs, fmt.Errorf(msg))
728 return
729 }
730 }
Alix94e26032022-08-16 20:37:33 +0000731 targets, targetErrs = generateBazelTargets(bpCtx, aModule)
732 errs = append(errs, targetErrs...)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400733 for _, t := range targets {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000734 // A module can potentially generate more than 1 Bazel
735 // target, each of a different rule class.
736 metrics.IncrementRuleClassCount(t.ruleClass)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400737 }
MarkDacek9c094ca2023-03-16 19:15:19 +0000738 } else if _, ok := ctx.Config().BazelModulesForceEnabledByFlag()[m.Name()]; ok && m.Name() != "" {
739 err := fmt.Errorf("Force Enabled Module %s not converted", m.Name())
740 errs = append(errs, err)
Chris Parsons39a16972023-06-08 14:28:51 +0000741 } else if aModule, ok := m.(android.Module); ok {
742 reason := aModule.GetUnconvertedReason()
743 if reason == nil {
744 panic(fmt.Errorf("module '%s' was neither converted nor marked unconvertible with bp2build", aModule.Name()))
745 } else {
746 metrics.AddUnconvertedModule(m, moduleType, dir, *reason)
747 }
748 return
Spandan Dasea2abba2023-06-14 21:30:38 +0000749 } else if glib, ok := m.(*bootstrap.GoPackage); ok {
750 targets, targetErrs = generateBazelTargetsGoPackage(bpCtx, glib, nameToGoLibMap)
751 errs = append(errs, targetErrs...)
752 metrics.IncrementRuleClassCount("go_library")
Spandan Das41f1eee2023-08-01 22:28:16 +0000753 metrics.AddConvertedModule(glib, "go_library", dir)
Spandan Das2a55cea2023-06-14 17:56:10 +0000754 } else if gbin, ok := m.(*bootstrap.GoBinary); ok {
Spandan Dasde623292023-06-14 21:30:38 +0000755 targets, targetErrs = generateBazelTargetsGoBinary(bpCtx, gbin, nameToGoLibMap)
756 errs = append(errs, targetErrs...)
757 metrics.IncrementRuleClassCount("go_binary")
Spandan Das41f1eee2023-08-01 22:28:16 +0000758 metrics.AddConvertedModule(gbin, "go_binary", dir)
Liz Kammerfc46bc12021-02-19 11:06:17 -0500759 } else {
Chris Parsons39a16972023-06-08 14:28:51 +0000760 metrics.AddUnconvertedModule(m, moduleType, dir, android.UnconvertedReason{
761 ReasonType: int(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED),
762 })
Liz Kammerba3ea162021-02-17 13:22:03 -0500763 return
Jingwen Chen73850672020-12-14 08:25:34 -0500764 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500765 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500766 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500767 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500768 // package module name contain slashes, and thus cannot
769 // be mapped cleanly to a bazel label.
770 return
771 }
Alix94e26032022-08-16 20:37:33 +0000772 t, err := generateSoongModuleTarget(bpCtx, m)
773 if err != nil {
774 errs = append(errs, err)
775 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400776 targets = append(targets, t)
Spandan Das5af0bd32022-09-28 20:43:08 +0000777 case ApiBp2build:
778 if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
779 targets, errs = generateBazelTargets(bpCtx, aModule)
780 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500781 default:
Liz Kammer6eff3232021-08-26 08:37:59 -0400782 errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
783 return
Jingwen Chen73850672020-12-14 08:25:34 -0500784 }
785
Spandan Dasabedff02023-03-07 19:24:34 +0000786 for _, target := range targets {
787 targetDir := target.PackageName()
788 buildFileToTargets[targetDir] = append(buildFileToTargets[targetDir], target)
789 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800790 })
Liz Kammer6eff3232021-08-26 08:37:59 -0400791
792 if len(errs) > 0 {
793 return conversionResults{}, errs
794 }
795
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400796 if generateFilegroups {
797 // Add a filegroup target that exposes all sources in the subtree of this package
798 // 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 -0700799 //
800 // This works because: https://bazel.build/reference/be/functions#exports_files
801 // "As a legacy behaviour, also files mentioned as input to a rule are exported with the
802 // default visibility until the flag --incompatible_no_implicit_file_export is flipped. However, this behavior
803 // should not be relied upon and actively migrated away from."
804 //
805 // TODO(b/198619163): We should change this to export_files(glob(["**/*"])) instead, but doing that causes these errors:
806 // "Error in exports_files: generated label '//external/avb:avbtool' conflicts with existing py_binary rule"
807 // So we need to solve all the "target ... is both a rule and a file" warnings first.
Usta Shresthac6057152022-09-24 00:23:31 -0400808 for dir := range dirs {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400809 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
810 name: "bp2build_all_srcs",
811 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]))`,
812 ruleClass: "filegroup",
813 })
814 }
815 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500816
Liz Kammer6eff3232021-08-26 08:37:59 -0400817 return conversionResults{
818 buildFileToTargets: buildFileToTargets,
819 metrics: metrics,
Liz Kammer6eff3232021-08-26 08:37:59 -0400820 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500821}
822
Alix94e26032022-08-16 20:37:33 +0000823func generateBazelTargets(ctx bpToBuildContext, m android.Module) ([]BazelTarget, []error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400824 var targets []BazelTarget
Alix94e26032022-08-16 20:37:33 +0000825 var errs []error
Liz Kammer2ada09a2021-08-11 00:17:36 -0400826 for _, m := range m.Bp2buildTargets() {
Alix94e26032022-08-16 20:37:33 +0000827 target, err := generateBazelTarget(ctx, m)
828 if err != nil {
829 errs = append(errs, err)
830 return targets, errs
831 }
832 targets = append(targets, target)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400833 }
Alix94e26032022-08-16 20:37:33 +0000834 return targets, errs
Liz Kammer2ada09a2021-08-11 00:17:36 -0400835}
836
837type bp2buildModule interface {
838 TargetName() string
839 TargetPackage() string
840 BazelRuleClass() string
841 BazelRuleLoadLocation() string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000842 BazelAttributes() []interface{}
Liz Kammer2ada09a2021-08-11 00:17:36 -0400843}
844
Alix94e26032022-08-16 20:37:33 +0000845func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) (BazelTarget, error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400846 ruleClass := m.BazelRuleClass()
847 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500848
Jingwen Chen73850672020-12-14 08:25:34 -0500849 // extract the bazel attributes from the module.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000850 attrs := m.BazelAttributes()
Alix94e26032022-08-16 20:37:33 +0000851 props, err := extractModuleProperties(attrs, true)
852 if err != nil {
853 return BazelTarget{}, err
854 }
Jingwen Chen73850672020-12-14 08:25:34 -0500855
Liz Kammer0eae52e2021-10-06 10:32:26 -0400856 // name is handled in a special manner
857 delete(props.Attrs, "name")
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500858
Jingwen Chen73850672020-12-14 08:25:34 -0500859 // Return the Bazel target with rule class and attributes, ready to be
860 // code-generated.
861 attributes := propsToAttributes(props.Attrs)
Sasha Smundakfb589492022-08-04 11:13:27 -0700862 var content string
Liz Kammer2ada09a2021-08-11 00:17:36 -0400863 targetName := m.TargetName()
Sasha Smundakfb589492022-08-04 11:13:27 -0700864 if targetName != "" {
865 content = fmt.Sprintf(ruleTargetTemplate, ruleClass, targetName, attributes)
866 } else {
867 content = fmt.Sprintf(unnamedRuleTargetTemplate, ruleClass, attributes)
868 }
Jingwen Chen73850672020-12-14 08:25:34 -0500869 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500870 name: targetName,
Liz Kammer2ada09a2021-08-11 00:17:36 -0400871 packageName: m.TargetPackage(),
Jingwen Chen40067de2021-01-26 21:58:43 -0500872 ruleClass: ruleClass,
873 bzlLoadLocation: bzlLoadLocation,
Sasha Smundakfb589492022-08-04 11:13:27 -0700874 content: content,
Alix94e26032022-08-16 20:37:33 +0000875 }, nil
Jingwen Chen73850672020-12-14 08:25:34 -0500876}
877
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800878// Convert a module and its deps and props into a Bazel macro/rule
879// representation in the BUILD file.
Alix94e26032022-08-16 20:37:33 +0000880func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) (BazelTarget, error) {
881 props, err := getBuildProperties(ctx, m)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800882
883 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
884 // items, if the modules are added using different DependencyTag. Figure
885 // out the implications of that.
886 depLabels := map[string]bool{}
887 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500888 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800889 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
890 })
891 }
Liz Kammer0eae52e2021-10-06 10:32:26 -0400892
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400893 for p := range ignoredPropNames {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400894 delete(props.Attrs, p)
895 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800896 attributes := propsToAttributes(props.Attrs)
897
898 depLabelList := "[\n"
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400899 for depLabel := range depLabels {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800900 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
901 }
902 depLabelList += " ]"
903
904 targetName := targetNameWithVariant(ctx, m)
905 return BazelTarget{
Spandan Dasabedff02023-03-07 19:24:34 +0000906 name: targetName,
907 packageName: ctx.ModuleDir(m),
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800908 content: fmt.Sprintf(
Sasha Smundakfb589492022-08-04 11:13:27 -0700909 soongModuleTargetTemplate,
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800910 targetName,
911 ctx.ModuleName(m),
912 canonicalizeModuleType(ctx.ModuleType(m)),
913 ctx.ModuleSubDir(m),
914 depLabelList,
915 attributes),
Alix94e26032022-08-16 20:37:33 +0000916 }, err
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800917}
918
Alix94e26032022-08-16 20:37:33 +0000919func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800920 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
921 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
922 if aModule, ok := m.(android.Module); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000923 return extractModuleProperties(aModule.GetProperties(), false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800924 }
925
Alix94e26032022-08-16 20:37:33 +0000926 return BazelAttributes{}, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800927}
928
929// Generically extract module properties and types into a map, keyed by the module property name.
Alix94e26032022-08-16 20:37:33 +0000930func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800931 ret := map[string]string{}
932
933 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400934 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800935 propertiesValue := reflect.ValueOf(properties)
936 // Check that propertiesValue is a pointer to the Properties struct, like
937 // *cc.BaseLinkerProperties or *java.CompilerProperties.
938 //
939 // propertiesValue can also be type-asserted to the structs to
940 // manipulate internal props, if needed.
941 if isStructPtr(propertiesValue.Type()) {
942 structValue := propertiesValue.Elem()
Alix94e26032022-08-16 20:37:33 +0000943 ok, err := extractStructProperties(structValue, 0)
944 if err != nil {
945 return BazelAttributes{}, err
946 }
947 for k, v := range ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000948 if existing, exists := ret[k]; checkForDuplicateProperties && exists {
Alix94e26032022-08-16 20:37:33 +0000949 return BazelAttributes{}, fmt.Errorf(
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000950 "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes",
Alix94e26032022-08-16 20:37:33 +0000951 k, existing)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000952 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800953 ret[k] = v
954 }
955 } else {
Alix94e26032022-08-16 20:37:33 +0000956 return BazelAttributes{},
957 fmt.Errorf(
958 "properties must be a pointer to a struct, got %T",
959 propertiesValue.Interface())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800960 }
961 }
962
Liz Kammer2ada09a2021-08-11 00:17:36 -0400963 return BazelAttributes{
964 Attrs: ret,
Alix94e26032022-08-16 20:37:33 +0000965 }, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800966}
967
968func isStructPtr(t reflect.Type) bool {
969 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
970}
971
972// prettyPrint a property value into the equivalent Starlark representation
973// recursively.
Jingwen Chen58ff6802021-11-17 12:14:41 +0000974func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) {
975 if !emitZeroValues && isZero(propertyValue) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800976 // A property value being set or unset actually matters -- Soong does set default
977 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
978 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
979 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +0000980 // In Bazel-parlance, we would use "attr.<type>(default = <default
981 // value>)" to set the default value of unset attributes. In the cases
982 // where the bp2build converter didn't set the default value within the
983 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -0400984 // value. For those cases, we return an empty string so we don't
985 // unnecessarily generate empty values.
986 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800987 }
988
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800989 switch propertyValue.Kind() {
990 case reflect.String:
Liz Kammer72beb342022-02-03 08:42:10 -0500991 return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800992 case reflect.Bool:
Liz Kammer72beb342022-02-03 08:42:10 -0500993 return starlark_fmt.PrintBool(propertyValue.Bool()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800994 case reflect.Int, reflect.Uint, reflect.Int64:
Liz Kammer72beb342022-02-03 08:42:10 -0500995 return fmt.Sprintf("%v", propertyValue.Interface()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800996 case reflect.Ptr:
Jingwen Chen58ff6802021-11-17 12:14:41 +0000997 return prettyPrint(propertyValue.Elem(), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800998 case reflect.Slice:
Liz Kammer72beb342022-02-03 08:42:10 -0500999 elements := make([]string, 0, propertyValue.Len())
1000 for i := 0; i < propertyValue.Len(); i++ {
1001 val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001002 if err != nil {
1003 return "", err
1004 }
Liz Kammer72beb342022-02-03 08:42:10 -05001005 if val != "" {
1006 elements = append(elements, val)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001007 }
1008 }
Sam Delmerico932c01c2022-03-25 16:33:26 +00001009 return starlark_fmt.PrintList(elements, indent, func(s string) string {
1010 return "%s"
1011 }), nil
Jingwen Chenb4628eb2021-04-08 14:40:57 +00001012
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001013 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -05001014 // Special cases where the bp2build sends additional information to the codegenerator
1015 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +00001016 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
1017 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -05001018 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
1019 return fmt.Sprintf("%q", label.Label), nil
1020 }
1021
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001022 // Sort and print the struct props by the key.
Alix94e26032022-08-16 20:37:33 +00001023 structProps, err := extractStructProperties(propertyValue, indent)
1024
1025 if err != nil {
1026 return "", err
1027 }
1028
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001029 if len(structProps) == 0 {
1030 return "", nil
1031 }
Liz Kammer72beb342022-02-03 08:42:10 -05001032 return starlark_fmt.PrintDict(structProps, indent), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001033 case reflect.Interface:
1034 // TODO(b/164227191): implement pretty print for interfaces.
1035 // Interfaces are used for for arch, multilib and target properties.
1036 return "", nil
Spandan Das6a448ec2023-04-19 17:36:12 +00001037 case reflect.Map:
1038 if v, ok := propertyValue.Interface().(bazel.StringMapAttribute); ok {
1039 return starlark_fmt.PrintStringStringDict(v, indent), nil
1040 }
1041 return "", fmt.Errorf("bp2build expects map of type map[string]string for field: %s", propertyValue)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001042 default:
1043 return "", fmt.Errorf(
1044 "unexpected kind for property struct field: %s", propertyValue.Kind())
1045 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001046}
1047
1048// Converts a reflected property struct value into a map of property names and property values,
1049// which each property value correctly pretty-printed and indented at the right nest level,
1050// since property structs can be nested. In Starlark, nested structs are represented as nested
1051// dicts: https://docs.bazel.build/skylark/lib/dict.html
Alix94e26032022-08-16 20:37:33 +00001052func extractStructProperties(structValue reflect.Value, indent int) (map[string]string, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001053 if structValue.Kind() != reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001054 return map[string]string{}, fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind())
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001055 }
1056
Alix94e26032022-08-16 20:37:33 +00001057 var err error
1058
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001059 ret := map[string]string{}
1060 structType := structValue.Type()
1061 for i := 0; i < structValue.NumField(); i++ {
1062 field := structType.Field(i)
1063 if shouldSkipStructField(field) {
1064 continue
1065 }
1066
1067 fieldValue := structValue.Field(i)
1068 if isZero(fieldValue) {
1069 // Ignore zero-valued fields
1070 continue
1071 }
Liz Kammer7a210ac2021-09-22 15:52:58 -04001072
Liz Kammer32a03392021-09-14 11:17:21 -04001073 // if the struct is embedded (anonymous), flatten the properties into the containing struct
1074 if field.Anonymous {
1075 if field.Type.Kind() == reflect.Ptr {
1076 fieldValue = fieldValue.Elem()
1077 }
1078 if fieldValue.Type().Kind() == reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001079 propsToMerge, err := extractStructProperties(fieldValue, indent)
1080 if err != nil {
1081 return map[string]string{}, err
1082 }
Liz Kammer32a03392021-09-14 11:17:21 -04001083 for prop, value := range propsToMerge {
1084 ret[prop] = value
1085 }
1086 continue
1087 }
1088 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001089
1090 propertyName := proptools.PropertyNameForField(field.Name)
Alix94e26032022-08-16 20:37:33 +00001091 var prettyPrintedValue string
1092 prettyPrintedValue, err = prettyPrint(fieldValue, indent+1, false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001093 if err != nil {
Alix94e26032022-08-16 20:37:33 +00001094 return map[string]string{}, fmt.Errorf(
1095 "Error while parsing property: %q. %s",
1096 propertyName,
1097 err)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001098 }
1099 if prettyPrintedValue != "" {
1100 ret[propertyName] = prettyPrintedValue
1101 }
1102 }
1103
Alix94e26032022-08-16 20:37:33 +00001104 return ret, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001105}
1106
1107func isZero(value reflect.Value) bool {
1108 switch value.Kind() {
1109 case reflect.Func, reflect.Map, reflect.Slice:
1110 return value.IsNil()
1111 case reflect.Array:
1112 valueIsZero := true
1113 for i := 0; i < value.Len(); i++ {
1114 valueIsZero = valueIsZero && isZero(value.Index(i))
1115 }
1116 return valueIsZero
1117 case reflect.Struct:
1118 valueIsZero := true
1119 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +02001120 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001121 }
1122 return valueIsZero
1123 case reflect.Ptr:
1124 if !value.IsNil() {
1125 return isZero(reflect.Indirect(value))
1126 } else {
1127 return true
1128 }
Liz Kammer46fb7ab2021-12-01 10:09:34 -05001129 // Always print bool/strings, if you want a bool/string attribute to be able to take the default value, use a
1130 // pointer instead
1131 case reflect.Bool, reflect.String:
Liz Kammerd366c902021-06-03 13:43:01 -04001132 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001133 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -04001134 if !value.IsValid() {
1135 return true
1136 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001137 zeroValue := reflect.Zero(value.Type())
1138 result := value.Interface() == zeroValue.Interface()
1139 return result
1140 }
1141}
1142
1143func escapeString(s string) string {
1144 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +00001145
1146 // b/184026959: Reverse the application of some common control sequences.
1147 // These must be generated literally in the BUILD file.
1148 s = strings.ReplaceAll(s, "\t", "\\t")
1149 s = strings.ReplaceAll(s, "\n", "\\n")
1150 s = strings.ReplaceAll(s, "\r", "\\r")
1151
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001152 return strings.ReplaceAll(s, "\"", "\\\"")
1153}
1154
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001155func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
1156 name := ""
1157 if c.ModuleSubDir(logicModule) != "" {
1158 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
1159 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
1160 } else {
1161 name = c.ModuleName(logicModule)
1162 }
1163
1164 return strings.Replace(name, "//", "", 1)
1165}
1166
1167func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
1168 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
1169}