blob: 15b77669c77b3d62a4d0d0dce3f4f74ac72fd995 [file] [log] [blame]
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001// Copyright 2020 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package bp2build
16
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux0da7ce62021-08-23 17:04:20 +000017/*
18For shareable/common functionality for conversion from soong-module to build files
19for queryview/bp2build
20*/
21
Liz Kammer2dd9ca42020-11-25 16:06:39 -080022import (
Liz Kammer2dd9ca42020-11-25 16:06:39 -080023 "fmt"
24 "reflect"
Jingwen Chen49109762021-05-25 05:16:48 +000025 "sort"
Liz Kammer2dd9ca42020-11-25 16:06:39 -080026 "strings"
27
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux0da7ce62021-08-23 17:04:20 +000028 "android/soong/android"
29 "android/soong/bazel"
Liz Kammer72beb342022-02-03 08:42:10 -050030 "android/soong/starlark_fmt"
Chris Parsons39a16972023-06-08 14:28:51 +000031 "android/soong/ui/metrics/bp2build_metrics_proto"
ustada2a2112023-08-08 00:29:08 -040032
Liz Kammer2dd9ca42020-11-25 16:06:39 -080033 "github.com/google/blueprint"
Spandan Dasea2abba2023-06-14 21:30:38 +000034 "github.com/google/blueprint/bootstrap"
Liz Kammer2dd9ca42020-11-25 16:06:39 -080035 "github.com/google/blueprint/proptools"
36)
37
38type BazelAttributes struct {
39 Attrs map[string]string
40}
41
Cole Faustb4cb0c82023-09-14 15:16:58 -070042type BazelLoadSymbol struct {
43 // The name of the symbol in the file being loaded
44 symbol string
45 // The name the symbol wil have in this file. Can be left blank to use the same name as symbol.
46 alias string
Jingwen Chen40067de2021-01-26 21:58:43 -050047}
48
Cole Faustb4cb0c82023-09-14 15:16:58 -070049type BazelLoad struct {
50 file string
51 symbols []BazelLoadSymbol
52}
53
54type BazelTarget struct {
55 name string
56 packageName string
57 content string
58 ruleClass string
59 loads []BazelLoad
Jingwen Chen40067de2021-01-26 21:58:43 -050060}
61
Jingwen Chenc63677b2021-06-17 05:43:19 +000062// Label is the fully qualified Bazel label constructed from the BazelTarget's
63// package name and target name.
64func (t BazelTarget) Label() string {
65 if t.packageName == "." {
66 return "//:" + t.name
67 } else {
68 return "//" + t.packageName + ":" + t.name
69 }
70}
71
Spandan Dasabedff02023-03-07 19:24:34 +000072// PackageName returns the package of the Bazel target.
73// Defaults to root of tree.
74func (t BazelTarget) PackageName() string {
75 if t.packageName == "" {
76 return "."
77 }
78 return t.packageName
79}
80
Jingwen Chen40067de2021-01-26 21:58:43 -050081// BazelTargets is a typedef for a slice of BazelTarget objects.
82type BazelTargets []BazelTarget
83
Sasha Smundak8bea2672022-08-04 13:31:14 -070084func (targets BazelTargets) packageRule() *BazelTarget {
85 for _, target := range targets {
86 if target.ruleClass == "package" {
87 return &target
88 }
89 }
90 return nil
91}
92
93// sort a list of BazelTargets in-place, by name, and by generated/handcrafted types.
Jingwen Chen49109762021-05-25 05:16:48 +000094func (targets BazelTargets) sort() {
95 sort.Slice(targets, func(i, j int) bool {
Jingwen Chen49109762021-05-25 05:16:48 +000096 return targets[i].name < targets[j].name
97 })
98}
99
Jingwen Chen40067de2021-01-26 21:58:43 -0500100// String returns the string representation of BazelTargets, without load
101// statements (use LoadStatements for that), since the targets are usually not
102// adjacent to the load statements at the top of the BUILD file.
103func (targets BazelTargets) String() string {
ustada2a2112023-08-08 00:29:08 -0400104 var res strings.Builder
Jingwen Chen40067de2021-01-26 21:58:43 -0500105 for i, target := range targets {
Sasha Smundak8bea2672022-08-04 13:31:14 -0700106 if target.ruleClass != "package" {
ustada2a2112023-08-08 00:29:08 -0400107 res.WriteString(target.content)
Sasha Smundak8bea2672022-08-04 13:31:14 -0700108 }
Jingwen Chen40067de2021-01-26 21:58:43 -0500109 if i != len(targets)-1 {
ustada2a2112023-08-08 00:29:08 -0400110 res.WriteString("\n\n")
Jingwen Chen40067de2021-01-26 21:58:43 -0500111 }
112 }
ustada2a2112023-08-08 00:29:08 -0400113 return res.String()
Jingwen Chen40067de2021-01-26 21:58:43 -0500114}
115
116// LoadStatements return the string representation of the sorted and deduplicated
117// Starlark rule load statements needed by a group of BazelTargets.
118func (targets BazelTargets) LoadStatements() string {
Cole Faustb4cb0c82023-09-14 15:16:58 -0700119 // First, merge all the load statements from all the targets onto one list
120 bzlToLoadedSymbols := map[string][]BazelLoadSymbol{}
Jingwen Chen40067de2021-01-26 21:58:43 -0500121 for _, target := range targets {
Cole Faustb4cb0c82023-09-14 15:16:58 -0700122 for _, load := range target.loads {
123 outer:
124 for _, symbol := range load.symbols {
125 alias := symbol.alias
126 if alias == "" {
127 alias = symbol.symbol
128 }
129 for _, otherSymbol := range bzlToLoadedSymbols[load.file] {
130 otherAlias := otherSymbol.alias
131 if otherAlias == "" {
132 otherAlias = otherSymbol.symbol
133 }
134 if symbol.symbol == otherSymbol.symbol && alias == otherAlias {
135 continue outer
136 } else if alias == otherAlias {
137 panic(fmt.Sprintf("Conflicting destination (%s) for loads of %s and %s", alias, symbol.symbol, otherSymbol.symbol))
138 }
139 }
140 bzlToLoadedSymbols[load.file] = append(bzlToLoadedSymbols[load.file], symbol)
141 }
Jingwen Chen40067de2021-01-26 21:58:43 -0500142 }
143 }
144
Cole Faustb4cb0c82023-09-14 15:16:58 -0700145 var loadStatements strings.Builder
146 for i, bzl := range android.SortedKeys(bzlToLoadedSymbols) {
147 symbols := bzlToLoadedSymbols[bzl]
148 loadStatements.WriteString("load(\"")
149 loadStatements.WriteString(bzl)
150 loadStatements.WriteString("\", ")
151 sort.Slice(symbols, func(i, j int) bool {
152 if symbols[i].symbol < symbols[j].symbol {
153 return true
154 }
155 return symbols[i].alias < symbols[j].alias
156 })
157 for j, symbol := range symbols {
158 if symbol.alias != "" && symbol.alias != symbol.symbol {
159 loadStatements.WriteString(symbol.alias)
160 loadStatements.WriteString(" = ")
161 }
162 loadStatements.WriteString("\"")
163 loadStatements.WriteString(symbol.symbol)
164 loadStatements.WriteString("\"")
165 if j != len(symbols)-1 {
166 loadStatements.WriteString(", ")
Jingwen Chen40067de2021-01-26 21:58:43 -0500167 }
168 }
Cole Faustb4cb0c82023-09-14 15:16:58 -0700169 loadStatements.WriteString(")")
170 if i != len(bzlToLoadedSymbols)-1 {
171 loadStatements.WriteString("\n")
172 }
Jingwen Chen40067de2021-01-26 21:58:43 -0500173 }
Cole Faustb4cb0c82023-09-14 15:16:58 -0700174 return loadStatements.String()
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800175}
176
177type bpToBuildContext interface {
178 ModuleName(module blueprint.Module) string
179 ModuleDir(module blueprint.Module) string
180 ModuleSubDir(module blueprint.Module) string
181 ModuleType(module blueprint.Module) string
182
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500183 VisitAllModules(visit func(blueprint.Module))
184 VisitDirectDeps(module blueprint.Module, visit func(blueprint.Module))
185}
186
187type CodegenContext struct {
Jingwen Chen16d90a82021-09-17 07:16:13 +0000188 config android.Config
Paul Duffinc6390592022-11-04 13:35:21 +0000189 context *android.Context
Jingwen Chen16d90a82021-09-17 07:16:13 +0000190 mode CodegenMode
191 additionalDeps []string
Liz Kammer6eff3232021-08-26 08:37:59 -0400192 unconvertedDepMode unconvertedDepsMode
Cole Faustb85d1a12022-11-08 18:14:01 -0800193 topDir string
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500194}
195
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400196func (ctx *CodegenContext) Mode() CodegenMode {
197 return ctx.mode
Jingwen Chen164e0862021-02-19 00:48:40 -0500198}
199
Jingwen Chen33832f92021-01-24 22:55:54 -0500200// CodegenMode is an enum to differentiate code-generation modes.
201type CodegenMode int
202
203const (
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400204 // Bp2Build - generate BUILD files with targets buildable by Bazel directly.
Jingwen Chen33832f92021-01-24 22:55:54 -0500205 //
206 // This mode is used for the Soong->Bazel build definition conversion.
207 Bp2Build CodegenMode = iota
208
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400209 // QueryView - generate BUILD files with targets representing fully mutated
Jingwen Chen33832f92021-01-24 22:55:54 -0500210 // Soong modules, representing the fully configured Soong module graph with
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400211 // variants and dependency edges.
Jingwen Chen33832f92021-01-24 22:55:54 -0500212 //
213 // This mode is used for discovering and introspecting the existing Soong
214 // module graph.
215 QueryView
216)
217
Liz Kammer6eff3232021-08-26 08:37:59 -0400218type unconvertedDepsMode int
219
220const (
221 // Include a warning in conversion metrics about converted modules with unconverted direct deps
222 warnUnconvertedDeps unconvertedDepsMode = iota
223 // Error and fail conversion if encountering a module with unconverted direct deps
224 // Enabled by setting environment variable `BP2BUILD_ERROR_UNCONVERTED`
225 errorModulesUnconvertedDeps
226)
227
Jingwen Chendcc329a2021-01-26 02:49:03 -0500228func (mode CodegenMode) String() string {
229 switch mode {
230 case Bp2Build:
231 return "Bp2Build"
232 case QueryView:
233 return "QueryView"
234 default:
235 return fmt.Sprintf("%d", mode)
236 }
237}
238
Liz Kammerba3ea162021-02-17 13:22:03 -0500239// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
240// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
241// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
242// call AdditionalNinjaDeps and add them manually to the ninja file.
243func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
244 ctx.additionalDeps = append(ctx.additionalDeps, deps...)
245}
246
247// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
248func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
249 return ctx.additionalDeps
250}
251
Paul Duffinc6390592022-11-04 13:35:21 +0000252func (ctx *CodegenContext) Config() android.Config { return ctx.config }
253func (ctx *CodegenContext) Context() *android.Context { return ctx.context }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500254
255// NewCodegenContext creates a wrapper context that conforms to PathContext for
256// writing BUILD files in the output directory.
Cole Faustb85d1a12022-11-08 18:14:01 -0800257func NewCodegenContext(config android.Config, context *android.Context, mode CodegenMode, topDir string) *CodegenContext {
Liz Kammer6eff3232021-08-26 08:37:59 -0400258 var unconvertedDeps unconvertedDepsMode
259 if config.IsEnvTrue("BP2BUILD_ERROR_UNCONVERTED") {
260 unconvertedDeps = errorModulesUnconvertedDeps
261 }
Liz Kammerba3ea162021-02-17 13:22:03 -0500262 return &CodegenContext{
Liz Kammer6eff3232021-08-26 08:37:59 -0400263 context: context,
264 config: config,
265 mode: mode,
266 unconvertedDepMode: unconvertedDeps,
Cole Faustb85d1a12022-11-08 18:14:01 -0800267 topDir: topDir,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500268 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800269}
270
271// props is an unsorted map. This function ensures that
272// the generated attributes are sorted to ensure determinism.
273func propsToAttributes(props map[string]string) string {
274 var attributes string
Cole Faust18994c72023-02-28 16:02:16 -0800275 for _, propName := range android.SortedKeys(props) {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400276 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800277 }
278 return attributes
279}
280
Liz Kammer6eff3232021-08-26 08:37:59 -0400281type conversionResults struct {
282 buildFileToTargets map[string]BazelTargets
283 metrics CodegenMetrics
Liz Kammer6eff3232021-08-26 08:37:59 -0400284}
285
286func (r conversionResults) BuildDirToTargets() map[string]BazelTargets {
287 return r.buildFileToTargets
288}
289
Spandan Dasea2abba2023-06-14 21:30:38 +0000290// struct to store state of go bazel targets
291// this implements bp2buildModule interface and is passed to generateBazelTargets
292type goBazelTarget struct {
293 targetName string
294 targetPackage string
295 bazelRuleClass string
296 bazelRuleLoadLocation string
297 bazelAttributes []interface{}
298}
299
300var _ bp2buildModule = (*goBazelTarget)(nil)
301
302func (g goBazelTarget) TargetName() string {
303 return g.targetName
304}
305
306func (g goBazelTarget) TargetPackage() string {
307 return g.targetPackage
308}
309
310func (g goBazelTarget) BazelRuleClass() string {
311 return g.bazelRuleClass
312}
313
314func (g goBazelTarget) BazelRuleLoadLocation() string {
315 return g.bazelRuleLoadLocation
316}
317
318func (g goBazelTarget) BazelAttributes() []interface{} {
319 return g.bazelAttributes
320}
321
322// Creates a target_compatible_with entry that is *not* compatible with android
323func targetNotCompatibleWithAndroid() bazel.LabelListAttribute {
324 ret := bazel.LabelListAttribute{}
325 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsAndroid,
326 bazel.MakeLabelList(
327 []bazel.Label{
328 bazel.Label{
329 Label: "@platforms//:incompatible",
330 },
331 },
332 ),
333 )
334 return ret
335}
336
337// helper function to return labels for srcs used in bootstrap_go_package and bootstrap_go_binary
338// this function has the following limitations which make it unsuitable for widespread use
Spandan Das0a8a2752023-06-21 01:50:33 +0000339// - wildcard patterns in srcs
340// This is ok for go since build/blueprint does not support it.
Spandan Dasea2abba2023-06-14 21:30:38 +0000341//
342// Prefer to use `BazelLabelForModuleSrc` instead
Spandan Das0a8a2752023-06-21 01:50:33 +0000343func goSrcLabels(cfg android.Config, moduleDir string, srcs []string, linuxSrcs, darwinSrcs []string) bazel.LabelListAttribute {
Spandan Dasea2abba2023-06-14 21:30:38 +0000344 labels := func(srcs []string) bazel.LabelList {
345 ret := []bazel.Label{}
346 for _, src := range srcs {
347 srcLabel := bazel.Label{
Spandan Das0a8a2752023-06-21 01:50:33 +0000348 Label: src,
Spandan Dasea2abba2023-06-14 21:30:38 +0000349 }
350 ret = append(ret, srcLabel)
351 }
Spandan Das0a8a2752023-06-21 01:50:33 +0000352 // Respect package boundaries
353 return android.TransformSubpackagePaths(
354 cfg,
355 moduleDir,
356 bazel.MakeLabelList(ret),
357 )
Spandan Dasea2abba2023-06-14 21:30:38 +0000358 }
359
360 ret := bazel.LabelListAttribute{}
361 // common
362 ret.SetSelectValue(bazel.NoConfigAxis, "", labels(srcs))
363 // linux
364 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsLinux, labels(linuxSrcs))
365 // darwin
366 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsDarwin, labels(darwinSrcs))
367 return ret
368}
369
370func goDepLabels(deps []string, goModulesMap nameToGoLibraryModule) bazel.LabelListAttribute {
371 labels := []bazel.Label{}
372 for _, dep := range deps {
373 moduleDir := goModulesMap[dep].Dir
374 if moduleDir == "." {
375 moduleDir = ""
376 }
377 label := bazel.Label{
378 Label: fmt.Sprintf("//%s:%s", moduleDir, dep),
379 }
380 labels = append(labels, label)
381 }
382 return bazel.MakeLabelListAttribute(bazel.MakeLabelList(labels))
383}
384
385// attributes common to blueprint_go_binary and bootstap_go_package
386type goAttributes struct {
387 Importpath bazel.StringAttribute
388 Srcs bazel.LabelListAttribute
389 Deps bazel.LabelListAttribute
Spandan Das682e7862023-06-22 22:22:11 +0000390 Data bazel.LabelListAttribute
Spandan Dasea2abba2023-06-14 21:30:38 +0000391 Target_compatible_with bazel.LabelListAttribute
Spandan Das682e7862023-06-22 22:22:11 +0000392
393 // attributes for the dynamically generated go_test target
394 Embed bazel.LabelListAttribute
Spandan Dasea2abba2023-06-14 21:30:38 +0000395}
396
Spandan Das682e7862023-06-22 22:22:11 +0000397type goTestProperties struct {
398 name string
399 dir string
400 testSrcs []string
401 linuxTestSrcs []string
402 darwinTestSrcs []string
403 testData []string
404 // Name of the target that should be compiled together with the test
405 embedName string
406}
407
408// Creates a go_test target for bootstrap_go_package / blueprint_go_binary
409func generateBazelTargetsGoTest(ctx *android.Context, goModulesMap nameToGoLibraryModule, gp goTestProperties) (BazelTarget, error) {
410 ca := android.CommonAttributes{
411 Name: gp.name,
412 }
413 ga := goAttributes{
414 Srcs: goSrcLabels(ctx.Config(), gp.dir, gp.testSrcs, gp.linuxTestSrcs, gp.darwinTestSrcs),
415 Data: goSrcLabels(ctx.Config(), gp.dir, gp.testData, []string{}, []string{}),
416 Embed: bazel.MakeLabelListAttribute(
417 bazel.MakeLabelList(
418 []bazel.Label{bazel.Label{Label: ":" + gp.embedName}},
419 ),
420 ),
421 Target_compatible_with: targetNotCompatibleWithAndroid(),
422 }
423
424 libTest := goBazelTarget{
425 targetName: gp.name,
426 targetPackage: gp.dir,
427 bazelRuleClass: "go_test",
428 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
429 bazelAttributes: []interface{}{&ca, &ga},
430 }
431 return generateBazelTarget(ctx, libTest)
432}
433
434// TODO - b/288491147: testSrcs of certain bootstrap_go_package/blueprint_go_binary are not hermetic and depend on
435// testdata checked into the filesystem.
436// Denylist the generation of go_test targets for these Soong modules.
437// The go_library/go_binary will still be generated, since those are hermitic.
438var (
439 goTestsDenylist = []string{
440 "android-archive-zip",
441 "bazel_notice_gen",
442 "blueprint-bootstrap-bpdoc",
443 "blueprint-microfactory",
444 "blueprint-pathtools",
445 "bssl_ar",
446 "compliance_checkmetadata",
447 "compliance_checkshare",
448 "compliance_dumpgraph",
449 "compliance_dumpresolutions",
450 "compliance_listshare",
451 "compliance-module",
452 "compliancenotice_bom",
453 "compliancenotice_shippedlibs",
454 "compliance_rtrace",
455 "compliance_sbom",
456 "golang-protobuf-internal-fuzz-jsonfuzz",
457 "golang-protobuf-internal-fuzz-textfuzz",
458 "golang-protobuf-internal-fuzz-wirefuzz",
459 "htmlnotice",
460 "protoc-gen-go",
461 "rbcrun-module",
462 "spdx-tools-builder",
463 "spdx-tools-builder2v1",
464 "spdx-tools-builder2v2",
465 "spdx-tools-builder2v3",
466 "spdx-tools-idsearcher",
467 "spdx-tools-spdx-json",
468 "spdx-tools-utils",
469 "soong-ui-build",
470 "textnotice",
471 "xmlnotice",
472 }
473)
474
Spandan Das89aa0f72023-06-30 20:18:39 +0000475func testOfGoPackageIsIncompatible(g *bootstrap.GoPackage) bool {
476 return android.InList(g.Name(), goTestsDenylist) ||
477 // Denylist tests of soong_build
478 // Theses tests have a guard that prevent usage outside a test environment
479 // The guard (`ensureTestOnly`) looks for a `-test` in os.Args, which is present in soong's gotestrunner, but missing in `b test`
480 g.IsPluginFor("soong_build") ||
481 // soong-android is a dep of soong_build
482 // This dependency is created by soong_build by listing it in its deps explicitly in Android.bp, and not via `plugin_for` in `soong-android`
483 g.Name() == "soong-android"
484}
485
486func testOfGoBinaryIsIncompatible(g *bootstrap.GoBinary) bool {
487 return android.InList(g.Name(), goTestsDenylist)
488}
489
Spandan Dasea2abba2023-06-14 21:30:38 +0000490func generateBazelTargetsGoPackage(ctx *android.Context, g *bootstrap.GoPackage, goModulesMap nameToGoLibraryModule) ([]BazelTarget, []error) {
491 ca := android.CommonAttributes{
492 Name: g.Name(),
493 }
Spandan Dasde623292023-06-14 21:30:38 +0000494
495 // For this bootstrap_go_package dep chain,
496 // A --> B --> C ( ---> depends on)
497 // Soong provides the convenience of only listing B as deps of A even if a src file of A imports C
498 // Bazel OTOH
499 // 1. requires C to be listed in `deps` expllicity.
500 // 2. does not require C to be listed if src of A does not import C
501 //
502 // bp2build does not have sufficient info on whether C is a direct dep of A or not, so for now collect all transitive deps and add them to deps
503 transitiveDeps := transitiveGoDeps(g.Deps(), goModulesMap)
504
Spandan Dasea2abba2023-06-14 21:30:38 +0000505 ga := goAttributes{
506 Importpath: bazel.StringAttribute{
507 Value: proptools.StringPtr(g.GoPkgPath()),
508 },
Spandan Das0a8a2752023-06-21 01:50:33 +0000509 Srcs: goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs()),
510 Deps: goDepLabels(
511 android.FirstUniqueStrings(transitiveDeps),
512 goModulesMap,
513 ),
Spandan Dasea2abba2023-06-14 21:30:38 +0000514 Target_compatible_with: targetNotCompatibleWithAndroid(),
515 }
516
517 lib := goBazelTarget{
518 targetName: g.Name(),
519 targetPackage: ctx.ModuleDir(g),
520 bazelRuleClass: "go_library",
521 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
522 bazelAttributes: []interface{}{&ca, &ga},
523 }
Spandan Das682e7862023-06-22 22:22:11 +0000524 retTargets := []BazelTarget{}
525 var retErrs []error
526 if libTarget, err := generateBazelTarget(ctx, lib); err == nil {
527 retTargets = append(retTargets, libTarget)
528 } else {
529 retErrs = []error{err}
Spandan Dasea2abba2023-06-14 21:30:38 +0000530 }
Spandan Das682e7862023-06-22 22:22:11 +0000531
532 // If the library contains test srcs, create an additional go_test target
Spandan Das89aa0f72023-06-30 20:18:39 +0000533 if !testOfGoPackageIsIncompatible(g) && (len(g.TestSrcs()) > 0 || len(g.LinuxTestSrcs()) > 0 || len(g.DarwinTestSrcs()) > 0) {
Spandan Das682e7862023-06-22 22:22:11 +0000534 gp := goTestProperties{
535 name: g.Name() + "-test",
536 dir: ctx.ModuleDir(g),
537 testSrcs: g.TestSrcs(),
538 linuxTestSrcs: g.LinuxTestSrcs(),
539 darwinTestSrcs: g.DarwinTestSrcs(),
540 testData: g.TestData(),
541 embedName: g.Name(), // embed the source go_library in the test so that its .go files are included in the compilation unit
542 }
543 if libTestTarget, err := generateBazelTargetsGoTest(ctx, goModulesMap, gp); err == nil {
544 retTargets = append(retTargets, libTestTarget)
545 } else {
546 retErrs = append(retErrs, err)
547 }
548 }
549
550 return retTargets, retErrs
Spandan Dasea2abba2023-06-14 21:30:38 +0000551}
552
553type goLibraryModule struct {
554 Dir string
555 Deps []string
556}
557
558type nameToGoLibraryModule map[string]goLibraryModule
559
560// Visit each module in the graph
561// If a module is of type `bootstrap_go_package`, return a map containing metadata like its dir and deps
562func createGoLibraryModuleMap(ctx *android.Context) nameToGoLibraryModule {
563 ret := nameToGoLibraryModule{}
564 ctx.VisitAllModules(func(m blueprint.Module) {
565 moduleType := ctx.ModuleType(m)
566 // We do not need to store information about blueprint_go_binary since it does not have any rdeps
567 if moduleType == "bootstrap_go_package" {
568 ret[m.Name()] = goLibraryModule{
569 Dir: ctx.ModuleDir(m),
570 Deps: m.(*bootstrap.GoPackage).Deps(),
571 }
572 }
573 })
574 return ret
575}
576
Spandan Dasde623292023-06-14 21:30:38 +0000577// Returns the deps in the transitive closure of a go target
578func transitiveGoDeps(directDeps []string, goModulesMap nameToGoLibraryModule) []string {
579 allDeps := directDeps
580 i := 0
581 for i < len(allDeps) {
582 curr := allDeps[i]
583 allDeps = append(allDeps, goModulesMap[curr].Deps...)
584 i += 1
585 }
586 allDeps = android.SortedUniqueStrings(allDeps)
587 return allDeps
588}
589
590func generateBazelTargetsGoBinary(ctx *android.Context, g *bootstrap.GoBinary, goModulesMap nameToGoLibraryModule) ([]BazelTarget, []error) {
591 ca := android.CommonAttributes{
592 Name: g.Name(),
593 }
594
Spandan Das682e7862023-06-22 22:22:11 +0000595 retTargets := []BazelTarget{}
596 var retErrs []error
597
Spandan Dasde623292023-06-14 21:30:38 +0000598 // For this bootstrap_go_package dep chain,
599 // A --> B --> C ( ---> depends on)
600 // Soong provides the convenience of only listing B as deps of A even if a src file of A imports C
601 // Bazel OTOH
602 // 1. requires C to be listed in `deps` expllicity.
603 // 2. does not require C to be listed if src of A does not import C
604 //
605 // bp2build does not have sufficient info on whether C is a direct dep of A or not, so for now collect all transitive deps and add them to deps
606 transitiveDeps := transitiveGoDeps(g.Deps(), goModulesMap)
607
Spandan Das682e7862023-06-22 22:22:11 +0000608 goSource := ""
609 // If the library contains test srcs, create an additional go_test target
610 // The go_test target will embed a go_source containining the source .go files it tests
Spandan Das89aa0f72023-06-30 20:18:39 +0000611 if !testOfGoBinaryIsIncompatible(g) && (len(g.TestSrcs()) > 0 || len(g.LinuxTestSrcs()) > 0 || len(g.DarwinTestSrcs()) > 0) {
Spandan Das682e7862023-06-22 22:22:11 +0000612 // Create a go_source containing the source .go files of go_library
613 // This target will be an `embed` of the go_binary and go_test
614 goSource = g.Name() + "-source"
615 ca := android.CommonAttributes{
616 Name: goSource,
617 }
618 ga := goAttributes{
619 Srcs: goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs()),
620 Deps: goDepLabels(transitiveDeps, goModulesMap),
621 Target_compatible_with: targetNotCompatibleWithAndroid(),
622 }
623 libTestSource := goBazelTarget{
624 targetName: goSource,
625 targetPackage: ctx.ModuleDir(g),
626 bazelRuleClass: "go_source",
627 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
628 bazelAttributes: []interface{}{&ca, &ga},
629 }
630 if libSourceTarget, err := generateBazelTarget(ctx, libTestSource); err == nil {
631 retTargets = append(retTargets, libSourceTarget)
632 } else {
633 retErrs = append(retErrs, err)
634 }
635
636 // Create a go_test target
637 gp := goTestProperties{
638 name: g.Name() + "-test",
639 dir: ctx.ModuleDir(g),
640 testSrcs: g.TestSrcs(),
641 linuxTestSrcs: g.LinuxTestSrcs(),
642 darwinTestSrcs: g.DarwinTestSrcs(),
643 testData: g.TestData(),
644 // embed the go_source in the test
645 embedName: g.Name() + "-source",
646 }
647 if libTestTarget, err := generateBazelTargetsGoTest(ctx, goModulesMap, gp); err == nil {
648 retTargets = append(retTargets, libTestTarget)
649 } else {
650 retErrs = append(retErrs, err)
651 }
652
653 }
654
655 // Create a go_binary target
Spandan Dasde623292023-06-14 21:30:38 +0000656 ga := goAttributes{
Spandan Dasde623292023-06-14 21:30:38 +0000657 Deps: goDepLabels(transitiveDeps, goModulesMap),
658 Target_compatible_with: targetNotCompatibleWithAndroid(),
659 }
660
Spandan Das682e7862023-06-22 22:22:11 +0000661 // If the binary has testSrcs, embed the common `go_source`
662 if goSource != "" {
663 ga.Embed = bazel.MakeLabelListAttribute(
664 bazel.MakeLabelList(
665 []bazel.Label{bazel.Label{Label: ":" + goSource}},
666 ),
667 )
668 } else {
669 ga.Srcs = goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs())
670 }
671
Spandan Dasde623292023-06-14 21:30:38 +0000672 bin := goBazelTarget{
673 targetName: g.Name(),
674 targetPackage: ctx.ModuleDir(g),
675 bazelRuleClass: "go_binary",
676 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
677 bazelAttributes: []interface{}{&ca, &ga},
678 }
Spandan Das682e7862023-06-22 22:22:11 +0000679
680 if binTarget, err := generateBazelTarget(ctx, bin); err == nil {
681 retTargets = append(retTargets, binTarget)
682 } else {
683 retErrs = []error{err}
Spandan Dasde623292023-06-14 21:30:38 +0000684 }
Spandan Das682e7862023-06-22 22:22:11 +0000685
686 return retTargets, retErrs
Spandan Dasde623292023-06-14 21:30:38 +0000687}
688
Liz Kammer6eff3232021-08-26 08:37:59 -0400689func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (conversionResults, []error) {
ustaaaf2fd12023-07-01 11:40:36 -0400690 ctx.Context().BeginEvent("GenerateBazelTargets")
691 defer ctx.Context().EndEvent("GenerateBazelTargets")
Jingwen Chen40067de2021-01-26 21:58:43 -0500692 buildFileToTargets := make(map[string]BazelTargets)
Jingwen Chen164e0862021-02-19 00:48:40 -0500693
694 // Simple metrics tracking for bp2build
usta4f5d2c12022-10-28 23:32:01 -0400695 metrics := CreateCodegenMetrics()
Jingwen Chen164e0862021-02-19 00:48:40 -0500696
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400697 dirs := make(map[string]bool)
698
Liz Kammer6eff3232021-08-26 08:37:59 -0400699 var errs []error
700
Spandan Dasea2abba2023-06-14 21:30:38 +0000701 // Visit go libraries in a pre-run and store its state in a map
702 // The time complexity remains O(N), and this does not add significant wall time.
703 nameToGoLibMap := createGoLibraryModuleMap(ctx.Context())
704
Jingwen Chen164e0862021-02-19 00:48:40 -0500705 bpCtx := ctx.Context()
706 bpCtx.VisitAllModules(func(m blueprint.Module) {
707 dir := bpCtx.ModuleDir(m)
Chris Parsons492bd912022-01-20 12:55:05 -0500708 moduleType := bpCtx.ModuleType(m)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400709 dirs[dir] = true
710
Liz Kammer2ada09a2021-08-11 00:17:36 -0400711 var targets []BazelTarget
Spandan Dasea2abba2023-06-14 21:30:38 +0000712 var targetErrs []error
Jingwen Chen73850672020-12-14 08:25:34 -0500713
Jingwen Chen164e0862021-02-19 00:48:40 -0500714 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500715 case Bp2Build:
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000716 // There are two main ways of converting a Soong module to Bazel:
717 // 1) Manually handcrafting a Bazel target and associating the module with its label
718 // 2) Automatically generating with bp2build converters
719 //
720 // bp2build converters are used for the majority of modules.
Liz Kammerba3ea162021-02-17 13:22:03 -0500721 if b, ok := m.(android.Bazelable); ok && b.HasHandcraftedLabel() {
Liz Kammerc86e0942023-08-11 16:15:12 -0400722 if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
723 panic(fmt.Errorf("module %q [%s] [%s] was both converted with bp2build and has a handcrafted label", bpCtx.ModuleName(m), moduleType, dir))
724 }
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000725 // Handle modules converted to handcrafted targets.
726 //
727 // Since these modules are associated with some handcrafted
Cole Faustea602c52022-08-31 14:48:26 -0700728 // target in a BUILD file, we don't autoconvert them.
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000729
730 // Log the module.
Chris Parsons39a16972023-06-08 14:28:51 +0000731 metrics.AddUnconvertedModule(m, moduleType, dir,
732 android.UnconvertedReason{
733 ReasonType: int(bp2build_metrics_proto.UnconvertedReasonType_DEFINED_IN_BUILD_FILE),
734 })
Liz Kammer2ada09a2021-08-11 00:17:36 -0400735 } else if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000736 // Handle modules converted to generated targets.
737
738 // Log the module.
Chris Parsons39a16972023-06-08 14:28:51 +0000739 metrics.AddConvertedModule(aModule, moduleType, dir)
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000740
741 // Handle modules with unconverted deps. By default, emit a warning.
Liz Kammer6eff3232021-08-26 08:37:59 -0400742 if unconvertedDeps := aModule.GetUnconvertedBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700743 msg := fmt.Sprintf("%s %s:%s depends on unconverted modules: %s",
744 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400745 switch ctx.unconvertedDepMode {
746 case warnUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400747 metrics.moduleWithUnconvertedDepsMsgs = append(metrics.moduleWithUnconvertedDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400748 case errorModulesUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400749 errs = append(errs, fmt.Errorf(msg))
750 return
751 }
752 }
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500753 if unconvertedDeps := aModule.GetMissingBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700754 msg := fmt.Sprintf("%s %s:%s depends on missing modules: %s",
755 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400756 switch ctx.unconvertedDepMode {
757 case warnUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500758 metrics.moduleWithMissingDepsMsgs = append(metrics.moduleWithMissingDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400759 case errorModulesUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500760 errs = append(errs, fmt.Errorf(msg))
761 return
762 }
763 }
Alix94e26032022-08-16 20:37:33 +0000764 targets, targetErrs = generateBazelTargets(bpCtx, aModule)
765 errs = append(errs, targetErrs...)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400766 for _, t := range targets {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000767 // A module can potentially generate more than 1 Bazel
768 // target, each of a different rule class.
769 metrics.IncrementRuleClassCount(t.ruleClass)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400770 }
MarkDacek9c094ca2023-03-16 19:15:19 +0000771 } else if _, ok := ctx.Config().BazelModulesForceEnabledByFlag()[m.Name()]; ok && m.Name() != "" {
772 err := fmt.Errorf("Force Enabled Module %s not converted", m.Name())
773 errs = append(errs, err)
Chris Parsons39a16972023-06-08 14:28:51 +0000774 } else if aModule, ok := m.(android.Module); ok {
775 reason := aModule.GetUnconvertedReason()
776 if reason == nil {
777 panic(fmt.Errorf("module '%s' was neither converted nor marked unconvertible with bp2build", aModule.Name()))
778 } else {
779 metrics.AddUnconvertedModule(m, moduleType, dir, *reason)
780 }
781 return
Spandan Dasea2abba2023-06-14 21:30:38 +0000782 } else if glib, ok := m.(*bootstrap.GoPackage); ok {
783 targets, targetErrs = generateBazelTargetsGoPackage(bpCtx, glib, nameToGoLibMap)
784 errs = append(errs, targetErrs...)
785 metrics.IncrementRuleClassCount("go_library")
Spandan Das41f1eee2023-08-01 22:28:16 +0000786 metrics.AddConvertedModule(glib, "go_library", dir)
Spandan Das2a55cea2023-06-14 17:56:10 +0000787 } else if gbin, ok := m.(*bootstrap.GoBinary); ok {
Spandan Dasde623292023-06-14 21:30:38 +0000788 targets, targetErrs = generateBazelTargetsGoBinary(bpCtx, gbin, nameToGoLibMap)
789 errs = append(errs, targetErrs...)
790 metrics.IncrementRuleClassCount("go_binary")
Spandan Das41f1eee2023-08-01 22:28:16 +0000791 metrics.AddConvertedModule(gbin, "go_binary", dir)
Liz Kammerfc46bc12021-02-19 11:06:17 -0500792 } else {
Chris Parsons39a16972023-06-08 14:28:51 +0000793 metrics.AddUnconvertedModule(m, moduleType, dir, android.UnconvertedReason{
794 ReasonType: int(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED),
795 })
Liz Kammerba3ea162021-02-17 13:22:03 -0500796 return
Jingwen Chen73850672020-12-14 08:25:34 -0500797 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500798 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500799 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500800 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500801 // package module name contain slashes, and thus cannot
802 // be mapped cleanly to a bazel label.
803 return
804 }
Alix94e26032022-08-16 20:37:33 +0000805 t, err := generateSoongModuleTarget(bpCtx, m)
806 if err != nil {
807 errs = append(errs, err)
808 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400809 targets = append(targets, t)
Jingwen Chen33832f92021-01-24 22:55:54 -0500810 default:
Liz Kammer6eff3232021-08-26 08:37:59 -0400811 errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
812 return
Jingwen Chen73850672020-12-14 08:25:34 -0500813 }
814
Spandan Dasabedff02023-03-07 19:24:34 +0000815 for _, target := range targets {
816 targetDir := target.PackageName()
817 buildFileToTargets[targetDir] = append(buildFileToTargets[targetDir], target)
818 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800819 })
Liz Kammer6eff3232021-08-26 08:37:59 -0400820
821 if len(errs) > 0 {
822 return conversionResults{}, errs
823 }
824
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400825 if generateFilegroups {
826 // Add a filegroup target that exposes all sources in the subtree of this package
827 // 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 -0700828 //
829 // This works because: https://bazel.build/reference/be/functions#exports_files
830 // "As a legacy behaviour, also files mentioned as input to a rule are exported with the
831 // default visibility until the flag --incompatible_no_implicit_file_export is flipped. However, this behavior
832 // should not be relied upon and actively migrated away from."
833 //
834 // TODO(b/198619163): We should change this to export_files(glob(["**/*"])) instead, but doing that causes these errors:
835 // "Error in exports_files: generated label '//external/avb:avbtool' conflicts with existing py_binary rule"
836 // So we need to solve all the "target ... is both a rule and a file" warnings first.
Usta Shresthac6057152022-09-24 00:23:31 -0400837 for dir := range dirs {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400838 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
839 name: "bp2build_all_srcs",
Jingwen Chen5802d072023-09-20 10:25:09 +0000840 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]), tags = ["manual"])`,
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400841 ruleClass: "filegroup",
842 })
843 }
844 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500845
Liz Kammer6eff3232021-08-26 08:37:59 -0400846 return conversionResults{
847 buildFileToTargets: buildFileToTargets,
848 metrics: metrics,
Liz Kammer6eff3232021-08-26 08:37:59 -0400849 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500850}
851
Alix94e26032022-08-16 20:37:33 +0000852func generateBazelTargets(ctx bpToBuildContext, m android.Module) ([]BazelTarget, []error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400853 var targets []BazelTarget
Alix94e26032022-08-16 20:37:33 +0000854 var errs []error
Liz Kammer2ada09a2021-08-11 00:17:36 -0400855 for _, m := range m.Bp2buildTargets() {
Alix94e26032022-08-16 20:37:33 +0000856 target, err := generateBazelTarget(ctx, m)
857 if err != nil {
858 errs = append(errs, err)
859 return targets, errs
860 }
861 targets = append(targets, target)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400862 }
Alix94e26032022-08-16 20:37:33 +0000863 return targets, errs
Liz Kammer2ada09a2021-08-11 00:17:36 -0400864}
865
866type bp2buildModule interface {
867 TargetName() string
868 TargetPackage() string
869 BazelRuleClass() string
870 BazelRuleLoadLocation() string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000871 BazelAttributes() []interface{}
Liz Kammer2ada09a2021-08-11 00:17:36 -0400872}
873
Alix94e26032022-08-16 20:37:33 +0000874func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) (BazelTarget, error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400875 ruleClass := m.BazelRuleClass()
876 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500877
Jingwen Chen73850672020-12-14 08:25:34 -0500878 // extract the bazel attributes from the module.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000879 attrs := m.BazelAttributes()
Alix94e26032022-08-16 20:37:33 +0000880 props, err := extractModuleProperties(attrs, true)
881 if err != nil {
882 return BazelTarget{}, err
883 }
Jingwen Chen73850672020-12-14 08:25:34 -0500884
Liz Kammer0eae52e2021-10-06 10:32:26 -0400885 // name is handled in a special manner
886 delete(props.Attrs, "name")
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500887
Jingwen Chen73850672020-12-14 08:25:34 -0500888 // Return the Bazel target with rule class and attributes, ready to be
889 // code-generated.
890 attributes := propsToAttributes(props.Attrs)
Sasha Smundakfb589492022-08-04 11:13:27 -0700891 var content string
Liz Kammer2ada09a2021-08-11 00:17:36 -0400892 targetName := m.TargetName()
Sasha Smundakfb589492022-08-04 11:13:27 -0700893 if targetName != "" {
894 content = fmt.Sprintf(ruleTargetTemplate, ruleClass, targetName, attributes)
895 } else {
896 content = fmt.Sprintf(unnamedRuleTargetTemplate, ruleClass, attributes)
897 }
Cole Faustb4cb0c82023-09-14 15:16:58 -0700898 var loads []BazelLoad
899 if bzlLoadLocation != "" {
900 loads = append(loads, BazelLoad{
901 file: bzlLoadLocation,
902 symbols: []BazelLoadSymbol{{symbol: ruleClass}},
903 })
904 }
Jingwen Chen73850672020-12-14 08:25:34 -0500905 return BazelTarget{
Cole Faustb4cb0c82023-09-14 15:16:58 -0700906 name: targetName,
907 packageName: m.TargetPackage(),
908 ruleClass: ruleClass,
909 loads: loads,
910 content: content,
Alix94e26032022-08-16 20:37:33 +0000911 }, nil
Jingwen Chen73850672020-12-14 08:25:34 -0500912}
913
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800914// Convert a module and its deps and props into a Bazel macro/rule
915// representation in the BUILD file.
Alix94e26032022-08-16 20:37:33 +0000916func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) (BazelTarget, error) {
917 props, err := getBuildProperties(ctx, m)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800918
919 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
920 // items, if the modules are added using different DependencyTag. Figure
921 // out the implications of that.
922 depLabels := map[string]bool{}
923 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500924 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800925 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
926 })
927 }
Liz Kammer0eae52e2021-10-06 10:32:26 -0400928
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400929 for p := range ignoredPropNames {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400930 delete(props.Attrs, p)
931 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800932 attributes := propsToAttributes(props.Attrs)
933
934 depLabelList := "[\n"
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400935 for depLabel := range depLabels {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800936 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
937 }
938 depLabelList += " ]"
939
940 targetName := targetNameWithVariant(ctx, m)
941 return BazelTarget{
Spandan Dasabedff02023-03-07 19:24:34 +0000942 name: targetName,
943 packageName: ctx.ModuleDir(m),
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800944 content: fmt.Sprintf(
Sasha Smundakfb589492022-08-04 11:13:27 -0700945 soongModuleTargetTemplate,
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800946 targetName,
947 ctx.ModuleName(m),
948 canonicalizeModuleType(ctx.ModuleType(m)),
949 ctx.ModuleSubDir(m),
950 depLabelList,
951 attributes),
Alix94e26032022-08-16 20:37:33 +0000952 }, err
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800953}
954
Alix94e26032022-08-16 20:37:33 +0000955func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800956 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
957 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
958 if aModule, ok := m.(android.Module); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000959 return extractModuleProperties(aModule.GetProperties(), false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800960 }
961
Alix94e26032022-08-16 20:37:33 +0000962 return BazelAttributes{}, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800963}
964
965// Generically extract module properties and types into a map, keyed by the module property name.
Alix94e26032022-08-16 20:37:33 +0000966func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800967 ret := map[string]string{}
968
969 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400970 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800971 propertiesValue := reflect.ValueOf(properties)
972 // Check that propertiesValue is a pointer to the Properties struct, like
973 // *cc.BaseLinkerProperties or *java.CompilerProperties.
974 //
975 // propertiesValue can also be type-asserted to the structs to
976 // manipulate internal props, if needed.
977 if isStructPtr(propertiesValue.Type()) {
978 structValue := propertiesValue.Elem()
Alix94e26032022-08-16 20:37:33 +0000979 ok, err := extractStructProperties(structValue, 0)
980 if err != nil {
981 return BazelAttributes{}, err
982 }
983 for k, v := range ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000984 if existing, exists := ret[k]; checkForDuplicateProperties && exists {
Alix94e26032022-08-16 20:37:33 +0000985 return BazelAttributes{}, fmt.Errorf(
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000986 "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes",
Alix94e26032022-08-16 20:37:33 +0000987 k, existing)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000988 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800989 ret[k] = v
990 }
991 } else {
Alix94e26032022-08-16 20:37:33 +0000992 return BazelAttributes{},
993 fmt.Errorf(
994 "properties must be a pointer to a struct, got %T",
995 propertiesValue.Interface())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800996 }
997 }
998
Liz Kammer2ada09a2021-08-11 00:17:36 -0400999 return BazelAttributes{
1000 Attrs: ret,
Alix94e26032022-08-16 20:37:33 +00001001 }, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001002}
1003
1004func isStructPtr(t reflect.Type) bool {
1005 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
1006}
1007
1008// prettyPrint a property value into the equivalent Starlark representation
1009// recursively.
Jingwen Chen58ff6802021-11-17 12:14:41 +00001010func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) {
1011 if !emitZeroValues && isZero(propertyValue) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001012 // A property value being set or unset actually matters -- Soong does set default
1013 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
1014 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
1015 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +00001016 // In Bazel-parlance, we would use "attr.<type>(default = <default
1017 // value>)" to set the default value of unset attributes. In the cases
1018 // where the bp2build converter didn't set the default value within the
1019 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -04001020 // value. For those cases, we return an empty string so we don't
1021 // unnecessarily generate empty values.
1022 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001023 }
1024
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001025 switch propertyValue.Kind() {
1026 case reflect.String:
Liz Kammer72beb342022-02-03 08:42:10 -05001027 return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001028 case reflect.Bool:
Liz Kammer72beb342022-02-03 08:42:10 -05001029 return starlark_fmt.PrintBool(propertyValue.Bool()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001030 case reflect.Int, reflect.Uint, reflect.Int64:
Liz Kammer72beb342022-02-03 08:42:10 -05001031 return fmt.Sprintf("%v", propertyValue.Interface()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001032 case reflect.Ptr:
Jingwen Chen58ff6802021-11-17 12:14:41 +00001033 return prettyPrint(propertyValue.Elem(), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001034 case reflect.Slice:
Liz Kammer72beb342022-02-03 08:42:10 -05001035 elements := make([]string, 0, propertyValue.Len())
1036 for i := 0; i < propertyValue.Len(); i++ {
1037 val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001038 if err != nil {
1039 return "", err
1040 }
Liz Kammer72beb342022-02-03 08:42:10 -05001041 if val != "" {
1042 elements = append(elements, val)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001043 }
1044 }
Sam Delmerico932c01c2022-03-25 16:33:26 +00001045 return starlark_fmt.PrintList(elements, indent, func(s string) string {
1046 return "%s"
1047 }), nil
Jingwen Chenb4628eb2021-04-08 14:40:57 +00001048
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001049 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -05001050 // Special cases where the bp2build sends additional information to the codegenerator
1051 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +00001052 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
1053 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -05001054 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
1055 return fmt.Sprintf("%q", label.Label), nil
1056 }
1057
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001058 // Sort and print the struct props by the key.
Alix94e26032022-08-16 20:37:33 +00001059 structProps, err := extractStructProperties(propertyValue, indent)
1060
1061 if err != nil {
1062 return "", err
1063 }
1064
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001065 if len(structProps) == 0 {
1066 return "", nil
1067 }
Liz Kammer72beb342022-02-03 08:42:10 -05001068 return starlark_fmt.PrintDict(structProps, indent), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001069 case reflect.Interface:
1070 // TODO(b/164227191): implement pretty print for interfaces.
1071 // Interfaces are used for for arch, multilib and target properties.
1072 return "", nil
Spandan Das6a448ec2023-04-19 17:36:12 +00001073 case reflect.Map:
1074 if v, ok := propertyValue.Interface().(bazel.StringMapAttribute); ok {
1075 return starlark_fmt.PrintStringStringDict(v, indent), nil
1076 }
1077 return "", fmt.Errorf("bp2build expects map of type map[string]string for field: %s", propertyValue)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001078 default:
1079 return "", fmt.Errorf(
1080 "unexpected kind for property struct field: %s", propertyValue.Kind())
1081 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001082}
1083
1084// Converts a reflected property struct value into a map of property names and property values,
1085// which each property value correctly pretty-printed and indented at the right nest level,
1086// since property structs can be nested. In Starlark, nested structs are represented as nested
1087// dicts: https://docs.bazel.build/skylark/lib/dict.html
Alix94e26032022-08-16 20:37:33 +00001088func extractStructProperties(structValue reflect.Value, indent int) (map[string]string, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001089 if structValue.Kind() != reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001090 return map[string]string{}, fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind())
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001091 }
1092
Alix94e26032022-08-16 20:37:33 +00001093 var err error
1094
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001095 ret := map[string]string{}
1096 structType := structValue.Type()
1097 for i := 0; i < structValue.NumField(); i++ {
1098 field := structType.Field(i)
1099 if shouldSkipStructField(field) {
1100 continue
1101 }
1102
1103 fieldValue := structValue.Field(i)
1104 if isZero(fieldValue) {
1105 // Ignore zero-valued fields
1106 continue
1107 }
Liz Kammer7a210ac2021-09-22 15:52:58 -04001108
Liz Kammer32a03392021-09-14 11:17:21 -04001109 // if the struct is embedded (anonymous), flatten the properties into the containing struct
1110 if field.Anonymous {
1111 if field.Type.Kind() == reflect.Ptr {
1112 fieldValue = fieldValue.Elem()
1113 }
1114 if fieldValue.Type().Kind() == reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001115 propsToMerge, err := extractStructProperties(fieldValue, indent)
1116 if err != nil {
1117 return map[string]string{}, err
1118 }
Liz Kammer32a03392021-09-14 11:17:21 -04001119 for prop, value := range propsToMerge {
1120 ret[prop] = value
1121 }
1122 continue
1123 }
1124 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001125
1126 propertyName := proptools.PropertyNameForField(field.Name)
Alix94e26032022-08-16 20:37:33 +00001127 var prettyPrintedValue string
1128 prettyPrintedValue, err = prettyPrint(fieldValue, indent+1, false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001129 if err != nil {
Alix94e26032022-08-16 20:37:33 +00001130 return map[string]string{}, fmt.Errorf(
1131 "Error while parsing property: %q. %s",
1132 propertyName,
1133 err)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001134 }
1135 if prettyPrintedValue != "" {
1136 ret[propertyName] = prettyPrintedValue
1137 }
1138 }
1139
Alix94e26032022-08-16 20:37:33 +00001140 return ret, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001141}
1142
1143func isZero(value reflect.Value) bool {
1144 switch value.Kind() {
1145 case reflect.Func, reflect.Map, reflect.Slice:
1146 return value.IsNil()
1147 case reflect.Array:
1148 valueIsZero := true
1149 for i := 0; i < value.Len(); i++ {
1150 valueIsZero = valueIsZero && isZero(value.Index(i))
1151 }
1152 return valueIsZero
1153 case reflect.Struct:
1154 valueIsZero := true
1155 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +02001156 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001157 }
1158 return valueIsZero
1159 case reflect.Ptr:
1160 if !value.IsNil() {
1161 return isZero(reflect.Indirect(value))
1162 } else {
1163 return true
1164 }
Liz Kammer46fb7ab2021-12-01 10:09:34 -05001165 // Always print bool/strings, if you want a bool/string attribute to be able to take the default value, use a
1166 // pointer instead
1167 case reflect.Bool, reflect.String:
Liz Kammerd366c902021-06-03 13:43:01 -04001168 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001169 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -04001170 if !value.IsValid() {
1171 return true
1172 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001173 zeroValue := reflect.Zero(value.Type())
1174 result := value.Interface() == zeroValue.Interface()
1175 return result
1176 }
1177}
1178
1179func escapeString(s string) string {
1180 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +00001181
1182 // b/184026959: Reverse the application of some common control sequences.
1183 // These must be generated literally in the BUILD file.
1184 s = strings.ReplaceAll(s, "\t", "\\t")
1185 s = strings.ReplaceAll(s, "\n", "\\n")
1186 s = strings.ReplaceAll(s, "\r", "\\r")
1187
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001188 return strings.ReplaceAll(s, "\"", "\\\"")
1189}
1190
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001191func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
1192 name := ""
1193 if c.ModuleSubDir(logicModule) != "" {
1194 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
1195 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
1196 } else {
1197 name = c.ModuleName(logicModule)
1198 }
1199
1200 return strings.Replace(name, "//", "", 1)
1201}
1202
1203func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
1204 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
1205}