blob: a06b89edb135a2a1cf29f5855cd56dd476e0764d [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"
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
45}
46
47// IsLoadedFromStarlark determines if the BazelTarget's rule class is loaded from a .bzl file,
48// as opposed to a native rule built into Bazel.
49func (t BazelTarget) IsLoadedFromStarlark() bool {
50 return t.bzlLoadLocation != ""
51}
52
Jingwen Chenc63677b2021-06-17 05:43:19 +000053// Label is the fully qualified Bazel label constructed from the BazelTarget's
54// package name and target name.
55func (t BazelTarget) Label() string {
56 if t.packageName == "." {
57 return "//:" + t.name
58 } else {
59 return "//" + t.packageName + ":" + t.name
60 }
61}
62
Jingwen Chen40067de2021-01-26 21:58:43 -050063// BazelTargets is a typedef for a slice of BazelTarget objects.
64type BazelTargets []BazelTarget
65
Sasha Smundak8bea2672022-08-04 13:31:14 -070066func (targets BazelTargets) packageRule() *BazelTarget {
67 for _, target := range targets {
68 if target.ruleClass == "package" {
69 return &target
70 }
71 }
72 return nil
73}
74
75// sort a list of BazelTargets in-place, by name, and by generated/handcrafted types.
Jingwen Chen49109762021-05-25 05:16:48 +000076func (targets BazelTargets) sort() {
77 sort.Slice(targets, func(i, j int) bool {
Jingwen Chen49109762021-05-25 05:16:48 +000078 return targets[i].name < targets[j].name
79 })
80}
81
Jingwen Chen40067de2021-01-26 21:58:43 -050082// String returns the string representation of BazelTargets, without load
83// statements (use LoadStatements for that), since the targets are usually not
84// adjacent to the load statements at the top of the BUILD file.
85func (targets BazelTargets) String() string {
86 var res string
87 for i, target := range targets {
Sasha Smundak8bea2672022-08-04 13:31:14 -070088 if target.ruleClass != "package" {
89 res += target.content
90 }
Jingwen Chen40067de2021-01-26 21:58:43 -050091 if i != len(targets)-1 {
92 res += "\n\n"
93 }
94 }
95 return res
96}
97
98// LoadStatements return the string representation of the sorted and deduplicated
99// Starlark rule load statements needed by a group of BazelTargets.
100func (targets BazelTargets) LoadStatements() string {
101 bzlToLoadedSymbols := map[string][]string{}
102 for _, target := range targets {
103 if target.IsLoadedFromStarlark() {
104 bzlToLoadedSymbols[target.bzlLoadLocation] =
105 append(bzlToLoadedSymbols[target.bzlLoadLocation], target.ruleClass)
106 }
107 }
108
109 var loadStatements []string
110 for bzl, ruleClasses := range bzlToLoadedSymbols {
111 loadStatement := "load(\""
112 loadStatement += bzl
113 loadStatement += "\", "
114 ruleClasses = android.SortedUniqueStrings(ruleClasses)
115 for i, ruleClass := range ruleClasses {
116 loadStatement += "\"" + ruleClass + "\""
117 if i != len(ruleClasses)-1 {
118 loadStatement += ", "
119 }
120 }
121 loadStatement += ")"
122 loadStatements = append(loadStatements, loadStatement)
123 }
124 return strings.Join(android.SortedUniqueStrings(loadStatements), "\n")
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800125}
126
127type bpToBuildContext interface {
128 ModuleName(module blueprint.Module) string
129 ModuleDir(module blueprint.Module) string
130 ModuleSubDir(module blueprint.Module) string
131 ModuleType(module blueprint.Module) string
132
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500133 VisitAllModules(visit func(blueprint.Module))
134 VisitDirectDeps(module blueprint.Module, visit func(blueprint.Module))
135}
136
137type CodegenContext struct {
Jingwen Chen16d90a82021-09-17 07:16:13 +0000138 config android.Config
139 context android.Context
140 mode CodegenMode
141 additionalDeps []string
Liz Kammer6eff3232021-08-26 08:37:59 -0400142 unconvertedDepMode unconvertedDepsMode
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500143}
144
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400145func (ctx *CodegenContext) Mode() CodegenMode {
146 return ctx.mode
Jingwen Chen164e0862021-02-19 00:48:40 -0500147}
148
Jingwen Chen33832f92021-01-24 22:55:54 -0500149// CodegenMode is an enum to differentiate code-generation modes.
150type CodegenMode int
151
152const (
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400153 // Bp2Build - generate BUILD files with targets buildable by Bazel directly.
Jingwen Chen33832f92021-01-24 22:55:54 -0500154 //
155 // This mode is used for the Soong->Bazel build definition conversion.
156 Bp2Build CodegenMode = iota
157
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400158 // QueryView - generate BUILD files with targets representing fully mutated
Jingwen Chen33832f92021-01-24 22:55:54 -0500159 // Soong modules, representing the fully configured Soong module graph with
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400160 // variants and dependency edges.
Jingwen Chen33832f92021-01-24 22:55:54 -0500161 //
162 // This mode is used for discovering and introspecting the existing Soong
163 // module graph.
164 QueryView
Spandan Das5af0bd32022-09-28 20:43:08 +0000165
166 // ApiBp2build - generate BUILD files for API contribution targets
167 ApiBp2build
Jingwen Chen33832f92021-01-24 22:55:54 -0500168)
169
Liz Kammer6eff3232021-08-26 08:37:59 -0400170type unconvertedDepsMode int
171
172const (
173 // Include a warning in conversion metrics about converted modules with unconverted direct deps
174 warnUnconvertedDeps unconvertedDepsMode = iota
175 // Error and fail conversion if encountering a module with unconverted direct deps
176 // Enabled by setting environment variable `BP2BUILD_ERROR_UNCONVERTED`
177 errorModulesUnconvertedDeps
178)
179
Jingwen Chendcc329a2021-01-26 02:49:03 -0500180func (mode CodegenMode) String() string {
181 switch mode {
182 case Bp2Build:
183 return "Bp2Build"
184 case QueryView:
185 return "QueryView"
Spandan Das5af0bd32022-09-28 20:43:08 +0000186 case ApiBp2build:
187 return "ApiBp2build"
Jingwen Chendcc329a2021-01-26 02:49:03 -0500188 default:
189 return fmt.Sprintf("%d", mode)
190 }
191}
192
Liz Kammerba3ea162021-02-17 13:22:03 -0500193// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
194// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
195// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
196// call AdditionalNinjaDeps and add them manually to the ninja file.
197func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
198 ctx.additionalDeps = append(ctx.additionalDeps, deps...)
199}
200
201// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
202func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
203 return ctx.additionalDeps
204}
205
206func (ctx *CodegenContext) Config() android.Config { return ctx.config }
207func (ctx *CodegenContext) Context() android.Context { return ctx.context }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500208
209// NewCodegenContext creates a wrapper context that conforms to PathContext for
210// writing BUILD files in the output directory.
Liz Kammerba3ea162021-02-17 13:22:03 -0500211func NewCodegenContext(config android.Config, context android.Context, mode CodegenMode) *CodegenContext {
Liz Kammer6eff3232021-08-26 08:37:59 -0400212 var unconvertedDeps unconvertedDepsMode
213 if config.IsEnvTrue("BP2BUILD_ERROR_UNCONVERTED") {
214 unconvertedDeps = errorModulesUnconvertedDeps
215 }
Liz Kammerba3ea162021-02-17 13:22:03 -0500216 return &CodegenContext{
Liz Kammer6eff3232021-08-26 08:37:59 -0400217 context: context,
218 config: config,
219 mode: mode,
220 unconvertedDepMode: unconvertedDeps,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500221 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800222}
223
224// props is an unsorted map. This function ensures that
225// the generated attributes are sorted to ensure determinism.
226func propsToAttributes(props map[string]string) string {
227 var attributes string
228 for _, propName := range android.SortedStringKeys(props) {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400229 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800230 }
231 return attributes
232}
233
Liz Kammer6eff3232021-08-26 08:37:59 -0400234type conversionResults struct {
235 buildFileToTargets map[string]BazelTargets
236 metrics CodegenMetrics
Liz Kammer6eff3232021-08-26 08:37:59 -0400237}
238
239func (r conversionResults) BuildDirToTargets() map[string]BazelTargets {
240 return r.buildFileToTargets
241}
242
243func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (conversionResults, []error) {
Jingwen Chen40067de2021-01-26 21:58:43 -0500244 buildFileToTargets := make(map[string]BazelTargets)
Jingwen Chen164e0862021-02-19 00:48:40 -0500245
246 // Simple metrics tracking for bp2build
usta4f5d2c12022-10-28 23:32:01 -0400247 metrics := CreateCodegenMetrics()
Jingwen Chen164e0862021-02-19 00:48:40 -0500248
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400249 dirs := make(map[string]bool)
250
Liz Kammer6eff3232021-08-26 08:37:59 -0400251 var errs []error
252
Jingwen Chen164e0862021-02-19 00:48:40 -0500253 bpCtx := ctx.Context()
254 bpCtx.VisitAllModules(func(m blueprint.Module) {
255 dir := bpCtx.ModuleDir(m)
Chris Parsons492bd912022-01-20 12:55:05 -0500256 moduleType := bpCtx.ModuleType(m)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400257 dirs[dir] = true
258
Liz Kammer2ada09a2021-08-11 00:17:36 -0400259 var targets []BazelTarget
Jingwen Chen73850672020-12-14 08:25:34 -0500260
Jingwen Chen164e0862021-02-19 00:48:40 -0500261 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500262 case Bp2Build:
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000263 // There are two main ways of converting a Soong module to Bazel:
264 // 1) Manually handcrafting a Bazel target and associating the module with its label
265 // 2) Automatically generating with bp2build converters
266 //
267 // bp2build converters are used for the majority of modules.
Liz Kammerba3ea162021-02-17 13:22:03 -0500268 if b, ok := m.(android.Bazelable); ok && b.HasHandcraftedLabel() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000269 // Handle modules converted to handcrafted targets.
270 //
271 // Since these modules are associated with some handcrafted
Cole Faustea602c52022-08-31 14:48:26 -0700272 // target in a BUILD file, we don't autoconvert them.
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000273
274 // Log the module.
Kevin Dagostino60f562a2022-09-20 03:54:47 +0000275 metrics.AddConvertedModule(m, moduleType, dir, Handcrafted)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400276 } else if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000277 // Handle modules converted to generated targets.
278
279 // Log the module.
Kevin Dagostino60f562a2022-09-20 03:54:47 +0000280 metrics.AddConvertedModule(aModule, moduleType, dir, Generated)
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000281
282 // Handle modules with unconverted deps. By default, emit a warning.
Liz Kammer6eff3232021-08-26 08:37:59 -0400283 if unconvertedDeps := aModule.GetUnconvertedBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700284 msg := fmt.Sprintf("%s %s:%s depends on unconverted modules: %s",
285 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400286 switch ctx.unconvertedDepMode {
287 case warnUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400288 metrics.moduleWithUnconvertedDepsMsgs = append(metrics.moduleWithUnconvertedDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400289 case errorModulesUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400290 errs = append(errs, fmt.Errorf(msg))
291 return
292 }
293 }
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500294 if unconvertedDeps := aModule.GetMissingBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700295 msg := fmt.Sprintf("%s %s:%s depends on missing modules: %s",
296 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400297 switch ctx.unconvertedDepMode {
298 case warnUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500299 metrics.moduleWithMissingDepsMsgs = append(metrics.moduleWithMissingDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400300 case errorModulesUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500301 errs = append(errs, fmt.Errorf(msg))
302 return
303 }
304 }
Alix94e26032022-08-16 20:37:33 +0000305 var targetErrs []error
306 targets, targetErrs = generateBazelTargets(bpCtx, aModule)
307 errs = append(errs, targetErrs...)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400308 for _, t := range targets {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000309 // A module can potentially generate more than 1 Bazel
310 // target, each of a different rule class.
311 metrics.IncrementRuleClassCount(t.ruleClass)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400312 }
Liz Kammerfc46bc12021-02-19 11:06:17 -0500313 } else {
Chris Parsons492bd912022-01-20 12:55:05 -0500314 metrics.AddUnconvertedModule(moduleType)
Liz Kammerba3ea162021-02-17 13:22:03 -0500315 return
Jingwen Chen73850672020-12-14 08:25:34 -0500316 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500317 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500318 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500319 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500320 // package module name contain slashes, and thus cannot
321 // be mapped cleanly to a bazel label.
322 return
323 }
Alix94e26032022-08-16 20:37:33 +0000324 t, err := generateSoongModuleTarget(bpCtx, m)
325 if err != nil {
326 errs = append(errs, err)
327 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400328 targets = append(targets, t)
Spandan Das5af0bd32022-09-28 20:43:08 +0000329 case ApiBp2build:
330 if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
331 targets, errs = generateBazelTargets(bpCtx, aModule)
332 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500333 default:
Liz Kammer6eff3232021-08-26 08:37:59 -0400334 errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
335 return
Jingwen Chen73850672020-12-14 08:25:34 -0500336 }
337
Liz Kammer2ada09a2021-08-11 00:17:36 -0400338 buildFileToTargets[dir] = append(buildFileToTargets[dir], targets...)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800339 })
Liz Kammer6eff3232021-08-26 08:37:59 -0400340
341 if len(errs) > 0 {
342 return conversionResults{}, errs
343 }
344
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400345 if generateFilegroups {
346 // Add a filegroup target that exposes all sources in the subtree of this package
347 // NOTE: This also means we generate a BUILD file for every Android.bp file (as long as it has at least one module)
Cole Faust324a92e2022-08-23 15:29:05 -0700348 //
349 // This works because: https://bazel.build/reference/be/functions#exports_files
350 // "As a legacy behaviour, also files mentioned as input to a rule are exported with the
351 // default visibility until the flag --incompatible_no_implicit_file_export is flipped. However, this behavior
352 // should not be relied upon and actively migrated away from."
353 //
354 // TODO(b/198619163): We should change this to export_files(glob(["**/*"])) instead, but doing that causes these errors:
355 // "Error in exports_files: generated label '//external/avb:avbtool' conflicts with existing py_binary rule"
356 // So we need to solve all the "target ... is both a rule and a file" warnings first.
Usta Shresthac6057152022-09-24 00:23:31 -0400357 for dir := range dirs {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400358 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
359 name: "bp2build_all_srcs",
360 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]))`,
361 ruleClass: "filegroup",
362 })
363 }
364 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500365
Liz Kammer6eff3232021-08-26 08:37:59 -0400366 return conversionResults{
367 buildFileToTargets: buildFileToTargets,
368 metrics: metrics,
Liz Kammer6eff3232021-08-26 08:37:59 -0400369 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500370}
371
Alix94e26032022-08-16 20:37:33 +0000372func generateBazelTargets(ctx bpToBuildContext, m android.Module) ([]BazelTarget, []error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400373 var targets []BazelTarget
Alix94e26032022-08-16 20:37:33 +0000374 var errs []error
Liz Kammer2ada09a2021-08-11 00:17:36 -0400375 for _, m := range m.Bp2buildTargets() {
Alix94e26032022-08-16 20:37:33 +0000376 target, err := generateBazelTarget(ctx, m)
377 if err != nil {
378 errs = append(errs, err)
379 return targets, errs
380 }
381 targets = append(targets, target)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400382 }
Alix94e26032022-08-16 20:37:33 +0000383 return targets, errs
Liz Kammer2ada09a2021-08-11 00:17:36 -0400384}
385
386type bp2buildModule interface {
387 TargetName() string
388 TargetPackage() string
389 BazelRuleClass() string
390 BazelRuleLoadLocation() string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000391 BazelAttributes() []interface{}
Liz Kammer2ada09a2021-08-11 00:17:36 -0400392}
393
Alix94e26032022-08-16 20:37:33 +0000394func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) (BazelTarget, error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400395 ruleClass := m.BazelRuleClass()
396 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500397
Jingwen Chen73850672020-12-14 08:25:34 -0500398 // extract the bazel attributes from the module.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000399 attrs := m.BazelAttributes()
Alix94e26032022-08-16 20:37:33 +0000400 props, err := extractModuleProperties(attrs, true)
401 if err != nil {
402 return BazelTarget{}, err
403 }
Jingwen Chen73850672020-12-14 08:25:34 -0500404
Liz Kammer0eae52e2021-10-06 10:32:26 -0400405 // name is handled in a special manner
406 delete(props.Attrs, "name")
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500407
Jingwen Chen73850672020-12-14 08:25:34 -0500408 // Return the Bazel target with rule class and attributes, ready to be
409 // code-generated.
410 attributes := propsToAttributes(props.Attrs)
Sasha Smundakfb589492022-08-04 11:13:27 -0700411 var content string
Liz Kammer2ada09a2021-08-11 00:17:36 -0400412 targetName := m.TargetName()
Sasha Smundakfb589492022-08-04 11:13:27 -0700413 if targetName != "" {
414 content = fmt.Sprintf(ruleTargetTemplate, ruleClass, targetName, attributes)
415 } else {
416 content = fmt.Sprintf(unnamedRuleTargetTemplate, ruleClass, attributes)
417 }
Jingwen Chen73850672020-12-14 08:25:34 -0500418 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500419 name: targetName,
Liz Kammer2ada09a2021-08-11 00:17:36 -0400420 packageName: m.TargetPackage(),
Jingwen Chen40067de2021-01-26 21:58:43 -0500421 ruleClass: ruleClass,
422 bzlLoadLocation: bzlLoadLocation,
Sasha Smundakfb589492022-08-04 11:13:27 -0700423 content: content,
Alix94e26032022-08-16 20:37:33 +0000424 }, nil
Jingwen Chen73850672020-12-14 08:25:34 -0500425}
426
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800427// Convert a module and its deps and props into a Bazel macro/rule
428// representation in the BUILD file.
Alix94e26032022-08-16 20:37:33 +0000429func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) (BazelTarget, error) {
430 props, err := getBuildProperties(ctx, m)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800431
432 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
433 // items, if the modules are added using different DependencyTag. Figure
434 // out the implications of that.
435 depLabels := map[string]bool{}
436 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500437 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800438 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
439 })
440 }
Liz Kammer0eae52e2021-10-06 10:32:26 -0400441
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400442 for p := range ignoredPropNames {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400443 delete(props.Attrs, p)
444 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800445 attributes := propsToAttributes(props.Attrs)
446
447 depLabelList := "[\n"
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400448 for depLabel := range depLabels {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800449 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
450 }
451 depLabelList += " ]"
452
453 targetName := targetNameWithVariant(ctx, m)
454 return BazelTarget{
455 name: targetName,
456 content: fmt.Sprintf(
Sasha Smundakfb589492022-08-04 11:13:27 -0700457 soongModuleTargetTemplate,
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800458 targetName,
459 ctx.ModuleName(m),
460 canonicalizeModuleType(ctx.ModuleType(m)),
461 ctx.ModuleSubDir(m),
462 depLabelList,
463 attributes),
Alix94e26032022-08-16 20:37:33 +0000464 }, err
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800465}
466
Alix94e26032022-08-16 20:37:33 +0000467func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800468 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
469 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
470 if aModule, ok := m.(android.Module); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000471 return extractModuleProperties(aModule.GetProperties(), false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800472 }
473
Alix94e26032022-08-16 20:37:33 +0000474 return BazelAttributes{}, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800475}
476
477// Generically extract module properties and types into a map, keyed by the module property name.
Alix94e26032022-08-16 20:37:33 +0000478func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800479 ret := map[string]string{}
480
481 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400482 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800483 propertiesValue := reflect.ValueOf(properties)
484 // Check that propertiesValue is a pointer to the Properties struct, like
485 // *cc.BaseLinkerProperties or *java.CompilerProperties.
486 //
487 // propertiesValue can also be type-asserted to the structs to
488 // manipulate internal props, if needed.
489 if isStructPtr(propertiesValue.Type()) {
490 structValue := propertiesValue.Elem()
Alix94e26032022-08-16 20:37:33 +0000491 ok, err := extractStructProperties(structValue, 0)
492 if err != nil {
493 return BazelAttributes{}, err
494 }
495 for k, v := range ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000496 if existing, exists := ret[k]; checkForDuplicateProperties && exists {
Alix94e26032022-08-16 20:37:33 +0000497 return BazelAttributes{}, fmt.Errorf(
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000498 "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes",
Alix94e26032022-08-16 20:37:33 +0000499 k, existing)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000500 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800501 ret[k] = v
502 }
503 } else {
Alix94e26032022-08-16 20:37:33 +0000504 return BazelAttributes{},
505 fmt.Errorf(
506 "properties must be a pointer to a struct, got %T",
507 propertiesValue.Interface())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800508 }
509 }
510
Liz Kammer2ada09a2021-08-11 00:17:36 -0400511 return BazelAttributes{
512 Attrs: ret,
Alix94e26032022-08-16 20:37:33 +0000513 }, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800514}
515
516func isStructPtr(t reflect.Type) bool {
517 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
518}
519
520// prettyPrint a property value into the equivalent Starlark representation
521// recursively.
Jingwen Chen58ff6802021-11-17 12:14:41 +0000522func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) {
523 if !emitZeroValues && isZero(propertyValue) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800524 // A property value being set or unset actually matters -- Soong does set default
525 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
526 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
527 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +0000528 // In Bazel-parlance, we would use "attr.<type>(default = <default
529 // value>)" to set the default value of unset attributes. In the cases
530 // where the bp2build converter didn't set the default value within the
531 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -0400532 // value. For those cases, we return an empty string so we don't
533 // unnecessarily generate empty values.
534 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800535 }
536
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800537 switch propertyValue.Kind() {
538 case reflect.String:
Liz Kammer72beb342022-02-03 08:42:10 -0500539 return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800540 case reflect.Bool:
Liz Kammer72beb342022-02-03 08:42:10 -0500541 return starlark_fmt.PrintBool(propertyValue.Bool()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800542 case reflect.Int, reflect.Uint, reflect.Int64:
Liz Kammer72beb342022-02-03 08:42:10 -0500543 return fmt.Sprintf("%v", propertyValue.Interface()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800544 case reflect.Ptr:
Jingwen Chen58ff6802021-11-17 12:14:41 +0000545 return prettyPrint(propertyValue.Elem(), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800546 case reflect.Slice:
Liz Kammer72beb342022-02-03 08:42:10 -0500547 elements := make([]string, 0, propertyValue.Len())
548 for i := 0; i < propertyValue.Len(); i++ {
549 val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800550 if err != nil {
551 return "", err
552 }
Liz Kammer72beb342022-02-03 08:42:10 -0500553 if val != "" {
554 elements = append(elements, val)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800555 }
556 }
Sam Delmerico932c01c2022-03-25 16:33:26 +0000557 return starlark_fmt.PrintList(elements, indent, func(s string) string {
558 return "%s"
559 }), nil
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000560
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800561 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -0500562 // Special cases where the bp2build sends additional information to the codegenerator
563 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +0000564 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
565 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -0500566 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
567 return fmt.Sprintf("%q", label.Label), nil
568 }
569
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800570 // Sort and print the struct props by the key.
Alix94e26032022-08-16 20:37:33 +0000571 structProps, err := extractStructProperties(propertyValue, indent)
572
573 if err != nil {
574 return "", err
575 }
576
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000577 if len(structProps) == 0 {
578 return "", nil
579 }
Liz Kammer72beb342022-02-03 08:42:10 -0500580 return starlark_fmt.PrintDict(structProps, indent), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800581 case reflect.Interface:
582 // TODO(b/164227191): implement pretty print for interfaces.
583 // Interfaces are used for for arch, multilib and target properties.
584 return "", nil
585 default:
586 return "", fmt.Errorf(
587 "unexpected kind for property struct field: %s", propertyValue.Kind())
588 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800589}
590
591// Converts a reflected property struct value into a map of property names and property values,
592// which each property value correctly pretty-printed and indented at the right nest level,
593// since property structs can be nested. In Starlark, nested structs are represented as nested
594// dicts: https://docs.bazel.build/skylark/lib/dict.html
Alix94e26032022-08-16 20:37:33 +0000595func extractStructProperties(structValue reflect.Value, indent int) (map[string]string, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800596 if structValue.Kind() != reflect.Struct {
Alix94e26032022-08-16 20:37:33 +0000597 return map[string]string{}, fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800598 }
599
Alix94e26032022-08-16 20:37:33 +0000600 var err error
601
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800602 ret := map[string]string{}
603 structType := structValue.Type()
604 for i := 0; i < structValue.NumField(); i++ {
605 field := structType.Field(i)
606 if shouldSkipStructField(field) {
607 continue
608 }
609
610 fieldValue := structValue.Field(i)
611 if isZero(fieldValue) {
612 // Ignore zero-valued fields
613 continue
614 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400615
Liz Kammer32a03392021-09-14 11:17:21 -0400616 // if the struct is embedded (anonymous), flatten the properties into the containing struct
617 if field.Anonymous {
618 if field.Type.Kind() == reflect.Ptr {
619 fieldValue = fieldValue.Elem()
620 }
621 if fieldValue.Type().Kind() == reflect.Struct {
Alix94e26032022-08-16 20:37:33 +0000622 propsToMerge, err := extractStructProperties(fieldValue, indent)
623 if err != nil {
624 return map[string]string{}, err
625 }
Liz Kammer32a03392021-09-14 11:17:21 -0400626 for prop, value := range propsToMerge {
627 ret[prop] = value
628 }
629 continue
630 }
631 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800632
633 propertyName := proptools.PropertyNameForField(field.Name)
Alix94e26032022-08-16 20:37:33 +0000634 var prettyPrintedValue string
635 prettyPrintedValue, err = prettyPrint(fieldValue, indent+1, false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800636 if err != nil {
Alix94e26032022-08-16 20:37:33 +0000637 return map[string]string{}, fmt.Errorf(
638 "Error while parsing property: %q. %s",
639 propertyName,
640 err)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800641 }
642 if prettyPrintedValue != "" {
643 ret[propertyName] = prettyPrintedValue
644 }
645 }
646
Alix94e26032022-08-16 20:37:33 +0000647 return ret, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800648}
649
650func isZero(value reflect.Value) bool {
651 switch value.Kind() {
652 case reflect.Func, reflect.Map, reflect.Slice:
653 return value.IsNil()
654 case reflect.Array:
655 valueIsZero := true
656 for i := 0; i < value.Len(); i++ {
657 valueIsZero = valueIsZero && isZero(value.Index(i))
658 }
659 return valueIsZero
660 case reflect.Struct:
661 valueIsZero := true
662 for i := 0; i < value.NumField(); i++ {
Lukacs T. Berki1353e592021-04-30 15:35:09 +0200663 valueIsZero = valueIsZero && isZero(value.Field(i))
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800664 }
665 return valueIsZero
666 case reflect.Ptr:
667 if !value.IsNil() {
668 return isZero(reflect.Indirect(value))
669 } else {
670 return true
671 }
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500672 // Always print bool/strings, if you want a bool/string attribute to be able to take the default value, use a
673 // pointer instead
674 case reflect.Bool, reflect.String:
Liz Kammerd366c902021-06-03 13:43:01 -0400675 return false
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800676 default:
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -0400677 if !value.IsValid() {
678 return true
679 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800680 zeroValue := reflect.Zero(value.Type())
681 result := value.Interface() == zeroValue.Interface()
682 return result
683 }
684}
685
686func escapeString(s string) string {
687 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +0000688
689 // b/184026959: Reverse the application of some common control sequences.
690 // These must be generated literally in the BUILD file.
691 s = strings.ReplaceAll(s, "\t", "\\t")
692 s = strings.ReplaceAll(s, "\n", "\\n")
693 s = strings.ReplaceAll(s, "\r", "\\r")
694
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800695 return strings.ReplaceAll(s, "\"", "\\\"")
696}
697
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800698func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
699 name := ""
700 if c.ModuleSubDir(logicModule) != "" {
701 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
702 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
703 } else {
704 name = c.ModuleName(logicModule)
705 }
706
707 return strings.Replace(name, "//", "", 1)
708}
709
710func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
711 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
712}