blob: ed6e2dd1c2bf3a1fe614ad75bd1642b152c16af9 [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 Dasaf725832023-09-19 19:51:52 +0000290// struct to store state of b bazel targets (e.g. go targets which do not implement android.Module)
Spandan Dasea2abba2023-06-14 21:30:38 +0000291// this implements bp2buildModule interface and is passed to generateBazelTargets
Spandan Dasaf725832023-09-19 19:51:52 +0000292type bTarget struct {
Spandan Dasea2abba2023-06-14 21:30:38 +0000293 targetName string
294 targetPackage string
295 bazelRuleClass string
296 bazelRuleLoadLocation string
297 bazelAttributes []interface{}
298}
299
Spandan Dasaf725832023-09-19 19:51:52 +0000300var _ bp2buildModule = (*bTarget)(nil)
Spandan Dasea2abba2023-06-14 21:30:38 +0000301
Spandan Dasaf725832023-09-19 19:51:52 +0000302func (b bTarget) TargetName() string {
303 return b.targetName
Spandan Dasea2abba2023-06-14 21:30:38 +0000304}
305
Spandan Dasaf725832023-09-19 19:51:52 +0000306func (b bTarget) TargetPackage() string {
307 return b.targetPackage
Spandan Dasea2abba2023-06-14 21:30:38 +0000308}
309
Spandan Dasaf725832023-09-19 19:51:52 +0000310func (b bTarget) BazelRuleClass() string {
311 return b.bazelRuleClass
Spandan Dasea2abba2023-06-14 21:30:38 +0000312}
313
Spandan Dasaf725832023-09-19 19:51:52 +0000314func (b bTarget) BazelRuleLoadLocation() string {
315 return b.bazelRuleLoadLocation
Spandan Dasea2abba2023-06-14 21:30:38 +0000316}
317
Spandan Dasaf725832023-09-19 19:51:52 +0000318func (b bTarget) BazelAttributes() []interface{} {
319 return b.bazelAttributes
Spandan Dasea2abba2023-06-14 21:30:38 +0000320}
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
Spandan Dasaf725832023-09-19 19:51:52 +0000424 libTest := bTarget{
Spandan Das682e7862023-06-22 22:22:11 +0000425 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
Spandan Dasaf725832023-09-19 19:51:52 +0000517 lib := bTarget{
Spandan Dasea2abba2023-06-14 21:30:38 +0000518 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
Spandan Dasaf725832023-09-19 19:51:52 +0000558type buildConversionMetadata struct {
559 nameToGoLibraryModule nameToGoLibraryModule
560 ndkHeaders []blueprint.Module
561}
562
Spandan Dasea2abba2023-06-14 21:30:38 +0000563type nameToGoLibraryModule map[string]goLibraryModule
564
Spandan Dasaf725832023-09-19 19:51:52 +0000565// Visit each module in the graph, and collect metadata about the build graph
Spandan Dasea2abba2023-06-14 21:30:38 +0000566// If a module is of type `bootstrap_go_package`, return a map containing metadata like its dir and deps
Spandan Dasaf725832023-09-19 19:51:52 +0000567// If a module is of type `ndk_headers`, add it to a list and return the list
568func createBuildConversionMetadata(ctx *android.Context) buildConversionMetadata {
569 goMap := nameToGoLibraryModule{}
570 ndkHeaders := []blueprint.Module{}
Spandan Dasea2abba2023-06-14 21:30:38 +0000571 ctx.VisitAllModules(func(m blueprint.Module) {
572 moduleType := ctx.ModuleType(m)
573 // We do not need to store information about blueprint_go_binary since it does not have any rdeps
574 if moduleType == "bootstrap_go_package" {
Spandan Dasaf725832023-09-19 19:51:52 +0000575 goMap[m.Name()] = goLibraryModule{
Spandan Dasea2abba2023-06-14 21:30:38 +0000576 Dir: ctx.ModuleDir(m),
577 Deps: m.(*bootstrap.GoPackage).Deps(),
578 }
Spandan Dasa7da3f02023-09-28 19:30:51 +0000579 } else if moduleType == "ndk_headers" || moduleType == "versioned_ndk_headers" {
Spandan Dasaf725832023-09-19 19:51:52 +0000580 ndkHeaders = append(ndkHeaders, m)
Spandan Dasea2abba2023-06-14 21:30:38 +0000581 }
582 })
Spandan Dasaf725832023-09-19 19:51:52 +0000583 return buildConversionMetadata{
584 nameToGoLibraryModule: goMap,
585 ndkHeaders: ndkHeaders,
586 }
Spandan Dasea2abba2023-06-14 21:30:38 +0000587}
588
Spandan Dasde623292023-06-14 21:30:38 +0000589// Returns the deps in the transitive closure of a go target
590func transitiveGoDeps(directDeps []string, goModulesMap nameToGoLibraryModule) []string {
591 allDeps := directDeps
592 i := 0
593 for i < len(allDeps) {
594 curr := allDeps[i]
595 allDeps = append(allDeps, goModulesMap[curr].Deps...)
596 i += 1
597 }
598 allDeps = android.SortedUniqueStrings(allDeps)
599 return allDeps
600}
601
602func generateBazelTargetsGoBinary(ctx *android.Context, g *bootstrap.GoBinary, goModulesMap nameToGoLibraryModule) ([]BazelTarget, []error) {
603 ca := android.CommonAttributes{
604 Name: g.Name(),
605 }
606
Spandan Das682e7862023-06-22 22:22:11 +0000607 retTargets := []BazelTarget{}
608 var retErrs []error
609
Spandan Dasde623292023-06-14 21:30:38 +0000610 // For this bootstrap_go_package dep chain,
611 // A --> B --> C ( ---> depends on)
612 // Soong provides the convenience of only listing B as deps of A even if a src file of A imports C
613 // Bazel OTOH
614 // 1. requires C to be listed in `deps` expllicity.
615 // 2. does not require C to be listed if src of A does not import C
616 //
617 // 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
618 transitiveDeps := transitiveGoDeps(g.Deps(), goModulesMap)
619
Spandan Das682e7862023-06-22 22:22:11 +0000620 goSource := ""
621 // If the library contains test srcs, create an additional go_test target
622 // The go_test target will embed a go_source containining the source .go files it tests
Spandan Das89aa0f72023-06-30 20:18:39 +0000623 if !testOfGoBinaryIsIncompatible(g) && (len(g.TestSrcs()) > 0 || len(g.LinuxTestSrcs()) > 0 || len(g.DarwinTestSrcs()) > 0) {
Spandan Das682e7862023-06-22 22:22:11 +0000624 // Create a go_source containing the source .go files of go_library
625 // This target will be an `embed` of the go_binary and go_test
626 goSource = g.Name() + "-source"
627 ca := android.CommonAttributes{
628 Name: goSource,
629 }
630 ga := goAttributes{
631 Srcs: goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs()),
632 Deps: goDepLabels(transitiveDeps, goModulesMap),
633 Target_compatible_with: targetNotCompatibleWithAndroid(),
634 }
Spandan Dasaf725832023-09-19 19:51:52 +0000635 libTestSource := bTarget{
Spandan Das682e7862023-06-22 22:22:11 +0000636 targetName: goSource,
637 targetPackage: ctx.ModuleDir(g),
638 bazelRuleClass: "go_source",
639 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
640 bazelAttributes: []interface{}{&ca, &ga},
641 }
642 if libSourceTarget, err := generateBazelTarget(ctx, libTestSource); err == nil {
643 retTargets = append(retTargets, libSourceTarget)
644 } else {
645 retErrs = append(retErrs, err)
646 }
647
648 // Create a go_test target
649 gp := goTestProperties{
650 name: g.Name() + "-test",
651 dir: ctx.ModuleDir(g),
652 testSrcs: g.TestSrcs(),
653 linuxTestSrcs: g.LinuxTestSrcs(),
654 darwinTestSrcs: g.DarwinTestSrcs(),
655 testData: g.TestData(),
656 // embed the go_source in the test
657 embedName: g.Name() + "-source",
658 }
659 if libTestTarget, err := generateBazelTargetsGoTest(ctx, goModulesMap, gp); err == nil {
660 retTargets = append(retTargets, libTestTarget)
661 } else {
662 retErrs = append(retErrs, err)
663 }
664
665 }
666
667 // Create a go_binary target
Spandan Dasde623292023-06-14 21:30:38 +0000668 ga := goAttributes{
Spandan Dasde623292023-06-14 21:30:38 +0000669 Deps: goDepLabels(transitiveDeps, goModulesMap),
670 Target_compatible_with: targetNotCompatibleWithAndroid(),
671 }
672
Spandan Das682e7862023-06-22 22:22:11 +0000673 // If the binary has testSrcs, embed the common `go_source`
674 if goSource != "" {
675 ga.Embed = bazel.MakeLabelListAttribute(
676 bazel.MakeLabelList(
677 []bazel.Label{bazel.Label{Label: ":" + goSource}},
678 ),
679 )
680 } else {
681 ga.Srcs = goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs())
682 }
683
Spandan Dasaf725832023-09-19 19:51:52 +0000684 bin := bTarget{
Spandan Dasde623292023-06-14 21:30:38 +0000685 targetName: g.Name(),
686 targetPackage: ctx.ModuleDir(g),
687 bazelRuleClass: "go_binary",
688 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
689 bazelAttributes: []interface{}{&ca, &ga},
690 }
Spandan Das682e7862023-06-22 22:22:11 +0000691
692 if binTarget, err := generateBazelTarget(ctx, bin); err == nil {
693 retTargets = append(retTargets, binTarget)
694 } else {
695 retErrs = []error{err}
Spandan Dasde623292023-06-14 21:30:38 +0000696 }
Spandan Das682e7862023-06-22 22:22:11 +0000697
698 return retTargets, retErrs
Spandan Dasde623292023-06-14 21:30:38 +0000699}
700
Liz Kammer6eff3232021-08-26 08:37:59 -0400701func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (conversionResults, []error) {
ustaaaf2fd12023-07-01 11:40:36 -0400702 ctx.Context().BeginEvent("GenerateBazelTargets")
703 defer ctx.Context().EndEvent("GenerateBazelTargets")
Jingwen Chen40067de2021-01-26 21:58:43 -0500704 buildFileToTargets := make(map[string]BazelTargets)
Jingwen Chen164e0862021-02-19 00:48:40 -0500705
706 // Simple metrics tracking for bp2build
usta4f5d2c12022-10-28 23:32:01 -0400707 metrics := CreateCodegenMetrics()
Jingwen Chen164e0862021-02-19 00:48:40 -0500708
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400709 dirs := make(map[string]bool)
710
Liz Kammer6eff3232021-08-26 08:37:59 -0400711 var errs []error
712
Spandan Dasea2abba2023-06-14 21:30:38 +0000713 // Visit go libraries in a pre-run and store its state in a map
714 // The time complexity remains O(N), and this does not add significant wall time.
Spandan Dasaf725832023-09-19 19:51:52 +0000715 meta := createBuildConversionMetadata(ctx.Context())
716 nameToGoLibMap := meta.nameToGoLibraryModule
717 ndkHeaders := meta.ndkHeaders
Spandan Dasea2abba2023-06-14 21:30:38 +0000718
Jingwen Chen164e0862021-02-19 00:48:40 -0500719 bpCtx := ctx.Context()
720 bpCtx.VisitAllModules(func(m blueprint.Module) {
721 dir := bpCtx.ModuleDir(m)
Chris Parsons492bd912022-01-20 12:55:05 -0500722 moduleType := bpCtx.ModuleType(m)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400723 dirs[dir] = true
724
Liz Kammer2ada09a2021-08-11 00:17:36 -0400725 var targets []BazelTarget
Spandan Dasea2abba2023-06-14 21:30:38 +0000726 var targetErrs []error
Jingwen Chen73850672020-12-14 08:25:34 -0500727
Jingwen Chen164e0862021-02-19 00:48:40 -0500728 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500729 case Bp2Build:
Chris Parsons0c4de1f2023-09-21 20:36:35 +0000730 if aModule, ok := m.(android.Module); ok {
731 reason := aModule.GetUnconvertedReason()
732 if reason != nil {
733 // If this module was force-enabled, cause an error.
734 if _, ok := ctx.Config().BazelModulesForceEnabledByFlag()[m.Name()]; ok && m.Name() != "" {
735 err := fmt.Errorf("Force Enabled Module %s not converted", m.Name())
736 errs = append(errs, err)
737 }
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000738
Chris Parsons0c4de1f2023-09-21 20:36:35 +0000739 // Log the module isn't to be converted by bp2build.
740 // TODO: b/291598248 - Log handcrafted modules differently than other unconverted modules.
741 metrics.AddUnconvertedModule(m, moduleType, dir, *reason)
742 return
743 }
744 if len(aModule.Bp2buildTargets()) == 0 {
745 panic(fmt.Errorf("illegal bp2build invariant: module '%s' was neither converted nor marked unconvertible", aModule.Name()))
746 }
747
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000748 // Handle modules converted to generated targets.
Chris Parsons0c4de1f2023-09-21 20:36:35 +0000749 targets, targetErrs = generateBazelTargets(bpCtx, aModule)
750 errs = append(errs, targetErrs...)
751 for _, t := range targets {
752 // A module can potentially generate more than 1 Bazel
753 // target, each of a different rule class.
754 metrics.IncrementRuleClassCount(t.ruleClass)
755 }
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000756
757 // Log the module.
Chris Parsons39a16972023-06-08 14:28:51 +0000758 metrics.AddConvertedModule(aModule, moduleType, dir)
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000759
760 // Handle modules with unconverted deps. By default, emit a warning.
Liz Kammer6eff3232021-08-26 08:37:59 -0400761 if unconvertedDeps := aModule.GetUnconvertedBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700762 msg := fmt.Sprintf("%s %s:%s depends on unconverted modules: %s",
763 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400764 switch ctx.unconvertedDepMode {
765 case warnUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400766 metrics.moduleWithUnconvertedDepsMsgs = append(metrics.moduleWithUnconvertedDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400767 case errorModulesUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400768 errs = append(errs, fmt.Errorf(msg))
769 return
770 }
771 }
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500772 if unconvertedDeps := aModule.GetMissingBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700773 msg := fmt.Sprintf("%s %s:%s depends on missing modules: %s",
774 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400775 switch ctx.unconvertedDepMode {
776 case warnUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500777 metrics.moduleWithMissingDepsMsgs = append(metrics.moduleWithMissingDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400778 case errorModulesUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500779 errs = append(errs, fmt.Errorf(msg))
780 return
781 }
782 }
Spandan Dasea2abba2023-06-14 21:30:38 +0000783 } else if glib, ok := m.(*bootstrap.GoPackage); ok {
784 targets, targetErrs = generateBazelTargetsGoPackage(bpCtx, glib, nameToGoLibMap)
785 errs = append(errs, targetErrs...)
Liz Kammer15d7b0b2023-09-27 09:38:41 -0400786 metrics.IncrementRuleClassCount("bootstrap_go_package")
787 metrics.AddConvertedModule(glib, "bootstrap_go_package", dir)
Spandan Das2a55cea2023-06-14 17:56:10 +0000788 } else if gbin, ok := m.(*bootstrap.GoBinary); ok {
Spandan Dasde623292023-06-14 21:30:38 +0000789 targets, targetErrs = generateBazelTargetsGoBinary(bpCtx, gbin, nameToGoLibMap)
790 errs = append(errs, targetErrs...)
Liz Kammer15d7b0b2023-09-27 09:38:41 -0400791 metrics.IncrementRuleClassCount("blueprint_go_binary")
792 metrics.AddConvertedModule(gbin, "blueprint_go_binary", dir)
Liz Kammerfc46bc12021-02-19 11:06:17 -0500793 } else {
Chris Parsons39a16972023-06-08 14:28:51 +0000794 metrics.AddUnconvertedModule(m, moduleType, dir, android.UnconvertedReason{
795 ReasonType: int(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED),
796 })
Liz Kammerba3ea162021-02-17 13:22:03 -0500797 return
Jingwen Chen73850672020-12-14 08:25:34 -0500798 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500799 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500800 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500801 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500802 // package module name contain slashes, and thus cannot
803 // be mapped cleanly to a bazel label.
804 return
805 }
Alix94e26032022-08-16 20:37:33 +0000806 t, err := generateSoongModuleTarget(bpCtx, m)
807 if err != nil {
808 errs = append(errs, err)
809 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400810 targets = append(targets, t)
Jingwen Chen33832f92021-01-24 22:55:54 -0500811 default:
Liz Kammer6eff3232021-08-26 08:37:59 -0400812 errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
813 return
Jingwen Chen73850672020-12-14 08:25:34 -0500814 }
815
Spandan Dasabedff02023-03-07 19:24:34 +0000816 for _, target := range targets {
817 targetDir := target.PackageName()
818 buildFileToTargets[targetDir] = append(buildFileToTargets[targetDir], target)
819 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800820 })
Liz Kammer6eff3232021-08-26 08:37:59 -0400821
Spandan Dasaf725832023-09-19 19:51:52 +0000822 // Create an ndk_sysroot target that has a dependency edge on every target corresponding to Soong's ndk_headers
823 // This root target will provide headers to sdk variants of jni libraries
824 if ctx.Mode() == Bp2Build {
825 var depLabels bazel.LabelList
826 for _, ndkHeader := range ndkHeaders {
827 depLabel := bazel.Label{
828 Label: "//" + bpCtx.ModuleDir(ndkHeader) + ":" + ndkHeader.Name(),
829 }
830 depLabels.Add(&depLabel)
831 }
832 a := struct {
Liz Kammer96da2ba2023-10-13 16:22:24 -0400833 Deps bazel.LabelListAttribute
Spandan Dasaf725832023-09-19 19:51:52 +0000834 }{
Liz Kammer96da2ba2023-10-13 16:22:24 -0400835 Deps: bazel.MakeLabelListAttribute(bazel.UniqueSortedBazelLabelList(depLabels)),
Spandan Dasaf725832023-09-19 19:51:52 +0000836 }
837 ndkSysroot := bTarget{
838 targetName: "ndk_sysroot",
839 targetPackage: "build/bazel/rules/cc", // The location is subject to change, use build/bazel for now
840 bazelRuleClass: "cc_library_headers",
841 bazelRuleLoadLocation: "//build/bazel/rules/cc:cc_library_headers.bzl",
842 bazelAttributes: []interface{}{&a},
843 }
844
845 if t, err := generateBazelTarget(bpCtx, ndkSysroot); err == nil {
846 dir := ndkSysroot.targetPackage
847 buildFileToTargets[dir] = append(buildFileToTargets[dir], t)
848 } else {
849 errs = append(errs, err)
850 }
851 }
852
Liz Kammer6eff3232021-08-26 08:37:59 -0400853 if len(errs) > 0 {
854 return conversionResults{}, errs
855 }
856
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400857 if generateFilegroups {
858 // Add a filegroup target that exposes all sources in the subtree of this package
859 // 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 -0700860 //
861 // This works because: https://bazel.build/reference/be/functions#exports_files
862 // "As a legacy behaviour, also files mentioned as input to a rule are exported with the
863 // default visibility until the flag --incompatible_no_implicit_file_export is flipped. However, this behavior
864 // should not be relied upon and actively migrated away from."
865 //
866 // TODO(b/198619163): We should change this to export_files(glob(["**/*"])) instead, but doing that causes these errors:
867 // "Error in exports_files: generated label '//external/avb:avbtool' conflicts with existing py_binary rule"
868 // So we need to solve all the "target ... is both a rule and a file" warnings first.
Usta Shresthac6057152022-09-24 00:23:31 -0400869 for dir := range dirs {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400870 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
871 name: "bp2build_all_srcs",
Jingwen Chen5802d072023-09-20 10:25:09 +0000872 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]), tags = ["manual"])`,
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400873 ruleClass: "filegroup",
874 })
875 }
876 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500877
Liz Kammer6eff3232021-08-26 08:37:59 -0400878 return conversionResults{
879 buildFileToTargets: buildFileToTargets,
880 metrics: metrics,
Liz Kammer6eff3232021-08-26 08:37:59 -0400881 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500882}
883
Alix94e26032022-08-16 20:37:33 +0000884func generateBazelTargets(ctx bpToBuildContext, m android.Module) ([]BazelTarget, []error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400885 var targets []BazelTarget
Alix94e26032022-08-16 20:37:33 +0000886 var errs []error
Liz Kammer2ada09a2021-08-11 00:17:36 -0400887 for _, m := range m.Bp2buildTargets() {
Alix94e26032022-08-16 20:37:33 +0000888 target, err := generateBazelTarget(ctx, m)
889 if err != nil {
890 errs = append(errs, err)
891 return targets, errs
892 }
893 targets = append(targets, target)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400894 }
Alix94e26032022-08-16 20:37:33 +0000895 return targets, errs
Liz Kammer2ada09a2021-08-11 00:17:36 -0400896}
897
898type bp2buildModule interface {
899 TargetName() string
900 TargetPackage() string
901 BazelRuleClass() string
902 BazelRuleLoadLocation() string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000903 BazelAttributes() []interface{}
Liz Kammer2ada09a2021-08-11 00:17:36 -0400904}
905
Alix94e26032022-08-16 20:37:33 +0000906func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) (BazelTarget, error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400907 ruleClass := m.BazelRuleClass()
908 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500909
Jingwen Chen73850672020-12-14 08:25:34 -0500910 // extract the bazel attributes from the module.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000911 attrs := m.BazelAttributes()
Alix94e26032022-08-16 20:37:33 +0000912 props, err := extractModuleProperties(attrs, true)
913 if err != nil {
914 return BazelTarget{}, err
915 }
Jingwen Chen73850672020-12-14 08:25:34 -0500916
Liz Kammer0eae52e2021-10-06 10:32:26 -0400917 // name is handled in a special manner
918 delete(props.Attrs, "name")
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500919
Jingwen Chen73850672020-12-14 08:25:34 -0500920 // Return the Bazel target with rule class and attributes, ready to be
921 // code-generated.
922 attributes := propsToAttributes(props.Attrs)
Sasha Smundakfb589492022-08-04 11:13:27 -0700923 var content string
Liz Kammer2ada09a2021-08-11 00:17:36 -0400924 targetName := m.TargetName()
Sasha Smundakfb589492022-08-04 11:13:27 -0700925 if targetName != "" {
926 content = fmt.Sprintf(ruleTargetTemplate, ruleClass, targetName, attributes)
927 } else {
928 content = fmt.Sprintf(unnamedRuleTargetTemplate, ruleClass, attributes)
929 }
Cole Faustb4cb0c82023-09-14 15:16:58 -0700930 var loads []BazelLoad
931 if bzlLoadLocation != "" {
932 loads = append(loads, BazelLoad{
933 file: bzlLoadLocation,
934 symbols: []BazelLoadSymbol{{symbol: ruleClass}},
935 })
936 }
Jingwen Chen73850672020-12-14 08:25:34 -0500937 return BazelTarget{
Cole Faustb4cb0c82023-09-14 15:16:58 -0700938 name: targetName,
939 packageName: m.TargetPackage(),
940 ruleClass: ruleClass,
941 loads: loads,
942 content: content,
Alix94e26032022-08-16 20:37:33 +0000943 }, nil
Jingwen Chen73850672020-12-14 08:25:34 -0500944}
945
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800946// Convert a module and its deps and props into a Bazel macro/rule
947// representation in the BUILD file.
Alix94e26032022-08-16 20:37:33 +0000948func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) (BazelTarget, error) {
949 props, err := getBuildProperties(ctx, m)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800950
951 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
952 // items, if the modules are added using different DependencyTag. Figure
953 // out the implications of that.
954 depLabels := map[string]bool{}
955 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500956 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800957 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
958 })
959 }
Liz Kammer0eae52e2021-10-06 10:32:26 -0400960
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400961 for p := range ignoredPropNames {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400962 delete(props.Attrs, p)
963 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800964 attributes := propsToAttributes(props.Attrs)
965
966 depLabelList := "[\n"
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400967 for depLabel := range depLabels {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800968 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
969 }
970 depLabelList += " ]"
971
972 targetName := targetNameWithVariant(ctx, m)
973 return BazelTarget{
Spandan Dasabedff02023-03-07 19:24:34 +0000974 name: targetName,
975 packageName: ctx.ModuleDir(m),
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800976 content: fmt.Sprintf(
Sasha Smundakfb589492022-08-04 11:13:27 -0700977 soongModuleTargetTemplate,
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800978 targetName,
979 ctx.ModuleName(m),
980 canonicalizeModuleType(ctx.ModuleType(m)),
981 ctx.ModuleSubDir(m),
982 depLabelList,
983 attributes),
Alix94e26032022-08-16 20:37:33 +0000984 }, err
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800985}
986
Alix94e26032022-08-16 20:37:33 +0000987func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800988 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
989 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
990 if aModule, ok := m.(android.Module); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000991 return extractModuleProperties(aModule.GetProperties(), false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800992 }
993
Alix94e26032022-08-16 20:37:33 +0000994 return BazelAttributes{}, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800995}
996
997// Generically extract module properties and types into a map, keyed by the module property name.
Alix94e26032022-08-16 20:37:33 +0000998func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800999 ret := map[string]string{}
1000
1001 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -04001002 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001003 propertiesValue := reflect.ValueOf(properties)
1004 // Check that propertiesValue is a pointer to the Properties struct, like
1005 // *cc.BaseLinkerProperties or *java.CompilerProperties.
1006 //
1007 // propertiesValue can also be type-asserted to the structs to
1008 // manipulate internal props, if needed.
1009 if isStructPtr(propertiesValue.Type()) {
1010 structValue := propertiesValue.Elem()
Alix94e26032022-08-16 20:37:33 +00001011 ok, err := extractStructProperties(structValue, 0)
1012 if err != nil {
1013 return BazelAttributes{}, err
1014 }
1015 for k, v := range ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001016 if existing, exists := ret[k]; checkForDuplicateProperties && exists {
Alix94e26032022-08-16 20:37:33 +00001017 return BazelAttributes{}, fmt.Errorf(
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001018 "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes",
Alix94e26032022-08-16 20:37:33 +00001019 k, existing)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001020 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001021 ret[k] = v
1022 }
1023 } else {
Alix94e26032022-08-16 20:37:33 +00001024 return BazelAttributes{},
1025 fmt.Errorf(
1026 "properties must be a pointer to a struct, got %T",
1027 propertiesValue.Interface())
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001028 }
1029 }
1030
Liz Kammer2ada09a2021-08-11 00:17:36 -04001031 return BazelAttributes{
1032 Attrs: ret,
Alix94e26032022-08-16 20:37:33 +00001033 }, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001034}
1035
1036func isStructPtr(t reflect.Type) bool {
1037 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
1038}
1039
1040// prettyPrint a property value into the equivalent Starlark representation
1041// recursively.
Jingwen Chen58ff6802021-11-17 12:14:41 +00001042func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) {
1043 if !emitZeroValues && isZero(propertyValue) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001044 // A property value being set or unset actually matters -- Soong does set default
1045 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
1046 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
1047 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +00001048 // In Bazel-parlance, we would use "attr.<type>(default = <default
1049 // value>)" to set the default value of unset attributes. In the cases
1050 // where the bp2build converter didn't set the default value within the
1051 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -04001052 // value. For those cases, we return an empty string so we don't
1053 // unnecessarily generate empty values.
1054 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001055 }
1056
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001057 switch propertyValue.Kind() {
1058 case reflect.String:
Liz Kammer72beb342022-02-03 08:42:10 -05001059 return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001060 case reflect.Bool:
Liz Kammer72beb342022-02-03 08:42:10 -05001061 return starlark_fmt.PrintBool(propertyValue.Bool()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001062 case reflect.Int, reflect.Uint, reflect.Int64:
Liz Kammer72beb342022-02-03 08:42:10 -05001063 return fmt.Sprintf("%v", propertyValue.Interface()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001064 case reflect.Ptr:
Jingwen Chen58ff6802021-11-17 12:14:41 +00001065 return prettyPrint(propertyValue.Elem(), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001066 case reflect.Slice:
Liz Kammer72beb342022-02-03 08:42:10 -05001067 elements := make([]string, 0, propertyValue.Len())
1068 for i := 0; i < propertyValue.Len(); i++ {
1069 val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001070 if err != nil {
1071 return "", err
1072 }
Liz Kammer72beb342022-02-03 08:42:10 -05001073 if val != "" {
1074 elements = append(elements, val)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001075 }
1076 }
Sam Delmerico932c01c2022-03-25 16:33:26 +00001077 return starlark_fmt.PrintList(elements, indent, func(s string) string {
1078 return "%s"
1079 }), nil
Jingwen Chenb4628eb2021-04-08 14:40:57 +00001080
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001081 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -05001082 // Special cases where the bp2build sends additional information to the codegenerator
1083 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +00001084 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
1085 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -05001086 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
1087 return fmt.Sprintf("%q", label.Label), nil
1088 }
1089
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001090 // Sort and print the struct props by the key.
Alix94e26032022-08-16 20:37:33 +00001091 structProps, err := extractStructProperties(propertyValue, indent)
1092
1093 if err != nil {
1094 return "", err
1095 }
1096
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001097 if len(structProps) == 0 {
1098 return "", nil
1099 }
Liz Kammer72beb342022-02-03 08:42:10 -05001100 return starlark_fmt.PrintDict(structProps, indent), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001101 case reflect.Interface:
1102 // TODO(b/164227191): implement pretty print for interfaces.
1103 // Interfaces are used for for arch, multilib and target properties.
1104 return "", nil
Spandan Das6a448ec2023-04-19 17:36:12 +00001105 case reflect.Map:
1106 if v, ok := propertyValue.Interface().(bazel.StringMapAttribute); ok {
1107 return starlark_fmt.PrintStringStringDict(v, indent), nil
1108 }
1109 return "", fmt.Errorf("bp2build expects map of type map[string]string for field: %s", propertyValue)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001110 default:
1111 return "", fmt.Errorf(
1112 "unexpected kind for property struct field: %s", propertyValue.Kind())
1113 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001114}
1115
1116// Converts a reflected property struct value into a map of property names and property values,
1117// which each property value correctly pretty-printed and indented at the right nest level,
1118// since property structs can be nested. In Starlark, nested structs are represented as nested
1119// dicts: https://docs.bazel.build/skylark/lib/dict.html
Alix94e26032022-08-16 20:37:33 +00001120func extractStructProperties(structValue reflect.Value, indent int) (map[string]string, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001121 if structValue.Kind() != reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001122 return map[string]string{}, fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind())
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001123 }
1124
Alix94e26032022-08-16 20:37:33 +00001125 var err error
1126
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001127 ret := map[string]string{}
1128 structType := structValue.Type()
1129 for i := 0; i < structValue.NumField(); i++ {
1130 field := structType.Field(i)
1131 if shouldSkipStructField(field) {
1132 continue
1133 }
1134
1135 fieldValue := structValue.Field(i)
1136 if isZero(fieldValue) {
1137 // Ignore zero-valued fields
1138 continue
1139 }
Liz Kammer7a210ac2021-09-22 15:52:58 -04001140
Liz Kammer32a03392021-09-14 11:17:21 -04001141 // if the struct is embedded (anonymous), flatten the properties into the containing struct
1142 if field.Anonymous {
1143 if field.Type.Kind() == reflect.Ptr {
1144 fieldValue = fieldValue.Elem()
1145 }
1146 if fieldValue.Type().Kind() == reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001147 propsToMerge, err := extractStructProperties(fieldValue, indent)
1148 if err != nil {
1149 return map[string]string{}, err
1150 }
Liz Kammer32a03392021-09-14 11:17:21 -04001151 for prop, value := range propsToMerge {
1152 ret[prop] = value
1153 }
1154 continue
1155 }
1156 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001157
1158 propertyName := proptools.PropertyNameForField(field.Name)
Alix94e26032022-08-16 20:37:33 +00001159 var prettyPrintedValue string
1160 prettyPrintedValue, err = prettyPrint(fieldValue, indent+1, false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001161 if err != nil {
Alix94e26032022-08-16 20:37:33 +00001162 return map[string]string{}, fmt.Errorf(
1163 "Error while parsing property: %q. %s",
1164 propertyName,
1165 err)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001166 }
1167 if prettyPrintedValue != "" {
1168 ret[propertyName] = prettyPrintedValue
1169 }
1170 }
1171
Alix94e26032022-08-16 20:37:33 +00001172 return ret, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001173}
1174
1175func isZero(value reflect.Value) bool {
1176 switch value.Kind() {
1177 case reflect.Func, reflect.Map, reflect.Slice:
1178 return value.IsNil()
1179 case reflect.Array:
1180 valueIsZero := true
1181 for i := 0; i < value.Len(); i++ {
1182 valueIsZero = valueIsZero && isZero(value.Index(i))
1183 }
1184 return valueIsZero
1185 case reflect.Struct:
1186 valueIsZero := true
1187 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +02001188 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001189 }
1190 return valueIsZero
1191 case reflect.Ptr:
1192 if !value.IsNil() {
1193 return isZero(reflect.Indirect(value))
1194 } else {
1195 return true
1196 }
Liz Kammer46fb7ab2021-12-01 10:09:34 -05001197 // Always print bool/strings, if you want a bool/string attribute to be able to take the default value, use a
1198 // pointer instead
1199 case reflect.Bool, reflect.String:
Liz Kammerd366c902021-06-03 13:43:01 -04001200 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001201 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -04001202 if !value.IsValid() {
1203 return true
1204 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001205 zeroValue := reflect.Zero(value.Type())
1206 result := value.Interface() == zeroValue.Interface()
1207 return result
1208 }
1209}
1210
1211func escapeString(s string) string {
1212 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +00001213
1214 // b/184026959: Reverse the application of some common control sequences.
1215 // These must be generated literally in the BUILD file.
1216 s = strings.ReplaceAll(s, "\t", "\\t")
1217 s = strings.ReplaceAll(s, "\n", "\\n")
1218 s = strings.ReplaceAll(s, "\r", "\\r")
1219
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001220 return strings.ReplaceAll(s, "\"", "\\\"")
1221}
1222
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001223func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
1224 name := ""
1225 if c.ModuleSubDir(logicModule) != "" {
1226 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
1227 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
1228 } else {
1229 name = c.ModuleName(logicModule)
1230 }
1231
1232 return strings.Replace(name, "//", "", 1)
1233}
1234
1235func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
1236 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
1237}