blob: 49b914472328e8044bfdcec6f9c9c87a73e32de9 [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
Cole Faustea602c52022-08-31 14:48:26 -070067// sort a list of BazelTargets in-place by name
Jingwen Chen49109762021-05-25 05:16:48 +000068func (targets BazelTargets) sort() {
69 sort.Slice(targets, func(i, j int) bool {
Jingwen Chen49109762021-05-25 05:16:48 +000070 return targets[i].name < targets[j].name
71 })
72}
73
Jingwen Chen40067de2021-01-26 21:58:43 -050074// String returns the string representation of BazelTargets, without load
75// statements (use LoadStatements for that), since the targets are usually not
76// adjacent to the load statements at the top of the BUILD file.
77func (targets BazelTargets) String() string {
78 var res string
79 for i, target := range targets {
80 res += target.content
81 if i != len(targets)-1 {
82 res += "\n\n"
83 }
84 }
85 return res
86}
87
88// LoadStatements return the string representation of the sorted and deduplicated
89// Starlark rule load statements needed by a group of BazelTargets.
90func (targets BazelTargets) LoadStatements() string {
91 bzlToLoadedSymbols := map[string][]string{}
92 for _, target := range targets {
93 if target.IsLoadedFromStarlark() {
94 bzlToLoadedSymbols[target.bzlLoadLocation] =
95 append(bzlToLoadedSymbols[target.bzlLoadLocation], target.ruleClass)
96 }
97 }
98
99 var loadStatements []string
100 for bzl, ruleClasses := range bzlToLoadedSymbols {
101 loadStatement := "load(\""
102 loadStatement += bzl
103 loadStatement += "\", "
104 ruleClasses = android.SortedUniqueStrings(ruleClasses)
105 for i, ruleClass := range ruleClasses {
106 loadStatement += "\"" + ruleClass + "\""
107 if i != len(ruleClasses)-1 {
108 loadStatement += ", "
109 }
110 }
111 loadStatement += ")"
112 loadStatements = append(loadStatements, loadStatement)
113 }
114 return strings.Join(android.SortedUniqueStrings(loadStatements), "\n")
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800115}
116
117type bpToBuildContext interface {
118 ModuleName(module blueprint.Module) string
119 ModuleDir(module blueprint.Module) string
120 ModuleSubDir(module blueprint.Module) string
121 ModuleType(module blueprint.Module) string
122
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500123 VisitAllModules(visit func(blueprint.Module))
124 VisitDirectDeps(module blueprint.Module, visit func(blueprint.Module))
125}
126
127type CodegenContext struct {
Jingwen Chen16d90a82021-09-17 07:16:13 +0000128 config android.Config
129 context android.Context
130 mode CodegenMode
131 additionalDeps []string
Liz Kammer6eff3232021-08-26 08:37:59 -0400132 unconvertedDepMode unconvertedDepsMode
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500133}
134
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400135func (ctx *CodegenContext) Mode() CodegenMode {
136 return ctx.mode
Jingwen Chen164e0862021-02-19 00:48:40 -0500137}
138
Jingwen Chen33832f92021-01-24 22:55:54 -0500139// CodegenMode is an enum to differentiate code-generation modes.
140type CodegenMode int
141
142const (
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400143 // Bp2Build - generate BUILD files with targets buildable by Bazel directly.
Jingwen Chen33832f92021-01-24 22:55:54 -0500144 //
145 // This mode is used for the Soong->Bazel build definition conversion.
146 Bp2Build CodegenMode = iota
147
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400148 // QueryView - generate BUILD files with targets representing fully mutated
Jingwen Chen33832f92021-01-24 22:55:54 -0500149 // Soong modules, representing the fully configured Soong module graph with
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400150 // variants and dependency edges.
Jingwen Chen33832f92021-01-24 22:55:54 -0500151 //
152 // This mode is used for discovering and introspecting the existing Soong
153 // module graph.
154 QueryView
155)
156
Liz Kammer6eff3232021-08-26 08:37:59 -0400157type unconvertedDepsMode int
158
159const (
160 // Include a warning in conversion metrics about converted modules with unconverted direct deps
161 warnUnconvertedDeps unconvertedDepsMode = iota
162 // Error and fail conversion if encountering a module with unconverted direct deps
163 // Enabled by setting environment variable `BP2BUILD_ERROR_UNCONVERTED`
164 errorModulesUnconvertedDeps
165)
166
Jingwen Chendcc329a2021-01-26 02:49:03 -0500167func (mode CodegenMode) String() string {
168 switch mode {
169 case Bp2Build:
170 return "Bp2Build"
171 case QueryView:
172 return "QueryView"
173 default:
174 return fmt.Sprintf("%d", mode)
175 }
176}
177
Liz Kammerba3ea162021-02-17 13:22:03 -0500178// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
179// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
180// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
181// call AdditionalNinjaDeps and add them manually to the ninja file.
182func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
183 ctx.additionalDeps = append(ctx.additionalDeps, deps...)
184}
185
186// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
187func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
188 return ctx.additionalDeps
189}
190
191func (ctx *CodegenContext) Config() android.Config { return ctx.config }
192func (ctx *CodegenContext) Context() android.Context { return ctx.context }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500193
194// NewCodegenContext creates a wrapper context that conforms to PathContext for
195// writing BUILD files in the output directory.
Liz Kammerba3ea162021-02-17 13:22:03 -0500196func NewCodegenContext(config android.Config, context android.Context, mode CodegenMode) *CodegenContext {
Liz Kammer6eff3232021-08-26 08:37:59 -0400197 var unconvertedDeps unconvertedDepsMode
198 if config.IsEnvTrue("BP2BUILD_ERROR_UNCONVERTED") {
199 unconvertedDeps = errorModulesUnconvertedDeps
200 }
Liz Kammerba3ea162021-02-17 13:22:03 -0500201 return &CodegenContext{
Liz Kammer6eff3232021-08-26 08:37:59 -0400202 context: context,
203 config: config,
204 mode: mode,
205 unconvertedDepMode: unconvertedDeps,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500206 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800207}
208
209// props is an unsorted map. This function ensures that
210// the generated attributes are sorted to ensure determinism.
211func propsToAttributes(props map[string]string) string {
212 var attributes string
213 for _, propName := range android.SortedStringKeys(props) {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400214 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800215 }
216 return attributes
217}
218
Liz Kammer6eff3232021-08-26 08:37:59 -0400219type conversionResults struct {
220 buildFileToTargets map[string]BazelTargets
221 metrics CodegenMetrics
Liz Kammer6eff3232021-08-26 08:37:59 -0400222}
223
224func (r conversionResults) BuildDirToTargets() map[string]BazelTargets {
225 return r.buildFileToTargets
226}
227
228func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (conversionResults, []error) {
Jingwen Chen40067de2021-01-26 21:58:43 -0500229 buildFileToTargets := make(map[string]BazelTargets)
Jingwen Chen164e0862021-02-19 00:48:40 -0500230
231 // Simple metrics tracking for bp2build
Liz Kammerba3ea162021-02-17 13:22:03 -0500232 metrics := CodegenMetrics{
Chris Parsons492bd912022-01-20 12:55:05 -0500233 ruleClassCount: make(map[string]uint64),
234 convertedModuleTypeCount: make(map[string]uint64),
235 totalModuleTypeCount: make(map[string]uint64),
Liz Kammerba3ea162021-02-17 13:22:03 -0500236 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500237
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400238 dirs := make(map[string]bool)
239
Liz Kammer6eff3232021-08-26 08:37:59 -0400240 var errs []error
241
Jingwen Chen164e0862021-02-19 00:48:40 -0500242 bpCtx := ctx.Context()
243 bpCtx.VisitAllModules(func(m blueprint.Module) {
244 dir := bpCtx.ModuleDir(m)
Chris Parsons492bd912022-01-20 12:55:05 -0500245 moduleType := bpCtx.ModuleType(m)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400246 dirs[dir] = true
247
Liz Kammer2ada09a2021-08-11 00:17:36 -0400248 var targets []BazelTarget
Jingwen Chen73850672020-12-14 08:25:34 -0500249
Jingwen Chen164e0862021-02-19 00:48:40 -0500250 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500251 case Bp2Build:
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000252 // There are two main ways of converting a Soong module to Bazel:
253 // 1) Manually handcrafting a Bazel target and associating the module with its label
254 // 2) Automatically generating with bp2build converters
255 //
256 // bp2build converters are used for the majority of modules.
Liz Kammerba3ea162021-02-17 13:22:03 -0500257 if b, ok := m.(android.Bazelable); ok && b.HasHandcraftedLabel() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000258 // Handle modules converted to handcrafted targets.
259 //
260 // Since these modules are associated with some handcrafted
Cole Faustea602c52022-08-31 14:48:26 -0700261 // target in a BUILD file, we don't autoconvert them.
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000262
263 // Log the module.
Chris Parsons492bd912022-01-20 12:55:05 -0500264 metrics.AddConvertedModule(m, moduleType, Handcrafted)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400265 } else if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000266 // Handle modules converted to generated targets.
267
268 // Log the module.
Chris Parsons492bd912022-01-20 12:55:05 -0500269 metrics.AddConvertedModule(aModule, moduleType, Generated)
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000270
271 // Handle modules with unconverted deps. By default, emit a warning.
Liz Kammer6eff3232021-08-26 08:37:59 -0400272 if unconvertedDeps := aModule.GetUnconvertedBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700273 msg := fmt.Sprintf("%s %s:%s depends on unconverted modules: %s",
274 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Liz Kammer6eff3232021-08-26 08:37:59 -0400275 if ctx.unconvertedDepMode == warnUnconvertedDeps {
276 metrics.moduleWithUnconvertedDepsMsgs = append(metrics.moduleWithUnconvertedDepsMsgs, msg)
277 } else if ctx.unconvertedDepMode == errorModulesUnconvertedDeps {
Liz Kammer6eff3232021-08-26 08:37:59 -0400278 errs = append(errs, fmt.Errorf(msg))
279 return
280 }
281 }
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500282 if unconvertedDeps := aModule.GetMissingBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700283 msg := fmt.Sprintf("%s %s:%s depends on missing modules: %s",
284 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500285 if ctx.unconvertedDepMode == warnUnconvertedDeps {
286 metrics.moduleWithMissingDepsMsgs = append(metrics.moduleWithMissingDepsMsgs, msg)
287 } else if ctx.unconvertedDepMode == errorModulesUnconvertedDeps {
288 errs = append(errs, fmt.Errorf(msg))
289 return
290 }
291 }
Alix94e26032022-08-16 20:37:33 +0000292 var targetErrs []error
293 targets, targetErrs = generateBazelTargets(bpCtx, aModule)
294 errs = append(errs, targetErrs...)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400295 for _, t := range targets {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000296 // A module can potentially generate more than 1 Bazel
297 // target, each of a different rule class.
298 metrics.IncrementRuleClassCount(t.ruleClass)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400299 }
Liz Kammerfc46bc12021-02-19 11:06:17 -0500300 } else {
Chris Parsons492bd912022-01-20 12:55:05 -0500301 metrics.AddUnconvertedModule(moduleType)
Liz Kammerba3ea162021-02-17 13:22:03 -0500302 return
Jingwen Chen73850672020-12-14 08:25:34 -0500303 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500304 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500305 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500306 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500307 // package module name contain slashes, and thus cannot
308 // be mapped cleanly to a bazel label.
309 return
310 }
Alix94e26032022-08-16 20:37:33 +0000311 t, err := generateSoongModuleTarget(bpCtx, m)
312 if err != nil {
313 errs = append(errs, err)
314 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400315 targets = append(targets, t)
Jingwen Chen33832f92021-01-24 22:55:54 -0500316 default:
Liz Kammer6eff3232021-08-26 08:37:59 -0400317 errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
318 return
Jingwen Chen73850672020-12-14 08:25:34 -0500319 }
320
Liz Kammer2ada09a2021-08-11 00:17:36 -0400321 buildFileToTargets[dir] = append(buildFileToTargets[dir], targets...)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800322 })
Liz Kammer6eff3232021-08-26 08:37:59 -0400323
324 if len(errs) > 0 {
325 return conversionResults{}, errs
326 }
327
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400328 if generateFilegroups {
329 // Add a filegroup target that exposes all sources in the subtree of this package
330 // 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 -0700331 //
332 // This works because: https://bazel.build/reference/be/functions#exports_files
333 // "As a legacy behaviour, also files mentioned as input to a rule are exported with the
334 // default visibility until the flag --incompatible_no_implicit_file_export is flipped. However, this behavior
335 // should not be relied upon and actively migrated away from."
336 //
337 // TODO(b/198619163): We should change this to export_files(glob(["**/*"])) instead, but doing that causes these errors:
338 // "Error in exports_files: generated label '//external/avb:avbtool' conflicts with existing py_binary rule"
339 // So we need to solve all the "target ... is both a rule and a file" warnings first.
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400340 for dir, _ := range dirs {
341 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
342 name: "bp2build_all_srcs",
343 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]))`,
344 ruleClass: "filegroup",
345 })
346 }
347 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500348
Liz Kammer6eff3232021-08-26 08:37:59 -0400349 return conversionResults{
350 buildFileToTargets: buildFileToTargets,
351 metrics: metrics,
Liz Kammer6eff3232021-08-26 08:37:59 -0400352 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500353}
354
Alix94e26032022-08-16 20:37:33 +0000355func generateBazelTargets(ctx bpToBuildContext, m android.Module) ([]BazelTarget, []error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400356 var targets []BazelTarget
Alix94e26032022-08-16 20:37:33 +0000357 var errs []error
Liz Kammer2ada09a2021-08-11 00:17:36 -0400358 for _, m := range m.Bp2buildTargets() {
Alix94e26032022-08-16 20:37:33 +0000359 target, err := generateBazelTarget(ctx, m)
360 if err != nil {
361 errs = append(errs, err)
362 return targets, errs
363 }
364 targets = append(targets, target)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400365 }
Alix94e26032022-08-16 20:37:33 +0000366 return targets, errs
Liz Kammer2ada09a2021-08-11 00:17:36 -0400367}
368
369type bp2buildModule interface {
370 TargetName() string
371 TargetPackage() string
372 BazelRuleClass() string
373 BazelRuleLoadLocation() string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000374 BazelAttributes() []interface{}
Liz Kammer2ada09a2021-08-11 00:17:36 -0400375}
376
Alix94e26032022-08-16 20:37:33 +0000377func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) (BazelTarget, error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400378 ruleClass := m.BazelRuleClass()
379 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500380
Jingwen Chen73850672020-12-14 08:25:34 -0500381 // extract the bazel attributes from the module.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000382 attrs := m.BazelAttributes()
Alix94e26032022-08-16 20:37:33 +0000383 props, err := extractModuleProperties(attrs, true)
384 if err != nil {
385 return BazelTarget{}, err
386 }
Jingwen Chen73850672020-12-14 08:25:34 -0500387
Liz Kammer0eae52e2021-10-06 10:32:26 -0400388 // name is handled in a special manner
389 delete(props.Attrs, "name")
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500390
Jingwen Chen73850672020-12-14 08:25:34 -0500391 // Return the Bazel target with rule class and attributes, ready to be
392 // code-generated.
393 attributes := propsToAttributes(props.Attrs)
Sasha Smundakfb589492022-08-04 11:13:27 -0700394 var content string
Liz Kammer2ada09a2021-08-11 00:17:36 -0400395 targetName := m.TargetName()
Sasha Smundakfb589492022-08-04 11:13:27 -0700396 if targetName != "" {
397 content = fmt.Sprintf(ruleTargetTemplate, ruleClass, targetName, attributes)
398 } else {
399 content = fmt.Sprintf(unnamedRuleTargetTemplate, ruleClass, attributes)
400 }
Jingwen Chen73850672020-12-14 08:25:34 -0500401 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500402 name: targetName,
Liz Kammer2ada09a2021-08-11 00:17:36 -0400403 packageName: m.TargetPackage(),
Jingwen Chen40067de2021-01-26 21:58:43 -0500404 ruleClass: ruleClass,
405 bzlLoadLocation: bzlLoadLocation,
Sasha Smundakfb589492022-08-04 11:13:27 -0700406 content: content,
Alix94e26032022-08-16 20:37:33 +0000407 }, nil
Jingwen Chen73850672020-12-14 08:25:34 -0500408}
409
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800410// Convert a module and its deps and props into a Bazel macro/rule
411// representation in the BUILD file.
Alix94e26032022-08-16 20:37:33 +0000412func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) (BazelTarget, error) {
413 props, err := getBuildProperties(ctx, m)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800414
415 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
416 // items, if the modules are added using different DependencyTag. Figure
417 // out the implications of that.
418 depLabels := map[string]bool{}
419 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500420 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800421 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
422 })
423 }
Liz Kammer0eae52e2021-10-06 10:32:26 -0400424
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400425 for p := range ignoredPropNames {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400426 delete(props.Attrs, p)
427 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800428 attributes := propsToAttributes(props.Attrs)
429
430 depLabelList := "[\n"
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400431 for depLabel := range depLabels {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800432 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
433 }
434 depLabelList += " ]"
435
436 targetName := targetNameWithVariant(ctx, m)
437 return BazelTarget{
438 name: targetName,
439 content: fmt.Sprintf(
Sasha Smundakfb589492022-08-04 11:13:27 -0700440 soongModuleTargetTemplate,
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800441 targetName,
442 ctx.ModuleName(m),
443 canonicalizeModuleType(ctx.ModuleType(m)),
444 ctx.ModuleSubDir(m),
445 depLabelList,
446 attributes),
Alix94e26032022-08-16 20:37:33 +0000447 }, err
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800448}
449
Alix94e26032022-08-16 20:37:33 +0000450func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800451 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
452 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
453 if aModule, ok := m.(android.Module); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000454 return extractModuleProperties(aModule.GetProperties(), false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800455 }
456
Alix94e26032022-08-16 20:37:33 +0000457 return BazelAttributes{}, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800458}
459
460// Generically extract module properties and types into a map, keyed by the module property name.
Alix94e26032022-08-16 20:37:33 +0000461func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800462 ret := map[string]string{}
463
464 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400465 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800466 propertiesValue := reflect.ValueOf(properties)
467 // Check that propertiesValue is a pointer to the Properties struct, like
468 // *cc.BaseLinkerProperties or *java.CompilerProperties.
469 //
470 // propertiesValue can also be type-asserted to the structs to
471 // manipulate internal props, if needed.
472 if isStructPtr(propertiesValue.Type()) {
473 structValue := propertiesValue.Elem()
Alix94e26032022-08-16 20:37:33 +0000474 ok, err := extractStructProperties(structValue, 0)
475 if err != nil {
476 return BazelAttributes{}, err
477 }
478 for k, v := range ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000479 if existing, exists := ret[k]; checkForDuplicateProperties && exists {
Alix94e26032022-08-16 20:37:33 +0000480 return BazelAttributes{}, fmt.Errorf(
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000481 "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes",
Alix94e26032022-08-16 20:37:33 +0000482 k, existing)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000483 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800484 ret[k] = v
485 }
486 } else {
Alix94e26032022-08-16 20:37:33 +0000487 return BazelAttributes{},
488 fmt.Errorf(
489 "properties must be a pointer to a struct, got %T",
490 propertiesValue.Interface())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800491 }
492 }
493
Liz Kammer2ada09a2021-08-11 00:17:36 -0400494 return BazelAttributes{
495 Attrs: ret,
Alix94e26032022-08-16 20:37:33 +0000496 }, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800497}
498
499func isStructPtr(t reflect.Type) bool {
500 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
501}
502
503// prettyPrint a property value into the equivalent Starlark representation
504// recursively.
Jingwen Chen58ff6802021-11-17 12:14:41 +0000505func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) {
506 if !emitZeroValues && isZero(propertyValue) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800507 // A property value being set or unset actually matters -- Soong does set default
508 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
509 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
510 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +0000511 // In Bazel-parlance, we would use "attr.<type>(default = <default
512 // value>)" to set the default value of unset attributes. In the cases
513 // where the bp2build converter didn't set the default value within the
514 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -0400515 // value. For those cases, we return an empty string so we don't
516 // unnecessarily generate empty values.
517 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800518 }
519
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800520 switch propertyValue.Kind() {
521 case reflect.String:
Liz Kammer72beb342022-02-03 08:42:10 -0500522 return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800523 case reflect.Bool:
Liz Kammer72beb342022-02-03 08:42:10 -0500524 return starlark_fmt.PrintBool(propertyValue.Bool()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800525 case reflect.Int, reflect.Uint, reflect.Int64:
Liz Kammer72beb342022-02-03 08:42:10 -0500526 return fmt.Sprintf("%v", propertyValue.Interface()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800527 case reflect.Ptr:
Jingwen Chen58ff6802021-11-17 12:14:41 +0000528 return prettyPrint(propertyValue.Elem(), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800529 case reflect.Slice:
Liz Kammer72beb342022-02-03 08:42:10 -0500530 elements := make([]string, 0, propertyValue.Len())
531 for i := 0; i < propertyValue.Len(); i++ {
532 val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800533 if err != nil {
534 return "", err
535 }
Liz Kammer72beb342022-02-03 08:42:10 -0500536 if val != "" {
537 elements = append(elements, val)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800538 }
539 }
Sam Delmerico932c01c2022-03-25 16:33:26 +0000540 return starlark_fmt.PrintList(elements, indent, func(s string) string {
541 return "%s"
542 }), nil
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000543
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800544 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -0500545 // Special cases where the bp2build sends additional information to the codegenerator
546 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +0000547 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
548 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -0500549 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
550 return fmt.Sprintf("%q", label.Label), nil
551 }
552
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800553 // Sort and print the struct props by the key.
Alix94e26032022-08-16 20:37:33 +0000554 structProps, err := extractStructProperties(propertyValue, indent)
555
556 if err != nil {
557 return "", err
558 }
559
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000560 if len(structProps) == 0 {
561 return "", nil
562 }
Liz Kammer72beb342022-02-03 08:42:10 -0500563 return starlark_fmt.PrintDict(structProps, indent), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800564 case reflect.Interface:
565 // TODO(b/164227191): implement pretty print for interfaces.
566 // Interfaces are used for for arch, multilib and target properties.
567 return "", nil
568 default:
569 return "", fmt.Errorf(
570 "unexpected kind for property struct field: %s", propertyValue.Kind())
571 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800572}
573
574// Converts a reflected property struct value into a map of property names and property values,
575// which each property value correctly pretty-printed and indented at the right nest level,
576// since property structs can be nested. In Starlark, nested structs are represented as nested
577// dicts: https://docs.bazel.build/skylark/lib/dict.html
Alix94e26032022-08-16 20:37:33 +0000578func extractStructProperties(structValue reflect.Value, indent int) (map[string]string, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800579 if structValue.Kind() != reflect.Struct {
Alix94e26032022-08-16 20:37:33 +0000580 return map[string]string{}, fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800581 }
582
Alix94e26032022-08-16 20:37:33 +0000583 var err error
584
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800585 ret := map[string]string{}
586 structType := structValue.Type()
587 for i := 0; i < structValue.NumField(); i++ {
588 field := structType.Field(i)
589 if shouldSkipStructField(field) {
590 continue
591 }
592
593 fieldValue := structValue.Field(i)
594 if isZero(fieldValue) {
595 // Ignore zero-valued fields
596 continue
597 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400598
Liz Kammer32a03392021-09-14 11:17:21 -0400599 // if the struct is embedded (anonymous), flatten the properties into the containing struct
600 if field.Anonymous {
601 if field.Type.Kind() == reflect.Ptr {
602 fieldValue = fieldValue.Elem()
603 }
604 if fieldValue.Type().Kind() == reflect.Struct {
Alix94e26032022-08-16 20:37:33 +0000605 propsToMerge, err := extractStructProperties(fieldValue, indent)
606 if err != nil {
607 return map[string]string{}, err
608 }
Liz Kammer32a03392021-09-14 11:17:21 -0400609 for prop, value := range propsToMerge {
610 ret[prop] = value
611 }
612 continue
613 }
614 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800615
616 propertyName := proptools.PropertyNameForField(field.Name)
Alix94e26032022-08-16 20:37:33 +0000617 var prettyPrintedValue string
618 prettyPrintedValue, err = prettyPrint(fieldValue, indent+1, false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800619 if err != nil {
Alix94e26032022-08-16 20:37:33 +0000620 return map[string]string{}, fmt.Errorf(
621 "Error while parsing property: %q. %s",
622 propertyName,
623 err)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800624 }
625 if prettyPrintedValue != "" {
626 ret[propertyName] = prettyPrintedValue
627 }
628 }
629
Alix94e26032022-08-16 20:37:33 +0000630 return ret, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800631}
632
633func isZero(value reflect.Value) bool {
634 switch value.Kind() {
635 case reflect.Func, reflect.Map, reflect.Slice:
636 return value.IsNil()
637 case reflect.Array:
638 valueIsZero := true
639 for i := 0; i < value.Len(); i++ {
640 valueIsZero = valueIsZero && isZero(value.Index(i))
641 }
642 return valueIsZero
643 case reflect.Struct:
644 valueIsZero := true
645 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +0200646 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800647 }
648 return valueIsZero
649 case reflect.Ptr:
650 if !value.IsNil() {
651 return isZero(reflect.Indirect(value))
652 } else {
653 return true
654 }
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500655 // Always print bool/strings, if you want a bool/string attribute to be able to take the default value, use a
656 // pointer instead
657 case reflect.Bool, reflect.String:
Liz Kammerd366c902021-06-03 13:43:01 -0400658 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800659 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -0400660 if !value.IsValid() {
661 return true
662 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800663 zeroValue := reflect.Zero(value.Type())
664 result := value.Interface() == zeroValue.Interface()
665 return result
666 }
667}
668
669func escapeString(s string) string {
670 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +0000671
672 // b/184026959: Reverse the application of some common control sequences.
673 // These must be generated literally in the BUILD file.
674 s = strings.ReplaceAll(s, "\t", "\\t")
675 s = strings.ReplaceAll(s, "\n", "\\n")
676 s = strings.ReplaceAll(s, "\r", "\\r")
677
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800678 return strings.ReplaceAll(s, "\"", "\\\"")
679}
680
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800681func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
682 name := ""
683 if c.ModuleSubDir(logicModule) != "" {
684 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
685 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
686 } else {
687 name = c.ModuleName(logicModule)
688 }
689
690 return strings.Replace(name, "//", "", 1)
691}
692
693func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
694 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
695}