blob: 906036330a04b7a953bba33b0bedbcf41595ba41 [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
178)
179
Liz Kammer6eff3232021-08-26 08:37:59 -0400180type unconvertedDepsMode int
181
182const (
183 // Include a warning in conversion metrics about converted modules with unconverted direct deps
184 warnUnconvertedDeps unconvertedDepsMode = iota
185 // Error and fail conversion if encountering a module with unconverted direct deps
186 // Enabled by setting environment variable `BP2BUILD_ERROR_UNCONVERTED`
187 errorModulesUnconvertedDeps
188)
189
Jingwen Chendcc329a2021-01-26 02:49:03 -0500190func (mode CodegenMode) String() string {
191 switch mode {
192 case Bp2Build:
193 return "Bp2Build"
194 case QueryView:
195 return "QueryView"
196 default:
197 return fmt.Sprintf("%d", mode)
198 }
199}
200
Liz Kammerba3ea162021-02-17 13:22:03 -0500201// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
202// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
203// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
204// call AdditionalNinjaDeps and add them manually to the ninja file.
205func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
206 ctx.additionalDeps = append(ctx.additionalDeps, deps...)
207}
208
209// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
210func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
211 return ctx.additionalDeps
212}
213
Paul Duffinc6390592022-11-04 13:35:21 +0000214func (ctx *CodegenContext) Config() android.Config { return ctx.config }
215func (ctx *CodegenContext) Context() *android.Context { return ctx.context }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500216
217// NewCodegenContext creates a wrapper context that conforms to PathContext for
218// writing BUILD files in the output directory.
Cole Faustb85d1a12022-11-08 18:14:01 -0800219func NewCodegenContext(config android.Config, context *android.Context, mode CodegenMode, topDir string) *CodegenContext {
Liz Kammer6eff3232021-08-26 08:37:59 -0400220 var unconvertedDeps unconvertedDepsMode
221 if config.IsEnvTrue("BP2BUILD_ERROR_UNCONVERTED") {
222 unconvertedDeps = errorModulesUnconvertedDeps
223 }
Liz Kammerba3ea162021-02-17 13:22:03 -0500224 return &CodegenContext{
Liz Kammer6eff3232021-08-26 08:37:59 -0400225 context: context,
226 config: config,
227 mode: mode,
228 unconvertedDepMode: unconvertedDeps,
Cole Faustb85d1a12022-11-08 18:14:01 -0800229 topDir: topDir,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500230 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800231}
232
233// props is an unsorted map. This function ensures that
234// the generated attributes are sorted to ensure determinism.
235func propsToAttributes(props map[string]string) string {
236 var attributes string
Cole Faust18994c72023-02-28 16:02:16 -0800237 for _, propName := range android.SortedKeys(props) {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400238 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800239 }
240 return attributes
241}
242
Liz Kammer6eff3232021-08-26 08:37:59 -0400243type conversionResults struct {
244 buildFileToTargets map[string]BazelTargets
245 metrics CodegenMetrics
Liz Kammer6eff3232021-08-26 08:37:59 -0400246}
247
248func (r conversionResults) BuildDirToTargets() map[string]BazelTargets {
249 return r.buildFileToTargets
250}
251
Spandan Dasea2abba2023-06-14 21:30:38 +0000252// struct to store state of go bazel targets
253// this implements bp2buildModule interface and is passed to generateBazelTargets
254type goBazelTarget struct {
255 targetName string
256 targetPackage string
257 bazelRuleClass string
258 bazelRuleLoadLocation string
259 bazelAttributes []interface{}
260}
261
262var _ bp2buildModule = (*goBazelTarget)(nil)
263
264func (g goBazelTarget) TargetName() string {
265 return g.targetName
266}
267
268func (g goBazelTarget) TargetPackage() string {
269 return g.targetPackage
270}
271
272func (g goBazelTarget) BazelRuleClass() string {
273 return g.bazelRuleClass
274}
275
276func (g goBazelTarget) BazelRuleLoadLocation() string {
277 return g.bazelRuleLoadLocation
278}
279
280func (g goBazelTarget) BazelAttributes() []interface{} {
281 return g.bazelAttributes
282}
283
284// Creates a target_compatible_with entry that is *not* compatible with android
285func targetNotCompatibleWithAndroid() bazel.LabelListAttribute {
286 ret := bazel.LabelListAttribute{}
287 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsAndroid,
288 bazel.MakeLabelList(
289 []bazel.Label{
290 bazel.Label{
291 Label: "@platforms//:incompatible",
292 },
293 },
294 ),
295 )
296 return ret
297}
298
299// helper function to return labels for srcs used in bootstrap_go_package and bootstrap_go_binary
300// this function has the following limitations which make it unsuitable for widespread use
Spandan Das0a8a2752023-06-21 01:50:33 +0000301// - wildcard patterns in srcs
302// This is ok for go since build/blueprint does not support it.
Spandan Dasea2abba2023-06-14 21:30:38 +0000303//
304// Prefer to use `BazelLabelForModuleSrc` instead
Spandan Das0a8a2752023-06-21 01:50:33 +0000305func goSrcLabels(cfg android.Config, moduleDir string, srcs []string, linuxSrcs, darwinSrcs []string) bazel.LabelListAttribute {
Spandan Dasea2abba2023-06-14 21:30:38 +0000306 labels := func(srcs []string) bazel.LabelList {
307 ret := []bazel.Label{}
308 for _, src := range srcs {
309 srcLabel := bazel.Label{
Spandan Das0a8a2752023-06-21 01:50:33 +0000310 Label: src,
Spandan Dasea2abba2023-06-14 21:30:38 +0000311 }
312 ret = append(ret, srcLabel)
313 }
Spandan Das0a8a2752023-06-21 01:50:33 +0000314 // Respect package boundaries
315 return android.TransformSubpackagePaths(
316 cfg,
317 moduleDir,
318 bazel.MakeLabelList(ret),
319 )
Spandan Dasea2abba2023-06-14 21:30:38 +0000320 }
321
322 ret := bazel.LabelListAttribute{}
323 // common
324 ret.SetSelectValue(bazel.NoConfigAxis, "", labels(srcs))
325 // linux
326 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsLinux, labels(linuxSrcs))
327 // darwin
328 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsDarwin, labels(darwinSrcs))
329 return ret
330}
331
332func goDepLabels(deps []string, goModulesMap nameToGoLibraryModule) bazel.LabelListAttribute {
333 labels := []bazel.Label{}
334 for _, dep := range deps {
335 moduleDir := goModulesMap[dep].Dir
336 if moduleDir == "." {
337 moduleDir = ""
338 }
339 label := bazel.Label{
340 Label: fmt.Sprintf("//%s:%s", moduleDir, dep),
341 }
342 labels = append(labels, label)
343 }
344 return bazel.MakeLabelListAttribute(bazel.MakeLabelList(labels))
345}
346
347// attributes common to blueprint_go_binary and bootstap_go_package
348type goAttributes struct {
349 Importpath bazel.StringAttribute
350 Srcs bazel.LabelListAttribute
351 Deps bazel.LabelListAttribute
Spandan Das682e7862023-06-22 22:22:11 +0000352 Data bazel.LabelListAttribute
Spandan Dasea2abba2023-06-14 21:30:38 +0000353 Target_compatible_with bazel.LabelListAttribute
Spandan Das682e7862023-06-22 22:22:11 +0000354
355 // attributes for the dynamically generated go_test target
356 Embed bazel.LabelListAttribute
Spandan Dasea2abba2023-06-14 21:30:38 +0000357}
358
Spandan Das682e7862023-06-22 22:22:11 +0000359type goTestProperties struct {
360 name string
361 dir string
362 testSrcs []string
363 linuxTestSrcs []string
364 darwinTestSrcs []string
365 testData []string
366 // Name of the target that should be compiled together with the test
367 embedName string
368}
369
370// Creates a go_test target for bootstrap_go_package / blueprint_go_binary
371func generateBazelTargetsGoTest(ctx *android.Context, goModulesMap nameToGoLibraryModule, gp goTestProperties) (BazelTarget, error) {
372 ca := android.CommonAttributes{
373 Name: gp.name,
374 }
375 ga := goAttributes{
376 Srcs: goSrcLabels(ctx.Config(), gp.dir, gp.testSrcs, gp.linuxTestSrcs, gp.darwinTestSrcs),
377 Data: goSrcLabels(ctx.Config(), gp.dir, gp.testData, []string{}, []string{}),
378 Embed: bazel.MakeLabelListAttribute(
379 bazel.MakeLabelList(
380 []bazel.Label{bazel.Label{Label: ":" + gp.embedName}},
381 ),
382 ),
383 Target_compatible_with: targetNotCompatibleWithAndroid(),
384 }
385
386 libTest := goBazelTarget{
387 targetName: gp.name,
388 targetPackage: gp.dir,
389 bazelRuleClass: "go_test",
390 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
391 bazelAttributes: []interface{}{&ca, &ga},
392 }
393 return generateBazelTarget(ctx, libTest)
394}
395
396// TODO - b/288491147: testSrcs of certain bootstrap_go_package/blueprint_go_binary are not hermetic and depend on
397// testdata checked into the filesystem.
398// Denylist the generation of go_test targets for these Soong modules.
399// The go_library/go_binary will still be generated, since those are hermitic.
400var (
401 goTestsDenylist = []string{
402 "android-archive-zip",
403 "bazel_notice_gen",
404 "blueprint-bootstrap-bpdoc",
405 "blueprint-microfactory",
406 "blueprint-pathtools",
407 "bssl_ar",
408 "compliance_checkmetadata",
409 "compliance_checkshare",
410 "compliance_dumpgraph",
411 "compliance_dumpresolutions",
412 "compliance_listshare",
413 "compliance-module",
414 "compliancenotice_bom",
415 "compliancenotice_shippedlibs",
416 "compliance_rtrace",
417 "compliance_sbom",
418 "golang-protobuf-internal-fuzz-jsonfuzz",
419 "golang-protobuf-internal-fuzz-textfuzz",
420 "golang-protobuf-internal-fuzz-wirefuzz",
421 "htmlnotice",
422 "protoc-gen-go",
423 "rbcrun-module",
424 "spdx-tools-builder",
425 "spdx-tools-builder2v1",
426 "spdx-tools-builder2v2",
427 "spdx-tools-builder2v3",
428 "spdx-tools-idsearcher",
429 "spdx-tools-spdx-json",
430 "spdx-tools-utils",
431 "soong-ui-build",
432 "textnotice",
433 "xmlnotice",
434 }
435)
436
Spandan Das89aa0f72023-06-30 20:18:39 +0000437func testOfGoPackageIsIncompatible(g *bootstrap.GoPackage) bool {
438 return android.InList(g.Name(), goTestsDenylist) ||
439 // Denylist tests of soong_build
440 // Theses tests have a guard that prevent usage outside a test environment
441 // The guard (`ensureTestOnly`) looks for a `-test` in os.Args, which is present in soong's gotestrunner, but missing in `b test`
442 g.IsPluginFor("soong_build") ||
443 // soong-android is a dep of soong_build
444 // 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`
445 g.Name() == "soong-android"
446}
447
448func testOfGoBinaryIsIncompatible(g *bootstrap.GoBinary) bool {
449 return android.InList(g.Name(), goTestsDenylist)
450}
451
Spandan Dasea2abba2023-06-14 21:30:38 +0000452func generateBazelTargetsGoPackage(ctx *android.Context, g *bootstrap.GoPackage, goModulesMap nameToGoLibraryModule) ([]BazelTarget, []error) {
453 ca := android.CommonAttributes{
454 Name: g.Name(),
455 }
Spandan Dasde623292023-06-14 21:30:38 +0000456
457 // For this bootstrap_go_package dep chain,
458 // A --> B --> C ( ---> depends on)
459 // Soong provides the convenience of only listing B as deps of A even if a src file of A imports C
460 // Bazel OTOH
461 // 1. requires C to be listed in `deps` expllicity.
462 // 2. does not require C to be listed if src of A does not import C
463 //
464 // 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
465 transitiveDeps := transitiveGoDeps(g.Deps(), goModulesMap)
466
Spandan Dasea2abba2023-06-14 21:30:38 +0000467 ga := goAttributes{
468 Importpath: bazel.StringAttribute{
469 Value: proptools.StringPtr(g.GoPkgPath()),
470 },
Spandan Das0a8a2752023-06-21 01:50:33 +0000471 Srcs: goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs()),
472 Deps: goDepLabels(
473 android.FirstUniqueStrings(transitiveDeps),
474 goModulesMap,
475 ),
Spandan Dasea2abba2023-06-14 21:30:38 +0000476 Target_compatible_with: targetNotCompatibleWithAndroid(),
477 }
478
479 lib := goBazelTarget{
480 targetName: g.Name(),
481 targetPackage: ctx.ModuleDir(g),
482 bazelRuleClass: "go_library",
483 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
484 bazelAttributes: []interface{}{&ca, &ga},
485 }
Spandan Das682e7862023-06-22 22:22:11 +0000486 retTargets := []BazelTarget{}
487 var retErrs []error
488 if libTarget, err := generateBazelTarget(ctx, lib); err == nil {
489 retTargets = append(retTargets, libTarget)
490 } else {
491 retErrs = []error{err}
Spandan Dasea2abba2023-06-14 21:30:38 +0000492 }
Spandan Das682e7862023-06-22 22:22:11 +0000493
494 // If the library contains test srcs, create an additional go_test target
Spandan Das89aa0f72023-06-30 20:18:39 +0000495 if !testOfGoPackageIsIncompatible(g) && (len(g.TestSrcs()) > 0 || len(g.LinuxTestSrcs()) > 0 || len(g.DarwinTestSrcs()) > 0) {
Spandan Das682e7862023-06-22 22:22:11 +0000496 gp := goTestProperties{
497 name: g.Name() + "-test",
498 dir: ctx.ModuleDir(g),
499 testSrcs: g.TestSrcs(),
500 linuxTestSrcs: g.LinuxTestSrcs(),
501 darwinTestSrcs: g.DarwinTestSrcs(),
502 testData: g.TestData(),
503 embedName: g.Name(), // embed the source go_library in the test so that its .go files are included in the compilation unit
504 }
505 if libTestTarget, err := generateBazelTargetsGoTest(ctx, goModulesMap, gp); err == nil {
506 retTargets = append(retTargets, libTestTarget)
507 } else {
508 retErrs = append(retErrs, err)
509 }
510 }
511
512 return retTargets, retErrs
Spandan Dasea2abba2023-06-14 21:30:38 +0000513}
514
515type goLibraryModule struct {
516 Dir string
517 Deps []string
518}
519
520type nameToGoLibraryModule map[string]goLibraryModule
521
522// Visit each module in the graph
523// If a module is of type `bootstrap_go_package`, return a map containing metadata like its dir and deps
524func createGoLibraryModuleMap(ctx *android.Context) nameToGoLibraryModule {
525 ret := nameToGoLibraryModule{}
526 ctx.VisitAllModules(func(m blueprint.Module) {
527 moduleType := ctx.ModuleType(m)
528 // We do not need to store information about blueprint_go_binary since it does not have any rdeps
529 if moduleType == "bootstrap_go_package" {
530 ret[m.Name()] = goLibraryModule{
531 Dir: ctx.ModuleDir(m),
532 Deps: m.(*bootstrap.GoPackage).Deps(),
533 }
534 }
535 })
536 return ret
537}
538
Spandan Dasde623292023-06-14 21:30:38 +0000539// Returns the deps in the transitive closure of a go target
540func transitiveGoDeps(directDeps []string, goModulesMap nameToGoLibraryModule) []string {
541 allDeps := directDeps
542 i := 0
543 for i < len(allDeps) {
544 curr := allDeps[i]
545 allDeps = append(allDeps, goModulesMap[curr].Deps...)
546 i += 1
547 }
548 allDeps = android.SortedUniqueStrings(allDeps)
549 return allDeps
550}
551
552func generateBazelTargetsGoBinary(ctx *android.Context, g *bootstrap.GoBinary, goModulesMap nameToGoLibraryModule) ([]BazelTarget, []error) {
553 ca := android.CommonAttributes{
554 Name: g.Name(),
555 }
556
Spandan Das682e7862023-06-22 22:22:11 +0000557 retTargets := []BazelTarget{}
558 var retErrs []error
559
Spandan Dasde623292023-06-14 21:30:38 +0000560 // For this bootstrap_go_package dep chain,
561 // A --> B --> C ( ---> depends on)
562 // Soong provides the convenience of only listing B as deps of A even if a src file of A imports C
563 // Bazel OTOH
564 // 1. requires C to be listed in `deps` expllicity.
565 // 2. does not require C to be listed if src of A does not import C
566 //
567 // 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
568 transitiveDeps := transitiveGoDeps(g.Deps(), goModulesMap)
569
Spandan Das682e7862023-06-22 22:22:11 +0000570 goSource := ""
571 // If the library contains test srcs, create an additional go_test target
572 // The go_test target will embed a go_source containining the source .go files it tests
Spandan Das89aa0f72023-06-30 20:18:39 +0000573 if !testOfGoBinaryIsIncompatible(g) && (len(g.TestSrcs()) > 0 || len(g.LinuxTestSrcs()) > 0 || len(g.DarwinTestSrcs()) > 0) {
Spandan Das682e7862023-06-22 22:22:11 +0000574 // Create a go_source containing the source .go files of go_library
575 // This target will be an `embed` of the go_binary and go_test
576 goSource = g.Name() + "-source"
577 ca := android.CommonAttributes{
578 Name: goSource,
579 }
580 ga := goAttributes{
581 Srcs: goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs()),
582 Deps: goDepLabels(transitiveDeps, goModulesMap),
583 Target_compatible_with: targetNotCompatibleWithAndroid(),
584 }
585 libTestSource := goBazelTarget{
586 targetName: goSource,
587 targetPackage: ctx.ModuleDir(g),
588 bazelRuleClass: "go_source",
589 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
590 bazelAttributes: []interface{}{&ca, &ga},
591 }
592 if libSourceTarget, err := generateBazelTarget(ctx, libTestSource); err == nil {
593 retTargets = append(retTargets, libSourceTarget)
594 } else {
595 retErrs = append(retErrs, err)
596 }
597
598 // Create a go_test target
599 gp := goTestProperties{
600 name: g.Name() + "-test",
601 dir: ctx.ModuleDir(g),
602 testSrcs: g.TestSrcs(),
603 linuxTestSrcs: g.LinuxTestSrcs(),
604 darwinTestSrcs: g.DarwinTestSrcs(),
605 testData: g.TestData(),
606 // embed the go_source in the test
607 embedName: g.Name() + "-source",
608 }
609 if libTestTarget, err := generateBazelTargetsGoTest(ctx, goModulesMap, gp); err == nil {
610 retTargets = append(retTargets, libTestTarget)
611 } else {
612 retErrs = append(retErrs, err)
613 }
614
615 }
616
617 // Create a go_binary target
Spandan Dasde623292023-06-14 21:30:38 +0000618 ga := goAttributes{
Spandan Dasde623292023-06-14 21:30:38 +0000619 Deps: goDepLabels(transitiveDeps, goModulesMap),
620 Target_compatible_with: targetNotCompatibleWithAndroid(),
621 }
622
Spandan Das682e7862023-06-22 22:22:11 +0000623 // If the binary has testSrcs, embed the common `go_source`
624 if goSource != "" {
625 ga.Embed = bazel.MakeLabelListAttribute(
626 bazel.MakeLabelList(
627 []bazel.Label{bazel.Label{Label: ":" + goSource}},
628 ),
629 )
630 } else {
631 ga.Srcs = goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs())
632 }
633
Spandan Dasde623292023-06-14 21:30:38 +0000634 bin := goBazelTarget{
635 targetName: g.Name(),
636 targetPackage: ctx.ModuleDir(g),
637 bazelRuleClass: "go_binary",
638 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
639 bazelAttributes: []interface{}{&ca, &ga},
640 }
Spandan Das682e7862023-06-22 22:22:11 +0000641
642 if binTarget, err := generateBazelTarget(ctx, bin); err == nil {
643 retTargets = append(retTargets, binTarget)
644 } else {
645 retErrs = []error{err}
Spandan Dasde623292023-06-14 21:30:38 +0000646 }
Spandan Das682e7862023-06-22 22:22:11 +0000647
648 return retTargets, retErrs
Spandan Dasde623292023-06-14 21:30:38 +0000649}
650
Liz Kammer6eff3232021-08-26 08:37:59 -0400651func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (conversionResults, []error) {
ustaaaf2fd12023-07-01 11:40:36 -0400652 ctx.Context().BeginEvent("GenerateBazelTargets")
653 defer ctx.Context().EndEvent("GenerateBazelTargets")
Jingwen Chen40067de2021-01-26 21:58:43 -0500654 buildFileToTargets := make(map[string]BazelTargets)
Jingwen Chen164e0862021-02-19 00:48:40 -0500655
656 // Simple metrics tracking for bp2build
usta4f5d2c12022-10-28 23:32:01 -0400657 metrics := CreateCodegenMetrics()
Jingwen Chen164e0862021-02-19 00:48:40 -0500658
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400659 dirs := make(map[string]bool)
660
Liz Kammer6eff3232021-08-26 08:37:59 -0400661 var errs []error
662
Spandan Dasea2abba2023-06-14 21:30:38 +0000663 // Visit go libraries in a pre-run and store its state in a map
664 // The time complexity remains O(N), and this does not add significant wall time.
665 nameToGoLibMap := createGoLibraryModuleMap(ctx.Context())
666
Jingwen Chen164e0862021-02-19 00:48:40 -0500667 bpCtx := ctx.Context()
668 bpCtx.VisitAllModules(func(m blueprint.Module) {
669 dir := bpCtx.ModuleDir(m)
Chris Parsons492bd912022-01-20 12:55:05 -0500670 moduleType := bpCtx.ModuleType(m)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400671 dirs[dir] = true
672
Liz Kammer2ada09a2021-08-11 00:17:36 -0400673 var targets []BazelTarget
Spandan Dasea2abba2023-06-14 21:30:38 +0000674 var targetErrs []error
Jingwen Chen73850672020-12-14 08:25:34 -0500675
Jingwen Chen164e0862021-02-19 00:48:40 -0500676 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500677 case Bp2Build:
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000678 // There are two main ways of converting a Soong module to Bazel:
679 // 1) Manually handcrafting a Bazel target and associating the module with its label
680 // 2) Automatically generating with bp2build converters
681 //
682 // bp2build converters are used for the majority of modules.
Liz Kammerba3ea162021-02-17 13:22:03 -0500683 if b, ok := m.(android.Bazelable); ok && b.HasHandcraftedLabel() {
Liz Kammerc86e0942023-08-11 16:15:12 -0400684 if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
685 panic(fmt.Errorf("module %q [%s] [%s] was both converted with bp2build and has a handcrafted label", bpCtx.ModuleName(m), moduleType, dir))
686 }
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000687 // Handle modules converted to handcrafted targets.
688 //
689 // Since these modules are associated with some handcrafted
Cole Faustea602c52022-08-31 14:48:26 -0700690 // target in a BUILD file, we don't autoconvert them.
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000691
692 // Log the module.
Chris Parsons39a16972023-06-08 14:28:51 +0000693 metrics.AddUnconvertedModule(m, moduleType, dir,
694 android.UnconvertedReason{
695 ReasonType: int(bp2build_metrics_proto.UnconvertedReasonType_DEFINED_IN_BUILD_FILE),
696 })
Liz Kammer2ada09a2021-08-11 00:17:36 -0400697 } else if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000698 // Handle modules converted to generated targets.
699
700 // Log the module.
Chris Parsons39a16972023-06-08 14:28:51 +0000701 metrics.AddConvertedModule(aModule, moduleType, dir)
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000702
703 // Handle modules with unconverted deps. By default, emit a warning.
Liz Kammer6eff3232021-08-26 08:37:59 -0400704 if unconvertedDeps := aModule.GetUnconvertedBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700705 msg := fmt.Sprintf("%s %s:%s depends on unconverted modules: %s",
706 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400707 switch ctx.unconvertedDepMode {
708 case warnUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400709 metrics.moduleWithUnconvertedDepsMsgs = append(metrics.moduleWithUnconvertedDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400710 case errorModulesUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400711 errs = append(errs, fmt.Errorf(msg))
712 return
713 }
714 }
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500715 if unconvertedDeps := aModule.GetMissingBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700716 msg := fmt.Sprintf("%s %s:%s depends on missing modules: %s",
717 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400718 switch ctx.unconvertedDepMode {
719 case warnUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500720 metrics.moduleWithMissingDepsMsgs = append(metrics.moduleWithMissingDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400721 case errorModulesUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500722 errs = append(errs, fmt.Errorf(msg))
723 return
724 }
725 }
Alix94e26032022-08-16 20:37:33 +0000726 targets, targetErrs = generateBazelTargets(bpCtx, aModule)
727 errs = append(errs, targetErrs...)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400728 for _, t := range targets {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000729 // A module can potentially generate more than 1 Bazel
730 // target, each of a different rule class.
731 metrics.IncrementRuleClassCount(t.ruleClass)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400732 }
MarkDacek9c094ca2023-03-16 19:15:19 +0000733 } else if _, ok := ctx.Config().BazelModulesForceEnabledByFlag()[m.Name()]; ok && m.Name() != "" {
734 err := fmt.Errorf("Force Enabled Module %s not converted", m.Name())
735 errs = append(errs, err)
Chris Parsons39a16972023-06-08 14:28:51 +0000736 } else if aModule, ok := m.(android.Module); ok {
737 reason := aModule.GetUnconvertedReason()
738 if reason == nil {
739 panic(fmt.Errorf("module '%s' was neither converted nor marked unconvertible with bp2build", aModule.Name()))
740 } else {
741 metrics.AddUnconvertedModule(m, moduleType, dir, *reason)
742 }
743 return
Spandan Dasea2abba2023-06-14 21:30:38 +0000744 } else if glib, ok := m.(*bootstrap.GoPackage); ok {
745 targets, targetErrs = generateBazelTargetsGoPackage(bpCtx, glib, nameToGoLibMap)
746 errs = append(errs, targetErrs...)
747 metrics.IncrementRuleClassCount("go_library")
Spandan Das41f1eee2023-08-01 22:28:16 +0000748 metrics.AddConvertedModule(glib, "go_library", dir)
Spandan Das2a55cea2023-06-14 17:56:10 +0000749 } else if gbin, ok := m.(*bootstrap.GoBinary); ok {
Spandan Dasde623292023-06-14 21:30:38 +0000750 targets, targetErrs = generateBazelTargetsGoBinary(bpCtx, gbin, nameToGoLibMap)
751 errs = append(errs, targetErrs...)
752 metrics.IncrementRuleClassCount("go_binary")
Spandan Das41f1eee2023-08-01 22:28:16 +0000753 metrics.AddConvertedModule(gbin, "go_binary", dir)
Liz Kammerfc46bc12021-02-19 11:06:17 -0500754 } else {
Chris Parsons39a16972023-06-08 14:28:51 +0000755 metrics.AddUnconvertedModule(m, moduleType, dir, android.UnconvertedReason{
756 ReasonType: int(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED),
757 })
Liz Kammerba3ea162021-02-17 13:22:03 -0500758 return
Jingwen Chen73850672020-12-14 08:25:34 -0500759 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500760 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500761 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500762 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500763 // package module name contain slashes, and thus cannot
764 // be mapped cleanly to a bazel label.
765 return
766 }
Alix94e26032022-08-16 20:37:33 +0000767 t, err := generateSoongModuleTarget(bpCtx, m)
768 if err != nil {
769 errs = append(errs, err)
770 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400771 targets = append(targets, t)
Jingwen Chen33832f92021-01-24 22:55:54 -0500772 default:
Liz Kammer6eff3232021-08-26 08:37:59 -0400773 errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
774 return
Jingwen Chen73850672020-12-14 08:25:34 -0500775 }
776
Spandan Dasabedff02023-03-07 19:24:34 +0000777 for _, target := range targets {
778 targetDir := target.PackageName()
779 buildFileToTargets[targetDir] = append(buildFileToTargets[targetDir], target)
780 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800781 })
Liz Kammer6eff3232021-08-26 08:37:59 -0400782
783 if len(errs) > 0 {
784 return conversionResults{}, errs
785 }
786
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400787 if generateFilegroups {
788 // Add a filegroup target that exposes all sources in the subtree of this package
789 // 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 -0700790 //
791 // This works because: https://bazel.build/reference/be/functions#exports_files
792 // "As a legacy behaviour, also files mentioned as input to a rule are exported with the
793 // default visibility until the flag --incompatible_no_implicit_file_export is flipped. However, this behavior
794 // should not be relied upon and actively migrated away from."
795 //
796 // TODO(b/198619163): We should change this to export_files(glob(["**/*"])) instead, but doing that causes these errors:
797 // "Error in exports_files: generated label '//external/avb:avbtool' conflicts with existing py_binary rule"
798 // So we need to solve all the "target ... is both a rule and a file" warnings first.
Usta Shresthac6057152022-09-24 00:23:31 -0400799 for dir := range dirs {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400800 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
801 name: "bp2build_all_srcs",
802 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]))`,
803 ruleClass: "filegroup",
804 })
805 }
806 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500807
Liz Kammer6eff3232021-08-26 08:37:59 -0400808 return conversionResults{
809 buildFileToTargets: buildFileToTargets,
810 metrics: metrics,
Liz Kammer6eff3232021-08-26 08:37:59 -0400811 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500812}
813
Alix94e26032022-08-16 20:37:33 +0000814func generateBazelTargets(ctx bpToBuildContext, m android.Module) ([]BazelTarget, []error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400815 var targets []BazelTarget
Alix94e26032022-08-16 20:37:33 +0000816 var errs []error
Liz Kammer2ada09a2021-08-11 00:17:36 -0400817 for _, m := range m.Bp2buildTargets() {
Alix94e26032022-08-16 20:37:33 +0000818 target, err := generateBazelTarget(ctx, m)
819 if err != nil {
820 errs = append(errs, err)
821 return targets, errs
822 }
823 targets = append(targets, target)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400824 }
Alix94e26032022-08-16 20:37:33 +0000825 return targets, errs
Liz Kammer2ada09a2021-08-11 00:17:36 -0400826}
827
828type bp2buildModule interface {
829 TargetName() string
830 TargetPackage() string
831 BazelRuleClass() string
832 BazelRuleLoadLocation() string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000833 BazelAttributes() []interface{}
Liz Kammer2ada09a2021-08-11 00:17:36 -0400834}
835
Alix94e26032022-08-16 20:37:33 +0000836func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) (BazelTarget, error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400837 ruleClass := m.BazelRuleClass()
838 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500839
Jingwen Chen73850672020-12-14 08:25:34 -0500840 // extract the bazel attributes from the module.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000841 attrs := m.BazelAttributes()
Alix94e26032022-08-16 20:37:33 +0000842 props, err := extractModuleProperties(attrs, true)
843 if err != nil {
844 return BazelTarget{}, err
845 }
Jingwen Chen73850672020-12-14 08:25:34 -0500846
Liz Kammer0eae52e2021-10-06 10:32:26 -0400847 // name is handled in a special manner
848 delete(props.Attrs, "name")
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500849
Jingwen Chen73850672020-12-14 08:25:34 -0500850 // Return the Bazel target with rule class and attributes, ready to be
851 // code-generated.
852 attributes := propsToAttributes(props.Attrs)
Sasha Smundakfb589492022-08-04 11:13:27 -0700853 var content string
Liz Kammer2ada09a2021-08-11 00:17:36 -0400854 targetName := m.TargetName()
Sasha Smundakfb589492022-08-04 11:13:27 -0700855 if targetName != "" {
856 content = fmt.Sprintf(ruleTargetTemplate, ruleClass, targetName, attributes)
857 } else {
858 content = fmt.Sprintf(unnamedRuleTargetTemplate, ruleClass, attributes)
859 }
Jingwen Chen73850672020-12-14 08:25:34 -0500860 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500861 name: targetName,
Liz Kammer2ada09a2021-08-11 00:17:36 -0400862 packageName: m.TargetPackage(),
Jingwen Chen40067de2021-01-26 21:58:43 -0500863 ruleClass: ruleClass,
864 bzlLoadLocation: bzlLoadLocation,
Sasha Smundakfb589492022-08-04 11:13:27 -0700865 content: content,
Alix94e26032022-08-16 20:37:33 +0000866 }, nil
Jingwen Chen73850672020-12-14 08:25:34 -0500867}
868
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800869// Convert a module and its deps and props into a Bazel macro/rule
870// representation in the BUILD file.
Alix94e26032022-08-16 20:37:33 +0000871func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) (BazelTarget, error) {
872 props, err := getBuildProperties(ctx, m)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800873
874 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
875 // items, if the modules are added using different DependencyTag. Figure
876 // out the implications of that.
877 depLabels := map[string]bool{}
878 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500879 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800880 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
881 })
882 }
Liz Kammer0eae52e2021-10-06 10:32:26 -0400883
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400884 for p := range ignoredPropNames {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400885 delete(props.Attrs, p)
886 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800887 attributes := propsToAttributes(props.Attrs)
888
889 depLabelList := "[\n"
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400890 for depLabel := range depLabels {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800891 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
892 }
893 depLabelList += " ]"
894
895 targetName := targetNameWithVariant(ctx, m)
896 return BazelTarget{
Spandan Dasabedff02023-03-07 19:24:34 +0000897 name: targetName,
898 packageName: ctx.ModuleDir(m),
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800899 content: fmt.Sprintf(
Sasha Smundakfb589492022-08-04 11:13:27 -0700900 soongModuleTargetTemplate,
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800901 targetName,
902 ctx.ModuleName(m),
903 canonicalizeModuleType(ctx.ModuleType(m)),
904 ctx.ModuleSubDir(m),
905 depLabelList,
906 attributes),
Alix94e26032022-08-16 20:37:33 +0000907 }, err
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800908}
909
Alix94e26032022-08-16 20:37:33 +0000910func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800911 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
912 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
913 if aModule, ok := m.(android.Module); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000914 return extractModuleProperties(aModule.GetProperties(), false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800915 }
916
Alix94e26032022-08-16 20:37:33 +0000917 return BazelAttributes{}, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800918}
919
920// Generically extract module properties and types into a map, keyed by the module property name.
Alix94e26032022-08-16 20:37:33 +0000921func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800922 ret := map[string]string{}
923
924 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400925 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800926 propertiesValue := reflect.ValueOf(properties)
927 // Check that propertiesValue is a pointer to the Properties struct, like
928 // *cc.BaseLinkerProperties or *java.CompilerProperties.
929 //
930 // propertiesValue can also be type-asserted to the structs to
931 // manipulate internal props, if needed.
932 if isStructPtr(propertiesValue.Type()) {
933 structValue := propertiesValue.Elem()
Alix94e26032022-08-16 20:37:33 +0000934 ok, err := extractStructProperties(structValue, 0)
935 if err != nil {
936 return BazelAttributes{}, err
937 }
938 for k, v := range ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000939 if existing, exists := ret[k]; checkForDuplicateProperties && exists {
Alix94e26032022-08-16 20:37:33 +0000940 return BazelAttributes{}, fmt.Errorf(
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000941 "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes",
Alix94e26032022-08-16 20:37:33 +0000942 k, existing)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000943 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800944 ret[k] = v
945 }
946 } else {
Alix94e26032022-08-16 20:37:33 +0000947 return BazelAttributes{},
948 fmt.Errorf(
949 "properties must be a pointer to a struct, got %T",
950 propertiesValue.Interface())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800951 }
952 }
953
Liz Kammer2ada09a2021-08-11 00:17:36 -0400954 return BazelAttributes{
955 Attrs: ret,
Alix94e26032022-08-16 20:37:33 +0000956 }, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800957}
958
959func isStructPtr(t reflect.Type) bool {
960 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
961}
962
963// prettyPrint a property value into the equivalent Starlark representation
964// recursively.
Jingwen Chen58ff6802021-11-17 12:14:41 +0000965func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) {
966 if !emitZeroValues && isZero(propertyValue) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800967 // A property value being set or unset actually matters -- Soong does set default
968 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
969 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
970 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +0000971 // In Bazel-parlance, we would use "attr.<type>(default = <default
972 // value>)" to set the default value of unset attributes. In the cases
973 // where the bp2build converter didn't set the default value within the
974 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -0400975 // value. For those cases, we return an empty string so we don't
976 // unnecessarily generate empty values.
977 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800978 }
979
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800980 switch propertyValue.Kind() {
981 case reflect.String:
Liz Kammer72beb342022-02-03 08:42:10 -0500982 return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800983 case reflect.Bool:
Liz Kammer72beb342022-02-03 08:42:10 -0500984 return starlark_fmt.PrintBool(propertyValue.Bool()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800985 case reflect.Int, reflect.Uint, reflect.Int64:
Liz Kammer72beb342022-02-03 08:42:10 -0500986 return fmt.Sprintf("%v", propertyValue.Interface()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800987 case reflect.Ptr:
Jingwen Chen58ff6802021-11-17 12:14:41 +0000988 return prettyPrint(propertyValue.Elem(), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800989 case reflect.Slice:
Liz Kammer72beb342022-02-03 08:42:10 -0500990 elements := make([]string, 0, propertyValue.Len())
991 for i := 0; i < propertyValue.Len(); i++ {
992 val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800993 if err != nil {
994 return "", err
995 }
Liz Kammer72beb342022-02-03 08:42:10 -0500996 if val != "" {
997 elements = append(elements, val)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800998 }
999 }
Sam Delmerico932c01c2022-03-25 16:33:26 +00001000 return starlark_fmt.PrintList(elements, indent, func(s string) string {
1001 return "%s"
1002 }), nil
Jingwen Chenb4628eb2021-04-08 14:40:57 +00001003
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001004 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -05001005 // Special cases where the bp2build sends additional information to the codegenerator
1006 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +00001007 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
1008 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -05001009 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
1010 return fmt.Sprintf("%q", label.Label), nil
1011 }
1012
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001013 // Sort and print the struct props by the key.
Alix94e26032022-08-16 20:37:33 +00001014 structProps, err := extractStructProperties(propertyValue, indent)
1015
1016 if err != nil {
1017 return "", err
1018 }
1019
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001020 if len(structProps) == 0 {
1021 return "", nil
1022 }
Liz Kammer72beb342022-02-03 08:42:10 -05001023 return starlark_fmt.PrintDict(structProps, indent), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001024 case reflect.Interface:
1025 // TODO(b/164227191): implement pretty print for interfaces.
1026 // Interfaces are used for for arch, multilib and target properties.
1027 return "", nil
Spandan Das6a448ec2023-04-19 17:36:12 +00001028 case reflect.Map:
1029 if v, ok := propertyValue.Interface().(bazel.StringMapAttribute); ok {
1030 return starlark_fmt.PrintStringStringDict(v, indent), nil
1031 }
1032 return "", fmt.Errorf("bp2build expects map of type map[string]string for field: %s", propertyValue)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001033 default:
1034 return "", fmt.Errorf(
1035 "unexpected kind for property struct field: %s", propertyValue.Kind())
1036 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001037}
1038
1039// Converts a reflected property struct value into a map of property names and property values,
1040// which each property value correctly pretty-printed and indented at the right nest level,
1041// since property structs can be nested. In Starlark, nested structs are represented as nested
1042// dicts: https://docs.bazel.build/skylark/lib/dict.html
Alix94e26032022-08-16 20:37:33 +00001043func extractStructProperties(structValue reflect.Value, indent int) (map[string]string, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001044 if structValue.Kind() != reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001045 return map[string]string{}, fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind())
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001046 }
1047
Alix94e26032022-08-16 20:37:33 +00001048 var err error
1049
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001050 ret := map[string]string{}
1051 structType := structValue.Type()
1052 for i := 0; i < structValue.NumField(); i++ {
1053 field := structType.Field(i)
1054 if shouldSkipStructField(field) {
1055 continue
1056 }
1057
1058 fieldValue := structValue.Field(i)
1059 if isZero(fieldValue) {
1060 // Ignore zero-valued fields
1061 continue
1062 }
Liz Kammer7a210ac2021-09-22 15:52:58 -04001063
Liz Kammer32a03392021-09-14 11:17:21 -04001064 // if the struct is embedded (anonymous), flatten the properties into the containing struct
1065 if field.Anonymous {
1066 if field.Type.Kind() == reflect.Ptr {
1067 fieldValue = fieldValue.Elem()
1068 }
1069 if fieldValue.Type().Kind() == reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001070 propsToMerge, err := extractStructProperties(fieldValue, indent)
1071 if err != nil {
1072 return map[string]string{}, err
1073 }
Liz Kammer32a03392021-09-14 11:17:21 -04001074 for prop, value := range propsToMerge {
1075 ret[prop] = value
1076 }
1077 continue
1078 }
1079 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001080
1081 propertyName := proptools.PropertyNameForField(field.Name)
Alix94e26032022-08-16 20:37:33 +00001082 var prettyPrintedValue string
1083 prettyPrintedValue, err = prettyPrint(fieldValue, indent+1, false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001084 if err != nil {
Alix94e26032022-08-16 20:37:33 +00001085 return map[string]string{}, fmt.Errorf(
1086 "Error while parsing property: %q. %s",
1087 propertyName,
1088 err)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001089 }
1090 if prettyPrintedValue != "" {
1091 ret[propertyName] = prettyPrintedValue
1092 }
1093 }
1094
Alix94e26032022-08-16 20:37:33 +00001095 return ret, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001096}
1097
1098func isZero(value reflect.Value) bool {
1099 switch value.Kind() {
1100 case reflect.Func, reflect.Map, reflect.Slice:
1101 return value.IsNil()
1102 case reflect.Array:
1103 valueIsZero := true
1104 for i := 0; i < value.Len(); i++ {
1105 valueIsZero = valueIsZero && isZero(value.Index(i))
1106 }
1107 return valueIsZero
1108 case reflect.Struct:
1109 valueIsZero := true
1110 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +02001111 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001112 }
1113 return valueIsZero
1114 case reflect.Ptr:
1115 if !value.IsNil() {
1116 return isZero(reflect.Indirect(value))
1117 } else {
1118 return true
1119 }
Liz Kammer46fb7ab2021-12-01 10:09:34 -05001120 // Always print bool/strings, if you want a bool/string attribute to be able to take the default value, use a
1121 // pointer instead
1122 case reflect.Bool, reflect.String:
Liz Kammerd366c902021-06-03 13:43:01 -04001123 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001124 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -04001125 if !value.IsValid() {
1126 return true
1127 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001128 zeroValue := reflect.Zero(value.Type())
1129 result := value.Interface() == zeroValue.Interface()
1130 return result
1131 }
1132}
1133
1134func escapeString(s string) string {
1135 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +00001136
1137 // b/184026959: Reverse the application of some common control sequences.
1138 // These must be generated literally in the BUILD file.
1139 s = strings.ReplaceAll(s, "\t", "\\t")
1140 s = strings.ReplaceAll(s, "\n", "\\n")
1141 s = strings.ReplaceAll(s, "\r", "\\r")
1142
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001143 return strings.ReplaceAll(s, "\"", "\\\"")
1144}
1145
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001146func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
1147 name := ""
1148 if c.ModuleSubDir(logicModule) != "" {
1149 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
1150 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
1151 } else {
1152 name = c.ModuleName(logicModule)
1153 }
1154
1155 return strings.Replace(name, "//", "", 1)
1156}
1157
1158func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
1159 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
1160}