blob: 82ce115f6149aec09ea3f811af45c8a7c9a49c55 [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"
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux0da7ce62021-08-23 17:04:20 +000031
Liz Kammer2dd9ca42020-11-25 16:06:39 -080032 "github.com/google/blueprint"
33 "github.com/google/blueprint/proptools"
34)
35
36type BazelAttributes struct {
37 Attrs map[string]string
38}
39
40type BazelTarget struct {
Jingwen Chen40067de2021-01-26 21:58:43 -050041 name string
Jingwen Chenc63677b2021-06-17 05:43:19 +000042 packageName string
Jingwen Chen40067de2021-01-26 21:58:43 -050043 content string
44 ruleClass string
45 bzlLoadLocation string
46}
47
48// IsLoadedFromStarlark determines if the BazelTarget's rule class is loaded from a .bzl file,
49// as opposed to a native rule built into Bazel.
50func (t BazelTarget) IsLoadedFromStarlark() bool {
51 return t.bzlLoadLocation != ""
52}
53
Jingwen Chenc63677b2021-06-17 05:43:19 +000054// Label is the fully qualified Bazel label constructed from the BazelTarget's
55// package name and target name.
56func (t BazelTarget) Label() string {
57 if t.packageName == "." {
58 return "//:" + t.name
59 } else {
60 return "//" + t.packageName + ":" + t.name
61 }
62}
63
Jingwen Chen40067de2021-01-26 21:58:43 -050064// BazelTargets is a typedef for a slice of BazelTarget objects.
65type BazelTargets []BazelTarget
66
Sasha Smundak8bea2672022-08-04 13:31:14 -070067func (targets BazelTargets) packageRule() *BazelTarget {
68 for _, target := range targets {
69 if target.ruleClass == "package" {
70 return &target
71 }
72 }
73 return nil
74}
75
76// sort a list of BazelTargets in-place, by name, and by generated/handcrafted types.
Jingwen Chen49109762021-05-25 05:16:48 +000077func (targets BazelTargets) sort() {
78 sort.Slice(targets, func(i, j int) bool {
Jingwen Chen49109762021-05-25 05:16:48 +000079 return targets[i].name < targets[j].name
80 })
81}
82
Jingwen Chen40067de2021-01-26 21:58:43 -050083// String returns the string representation of BazelTargets, without load
84// statements (use LoadStatements for that), since the targets are usually not
85// adjacent to the load statements at the top of the BUILD file.
86func (targets BazelTargets) String() string {
87 var res string
88 for i, target := range targets {
Sasha Smundak8bea2672022-08-04 13:31:14 -070089 if target.ruleClass != "package" {
90 res += target.content
91 }
Jingwen Chen40067de2021-01-26 21:58:43 -050092 if i != len(targets)-1 {
93 res += "\n\n"
94 }
95 }
96 return res
97}
98
99// LoadStatements return the string representation of the sorted and deduplicated
100// Starlark rule load statements needed by a group of BazelTargets.
101func (targets BazelTargets) LoadStatements() string {
102 bzlToLoadedSymbols := map[string][]string{}
103 for _, target := range targets {
104 if target.IsLoadedFromStarlark() {
105 bzlToLoadedSymbols[target.bzlLoadLocation] =
106 append(bzlToLoadedSymbols[target.bzlLoadLocation], target.ruleClass)
107 }
108 }
109
110 var loadStatements []string
111 for bzl, ruleClasses := range bzlToLoadedSymbols {
112 loadStatement := "load(\""
113 loadStatement += bzl
114 loadStatement += "\", "
115 ruleClasses = android.SortedUniqueStrings(ruleClasses)
116 for i, ruleClass := range ruleClasses {
117 loadStatement += "\"" + ruleClass + "\""
118 if i != len(ruleClasses)-1 {
119 loadStatement += ", "
120 }
121 }
122 loadStatement += ")"
123 loadStatements = append(loadStatements, loadStatement)
124 }
125 return strings.Join(android.SortedUniqueStrings(loadStatements), "\n")
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800126}
127
128type bpToBuildContext interface {
129 ModuleName(module blueprint.Module) string
130 ModuleDir(module blueprint.Module) string
131 ModuleSubDir(module blueprint.Module) string
132 ModuleType(module blueprint.Module) string
133
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500134 VisitAllModules(visit func(blueprint.Module))
135 VisitDirectDeps(module blueprint.Module, visit func(blueprint.Module))
136}
137
138type CodegenContext struct {
Jingwen Chen16d90a82021-09-17 07:16:13 +0000139 config android.Config
140 context android.Context
141 mode CodegenMode
142 additionalDeps []string
Liz Kammer6eff3232021-08-26 08:37:59 -0400143 unconvertedDepMode unconvertedDepsMode
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500144}
145
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400146func (ctx *CodegenContext) Mode() CodegenMode {
147 return ctx.mode
Jingwen Chen164e0862021-02-19 00:48:40 -0500148}
149
Jingwen Chen33832f92021-01-24 22:55:54 -0500150// CodegenMode is an enum to differentiate code-generation modes.
151type CodegenMode int
152
153const (
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400154 // Bp2Build - generate BUILD files with targets buildable by Bazel directly.
Jingwen Chen33832f92021-01-24 22:55:54 -0500155 //
156 // This mode is used for the Soong->Bazel build definition conversion.
157 Bp2Build CodegenMode = iota
158
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400159 // QueryView - generate BUILD files with targets representing fully mutated
Jingwen Chen33832f92021-01-24 22:55:54 -0500160 // Soong modules, representing the fully configured Soong module graph with
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400161 // variants and dependency edges.
Jingwen Chen33832f92021-01-24 22:55:54 -0500162 //
163 // This mode is used for discovering and introspecting the existing Soong
164 // module graph.
165 QueryView
Spandan Das5af0bd32022-09-28 20:43:08 +0000166
167 // ApiBp2build - generate BUILD files for API contribution targets
168 ApiBp2build
Jingwen Chen33832f92021-01-24 22:55:54 -0500169)
170
Liz Kammer6eff3232021-08-26 08:37:59 -0400171type unconvertedDepsMode int
172
173const (
174 // Include a warning in conversion metrics about converted modules with unconverted direct deps
175 warnUnconvertedDeps unconvertedDepsMode = iota
176 // Error and fail conversion if encountering a module with unconverted direct deps
177 // Enabled by setting environment variable `BP2BUILD_ERROR_UNCONVERTED`
178 errorModulesUnconvertedDeps
179)
180
Jingwen Chendcc329a2021-01-26 02:49:03 -0500181func (mode CodegenMode) String() string {
182 switch mode {
183 case Bp2Build:
184 return "Bp2Build"
185 case QueryView:
186 return "QueryView"
Spandan Das5af0bd32022-09-28 20:43:08 +0000187 case ApiBp2build:
188 return "ApiBp2build"
Jingwen Chendcc329a2021-01-26 02:49:03 -0500189 default:
190 return fmt.Sprintf("%d", mode)
191 }
192}
193
Liz Kammerba3ea162021-02-17 13:22:03 -0500194// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
195// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
196// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
197// call AdditionalNinjaDeps and add them manually to the ninja file.
198func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
199 ctx.additionalDeps = append(ctx.additionalDeps, deps...)
200}
201
202// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
203func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
204 return ctx.additionalDeps
205}
206
207func (ctx *CodegenContext) Config() android.Config { return ctx.config }
208func (ctx *CodegenContext) Context() android.Context { return ctx.context }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500209
210// NewCodegenContext creates a wrapper context that conforms to PathContext for
211// writing BUILD files in the output directory.
Liz Kammerba3ea162021-02-17 13:22:03 -0500212func NewCodegenContext(config android.Config, context android.Context, mode CodegenMode) *CodegenContext {
Liz Kammer6eff3232021-08-26 08:37:59 -0400213 var unconvertedDeps unconvertedDepsMode
214 if config.IsEnvTrue("BP2BUILD_ERROR_UNCONVERTED") {
215 unconvertedDeps = errorModulesUnconvertedDeps
216 }
Liz Kammerba3ea162021-02-17 13:22:03 -0500217 return &CodegenContext{
Liz Kammer6eff3232021-08-26 08:37:59 -0400218 context: context,
219 config: config,
220 mode: mode,
221 unconvertedDepMode: unconvertedDeps,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500222 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800223}
224
225// props is an unsorted map. This function ensures that
226// the generated attributes are sorted to ensure determinism.
227func propsToAttributes(props map[string]string) string {
228 var attributes string
229 for _, propName := range android.SortedStringKeys(props) {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400230 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800231 }
232 return attributes
233}
234
Liz Kammer6eff3232021-08-26 08:37:59 -0400235type conversionResults struct {
236 buildFileToTargets map[string]BazelTargets
237 metrics CodegenMetrics
Liz Kammer6eff3232021-08-26 08:37:59 -0400238}
239
240func (r conversionResults) BuildDirToTargets() map[string]BazelTargets {
241 return r.buildFileToTargets
242}
243
244func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (conversionResults, []error) {
Jingwen Chen40067de2021-01-26 21:58:43 -0500245 buildFileToTargets := make(map[string]BazelTargets)
Jingwen Chen164e0862021-02-19 00:48:40 -0500246
247 // Simple metrics tracking for bp2build
Liz Kammerba3ea162021-02-17 13:22:03 -0500248 metrics := CodegenMetrics{
Chris Parsons492bd912022-01-20 12:55:05 -0500249 ruleClassCount: make(map[string]uint64),
Kevin Dagostino60f562a2022-09-20 03:54:47 +0000250 convertedModulePathMap: make(map[string]string),
Chris Parsons492bd912022-01-20 12:55:05 -0500251 convertedModuleTypeCount: make(map[string]uint64),
252 totalModuleTypeCount: make(map[string]uint64),
Liz Kammerba3ea162021-02-17 13:22:03 -0500253 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500254
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400255 dirs := make(map[string]bool)
256
Liz Kammer6eff3232021-08-26 08:37:59 -0400257 var errs []error
258
Jingwen Chen164e0862021-02-19 00:48:40 -0500259 bpCtx := ctx.Context()
260 bpCtx.VisitAllModules(func(m blueprint.Module) {
261 dir := bpCtx.ModuleDir(m)
Chris Parsons492bd912022-01-20 12:55:05 -0500262 moduleType := bpCtx.ModuleType(m)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400263 dirs[dir] = true
264
Liz Kammer2ada09a2021-08-11 00:17:36 -0400265 var targets []BazelTarget
Jingwen Chen73850672020-12-14 08:25:34 -0500266
Jingwen Chen164e0862021-02-19 00:48:40 -0500267 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500268 case Bp2Build:
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000269 // There are two main ways of converting a Soong module to Bazel:
270 // 1) Manually handcrafting a Bazel target and associating the module with its label
271 // 2) Automatically generating with bp2build converters
272 //
273 // bp2build converters are used for the majority of modules.
Liz Kammerba3ea162021-02-17 13:22:03 -0500274 if b, ok := m.(android.Bazelable); ok && b.HasHandcraftedLabel() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000275 // Handle modules converted to handcrafted targets.
276 //
277 // Since these modules are associated with some handcrafted
Cole Faustea602c52022-08-31 14:48:26 -0700278 // target in a BUILD file, we don't autoconvert them.
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000279
280 // Log the module.
Kevin Dagostino60f562a2022-09-20 03:54:47 +0000281 metrics.AddConvertedModule(m, moduleType, dir, Handcrafted)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400282 } else if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000283 // Handle modules converted to generated targets.
284
285 // Log the module.
Kevin Dagostino60f562a2022-09-20 03:54:47 +0000286 metrics.AddConvertedModule(aModule, moduleType, dir, Generated)
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000287
288 // Handle modules with unconverted deps. By default, emit a warning.
Liz Kammer6eff3232021-08-26 08:37:59 -0400289 if unconvertedDeps := aModule.GetUnconvertedBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700290 msg := fmt.Sprintf("%s %s:%s depends on unconverted modules: %s",
291 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400292 switch ctx.unconvertedDepMode {
293 case warnUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400294 metrics.moduleWithUnconvertedDepsMsgs = append(metrics.moduleWithUnconvertedDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400295 case errorModulesUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400296 errs = append(errs, fmt.Errorf(msg))
297 return
298 }
299 }
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500300 if unconvertedDeps := aModule.GetMissingBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700301 msg := fmt.Sprintf("%s %s:%s depends on missing modules: %s",
302 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400303 switch ctx.unconvertedDepMode {
304 case warnUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500305 metrics.moduleWithMissingDepsMsgs = append(metrics.moduleWithMissingDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400306 case errorModulesUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500307 errs = append(errs, fmt.Errorf(msg))
308 return
309 }
310 }
Alix94e26032022-08-16 20:37:33 +0000311 var targetErrs []error
312 targets, targetErrs = generateBazelTargets(bpCtx, aModule)
313 errs = append(errs, targetErrs...)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400314 for _, t := range targets {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000315 // A module can potentially generate more than 1 Bazel
316 // target, each of a different rule class.
317 metrics.IncrementRuleClassCount(t.ruleClass)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400318 }
Liz Kammerfc46bc12021-02-19 11:06:17 -0500319 } else {
Chris Parsons492bd912022-01-20 12:55:05 -0500320 metrics.AddUnconvertedModule(moduleType)
Liz Kammerba3ea162021-02-17 13:22:03 -0500321 return
Jingwen Chen73850672020-12-14 08:25:34 -0500322 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500323 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500324 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500325 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500326 // package module name contain slashes, and thus cannot
327 // be mapped cleanly to a bazel label.
328 return
329 }
Alix94e26032022-08-16 20:37:33 +0000330 t, err := generateSoongModuleTarget(bpCtx, m)
331 if err != nil {
332 errs = append(errs, err)
333 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400334 targets = append(targets, t)
Spandan Das5af0bd32022-09-28 20:43:08 +0000335 case ApiBp2build:
336 if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
337 targets, errs = generateBazelTargets(bpCtx, aModule)
338 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500339 default:
Liz Kammer6eff3232021-08-26 08:37:59 -0400340 errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
341 return
Jingwen Chen73850672020-12-14 08:25:34 -0500342 }
343
Liz Kammer2ada09a2021-08-11 00:17:36 -0400344 buildFileToTargets[dir] = append(buildFileToTargets[dir], targets...)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800345 })
Liz Kammer6eff3232021-08-26 08:37:59 -0400346
347 if len(errs) > 0 {
348 return conversionResults{}, errs
349 }
350
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400351 if generateFilegroups {
352 // Add a filegroup target that exposes all sources in the subtree of this package
353 // 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 -0700354 //
355 // This works because: https://bazel.build/reference/be/functions#exports_files
356 // "As a legacy behaviour, also files mentioned as input to a rule are exported with the
357 // default visibility until the flag --incompatible_no_implicit_file_export is flipped. However, this behavior
358 // should not be relied upon and actively migrated away from."
359 //
360 // TODO(b/198619163): We should change this to export_files(glob(["**/*"])) instead, but doing that causes these errors:
361 // "Error in exports_files: generated label '//external/avb:avbtool' conflicts with existing py_binary rule"
362 // So we need to solve all the "target ... is both a rule and a file" warnings first.
Usta Shresthac6057152022-09-24 00:23:31 -0400363 for dir := range dirs {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400364 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
365 name: "bp2build_all_srcs",
366 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]))`,
367 ruleClass: "filegroup",
368 })
369 }
370 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500371
Liz Kammer6eff3232021-08-26 08:37:59 -0400372 return conversionResults{
373 buildFileToTargets: buildFileToTargets,
374 metrics: metrics,
Liz Kammer6eff3232021-08-26 08:37:59 -0400375 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500376}
377
Alix94e26032022-08-16 20:37:33 +0000378func generateBazelTargets(ctx bpToBuildContext, m android.Module) ([]BazelTarget, []error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400379 var targets []BazelTarget
Alix94e26032022-08-16 20:37:33 +0000380 var errs []error
Liz Kammer2ada09a2021-08-11 00:17:36 -0400381 for _, m := range m.Bp2buildTargets() {
Alix94e26032022-08-16 20:37:33 +0000382 target, err := generateBazelTarget(ctx, m)
383 if err != nil {
384 errs = append(errs, err)
385 return targets, errs
386 }
387 targets = append(targets, target)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400388 }
Alix94e26032022-08-16 20:37:33 +0000389 return targets, errs
Liz Kammer2ada09a2021-08-11 00:17:36 -0400390}
391
392type bp2buildModule interface {
393 TargetName() string
394 TargetPackage() string
395 BazelRuleClass() string
396 BazelRuleLoadLocation() string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000397 BazelAttributes() []interface{}
Liz Kammer2ada09a2021-08-11 00:17:36 -0400398}
399
Alix94e26032022-08-16 20:37:33 +0000400func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) (BazelTarget, error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400401 ruleClass := m.BazelRuleClass()
402 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500403
Jingwen Chen73850672020-12-14 08:25:34 -0500404 // extract the bazel attributes from the module.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000405 attrs := m.BazelAttributes()
Alix94e26032022-08-16 20:37:33 +0000406 props, err := extractModuleProperties(attrs, true)
407 if err != nil {
408 return BazelTarget{}, err
409 }
Jingwen Chen73850672020-12-14 08:25:34 -0500410
Liz Kammer0eae52e2021-10-06 10:32:26 -0400411 // name is handled in a special manner
412 delete(props.Attrs, "name")
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500413
Jingwen Chen73850672020-12-14 08:25:34 -0500414 // Return the Bazel target with rule class and attributes, ready to be
415 // code-generated.
416 attributes := propsToAttributes(props.Attrs)
Sasha Smundakfb589492022-08-04 11:13:27 -0700417 var content string
Liz Kammer2ada09a2021-08-11 00:17:36 -0400418 targetName := m.TargetName()
Sasha Smundakfb589492022-08-04 11:13:27 -0700419 if targetName != "" {
420 content = fmt.Sprintf(ruleTargetTemplate, ruleClass, targetName, attributes)
421 } else {
422 content = fmt.Sprintf(unnamedRuleTargetTemplate, ruleClass, attributes)
423 }
Jingwen Chen73850672020-12-14 08:25:34 -0500424 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500425 name: targetName,
Liz Kammer2ada09a2021-08-11 00:17:36 -0400426 packageName: m.TargetPackage(),
Jingwen Chen40067de2021-01-26 21:58:43 -0500427 ruleClass: ruleClass,
428 bzlLoadLocation: bzlLoadLocation,
Sasha Smundakfb589492022-08-04 11:13:27 -0700429 content: content,
Alix94e26032022-08-16 20:37:33 +0000430 }, nil
Jingwen Chen73850672020-12-14 08:25:34 -0500431}
432
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800433// Convert a module and its deps and props into a Bazel macro/rule
434// representation in the BUILD file.
Alix94e26032022-08-16 20:37:33 +0000435func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) (BazelTarget, error) {
436 props, err := getBuildProperties(ctx, m)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800437
438 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
439 // items, if the modules are added using different DependencyTag. Figure
440 // out the implications of that.
441 depLabels := map[string]bool{}
442 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500443 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800444 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
445 })
446 }
Liz Kammer0eae52e2021-10-06 10:32:26 -0400447
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400448 for p := range ignoredPropNames {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400449 delete(props.Attrs, p)
450 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800451 attributes := propsToAttributes(props.Attrs)
452
453 depLabelList := "[\n"
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400454 for depLabel := range depLabels {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800455 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
456 }
457 depLabelList += " ]"
458
459 targetName := targetNameWithVariant(ctx, m)
460 return BazelTarget{
461 name: targetName,
462 content: fmt.Sprintf(
Sasha Smundakfb589492022-08-04 11:13:27 -0700463 soongModuleTargetTemplate,
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800464 targetName,
465 ctx.ModuleName(m),
466 canonicalizeModuleType(ctx.ModuleType(m)),
467 ctx.ModuleSubDir(m),
468 depLabelList,
469 attributes),
Alix94e26032022-08-16 20:37:33 +0000470 }, err
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800471}
472
Alix94e26032022-08-16 20:37:33 +0000473func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800474 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
475 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
476 if aModule, ok := m.(android.Module); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000477 return extractModuleProperties(aModule.GetProperties(), false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800478 }
479
Alix94e26032022-08-16 20:37:33 +0000480 return BazelAttributes{}, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800481}
482
483// Generically extract module properties and types into a map, keyed by the module property name.
Alix94e26032022-08-16 20:37:33 +0000484func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800485 ret := map[string]string{}
486
487 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400488 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800489 propertiesValue := reflect.ValueOf(properties)
490 // Check that propertiesValue is a pointer to the Properties struct, like
491 // *cc.BaseLinkerProperties or *java.CompilerProperties.
492 //
493 // propertiesValue can also be type-asserted to the structs to
494 // manipulate internal props, if needed.
495 if isStructPtr(propertiesValue.Type()) {
496 structValue := propertiesValue.Elem()
Alix94e26032022-08-16 20:37:33 +0000497 ok, err := extractStructProperties(structValue, 0)
498 if err != nil {
499 return BazelAttributes{}, err
500 }
501 for k, v := range ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000502 if existing, exists := ret[k]; checkForDuplicateProperties && exists {
Alix94e26032022-08-16 20:37:33 +0000503 return BazelAttributes{}, fmt.Errorf(
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000504 "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes",
Alix94e26032022-08-16 20:37:33 +0000505 k, existing)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000506 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800507 ret[k] = v
508 }
509 } else {
Alix94e26032022-08-16 20:37:33 +0000510 return BazelAttributes{},
511 fmt.Errorf(
512 "properties must be a pointer to a struct, got %T",
513 propertiesValue.Interface())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800514 }
515 }
516
Liz Kammer2ada09a2021-08-11 00:17:36 -0400517 return BazelAttributes{
518 Attrs: ret,
Alix94e26032022-08-16 20:37:33 +0000519 }, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800520}
521
522func isStructPtr(t reflect.Type) bool {
523 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
524}
525
526// prettyPrint a property value into the equivalent Starlark representation
527// recursively.
Jingwen Chen58ff6802021-11-17 12:14:41 +0000528func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) {
529 if !emitZeroValues && isZero(propertyValue) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800530 // A property value being set or unset actually matters -- Soong does set default
531 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
532 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
533 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +0000534 // In Bazel-parlance, we would use "attr.<type>(default = <default
535 // value>)" to set the default value of unset attributes. In the cases
536 // where the bp2build converter didn't set the default value within the
537 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -0400538 // value. For those cases, we return an empty string so we don't
539 // unnecessarily generate empty values.
540 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800541 }
542
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800543 switch propertyValue.Kind() {
544 case reflect.String:
Liz Kammer72beb342022-02-03 08:42:10 -0500545 return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800546 case reflect.Bool:
Liz Kammer72beb342022-02-03 08:42:10 -0500547 return starlark_fmt.PrintBool(propertyValue.Bool()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800548 case reflect.Int, reflect.Uint, reflect.Int64:
Liz Kammer72beb342022-02-03 08:42:10 -0500549 return fmt.Sprintf("%v", propertyValue.Interface()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800550 case reflect.Ptr:
Jingwen Chen58ff6802021-11-17 12:14:41 +0000551 return prettyPrint(propertyValue.Elem(), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800552 case reflect.Slice:
Liz Kammer72beb342022-02-03 08:42:10 -0500553 elements := make([]string, 0, propertyValue.Len())
554 for i := 0; i < propertyValue.Len(); i++ {
555 val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800556 if err != nil {
557 return "", err
558 }
Liz Kammer72beb342022-02-03 08:42:10 -0500559 if val != "" {
560 elements = append(elements, val)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800561 }
562 }
Sam Delmerico932c01c2022-03-25 16:33:26 +0000563 return starlark_fmt.PrintList(elements, indent, func(s string) string {
564 return "%s"
565 }), nil
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000566
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800567 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -0500568 // Special cases where the bp2build sends additional information to the codegenerator
569 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +0000570 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
571 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -0500572 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
573 return fmt.Sprintf("%q", label.Label), nil
574 }
575
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800576 // Sort and print the struct props by the key.
Alix94e26032022-08-16 20:37:33 +0000577 structProps, err := extractStructProperties(propertyValue, indent)
578
579 if err != nil {
580 return "", err
581 }
582
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000583 if len(structProps) == 0 {
584 return "", nil
585 }
Liz Kammer72beb342022-02-03 08:42:10 -0500586 return starlark_fmt.PrintDict(structProps, indent), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800587 case reflect.Interface:
588 // TODO(b/164227191): implement pretty print for interfaces.
589 // Interfaces are used for for arch, multilib and target properties.
590 return "", nil
591 default:
592 return "", fmt.Errorf(
593 "unexpected kind for property struct field: %s", propertyValue.Kind())
594 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800595}
596
597// Converts a reflected property struct value into a map of property names and property values,
598// which each property value correctly pretty-printed and indented at the right nest level,
599// since property structs can be nested. In Starlark, nested structs are represented as nested
600// dicts: https://docs.bazel.build/skylark/lib/dict.html
Alix94e26032022-08-16 20:37:33 +0000601func extractStructProperties(structValue reflect.Value, indent int) (map[string]string, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800602 if structValue.Kind() != reflect.Struct {
Alix94e26032022-08-16 20:37:33 +0000603 return map[string]string{}, fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800604 }
605
Alix94e26032022-08-16 20:37:33 +0000606 var err error
607
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800608 ret := map[string]string{}
609 structType := structValue.Type()
610 for i := 0; i < structValue.NumField(); i++ {
611 field := structType.Field(i)
612 if shouldSkipStructField(field) {
613 continue
614 }
615
616 fieldValue := structValue.Field(i)
617 if isZero(fieldValue) {
618 // Ignore zero-valued fields
619 continue
620 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400621
Liz Kammer32a03392021-09-14 11:17:21 -0400622 // if the struct is embedded (anonymous), flatten the properties into the containing struct
623 if field.Anonymous {
624 if field.Type.Kind() == reflect.Ptr {
625 fieldValue = fieldValue.Elem()
626 }
627 if fieldValue.Type().Kind() == reflect.Struct {
Alix94e26032022-08-16 20:37:33 +0000628 propsToMerge, err := extractStructProperties(fieldValue, indent)
629 if err != nil {
630 return map[string]string{}, err
631 }
Liz Kammer32a03392021-09-14 11:17:21 -0400632 for prop, value := range propsToMerge {
633 ret[prop] = value
634 }
635 continue
636 }
637 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800638
639 propertyName := proptools.PropertyNameForField(field.Name)
Alix94e26032022-08-16 20:37:33 +0000640 var prettyPrintedValue string
641 prettyPrintedValue, err = prettyPrint(fieldValue, indent+1, false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800642 if err != nil {
Alix94e26032022-08-16 20:37:33 +0000643 return map[string]string{}, fmt.Errorf(
644 "Error while parsing property: %q. %s",
645 propertyName,
646 err)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800647 }
648 if prettyPrintedValue != "" {
649 ret[propertyName] = prettyPrintedValue
650 }
651 }
652
Alix94e26032022-08-16 20:37:33 +0000653 return ret, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800654}
655
656func isZero(value reflect.Value) bool {
657 switch value.Kind() {
658 case reflect.Func, reflect.Map, reflect.Slice:
659 return value.IsNil()
660 case reflect.Array:
661 valueIsZero := true
662 for i := 0; i < value.Len(); i++ {
663 valueIsZero = valueIsZero && isZero(value.Index(i))
664 }
665 return valueIsZero
666 case reflect.Struct:
667 valueIsZero := true
668 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +0200669 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800670 }
671 return valueIsZero
672 case reflect.Ptr:
673 if !value.IsNil() {
674 return isZero(reflect.Indirect(value))
675 } else {
676 return true
677 }
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500678 // Always print bool/strings, if you want a bool/string attribute to be able to take the default value, use a
679 // pointer instead
680 case reflect.Bool, reflect.String:
Liz Kammerd366c902021-06-03 13:43:01 -0400681 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800682 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -0400683 if !value.IsValid() {
684 return true
685 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800686 zeroValue := reflect.Zero(value.Type())
687 result := value.Interface() == zeroValue.Interface()
688 return result
689 }
690}
691
692func escapeString(s string) string {
693 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +0000694
695 // b/184026959: Reverse the application of some common control sequences.
696 // These must be generated literally in the BUILD file.
697 s = strings.ReplaceAll(s, "\t", "\\t")
698 s = strings.ReplaceAll(s, "\n", "\\n")
699 s = strings.ReplaceAll(s, "\r", "\\r")
700
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800701 return strings.ReplaceAll(s, "\"", "\\\"")
702}
703
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800704func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
705 name := ""
706 if c.ModuleSubDir(logicModule) != "" {
707 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
708 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
709 } else {
710 name = c.ModuleName(logicModule)
711 }
712
713 return strings.Replace(name, "//", "", 1)
714}
715
716func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
717 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
718}