blob: bd5676815dd589b4d13712218103bda797b47ec5 [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"
Liz Kammer2dd9ca42020-11-25 16:06:39 -080031 "github.com/google/blueprint"
32 "github.com/google/blueprint/proptools"
33)
34
35type BazelAttributes struct {
36 Attrs map[string]string
37}
38
Cole Faustb4cb0c82023-09-14 15:16:58 -070039type BazelLoadSymbol struct {
40 // The name of the symbol in the file being loaded
41 symbol string
42 // The name the symbol wil have in this file. Can be left blank to use the same name as symbol.
43 alias string
Jingwen Chen40067de2021-01-26 21:58:43 -050044}
45
Cole Faustb4cb0c82023-09-14 15:16:58 -070046type BazelLoad struct {
47 file string
48 symbols []BazelLoadSymbol
49}
50
51type BazelTarget struct {
52 name string
53 packageName string
54 content string
55 ruleClass string
56 loads []BazelLoad
Jingwen Chen40067de2021-01-26 21:58:43 -050057}
58
Jingwen Chenc63677b2021-06-17 05:43:19 +000059// Label is the fully qualified Bazel label constructed from the BazelTarget's
60// package name and target name.
61func (t BazelTarget) Label() string {
62 if t.packageName == "." {
63 return "//:" + t.name
64 } else {
65 return "//" + t.packageName + ":" + t.name
66 }
67}
68
Spandan Dasabedff02023-03-07 19:24:34 +000069// PackageName returns the package of the Bazel target.
70// Defaults to root of tree.
71func (t BazelTarget) PackageName() string {
72 if t.packageName == "" {
73 return "."
74 }
75 return t.packageName
76}
77
Jingwen Chen40067de2021-01-26 21:58:43 -050078// BazelTargets is a typedef for a slice of BazelTarget objects.
79type BazelTargets []BazelTarget
80
Sasha Smundak8bea2672022-08-04 13:31:14 -070081func (targets BazelTargets) packageRule() *BazelTarget {
82 for _, target := range targets {
83 if target.ruleClass == "package" {
84 return &target
85 }
86 }
87 return nil
88}
89
90// sort a list of BazelTargets in-place, by name, and by generated/handcrafted types.
Jingwen Chen49109762021-05-25 05:16:48 +000091func (targets BazelTargets) sort() {
92 sort.Slice(targets, func(i, j int) bool {
Jingwen Chen49109762021-05-25 05:16:48 +000093 return targets[i].name < targets[j].name
94 })
95}
96
Jingwen Chen40067de2021-01-26 21:58:43 -050097// String returns the string representation of BazelTargets, without load
98// statements (use LoadStatements for that), since the targets are usually not
99// adjacent to the load statements at the top of the BUILD file.
100func (targets BazelTargets) String() string {
ustada2a2112023-08-08 00:29:08 -0400101 var res strings.Builder
Jingwen Chen40067de2021-01-26 21:58:43 -0500102 for i, target := range targets {
Sasha Smundak8bea2672022-08-04 13:31:14 -0700103 if target.ruleClass != "package" {
ustada2a2112023-08-08 00:29:08 -0400104 res.WriteString(target.content)
Sasha Smundak8bea2672022-08-04 13:31:14 -0700105 }
Jingwen Chen40067de2021-01-26 21:58:43 -0500106 if i != len(targets)-1 {
ustada2a2112023-08-08 00:29:08 -0400107 res.WriteString("\n\n")
Jingwen Chen40067de2021-01-26 21:58:43 -0500108 }
109 }
ustada2a2112023-08-08 00:29:08 -0400110 return res.String()
Jingwen Chen40067de2021-01-26 21:58:43 -0500111}
112
113// LoadStatements return the string representation of the sorted and deduplicated
114// Starlark rule load statements needed by a group of BazelTargets.
115func (targets BazelTargets) LoadStatements() string {
Cole Faustb4cb0c82023-09-14 15:16:58 -0700116 // First, merge all the load statements from all the targets onto one list
117 bzlToLoadedSymbols := map[string][]BazelLoadSymbol{}
Jingwen Chen40067de2021-01-26 21:58:43 -0500118 for _, target := range targets {
Cole Faustb4cb0c82023-09-14 15:16:58 -0700119 for _, load := range target.loads {
120 outer:
121 for _, symbol := range load.symbols {
122 alias := symbol.alias
123 if alias == "" {
124 alias = symbol.symbol
125 }
126 for _, otherSymbol := range bzlToLoadedSymbols[load.file] {
127 otherAlias := otherSymbol.alias
128 if otherAlias == "" {
129 otherAlias = otherSymbol.symbol
130 }
131 if symbol.symbol == otherSymbol.symbol && alias == otherAlias {
132 continue outer
133 } else if alias == otherAlias {
134 panic(fmt.Sprintf("Conflicting destination (%s) for loads of %s and %s", alias, symbol.symbol, otherSymbol.symbol))
135 }
136 }
137 bzlToLoadedSymbols[load.file] = append(bzlToLoadedSymbols[load.file], symbol)
138 }
Jingwen Chen40067de2021-01-26 21:58:43 -0500139 }
140 }
141
Cole Faustb4cb0c82023-09-14 15:16:58 -0700142 var loadStatements strings.Builder
143 for i, bzl := range android.SortedKeys(bzlToLoadedSymbols) {
144 symbols := bzlToLoadedSymbols[bzl]
145 loadStatements.WriteString("load(\"")
146 loadStatements.WriteString(bzl)
147 loadStatements.WriteString("\", ")
148 sort.Slice(symbols, func(i, j int) bool {
149 if symbols[i].symbol < symbols[j].symbol {
150 return true
151 }
152 return symbols[i].alias < symbols[j].alias
153 })
154 for j, symbol := range symbols {
155 if symbol.alias != "" && symbol.alias != symbol.symbol {
156 loadStatements.WriteString(symbol.alias)
157 loadStatements.WriteString(" = ")
158 }
159 loadStatements.WriteString("\"")
160 loadStatements.WriteString(symbol.symbol)
161 loadStatements.WriteString("\"")
162 if j != len(symbols)-1 {
163 loadStatements.WriteString(", ")
Jingwen Chen40067de2021-01-26 21:58:43 -0500164 }
165 }
Cole Faustb4cb0c82023-09-14 15:16:58 -0700166 loadStatements.WriteString(")")
167 if i != len(bzlToLoadedSymbols)-1 {
168 loadStatements.WriteString("\n")
169 }
Jingwen Chen40067de2021-01-26 21:58:43 -0500170 }
Cole Faustb4cb0c82023-09-14 15:16:58 -0700171 return loadStatements.String()
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800172}
173
174type bpToBuildContext interface {
175 ModuleName(module blueprint.Module) string
176 ModuleDir(module blueprint.Module) string
177 ModuleSubDir(module blueprint.Module) string
178 ModuleType(module blueprint.Module) string
179
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500180 VisitAllModules(visit func(blueprint.Module))
181 VisitDirectDeps(module blueprint.Module, visit func(blueprint.Module))
182}
183
184type CodegenContext struct {
Jingwen Chen16d90a82021-09-17 07:16:13 +0000185 config android.Config
Paul Duffinc6390592022-11-04 13:35:21 +0000186 context *android.Context
Jingwen Chen16d90a82021-09-17 07:16:13 +0000187 mode CodegenMode
188 additionalDeps []string
Liz Kammer6eff3232021-08-26 08:37:59 -0400189 unconvertedDepMode unconvertedDepsMode
Cole Faustb85d1a12022-11-08 18:14:01 -0800190 topDir string
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500191}
192
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400193func (ctx *CodegenContext) Mode() CodegenMode {
194 return ctx.mode
Jingwen Chen164e0862021-02-19 00:48:40 -0500195}
196
Jingwen Chen33832f92021-01-24 22:55:54 -0500197// CodegenMode is an enum to differentiate code-generation modes.
198type CodegenMode int
199
200const (
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400201 // QueryView - generate BUILD files with targets representing fully mutated
Jingwen Chen33832f92021-01-24 22:55:54 -0500202 // Soong modules, representing the fully configured Soong module graph with
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400203 // variants and dependency edges.
Jingwen Chen33832f92021-01-24 22:55:54 -0500204 //
205 // This mode is used for discovering and introspecting the existing Soong
206 // module graph.
Colin Crossb63d7b32023-12-07 16:54:51 -0800207 QueryView CodegenMode = iota
Jingwen Chen33832f92021-01-24 22:55:54 -0500208)
209
Liz Kammer6eff3232021-08-26 08:37:59 -0400210type unconvertedDepsMode int
211
212const (
213 // Include a warning in conversion metrics about converted modules with unconverted direct deps
214 warnUnconvertedDeps unconvertedDepsMode = iota
215 // Error and fail conversion if encountering a module with unconverted direct deps
216 // Enabled by setting environment variable `BP2BUILD_ERROR_UNCONVERTED`
217 errorModulesUnconvertedDeps
218)
219
Jingwen Chendcc329a2021-01-26 02:49:03 -0500220func (mode CodegenMode) String() string {
221 switch mode {
Jingwen Chendcc329a2021-01-26 02:49:03 -0500222 case QueryView:
223 return "QueryView"
224 default:
225 return fmt.Sprintf("%d", mode)
226 }
227}
228
Liz Kammerba3ea162021-02-17 13:22:03 -0500229// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
230// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
231// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
232// call AdditionalNinjaDeps and add them manually to the ninja file.
233func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
234 ctx.additionalDeps = append(ctx.additionalDeps, deps...)
235}
236
237// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
238func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
239 return ctx.additionalDeps
240}
241
Paul Duffinc6390592022-11-04 13:35:21 +0000242func (ctx *CodegenContext) Config() android.Config { return ctx.config }
243func (ctx *CodegenContext) Context() *android.Context { return ctx.context }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500244
245// NewCodegenContext creates a wrapper context that conforms to PathContext for
246// writing BUILD files in the output directory.
Cole Faustb85d1a12022-11-08 18:14:01 -0800247func NewCodegenContext(config android.Config, context *android.Context, mode CodegenMode, topDir string) *CodegenContext {
Liz Kammer6eff3232021-08-26 08:37:59 -0400248 var unconvertedDeps unconvertedDepsMode
Liz Kammerba3ea162021-02-17 13:22:03 -0500249 return &CodegenContext{
Liz Kammer6eff3232021-08-26 08:37:59 -0400250 context: context,
251 config: config,
252 mode: mode,
253 unconvertedDepMode: unconvertedDeps,
Cole Faustb85d1a12022-11-08 18:14:01 -0800254 topDir: topDir,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500255 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800256}
257
258// props is an unsorted map. This function ensures that
259// the generated attributes are sorted to ensure determinism.
260func propsToAttributes(props map[string]string) string {
261 var attributes string
Cole Faust18994c72023-02-28 16:02:16 -0800262 for _, propName := range android.SortedKeys(props) {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400263 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800264 }
265 return attributes
266}
267
Liz Kammer6eff3232021-08-26 08:37:59 -0400268type conversionResults struct {
Cole Faust11edf552023-10-13 11:32:14 -0700269 buildFileToTargets map[string]BazelTargets
270 moduleNameToPartition map[string]string
Liz Kammer6eff3232021-08-26 08:37:59 -0400271}
272
273func (r conversionResults) BuildDirToTargets() map[string]BazelTargets {
274 return r.buildFileToTargets
275}
276
277func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (conversionResults, []error) {
ustaaaf2fd12023-07-01 11:40:36 -0400278 ctx.Context().BeginEvent("GenerateBazelTargets")
279 defer ctx.Context().EndEvent("GenerateBazelTargets")
Jingwen Chen40067de2021-01-26 21:58:43 -0500280 buildFileToTargets := make(map[string]BazelTargets)
Jingwen Chen164e0862021-02-19 00:48:40 -0500281
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400282 dirs := make(map[string]bool)
Cole Faust11edf552023-10-13 11:32:14 -0700283 moduleNameToPartition := make(map[string]string)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400284
Liz Kammer6eff3232021-08-26 08:37:59 -0400285 var errs []error
286
Jingwen Chen164e0862021-02-19 00:48:40 -0500287 bpCtx := ctx.Context()
288 bpCtx.VisitAllModules(func(m blueprint.Module) {
289 dir := bpCtx.ModuleDir(m)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400290 dirs[dir] = true
291
Liz Kammer2ada09a2021-08-11 00:17:36 -0400292 var targets []BazelTarget
Jingwen Chen73850672020-12-14 08:25:34 -0500293
Jingwen Chen164e0862021-02-19 00:48:40 -0500294 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500295 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500296 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500297 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500298 // package module name contain slashes, and thus cannot
299 // be mapped cleanly to a bazel label.
300 return
301 }
Alix94e26032022-08-16 20:37:33 +0000302 t, err := generateSoongModuleTarget(bpCtx, m)
303 if err != nil {
304 errs = append(errs, err)
305 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400306 targets = append(targets, t)
Jingwen Chen33832f92021-01-24 22:55:54 -0500307 default:
Liz Kammer6eff3232021-08-26 08:37:59 -0400308 errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
309 return
Jingwen Chen73850672020-12-14 08:25:34 -0500310 }
311
Spandan Dasabedff02023-03-07 19:24:34 +0000312 for _, target := range targets {
313 targetDir := target.PackageName()
314 buildFileToTargets[targetDir] = append(buildFileToTargets[targetDir], target)
315 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800316 })
Liz Kammer6eff3232021-08-26 08:37:59 -0400317
318 if len(errs) > 0 {
319 return conversionResults{}, errs
320 }
321
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400322 if generateFilegroups {
323 // Add a filegroup target that exposes all sources in the subtree of this package
324 // 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 -0700325 //
326 // This works because: https://bazel.build/reference/be/functions#exports_files
327 // "As a legacy behaviour, also files mentioned as input to a rule are exported with the
328 // default visibility until the flag --incompatible_no_implicit_file_export is flipped. However, this behavior
329 // should not be relied upon and actively migrated away from."
330 //
331 // TODO(b/198619163): We should change this to export_files(glob(["**/*"])) instead, but doing that causes these errors:
332 // "Error in exports_files: generated label '//external/avb:avbtool' conflicts with existing py_binary rule"
333 // So we need to solve all the "target ... is both a rule and a file" warnings first.
Usta Shresthac6057152022-09-24 00:23:31 -0400334 for dir := range dirs {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400335 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
336 name: "bp2build_all_srcs",
Jingwen Chen5802d072023-09-20 10:25:09 +0000337 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]), tags = ["manual"])`,
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400338 ruleClass: "filegroup",
339 })
340 }
341 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500342
Liz Kammer6eff3232021-08-26 08:37:59 -0400343 return conversionResults{
Cole Faust11edf552023-10-13 11:32:14 -0700344 buildFileToTargets: buildFileToTargets,
345 moduleNameToPartition: moduleNameToPartition,
Liz Kammer6eff3232021-08-26 08:37:59 -0400346 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500347}
348
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800349// Convert a module and its deps and props into a Bazel macro/rule
350// representation in the BUILD file.
Alix94e26032022-08-16 20:37:33 +0000351func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) (BazelTarget, error) {
352 props, err := getBuildProperties(ctx, m)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800353
354 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
355 // items, if the modules are added using different DependencyTag. Figure
356 // out the implications of that.
357 depLabels := map[string]bool{}
358 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500359 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800360 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
361 })
362 }
Liz Kammer0eae52e2021-10-06 10:32:26 -0400363
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400364 for p := range ignoredPropNames {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400365 delete(props.Attrs, p)
366 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800367 attributes := propsToAttributes(props.Attrs)
368
369 depLabelList := "[\n"
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400370 for depLabel := range depLabels {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800371 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
372 }
373 depLabelList += " ]"
374
375 targetName := targetNameWithVariant(ctx, m)
376 return BazelTarget{
Spandan Dasabedff02023-03-07 19:24:34 +0000377 name: targetName,
378 packageName: ctx.ModuleDir(m),
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800379 content: fmt.Sprintf(
Sasha Smundakfb589492022-08-04 11:13:27 -0700380 soongModuleTargetTemplate,
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800381 targetName,
382 ctx.ModuleName(m),
383 canonicalizeModuleType(ctx.ModuleType(m)),
384 ctx.ModuleSubDir(m),
385 depLabelList,
386 attributes),
Alix94e26032022-08-16 20:37:33 +0000387 }, err
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800388}
389
Alix94e26032022-08-16 20:37:33 +0000390func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800391 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
392 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
393 if aModule, ok := m.(android.Module); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000394 return extractModuleProperties(aModule.GetProperties(), false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800395 }
396
Alix94e26032022-08-16 20:37:33 +0000397 return BazelAttributes{}, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800398}
399
400// Generically extract module properties and types into a map, keyed by the module property name.
Alix94e26032022-08-16 20:37:33 +0000401func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800402 ret := map[string]string{}
403
404 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400405 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800406 propertiesValue := reflect.ValueOf(properties)
407 // Check that propertiesValue is a pointer to the Properties struct, like
408 // *cc.BaseLinkerProperties or *java.CompilerProperties.
409 //
410 // propertiesValue can also be type-asserted to the structs to
411 // manipulate internal props, if needed.
412 if isStructPtr(propertiesValue.Type()) {
413 structValue := propertiesValue.Elem()
Alix94e26032022-08-16 20:37:33 +0000414 ok, err := extractStructProperties(structValue, 0)
415 if err != nil {
416 return BazelAttributes{}, err
417 }
418 for k, v := range ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000419 if existing, exists := ret[k]; checkForDuplicateProperties && exists {
Alix94e26032022-08-16 20:37:33 +0000420 return BazelAttributes{}, fmt.Errorf(
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000421 "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes",
Alix94e26032022-08-16 20:37:33 +0000422 k, existing)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000423 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800424 ret[k] = v
425 }
426 } else {
Alix94e26032022-08-16 20:37:33 +0000427 return BazelAttributes{},
428 fmt.Errorf(
429 "properties must be a pointer to a struct, got %T",
430 propertiesValue.Interface())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800431 }
432 }
433
Liz Kammer2ada09a2021-08-11 00:17:36 -0400434 return BazelAttributes{
435 Attrs: ret,
Alix94e26032022-08-16 20:37:33 +0000436 }, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800437}
438
439func isStructPtr(t reflect.Type) bool {
440 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
441}
442
443// prettyPrint a property value into the equivalent Starlark representation
444// recursively.
Jingwen Chen58ff6802021-11-17 12:14:41 +0000445func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) {
446 if !emitZeroValues && isZero(propertyValue) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800447 // A property value being set or unset actually matters -- Soong does set default
448 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
Elliott Hughes10363162024-01-09 22:02:03 +0000449 // https://cs.android.com/android/platform/superproject/+/main:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800450 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +0000451 // In Bazel-parlance, we would use "attr.<type>(default = <default
452 // value>)" to set the default value of unset attributes. In the cases
453 // where the bp2build converter didn't set the default value within the
454 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -0400455 // value. For those cases, we return an empty string so we don't
456 // unnecessarily generate empty values.
457 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800458 }
459
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800460 switch propertyValue.Kind() {
461 case reflect.String:
Liz Kammer72beb342022-02-03 08:42:10 -0500462 return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800463 case reflect.Bool:
Liz Kammer72beb342022-02-03 08:42:10 -0500464 return starlark_fmt.PrintBool(propertyValue.Bool()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800465 case reflect.Int, reflect.Uint, reflect.Int64:
Liz Kammer72beb342022-02-03 08:42:10 -0500466 return fmt.Sprintf("%v", propertyValue.Interface()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800467 case reflect.Ptr:
Jingwen Chen58ff6802021-11-17 12:14:41 +0000468 return prettyPrint(propertyValue.Elem(), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800469 case reflect.Slice:
Liz Kammer72beb342022-02-03 08:42:10 -0500470 elements := make([]string, 0, propertyValue.Len())
471 for i := 0; i < propertyValue.Len(); i++ {
472 val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800473 if err != nil {
474 return "", err
475 }
Liz Kammer72beb342022-02-03 08:42:10 -0500476 if val != "" {
477 elements = append(elements, val)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800478 }
479 }
Sam Delmerico932c01c2022-03-25 16:33:26 +0000480 return starlark_fmt.PrintList(elements, indent, func(s string) string {
481 return "%s"
482 }), nil
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000483
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800484 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -0500485 // Special cases where the bp2build sends additional information to the codegenerator
486 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +0000487 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
488 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -0500489 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
490 return fmt.Sprintf("%q", label.Label), nil
491 }
492
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800493 // Sort and print the struct props by the key.
Alix94e26032022-08-16 20:37:33 +0000494 structProps, err := extractStructProperties(propertyValue, indent)
495
496 if err != nil {
497 return "", err
498 }
499
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000500 if len(structProps) == 0 {
501 return "", nil
502 }
Liz Kammer72beb342022-02-03 08:42:10 -0500503 return starlark_fmt.PrintDict(structProps, indent), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800504 case reflect.Interface:
505 // TODO(b/164227191): implement pretty print for interfaces.
506 // Interfaces are used for for arch, multilib and target properties.
507 return "", nil
Spandan Das6a448ec2023-04-19 17:36:12 +0000508 case reflect.Map:
509 if v, ok := propertyValue.Interface().(bazel.StringMapAttribute); ok {
510 return starlark_fmt.PrintStringStringDict(v, indent), nil
511 }
512 return "", fmt.Errorf("bp2build expects map of type map[string]string for field: %s", propertyValue)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800513 default:
514 return "", fmt.Errorf(
515 "unexpected kind for property struct field: %s", propertyValue.Kind())
516 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800517}
518
519// Converts a reflected property struct value into a map of property names and property values,
520// which each property value correctly pretty-printed and indented at the right nest level,
521// since property structs can be nested. In Starlark, nested structs are represented as nested
522// dicts: https://docs.bazel.build/skylark/lib/dict.html
Alix94e26032022-08-16 20:37:33 +0000523func extractStructProperties(structValue reflect.Value, indent int) (map[string]string, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800524 if structValue.Kind() != reflect.Struct {
Alix94e26032022-08-16 20:37:33 +0000525 return map[string]string{}, fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800526 }
527
Alix94e26032022-08-16 20:37:33 +0000528 var err error
529
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800530 ret := map[string]string{}
531 structType := structValue.Type()
532 for i := 0; i < structValue.NumField(); i++ {
533 field := structType.Field(i)
534 if shouldSkipStructField(field) {
535 continue
536 }
537
538 fieldValue := structValue.Field(i)
539 if isZero(fieldValue) {
540 // Ignore zero-valued fields
541 continue
542 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400543
Liz Kammer32a03392021-09-14 11:17:21 -0400544 // if the struct is embedded (anonymous), flatten the properties into the containing struct
545 if field.Anonymous {
546 if field.Type.Kind() == reflect.Ptr {
547 fieldValue = fieldValue.Elem()
548 }
549 if fieldValue.Type().Kind() == reflect.Struct {
Alix94e26032022-08-16 20:37:33 +0000550 propsToMerge, err := extractStructProperties(fieldValue, indent)
551 if err != nil {
552 return map[string]string{}, err
553 }
Liz Kammer32a03392021-09-14 11:17:21 -0400554 for prop, value := range propsToMerge {
555 ret[prop] = value
556 }
557 continue
558 }
559 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800560
561 propertyName := proptools.PropertyNameForField(field.Name)
Alix94e26032022-08-16 20:37:33 +0000562 var prettyPrintedValue string
563 prettyPrintedValue, err = prettyPrint(fieldValue, indent+1, false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800564 if err != nil {
Alix94e26032022-08-16 20:37:33 +0000565 return map[string]string{}, fmt.Errorf(
566 "Error while parsing property: %q. %s",
567 propertyName,
568 err)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800569 }
570 if prettyPrintedValue != "" {
571 ret[propertyName] = prettyPrintedValue
572 }
573 }
574
Alix94e26032022-08-16 20:37:33 +0000575 return ret, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800576}
577
578func isZero(value reflect.Value) bool {
579 switch value.Kind() {
580 case reflect.Func, reflect.Map, reflect.Slice:
581 return value.IsNil()
582 case reflect.Array:
583 valueIsZero := true
584 for i := 0; i < value.Len(); i++ {
585 valueIsZero = valueIsZero && isZero(value.Index(i))
586 }
587 return valueIsZero
588 case reflect.Struct:
589 valueIsZero := true
590 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +0200591 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800592 }
593 return valueIsZero
594 case reflect.Ptr:
595 if !value.IsNil() {
596 return isZero(reflect.Indirect(value))
597 } else {
598 return true
599 }
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500600 // Always print bool/strings, if you want a bool/string attribute to be able to take the default value, use a
601 // pointer instead
602 case reflect.Bool, reflect.String:
Liz Kammerd366c902021-06-03 13:43:01 -0400603 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800604 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -0400605 if !value.IsValid() {
606 return true
607 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800608 zeroValue := reflect.Zero(value.Type())
609 result := value.Interface() == zeroValue.Interface()
610 return result
611 }
612}
613
614func escapeString(s string) string {
615 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +0000616
617 // b/184026959: Reverse the application of some common control sequences.
618 // These must be generated literally in the BUILD file.
619 s = strings.ReplaceAll(s, "\t", "\\t")
620 s = strings.ReplaceAll(s, "\n", "\\n")
621 s = strings.ReplaceAll(s, "\r", "\\r")
622
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800623 return strings.ReplaceAll(s, "\"", "\\\"")
624}
625
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800626func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
627 name := ""
628 if c.ModuleSubDir(logicModule) != "" {
629 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
630 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
631 } else {
632 name = c.ModuleName(logicModule)
633 }
634
635 return strings.Replace(name, "//", "", 1)
636}
637
638func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
639 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
640}