blob: d2187ffa6c663cd7dbb6e695c67e45facc51000a [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 {
Cole Faust11edf552023-10-13 11:32:14 -0700282 buildFileToTargets map[string]BazelTargets
283 moduleNameToPartition map[string]string
284 metrics CodegenMetrics
Liz Kammer6eff3232021-08-26 08:37:59 -0400285}
286
287func (r conversionResults) BuildDirToTargets() map[string]BazelTargets {
288 return r.buildFileToTargets
289}
290
Spandan Dasaf725832023-09-19 19:51:52 +0000291// 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 +0000292// this implements bp2buildModule interface and is passed to generateBazelTargets
Spandan Dasaf725832023-09-19 19:51:52 +0000293type bTarget struct {
Spandan Dasea2abba2023-06-14 21:30:38 +0000294 targetName string
295 targetPackage string
296 bazelRuleClass string
297 bazelRuleLoadLocation string
298 bazelAttributes []interface{}
299}
300
Spandan Dasaf725832023-09-19 19:51:52 +0000301var _ bp2buildModule = (*bTarget)(nil)
Spandan Dasea2abba2023-06-14 21:30:38 +0000302
Spandan Dasaf725832023-09-19 19:51:52 +0000303func (b bTarget) TargetName() string {
304 return b.targetName
Spandan Dasea2abba2023-06-14 21:30:38 +0000305}
306
Spandan Dasaf725832023-09-19 19:51:52 +0000307func (b bTarget) TargetPackage() string {
308 return b.targetPackage
Spandan Dasea2abba2023-06-14 21:30:38 +0000309}
310
Spandan Dasaf725832023-09-19 19:51:52 +0000311func (b bTarget) BazelRuleClass() string {
312 return b.bazelRuleClass
Spandan Dasea2abba2023-06-14 21:30:38 +0000313}
314
Spandan Dasaf725832023-09-19 19:51:52 +0000315func (b bTarget) BazelRuleLoadLocation() string {
316 return b.bazelRuleLoadLocation
Spandan Dasea2abba2023-06-14 21:30:38 +0000317}
318
Spandan Dasaf725832023-09-19 19:51:52 +0000319func (b bTarget) BazelAttributes() []interface{} {
320 return b.bazelAttributes
Spandan Dasea2abba2023-06-14 21:30:38 +0000321}
322
323// Creates a target_compatible_with entry that is *not* compatible with android
324func targetNotCompatibleWithAndroid() bazel.LabelListAttribute {
325 ret := bazel.LabelListAttribute{}
326 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsAndroid,
327 bazel.MakeLabelList(
328 []bazel.Label{
329 bazel.Label{
330 Label: "@platforms//:incompatible",
331 },
332 },
333 ),
334 )
335 return ret
336}
337
338// helper function to return labels for srcs used in bootstrap_go_package and bootstrap_go_binary
339// this function has the following limitations which make it unsuitable for widespread use
Spandan Das0a8a2752023-06-21 01:50:33 +0000340// - wildcard patterns in srcs
341// This is ok for go since build/blueprint does not support it.
Spandan Dasea2abba2023-06-14 21:30:38 +0000342//
343// Prefer to use `BazelLabelForModuleSrc` instead
Spandan Das0a8a2752023-06-21 01:50:33 +0000344func goSrcLabels(cfg android.Config, moduleDir string, srcs []string, linuxSrcs, darwinSrcs []string) bazel.LabelListAttribute {
Spandan Dasea2abba2023-06-14 21:30:38 +0000345 labels := func(srcs []string) bazel.LabelList {
346 ret := []bazel.Label{}
347 for _, src := range srcs {
348 srcLabel := bazel.Label{
Spandan Das0a8a2752023-06-21 01:50:33 +0000349 Label: src,
Spandan Dasea2abba2023-06-14 21:30:38 +0000350 }
351 ret = append(ret, srcLabel)
352 }
Spandan Das0a8a2752023-06-21 01:50:33 +0000353 // Respect package boundaries
354 return android.TransformSubpackagePaths(
355 cfg,
356 moduleDir,
357 bazel.MakeLabelList(ret),
358 )
Spandan Dasea2abba2023-06-14 21:30:38 +0000359 }
360
361 ret := bazel.LabelListAttribute{}
362 // common
363 ret.SetSelectValue(bazel.NoConfigAxis, "", labels(srcs))
364 // linux
365 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsLinux, labels(linuxSrcs))
366 // darwin
367 ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsDarwin, labels(darwinSrcs))
368 return ret
369}
370
371func goDepLabels(deps []string, goModulesMap nameToGoLibraryModule) bazel.LabelListAttribute {
372 labels := []bazel.Label{}
373 for _, dep := range deps {
374 moduleDir := goModulesMap[dep].Dir
375 if moduleDir == "." {
376 moduleDir = ""
377 }
378 label := bazel.Label{
379 Label: fmt.Sprintf("//%s:%s", moduleDir, dep),
380 }
381 labels = append(labels, label)
382 }
383 return bazel.MakeLabelListAttribute(bazel.MakeLabelList(labels))
384}
385
386// attributes common to blueprint_go_binary and bootstap_go_package
387type goAttributes struct {
388 Importpath bazel.StringAttribute
389 Srcs bazel.LabelListAttribute
390 Deps bazel.LabelListAttribute
Spandan Das682e7862023-06-22 22:22:11 +0000391 Data bazel.LabelListAttribute
Spandan Dasea2abba2023-06-14 21:30:38 +0000392 Target_compatible_with bazel.LabelListAttribute
Spandan Das682e7862023-06-22 22:22:11 +0000393
394 // attributes for the dynamically generated go_test target
395 Embed bazel.LabelListAttribute
Spandan Dasea2abba2023-06-14 21:30:38 +0000396}
397
Spandan Das682e7862023-06-22 22:22:11 +0000398type goTestProperties struct {
399 name string
400 dir string
401 testSrcs []string
402 linuxTestSrcs []string
403 darwinTestSrcs []string
404 testData []string
405 // Name of the target that should be compiled together with the test
406 embedName string
407}
408
409// Creates a go_test target for bootstrap_go_package / blueprint_go_binary
410func generateBazelTargetsGoTest(ctx *android.Context, goModulesMap nameToGoLibraryModule, gp goTestProperties) (BazelTarget, error) {
411 ca := android.CommonAttributes{
412 Name: gp.name,
413 }
414 ga := goAttributes{
415 Srcs: goSrcLabels(ctx.Config(), gp.dir, gp.testSrcs, gp.linuxTestSrcs, gp.darwinTestSrcs),
416 Data: goSrcLabels(ctx.Config(), gp.dir, gp.testData, []string{}, []string{}),
417 Embed: bazel.MakeLabelListAttribute(
418 bazel.MakeLabelList(
419 []bazel.Label{bazel.Label{Label: ":" + gp.embedName}},
420 ),
421 ),
422 Target_compatible_with: targetNotCompatibleWithAndroid(),
423 }
424
Spandan Dasaf725832023-09-19 19:51:52 +0000425 libTest := bTarget{
Spandan Das682e7862023-06-22 22:22:11 +0000426 targetName: gp.name,
427 targetPackage: gp.dir,
428 bazelRuleClass: "go_test",
429 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
430 bazelAttributes: []interface{}{&ca, &ga},
431 }
432 return generateBazelTarget(ctx, libTest)
433}
434
435// TODO - b/288491147: testSrcs of certain bootstrap_go_package/blueprint_go_binary are not hermetic and depend on
436// testdata checked into the filesystem.
437// Denylist the generation of go_test targets for these Soong modules.
438// The go_library/go_binary will still be generated, since those are hermitic.
439var (
440 goTestsDenylist = []string{
441 "android-archive-zip",
442 "bazel_notice_gen",
443 "blueprint-bootstrap-bpdoc",
444 "blueprint-microfactory",
445 "blueprint-pathtools",
446 "bssl_ar",
447 "compliance_checkmetadata",
448 "compliance_checkshare",
449 "compliance_dumpgraph",
450 "compliance_dumpresolutions",
451 "compliance_listshare",
452 "compliance-module",
453 "compliancenotice_bom",
454 "compliancenotice_shippedlibs",
455 "compliance_rtrace",
456 "compliance_sbom",
457 "golang-protobuf-internal-fuzz-jsonfuzz",
458 "golang-protobuf-internal-fuzz-textfuzz",
459 "golang-protobuf-internal-fuzz-wirefuzz",
460 "htmlnotice",
461 "protoc-gen-go",
462 "rbcrun-module",
463 "spdx-tools-builder",
464 "spdx-tools-builder2v1",
465 "spdx-tools-builder2v2",
466 "spdx-tools-builder2v3",
467 "spdx-tools-idsearcher",
468 "spdx-tools-spdx-json",
469 "spdx-tools-utils",
470 "soong-ui-build",
471 "textnotice",
472 "xmlnotice",
473 }
474)
475
Spandan Das89aa0f72023-06-30 20:18:39 +0000476func testOfGoPackageIsIncompatible(g *bootstrap.GoPackage) bool {
477 return android.InList(g.Name(), goTestsDenylist) ||
478 // Denylist tests of soong_build
479 // Theses tests have a guard that prevent usage outside a test environment
480 // The guard (`ensureTestOnly`) looks for a `-test` in os.Args, which is present in soong's gotestrunner, but missing in `b test`
481 g.IsPluginFor("soong_build") ||
482 // soong-android is a dep of soong_build
483 // 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`
484 g.Name() == "soong-android"
485}
486
487func testOfGoBinaryIsIncompatible(g *bootstrap.GoBinary) bool {
488 return android.InList(g.Name(), goTestsDenylist)
489}
490
Spandan Dasea2abba2023-06-14 21:30:38 +0000491func generateBazelTargetsGoPackage(ctx *android.Context, g *bootstrap.GoPackage, goModulesMap nameToGoLibraryModule) ([]BazelTarget, []error) {
492 ca := android.CommonAttributes{
493 Name: g.Name(),
494 }
Spandan Dasde623292023-06-14 21:30:38 +0000495
496 // For this bootstrap_go_package dep chain,
497 // A --> B --> C ( ---> depends on)
498 // Soong provides the convenience of only listing B as deps of A even if a src file of A imports C
499 // Bazel OTOH
500 // 1. requires C to be listed in `deps` expllicity.
501 // 2. does not require C to be listed if src of A does not import C
502 //
503 // 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
504 transitiveDeps := transitiveGoDeps(g.Deps(), goModulesMap)
505
Spandan Dasea2abba2023-06-14 21:30:38 +0000506 ga := goAttributes{
507 Importpath: bazel.StringAttribute{
508 Value: proptools.StringPtr(g.GoPkgPath()),
509 },
Spandan Das0a8a2752023-06-21 01:50:33 +0000510 Srcs: goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs()),
511 Deps: goDepLabels(
512 android.FirstUniqueStrings(transitiveDeps),
513 goModulesMap,
514 ),
Spandan Dasea2abba2023-06-14 21:30:38 +0000515 Target_compatible_with: targetNotCompatibleWithAndroid(),
516 }
517
Spandan Dasaf725832023-09-19 19:51:52 +0000518 lib := bTarget{
Spandan Dasea2abba2023-06-14 21:30:38 +0000519 targetName: g.Name(),
520 targetPackage: ctx.ModuleDir(g),
521 bazelRuleClass: "go_library",
522 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
523 bazelAttributes: []interface{}{&ca, &ga},
524 }
Spandan Das682e7862023-06-22 22:22:11 +0000525 retTargets := []BazelTarget{}
526 var retErrs []error
527 if libTarget, err := generateBazelTarget(ctx, lib); err == nil {
528 retTargets = append(retTargets, libTarget)
529 } else {
530 retErrs = []error{err}
Spandan Dasea2abba2023-06-14 21:30:38 +0000531 }
Spandan Das682e7862023-06-22 22:22:11 +0000532
533 // If the library contains test srcs, create an additional go_test target
Spandan Das89aa0f72023-06-30 20:18:39 +0000534 if !testOfGoPackageIsIncompatible(g) && (len(g.TestSrcs()) > 0 || len(g.LinuxTestSrcs()) > 0 || len(g.DarwinTestSrcs()) > 0) {
Spandan Das682e7862023-06-22 22:22:11 +0000535 gp := goTestProperties{
536 name: g.Name() + "-test",
537 dir: ctx.ModuleDir(g),
538 testSrcs: g.TestSrcs(),
539 linuxTestSrcs: g.LinuxTestSrcs(),
540 darwinTestSrcs: g.DarwinTestSrcs(),
541 testData: g.TestData(),
542 embedName: g.Name(), // embed the source go_library in the test so that its .go files are included in the compilation unit
543 }
544 if libTestTarget, err := generateBazelTargetsGoTest(ctx, goModulesMap, gp); err == nil {
545 retTargets = append(retTargets, libTestTarget)
546 } else {
547 retErrs = append(retErrs, err)
548 }
549 }
550
551 return retTargets, retErrs
Spandan Dasea2abba2023-06-14 21:30:38 +0000552}
553
554type goLibraryModule struct {
555 Dir string
556 Deps []string
557}
558
Spandan Dasaf725832023-09-19 19:51:52 +0000559type buildConversionMetadata struct {
560 nameToGoLibraryModule nameToGoLibraryModule
561 ndkHeaders []blueprint.Module
562}
563
Spandan Dasea2abba2023-06-14 21:30:38 +0000564type nameToGoLibraryModule map[string]goLibraryModule
565
Spandan Dasaf725832023-09-19 19:51:52 +0000566// Visit each module in the graph, and collect metadata about the build graph
Spandan Dasea2abba2023-06-14 21:30:38 +0000567// 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 +0000568// If a module is of type `ndk_headers`, add it to a list and return the list
569func createBuildConversionMetadata(ctx *android.Context) buildConversionMetadata {
570 goMap := nameToGoLibraryModule{}
571 ndkHeaders := []blueprint.Module{}
Spandan Dasea2abba2023-06-14 21:30:38 +0000572 ctx.VisitAllModules(func(m blueprint.Module) {
573 moduleType := ctx.ModuleType(m)
574 // We do not need to store information about blueprint_go_binary since it does not have any rdeps
575 if moduleType == "bootstrap_go_package" {
Spandan Dasaf725832023-09-19 19:51:52 +0000576 goMap[m.Name()] = goLibraryModule{
Spandan Dasea2abba2023-06-14 21:30:38 +0000577 Dir: ctx.ModuleDir(m),
578 Deps: m.(*bootstrap.GoPackage).Deps(),
579 }
Spandan Dasa7da3f02023-09-28 19:30:51 +0000580 } else if moduleType == "ndk_headers" || moduleType == "versioned_ndk_headers" {
Spandan Dasaf725832023-09-19 19:51:52 +0000581 ndkHeaders = append(ndkHeaders, m)
Spandan Dasea2abba2023-06-14 21:30:38 +0000582 }
583 })
Spandan Dasaf725832023-09-19 19:51:52 +0000584 return buildConversionMetadata{
585 nameToGoLibraryModule: goMap,
586 ndkHeaders: ndkHeaders,
587 }
Spandan Dasea2abba2023-06-14 21:30:38 +0000588}
589
Spandan Dasde623292023-06-14 21:30:38 +0000590// Returns the deps in the transitive closure of a go target
591func transitiveGoDeps(directDeps []string, goModulesMap nameToGoLibraryModule) []string {
592 allDeps := directDeps
593 i := 0
594 for i < len(allDeps) {
595 curr := allDeps[i]
596 allDeps = append(allDeps, goModulesMap[curr].Deps...)
597 i += 1
598 }
599 allDeps = android.SortedUniqueStrings(allDeps)
600 return allDeps
601}
602
603func generateBazelTargetsGoBinary(ctx *android.Context, g *bootstrap.GoBinary, goModulesMap nameToGoLibraryModule) ([]BazelTarget, []error) {
604 ca := android.CommonAttributes{
605 Name: g.Name(),
606 }
607
Spandan Das682e7862023-06-22 22:22:11 +0000608 retTargets := []BazelTarget{}
609 var retErrs []error
610
Spandan Dasde623292023-06-14 21:30:38 +0000611 // For this bootstrap_go_package dep chain,
612 // A --> B --> C ( ---> depends on)
613 // Soong provides the convenience of only listing B as deps of A even if a src file of A imports C
614 // Bazel OTOH
615 // 1. requires C to be listed in `deps` expllicity.
616 // 2. does not require C to be listed if src of A does not import C
617 //
618 // 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
619 transitiveDeps := transitiveGoDeps(g.Deps(), goModulesMap)
620
Spandan Das682e7862023-06-22 22:22:11 +0000621 goSource := ""
622 // If the library contains test srcs, create an additional go_test target
623 // The go_test target will embed a go_source containining the source .go files it tests
Spandan Das89aa0f72023-06-30 20:18:39 +0000624 if !testOfGoBinaryIsIncompatible(g) && (len(g.TestSrcs()) > 0 || len(g.LinuxTestSrcs()) > 0 || len(g.DarwinTestSrcs()) > 0) {
Spandan Das682e7862023-06-22 22:22:11 +0000625 // Create a go_source containing the source .go files of go_library
626 // This target will be an `embed` of the go_binary and go_test
627 goSource = g.Name() + "-source"
628 ca := android.CommonAttributes{
629 Name: goSource,
630 }
631 ga := goAttributes{
632 Srcs: goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs()),
633 Deps: goDepLabels(transitiveDeps, goModulesMap),
634 Target_compatible_with: targetNotCompatibleWithAndroid(),
635 }
Spandan Dasaf725832023-09-19 19:51:52 +0000636 libTestSource := bTarget{
Spandan Das682e7862023-06-22 22:22:11 +0000637 targetName: goSource,
638 targetPackage: ctx.ModuleDir(g),
639 bazelRuleClass: "go_source",
640 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
641 bazelAttributes: []interface{}{&ca, &ga},
642 }
643 if libSourceTarget, err := generateBazelTarget(ctx, libTestSource); err == nil {
644 retTargets = append(retTargets, libSourceTarget)
645 } else {
646 retErrs = append(retErrs, err)
647 }
648
649 // Create a go_test target
650 gp := goTestProperties{
651 name: g.Name() + "-test",
652 dir: ctx.ModuleDir(g),
653 testSrcs: g.TestSrcs(),
654 linuxTestSrcs: g.LinuxTestSrcs(),
655 darwinTestSrcs: g.DarwinTestSrcs(),
656 testData: g.TestData(),
657 // embed the go_source in the test
658 embedName: g.Name() + "-source",
659 }
660 if libTestTarget, err := generateBazelTargetsGoTest(ctx, goModulesMap, gp); err == nil {
661 retTargets = append(retTargets, libTestTarget)
662 } else {
663 retErrs = append(retErrs, err)
664 }
665
666 }
667
668 // Create a go_binary target
Spandan Dasde623292023-06-14 21:30:38 +0000669 ga := goAttributes{
Spandan Dasde623292023-06-14 21:30:38 +0000670 Deps: goDepLabels(transitiveDeps, goModulesMap),
671 Target_compatible_with: targetNotCompatibleWithAndroid(),
672 }
673
Spandan Das682e7862023-06-22 22:22:11 +0000674 // If the binary has testSrcs, embed the common `go_source`
675 if goSource != "" {
676 ga.Embed = bazel.MakeLabelListAttribute(
677 bazel.MakeLabelList(
678 []bazel.Label{bazel.Label{Label: ":" + goSource}},
679 ),
680 )
681 } else {
682 ga.Srcs = goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs())
683 }
684
Spandan Dasaf725832023-09-19 19:51:52 +0000685 bin := bTarget{
Spandan Dasde623292023-06-14 21:30:38 +0000686 targetName: g.Name(),
687 targetPackage: ctx.ModuleDir(g),
688 bazelRuleClass: "go_binary",
689 bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl",
690 bazelAttributes: []interface{}{&ca, &ga},
691 }
Spandan Das682e7862023-06-22 22:22:11 +0000692
693 if binTarget, err := generateBazelTarget(ctx, bin); err == nil {
694 retTargets = append(retTargets, binTarget)
695 } else {
696 retErrs = []error{err}
Spandan Dasde623292023-06-14 21:30:38 +0000697 }
Spandan Das682e7862023-06-22 22:22:11 +0000698
699 return retTargets, retErrs
Spandan Dasde623292023-06-14 21:30:38 +0000700}
701
Liz Kammer6eff3232021-08-26 08:37:59 -0400702func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (conversionResults, []error) {
ustaaaf2fd12023-07-01 11:40:36 -0400703 ctx.Context().BeginEvent("GenerateBazelTargets")
704 defer ctx.Context().EndEvent("GenerateBazelTargets")
Jingwen Chen40067de2021-01-26 21:58:43 -0500705 buildFileToTargets := make(map[string]BazelTargets)
Jingwen Chen164e0862021-02-19 00:48:40 -0500706
707 // Simple metrics tracking for bp2build
usta4f5d2c12022-10-28 23:32:01 -0400708 metrics := CreateCodegenMetrics()
Jingwen Chen164e0862021-02-19 00:48:40 -0500709
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400710 dirs := make(map[string]bool)
Cole Faust11edf552023-10-13 11:32:14 -0700711 moduleNameToPartition := make(map[string]string)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400712
Liz Kammer6eff3232021-08-26 08:37:59 -0400713 var errs []error
714
Spandan Dasea2abba2023-06-14 21:30:38 +0000715 // Visit go libraries in a pre-run and store its state in a map
716 // The time complexity remains O(N), and this does not add significant wall time.
Spandan Dasaf725832023-09-19 19:51:52 +0000717 meta := createBuildConversionMetadata(ctx.Context())
718 nameToGoLibMap := meta.nameToGoLibraryModule
719 ndkHeaders := meta.ndkHeaders
Spandan Dasea2abba2023-06-14 21:30:38 +0000720
Jingwen Chen164e0862021-02-19 00:48:40 -0500721 bpCtx := ctx.Context()
722 bpCtx.VisitAllModules(func(m blueprint.Module) {
723 dir := bpCtx.ModuleDir(m)
Chris Parsons492bd912022-01-20 12:55:05 -0500724 moduleType := bpCtx.ModuleType(m)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400725 dirs[dir] = true
726
Liz Kammer2ada09a2021-08-11 00:17:36 -0400727 var targets []BazelTarget
Spandan Dasea2abba2023-06-14 21:30:38 +0000728 var targetErrs []error
Jingwen Chen73850672020-12-14 08:25:34 -0500729
Jingwen Chen164e0862021-02-19 00:48:40 -0500730 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500731 case Bp2Build:
Chris Parsons0c4de1f2023-09-21 20:36:35 +0000732 if aModule, ok := m.(android.Module); ok {
733 reason := aModule.GetUnconvertedReason()
734 if reason != nil {
735 // If this module was force-enabled, cause an error.
736 if _, ok := ctx.Config().BazelModulesForceEnabledByFlag()[m.Name()]; ok && m.Name() != "" {
737 err := fmt.Errorf("Force Enabled Module %s not converted", m.Name())
738 errs = append(errs, err)
739 }
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000740
Chris Parsons0c4de1f2023-09-21 20:36:35 +0000741 // Log the module isn't to be converted by bp2build.
742 // TODO: b/291598248 - Log handcrafted modules differently than other unconverted modules.
743 metrics.AddUnconvertedModule(m, moduleType, dir, *reason)
744 return
745 }
746 if len(aModule.Bp2buildTargets()) == 0 {
747 panic(fmt.Errorf("illegal bp2build invariant: module '%s' was neither converted nor marked unconvertible", aModule.Name()))
748 }
749
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000750 // Handle modules converted to generated targets.
Chris Parsons0c4de1f2023-09-21 20:36:35 +0000751 targets, targetErrs = generateBazelTargets(bpCtx, aModule)
752 errs = append(errs, targetErrs...)
753 for _, t := range targets {
754 // A module can potentially generate more than 1 Bazel
755 // target, each of a different rule class.
756 metrics.IncrementRuleClassCount(t.ruleClass)
757 }
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000758
Cole Faust11edf552023-10-13 11:32:14 -0700759 // record the partition
760 moduleNameToPartition[android.RemoveOptionalPrebuiltPrefix(aModule.Name())] = aModule.GetPartitionForBp2build()
761
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000762 // Log the module.
Chris Parsons39a16972023-06-08 14:28:51 +0000763 metrics.AddConvertedModule(aModule, moduleType, dir)
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000764
765 // Handle modules with unconverted deps. By default, emit a warning.
Liz Kammer6eff3232021-08-26 08:37:59 -0400766 if unconvertedDeps := aModule.GetUnconvertedBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700767 msg := fmt.Sprintf("%s %s:%s depends on unconverted modules: %s",
768 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400769 switch ctx.unconvertedDepMode {
770 case warnUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400771 metrics.moduleWithUnconvertedDepsMsgs = append(metrics.moduleWithUnconvertedDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400772 case errorModulesUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400773 errs = append(errs, fmt.Errorf(msg))
774 return
775 }
776 }
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500777 if unconvertedDeps := aModule.GetMissingBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700778 msg := fmt.Sprintf("%s %s:%s depends on missing modules: %s",
779 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400780 switch ctx.unconvertedDepMode {
781 case warnUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500782 metrics.moduleWithMissingDepsMsgs = append(metrics.moduleWithMissingDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400783 case errorModulesUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500784 errs = append(errs, fmt.Errorf(msg))
785 return
786 }
787 }
Spandan Dasea2abba2023-06-14 21:30:38 +0000788 } else if glib, ok := m.(*bootstrap.GoPackage); ok {
789 targets, targetErrs = generateBazelTargetsGoPackage(bpCtx, glib, nameToGoLibMap)
790 errs = append(errs, targetErrs...)
Liz Kammer15d7b0b2023-09-27 09:38:41 -0400791 metrics.IncrementRuleClassCount("bootstrap_go_package")
792 metrics.AddConvertedModule(glib, "bootstrap_go_package", dir)
Spandan Das2a55cea2023-06-14 17:56:10 +0000793 } else if gbin, ok := m.(*bootstrap.GoBinary); ok {
Spandan Dasde623292023-06-14 21:30:38 +0000794 targets, targetErrs = generateBazelTargetsGoBinary(bpCtx, gbin, nameToGoLibMap)
795 errs = append(errs, targetErrs...)
Liz Kammer15d7b0b2023-09-27 09:38:41 -0400796 metrics.IncrementRuleClassCount("blueprint_go_binary")
797 metrics.AddConvertedModule(gbin, "blueprint_go_binary", dir)
Liz Kammerfc46bc12021-02-19 11:06:17 -0500798 } else {
Chris Parsons39a16972023-06-08 14:28:51 +0000799 metrics.AddUnconvertedModule(m, moduleType, dir, android.UnconvertedReason{
800 ReasonType: int(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED),
801 })
Liz Kammerba3ea162021-02-17 13:22:03 -0500802 return
Jingwen Chen73850672020-12-14 08:25:34 -0500803 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500804 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500805 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500806 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500807 // package module name contain slashes, and thus cannot
808 // be mapped cleanly to a bazel label.
809 return
810 }
Alix94e26032022-08-16 20:37:33 +0000811 t, err := generateSoongModuleTarget(bpCtx, m)
812 if err != nil {
813 errs = append(errs, err)
814 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400815 targets = append(targets, t)
Jingwen Chen33832f92021-01-24 22:55:54 -0500816 default:
Liz Kammer6eff3232021-08-26 08:37:59 -0400817 errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
818 return
Jingwen Chen73850672020-12-14 08:25:34 -0500819 }
820
Spandan Dasabedff02023-03-07 19:24:34 +0000821 for _, target := range targets {
822 targetDir := target.PackageName()
823 buildFileToTargets[targetDir] = append(buildFileToTargets[targetDir], target)
824 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800825 })
Liz Kammer6eff3232021-08-26 08:37:59 -0400826
Spandan Dasaf725832023-09-19 19:51:52 +0000827 // Create an ndk_sysroot target that has a dependency edge on every target corresponding to Soong's ndk_headers
828 // This root target will provide headers to sdk variants of jni libraries
829 if ctx.Mode() == Bp2Build {
830 var depLabels bazel.LabelList
831 for _, ndkHeader := range ndkHeaders {
832 depLabel := bazel.Label{
833 Label: "//" + bpCtx.ModuleDir(ndkHeader) + ":" + ndkHeader.Name(),
834 }
835 depLabels.Add(&depLabel)
836 }
837 a := struct {
Liz Kammer96da2ba2023-10-13 16:22:24 -0400838 Deps bazel.LabelListAttribute
Spandan Dasaf725832023-09-19 19:51:52 +0000839 }{
Liz Kammer96da2ba2023-10-13 16:22:24 -0400840 Deps: bazel.MakeLabelListAttribute(bazel.UniqueSortedBazelLabelList(depLabels)),
Spandan Dasaf725832023-09-19 19:51:52 +0000841 }
842 ndkSysroot := bTarget{
843 targetName: "ndk_sysroot",
844 targetPackage: "build/bazel/rules/cc", // The location is subject to change, use build/bazel for now
845 bazelRuleClass: "cc_library_headers",
846 bazelRuleLoadLocation: "//build/bazel/rules/cc:cc_library_headers.bzl",
847 bazelAttributes: []interface{}{&a},
848 }
849
850 if t, err := generateBazelTarget(bpCtx, ndkSysroot); err == nil {
851 dir := ndkSysroot.targetPackage
852 buildFileToTargets[dir] = append(buildFileToTargets[dir], t)
853 } else {
854 errs = append(errs, err)
855 }
856 }
857
Liz Kammer6eff3232021-08-26 08:37:59 -0400858 if len(errs) > 0 {
859 return conversionResults{}, errs
860 }
861
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400862 if generateFilegroups {
863 // Add a filegroup target that exposes all sources in the subtree of this package
864 // 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 -0700865 //
866 // This works because: https://bazel.build/reference/be/functions#exports_files
867 // "As a legacy behaviour, also files mentioned as input to a rule are exported with the
868 // default visibility until the flag --incompatible_no_implicit_file_export is flipped. However, this behavior
869 // should not be relied upon and actively migrated away from."
870 //
871 // TODO(b/198619163): We should change this to export_files(glob(["**/*"])) instead, but doing that causes these errors:
872 // "Error in exports_files: generated label '//external/avb:avbtool' conflicts with existing py_binary rule"
873 // So we need to solve all the "target ... is both a rule and a file" warnings first.
Usta Shresthac6057152022-09-24 00:23:31 -0400874 for dir := range dirs {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400875 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
876 name: "bp2build_all_srcs",
Jingwen Chen5802d072023-09-20 10:25:09 +0000877 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]), tags = ["manual"])`,
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400878 ruleClass: "filegroup",
879 })
880 }
881 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500882
Liz Kammer6eff3232021-08-26 08:37:59 -0400883 return conversionResults{
Cole Faust11edf552023-10-13 11:32:14 -0700884 buildFileToTargets: buildFileToTargets,
885 moduleNameToPartition: moduleNameToPartition,
886 metrics: metrics,
Liz Kammer6eff3232021-08-26 08:37:59 -0400887 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500888}
889
Alix94e26032022-08-16 20:37:33 +0000890func generateBazelTargets(ctx bpToBuildContext, m android.Module) ([]BazelTarget, []error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400891 var targets []BazelTarget
Alix94e26032022-08-16 20:37:33 +0000892 var errs []error
Liz Kammer2ada09a2021-08-11 00:17:36 -0400893 for _, m := range m.Bp2buildTargets() {
Alix94e26032022-08-16 20:37:33 +0000894 target, err := generateBazelTarget(ctx, m)
895 if err != nil {
896 errs = append(errs, err)
897 return targets, errs
898 }
899 targets = append(targets, target)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400900 }
Alix94e26032022-08-16 20:37:33 +0000901 return targets, errs
Liz Kammer2ada09a2021-08-11 00:17:36 -0400902}
903
904type bp2buildModule interface {
905 TargetName() string
906 TargetPackage() string
907 BazelRuleClass() string
908 BazelRuleLoadLocation() string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000909 BazelAttributes() []interface{}
Liz Kammer2ada09a2021-08-11 00:17:36 -0400910}
911
Alix94e26032022-08-16 20:37:33 +0000912func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) (BazelTarget, error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400913 ruleClass := m.BazelRuleClass()
914 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500915
Jingwen Chen73850672020-12-14 08:25:34 -0500916 // extract the bazel attributes from the module.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000917 attrs := m.BazelAttributes()
Alix94e26032022-08-16 20:37:33 +0000918 props, err := extractModuleProperties(attrs, true)
919 if err != nil {
920 return BazelTarget{}, err
921 }
Jingwen Chen73850672020-12-14 08:25:34 -0500922
Liz Kammer0eae52e2021-10-06 10:32:26 -0400923 // name is handled in a special manner
924 delete(props.Attrs, "name")
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500925
Jingwen Chen73850672020-12-14 08:25:34 -0500926 // Return the Bazel target with rule class and attributes, ready to be
927 // code-generated.
928 attributes := propsToAttributes(props.Attrs)
Sasha Smundakfb589492022-08-04 11:13:27 -0700929 var content string
Liz Kammer2ada09a2021-08-11 00:17:36 -0400930 targetName := m.TargetName()
Sasha Smundakfb589492022-08-04 11:13:27 -0700931 if targetName != "" {
932 content = fmt.Sprintf(ruleTargetTemplate, ruleClass, targetName, attributes)
933 } else {
934 content = fmt.Sprintf(unnamedRuleTargetTemplate, ruleClass, attributes)
935 }
Cole Faustb4cb0c82023-09-14 15:16:58 -0700936 var loads []BazelLoad
937 if bzlLoadLocation != "" {
938 loads = append(loads, BazelLoad{
939 file: bzlLoadLocation,
940 symbols: []BazelLoadSymbol{{symbol: ruleClass}},
941 })
942 }
Jingwen Chen73850672020-12-14 08:25:34 -0500943 return BazelTarget{
Cole Faustb4cb0c82023-09-14 15:16:58 -0700944 name: targetName,
945 packageName: m.TargetPackage(),
946 ruleClass: ruleClass,
947 loads: loads,
948 content: content,
Alix94e26032022-08-16 20:37:33 +0000949 }, nil
Jingwen Chen73850672020-12-14 08:25:34 -0500950}
951
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800952// Convert a module and its deps and props into a Bazel macro/rule
953// representation in the BUILD file.
Alix94e26032022-08-16 20:37:33 +0000954func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) (BazelTarget, error) {
955 props, err := getBuildProperties(ctx, m)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800956
957 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
958 // items, if the modules are added using different DependencyTag. Figure
959 // out the implications of that.
960 depLabels := map[string]bool{}
961 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500962 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800963 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
964 })
965 }
Liz Kammer0eae52e2021-10-06 10:32:26 -0400966
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400967 for p := range ignoredPropNames {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400968 delete(props.Attrs, p)
969 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800970 attributes := propsToAttributes(props.Attrs)
971
972 depLabelList := "[\n"
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400973 for depLabel := range depLabels {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800974 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
975 }
976 depLabelList += " ]"
977
978 targetName := targetNameWithVariant(ctx, m)
979 return BazelTarget{
Spandan Dasabedff02023-03-07 19:24:34 +0000980 name: targetName,
981 packageName: ctx.ModuleDir(m),
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800982 content: fmt.Sprintf(
Sasha Smundakfb589492022-08-04 11:13:27 -0700983 soongModuleTargetTemplate,
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800984 targetName,
985 ctx.ModuleName(m),
986 canonicalizeModuleType(ctx.ModuleType(m)),
987 ctx.ModuleSubDir(m),
988 depLabelList,
989 attributes),
Alix94e26032022-08-16 20:37:33 +0000990 }, err
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800991}
992
Alix94e26032022-08-16 20:37:33 +0000993func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800994 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
995 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
996 if aModule, ok := m.(android.Module); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000997 return extractModuleProperties(aModule.GetProperties(), false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800998 }
999
Alix94e26032022-08-16 20:37:33 +00001000 return BazelAttributes{}, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001001}
1002
1003// Generically extract module properties and types into a map, keyed by the module property name.
Alix94e26032022-08-16 20:37:33 +00001004func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001005 ret := map[string]string{}
1006
1007 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -04001008 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001009 propertiesValue := reflect.ValueOf(properties)
1010 // Check that propertiesValue is a pointer to the Properties struct, like
1011 // *cc.BaseLinkerProperties or *java.CompilerProperties.
1012 //
1013 // propertiesValue can also be type-asserted to the structs to
1014 // manipulate internal props, if needed.
1015 if isStructPtr(propertiesValue.Type()) {
1016 structValue := propertiesValue.Elem()
Alix94e26032022-08-16 20:37:33 +00001017 ok, err := extractStructProperties(structValue, 0)
1018 if err != nil {
1019 return BazelAttributes{}, err
1020 }
1021 for k, v := range ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001022 if existing, exists := ret[k]; checkForDuplicateProperties && exists {
Alix94e26032022-08-16 20:37:33 +00001023 return BazelAttributes{}, fmt.Errorf(
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001024 "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes",
Alix94e26032022-08-16 20:37:33 +00001025 k, existing)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001026 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001027 ret[k] = v
1028 }
1029 } else {
Alix94e26032022-08-16 20:37:33 +00001030 return BazelAttributes{},
1031 fmt.Errorf(
1032 "properties must be a pointer to a struct, got %T",
1033 propertiesValue.Interface())
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001034 }
1035 }
1036
Liz Kammer2ada09a2021-08-11 00:17:36 -04001037 return BazelAttributes{
1038 Attrs: ret,
Alix94e26032022-08-16 20:37:33 +00001039 }, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001040}
1041
1042func isStructPtr(t reflect.Type) bool {
1043 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
1044}
1045
1046// prettyPrint a property value into the equivalent Starlark representation
1047// recursively.
Jingwen Chen58ff6802021-11-17 12:14:41 +00001048func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) {
1049 if !emitZeroValues && isZero(propertyValue) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001050 // A property value being set or unset actually matters -- Soong does set default
1051 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
1052 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
1053 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +00001054 // In Bazel-parlance, we would use "attr.<type>(default = <default
1055 // value>)" to set the default value of unset attributes. In the cases
1056 // where the bp2build converter didn't set the default value within the
1057 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -04001058 // value. For those cases, we return an empty string so we don't
1059 // unnecessarily generate empty values.
1060 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001061 }
1062
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001063 switch propertyValue.Kind() {
1064 case reflect.String:
Liz Kammer72beb342022-02-03 08:42:10 -05001065 return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001066 case reflect.Bool:
Liz Kammer72beb342022-02-03 08:42:10 -05001067 return starlark_fmt.PrintBool(propertyValue.Bool()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001068 case reflect.Int, reflect.Uint, reflect.Int64:
Liz Kammer72beb342022-02-03 08:42:10 -05001069 return fmt.Sprintf("%v", propertyValue.Interface()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001070 case reflect.Ptr:
Jingwen Chen58ff6802021-11-17 12:14:41 +00001071 return prettyPrint(propertyValue.Elem(), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001072 case reflect.Slice:
Liz Kammer72beb342022-02-03 08:42:10 -05001073 elements := make([]string, 0, propertyValue.Len())
1074 for i := 0; i < propertyValue.Len(); i++ {
1075 val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001076 if err != nil {
1077 return "", err
1078 }
Liz Kammer72beb342022-02-03 08:42:10 -05001079 if val != "" {
1080 elements = append(elements, val)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001081 }
1082 }
Sam Delmerico932c01c2022-03-25 16:33:26 +00001083 return starlark_fmt.PrintList(elements, indent, func(s string) string {
1084 return "%s"
1085 }), nil
Jingwen Chenb4628eb2021-04-08 14:40:57 +00001086
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001087 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -05001088 // Special cases where the bp2build sends additional information to the codegenerator
1089 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +00001090 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
1091 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -05001092 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
1093 return fmt.Sprintf("%q", label.Label), nil
1094 }
1095
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001096 // Sort and print the struct props by the key.
Alix94e26032022-08-16 20:37:33 +00001097 structProps, err := extractStructProperties(propertyValue, indent)
1098
1099 if err != nil {
1100 return "", err
1101 }
1102
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001103 if len(structProps) == 0 {
1104 return "", nil
1105 }
Liz Kammer72beb342022-02-03 08:42:10 -05001106 return starlark_fmt.PrintDict(structProps, indent), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001107 case reflect.Interface:
1108 // TODO(b/164227191): implement pretty print for interfaces.
1109 // Interfaces are used for for arch, multilib and target properties.
1110 return "", nil
Spandan Das6a448ec2023-04-19 17:36:12 +00001111 case reflect.Map:
1112 if v, ok := propertyValue.Interface().(bazel.StringMapAttribute); ok {
1113 return starlark_fmt.PrintStringStringDict(v, indent), nil
1114 }
1115 return "", fmt.Errorf("bp2build expects map of type map[string]string for field: %s", propertyValue)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001116 default:
1117 return "", fmt.Errorf(
1118 "unexpected kind for property struct field: %s", propertyValue.Kind())
1119 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001120}
1121
1122// Converts a reflected property struct value into a map of property names and property values,
1123// which each property value correctly pretty-printed and indented at the right nest level,
1124// since property structs can be nested. In Starlark, nested structs are represented as nested
1125// dicts: https://docs.bazel.build/skylark/lib/dict.html
Alix94e26032022-08-16 20:37:33 +00001126func extractStructProperties(structValue reflect.Value, indent int) (map[string]string, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001127 if structValue.Kind() != reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001128 return map[string]string{}, fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind())
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001129 }
1130
Alix94e26032022-08-16 20:37:33 +00001131 var err error
1132
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001133 ret := map[string]string{}
1134 structType := structValue.Type()
1135 for i := 0; i < structValue.NumField(); i++ {
1136 field := structType.Field(i)
1137 if shouldSkipStructField(field) {
1138 continue
1139 }
1140
1141 fieldValue := structValue.Field(i)
1142 if isZero(fieldValue) {
1143 // Ignore zero-valued fields
1144 continue
1145 }
Liz Kammer7a210ac2021-09-22 15:52:58 -04001146
Liz Kammer32a03392021-09-14 11:17:21 -04001147 // if the struct is embedded (anonymous), flatten the properties into the containing struct
1148 if field.Anonymous {
1149 if field.Type.Kind() == reflect.Ptr {
1150 fieldValue = fieldValue.Elem()
1151 }
1152 if fieldValue.Type().Kind() == reflect.Struct {
Alix94e26032022-08-16 20:37:33 +00001153 propsToMerge, err := extractStructProperties(fieldValue, indent)
1154 if err != nil {
1155 return map[string]string{}, err
1156 }
Liz Kammer32a03392021-09-14 11:17:21 -04001157 for prop, value := range propsToMerge {
1158 ret[prop] = value
1159 }
1160 continue
1161 }
1162 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001163
1164 propertyName := proptools.PropertyNameForField(field.Name)
Alix94e26032022-08-16 20:37:33 +00001165 var prettyPrintedValue string
1166 prettyPrintedValue, err = prettyPrint(fieldValue, indent+1, false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001167 if err != nil {
Alix94e26032022-08-16 20:37:33 +00001168 return map[string]string{}, fmt.Errorf(
1169 "Error while parsing property: %q. %s",
1170 propertyName,
1171 err)
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001172 }
1173 if prettyPrintedValue != "" {
1174 ret[propertyName] = prettyPrintedValue
1175 }
1176 }
1177
Alix94e26032022-08-16 20:37:33 +00001178 return ret, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001179}
1180
1181func isZero(value reflect.Value) bool {
1182 switch value.Kind() {
1183 case reflect.Func, reflect.Map, reflect.Slice:
1184 return value.IsNil()
1185 case reflect.Array:
1186 valueIsZero := true
1187 for i := 0; i < value.Len(); i++ {
1188 valueIsZero = valueIsZero && isZero(value.Index(i))
1189 }
1190 return valueIsZero
1191 case reflect.Struct:
1192 valueIsZero := true
1193 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +02001194 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001195 }
1196 return valueIsZero
1197 case reflect.Ptr:
1198 if !value.IsNil() {
1199 return isZero(reflect.Indirect(value))
1200 } else {
1201 return true
1202 }
Liz Kammer46fb7ab2021-12-01 10:09:34 -05001203 // Always print bool/strings, if you want a bool/string attribute to be able to take the default value, use a
1204 // pointer instead
1205 case reflect.Bool, reflect.String:
Liz Kammerd366c902021-06-03 13:43:01 -04001206 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001207 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -04001208 if !value.IsValid() {
1209 return true
1210 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001211 zeroValue := reflect.Zero(value.Type())
1212 result := value.Interface() == zeroValue.Interface()
1213 return result
1214 }
1215}
1216
1217func escapeString(s string) string {
1218 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +00001219
1220 // b/184026959: Reverse the application of some common control sequences.
1221 // These must be generated literally in the BUILD file.
1222 s = strings.ReplaceAll(s, "\t", "\\t")
1223 s = strings.ReplaceAll(s, "\n", "\\n")
1224 s = strings.ReplaceAll(s, "\r", "\\r")
1225
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001226 return strings.ReplaceAll(s, "\"", "\\\"")
1227}
1228
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001229func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
1230 name := ""
1231 if c.ModuleSubDir(logicModule) != "" {
1232 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
1233 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
1234 } else {
1235 name = c.ModuleName(logicModule)
1236 }
1237
1238 return strings.Replace(name, "//", "", 1)
1239}
1240
1241func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
1242 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
1243}