blob: f652a351798c527f0bcce24f21278cc621ba32a8 [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"
30
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
39type BazelTarget struct {
Jingwen Chen40067de2021-01-26 21:58:43 -050040 name string
Jingwen Chenc63677b2021-06-17 05:43:19 +000041 packageName string
Jingwen Chen40067de2021-01-26 21:58:43 -050042 content string
43 ruleClass string
44 bzlLoadLocation string
Jingwen Chen49109762021-05-25 05:16:48 +000045 handcrafted bool
Jingwen Chen40067de2021-01-26 21:58:43 -050046}
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
Jingwen Chen49109762021-05-25 05:16:48 +000067// HasHandcraftedTargetsreturns true if a set of bazel targets contain
68// handcrafted ones.
69func (targets BazelTargets) hasHandcraftedTargets() bool {
70 for _, target := range targets {
71 if target.handcrafted {
72 return true
73 }
74 }
75 return false
76}
77
78// sort a list of BazelTargets in-place, by name, and by generated/handcrafted types.
79func (targets BazelTargets) sort() {
80 sort.Slice(targets, func(i, j int) bool {
81 if targets[i].handcrafted != targets[j].handcrafted {
82 // Handcrafted targets will be generated after the bp2build generated targets.
83 return targets[j].handcrafted
84 }
85 // This will cover all bp2build generated targets.
86 return targets[i].name < targets[j].name
87 })
88}
89
Jingwen Chen40067de2021-01-26 21:58:43 -050090// String returns the string representation of BazelTargets, without load
91// statements (use LoadStatements for that), since the targets are usually not
92// adjacent to the load statements at the top of the BUILD file.
93func (targets BazelTargets) String() string {
94 var res string
95 for i, target := range targets {
Jingwen Chen49109762021-05-25 05:16:48 +000096 // There is only at most 1 handcrafted "target", because its contents
97 // represent the entire BUILD file content from the tree. See
98 // build_conversion.go#getHandcraftedBuildContent for more information.
99 //
100 // Add a header to make it easy to debug where the handcrafted targets
101 // are in a generated BUILD file.
102 if target.handcrafted {
103 res += "# -----------------------------\n"
104 res += "# Section: Handcrafted targets. \n"
105 res += "# -----------------------------\n\n"
106 }
107
Jingwen Chen40067de2021-01-26 21:58:43 -0500108 res += target.content
109 if i != len(targets)-1 {
110 res += "\n\n"
111 }
112 }
113 return res
114}
115
116// LoadStatements return the string representation of the sorted and deduplicated
117// Starlark rule load statements needed by a group of BazelTargets.
118func (targets BazelTargets) LoadStatements() string {
119 bzlToLoadedSymbols := map[string][]string{}
120 for _, target := range targets {
121 if target.IsLoadedFromStarlark() {
122 bzlToLoadedSymbols[target.bzlLoadLocation] =
123 append(bzlToLoadedSymbols[target.bzlLoadLocation], target.ruleClass)
124 }
125 }
126
127 var loadStatements []string
128 for bzl, ruleClasses := range bzlToLoadedSymbols {
129 loadStatement := "load(\""
130 loadStatement += bzl
131 loadStatement += "\", "
132 ruleClasses = android.SortedUniqueStrings(ruleClasses)
133 for i, ruleClass := range ruleClasses {
134 loadStatement += "\"" + ruleClass + "\""
135 if i != len(ruleClasses)-1 {
136 loadStatement += ", "
137 }
138 }
139 loadStatement += ")"
140 loadStatements = append(loadStatements, loadStatement)
141 }
142 return strings.Join(android.SortedUniqueStrings(loadStatements), "\n")
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800143}
144
145type bpToBuildContext interface {
146 ModuleName(module blueprint.Module) string
147 ModuleDir(module blueprint.Module) string
148 ModuleSubDir(module blueprint.Module) string
149 ModuleType(module blueprint.Module) string
150
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500151 VisitAllModules(visit func(blueprint.Module))
152 VisitDirectDeps(module blueprint.Module, visit func(blueprint.Module))
153}
154
155type CodegenContext struct {
Liz Kammerba3ea162021-02-17 13:22:03 -0500156 config android.Config
157 context android.Context
158 mode CodegenMode
159 additionalDeps []string
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500160}
161
Jingwen Chen164e0862021-02-19 00:48:40 -0500162func (c *CodegenContext) Mode() CodegenMode {
163 return c.mode
164}
165
Jingwen Chen33832f92021-01-24 22:55:54 -0500166// CodegenMode is an enum to differentiate code-generation modes.
167type CodegenMode int
168
169const (
170 // Bp2Build: generate BUILD files with targets buildable by Bazel directly.
171 //
172 // This mode is used for the Soong->Bazel build definition conversion.
173 Bp2Build CodegenMode = iota
174
175 // QueryView: generate BUILD files with targets representing fully mutated
176 // Soong modules, representing the fully configured Soong module graph with
177 // variants and dependency endges.
178 //
179 // This mode is used for discovering and introspecting the existing Soong
180 // module graph.
181 QueryView
182)
183
Jingwen Chendcc329a2021-01-26 02:49:03 -0500184func (mode CodegenMode) String() string {
185 switch mode {
186 case Bp2Build:
187 return "Bp2Build"
188 case QueryView:
189 return "QueryView"
190 default:
191 return fmt.Sprintf("%d", mode)
192 }
193}
194
Liz Kammerba3ea162021-02-17 13:22:03 -0500195// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
196// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
197// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
198// call AdditionalNinjaDeps and add them manually to the ninja file.
199func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
200 ctx.additionalDeps = append(ctx.additionalDeps, deps...)
201}
202
203// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
204func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
205 return ctx.additionalDeps
206}
207
208func (ctx *CodegenContext) Config() android.Config { return ctx.config }
209func (ctx *CodegenContext) Context() android.Context { return ctx.context }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500210
211// NewCodegenContext creates a wrapper context that conforms to PathContext for
212// writing BUILD files in the output directory.
Liz Kammerba3ea162021-02-17 13:22:03 -0500213func NewCodegenContext(config android.Config, context android.Context, mode CodegenMode) *CodegenContext {
214 return &CodegenContext{
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500215 context: context,
216 config: config,
Jingwen Chen33832f92021-01-24 22:55:54 -0500217 mode: mode,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500218 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800219}
220
221// props is an unsorted map. This function ensures that
222// the generated attributes are sorted to ensure determinism.
223func propsToAttributes(props map[string]string) string {
224 var attributes string
225 for _, propName := range android.SortedStringKeys(props) {
226 if shouldGenerateAttribute(propName) {
227 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
228 }
229 }
230 return attributes
231}
232
Jingwen Chenc63677b2021-06-17 05:43:19 +0000233func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (map[string]BazelTargets, CodegenMetrics, CodegenCompatLayer) {
Jingwen Chen40067de2021-01-26 21:58:43 -0500234 buildFileToTargets := make(map[string]BazelTargets)
Liz Kammerba3ea162021-02-17 13:22:03 -0500235 buildFileToAppend := make(map[string]bool)
Jingwen Chen164e0862021-02-19 00:48:40 -0500236
237 // Simple metrics tracking for bp2build
Liz Kammerba3ea162021-02-17 13:22:03 -0500238 metrics := CodegenMetrics{
239 RuleClassCount: make(map[string]int),
240 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500241
Jingwen Chenc63677b2021-06-17 05:43:19 +0000242 compatLayer := CodegenCompatLayer{
243 NameToLabelMap: make(map[string]string),
244 }
245
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400246 dirs := make(map[string]bool)
247
Jingwen Chen164e0862021-02-19 00:48:40 -0500248 bpCtx := ctx.Context()
249 bpCtx.VisitAllModules(func(m blueprint.Module) {
250 dir := bpCtx.ModuleDir(m)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400251 dirs[dir] = true
252
Liz Kammer2ada09a2021-08-11 00:17:36 -0400253 var targets []BazelTarget
Jingwen Chen73850672020-12-14 08:25:34 -0500254
Jingwen Chen164e0862021-02-19 00:48:40 -0500255 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500256 case Bp2Build:
Liz Kammerba3ea162021-02-17 13:22:03 -0500257 if b, ok := m.(android.Bazelable); ok && b.HasHandcraftedLabel() {
258 metrics.handCraftedTargetCount += 1
259 metrics.TotalModuleCount += 1
Jingwen Chenc63677b2021-06-17 05:43:19 +0000260 compatLayer.AddNameToLabelEntry(m.Name(), b.HandcraftedLabel())
Liz Kammerba3ea162021-02-17 13:22:03 -0500261 pathToBuildFile := getBazelPackagePath(b)
262 // We are using the entire contents of handcrafted build file, so if multiple targets within
263 // a package have handcrafted targets, we only want to include the contents one time.
264 if _, exists := buildFileToAppend[pathToBuildFile]; exists {
265 return
266 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400267 t, err := getHandcraftedBuildContent(ctx, b, pathToBuildFile)
Liz Kammerba3ea162021-02-17 13:22:03 -0500268 if err != nil {
269 panic(fmt.Errorf("Error converting %s: %s", bpCtx.ModuleName(m), err))
270 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400271 targets = append(targets, t)
Liz Kammerba3ea162021-02-17 13:22:03 -0500272 // TODO(b/181575318): currently we append the whole BUILD file, let's change that to do
273 // something more targeted based on the rule type and target
274 buildFileToAppend[pathToBuildFile] = true
Liz Kammer2ada09a2021-08-11 00:17:36 -0400275 } else if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
276 targets = generateBazelTargets(bpCtx, aModule)
277 for _, t := range targets {
278 if t.name == m.Name() {
279 // only add targets that exist in Soong to compatibility layer
280 compatLayer.AddNameToLabelEntry(m.Name(), t.Label())
281 }
282 metrics.RuleClassCount[t.ruleClass] += 1
283 }
Liz Kammerfc46bc12021-02-19 11:06:17 -0500284 } else {
Liz Kammerba3ea162021-02-17 13:22:03 -0500285 metrics.TotalModuleCount += 1
286 return
Jingwen Chen73850672020-12-14 08:25:34 -0500287 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500288 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500289 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500290 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500291 // package module name contain slashes, and thus cannot
292 // be mapped cleanly to a bazel label.
293 return
294 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400295 t := generateSoongModuleTarget(bpCtx, m)
296 targets = append(targets, t)
Jingwen Chen33832f92021-01-24 22:55:54 -0500297 default:
Jingwen Chen164e0862021-02-19 00:48:40 -0500298 panic(fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
Jingwen Chen73850672020-12-14 08:25:34 -0500299 }
300
Liz Kammer2ada09a2021-08-11 00:17:36 -0400301 buildFileToTargets[dir] = append(buildFileToTargets[dir], targets...)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800302 })
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400303 if generateFilegroups {
304 // Add a filegroup target that exposes all sources in the subtree of this package
305 // NOTE: This also means we generate a BUILD file for every Android.bp file (as long as it has at least one module)
306 for dir, _ := range dirs {
307 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
308 name: "bp2build_all_srcs",
309 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]))`,
310 ruleClass: "filegroup",
311 })
312 }
313 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500314
Jingwen Chenc63677b2021-06-17 05:43:19 +0000315 return buildFileToTargets, metrics, compatLayer
Jingwen Chen164e0862021-02-19 00:48:40 -0500316}
317
Liz Kammerba3ea162021-02-17 13:22:03 -0500318func getBazelPackagePath(b android.Bazelable) string {
Liz Kammerbdc60992021-02-24 16:55:11 -0500319 label := b.HandcraftedLabel()
Liz Kammerba3ea162021-02-17 13:22:03 -0500320 pathToBuildFile := strings.TrimPrefix(label, "//")
321 pathToBuildFile = strings.Split(pathToBuildFile, ":")[0]
322 return pathToBuildFile
323}
324
325func getHandcraftedBuildContent(ctx *CodegenContext, b android.Bazelable, pathToBuildFile string) (BazelTarget, error) {
326 p := android.ExistentPathForSource(ctx, pathToBuildFile, HandcraftedBuildFileName)
327 if !p.Valid() {
328 return BazelTarget{}, fmt.Errorf("Could not find file %q for handcrafted target.", pathToBuildFile)
329 }
330 c, err := b.GetBazelBuildFileContents(ctx.Config(), pathToBuildFile, HandcraftedBuildFileName)
331 if err != nil {
332 return BazelTarget{}, err
333 }
334 // TODO(b/181575318): once this is more targeted, we need to include name, rule class, etc
335 return BazelTarget{
Jingwen Chen49109762021-05-25 05:16:48 +0000336 content: c,
337 handcrafted: true,
Liz Kammerba3ea162021-02-17 13:22:03 -0500338 }, nil
339}
340
Liz Kammer2ada09a2021-08-11 00:17:36 -0400341func generateBazelTargets(ctx bpToBuildContext, m android.Module) []BazelTarget {
342 var targets []BazelTarget
343 for _, m := range m.Bp2buildTargets() {
344 targets = append(targets, generateBazelTarget(ctx, m))
345 }
346 return targets
347}
348
349type bp2buildModule interface {
350 TargetName() string
351 TargetPackage() string
352 BazelRuleClass() string
353 BazelRuleLoadLocation() string
354 BazelAttributes() interface{}
355}
356
357func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) BazelTarget {
358 ruleClass := m.BazelRuleClass()
359 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500360
Jingwen Chen73850672020-12-14 08:25:34 -0500361 // extract the bazel attributes from the module.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400362 props := extractModuleProperties([]interface{}{m.BazelAttributes()})
Jingwen Chen73850672020-12-14 08:25:34 -0500363
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500364 delete(props.Attrs, "bp2build_available")
365
Jingwen Chen73850672020-12-14 08:25:34 -0500366 // Return the Bazel target with rule class and attributes, ready to be
367 // code-generated.
368 attributes := propsToAttributes(props.Attrs)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400369 targetName := m.TargetName()
Jingwen Chen73850672020-12-14 08:25:34 -0500370 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500371 name: targetName,
Liz Kammer2ada09a2021-08-11 00:17:36 -0400372 packageName: m.TargetPackage(),
Jingwen Chen40067de2021-01-26 21:58:43 -0500373 ruleClass: ruleClass,
374 bzlLoadLocation: bzlLoadLocation,
Jingwen Chen73850672020-12-14 08:25:34 -0500375 content: fmt.Sprintf(
376 bazelTarget,
377 ruleClass,
378 targetName,
379 attributes,
380 ),
Jingwen Chen49109762021-05-25 05:16:48 +0000381 handcrafted: false,
Jingwen Chen73850672020-12-14 08:25:34 -0500382 }
383}
384
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800385// Convert a module and its deps and props into a Bazel macro/rule
386// representation in the BUILD file.
387func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) BazelTarget {
388 props := getBuildProperties(ctx, m)
389
390 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
391 // items, if the modules are added using different DependencyTag. Figure
392 // out the implications of that.
393 depLabels := map[string]bool{}
394 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500395 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800396 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
397 })
398 }
399 attributes := propsToAttributes(props.Attrs)
400
401 depLabelList := "[\n"
402 for depLabel, _ := range depLabels {
403 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
404 }
405 depLabelList += " ]"
406
407 targetName := targetNameWithVariant(ctx, m)
408 return BazelTarget{
409 name: targetName,
410 content: fmt.Sprintf(
411 soongModuleTarget,
412 targetName,
413 ctx.ModuleName(m),
414 canonicalizeModuleType(ctx.ModuleType(m)),
415 ctx.ModuleSubDir(m),
416 depLabelList,
417 attributes),
418 }
419}
420
421func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) BazelAttributes {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800422 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
423 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
424 if aModule, ok := m.(android.Module); ok {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400425 return extractModuleProperties(aModule.GetProperties())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800426 }
427
Liz Kammer2ada09a2021-08-11 00:17:36 -0400428 return BazelAttributes{}
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800429}
430
431// Generically extract module properties and types into a map, keyed by the module property name.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400432func extractModuleProperties(props []interface{}) BazelAttributes {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800433 ret := map[string]string{}
434
435 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400436 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800437 propertiesValue := reflect.ValueOf(properties)
438 // Check that propertiesValue is a pointer to the Properties struct, like
439 // *cc.BaseLinkerProperties or *java.CompilerProperties.
440 //
441 // propertiesValue can also be type-asserted to the structs to
442 // manipulate internal props, if needed.
443 if isStructPtr(propertiesValue.Type()) {
444 structValue := propertiesValue.Elem()
445 for k, v := range extractStructProperties(structValue, 0) {
446 ret[k] = v
447 }
448 } else {
449 panic(fmt.Errorf(
450 "properties must be a pointer to a struct, got %T",
451 propertiesValue.Interface()))
452 }
453 }
454
Liz Kammer2ada09a2021-08-11 00:17:36 -0400455 return BazelAttributes{
456 Attrs: ret,
457 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800458}
459
460func isStructPtr(t reflect.Type) bool {
461 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
462}
463
464// prettyPrint a property value into the equivalent Starlark representation
465// recursively.
466func prettyPrint(propertyValue reflect.Value, indent int) (string, error) {
467 if isZero(propertyValue) {
468 // A property value being set or unset actually matters -- Soong does set default
469 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
470 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
471 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +0000472 // In Bazel-parlance, we would use "attr.<type>(default = <default
473 // value>)" to set the default value of unset attributes. In the cases
474 // where the bp2build converter didn't set the default value within the
475 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -0400476 // value. For those cases, we return an empty string so we don't
477 // unnecessarily generate empty values.
478 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800479 }
480
481 var ret string
482 switch propertyValue.Kind() {
483 case reflect.String:
484 ret = fmt.Sprintf("\"%v\"", escapeString(propertyValue.String()))
485 case reflect.Bool:
486 ret = strings.Title(fmt.Sprintf("%v", propertyValue.Interface()))
487 case reflect.Int, reflect.Uint, reflect.Int64:
488 ret = fmt.Sprintf("%v", propertyValue.Interface())
489 case reflect.Ptr:
490 return prettyPrint(propertyValue.Elem(), indent)
491 case reflect.Slice:
Jingwen Chen63930982021-03-24 10:04:33 -0400492 if propertyValue.Len() == 0 {
Liz Kammer2b07ec72021-05-26 15:08:27 -0400493 return "[]", nil
Jingwen Chen63930982021-03-24 10:04:33 -0400494 }
495
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000496 if propertyValue.Len() == 1 {
497 // Single-line list for list with only 1 element
498 ret += "["
499 indexedValue, err := prettyPrint(propertyValue.Index(0), indent)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800500 if err != nil {
501 return "", err
502 }
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000503 ret += indexedValue
504 ret += "]"
505 } else {
506 // otherwise, use a multiline list.
507 ret += "[\n"
508 for i := 0; i < propertyValue.Len(); i++ {
509 indexedValue, err := prettyPrint(propertyValue.Index(i), indent+1)
510 if err != nil {
511 return "", err
512 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800513
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000514 if indexedValue != "" {
515 ret += makeIndent(indent + 1)
516 ret += indexedValue
517 ret += ",\n"
518 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800519 }
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000520 ret += makeIndent(indent)
521 ret += "]"
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800522 }
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000523
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800524 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -0500525 // Special cases where the bp2build sends additional information to the codegenerator
526 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +0000527 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
528 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -0500529 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
530 return fmt.Sprintf("%q", label.Label), nil
531 }
532
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800533 ret = "{\n"
534 // Sort and print the struct props by the key.
535 structProps := extractStructProperties(propertyValue, indent)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000536 if len(structProps) == 0 {
537 return "", nil
538 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800539 for _, k := range android.SortedStringKeys(structProps) {
540 ret += makeIndent(indent + 1)
541 ret += fmt.Sprintf("%q: %s,\n", k, structProps[k])
542 }
543 ret += makeIndent(indent)
544 ret += "}"
545 case reflect.Interface:
546 // TODO(b/164227191): implement pretty print for interfaces.
547 // Interfaces are used for for arch, multilib and target properties.
548 return "", nil
549 default:
550 return "", fmt.Errorf(
551 "unexpected kind for property struct field: %s", propertyValue.Kind())
552 }
553 return ret, nil
554}
555
556// Converts a reflected property struct value into a map of property names and property values,
557// which each property value correctly pretty-printed and indented at the right nest level,
558// since property structs can be nested. In Starlark, nested structs are represented as nested
559// dicts: https://docs.bazel.build/skylark/lib/dict.html
560func extractStructProperties(structValue reflect.Value, indent int) map[string]string {
561 if structValue.Kind() != reflect.Struct {
562 panic(fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind()))
563 }
564
565 ret := map[string]string{}
566 structType := structValue.Type()
567 for i := 0; i < structValue.NumField(); i++ {
568 field := structType.Field(i)
569 if shouldSkipStructField(field) {
570 continue
571 }
572
573 fieldValue := structValue.Field(i)
574 if isZero(fieldValue) {
575 // Ignore zero-valued fields
576 continue
577 }
578
579 propertyName := proptools.PropertyNameForField(field.Name)
580 prettyPrintedValue, err := prettyPrint(fieldValue, indent+1)
581 if err != nil {
582 panic(
583 fmt.Errorf(
584 "Error while parsing property: %q. %s",
585 propertyName,
586 err))
587 }
588 if prettyPrintedValue != "" {
589 ret[propertyName] = prettyPrintedValue
590 }
591 }
592
593 return ret
594}
595
596func isZero(value reflect.Value) bool {
597 switch value.Kind() {
598 case reflect.Func, reflect.Map, reflect.Slice:
599 return value.IsNil()
600 case reflect.Array:
601 valueIsZero := true
602 for i := 0; i < value.Len(); i++ {
603 valueIsZero = valueIsZero && isZero(value.Index(i))
604 }
605 return valueIsZero
606 case reflect.Struct:
607 valueIsZero := true
608 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +0200609 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800610 }
611 return valueIsZero
612 case reflect.Ptr:
613 if !value.IsNil() {
614 return isZero(reflect.Indirect(value))
615 } else {
616 return true
617 }
Liz Kammerd366c902021-06-03 13:43:01 -0400618 // Always print bools, if you want a bool attribute to be able to take the default value, use a
619 // bool pointer instead
620 case reflect.Bool:
621 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800622 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -0400623 if !value.IsValid() {
624 return true
625 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800626 zeroValue := reflect.Zero(value.Type())
627 result := value.Interface() == zeroValue.Interface()
628 return result
629 }
630}
631
632func escapeString(s string) string {
633 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +0000634
635 // b/184026959: Reverse the application of some common control sequences.
636 // These must be generated literally in the BUILD file.
637 s = strings.ReplaceAll(s, "\t", "\\t")
638 s = strings.ReplaceAll(s, "\n", "\\n")
639 s = strings.ReplaceAll(s, "\r", "\\r")
640
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800641 return strings.ReplaceAll(s, "\"", "\\\"")
642}
643
644func makeIndent(indent int) string {
645 if indent < 0 {
646 panic(fmt.Errorf("indent column cannot be less than 0, but got %d", indent))
647 }
648 return strings.Repeat(" ", indent)
649}
650
Jingwen Chen73850672020-12-14 08:25:34 -0500651func targetNameForBp2Build(c bpToBuildContext, logicModule blueprint.Module) string {
Jingwen Chenfb4692a2021-02-07 10:05:16 -0500652 return strings.Replace(c.ModuleName(logicModule), bazel.BazelTargetModuleNamePrefix, "", 1)
Jingwen Chen73850672020-12-14 08:25:34 -0500653}
654
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800655func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
656 name := ""
657 if c.ModuleSubDir(logicModule) != "" {
658 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
659 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
660 } else {
661 name = c.ModuleName(logicModule)
662 }
663
664 return strings.Replace(name, "//", "", 1)
665}
666
667func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
668 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
669}