blob: 242ea1e69d51aff7798b3cee300f2efed639d96e [file] [log] [blame]
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001// Copyright 2020 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package bp2build
16
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux0da7ce62021-08-23 17:04:20 +000017/*
18For shareable/common functionality for conversion from soong-module to build files
19for queryview/bp2build
20*/
21
Liz Kammer2dd9ca42020-11-25 16:06:39 -080022import (
Liz Kammer2dd9ca42020-11-25 16:06:39 -080023 "fmt"
24 "reflect"
Jingwen Chen49109762021-05-25 05:16:48 +000025 "sort"
Liz Kammer2dd9ca42020-11-25 16:06:39 -080026 "strings"
27
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux0da7ce62021-08-23 17:04:20 +000028 "android/soong/android"
29 "android/soong/bazel"
Liz Kammer72beb342022-02-03 08:42:10 -050030 "android/soong/starlark_fmt"
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux0da7ce62021-08-23 17:04:20 +000031
Liz Kammer2dd9ca42020-11-25 16:06:39 -080032 "github.com/google/blueprint"
33 "github.com/google/blueprint/proptools"
34)
35
36type BazelAttributes struct {
37 Attrs map[string]string
38}
39
40type BazelTarget struct {
Jingwen Chen40067de2021-01-26 21:58:43 -050041 name string
Jingwen Chenc63677b2021-06-17 05:43:19 +000042 packageName string
Jingwen Chen40067de2021-01-26 21:58:43 -050043 content string
44 ruleClass string
45 bzlLoadLocation string
Jingwen Chen49109762021-05-25 05:16:48 +000046 handcrafted bool
Jingwen Chen40067de2021-01-26 21:58:43 -050047}
48
49// IsLoadedFromStarlark determines if the BazelTarget's rule class is loaded from a .bzl file,
50// as opposed to a native rule built into Bazel.
51func (t BazelTarget) IsLoadedFromStarlark() bool {
52 return t.bzlLoadLocation != ""
53}
54
Jingwen Chenc63677b2021-06-17 05:43:19 +000055// Label is the fully qualified Bazel label constructed from the BazelTarget's
56// package name and target name.
57func (t BazelTarget) Label() string {
58 if t.packageName == "." {
59 return "//:" + t.name
60 } else {
61 return "//" + t.packageName + ":" + t.name
62 }
63}
64
Jingwen Chen40067de2021-01-26 21:58:43 -050065// BazelTargets is a typedef for a slice of BazelTarget objects.
66type BazelTargets []BazelTarget
67
Jingwen Chen49109762021-05-25 05:16:48 +000068// HasHandcraftedTargetsreturns true if a set of bazel targets contain
69// handcrafted ones.
70func (targets BazelTargets) hasHandcraftedTargets() bool {
71 for _, target := range targets {
72 if target.handcrafted {
73 return true
74 }
75 }
76 return false
77}
78
79// sort a list of BazelTargets in-place, by name, and by generated/handcrafted types.
80func (targets BazelTargets) sort() {
81 sort.Slice(targets, func(i, j int) bool {
82 if targets[i].handcrafted != targets[j].handcrafted {
83 // Handcrafted targets will be generated after the bp2build generated targets.
84 return targets[j].handcrafted
85 }
86 // This will cover all bp2build generated targets.
87 return targets[i].name < targets[j].name
88 })
89}
90
Jingwen Chen40067de2021-01-26 21:58:43 -050091// String returns the string representation of BazelTargets, without load
92// statements (use LoadStatements for that), since the targets are usually not
93// adjacent to the load statements at the top of the BUILD file.
94func (targets BazelTargets) String() string {
95 var res string
96 for i, target := range targets {
Jingwen Chen49109762021-05-25 05:16:48 +000097 // There is only at most 1 handcrafted "target", because its contents
98 // represent the entire BUILD file content from the tree. See
99 // build_conversion.go#getHandcraftedBuildContent for more information.
100 //
101 // Add a header to make it easy to debug where the handcrafted targets
102 // are in a generated BUILD file.
103 if target.handcrafted {
104 res += "# -----------------------------\n"
105 res += "# Section: Handcrafted targets. \n"
106 res += "# -----------------------------\n\n"
107 }
108
Jingwen Chen40067de2021-01-26 21:58:43 -0500109 res += target.content
110 if i != len(targets)-1 {
111 res += "\n\n"
112 }
113 }
114 return res
115}
116
117// LoadStatements return the string representation of the sorted and deduplicated
118// Starlark rule load statements needed by a group of BazelTargets.
119func (targets BazelTargets) LoadStatements() string {
120 bzlToLoadedSymbols := map[string][]string{}
121 for _, target := range targets {
122 if target.IsLoadedFromStarlark() {
123 bzlToLoadedSymbols[target.bzlLoadLocation] =
124 append(bzlToLoadedSymbols[target.bzlLoadLocation], target.ruleClass)
125 }
126 }
127
128 var loadStatements []string
129 for bzl, ruleClasses := range bzlToLoadedSymbols {
130 loadStatement := "load(\""
131 loadStatement += bzl
132 loadStatement += "\", "
133 ruleClasses = android.SortedUniqueStrings(ruleClasses)
134 for i, ruleClass := range ruleClasses {
135 loadStatement += "\"" + ruleClass + "\""
136 if i != len(ruleClasses)-1 {
137 loadStatement += ", "
138 }
139 }
140 loadStatement += ")"
141 loadStatements = append(loadStatements, loadStatement)
142 }
143 return strings.Join(android.SortedUniqueStrings(loadStatements), "\n")
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800144}
145
146type bpToBuildContext interface {
147 ModuleName(module blueprint.Module) string
148 ModuleDir(module blueprint.Module) string
149 ModuleSubDir(module blueprint.Module) string
150 ModuleType(module blueprint.Module) string
151
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500152 VisitAllModules(visit func(blueprint.Module))
153 VisitDirectDeps(module blueprint.Module, visit func(blueprint.Module))
154}
155
156type CodegenContext struct {
Jingwen Chen16d90a82021-09-17 07:16:13 +0000157 config android.Config
158 context android.Context
159 mode CodegenMode
160 additionalDeps []string
Liz Kammer6eff3232021-08-26 08:37:59 -0400161 unconvertedDepMode unconvertedDepsMode
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500162}
163
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400164func (ctx *CodegenContext) Mode() CodegenMode {
165 return ctx.mode
Jingwen Chen164e0862021-02-19 00:48:40 -0500166}
167
Jingwen Chen33832f92021-01-24 22:55:54 -0500168// CodegenMode is an enum to differentiate code-generation modes.
169type CodegenMode int
170
171const (
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400172 // Bp2Build - generate BUILD files with targets buildable by Bazel directly.
Jingwen Chen33832f92021-01-24 22:55:54 -0500173 //
174 // This mode is used for the Soong->Bazel build definition conversion.
175 Bp2Build CodegenMode = iota
176
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400177 // QueryView - generate BUILD files with targets representing fully mutated
Jingwen Chen33832f92021-01-24 22:55:54 -0500178 // Soong modules, representing the fully configured Soong module graph with
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400179 // variants and dependency edges.
Jingwen Chen33832f92021-01-24 22:55:54 -0500180 //
181 // This mode is used for discovering and introspecting the existing Soong
182 // module graph.
183 QueryView
184)
185
Liz Kammer6eff3232021-08-26 08:37:59 -0400186type unconvertedDepsMode int
187
188const (
189 // Include a warning in conversion metrics about converted modules with unconverted direct deps
190 warnUnconvertedDeps unconvertedDepsMode = iota
191 // Error and fail conversion if encountering a module with unconverted direct deps
192 // Enabled by setting environment variable `BP2BUILD_ERROR_UNCONVERTED`
193 errorModulesUnconvertedDeps
194)
195
Jingwen Chendcc329a2021-01-26 02:49:03 -0500196func (mode CodegenMode) String() string {
197 switch mode {
198 case Bp2Build:
199 return "Bp2Build"
200 case QueryView:
201 return "QueryView"
202 default:
203 return fmt.Sprintf("%d", mode)
204 }
205}
206
Liz Kammerba3ea162021-02-17 13:22:03 -0500207// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
208// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
209// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
210// call AdditionalNinjaDeps and add them manually to the ninja file.
211func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
212 ctx.additionalDeps = append(ctx.additionalDeps, deps...)
213}
214
215// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
216func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
217 return ctx.additionalDeps
218}
219
220func (ctx *CodegenContext) Config() android.Config { return ctx.config }
221func (ctx *CodegenContext) Context() android.Context { return ctx.context }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500222
223// NewCodegenContext creates a wrapper context that conforms to PathContext for
224// writing BUILD files in the output directory.
Liz Kammerba3ea162021-02-17 13:22:03 -0500225func NewCodegenContext(config android.Config, context android.Context, mode CodegenMode) *CodegenContext {
Liz Kammer6eff3232021-08-26 08:37:59 -0400226 var unconvertedDeps unconvertedDepsMode
227 if config.IsEnvTrue("BP2BUILD_ERROR_UNCONVERTED") {
228 unconvertedDeps = errorModulesUnconvertedDeps
229 }
Liz Kammerba3ea162021-02-17 13:22:03 -0500230 return &CodegenContext{
Liz Kammer6eff3232021-08-26 08:37:59 -0400231 context: context,
232 config: config,
233 mode: mode,
234 unconvertedDepMode: unconvertedDeps,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500235 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800236}
237
238// props is an unsorted map. This function ensures that
239// the generated attributes are sorted to ensure determinism.
240func propsToAttributes(props map[string]string) string {
241 var attributes string
242 for _, propName := range android.SortedStringKeys(props) {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400243 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800244 }
245 return attributes
246}
247
Liz Kammer6eff3232021-08-26 08:37:59 -0400248type conversionResults struct {
249 buildFileToTargets map[string]BazelTargets
250 metrics CodegenMetrics
Liz Kammer6eff3232021-08-26 08:37:59 -0400251}
252
253func (r conversionResults) BuildDirToTargets() map[string]BazelTargets {
254 return r.buildFileToTargets
255}
256
257func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (conversionResults, []error) {
Jingwen Chen40067de2021-01-26 21:58:43 -0500258 buildFileToTargets := make(map[string]BazelTargets)
Liz Kammerba3ea162021-02-17 13:22:03 -0500259 buildFileToAppend := make(map[string]bool)
Jingwen Chen164e0862021-02-19 00:48:40 -0500260
261 // Simple metrics tracking for bp2build
Liz Kammerba3ea162021-02-17 13:22:03 -0500262 metrics := CodegenMetrics{
Chris Parsons492bd912022-01-20 12:55:05 -0500263 ruleClassCount: make(map[string]uint64),
264 convertedModuleTypeCount: make(map[string]uint64),
265 totalModuleTypeCount: make(map[string]uint64),
Liz Kammerba3ea162021-02-17 13:22:03 -0500266 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500267
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400268 dirs := make(map[string]bool)
269
Liz Kammer6eff3232021-08-26 08:37:59 -0400270 var errs []error
271
Jingwen Chen164e0862021-02-19 00:48:40 -0500272 bpCtx := ctx.Context()
273 bpCtx.VisitAllModules(func(m blueprint.Module) {
274 dir := bpCtx.ModuleDir(m)
Chris Parsons492bd912022-01-20 12:55:05 -0500275 moduleType := bpCtx.ModuleType(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 Bp2Build:
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000282 // There are two main ways of converting a Soong module to Bazel:
283 // 1) Manually handcrafting a Bazel target and associating the module with its label
284 // 2) Automatically generating with bp2build converters
285 //
286 // bp2build converters are used for the majority of modules.
Liz Kammerba3ea162021-02-17 13:22:03 -0500287 if b, ok := m.(android.Bazelable); ok && b.HasHandcraftedLabel() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000288 // Handle modules converted to handcrafted targets.
289 //
290 // Since these modules are associated with some handcrafted
291 // target in a BUILD file, we simply append the entire contents
292 // of that BUILD file to the generated BUILD file.
293 //
294 // The append operation is only done once, even if there are
295 // multiple modules from the same directory associated to
296 // targets in the same BUILD file (or package).
297
298 // Log the module.
Chris Parsons492bd912022-01-20 12:55:05 -0500299 metrics.AddConvertedModule(m, moduleType, Handcrafted)
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000300
Liz Kammerba3ea162021-02-17 13:22:03 -0500301 pathToBuildFile := getBazelPackagePath(b)
Liz Kammerba3ea162021-02-17 13:22:03 -0500302 if _, exists := buildFileToAppend[pathToBuildFile]; exists {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000303 // Append the BUILD file content once per package, at most.
Liz Kammerba3ea162021-02-17 13:22:03 -0500304 return
305 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400306 t, err := getHandcraftedBuildContent(ctx, b, pathToBuildFile)
Liz Kammerba3ea162021-02-17 13:22:03 -0500307 if err != nil {
Liz Kammer6eff3232021-08-26 08:37:59 -0400308 errs = append(errs, fmt.Errorf("Error converting %s: %s", bpCtx.ModuleName(m), err))
309 return
Liz Kammerba3ea162021-02-17 13:22:03 -0500310 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400311 targets = append(targets, t)
Liz Kammerba3ea162021-02-17 13:22:03 -0500312 // TODO(b/181575318): currently we append the whole BUILD file, let's change that to do
313 // something more targeted based on the rule type and target
314 buildFileToAppend[pathToBuildFile] = true
Liz Kammer2ada09a2021-08-11 00:17:36 -0400315 } else if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000316 // Handle modules converted to generated targets.
317
318 // Log the module.
Chris Parsons492bd912022-01-20 12:55:05 -0500319 metrics.AddConvertedModule(aModule, moduleType, Generated)
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000320
321 // Handle modules with unconverted deps. By default, emit a warning.
Liz Kammer6eff3232021-08-26 08:37:59 -0400322 if unconvertedDeps := aModule.GetUnconvertedBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700323 msg := fmt.Sprintf("%s %s:%s depends on unconverted modules: %s",
324 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Liz Kammer6eff3232021-08-26 08:37:59 -0400325 if ctx.unconvertedDepMode == warnUnconvertedDeps {
326 metrics.moduleWithUnconvertedDepsMsgs = append(metrics.moduleWithUnconvertedDepsMsgs, msg)
327 } else if ctx.unconvertedDepMode == errorModulesUnconvertedDeps {
Liz Kammer6eff3232021-08-26 08:37:59 -0400328 errs = append(errs, fmt.Errorf(msg))
329 return
330 }
331 }
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500332 if unconvertedDeps := aModule.GetMissingBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700333 msg := fmt.Sprintf("%s %s:%s depends on missing modules: %s",
334 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500335 if ctx.unconvertedDepMode == warnUnconvertedDeps {
336 metrics.moduleWithMissingDepsMsgs = append(metrics.moduleWithMissingDepsMsgs, msg)
337 } else if ctx.unconvertedDepMode == errorModulesUnconvertedDeps {
338 errs = append(errs, fmt.Errorf(msg))
339 return
340 }
341 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400342 targets = generateBazelTargets(bpCtx, aModule)
343 for _, t := range targets {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000344 // A module can potentially generate more than 1 Bazel
345 // target, each of a different rule class.
346 metrics.IncrementRuleClassCount(t.ruleClass)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400347 }
Liz Kammerfc46bc12021-02-19 11:06:17 -0500348 } else {
Chris Parsons492bd912022-01-20 12:55:05 -0500349 metrics.AddUnconvertedModule(moduleType)
Liz Kammerba3ea162021-02-17 13:22:03 -0500350 return
Jingwen Chen73850672020-12-14 08:25:34 -0500351 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500352 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500353 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500354 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500355 // package module name contain slashes, and thus cannot
356 // be mapped cleanly to a bazel label.
357 return
358 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400359 t := generateSoongModuleTarget(bpCtx, m)
360 targets = append(targets, t)
Jingwen Chen33832f92021-01-24 22:55:54 -0500361 default:
Liz Kammer6eff3232021-08-26 08:37:59 -0400362 errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
363 return
Jingwen Chen73850672020-12-14 08:25:34 -0500364 }
365
Liz Kammer2ada09a2021-08-11 00:17:36 -0400366 buildFileToTargets[dir] = append(buildFileToTargets[dir], targets...)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800367 })
Liz Kammer6eff3232021-08-26 08:37:59 -0400368
369 if len(errs) > 0 {
370 return conversionResults{}, errs
371 }
372
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400373 if generateFilegroups {
374 // Add a filegroup target that exposes all sources in the subtree of this package
375 // NOTE: This also means we generate a BUILD file for every Android.bp file (as long as it has at least one module)
376 for dir, _ := range dirs {
377 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
378 name: "bp2build_all_srcs",
379 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]))`,
380 ruleClass: "filegroup",
381 })
382 }
383 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500384
Liz Kammer6eff3232021-08-26 08:37:59 -0400385 return conversionResults{
386 buildFileToTargets: buildFileToTargets,
387 metrics: metrics,
Liz Kammer6eff3232021-08-26 08:37:59 -0400388 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500389}
390
Liz Kammerba3ea162021-02-17 13:22:03 -0500391func getBazelPackagePath(b android.Bazelable) string {
Liz Kammerbdc60992021-02-24 16:55:11 -0500392 label := b.HandcraftedLabel()
Liz Kammerba3ea162021-02-17 13:22:03 -0500393 pathToBuildFile := strings.TrimPrefix(label, "//")
394 pathToBuildFile = strings.Split(pathToBuildFile, ":")[0]
395 return pathToBuildFile
396}
397
398func getHandcraftedBuildContent(ctx *CodegenContext, b android.Bazelable, pathToBuildFile string) (BazelTarget, error) {
399 p := android.ExistentPathForSource(ctx, pathToBuildFile, HandcraftedBuildFileName)
400 if !p.Valid() {
401 return BazelTarget{}, fmt.Errorf("Could not find file %q for handcrafted target.", pathToBuildFile)
402 }
403 c, err := b.GetBazelBuildFileContents(ctx.Config(), pathToBuildFile, HandcraftedBuildFileName)
404 if err != nil {
405 return BazelTarget{}, err
406 }
407 // TODO(b/181575318): once this is more targeted, we need to include name, rule class, etc
408 return BazelTarget{
Jingwen Chen49109762021-05-25 05:16:48 +0000409 content: c,
410 handcrafted: true,
Liz Kammerba3ea162021-02-17 13:22:03 -0500411 }, nil
412}
413
Liz Kammer2ada09a2021-08-11 00:17:36 -0400414func generateBazelTargets(ctx bpToBuildContext, m android.Module) []BazelTarget {
415 var targets []BazelTarget
416 for _, m := range m.Bp2buildTargets() {
417 targets = append(targets, generateBazelTarget(ctx, m))
418 }
419 return targets
420}
421
422type bp2buildModule interface {
423 TargetName() string
424 TargetPackage() string
425 BazelRuleClass() string
426 BazelRuleLoadLocation() string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000427 BazelAttributes() []interface{}
Liz Kammer2ada09a2021-08-11 00:17:36 -0400428}
429
430func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) BazelTarget {
431 ruleClass := m.BazelRuleClass()
432 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500433
Jingwen Chen73850672020-12-14 08:25:34 -0500434 // extract the bazel attributes from the module.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000435 attrs := m.BazelAttributes()
436 props := extractModuleProperties(attrs, true)
Jingwen Chen73850672020-12-14 08:25:34 -0500437
Liz Kammer0eae52e2021-10-06 10:32:26 -0400438 // name is handled in a special manner
439 delete(props.Attrs, "name")
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500440
Jingwen Chen73850672020-12-14 08:25:34 -0500441 // Return the Bazel target with rule class and attributes, ready to be
442 // code-generated.
443 attributes := propsToAttributes(props.Attrs)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400444 targetName := m.TargetName()
Jingwen Chen73850672020-12-14 08:25:34 -0500445 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500446 name: targetName,
Liz Kammer2ada09a2021-08-11 00:17:36 -0400447 packageName: m.TargetPackage(),
Jingwen Chen40067de2021-01-26 21:58:43 -0500448 ruleClass: ruleClass,
449 bzlLoadLocation: bzlLoadLocation,
Jingwen Chen73850672020-12-14 08:25:34 -0500450 content: fmt.Sprintf(
451 bazelTarget,
452 ruleClass,
453 targetName,
454 attributes,
455 ),
Jingwen Chen49109762021-05-25 05:16:48 +0000456 handcrafted: false,
Jingwen Chen73850672020-12-14 08:25:34 -0500457 }
458}
459
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800460// Convert a module and its deps and props into a Bazel macro/rule
461// representation in the BUILD file.
462func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) BazelTarget {
463 props := getBuildProperties(ctx, m)
464
465 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
466 // items, if the modules are added using different DependencyTag. Figure
467 // out the implications of that.
468 depLabels := map[string]bool{}
469 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500470 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800471 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
472 })
473 }
Liz Kammer0eae52e2021-10-06 10:32:26 -0400474
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400475 for p := range ignoredPropNames {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400476 delete(props.Attrs, p)
477 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800478 attributes := propsToAttributes(props.Attrs)
479
480 depLabelList := "[\n"
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400481 for depLabel := range depLabels {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800482 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
483 }
484 depLabelList += " ]"
485
486 targetName := targetNameWithVariant(ctx, m)
487 return BazelTarget{
488 name: targetName,
489 content: fmt.Sprintf(
490 soongModuleTarget,
491 targetName,
492 ctx.ModuleName(m),
493 canonicalizeModuleType(ctx.ModuleType(m)),
494 ctx.ModuleSubDir(m),
495 depLabelList,
496 attributes),
497 }
498}
499
500func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) BazelAttributes {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800501 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
502 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
503 if aModule, ok := m.(android.Module); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000504 return extractModuleProperties(aModule.GetProperties(), false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800505 }
506
Liz Kammer2ada09a2021-08-11 00:17:36 -0400507 return BazelAttributes{}
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800508}
509
510// Generically extract module properties and types into a map, keyed by the module property name.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000511func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) BazelAttributes {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800512 ret := map[string]string{}
513
514 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400515 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800516 propertiesValue := reflect.ValueOf(properties)
517 // Check that propertiesValue is a pointer to the Properties struct, like
518 // *cc.BaseLinkerProperties or *java.CompilerProperties.
519 //
520 // propertiesValue can also be type-asserted to the structs to
521 // manipulate internal props, if needed.
522 if isStructPtr(propertiesValue.Type()) {
523 structValue := propertiesValue.Elem()
524 for k, v := range extractStructProperties(structValue, 0) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000525 if existing, exists := ret[k]; checkForDuplicateProperties && exists {
526 panic(fmt.Errorf(
527 "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes",
528 k, existing))
529 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800530 ret[k] = v
531 }
532 } else {
533 panic(fmt.Errorf(
534 "properties must be a pointer to a struct, got %T",
535 propertiesValue.Interface()))
536 }
537 }
538
Liz Kammer2ada09a2021-08-11 00:17:36 -0400539 return BazelAttributes{
540 Attrs: ret,
541 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800542}
543
544func isStructPtr(t reflect.Type) bool {
545 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
546}
547
548// prettyPrint a property value into the equivalent Starlark representation
549// recursively.
Jingwen Chen58ff6802021-11-17 12:14:41 +0000550func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) {
551 if !emitZeroValues && isZero(propertyValue) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800552 // A property value being set or unset actually matters -- Soong does set default
553 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
554 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
555 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +0000556 // In Bazel-parlance, we would use "attr.<type>(default = <default
557 // value>)" to set the default value of unset attributes. In the cases
558 // where the bp2build converter didn't set the default value within the
559 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -0400560 // value. For those cases, we return an empty string so we don't
561 // unnecessarily generate empty values.
562 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800563 }
564
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800565 switch propertyValue.Kind() {
566 case reflect.String:
Liz Kammer72beb342022-02-03 08:42:10 -0500567 return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800568 case reflect.Bool:
Liz Kammer72beb342022-02-03 08:42:10 -0500569 return starlark_fmt.PrintBool(propertyValue.Bool()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800570 case reflect.Int, reflect.Uint, reflect.Int64:
Liz Kammer72beb342022-02-03 08:42:10 -0500571 return fmt.Sprintf("%v", propertyValue.Interface()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800572 case reflect.Ptr:
Jingwen Chen58ff6802021-11-17 12:14:41 +0000573 return prettyPrint(propertyValue.Elem(), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800574 case reflect.Slice:
Liz Kammer72beb342022-02-03 08:42:10 -0500575 elements := make([]string, 0, propertyValue.Len())
576 for i := 0; i < propertyValue.Len(); i++ {
577 val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800578 if err != nil {
579 return "", err
580 }
Liz Kammer72beb342022-02-03 08:42:10 -0500581 if val != "" {
582 elements = append(elements, val)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800583 }
584 }
Sam Delmerico932c01c2022-03-25 16:33:26 +0000585 return starlark_fmt.PrintList(elements, indent, func(s string) string {
586 return "%s"
587 }), nil
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000588
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800589 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -0500590 // Special cases where the bp2build sends additional information to the codegenerator
591 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +0000592 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
593 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -0500594 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
595 return fmt.Sprintf("%q", label.Label), nil
596 }
597
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800598 // Sort and print the struct props by the key.
599 structProps := extractStructProperties(propertyValue, indent)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000600 if len(structProps) == 0 {
601 return "", nil
602 }
Liz Kammer72beb342022-02-03 08:42:10 -0500603 return starlark_fmt.PrintDict(structProps, indent), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800604 case reflect.Interface:
605 // TODO(b/164227191): implement pretty print for interfaces.
606 // Interfaces are used for for arch, multilib and target properties.
607 return "", nil
608 default:
609 return "", fmt.Errorf(
610 "unexpected kind for property struct field: %s", propertyValue.Kind())
611 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800612}
613
614// Converts a reflected property struct value into a map of property names and property values,
615// which each property value correctly pretty-printed and indented at the right nest level,
616// since property structs can be nested. In Starlark, nested structs are represented as nested
617// dicts: https://docs.bazel.build/skylark/lib/dict.html
618func extractStructProperties(structValue reflect.Value, indent int) map[string]string {
619 if structValue.Kind() != reflect.Struct {
620 panic(fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind()))
621 }
622
623 ret := map[string]string{}
624 structType := structValue.Type()
625 for i := 0; i < structValue.NumField(); i++ {
626 field := structType.Field(i)
627 if shouldSkipStructField(field) {
628 continue
629 }
630
631 fieldValue := structValue.Field(i)
632 if isZero(fieldValue) {
633 // Ignore zero-valued fields
634 continue
635 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400636
Liz Kammer32a03392021-09-14 11:17:21 -0400637 // if the struct is embedded (anonymous), flatten the properties into the containing struct
638 if field.Anonymous {
639 if field.Type.Kind() == reflect.Ptr {
640 fieldValue = fieldValue.Elem()
641 }
642 if fieldValue.Type().Kind() == reflect.Struct {
643 propsToMerge := extractStructProperties(fieldValue, indent)
644 for prop, value := range propsToMerge {
645 ret[prop] = value
646 }
647 continue
648 }
649 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800650
651 propertyName := proptools.PropertyNameForField(field.Name)
Jingwen Chen58ff6802021-11-17 12:14:41 +0000652 prettyPrintedValue, err := prettyPrint(fieldValue, indent+1, false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800653 if err != nil {
654 panic(
655 fmt.Errorf(
656 "Error while parsing property: %q. %s",
657 propertyName,
658 err))
659 }
660 if prettyPrintedValue != "" {
661 ret[propertyName] = prettyPrintedValue
662 }
663 }
664
665 return ret
666}
667
668func isZero(value reflect.Value) bool {
669 switch value.Kind() {
670 case reflect.Func, reflect.Map, reflect.Slice:
671 return value.IsNil()
672 case reflect.Array:
673 valueIsZero := true
674 for i := 0; i < value.Len(); i++ {
675 valueIsZero = valueIsZero && isZero(value.Index(i))
676 }
677 return valueIsZero
678 case reflect.Struct:
679 valueIsZero := true
680 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +0200681 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800682 }
683 return valueIsZero
684 case reflect.Ptr:
685 if !value.IsNil() {
686 return isZero(reflect.Indirect(value))
687 } else {
688 return true
689 }
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500690 // Always print bool/strings, if you want a bool/string attribute to be able to take the default value, use a
691 // pointer instead
692 case reflect.Bool, reflect.String:
Liz Kammerd366c902021-06-03 13:43:01 -0400693 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800694 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -0400695 if !value.IsValid() {
696 return true
697 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800698 zeroValue := reflect.Zero(value.Type())
699 result := value.Interface() == zeroValue.Interface()
700 return result
701 }
702}
703
704func escapeString(s string) string {
705 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +0000706
707 // b/184026959: Reverse the application of some common control sequences.
708 // These must be generated literally in the BUILD file.
709 s = strings.ReplaceAll(s, "\t", "\\t")
710 s = strings.ReplaceAll(s, "\n", "\\n")
711 s = strings.ReplaceAll(s, "\r", "\\r")
712
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800713 return strings.ReplaceAll(s, "\"", "\\\"")
714}
715
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800716func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
717 name := ""
718 if c.ModuleSubDir(logicModule) != "" {
719 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
720 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
721 } else {
722 name = c.ModuleName(logicModule)
723 }
724
725 return strings.Replace(name, "//", "", 1)
726}
727
728func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
729 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
730}