blob: 18213a88007d830adeed4831c66493bc2e39a6c0 [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"
Liz Kammer72beb342022-02-03 08:42:10 -050029 "android/soong/starlark_fmt"
Liz Kammer2dd9ca42020-11-25 16:06:39 -080030 "github.com/google/blueprint"
31 "github.com/google/blueprint/proptools"
32)
33
34type BazelAttributes struct {
35 Attrs map[string]string
36}
37
Cole Faustb4cb0c82023-09-14 15:16:58 -070038type BazelLoadSymbol struct {
39 // The name of the symbol in the file being loaded
40 symbol string
41 // The name the symbol wil have in this file. Can be left blank to use the same name as symbol.
42 alias string
Jingwen Chen40067de2021-01-26 21:58:43 -050043}
44
Cole Faustb4cb0c82023-09-14 15:16:58 -070045type BazelLoad struct {
46 file string
47 symbols []BazelLoadSymbol
48}
49
50type BazelTarget struct {
51 name string
52 packageName string
53 content string
54 ruleClass string
55 loads []BazelLoad
Jingwen Chen40067de2021-01-26 21:58:43 -050056}
57
Jingwen Chenc63677b2021-06-17 05:43:19 +000058// Label is the fully qualified Bazel label constructed from the BazelTarget's
59// package name and target name.
60func (t BazelTarget) Label() string {
61 if t.packageName == "." {
62 return "//:" + t.name
63 } else {
64 return "//" + t.packageName + ":" + t.name
65 }
66}
67
Spandan Dasabedff02023-03-07 19:24:34 +000068// PackageName returns the package of the Bazel target.
69// Defaults to root of tree.
70func (t BazelTarget) PackageName() string {
71 if t.packageName == "" {
72 return "."
73 }
74 return t.packageName
75}
76
Jingwen Chen40067de2021-01-26 21:58:43 -050077// BazelTargets is a typedef for a slice of BazelTarget objects.
78type BazelTargets []BazelTarget
79
Sasha Smundak8bea2672022-08-04 13:31:14 -070080func (targets BazelTargets) packageRule() *BazelTarget {
81 for _, target := range targets {
82 if target.ruleClass == "package" {
83 return &target
84 }
85 }
86 return nil
87}
88
89// sort a list of BazelTargets in-place, by name, and by generated/handcrafted types.
Jingwen Chen49109762021-05-25 05:16:48 +000090func (targets BazelTargets) sort() {
91 sort.Slice(targets, func(i, j int) bool {
Jingwen Chen49109762021-05-25 05:16:48 +000092 return targets[i].name < targets[j].name
93 })
94}
95
Jingwen Chen40067de2021-01-26 21:58:43 -050096// String returns the string representation of BazelTargets, without load
97// statements (use LoadStatements for that), since the targets are usually not
98// adjacent to the load statements at the top of the BUILD file.
99func (targets BazelTargets) String() string {
ustada2a2112023-08-08 00:29:08 -0400100 var res strings.Builder
Jingwen Chen40067de2021-01-26 21:58:43 -0500101 for i, target := range targets {
Sasha Smundak8bea2672022-08-04 13:31:14 -0700102 if target.ruleClass != "package" {
ustada2a2112023-08-08 00:29:08 -0400103 res.WriteString(target.content)
Sasha Smundak8bea2672022-08-04 13:31:14 -0700104 }
Jingwen Chen40067de2021-01-26 21:58:43 -0500105 if i != len(targets)-1 {
ustada2a2112023-08-08 00:29:08 -0400106 res.WriteString("\n\n")
Jingwen Chen40067de2021-01-26 21:58:43 -0500107 }
108 }
ustada2a2112023-08-08 00:29:08 -0400109 return res.String()
Jingwen Chen40067de2021-01-26 21:58:43 -0500110}
111
112// LoadStatements return the string representation of the sorted and deduplicated
113// Starlark rule load statements needed by a group of BazelTargets.
114func (targets BazelTargets) LoadStatements() string {
Cole Faustb4cb0c82023-09-14 15:16:58 -0700115 // First, merge all the load statements from all the targets onto one list
116 bzlToLoadedSymbols := map[string][]BazelLoadSymbol{}
Jingwen Chen40067de2021-01-26 21:58:43 -0500117 for _, target := range targets {
Cole Faustb4cb0c82023-09-14 15:16:58 -0700118 for _, load := range target.loads {
119 outer:
120 for _, symbol := range load.symbols {
121 alias := symbol.alias
122 if alias == "" {
123 alias = symbol.symbol
124 }
125 for _, otherSymbol := range bzlToLoadedSymbols[load.file] {
126 otherAlias := otherSymbol.alias
127 if otherAlias == "" {
128 otherAlias = otherSymbol.symbol
129 }
130 if symbol.symbol == otherSymbol.symbol && alias == otherAlias {
131 continue outer
132 } else if alias == otherAlias {
133 panic(fmt.Sprintf("Conflicting destination (%s) for loads of %s and %s", alias, symbol.symbol, otherSymbol.symbol))
134 }
135 }
136 bzlToLoadedSymbols[load.file] = append(bzlToLoadedSymbols[load.file], symbol)
137 }
Jingwen Chen40067de2021-01-26 21:58:43 -0500138 }
139 }
140
Cole Faustb4cb0c82023-09-14 15:16:58 -0700141 var loadStatements strings.Builder
142 for i, bzl := range android.SortedKeys(bzlToLoadedSymbols) {
143 symbols := bzlToLoadedSymbols[bzl]
144 loadStatements.WriteString("load(\"")
145 loadStatements.WriteString(bzl)
146 loadStatements.WriteString("\", ")
147 sort.Slice(symbols, func(i, j int) bool {
148 if symbols[i].symbol < symbols[j].symbol {
149 return true
150 }
151 return symbols[i].alias < symbols[j].alias
152 })
153 for j, symbol := range symbols {
154 if symbol.alias != "" && symbol.alias != symbol.symbol {
155 loadStatements.WriteString(symbol.alias)
156 loadStatements.WriteString(" = ")
157 }
158 loadStatements.WriteString("\"")
159 loadStatements.WriteString(symbol.symbol)
160 loadStatements.WriteString("\"")
161 if j != len(symbols)-1 {
162 loadStatements.WriteString(", ")
Jingwen Chen40067de2021-01-26 21:58:43 -0500163 }
164 }
Cole Faustb4cb0c82023-09-14 15:16:58 -0700165 loadStatements.WriteString(")")
166 if i != len(bzlToLoadedSymbols)-1 {
167 loadStatements.WriteString("\n")
168 }
Jingwen Chen40067de2021-01-26 21:58:43 -0500169 }
Cole Faustb4cb0c82023-09-14 15:16:58 -0700170 return loadStatements.String()
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800171}
172
173type bpToBuildContext interface {
174 ModuleName(module blueprint.Module) string
175 ModuleDir(module blueprint.Module) string
176 ModuleSubDir(module blueprint.Module) string
177 ModuleType(module blueprint.Module) string
178
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500179 VisitAllModules(visit func(blueprint.Module))
180 VisitDirectDeps(module blueprint.Module, visit func(blueprint.Module))
181}
182
183type CodegenContext struct {
Colin Crossb8083bb2024-10-02 16:07:43 -0700184 config android.Config
185 context *android.Context
186 mode CodegenMode
187 additionalDeps []string
188 topDir string
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500189}
190
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400191func (ctx *CodegenContext) Mode() CodegenMode {
192 return ctx.mode
Jingwen Chen164e0862021-02-19 00:48:40 -0500193}
194
Jingwen Chen33832f92021-01-24 22:55:54 -0500195// CodegenMode is an enum to differentiate code-generation modes.
196type CodegenMode int
197
198const (
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400199 // QueryView - generate BUILD files with targets representing fully mutated
Jingwen Chen33832f92021-01-24 22:55:54 -0500200 // Soong modules, representing the fully configured Soong module graph with
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400201 // variants and dependency edges.
Jingwen Chen33832f92021-01-24 22:55:54 -0500202 //
203 // This mode is used for discovering and introspecting the existing Soong
204 // module graph.
Colin Crossb63d7b32023-12-07 16:54:51 -0800205 QueryView CodegenMode = iota
Jingwen Chen33832f92021-01-24 22:55:54 -0500206)
207
Jingwen Chendcc329a2021-01-26 02:49:03 -0500208func (mode CodegenMode) String() string {
209 switch mode {
Jingwen Chendcc329a2021-01-26 02:49:03 -0500210 case QueryView:
211 return "QueryView"
212 default:
213 return fmt.Sprintf("%d", mode)
214 }
215}
216
Liz Kammerba3ea162021-02-17 13:22:03 -0500217// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
218// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
219// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
220// call AdditionalNinjaDeps and add them manually to the ninja file.
221func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
222 ctx.additionalDeps = append(ctx.additionalDeps, deps...)
223}
224
225// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
226func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
227 return ctx.additionalDeps
228}
229
Paul Duffinc6390592022-11-04 13:35:21 +0000230func (ctx *CodegenContext) Config() android.Config { return ctx.config }
231func (ctx *CodegenContext) Context() *android.Context { return ctx.context }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500232
233// NewCodegenContext creates a wrapper context that conforms to PathContext for
234// writing BUILD files in the output directory.
Cole Faustb85d1a12022-11-08 18:14:01 -0800235func NewCodegenContext(config android.Config, context *android.Context, mode CodegenMode, topDir string) *CodegenContext {
Liz Kammerba3ea162021-02-17 13:22:03 -0500236 return &CodegenContext{
Colin Crossb8083bb2024-10-02 16:07:43 -0700237 context: context,
238 config: config,
239 mode: mode,
240 topDir: topDir,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500241 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800242}
243
244// props is an unsorted map. This function ensures that
245// the generated attributes are sorted to ensure determinism.
246func propsToAttributes(props map[string]string) string {
247 var attributes string
Cole Faust18994c72023-02-28 16:02:16 -0800248 for _, propName := range android.SortedKeys(props) {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400249 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800250 }
251 return attributes
252}
253
Liz Kammer6eff3232021-08-26 08:37:59 -0400254type conversionResults struct {
Cole Faust11edf552023-10-13 11:32:14 -0700255 buildFileToTargets map[string]BazelTargets
256 moduleNameToPartition map[string]string
Liz Kammer6eff3232021-08-26 08:37:59 -0400257}
258
259func (r conversionResults) BuildDirToTargets() map[string]BazelTargets {
260 return r.buildFileToTargets
261}
262
263func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (conversionResults, []error) {
ustaaaf2fd12023-07-01 11:40:36 -0400264 ctx.Context().BeginEvent("GenerateBazelTargets")
265 defer ctx.Context().EndEvent("GenerateBazelTargets")
Jingwen Chen40067de2021-01-26 21:58:43 -0500266 buildFileToTargets := make(map[string]BazelTargets)
Jingwen Chen164e0862021-02-19 00:48:40 -0500267
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400268 dirs := make(map[string]bool)
Cole Faust11edf552023-10-13 11:32:14 -0700269 moduleNameToPartition := make(map[string]string)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400270
Liz Kammer6eff3232021-08-26 08:37:59 -0400271 var errs []error
272
Jingwen Chen164e0862021-02-19 00:48:40 -0500273 bpCtx := ctx.Context()
274 bpCtx.VisitAllModules(func(m blueprint.Module) {
275 dir := bpCtx.ModuleDir(m)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400276 dirs[dir] = true
277
Liz Kammer2ada09a2021-08-11 00:17:36 -0400278 var targets []BazelTarget
Jingwen Chen73850672020-12-14 08:25:34 -0500279
Jingwen Chen164e0862021-02-19 00:48:40 -0500280 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500281 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500282 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500283 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500284 // package module name contain slashes, and thus cannot
285 // be mapped cleanly to a bazel label.
286 return
287 }
Alix94e26032022-08-16 20:37:33 +0000288 t, err := generateSoongModuleTarget(bpCtx, m)
289 if err != nil {
290 errs = append(errs, err)
291 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400292 targets = append(targets, t)
Jingwen Chen33832f92021-01-24 22:55:54 -0500293 default:
Liz Kammer6eff3232021-08-26 08:37:59 -0400294 errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
295 return
Jingwen Chen73850672020-12-14 08:25:34 -0500296 }
297
Spandan Dasabedff02023-03-07 19:24:34 +0000298 for _, target := range targets {
299 targetDir := target.PackageName()
300 buildFileToTargets[targetDir] = append(buildFileToTargets[targetDir], target)
301 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800302 })
Liz Kammer6eff3232021-08-26 08:37:59 -0400303
304 if len(errs) > 0 {
305 return conversionResults{}, errs
306 }
307
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400308 if generateFilegroups {
309 // Add a filegroup target that exposes all sources in the subtree of this package
310 // 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 -0700311 //
312 // This works because: https://bazel.build/reference/be/functions#exports_files
313 // "As a legacy behaviour, also files mentioned as input to a rule are exported with the
314 // default visibility until the flag --incompatible_no_implicit_file_export is flipped. However, this behavior
315 // should not be relied upon and actively migrated away from."
316 //
317 // TODO(b/198619163): We should change this to export_files(glob(["**/*"])) instead, but doing that causes these errors:
318 // "Error in exports_files: generated label '//external/avb:avbtool' conflicts with existing py_binary rule"
319 // So we need to solve all the "target ... is both a rule and a file" warnings first.
Usta Shresthac6057152022-09-24 00:23:31 -0400320 for dir := range dirs {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400321 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
322 name: "bp2build_all_srcs",
Jingwen Chen5802d072023-09-20 10:25:09 +0000323 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]), tags = ["manual"])`,
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400324 ruleClass: "filegroup",
325 })
326 }
327 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500328
Liz Kammer6eff3232021-08-26 08:37:59 -0400329 return conversionResults{
Cole Faust11edf552023-10-13 11:32:14 -0700330 buildFileToTargets: buildFileToTargets,
331 moduleNameToPartition: moduleNameToPartition,
Liz Kammer6eff3232021-08-26 08:37:59 -0400332 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500333}
334
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800335// Convert a module and its deps and props into a Bazel macro/rule
336// representation in the BUILD file.
Alix94e26032022-08-16 20:37:33 +0000337func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) (BazelTarget, error) {
338 props, err := getBuildProperties(ctx, m)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800339
340 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
341 // items, if the modules are added using different DependencyTag. Figure
342 // out the implications of that.
343 depLabels := map[string]bool{}
344 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500345 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800346 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
347 })
348 }
Liz Kammer0eae52e2021-10-06 10:32:26 -0400349
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400350 for p := range ignoredPropNames {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400351 delete(props.Attrs, p)
352 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800353 attributes := propsToAttributes(props.Attrs)
354
355 depLabelList := "[\n"
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400356 for depLabel := range depLabels {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800357 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
358 }
359 depLabelList += " ]"
360
361 targetName := targetNameWithVariant(ctx, m)
362 return BazelTarget{
Spandan Dasabedff02023-03-07 19:24:34 +0000363 name: targetName,
364 packageName: ctx.ModuleDir(m),
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800365 content: fmt.Sprintf(
Sasha Smundakfb589492022-08-04 11:13:27 -0700366 soongModuleTargetTemplate,
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800367 targetName,
368 ctx.ModuleName(m),
369 canonicalizeModuleType(ctx.ModuleType(m)),
370 ctx.ModuleSubDir(m),
371 depLabelList,
372 attributes),
Alix94e26032022-08-16 20:37:33 +0000373 }, err
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800374}
375
Alix94e26032022-08-16 20:37:33 +0000376func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800377 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
378 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
379 if aModule, ok := m.(android.Module); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000380 return extractModuleProperties(aModule.GetProperties(), false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800381 }
382
Alix94e26032022-08-16 20:37:33 +0000383 return BazelAttributes{}, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800384}
385
386// Generically extract module properties and types into a map, keyed by the module property name.
Alix94e26032022-08-16 20:37:33 +0000387func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800388 ret := map[string]string{}
389
390 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400391 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800392 propertiesValue := reflect.ValueOf(properties)
393 // Check that propertiesValue is a pointer to the Properties struct, like
394 // *cc.BaseLinkerProperties or *java.CompilerProperties.
395 //
396 // propertiesValue can also be type-asserted to the structs to
397 // manipulate internal props, if needed.
398 if isStructPtr(propertiesValue.Type()) {
399 structValue := propertiesValue.Elem()
Alix94e26032022-08-16 20:37:33 +0000400 ok, err := extractStructProperties(structValue, 0)
401 if err != nil {
402 return BazelAttributes{}, err
403 }
404 for k, v := range ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000405 if existing, exists := ret[k]; checkForDuplicateProperties && exists {
Alix94e26032022-08-16 20:37:33 +0000406 return BazelAttributes{}, fmt.Errorf(
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000407 "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes",
Alix94e26032022-08-16 20:37:33 +0000408 k, existing)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000409 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800410 ret[k] = v
411 }
412 } else {
Alix94e26032022-08-16 20:37:33 +0000413 return BazelAttributes{},
414 fmt.Errorf(
415 "properties must be a pointer to a struct, got %T",
416 propertiesValue.Interface())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800417 }
418 }
419
Liz Kammer2ada09a2021-08-11 00:17:36 -0400420 return BazelAttributes{
421 Attrs: ret,
Alix94e26032022-08-16 20:37:33 +0000422 }, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800423}
424
425func isStructPtr(t reflect.Type) bool {
426 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
427}
428
429// prettyPrint a property value into the equivalent Starlark representation
430// recursively.
Jingwen Chen58ff6802021-11-17 12:14:41 +0000431func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) {
432 if !emitZeroValues && isZero(propertyValue) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800433 // A property value being set or unset actually matters -- Soong does set default
434 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
Elliott Hughes10363162024-01-09 22:02:03 +0000435 // 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 -0800436 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +0000437 // In Bazel-parlance, we would use "attr.<type>(default = <default
438 // value>)" to set the default value of unset attributes. In the cases
439 // where the bp2build converter didn't set the default value within the
440 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -0400441 // value. For those cases, we return an empty string so we don't
442 // unnecessarily generate empty values.
443 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800444 }
445
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800446 switch propertyValue.Kind() {
447 case reflect.String:
Liz Kammer72beb342022-02-03 08:42:10 -0500448 return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800449 case reflect.Bool:
Liz Kammer72beb342022-02-03 08:42:10 -0500450 return starlark_fmt.PrintBool(propertyValue.Bool()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800451 case reflect.Int, reflect.Uint, reflect.Int64:
Liz Kammer72beb342022-02-03 08:42:10 -0500452 return fmt.Sprintf("%v", propertyValue.Interface()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800453 case reflect.Ptr:
Jingwen Chen58ff6802021-11-17 12:14:41 +0000454 return prettyPrint(propertyValue.Elem(), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800455 case reflect.Slice:
Liz Kammer72beb342022-02-03 08:42:10 -0500456 elements := make([]string, 0, propertyValue.Len())
457 for i := 0; i < propertyValue.Len(); i++ {
458 val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800459 if err != nil {
460 return "", err
461 }
Liz Kammer72beb342022-02-03 08:42:10 -0500462 if val != "" {
463 elements = append(elements, val)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800464 }
465 }
Sam Delmerico932c01c2022-03-25 16:33:26 +0000466 return starlark_fmt.PrintList(elements, indent, func(s string) string {
467 return "%s"
468 }), nil
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000469
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800470 case reflect.Struct:
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800471 // Sort and print the struct props by the key.
Alix94e26032022-08-16 20:37:33 +0000472 structProps, err := extractStructProperties(propertyValue, indent)
473
474 if err != nil {
475 return "", err
476 }
477
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000478 if len(structProps) == 0 {
479 return "", nil
480 }
Liz Kammer72beb342022-02-03 08:42:10 -0500481 return starlark_fmt.PrintDict(structProps, indent), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800482 case reflect.Interface:
483 // TODO(b/164227191): implement pretty print for interfaces.
484 // Interfaces are used for for arch, multilib and target properties.
485 return "", nil
Spandan Das6a448ec2023-04-19 17:36:12 +0000486 case reflect.Map:
Colin Crossb8083bb2024-10-02 16:07:43 -0700487 if v, ok := propertyValue.Interface().(map[string]string); ok {
Spandan Das6a448ec2023-04-19 17:36:12 +0000488 return starlark_fmt.PrintStringStringDict(v, indent), nil
489 }
490 return "", fmt.Errorf("bp2build expects map of type map[string]string for field: %s", propertyValue)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800491 default:
492 return "", fmt.Errorf(
493 "unexpected kind for property struct field: %s", propertyValue.Kind())
494 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800495}
496
497// Converts a reflected property struct value into a map of property names and property values,
498// which each property value correctly pretty-printed and indented at the right nest level,
499// since property structs can be nested. In Starlark, nested structs are represented as nested
500// dicts: https://docs.bazel.build/skylark/lib/dict.html
Alix94e26032022-08-16 20:37:33 +0000501func extractStructProperties(structValue reflect.Value, indent int) (map[string]string, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800502 if structValue.Kind() != reflect.Struct {
Alix94e26032022-08-16 20:37:33 +0000503 return map[string]string{}, fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800504 }
505
Alix94e26032022-08-16 20:37:33 +0000506 var err error
507
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800508 ret := map[string]string{}
509 structType := structValue.Type()
510 for i := 0; i < structValue.NumField(); i++ {
511 field := structType.Field(i)
512 if shouldSkipStructField(field) {
513 continue
514 }
515
516 fieldValue := structValue.Field(i)
517 if isZero(fieldValue) {
518 // Ignore zero-valued fields
519 continue
520 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400521
Liz Kammer32a03392021-09-14 11:17:21 -0400522 // if the struct is embedded (anonymous), flatten the properties into the containing struct
523 if field.Anonymous {
524 if field.Type.Kind() == reflect.Ptr {
525 fieldValue = fieldValue.Elem()
526 }
527 if fieldValue.Type().Kind() == reflect.Struct {
Alix94e26032022-08-16 20:37:33 +0000528 propsToMerge, err := extractStructProperties(fieldValue, indent)
529 if err != nil {
530 return map[string]string{}, err
531 }
Liz Kammer32a03392021-09-14 11:17:21 -0400532 for prop, value := range propsToMerge {
533 ret[prop] = value
534 }
535 continue
536 }
537 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800538
539 propertyName := proptools.PropertyNameForField(field.Name)
Alix94e26032022-08-16 20:37:33 +0000540 var prettyPrintedValue string
541 prettyPrintedValue, err = prettyPrint(fieldValue, indent+1, false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800542 if err != nil {
Alix94e26032022-08-16 20:37:33 +0000543 return map[string]string{}, fmt.Errorf(
544 "Error while parsing property: %q. %s",
545 propertyName,
546 err)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800547 }
548 if prettyPrintedValue != "" {
549 ret[propertyName] = prettyPrintedValue
550 }
551 }
552
Alix94e26032022-08-16 20:37:33 +0000553 return ret, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800554}
555
556func isZero(value reflect.Value) bool {
557 switch value.Kind() {
558 case reflect.Func, reflect.Map, reflect.Slice:
559 return value.IsNil()
560 case reflect.Array:
561 valueIsZero := true
562 for i := 0; i < value.Len(); i++ {
563 valueIsZero = valueIsZero && isZero(value.Index(i))
564 }
565 return valueIsZero
566 case reflect.Struct:
567 valueIsZero := true
568 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +0200569 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800570 }
571 return valueIsZero
572 case reflect.Ptr:
573 if !value.IsNil() {
574 return isZero(reflect.Indirect(value))
575 } else {
576 return true
577 }
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500578 // Always print bool/strings, if you want a bool/string attribute to be able to take the default value, use a
579 // pointer instead
580 case reflect.Bool, reflect.String:
Liz Kammerd366c902021-06-03 13:43:01 -0400581 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800582 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -0400583 if !value.IsValid() {
584 return true
585 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800586 zeroValue := reflect.Zero(value.Type())
587 result := value.Interface() == zeroValue.Interface()
588 return result
589 }
590}
591
592func escapeString(s string) string {
593 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +0000594
595 // b/184026959: Reverse the application of some common control sequences.
596 // These must be generated literally in the BUILD file.
597 s = strings.ReplaceAll(s, "\t", "\\t")
598 s = strings.ReplaceAll(s, "\n", "\\n")
599 s = strings.ReplaceAll(s, "\r", "\\r")
600
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800601 return strings.ReplaceAll(s, "\"", "\\\"")
602}
603
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800604func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
605 name := ""
606 if c.ModuleSubDir(logicModule) != "" {
607 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
608 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
609 } else {
610 name = c.ModuleName(logicModule)
611 }
612
613 return strings.Replace(name, "//", "", 1)
614}
615
616func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
617 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
618}