blob: a64d474d31d32b396a5eb7e27618120cc8b4ddab [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
17import (
18 "android/soong/android"
Liz Kammer356f7d42021-01-26 09:18:53 -050019 "android/soong/bazel"
Liz Kammer2dd9ca42020-11-25 16:06:39 -080020 "fmt"
21 "reflect"
Jingwen Chen49109762021-05-25 05:16:48 +000022 "sort"
Liz Kammer2dd9ca42020-11-25 16:06:39 -080023 "strings"
24
25 "github.com/google/blueprint"
26 "github.com/google/blueprint/proptools"
27)
28
29type BazelAttributes struct {
30 Attrs map[string]string
31}
32
33type BazelTarget struct {
Jingwen Chen40067de2021-01-26 21:58:43 -050034 name string
Jingwen Chenc63677b2021-06-17 05:43:19 +000035 packageName string
Jingwen Chen40067de2021-01-26 21:58:43 -050036 content string
37 ruleClass string
38 bzlLoadLocation string
Jingwen Chen49109762021-05-25 05:16:48 +000039 handcrafted bool
Jingwen Chen40067de2021-01-26 21:58:43 -050040}
41
42// IsLoadedFromStarlark determines if the BazelTarget's rule class is loaded from a .bzl file,
43// as opposed to a native rule built into Bazel.
44func (t BazelTarget) IsLoadedFromStarlark() bool {
45 return t.bzlLoadLocation != ""
46}
47
Jingwen Chenc63677b2021-06-17 05:43:19 +000048// Label is the fully qualified Bazel label constructed from the BazelTarget's
49// package name and target name.
50func (t BazelTarget) Label() string {
51 if t.packageName == "." {
52 return "//:" + t.name
53 } else {
54 return "//" + t.packageName + ":" + t.name
55 }
56}
57
Jingwen Chen40067de2021-01-26 21:58:43 -050058// BazelTargets is a typedef for a slice of BazelTarget objects.
59type BazelTargets []BazelTarget
60
Jingwen Chen49109762021-05-25 05:16:48 +000061// HasHandcraftedTargetsreturns true if a set of bazel targets contain
62// handcrafted ones.
63func (targets BazelTargets) hasHandcraftedTargets() bool {
64 for _, target := range targets {
65 if target.handcrafted {
66 return true
67 }
68 }
69 return false
70}
71
72// sort a list of BazelTargets in-place, by name, and by generated/handcrafted types.
73func (targets BazelTargets) sort() {
74 sort.Slice(targets, func(i, j int) bool {
75 if targets[i].handcrafted != targets[j].handcrafted {
76 // Handcrafted targets will be generated after the bp2build generated targets.
77 return targets[j].handcrafted
78 }
79 // This will cover all bp2build generated targets.
80 return targets[i].name < targets[j].name
81 })
82}
83
Jingwen Chen40067de2021-01-26 21:58:43 -050084// String returns the string representation of BazelTargets, without load
85// statements (use LoadStatements for that), since the targets are usually not
86// adjacent to the load statements at the top of the BUILD file.
87func (targets BazelTargets) String() string {
88 var res string
89 for i, target := range targets {
Jingwen Chen49109762021-05-25 05:16:48 +000090 // There is only at most 1 handcrafted "target", because its contents
91 // represent the entire BUILD file content from the tree. See
92 // build_conversion.go#getHandcraftedBuildContent for more information.
93 //
94 // Add a header to make it easy to debug where the handcrafted targets
95 // are in a generated BUILD file.
96 if target.handcrafted {
97 res += "# -----------------------------\n"
98 res += "# Section: Handcrafted targets. \n"
99 res += "# -----------------------------\n\n"
100 }
101
Jingwen Chen40067de2021-01-26 21:58:43 -0500102 res += target.content
103 if i != len(targets)-1 {
104 res += "\n\n"
105 }
106 }
107 return res
108}
109
110// LoadStatements return the string representation of the sorted and deduplicated
111// Starlark rule load statements needed by a group of BazelTargets.
112func (targets BazelTargets) LoadStatements() string {
113 bzlToLoadedSymbols := map[string][]string{}
114 for _, target := range targets {
115 if target.IsLoadedFromStarlark() {
116 bzlToLoadedSymbols[target.bzlLoadLocation] =
117 append(bzlToLoadedSymbols[target.bzlLoadLocation], target.ruleClass)
118 }
119 }
120
121 var loadStatements []string
122 for bzl, ruleClasses := range bzlToLoadedSymbols {
123 loadStatement := "load(\""
124 loadStatement += bzl
125 loadStatement += "\", "
126 ruleClasses = android.SortedUniqueStrings(ruleClasses)
127 for i, ruleClass := range ruleClasses {
128 loadStatement += "\"" + ruleClass + "\""
129 if i != len(ruleClasses)-1 {
130 loadStatement += ", "
131 }
132 }
133 loadStatement += ")"
134 loadStatements = append(loadStatements, loadStatement)
135 }
136 return strings.Join(android.SortedUniqueStrings(loadStatements), "\n")
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800137}
138
139type bpToBuildContext interface {
140 ModuleName(module blueprint.Module) string
141 ModuleDir(module blueprint.Module) string
142 ModuleSubDir(module blueprint.Module) string
143 ModuleType(module blueprint.Module) string
144
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500145 VisitAllModules(visit func(blueprint.Module))
146 VisitDirectDeps(module blueprint.Module, visit func(blueprint.Module))
147}
148
149type CodegenContext struct {
Liz Kammerba3ea162021-02-17 13:22:03 -0500150 config android.Config
151 context android.Context
152 mode CodegenMode
153 additionalDeps []string
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500154}
155
Jingwen Chen164e0862021-02-19 00:48:40 -0500156func (c *CodegenContext) Mode() CodegenMode {
157 return c.mode
158}
159
Jingwen Chen33832f92021-01-24 22:55:54 -0500160// CodegenMode is an enum to differentiate code-generation modes.
161type CodegenMode int
162
163const (
164 // Bp2Build: generate BUILD files with targets buildable by Bazel directly.
165 //
166 // This mode is used for the Soong->Bazel build definition conversion.
167 Bp2Build CodegenMode = iota
168
169 // QueryView: generate BUILD files with targets representing fully mutated
170 // Soong modules, representing the fully configured Soong module graph with
171 // variants and dependency endges.
172 //
173 // This mode is used for discovering and introspecting the existing Soong
174 // module graph.
175 QueryView
176)
177
Jingwen Chendcc329a2021-01-26 02:49:03 -0500178func (mode CodegenMode) String() string {
179 switch mode {
180 case Bp2Build:
181 return "Bp2Build"
182 case QueryView:
183 return "QueryView"
184 default:
185 return fmt.Sprintf("%d", mode)
186 }
187}
188
Liz Kammerba3ea162021-02-17 13:22:03 -0500189// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
190// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
191// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
192// call AdditionalNinjaDeps and add them manually to the ninja file.
193func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
194 ctx.additionalDeps = append(ctx.additionalDeps, deps...)
195}
196
197// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
198func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
199 return ctx.additionalDeps
200}
201
202func (ctx *CodegenContext) Config() android.Config { return ctx.config }
203func (ctx *CodegenContext) Context() android.Context { return ctx.context }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500204
205// NewCodegenContext creates a wrapper context that conforms to PathContext for
206// writing BUILD files in the output directory.
Liz Kammerba3ea162021-02-17 13:22:03 -0500207func NewCodegenContext(config android.Config, context android.Context, mode CodegenMode) *CodegenContext {
208 return &CodegenContext{
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500209 context: context,
210 config: config,
Jingwen Chen33832f92021-01-24 22:55:54 -0500211 mode: mode,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500212 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800213}
214
215// props is an unsorted map. This function ensures that
216// the generated attributes are sorted to ensure determinism.
217func propsToAttributes(props map[string]string) string {
218 var attributes string
219 for _, propName := range android.SortedStringKeys(props) {
220 if shouldGenerateAttribute(propName) {
221 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
222 }
223 }
224 return attributes
225}
226
Jingwen Chenc63677b2021-06-17 05:43:19 +0000227func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (map[string]BazelTargets, CodegenMetrics, CodegenCompatLayer) {
Jingwen Chen40067de2021-01-26 21:58:43 -0500228 buildFileToTargets := make(map[string]BazelTargets)
Liz Kammerba3ea162021-02-17 13:22:03 -0500229 buildFileToAppend := make(map[string]bool)
Jingwen Chen164e0862021-02-19 00:48:40 -0500230
231 // Simple metrics tracking for bp2build
Liz Kammerba3ea162021-02-17 13:22:03 -0500232 metrics := CodegenMetrics{
233 RuleClassCount: make(map[string]int),
234 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500235
Jingwen Chenc63677b2021-06-17 05:43:19 +0000236 compatLayer := CodegenCompatLayer{
237 NameToLabelMap: make(map[string]string),
238 }
239
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400240 dirs := make(map[string]bool)
241
Jingwen Chen164e0862021-02-19 00:48:40 -0500242 bpCtx := ctx.Context()
243 bpCtx.VisitAllModules(func(m blueprint.Module) {
244 dir := bpCtx.ModuleDir(m)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400245 dirs[dir] = true
246
Liz Kammer2ada09a2021-08-11 00:17:36 -0400247 var targets []BazelTarget
Jingwen Chen73850672020-12-14 08:25:34 -0500248
Jingwen Chen164e0862021-02-19 00:48:40 -0500249 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500250 case Bp2Build:
Liz Kammerba3ea162021-02-17 13:22:03 -0500251 if b, ok := m.(android.Bazelable); ok && b.HasHandcraftedLabel() {
252 metrics.handCraftedTargetCount += 1
253 metrics.TotalModuleCount += 1
Jingwen Chenc63677b2021-06-17 05:43:19 +0000254 compatLayer.AddNameToLabelEntry(m.Name(), b.HandcraftedLabel())
Liz Kammerba3ea162021-02-17 13:22:03 -0500255 pathToBuildFile := getBazelPackagePath(b)
256 // We are using the entire contents of handcrafted build file, so if multiple targets within
257 // a package have handcrafted targets, we only want to include the contents one time.
258 if _, exists := buildFileToAppend[pathToBuildFile]; exists {
259 return
260 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400261 t, err := getHandcraftedBuildContent(ctx, b, pathToBuildFile)
Liz Kammerba3ea162021-02-17 13:22:03 -0500262 if err != nil {
263 panic(fmt.Errorf("Error converting %s: %s", bpCtx.ModuleName(m), err))
264 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400265 targets = append(targets, t)
Liz Kammerba3ea162021-02-17 13:22:03 -0500266 // TODO(b/181575318): currently we append the whole BUILD file, let's change that to do
267 // something more targeted based on the rule type and target
268 buildFileToAppend[pathToBuildFile] = true
Liz Kammer2ada09a2021-08-11 00:17:36 -0400269 } else if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
270 targets = generateBazelTargets(bpCtx, aModule)
271 for _, t := range targets {
272 if t.name == m.Name() {
273 // only add targets that exist in Soong to compatibility layer
274 compatLayer.AddNameToLabelEntry(m.Name(), t.Label())
275 }
276 metrics.RuleClassCount[t.ruleClass] += 1
277 }
Liz Kammerfc46bc12021-02-19 11:06:17 -0500278 } else {
Liz Kammerba3ea162021-02-17 13:22:03 -0500279 metrics.TotalModuleCount += 1
280 return
Jingwen Chen73850672020-12-14 08:25:34 -0500281 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500282 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500283 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500284 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500285 // package module name contain slashes, and thus cannot
286 // be mapped cleanly to a bazel label.
287 return
288 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400289 t := generateSoongModuleTarget(bpCtx, m)
290 targets = append(targets, t)
Jingwen Chen33832f92021-01-24 22:55:54 -0500291 default:
Jingwen Chen164e0862021-02-19 00:48:40 -0500292 panic(fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
Jingwen Chen73850672020-12-14 08:25:34 -0500293 }
294
Liz Kammer2ada09a2021-08-11 00:17:36 -0400295 buildFileToTargets[dir] = append(buildFileToTargets[dir], targets...)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800296 })
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400297 if generateFilegroups {
298 // Add a filegroup target that exposes all sources in the subtree of this package
299 // NOTE: This also means we generate a BUILD file for every Android.bp file (as long as it has at least one module)
300 for dir, _ := range dirs {
301 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
302 name: "bp2build_all_srcs",
303 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]))`,
304 ruleClass: "filegroup",
305 })
306 }
307 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500308
Jingwen Chenc63677b2021-06-17 05:43:19 +0000309 return buildFileToTargets, metrics, compatLayer
Jingwen Chen164e0862021-02-19 00:48:40 -0500310}
311
Liz Kammerba3ea162021-02-17 13:22:03 -0500312func getBazelPackagePath(b android.Bazelable) string {
Liz Kammerbdc60992021-02-24 16:55:11 -0500313 label := b.HandcraftedLabel()
Liz Kammerba3ea162021-02-17 13:22:03 -0500314 pathToBuildFile := strings.TrimPrefix(label, "//")
315 pathToBuildFile = strings.Split(pathToBuildFile, ":")[0]
316 return pathToBuildFile
317}
318
319func getHandcraftedBuildContent(ctx *CodegenContext, b android.Bazelable, pathToBuildFile string) (BazelTarget, error) {
320 p := android.ExistentPathForSource(ctx, pathToBuildFile, HandcraftedBuildFileName)
321 if !p.Valid() {
322 return BazelTarget{}, fmt.Errorf("Could not find file %q for handcrafted target.", pathToBuildFile)
323 }
324 c, err := b.GetBazelBuildFileContents(ctx.Config(), pathToBuildFile, HandcraftedBuildFileName)
325 if err != nil {
326 return BazelTarget{}, err
327 }
328 // TODO(b/181575318): once this is more targeted, we need to include name, rule class, etc
329 return BazelTarget{
Jingwen Chen49109762021-05-25 05:16:48 +0000330 content: c,
331 handcrafted: true,
Liz Kammerba3ea162021-02-17 13:22:03 -0500332 }, nil
333}
334
Liz Kammer2ada09a2021-08-11 00:17:36 -0400335func generateBazelTargets(ctx bpToBuildContext, m android.Module) []BazelTarget {
336 var targets []BazelTarget
337 for _, m := range m.Bp2buildTargets() {
338 targets = append(targets, generateBazelTarget(ctx, m))
339 }
340 return targets
341}
342
343type bp2buildModule interface {
344 TargetName() string
345 TargetPackage() string
346 BazelRuleClass() string
347 BazelRuleLoadLocation() string
348 BazelAttributes() interface{}
349}
350
351func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) BazelTarget {
352 ruleClass := m.BazelRuleClass()
353 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500354
Jingwen Chen73850672020-12-14 08:25:34 -0500355 // extract the bazel attributes from the module.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400356 props := extractModuleProperties([]interface{}{m.BazelAttributes()})
Jingwen Chen73850672020-12-14 08:25:34 -0500357
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500358 delete(props.Attrs, "bp2build_available")
359
Jingwen Chen73850672020-12-14 08:25:34 -0500360 // Return the Bazel target with rule class and attributes, ready to be
361 // code-generated.
362 attributes := propsToAttributes(props.Attrs)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400363 targetName := m.TargetName()
Jingwen Chen73850672020-12-14 08:25:34 -0500364 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500365 name: targetName,
Liz Kammer2ada09a2021-08-11 00:17:36 -0400366 packageName: m.TargetPackage(),
Jingwen Chen40067de2021-01-26 21:58:43 -0500367 ruleClass: ruleClass,
368 bzlLoadLocation: bzlLoadLocation,
Jingwen Chen73850672020-12-14 08:25:34 -0500369 content: fmt.Sprintf(
370 bazelTarget,
371 ruleClass,
372 targetName,
373 attributes,
374 ),
Jingwen Chen49109762021-05-25 05:16:48 +0000375 handcrafted: false,
Jingwen Chen73850672020-12-14 08:25:34 -0500376 }
377}
378
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800379// Convert a module and its deps and props into a Bazel macro/rule
380// representation in the BUILD file.
381func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) BazelTarget {
382 props := getBuildProperties(ctx, m)
383
384 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
385 // items, if the modules are added using different DependencyTag. Figure
386 // out the implications of that.
387 depLabels := map[string]bool{}
388 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500389 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800390 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
391 })
392 }
393 attributes := propsToAttributes(props.Attrs)
394
395 depLabelList := "[\n"
396 for depLabel, _ := range depLabels {
397 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
398 }
399 depLabelList += " ]"
400
401 targetName := targetNameWithVariant(ctx, m)
402 return BazelTarget{
403 name: targetName,
404 content: fmt.Sprintf(
405 soongModuleTarget,
406 targetName,
407 ctx.ModuleName(m),
408 canonicalizeModuleType(ctx.ModuleType(m)),
409 ctx.ModuleSubDir(m),
410 depLabelList,
411 attributes),
412 }
413}
414
415func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) BazelAttributes {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800416 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
417 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
418 if aModule, ok := m.(android.Module); ok {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400419 return extractModuleProperties(aModule.GetProperties())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800420 }
421
Liz Kammer2ada09a2021-08-11 00:17:36 -0400422 return BazelAttributes{}
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800423}
424
425// Generically extract module properties and types into a map, keyed by the module property name.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400426func extractModuleProperties(props []interface{}) BazelAttributes {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800427 ret := map[string]string{}
428
429 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400430 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800431 propertiesValue := reflect.ValueOf(properties)
432 // Check that propertiesValue is a pointer to the Properties struct, like
433 // *cc.BaseLinkerProperties or *java.CompilerProperties.
434 //
435 // propertiesValue can also be type-asserted to the structs to
436 // manipulate internal props, if needed.
437 if isStructPtr(propertiesValue.Type()) {
438 structValue := propertiesValue.Elem()
439 for k, v := range extractStructProperties(structValue, 0) {
440 ret[k] = v
441 }
442 } else {
443 panic(fmt.Errorf(
444 "properties must be a pointer to a struct, got %T",
445 propertiesValue.Interface()))
446 }
447 }
448
Liz Kammer2ada09a2021-08-11 00:17:36 -0400449 return BazelAttributes{
450 Attrs: ret,
451 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800452}
453
454func isStructPtr(t reflect.Type) bool {
455 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
456}
457
458// prettyPrint a property value into the equivalent Starlark representation
459// recursively.
460func prettyPrint(propertyValue reflect.Value, indent int) (string, error) {
461 if isZero(propertyValue) {
462 // A property value being set or unset actually matters -- Soong does set default
463 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
464 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
465 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +0000466 // In Bazel-parlance, we would use "attr.<type>(default = <default
467 // value>)" to set the default value of unset attributes. In the cases
468 // where the bp2build converter didn't set the default value within the
469 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -0400470 // value. For those cases, we return an empty string so we don't
471 // unnecessarily generate empty values.
472 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800473 }
474
475 var ret string
476 switch propertyValue.Kind() {
477 case reflect.String:
478 ret = fmt.Sprintf("\"%v\"", escapeString(propertyValue.String()))
479 case reflect.Bool:
480 ret = strings.Title(fmt.Sprintf("%v", propertyValue.Interface()))
481 case reflect.Int, reflect.Uint, reflect.Int64:
482 ret = fmt.Sprintf("%v", propertyValue.Interface())
483 case reflect.Ptr:
484 return prettyPrint(propertyValue.Elem(), indent)
485 case reflect.Slice:
Jingwen Chen63930982021-03-24 10:04:33 -0400486 if propertyValue.Len() == 0 {
Liz Kammer2b07ec72021-05-26 15:08:27 -0400487 return "[]", nil
Jingwen Chen63930982021-03-24 10:04:33 -0400488 }
489
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000490 if propertyValue.Len() == 1 {
491 // Single-line list for list with only 1 element
492 ret += "["
493 indexedValue, err := prettyPrint(propertyValue.Index(0), indent)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800494 if err != nil {
495 return "", err
496 }
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000497 ret += indexedValue
498 ret += "]"
499 } else {
500 // otherwise, use a multiline list.
501 ret += "[\n"
502 for i := 0; i < propertyValue.Len(); i++ {
503 indexedValue, err := prettyPrint(propertyValue.Index(i), indent+1)
504 if err != nil {
505 return "", err
506 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800507
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000508 if indexedValue != "" {
509 ret += makeIndent(indent + 1)
510 ret += indexedValue
511 ret += ",\n"
512 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800513 }
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000514 ret += makeIndent(indent)
515 ret += "]"
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800516 }
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000517
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800518 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -0500519 // Special cases where the bp2build sends additional information to the codegenerator
520 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +0000521 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
522 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -0500523 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
524 return fmt.Sprintf("%q", label.Label), nil
525 }
526
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800527 ret = "{\n"
528 // Sort and print the struct props by the key.
529 structProps := extractStructProperties(propertyValue, indent)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000530 if len(structProps) == 0 {
531 return "", nil
532 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800533 for _, k := range android.SortedStringKeys(structProps) {
534 ret += makeIndent(indent + 1)
535 ret += fmt.Sprintf("%q: %s,\n", k, structProps[k])
536 }
537 ret += makeIndent(indent)
538 ret += "}"
539 case reflect.Interface:
540 // TODO(b/164227191): implement pretty print for interfaces.
541 // Interfaces are used for for arch, multilib and target properties.
542 return "", nil
543 default:
544 return "", fmt.Errorf(
545 "unexpected kind for property struct field: %s", propertyValue.Kind())
546 }
547 return ret, nil
548}
549
550// Converts a reflected property struct value into a map of property names and property values,
551// which each property value correctly pretty-printed and indented at the right nest level,
552// since property structs can be nested. In Starlark, nested structs are represented as nested
553// dicts: https://docs.bazel.build/skylark/lib/dict.html
554func extractStructProperties(structValue reflect.Value, indent int) map[string]string {
555 if structValue.Kind() != reflect.Struct {
556 panic(fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind()))
557 }
558
559 ret := map[string]string{}
560 structType := structValue.Type()
561 for i := 0; i < structValue.NumField(); i++ {
562 field := structType.Field(i)
563 if shouldSkipStructField(field) {
564 continue
565 }
566
567 fieldValue := structValue.Field(i)
568 if isZero(fieldValue) {
569 // Ignore zero-valued fields
570 continue
571 }
572
573 propertyName := proptools.PropertyNameForField(field.Name)
574 prettyPrintedValue, err := prettyPrint(fieldValue, indent+1)
575 if err != nil {
576 panic(
577 fmt.Errorf(
578 "Error while parsing property: %q. %s",
579 propertyName,
580 err))
581 }
582 if prettyPrintedValue != "" {
583 ret[propertyName] = prettyPrintedValue
584 }
585 }
586
587 return ret
588}
589
590func isZero(value reflect.Value) bool {
591 switch value.Kind() {
592 case reflect.Func, reflect.Map, reflect.Slice:
593 return value.IsNil()
594 case reflect.Array:
595 valueIsZero := true
596 for i := 0; i < value.Len(); i++ {
597 valueIsZero = valueIsZero && isZero(value.Index(i))
598 }
599 return valueIsZero
600 case reflect.Struct:
601 valueIsZero := true
602 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +0200603 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800604 }
605 return valueIsZero
606 case reflect.Ptr:
607 if !value.IsNil() {
608 return isZero(reflect.Indirect(value))
609 } else {
610 return true
611 }
Liz Kammerd366c902021-06-03 13:43:01 -0400612 // Always print bools, if you want a bool attribute to be able to take the default value, use a
613 // bool pointer instead
614 case reflect.Bool:
615 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800616 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -0400617 if !value.IsValid() {
618 return true
619 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800620 zeroValue := reflect.Zero(value.Type())
621 result := value.Interface() == zeroValue.Interface()
622 return result
623 }
624}
625
626func escapeString(s string) string {
627 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +0000628
629 // b/184026959: Reverse the application of some common control sequences.
630 // These must be generated literally in the BUILD file.
631 s = strings.ReplaceAll(s, "\t", "\\t")
632 s = strings.ReplaceAll(s, "\n", "\\n")
633 s = strings.ReplaceAll(s, "\r", "\\r")
634
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800635 return strings.ReplaceAll(s, "\"", "\\\"")
636}
637
638func makeIndent(indent int) string {
639 if indent < 0 {
640 panic(fmt.Errorf("indent column cannot be less than 0, but got %d", indent))
641 }
642 return strings.Repeat(" ", indent)
643}
644
Jingwen Chen73850672020-12-14 08:25:34 -0500645func targetNameForBp2Build(c bpToBuildContext, logicModule blueprint.Module) string {
Jingwen Chenfb4692a2021-02-07 10:05:16 -0500646 return strings.Replace(c.ModuleName(logicModule), bazel.BazelTargetModuleNamePrefix, "", 1)
Jingwen Chen73850672020-12-14 08:25:34 -0500647}
648
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800649func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
650 name := ""
651 if c.ModuleSubDir(logicModule) != "" {
652 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
653 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
654 } else {
655 name = c.ModuleName(logicModule)
656 }
657
658 return strings.Replace(name, "//", "", 1)
659}
660
661func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
662 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
663}