blob: 53c37b90e675d1fb016cd9612b3d17c64702bd4b [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 {
833 Deps bazel.LabelListAttribute
834 System_dynamic_deps bazel.LabelListAttribute
835 }{
836 Deps: bazel.MakeLabelListAttribute(bazel.UniqueSortedBazelLabelList(depLabels)),
837 System_dynamic_deps: bazel.MakeLabelListAttribute(bazel.MakeLabelList([]bazel.Label{})),
838 }
839 ndkSysroot := bTarget{
840 targetName: "ndk_sysroot",
841 targetPackage: "build/bazel/rules/cc", // The location is subject to change, use build/bazel for now
842 bazelRuleClass: "cc_library_headers",
843 bazelRuleLoadLocation: "//build/bazel/rules/cc:cc_library_headers.bzl",
844 bazelAttributes: []interface{}{&a},
845 }
846
847 if t, err := generateBazelTarget(bpCtx, ndkSysroot); err == nil {
848 dir := ndkSysroot.targetPackage
849 buildFileToTargets[dir] = append(buildFileToTargets[dir], t)
850 } else {
851 errs = append(errs, err)
852 }
853 }
854
Liz Kammer6eff3232021-08-26 08:37:59 -0400855 if len(errs) > 0 {
856 return conversionResults{}, errs
857 }
858
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400859 if generateFilegroups {
860 // Add a filegroup target that exposes all sources in the subtree of this package
861 // 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 -0700862 //
863 // This works because: https://bazel.build/reference/be/functions#exports_files
864 // "As a legacy behaviour, also files mentioned as input to a rule are exported with the
865 // default visibility until the flag --incompatible_no_implicit_file_export is flipped. However, this behavior
866 // should not be relied upon and actively migrated away from."
867 //
868 // TODO(b/198619163): We should change this to export_files(glob(["**/*"])) instead, but doing that causes these errors:
869 // "Error in exports_files: generated label '//external/avb:avbtool' conflicts with existing py_binary rule"
870 // So we need to solve all the "target ... is both a rule and a file" warnings first.
Usta Shresthac6057152022-09-24 00:23:31 -0400871 for dir := range dirs {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400872 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
873 name: "bp2build_all_srcs",
Jingwen Chen5802d072023-09-20 10:25:09 +0000874 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]), tags = ["manual"])`,
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400875 ruleClass: "filegroup",
876 })
877 }
878 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500879
Liz Kammer6eff3232021-08-26 08:37:59 -0400880 return conversionResults{
881 buildFileToTargets: buildFileToTargets,
882 metrics: metrics,
Liz Kammer6eff3232021-08-26 08:37:59 -0400883 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500884}
885
Alix94e26032022-08-16 20:37:33 +0000886func generateBazelTargets(ctx bpToBuildContext, m android.Module) ([]BazelTarget, []error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400887 var targets []BazelTarget
Alix94e26032022-08-16 20:37:33 +0000888 var errs []error
Liz Kammer2ada09a2021-08-11 00:17:36 -0400889 for _, m := range m.Bp2buildTargets() {
Alix94e26032022-08-16 20:37:33 +0000890 target, err := generateBazelTarget(ctx, m)
891 if err != nil {
892 errs = append(errs, err)
893 return targets, errs
894 }
895 targets = append(targets, target)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400896 }
Alix94e26032022-08-16 20:37:33 +0000897 return targets, errs
Liz Kammer2ada09a2021-08-11 00:17:36 -0400898}
899
900type bp2buildModule interface {
901 TargetName() string
902 TargetPackage() string
903 BazelRuleClass() string
904 BazelRuleLoadLocation() string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000905 BazelAttributes() []interface{}
Liz Kammer2ada09a2021-08-11 00:17:36 -0400906}
907
Alix94e26032022-08-16 20:37:33 +0000908func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) (BazelTarget, error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400909 ruleClass := m.BazelRuleClass()
910 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500911
Jingwen Chen73850672020-12-14 08:25:34 -0500912 // extract the bazel attributes from the module.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000913 attrs := m.BazelAttributes()
Alix94e26032022-08-16 20:37:33 +0000914 props, err := extractModuleProperties(attrs, true)
915 if err != nil {
916 return BazelTarget{}, err
917 }
Jingwen Chen73850672020-12-14 08:25:34 -0500918
Liz Kammer0eae52e2021-10-06 10:32:26 -0400919 // name is handled in a special manner
920 delete(props.Attrs, "name")
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500921
Jingwen Chen73850672020-12-14 08:25:34 -0500922 // Return the Bazel target with rule class and attributes, ready to be
923 // code-generated.
924 attributes := propsToAttributes(props.Attrs)
Sasha Smundakfb589492022-08-04 11:13:27 -0700925 var content string
Liz Kammer2ada09a2021-08-11 00:17:36 -0400926 targetName := m.TargetName()
Sasha Smundakfb589492022-08-04 11:13:27 -0700927 if targetName != "" {
928 content = fmt.Sprintf(ruleTargetTemplate, ruleClass, targetName, attributes)
929 } else {
930 content = fmt.Sprintf(unnamedRuleTargetTemplate, ruleClass, attributes)
931 }
Cole Faustb4cb0c82023-09-14 15:16:58 -0700932 var loads []BazelLoad
933 if bzlLoadLocation != "" {
934 loads = append(loads, BazelLoad{
935 file: bzlLoadLocation,
936 symbols: []BazelLoadSymbol{{symbol: ruleClass}},
937 })
938 }
Jingwen Chen73850672020-12-14 08:25:34 -0500939 return BazelTarget{
Cole Faustb4cb0c82023-09-14 15:16:58 -0700940 name: targetName,
941 packageName: m.TargetPackage(),
942 ruleClass: ruleClass,
943 loads: loads,
944 content: content,
Alix94e26032022-08-16 20:37:33 +0000945 }, nil
Jingwen Chen73850672020-12-14 08:25:34 -0500946}
947
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800948// Convert a module and its deps and props into a Bazel macro/rule
949// representation in the BUILD file.
Alix94e26032022-08-16 20:37:33 +0000950func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) (BazelTarget, error) {
951 props, err := getBuildProperties(ctx, m)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800952
953 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
954 // items, if the modules are added using different DependencyTag. Figure
955 // out the implications of that.
956 depLabels := map[string]bool{}
957 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500958 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800959 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
960 })
961 }
Liz Kammer0eae52e2021-10-06 10:32:26 -0400962
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400963 for p := range ignoredPropNames {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400964 delete(props.Attrs, p)
965 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800966 attributes := propsToAttributes(props.Attrs)
967
968 depLabelList := "[\n"
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400969 for depLabel := range depLabels {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800970 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
971 }
972 depLabelList += " ]"
973
974 targetName := targetNameWithVariant(ctx, m)
975 return BazelTarget{
Spandan Dasabedff02023-03-07 19:24:34 +0000976 name: targetName,
977 packageName: ctx.ModuleDir(m),
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800978 content: fmt.Sprintf(
Sasha Smundakfb589492022-08-04 11:13:27 -0700979 soongModuleTargetTemplate,
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800980 targetName,
981 ctx.ModuleName(m),
982 canonicalizeModuleType(ctx.ModuleType(m)),
983 ctx.ModuleSubDir(m),
984 depLabelList,
985 attributes),
Alix94e26032022-08-16 20:37:33 +0000986 }, err
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800987}
988
Alix94e26032022-08-16 20:37:33 +0000989func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800990 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
991 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
992 if aModule, ok := m.(android.Module); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000993 return extractModuleProperties(aModule.GetProperties(), false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800994 }
995
Alix94e26032022-08-16 20:37:33 +0000996 return BazelAttributes{}, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800997}
998
999// Generically extract module properties and types into a map, keyed by the module property name.
Alix94e26032022-08-16 20:37:33 +00001000func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001001 ret := map[string]string{}
1002
1003 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -04001004 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001005 propertiesValue := reflect.ValueOf(properties)
1006 // Check that propertiesValue is a pointer to the Properties struct, like
1007 // *cc.BaseLinkerProperties or *java.CompilerProperties.
1008 //
1009 // propertiesValue can also be type-asserted to the structs to
1010 // manipulate internal props, if needed.
1011 if isStructPtr(propertiesValue.Type()) {
1012 structValue := propertiesValue.Elem()
Alix94e26032022-08-16 20:37:33 +00001013 ok, err := extractStructProperties(structValue, 0)
1014 if err != nil {
1015 return BazelAttributes{}, err
1016 }
1017 for k, v := range ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001018 if existing, exists := ret[k]; checkForDuplicateProperties && exists {
Alix94e26032022-08-16 20:37:33 +00001019 return BazelAttributes{}, fmt.Errorf(
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001020 "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes",
Alix94e26032022-08-16 20:37:33 +00001021 k, existing)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001022 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001023 ret[k] = v
1024 }
1025 } else {
Alix94e26032022-08-16 20:37:33 +00001026 return BazelAttributes{},
1027 fmt.Errorf(
1028 "properties must be a pointer to a struct, got %T",
1029 propertiesValue.Interface())
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001030 }
1031 }
1032
Liz Kammer2ada09a2021-08-11 00:17:36 -04001033 return BazelAttributes{
1034 Attrs: ret,
Alix94e26032022-08-16 20:37:33 +00001035 }, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001036}
1037
1038func isStructPtr(t reflect.Type) bool {
1039 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
1040}
1041
1042// prettyPrint a property value into the equivalent Starlark representation
1043// recursively.
Jingwen Chen58ff6802021-11-17 12:14:41 +00001044func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) {
1045 if !emitZeroValues && isZero(propertyValue) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001046 // A property value being set or unset actually matters -- Soong does set default
1047 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
1048 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
1049 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +00001050 // In Bazel-parlance, we would use "attr.<type>(default = <default
1051 // value>)" to set the default value of unset attributes. In the cases
1052 // where the bp2build converter didn't set the default value within the
1053 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -04001054 // value. For those cases, we return an empty string so we don't
1055 // unnecessarily generate empty values.
1056 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001057 }
1058
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001059 switch propertyValue.Kind() {
1060 case reflect.String:
Liz Kammer72beb342022-02-03 08:42:10 -05001061 return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001062 case reflect.Bool:
Liz Kammer72beb342022-02-03 08:42:10 -05001063 return starlark_fmt.PrintBool(propertyValue.Bool()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001064 case reflect.Int, reflect.Uint, reflect.Int64:
Liz Kammer72beb342022-02-03 08:42:10 -05001065 return fmt.Sprintf("%v", propertyValue.Interface()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001066 case reflect.Ptr:
Jingwen Chen58ff6802021-11-17 12:14:41 +00001067 return prettyPrint(propertyValue.Elem(), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001068 case reflect.Slice:
Liz Kammer72beb342022-02-03 08:42:10 -05001069 elements := make([]string, 0, propertyValue.Len())
1070 for i := 0; i < propertyValue.Len(); i++ {
1071 val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001072 if err != nil {
1073 return "", err
1074 }
Liz Kammer72beb342022-02-03 08:42:10 -05001075 if val != "" {
1076 elements = append(elements, val)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001077 }
1078 }
Sam Delmerico932c01c2022-03-25 16:33:26 +00001079 return starlark_fmt.PrintList(elements, indent, func(s string) string {
1080 return "%s"
1081 }), nil
Jingwen Chenb4628eb2021-04-08 14:40:57 +00001082
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001083 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -05001084 // Special cases where the bp2build sends additional information to the codegenerator
1085 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +00001086 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
1087 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -05001088 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
1089 return fmt.Sprintf("%q", label.Label), nil
1090 }
1091
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001092 // Sort and print the struct props by the key.
Alix94e26032022-08-16 20:37:33 +00001093 structProps, err := extractStructProperties(propertyValue, indent)
1094
1095 if err != nil {
1096 return "", err
1097 }
1098
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001099 if len(structProps) == 0 {
1100 return "", nil
1101 }
Liz Kammer72beb342022-02-03 08:42:10 -05001102 return starlark_fmt.PrintDict(structProps, indent), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001103 case reflect.Interface:
1104 // TODO(b/164227191): implement pretty print for interfaces.
1105 // Interfaces are used for for arch, multilib and target properties.
1106 return "", nil
Spandan Das6a448ec2023-04-19 17:36:12 +00001107 case reflect.Map:
1108 if v, ok := propertyValue.Interface().(bazel.StringMapAttribute); ok {
1109 return starlark_fmt.PrintStringStringDict(v, indent), nil
1110 }
1111 return "", fmt.Errorf("bp2build expects map of type map[string]string for field: %s", propertyValue)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001112 default:
1113 return "", fmt.Errorf(
1114 "unexpected kind for property struct field: %s", propertyValue.Kind())
1115 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001116}
1117
1118// Converts a reflected property struct value into a map of property names and property values,
1119// which each property value correctly pretty-printed and indented at the right nest level,
1120// since property structs can be nested. In Starlark, nested structs are represented as nested
1121// dicts: https://docs.bazel.build/skylark/lib/dict.html
Alix94e26032022-08-16 20:37:33 +00001122func extractStructProperties(structValue reflect.Value, indent int) (map[string]string, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001123 if structValue.Kind() != reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001124 return map[string]string{}, fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind())
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001125 }
1126
Alix94e26032022-08-16 20:37:33 +00001127 var err error
1128
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001129 ret := map[string]string{}
1130 structType := structValue.Type()
1131 for i := 0; i < structValue.NumField(); i++ {
1132 field := structType.Field(i)
1133 if shouldSkipStructField(field) {
1134 continue
1135 }
1136
1137 fieldValue := structValue.Field(i)
1138 if isZero(fieldValue) {
1139 // Ignore zero-valued fields
1140 continue
1141 }
Liz Kammer7a210ac2021-09-22 15:52:58 -04001142
Liz Kammer32a03392021-09-14 11:17:21 -04001143 // if the struct is embedded (anonymous), flatten the properties into the containing struct
1144 if field.Anonymous {
1145 if field.Type.Kind() == reflect.Ptr {
1146 fieldValue = fieldValue.Elem()
1147 }
1148 if fieldValue.Type().Kind() == reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001149 propsToMerge, err := extractStructProperties(fieldValue, indent)
1150 if err != nil {
1151 return map[string]string{}, err
1152 }
Liz Kammer32a03392021-09-14 11:17:21 -04001153 for prop, value := range propsToMerge {
1154 ret[prop] = value
1155 }
1156 continue
1157 }
1158 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001159
1160 propertyName := proptools.PropertyNameForField(field.Name)
Alix94e26032022-08-16 20:37:33 +00001161 var prettyPrintedValue string
1162 prettyPrintedValue, err = prettyPrint(fieldValue, indent+1, false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001163 if err != nil {
Alix94e26032022-08-16 20:37:33 +00001164 return map[string]string{}, fmt.Errorf(
1165 "Error while parsing property: %q. %s",
1166 propertyName,
1167 err)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001168 }
1169 if prettyPrintedValue != "" {
1170 ret[propertyName] = prettyPrintedValue
1171 }
1172 }
1173
Alix94e26032022-08-16 20:37:33 +00001174 return ret, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001175}
1176
1177func isZero(value reflect.Value) bool {
1178 switch value.Kind() {
1179 case reflect.Func, reflect.Map, reflect.Slice:
1180 return value.IsNil()
1181 case reflect.Array:
1182 valueIsZero := true
1183 for i := 0; i < value.Len(); i++ {
1184 valueIsZero = valueIsZero && isZero(value.Index(i))
1185 }
1186 return valueIsZero
1187 case reflect.Struct:
1188 valueIsZero := true
1189 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +02001190 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001191 }
1192 return valueIsZero
1193 case reflect.Ptr:
1194 if !value.IsNil() {
1195 return isZero(reflect.Indirect(value))
1196 } else {
1197 return true
1198 }
Liz Kammer46fb7ab2021-12-01 10:09:34 -05001199 // Always print bool/strings, if you want a bool/string attribute to be able to take the default value, use a
1200 // pointer instead
1201 case reflect.Bool, reflect.String:
Liz Kammerd366c902021-06-03 13:43:01 -04001202 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001203 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -04001204 if !value.IsValid() {
1205 return true
1206 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001207 zeroValue := reflect.Zero(value.Type())
1208 result := value.Interface() == zeroValue.Interface()
1209 return result
1210 }
1211}
1212
1213func escapeString(s string) string {
1214 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +00001215
1216 // b/184026959: Reverse the application of some common control sequences.
1217 // These must be generated literally in the BUILD file.
1218 s = strings.ReplaceAll(s, "\t", "\\t")
1219 s = strings.ReplaceAll(s, "\n", "\\n")
1220 s = strings.ReplaceAll(s, "\r", "\\r")
1221
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001222 return strings.ReplaceAll(s, "\"", "\\\"")
1223}
1224
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001225func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
1226 name := ""
1227 if c.ModuleSubDir(logicModule) != "" {
1228 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
1229 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
1230 } else {
1231 name = c.ModuleName(logicModule)
1232 }
1233
1234 return strings.Replace(name, "//", "", 1)
1235}
1236
1237func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
1238 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
1239}