blob: 4a0eeea5169004f3009fbedec047c64ce1ff886b [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 {
Jingwen Chen16d90a82021-09-17 07:16:13 +0000156 config android.Config
157 context android.Context
158 mode CodegenMode
159 additionalDeps []string
Liz Kammer6eff3232021-08-26 08:37:59 -0400160 unconvertedDepMode unconvertedDepsMode
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500161}
162
Jingwen Chen164e0862021-02-19 00:48:40 -0500163func (c *CodegenContext) Mode() CodegenMode {
164 return c.mode
165}
166
Jingwen Chen33832f92021-01-24 22:55:54 -0500167// CodegenMode is an enum to differentiate code-generation modes.
168type CodegenMode int
169
170const (
171 // Bp2Build: generate BUILD files with targets buildable by Bazel directly.
172 //
173 // This mode is used for the Soong->Bazel build definition conversion.
174 Bp2Build CodegenMode = iota
175
176 // QueryView: generate BUILD files with targets representing fully mutated
177 // Soong modules, representing the fully configured Soong module graph with
178 // variants and dependency endges.
179 //
180 // This mode is used for discovering and introspecting the existing Soong
181 // module graph.
182 QueryView
183)
184
Liz Kammer6eff3232021-08-26 08:37:59 -0400185type unconvertedDepsMode int
186
187const (
188 // Include a warning in conversion metrics about converted modules with unconverted direct deps
189 warnUnconvertedDeps unconvertedDepsMode = iota
190 // Error and fail conversion if encountering a module with unconverted direct deps
191 // Enabled by setting environment variable `BP2BUILD_ERROR_UNCONVERTED`
192 errorModulesUnconvertedDeps
193)
194
Jingwen Chendcc329a2021-01-26 02:49:03 -0500195func (mode CodegenMode) String() string {
196 switch mode {
197 case Bp2Build:
198 return "Bp2Build"
199 case QueryView:
200 return "QueryView"
201 default:
202 return fmt.Sprintf("%d", mode)
203 }
204}
205
Liz Kammerba3ea162021-02-17 13:22:03 -0500206// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
207// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
208// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
209// call AdditionalNinjaDeps and add them manually to the ninja file.
210func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
211 ctx.additionalDeps = append(ctx.additionalDeps, deps...)
212}
213
214// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
215func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
216 return ctx.additionalDeps
217}
218
219func (ctx *CodegenContext) Config() android.Config { return ctx.config }
220func (ctx *CodegenContext) Context() android.Context { return ctx.context }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500221
222// NewCodegenContext creates a wrapper context that conforms to PathContext for
223// writing BUILD files in the output directory.
Liz Kammerba3ea162021-02-17 13:22:03 -0500224func NewCodegenContext(config android.Config, context android.Context, mode CodegenMode) *CodegenContext {
Liz Kammer6eff3232021-08-26 08:37:59 -0400225 var unconvertedDeps unconvertedDepsMode
226 if config.IsEnvTrue("BP2BUILD_ERROR_UNCONVERTED") {
227 unconvertedDeps = errorModulesUnconvertedDeps
228 }
Liz Kammerba3ea162021-02-17 13:22:03 -0500229 return &CodegenContext{
Liz Kammer6eff3232021-08-26 08:37:59 -0400230 context: context,
231 config: config,
232 mode: mode,
233 unconvertedDepMode: unconvertedDeps,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500234 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800235}
236
237// props is an unsorted map. This function ensures that
238// the generated attributes are sorted to ensure determinism.
239func propsToAttributes(props map[string]string) string {
240 var attributes string
241 for _, propName := range android.SortedStringKeys(props) {
242 if shouldGenerateAttribute(propName) {
243 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
244 }
245 }
246 return attributes
247}
248
Liz Kammer6eff3232021-08-26 08:37:59 -0400249type conversionResults struct {
250 buildFileToTargets map[string]BazelTargets
251 metrics CodegenMetrics
Liz Kammer6eff3232021-08-26 08:37:59 -0400252}
253
254func (r conversionResults) BuildDirToTargets() map[string]BazelTargets {
255 return r.buildFileToTargets
256}
257
258func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (conversionResults, []error) {
Jingwen Chen40067de2021-01-26 21:58:43 -0500259 buildFileToTargets := make(map[string]BazelTargets)
Liz Kammerba3ea162021-02-17 13:22:03 -0500260 buildFileToAppend := make(map[string]bool)
Jingwen Chen164e0862021-02-19 00:48:40 -0500261
262 // Simple metrics tracking for bp2build
Liz Kammerba3ea162021-02-17 13:22:03 -0500263 metrics := CodegenMetrics{
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000264 ruleClassCount: make(map[string]int),
Liz Kammerba3ea162021-02-17 13:22:03 -0500265 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500266
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400267 dirs := make(map[string]bool)
268
Liz Kammer6eff3232021-08-26 08:37:59 -0400269 var errs []error
270
Jingwen Chen164e0862021-02-19 00:48:40 -0500271 bpCtx := ctx.Context()
272 bpCtx.VisitAllModules(func(m blueprint.Module) {
273 dir := bpCtx.ModuleDir(m)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400274 dirs[dir] = true
275
Liz Kammer2ada09a2021-08-11 00:17:36 -0400276 var targets []BazelTarget
Jingwen Chen73850672020-12-14 08:25:34 -0500277
Jingwen Chen164e0862021-02-19 00:48:40 -0500278 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500279 case Bp2Build:
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000280 // There are two main ways of converting a Soong module to Bazel:
281 // 1) Manually handcrafting a Bazel target and associating the module with its label
282 // 2) Automatically generating with bp2build converters
283 //
284 // bp2build converters are used for the majority of modules.
Liz Kammerba3ea162021-02-17 13:22:03 -0500285 if b, ok := m.(android.Bazelable); ok && b.HasHandcraftedLabel() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000286 // Handle modules converted to handcrafted targets.
287 //
288 // Since these modules are associated with some handcrafted
289 // target in a BUILD file, we simply append the entire contents
290 // of that BUILD file to the generated BUILD file.
291 //
292 // The append operation is only done once, even if there are
293 // multiple modules from the same directory associated to
294 // targets in the same BUILD file (or package).
295
296 // Log the module.
297 metrics.AddConvertedModule(m.Name(), Handcrafted)
298
Liz Kammerba3ea162021-02-17 13:22:03 -0500299 pathToBuildFile := getBazelPackagePath(b)
Liz Kammerba3ea162021-02-17 13:22:03 -0500300 if _, exists := buildFileToAppend[pathToBuildFile]; exists {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000301 // Append the BUILD file content once per package, at most.
Liz Kammerba3ea162021-02-17 13:22:03 -0500302 return
303 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400304 t, err := getHandcraftedBuildContent(ctx, b, pathToBuildFile)
Liz Kammerba3ea162021-02-17 13:22:03 -0500305 if err != nil {
Liz Kammer6eff3232021-08-26 08:37:59 -0400306 errs = append(errs, fmt.Errorf("Error converting %s: %s", bpCtx.ModuleName(m), err))
307 return
Liz Kammerba3ea162021-02-17 13:22:03 -0500308 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400309 targets = append(targets, t)
Liz Kammerba3ea162021-02-17 13:22:03 -0500310 // TODO(b/181575318): currently we append the whole BUILD file, let's change that to do
311 // something more targeted based on the rule type and target
312 buildFileToAppend[pathToBuildFile] = true
Liz Kammer2ada09a2021-08-11 00:17:36 -0400313 } else if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000314 // Handle modules converted to generated targets.
315
316 // Log the module.
317 metrics.AddConvertedModule(m.Name(), Generated)
318
319 // Handle modules with unconverted deps. By default, emit a warning.
Liz Kammer6eff3232021-08-26 08:37:59 -0400320 if unconvertedDeps := aModule.GetUnconvertedBp2buildDeps(); len(unconvertedDeps) > 0 {
321 msg := fmt.Sprintf("%q depends on unconverted modules: %s", m.Name(), strings.Join(unconvertedDeps, ", "))
322 if ctx.unconvertedDepMode == warnUnconvertedDeps {
323 metrics.moduleWithUnconvertedDepsMsgs = append(metrics.moduleWithUnconvertedDepsMsgs, msg)
324 } else if ctx.unconvertedDepMode == errorModulesUnconvertedDeps {
Liz Kammer6eff3232021-08-26 08:37:59 -0400325 errs = append(errs, fmt.Errorf(msg))
326 return
327 }
328 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400329 targets = generateBazelTargets(bpCtx, aModule)
330 for _, t := range targets {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000331 // A module can potentially generate more than 1 Bazel
332 // target, each of a different rule class.
333 metrics.IncrementRuleClassCount(t.ruleClass)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400334 }
Liz Kammerfc46bc12021-02-19 11:06:17 -0500335 } else {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000336 metrics.IncrementUnconvertedCount()
Liz Kammerba3ea162021-02-17 13:22:03 -0500337 return
Jingwen Chen73850672020-12-14 08:25:34 -0500338 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500339 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500340 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500341 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500342 // package module name contain slashes, and thus cannot
343 // be mapped cleanly to a bazel label.
344 return
345 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400346 t := generateSoongModuleTarget(bpCtx, m)
347 targets = append(targets, t)
Jingwen Chen33832f92021-01-24 22:55:54 -0500348 default:
Liz Kammer6eff3232021-08-26 08:37:59 -0400349 errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
350 return
Jingwen Chen73850672020-12-14 08:25:34 -0500351 }
352
Liz Kammer2ada09a2021-08-11 00:17:36 -0400353 buildFileToTargets[dir] = append(buildFileToTargets[dir], targets...)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800354 })
Liz Kammer6eff3232021-08-26 08:37:59 -0400355
356 if len(errs) > 0 {
357 return conversionResults{}, errs
358 }
359
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400360 if generateFilegroups {
361 // Add a filegroup target that exposes all sources in the subtree of this package
362 // NOTE: This also means we generate a BUILD file for every Android.bp file (as long as it has at least one module)
363 for dir, _ := range dirs {
364 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
365 name: "bp2build_all_srcs",
366 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]))`,
367 ruleClass: "filegroup",
368 })
369 }
370 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500371
Liz Kammer6eff3232021-08-26 08:37:59 -0400372 return conversionResults{
373 buildFileToTargets: buildFileToTargets,
374 metrics: metrics,
Liz Kammer6eff3232021-08-26 08:37:59 -0400375 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500376}
377
Liz Kammerba3ea162021-02-17 13:22:03 -0500378func getBazelPackagePath(b android.Bazelable) string {
Liz Kammerbdc60992021-02-24 16:55:11 -0500379 label := b.HandcraftedLabel()
Liz Kammerba3ea162021-02-17 13:22:03 -0500380 pathToBuildFile := strings.TrimPrefix(label, "//")
381 pathToBuildFile = strings.Split(pathToBuildFile, ":")[0]
382 return pathToBuildFile
383}
384
385func getHandcraftedBuildContent(ctx *CodegenContext, b android.Bazelable, pathToBuildFile string) (BazelTarget, error) {
386 p := android.ExistentPathForSource(ctx, pathToBuildFile, HandcraftedBuildFileName)
387 if !p.Valid() {
388 return BazelTarget{}, fmt.Errorf("Could not find file %q for handcrafted target.", pathToBuildFile)
389 }
390 c, err := b.GetBazelBuildFileContents(ctx.Config(), pathToBuildFile, HandcraftedBuildFileName)
391 if err != nil {
392 return BazelTarget{}, err
393 }
394 // TODO(b/181575318): once this is more targeted, we need to include name, rule class, etc
395 return BazelTarget{
Jingwen Chen49109762021-05-25 05:16:48 +0000396 content: c,
397 handcrafted: true,
Liz Kammerba3ea162021-02-17 13:22:03 -0500398 }, nil
399}
400
Liz Kammer2ada09a2021-08-11 00:17:36 -0400401func generateBazelTargets(ctx bpToBuildContext, m android.Module) []BazelTarget {
402 var targets []BazelTarget
403 for _, m := range m.Bp2buildTargets() {
404 targets = append(targets, generateBazelTarget(ctx, m))
405 }
406 return targets
407}
408
409type bp2buildModule interface {
410 TargetName() string
411 TargetPackage() string
412 BazelRuleClass() string
413 BazelRuleLoadLocation() string
414 BazelAttributes() interface{}
415}
416
417func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) BazelTarget {
418 ruleClass := m.BazelRuleClass()
419 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500420
Jingwen Chen73850672020-12-14 08:25:34 -0500421 // extract the bazel attributes from the module.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400422 props := extractModuleProperties([]interface{}{m.BazelAttributes()})
Jingwen Chen73850672020-12-14 08:25:34 -0500423
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500424 delete(props.Attrs, "bp2build_available")
425
Jingwen Chen73850672020-12-14 08:25:34 -0500426 // Return the Bazel target with rule class and attributes, ready to be
427 // code-generated.
428 attributes := propsToAttributes(props.Attrs)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400429 targetName := m.TargetName()
Jingwen Chen73850672020-12-14 08:25:34 -0500430 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500431 name: targetName,
Liz Kammer2ada09a2021-08-11 00:17:36 -0400432 packageName: m.TargetPackage(),
Jingwen Chen40067de2021-01-26 21:58:43 -0500433 ruleClass: ruleClass,
434 bzlLoadLocation: bzlLoadLocation,
Jingwen Chen73850672020-12-14 08:25:34 -0500435 content: fmt.Sprintf(
436 bazelTarget,
437 ruleClass,
438 targetName,
439 attributes,
440 ),
Jingwen Chen49109762021-05-25 05:16:48 +0000441 handcrafted: false,
Jingwen Chen73850672020-12-14 08:25:34 -0500442 }
443}
444
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800445// Convert a module and its deps and props into a Bazel macro/rule
446// representation in the BUILD file.
447func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) BazelTarget {
448 props := getBuildProperties(ctx, m)
449
450 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
451 // items, if the modules are added using different DependencyTag. Figure
452 // out the implications of that.
453 depLabels := map[string]bool{}
454 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500455 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800456 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
457 })
458 }
459 attributes := propsToAttributes(props.Attrs)
460
461 depLabelList := "[\n"
462 for depLabel, _ := range depLabels {
463 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
464 }
465 depLabelList += " ]"
466
467 targetName := targetNameWithVariant(ctx, m)
468 return BazelTarget{
469 name: targetName,
470 content: fmt.Sprintf(
471 soongModuleTarget,
472 targetName,
473 ctx.ModuleName(m),
474 canonicalizeModuleType(ctx.ModuleType(m)),
475 ctx.ModuleSubDir(m),
476 depLabelList,
477 attributes),
478 }
479}
480
481func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) BazelAttributes {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800482 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
483 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
484 if aModule, ok := m.(android.Module); ok {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400485 return extractModuleProperties(aModule.GetProperties())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800486 }
487
Liz Kammer2ada09a2021-08-11 00:17:36 -0400488 return BazelAttributes{}
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800489}
490
491// Generically extract module properties and types into a map, keyed by the module property name.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400492func extractModuleProperties(props []interface{}) BazelAttributes {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800493 ret := map[string]string{}
494
495 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400496 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800497 propertiesValue := reflect.ValueOf(properties)
498 // Check that propertiesValue is a pointer to the Properties struct, like
499 // *cc.BaseLinkerProperties or *java.CompilerProperties.
500 //
501 // propertiesValue can also be type-asserted to the structs to
502 // manipulate internal props, if needed.
503 if isStructPtr(propertiesValue.Type()) {
504 structValue := propertiesValue.Elem()
505 for k, v := range extractStructProperties(structValue, 0) {
506 ret[k] = v
507 }
508 } else {
509 panic(fmt.Errorf(
510 "properties must be a pointer to a struct, got %T",
511 propertiesValue.Interface()))
512 }
513 }
514
Liz Kammer2ada09a2021-08-11 00:17:36 -0400515 return BazelAttributes{
516 Attrs: ret,
517 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800518}
519
520func isStructPtr(t reflect.Type) bool {
521 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
522}
523
524// prettyPrint a property value into the equivalent Starlark representation
525// recursively.
526func prettyPrint(propertyValue reflect.Value, indent int) (string, error) {
527 if isZero(propertyValue) {
528 // A property value being set or unset actually matters -- Soong does set default
529 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
530 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
531 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +0000532 // In Bazel-parlance, we would use "attr.<type>(default = <default
533 // value>)" to set the default value of unset attributes. In the cases
534 // where the bp2build converter didn't set the default value within the
535 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -0400536 // value. For those cases, we return an empty string so we don't
537 // unnecessarily generate empty values.
538 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800539 }
540
541 var ret string
542 switch propertyValue.Kind() {
543 case reflect.String:
544 ret = fmt.Sprintf("\"%v\"", escapeString(propertyValue.String()))
545 case reflect.Bool:
546 ret = strings.Title(fmt.Sprintf("%v", propertyValue.Interface()))
547 case reflect.Int, reflect.Uint, reflect.Int64:
548 ret = fmt.Sprintf("%v", propertyValue.Interface())
549 case reflect.Ptr:
550 return prettyPrint(propertyValue.Elem(), indent)
551 case reflect.Slice:
Jingwen Chen63930982021-03-24 10:04:33 -0400552 if propertyValue.Len() == 0 {
Liz Kammer2b07ec72021-05-26 15:08:27 -0400553 return "[]", nil
Jingwen Chen63930982021-03-24 10:04:33 -0400554 }
555
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000556 if propertyValue.Len() == 1 {
557 // Single-line list for list with only 1 element
558 ret += "["
559 indexedValue, err := prettyPrint(propertyValue.Index(0), indent)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800560 if err != nil {
561 return "", err
562 }
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000563 ret += indexedValue
564 ret += "]"
565 } else {
566 // otherwise, use a multiline list.
567 ret += "[\n"
568 for i := 0; i < propertyValue.Len(); i++ {
569 indexedValue, err := prettyPrint(propertyValue.Index(i), indent+1)
570 if err != nil {
571 return "", err
572 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800573
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000574 if indexedValue != "" {
575 ret += makeIndent(indent + 1)
576 ret += indexedValue
577 ret += ",\n"
578 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800579 }
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000580 ret += makeIndent(indent)
581 ret += "]"
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800582 }
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000583
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800584 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -0500585 // Special cases where the bp2build sends additional information to the codegenerator
586 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +0000587 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
588 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -0500589 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
590 return fmt.Sprintf("%q", label.Label), nil
591 }
592
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800593 ret = "{\n"
594 // Sort and print the struct props by the key.
595 structProps := extractStructProperties(propertyValue, indent)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000596 if len(structProps) == 0 {
597 return "", nil
598 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800599 for _, k := range android.SortedStringKeys(structProps) {
600 ret += makeIndent(indent + 1)
601 ret += fmt.Sprintf("%q: %s,\n", k, structProps[k])
602 }
603 ret += makeIndent(indent)
604 ret += "}"
605 case reflect.Interface:
606 // TODO(b/164227191): implement pretty print for interfaces.
607 // Interfaces are used for for arch, multilib and target properties.
608 return "", nil
609 default:
610 return "", fmt.Errorf(
611 "unexpected kind for property struct field: %s", propertyValue.Kind())
612 }
613 return ret, nil
614}
615
616// Converts a reflected property struct value into a map of property names and property values,
617// which each property value correctly pretty-printed and indented at the right nest level,
618// since property structs can be nested. In Starlark, nested structs are represented as nested
619// dicts: https://docs.bazel.build/skylark/lib/dict.html
620func extractStructProperties(structValue reflect.Value, indent int) map[string]string {
621 if structValue.Kind() != reflect.Struct {
622 panic(fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind()))
623 }
624
625 ret := map[string]string{}
626 structType := structValue.Type()
627 for i := 0; i < structValue.NumField(); i++ {
628 field := structType.Field(i)
629 if shouldSkipStructField(field) {
630 continue
631 }
632
633 fieldValue := structValue.Field(i)
634 if isZero(fieldValue) {
635 // Ignore zero-valued fields
636 continue
637 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400638
Liz Kammer32a03392021-09-14 11:17:21 -0400639 // if the struct is embedded (anonymous), flatten the properties into the containing struct
640 if field.Anonymous {
641 if field.Type.Kind() == reflect.Ptr {
642 fieldValue = fieldValue.Elem()
643 }
644 if fieldValue.Type().Kind() == reflect.Struct {
645 propsToMerge := extractStructProperties(fieldValue, indent)
646 for prop, value := range propsToMerge {
647 ret[prop] = value
648 }
649 continue
650 }
651 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800652
653 propertyName := proptools.PropertyNameForField(field.Name)
654 prettyPrintedValue, err := prettyPrint(fieldValue, indent+1)
655 if err != nil {
656 panic(
657 fmt.Errorf(
658 "Error while parsing property: %q. %s",
659 propertyName,
660 err))
661 }
662 if prettyPrintedValue != "" {
663 ret[propertyName] = prettyPrintedValue
664 }
665 }
666
667 return ret
668}
669
670func isZero(value reflect.Value) bool {
671 switch value.Kind() {
672 case reflect.Func, reflect.Map, reflect.Slice:
673 return value.IsNil()
674 case reflect.Array:
675 valueIsZero := true
676 for i := 0; i < value.Len(); i++ {
677 valueIsZero = valueIsZero && isZero(value.Index(i))
678 }
679 return valueIsZero
680 case reflect.Struct:
681 valueIsZero := true
682 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +0200683 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800684 }
685 return valueIsZero
686 case reflect.Ptr:
687 if !value.IsNil() {
688 return isZero(reflect.Indirect(value))
689 } else {
690 return true
691 }
Liz Kammerd366c902021-06-03 13:43:01 -0400692 // Always print bools, if you want a bool attribute to be able to take the default value, use a
693 // bool pointer instead
694 case reflect.Bool:
695 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800696 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -0400697 if !value.IsValid() {
698 return true
699 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800700 zeroValue := reflect.Zero(value.Type())
701 result := value.Interface() == zeroValue.Interface()
702 return result
703 }
704}
705
706func escapeString(s string) string {
707 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +0000708
709 // b/184026959: Reverse the application of some common control sequences.
710 // These must be generated literally in the BUILD file.
711 s = strings.ReplaceAll(s, "\t", "\\t")
712 s = strings.ReplaceAll(s, "\n", "\\n")
713 s = strings.ReplaceAll(s, "\r", "\\r")
714
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800715 return strings.ReplaceAll(s, "\"", "\\\"")
716}
717
718func makeIndent(indent int) string {
719 if indent < 0 {
720 panic(fmt.Errorf("indent column cannot be less than 0, but got %d", indent))
721 }
722 return strings.Repeat(" ", indent)
723}
724
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800725func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
726 name := ""
727 if c.ModuleSubDir(logicModule) != "" {
728 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
729 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
730 } else {
731 name = c.ModuleName(logicModule)
732 }
733
734 return strings.Replace(name, "//", "", 1)
735}
736
737func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
738 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
739}