blob: b7678a4697e6e27b0e45d3e7412c2f2578b1bb60 [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
Spandan Dasabedff02023-03-07 19:24:34 +000063// PackageName returns the package of the Bazel target.
64// Defaults to root of tree.
65func (t BazelTarget) PackageName() string {
66 if t.packageName == "" {
67 return "."
68 }
69 return t.packageName
70}
71
Jingwen Chen40067de2021-01-26 21:58:43 -050072// BazelTargets is a typedef for a slice of BazelTarget objects.
73type BazelTargets []BazelTarget
74
Sasha Smundak8bea2672022-08-04 13:31:14 -070075func (targets BazelTargets) packageRule() *BazelTarget {
76 for _, target := range targets {
77 if target.ruleClass == "package" {
78 return &target
79 }
80 }
81 return nil
82}
83
84// sort a list of BazelTargets in-place, by name, and by generated/handcrafted types.
Jingwen Chen49109762021-05-25 05:16:48 +000085func (targets BazelTargets) sort() {
86 sort.Slice(targets, func(i, j int) bool {
Jingwen Chen49109762021-05-25 05:16:48 +000087 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 {
Sasha Smundak8bea2672022-08-04 13:31:14 -070097 if target.ruleClass != "package" {
98 res += target.content
99 }
Jingwen Chen40067de2021-01-26 21:58:43 -0500100 if i != len(targets)-1 {
101 res += "\n\n"
102 }
103 }
104 return res
105}
106
107// LoadStatements return the string representation of the sorted and deduplicated
108// Starlark rule load statements needed by a group of BazelTargets.
109func (targets BazelTargets) LoadStatements() string {
110 bzlToLoadedSymbols := map[string][]string{}
111 for _, target := range targets {
112 if target.IsLoadedFromStarlark() {
113 bzlToLoadedSymbols[target.bzlLoadLocation] =
114 append(bzlToLoadedSymbols[target.bzlLoadLocation], target.ruleClass)
115 }
116 }
117
118 var loadStatements []string
119 for bzl, ruleClasses := range bzlToLoadedSymbols {
120 loadStatement := "load(\""
121 loadStatement += bzl
122 loadStatement += "\", "
123 ruleClasses = android.SortedUniqueStrings(ruleClasses)
124 for i, ruleClass := range ruleClasses {
125 loadStatement += "\"" + ruleClass + "\""
126 if i != len(ruleClasses)-1 {
127 loadStatement += ", "
128 }
129 }
130 loadStatement += ")"
131 loadStatements = append(loadStatements, loadStatement)
132 }
133 return strings.Join(android.SortedUniqueStrings(loadStatements), "\n")
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800134}
135
136type bpToBuildContext interface {
137 ModuleName(module blueprint.Module) string
138 ModuleDir(module blueprint.Module) string
139 ModuleSubDir(module blueprint.Module) string
140 ModuleType(module blueprint.Module) string
141
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500142 VisitAllModules(visit func(blueprint.Module))
143 VisitDirectDeps(module blueprint.Module, visit func(blueprint.Module))
144}
145
146type CodegenContext struct {
Jingwen Chen16d90a82021-09-17 07:16:13 +0000147 config android.Config
Paul Duffinc6390592022-11-04 13:35:21 +0000148 context *android.Context
Jingwen Chen16d90a82021-09-17 07:16:13 +0000149 mode CodegenMode
150 additionalDeps []string
Liz Kammer6eff3232021-08-26 08:37:59 -0400151 unconvertedDepMode unconvertedDepsMode
Cole Faustb85d1a12022-11-08 18:14:01 -0800152 topDir string
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500153}
154
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400155func (ctx *CodegenContext) Mode() CodegenMode {
156 return ctx.mode
Jingwen Chen164e0862021-02-19 00:48:40 -0500157}
158
Jingwen Chen33832f92021-01-24 22:55:54 -0500159// CodegenMode is an enum to differentiate code-generation modes.
160type CodegenMode int
161
162const (
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400163 // Bp2Build - generate BUILD files with targets buildable by Bazel directly.
Jingwen Chen33832f92021-01-24 22:55:54 -0500164 //
165 // This mode is used for the Soong->Bazel build definition conversion.
166 Bp2Build CodegenMode = iota
167
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400168 // QueryView - generate BUILD files with targets representing fully mutated
Jingwen Chen33832f92021-01-24 22:55:54 -0500169 // Soong modules, representing the fully configured Soong module graph with
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400170 // variants and dependency edges.
Jingwen Chen33832f92021-01-24 22:55:54 -0500171 //
172 // This mode is used for discovering and introspecting the existing Soong
173 // module graph.
174 QueryView
Spandan Das5af0bd32022-09-28 20:43:08 +0000175
176 // ApiBp2build - generate BUILD files for API contribution targets
177 ApiBp2build
Jingwen Chen33832f92021-01-24 22:55:54 -0500178)
179
Liz Kammer6eff3232021-08-26 08:37:59 -0400180type unconvertedDepsMode int
181
182const (
183 // Include a warning in conversion metrics about converted modules with unconverted direct deps
184 warnUnconvertedDeps unconvertedDepsMode = iota
185 // Error and fail conversion if encountering a module with unconverted direct deps
186 // Enabled by setting environment variable `BP2BUILD_ERROR_UNCONVERTED`
187 errorModulesUnconvertedDeps
188)
189
Jingwen Chendcc329a2021-01-26 02:49:03 -0500190func (mode CodegenMode) String() string {
191 switch mode {
192 case Bp2Build:
193 return "Bp2Build"
194 case QueryView:
195 return "QueryView"
Spandan Das5af0bd32022-09-28 20:43:08 +0000196 case ApiBp2build:
197 return "ApiBp2build"
Jingwen Chendcc329a2021-01-26 02:49:03 -0500198 default:
199 return fmt.Sprintf("%d", mode)
200 }
201}
202
Liz Kammerba3ea162021-02-17 13:22:03 -0500203// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
204// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
205// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
206// call AdditionalNinjaDeps and add them manually to the ninja file.
207func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
208 ctx.additionalDeps = append(ctx.additionalDeps, deps...)
209}
210
211// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
212func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
213 return ctx.additionalDeps
214}
215
Paul Duffinc6390592022-11-04 13:35:21 +0000216func (ctx *CodegenContext) Config() android.Config { return ctx.config }
217func (ctx *CodegenContext) Context() *android.Context { return ctx.context }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500218
219// NewCodegenContext creates a wrapper context that conforms to PathContext for
220// writing BUILD files in the output directory.
Cole Faustb85d1a12022-11-08 18:14:01 -0800221func NewCodegenContext(config android.Config, context *android.Context, mode CodegenMode, topDir string) *CodegenContext {
Liz Kammer6eff3232021-08-26 08:37:59 -0400222 var unconvertedDeps unconvertedDepsMode
223 if config.IsEnvTrue("BP2BUILD_ERROR_UNCONVERTED") {
224 unconvertedDeps = errorModulesUnconvertedDeps
225 }
Liz Kammerba3ea162021-02-17 13:22:03 -0500226 return &CodegenContext{
Liz Kammer6eff3232021-08-26 08:37:59 -0400227 context: context,
228 config: config,
229 mode: mode,
230 unconvertedDepMode: unconvertedDeps,
Cole Faustb85d1a12022-11-08 18:14:01 -0800231 topDir: topDir,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500232 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800233}
234
235// props is an unsorted map. This function ensures that
236// the generated attributes are sorted to ensure determinism.
237func propsToAttributes(props map[string]string) string {
238 var attributes string
Cole Faust18994c72023-02-28 16:02:16 -0800239 for _, propName := range android.SortedKeys(props) {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400240 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800241 }
242 return attributes
243}
244
Liz Kammer6eff3232021-08-26 08:37:59 -0400245type conversionResults struct {
246 buildFileToTargets map[string]BazelTargets
247 metrics CodegenMetrics
Liz Kammer6eff3232021-08-26 08:37:59 -0400248}
249
250func (r conversionResults) BuildDirToTargets() map[string]BazelTargets {
251 return r.buildFileToTargets
252}
253
254func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (conversionResults, []error) {
Jingwen Chen40067de2021-01-26 21:58:43 -0500255 buildFileToTargets := make(map[string]BazelTargets)
Jingwen Chen164e0862021-02-19 00:48:40 -0500256
257 // Simple metrics tracking for bp2build
usta4f5d2c12022-10-28 23:32:01 -0400258 metrics := CreateCodegenMetrics()
Jingwen Chen164e0862021-02-19 00:48:40 -0500259
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400260 dirs := make(map[string]bool)
261
Liz Kammer6eff3232021-08-26 08:37:59 -0400262 var errs []error
263
Jingwen Chen164e0862021-02-19 00:48:40 -0500264 bpCtx := ctx.Context()
265 bpCtx.VisitAllModules(func(m blueprint.Module) {
266 dir := bpCtx.ModuleDir(m)
Chris Parsons492bd912022-01-20 12:55:05 -0500267 moduleType := bpCtx.ModuleType(m)
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400268 dirs[dir] = true
269
Liz Kammer2ada09a2021-08-11 00:17:36 -0400270 var targets []BazelTarget
Jingwen Chen73850672020-12-14 08:25:34 -0500271
Jingwen Chen164e0862021-02-19 00:48:40 -0500272 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500273 case Bp2Build:
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000274 // There are two main ways of converting a Soong module to Bazel:
275 // 1) Manually handcrafting a Bazel target and associating the module with its label
276 // 2) Automatically generating with bp2build converters
277 //
278 // bp2build converters are used for the majority of modules.
Liz Kammerba3ea162021-02-17 13:22:03 -0500279 if b, ok := m.(android.Bazelable); ok && b.HasHandcraftedLabel() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000280 // Handle modules converted to handcrafted targets.
281 //
282 // Since these modules are associated with some handcrafted
Cole Faustea602c52022-08-31 14:48:26 -0700283 // target in a BUILD file, we don't autoconvert them.
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000284
285 // Log the module.
Kevin Dagostino60f562a2022-09-20 03:54:47 +0000286 metrics.AddConvertedModule(m, moduleType, dir, Handcrafted)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400287 } else if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000288 // Handle modules converted to generated targets.
289
290 // Log the module.
Kevin Dagostino60f562a2022-09-20 03:54:47 +0000291 metrics.AddConvertedModule(aModule, moduleType, dir, Generated)
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000292
293 // Handle modules with unconverted deps. By default, emit a warning.
Liz Kammer6eff3232021-08-26 08:37:59 -0400294 if unconvertedDeps := aModule.GetUnconvertedBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700295 msg := fmt.Sprintf("%s %s:%s depends on unconverted 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 Kammer6eff3232021-08-26 08:37:59 -0400299 metrics.moduleWithUnconvertedDepsMsgs = append(metrics.moduleWithUnconvertedDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400300 case errorModulesUnconvertedDeps:
Liz Kammer6eff3232021-08-26 08:37:59 -0400301 errs = append(errs, fmt.Errorf(msg))
302 return
303 }
304 }
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500305 if unconvertedDeps := aModule.GetMissingBp2buildDeps(); len(unconvertedDeps) > 0 {
Sasha Smundakf2bb26f2022-08-04 11:28:15 -0700306 msg := fmt.Sprintf("%s %s:%s depends on missing modules: %s",
307 moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", "))
Usta Shresthac6057152022-09-24 00:23:31 -0400308 switch ctx.unconvertedDepMode {
309 case warnUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500310 metrics.moduleWithMissingDepsMsgs = append(metrics.moduleWithMissingDepsMsgs, msg)
Usta Shresthac6057152022-09-24 00:23:31 -0400311 case errorModulesUnconvertedDeps:
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500312 errs = append(errs, fmt.Errorf(msg))
313 return
314 }
315 }
Alix94e26032022-08-16 20:37:33 +0000316 var targetErrs []error
317 targets, targetErrs = generateBazelTargets(bpCtx, aModule)
318 errs = append(errs, targetErrs...)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400319 for _, t := range targets {
Jingwen Chen310bc8f2021-09-20 10:54:27 +0000320 // A module can potentially generate more than 1 Bazel
321 // target, each of a different rule class.
322 metrics.IncrementRuleClassCount(t.ruleClass)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400323 }
MarkDacek9c094ca2023-03-16 19:15:19 +0000324 } else if _, ok := ctx.Config().BazelModulesForceEnabledByFlag()[m.Name()]; ok && m.Name() != "" {
325 err := fmt.Errorf("Force Enabled Module %s not converted", m.Name())
326 errs = append(errs, err)
Liz Kammerfc46bc12021-02-19 11:06:17 -0500327 } else {
Chris Parsons492bd912022-01-20 12:55:05 -0500328 metrics.AddUnconvertedModule(moduleType)
Liz Kammerba3ea162021-02-17 13:22:03 -0500329 return
Jingwen Chen73850672020-12-14 08:25:34 -0500330 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500331 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500332 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500333 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500334 // package module name contain slashes, and thus cannot
335 // be mapped cleanly to a bazel label.
336 return
337 }
Alix94e26032022-08-16 20:37:33 +0000338 t, err := generateSoongModuleTarget(bpCtx, m)
339 if err != nil {
340 errs = append(errs, err)
341 }
Liz Kammer2ada09a2021-08-11 00:17:36 -0400342 targets = append(targets, t)
Spandan Das5af0bd32022-09-28 20:43:08 +0000343 case ApiBp2build:
344 if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() {
345 targets, errs = generateBazelTargets(bpCtx, aModule)
346 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500347 default:
Liz Kammer6eff3232021-08-26 08:37:59 -0400348 errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
349 return
Jingwen Chen73850672020-12-14 08:25:34 -0500350 }
351
Spandan Dasabedff02023-03-07 19:24:34 +0000352 for _, target := range targets {
353 targetDir := target.PackageName()
354 buildFileToTargets[targetDir] = append(buildFileToTargets[targetDir], target)
355 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800356 })
Liz Kammer6eff3232021-08-26 08:37:59 -0400357
358 if len(errs) > 0 {
359 return conversionResults{}, errs
360 }
361
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400362 if generateFilegroups {
363 // Add a filegroup target that exposes all sources in the subtree of this package
364 // 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 -0700365 //
366 // This works because: https://bazel.build/reference/be/functions#exports_files
367 // "As a legacy behaviour, also files mentioned as input to a rule are exported with the
368 // default visibility until the flag --incompatible_no_implicit_file_export is flipped. However, this behavior
369 // should not be relied upon and actively migrated away from."
370 //
371 // TODO(b/198619163): We should change this to export_files(glob(["**/*"])) instead, but doing that causes these errors:
372 // "Error in exports_files: generated label '//external/avb:avbtool' conflicts with existing py_binary rule"
373 // So we need to solve all the "target ... is both a rule and a file" warnings first.
Usta Shresthac6057152022-09-24 00:23:31 -0400374 for dir := range dirs {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400375 buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{
376 name: "bp2build_all_srcs",
377 content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]))`,
378 ruleClass: "filegroup",
379 })
380 }
381 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500382
Liz Kammer6eff3232021-08-26 08:37:59 -0400383 return conversionResults{
384 buildFileToTargets: buildFileToTargets,
385 metrics: metrics,
Liz Kammer6eff3232021-08-26 08:37:59 -0400386 }, errs
Jingwen Chen164e0862021-02-19 00:48:40 -0500387}
388
Alix94e26032022-08-16 20:37:33 +0000389func generateBazelTargets(ctx bpToBuildContext, m android.Module) ([]BazelTarget, []error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400390 var targets []BazelTarget
Alix94e26032022-08-16 20:37:33 +0000391 var errs []error
Liz Kammer2ada09a2021-08-11 00:17:36 -0400392 for _, m := range m.Bp2buildTargets() {
Alix94e26032022-08-16 20:37:33 +0000393 target, err := generateBazelTarget(ctx, m)
394 if err != nil {
395 errs = append(errs, err)
396 return targets, errs
397 }
398 targets = append(targets, target)
Liz Kammer2ada09a2021-08-11 00:17:36 -0400399 }
Alix94e26032022-08-16 20:37:33 +0000400 return targets, errs
Liz Kammer2ada09a2021-08-11 00:17:36 -0400401}
402
403type bp2buildModule interface {
404 TargetName() string
405 TargetPackage() string
406 BazelRuleClass() string
407 BazelRuleLoadLocation() string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000408 BazelAttributes() []interface{}
Liz Kammer2ada09a2021-08-11 00:17:36 -0400409}
410
Alix94e26032022-08-16 20:37:33 +0000411func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) (BazelTarget, error) {
Liz Kammer2ada09a2021-08-11 00:17:36 -0400412 ruleClass := m.BazelRuleClass()
413 bzlLoadLocation := m.BazelRuleLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500414
Jingwen Chen73850672020-12-14 08:25:34 -0500415 // extract the bazel attributes from the module.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000416 attrs := m.BazelAttributes()
Alix94e26032022-08-16 20:37:33 +0000417 props, err := extractModuleProperties(attrs, true)
418 if err != nil {
419 return BazelTarget{}, err
420 }
Jingwen Chen73850672020-12-14 08:25:34 -0500421
Liz Kammer0eae52e2021-10-06 10:32:26 -0400422 // name is handled in a special manner
423 delete(props.Attrs, "name")
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500424
Jingwen Chen73850672020-12-14 08:25:34 -0500425 // Return the Bazel target with rule class and attributes, ready to be
426 // code-generated.
427 attributes := propsToAttributes(props.Attrs)
Sasha Smundakfb589492022-08-04 11:13:27 -0700428 var content string
Liz Kammer2ada09a2021-08-11 00:17:36 -0400429 targetName := m.TargetName()
Sasha Smundakfb589492022-08-04 11:13:27 -0700430 if targetName != "" {
431 content = fmt.Sprintf(ruleTargetTemplate, ruleClass, targetName, attributes)
432 } else {
433 content = fmt.Sprintf(unnamedRuleTargetTemplate, ruleClass, attributes)
434 }
Jingwen Chen73850672020-12-14 08:25:34 -0500435 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500436 name: targetName,
Liz Kammer2ada09a2021-08-11 00:17:36 -0400437 packageName: m.TargetPackage(),
Jingwen Chen40067de2021-01-26 21:58:43 -0500438 ruleClass: ruleClass,
439 bzlLoadLocation: bzlLoadLocation,
Sasha Smundakfb589492022-08-04 11:13:27 -0700440 content: content,
Alix94e26032022-08-16 20:37:33 +0000441 }, nil
Jingwen Chen73850672020-12-14 08:25:34 -0500442}
443
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800444// Convert a module and its deps and props into a Bazel macro/rule
445// representation in the BUILD file.
Alix94e26032022-08-16 20:37:33 +0000446func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) (BazelTarget, error) {
447 props, err := getBuildProperties(ctx, m)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800448
449 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
450 // items, if the modules are added using different DependencyTag. Figure
451 // out the implications of that.
452 depLabels := map[string]bool{}
453 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500454 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800455 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
456 })
457 }
Liz Kammer0eae52e2021-10-06 10:32:26 -0400458
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400459 for p := range ignoredPropNames {
Liz Kammer0eae52e2021-10-06 10:32:26 -0400460 delete(props.Attrs, p)
461 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800462 attributes := propsToAttributes(props.Attrs)
463
464 depLabelList := "[\n"
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400465 for depLabel := range depLabels {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800466 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
467 }
468 depLabelList += " ]"
469
470 targetName := targetNameWithVariant(ctx, m)
471 return BazelTarget{
Spandan Dasabedff02023-03-07 19:24:34 +0000472 name: targetName,
473 packageName: ctx.ModuleDir(m),
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800474 content: fmt.Sprintf(
Sasha Smundakfb589492022-08-04 11:13:27 -0700475 soongModuleTargetTemplate,
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800476 targetName,
477 ctx.ModuleName(m),
478 canonicalizeModuleType(ctx.ModuleType(m)),
479 ctx.ModuleSubDir(m),
480 depLabelList,
481 attributes),
Alix94e26032022-08-16 20:37:33 +0000482 }, err
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800483}
484
Alix94e26032022-08-16 20:37:33 +0000485func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800486 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
487 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
488 if aModule, ok := m.(android.Module); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000489 return extractModuleProperties(aModule.GetProperties(), false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800490 }
491
Alix94e26032022-08-16 20:37:33 +0000492 return BazelAttributes{}, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800493}
494
495// Generically extract module properties and types into a map, keyed by the module property name.
Alix94e26032022-08-16 20:37:33 +0000496func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) (BazelAttributes, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800497 ret := map[string]string{}
498
499 // Iterate over this android.Module's property structs.
Liz Kammer2ada09a2021-08-11 00:17:36 -0400500 for _, properties := range props {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800501 propertiesValue := reflect.ValueOf(properties)
502 // Check that propertiesValue is a pointer to the Properties struct, like
503 // *cc.BaseLinkerProperties or *java.CompilerProperties.
504 //
505 // propertiesValue can also be type-asserted to the structs to
506 // manipulate internal props, if needed.
507 if isStructPtr(propertiesValue.Type()) {
508 structValue := propertiesValue.Elem()
Alix94e26032022-08-16 20:37:33 +0000509 ok, err := extractStructProperties(structValue, 0)
510 if err != nil {
511 return BazelAttributes{}, err
512 }
513 for k, v := range ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000514 if existing, exists := ret[k]; checkForDuplicateProperties && exists {
Alix94e26032022-08-16 20:37:33 +0000515 return BazelAttributes{}, fmt.Errorf(
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000516 "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes",
Alix94e26032022-08-16 20:37:33 +0000517 k, existing)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000518 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800519 ret[k] = v
520 }
521 } else {
Alix94e26032022-08-16 20:37:33 +0000522 return BazelAttributes{},
523 fmt.Errorf(
524 "properties must be a pointer to a struct, got %T",
525 propertiesValue.Interface())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800526 }
527 }
528
Liz Kammer2ada09a2021-08-11 00:17:36 -0400529 return BazelAttributes{
530 Attrs: ret,
Alix94e26032022-08-16 20:37:33 +0000531 }, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800532}
533
534func isStructPtr(t reflect.Type) bool {
535 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
536}
537
538// prettyPrint a property value into the equivalent Starlark representation
539// recursively.
Jingwen Chen58ff6802021-11-17 12:14:41 +0000540func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) {
541 if !emitZeroValues && isZero(propertyValue) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800542 // A property value being set or unset actually matters -- Soong does set default
543 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
544 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
545 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +0000546 // In Bazel-parlance, we would use "attr.<type>(default = <default
547 // value>)" to set the default value of unset attributes. In the cases
548 // where the bp2build converter didn't set the default value within the
549 // mutator when creating the BazelTargetModule, this would be a zero
Jingwen Chen63930982021-03-24 10:04:33 -0400550 // value. For those cases, we return an empty string so we don't
551 // unnecessarily generate empty values.
552 return "", nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800553 }
554
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800555 switch propertyValue.Kind() {
556 case reflect.String:
Liz Kammer72beb342022-02-03 08:42:10 -0500557 return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800558 case reflect.Bool:
Liz Kammer72beb342022-02-03 08:42:10 -0500559 return starlark_fmt.PrintBool(propertyValue.Bool()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800560 case reflect.Int, reflect.Uint, reflect.Int64:
Liz Kammer72beb342022-02-03 08:42:10 -0500561 return fmt.Sprintf("%v", propertyValue.Interface()), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800562 case reflect.Ptr:
Jingwen Chen58ff6802021-11-17 12:14:41 +0000563 return prettyPrint(propertyValue.Elem(), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800564 case reflect.Slice:
Liz Kammer72beb342022-02-03 08:42:10 -0500565 elements := make([]string, 0, propertyValue.Len())
566 for i := 0; i < propertyValue.Len(); i++ {
567 val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800568 if err != nil {
569 return "", err
570 }
Liz Kammer72beb342022-02-03 08:42:10 -0500571 if val != "" {
572 elements = append(elements, val)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800573 }
574 }
Sam Delmerico932c01c2022-03-25 16:33:26 +0000575 return starlark_fmt.PrintList(elements, indent, func(s string) string {
576 return "%s"
577 }), nil
Jingwen Chenb4628eb2021-04-08 14:40:57 +0000578
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800579 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -0500580 // Special cases where the bp2build sends additional information to the codegenerator
581 // by wrapping the attributes in a custom struct type.
Jingwen Chenc1c26502021-04-05 10:35:13 +0000582 if attr, ok := propertyValue.Interface().(bazel.Attribute); ok {
583 return prettyPrintAttribute(attr, indent)
Liz Kammer356f7d42021-01-26 09:18:53 -0500584 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
585 return fmt.Sprintf("%q", label.Label), nil
586 }
587
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800588 // Sort and print the struct props by the key.
Alix94e26032022-08-16 20:37:33 +0000589 structProps, err := extractStructProperties(propertyValue, indent)
590
591 if err != nil {
592 return "", err
593 }
594
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000595 if len(structProps) == 0 {
596 return "", nil
597 }
Liz Kammer72beb342022-02-03 08:42:10 -0500598 return starlark_fmt.PrintDict(structProps, indent), nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800599 case reflect.Interface:
600 // TODO(b/164227191): implement pretty print for interfaces.
601 // Interfaces are used for for arch, multilib and target properties.
602 return "", nil
603 default:
604 return "", fmt.Errorf(
605 "unexpected kind for property struct field: %s", propertyValue.Kind())
606 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800607}
608
609// Converts a reflected property struct value into a map of property names and property values,
610// which each property value correctly pretty-printed and indented at the right nest level,
611// since property structs can be nested. In Starlark, nested structs are represented as nested
612// dicts: https://docs.bazel.build/skylark/lib/dict.html
Alix94e26032022-08-16 20:37:33 +0000613func extractStructProperties(structValue reflect.Value, indent int) (map[string]string, error) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800614 if structValue.Kind() != reflect.Struct {
Alix94e26032022-08-16 20:37:33 +0000615 return map[string]string{}, fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind())
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800616 }
617
Alix94e26032022-08-16 20:37:33 +0000618 var err error
619
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800620 ret := map[string]string{}
621 structType := structValue.Type()
622 for i := 0; i < structValue.NumField(); i++ {
623 field := structType.Field(i)
624 if shouldSkipStructField(field) {
625 continue
626 }
627
628 fieldValue := structValue.Field(i)
629 if isZero(fieldValue) {
630 // Ignore zero-valued fields
631 continue
632 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400633
Liz Kammer32a03392021-09-14 11:17:21 -0400634 // if the struct is embedded (anonymous), flatten the properties into the containing struct
635 if field.Anonymous {
636 if field.Type.Kind() == reflect.Ptr {
637 fieldValue = fieldValue.Elem()
638 }
639 if fieldValue.Type().Kind() == reflect.Struct {
Alix94e26032022-08-16 20:37:33 +0000640 propsToMerge, err := extractStructProperties(fieldValue, indent)
641 if err != nil {
642 return map[string]string{}, err
643 }
Liz Kammer32a03392021-09-14 11:17:21 -0400644 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)
Alix94e26032022-08-16 20:37:33 +0000652 var prettyPrintedValue string
653 prettyPrintedValue, err = prettyPrint(fieldValue, indent+1, false)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800654 if err != nil {
Alix94e26032022-08-16 20:37:33 +0000655 return map[string]string{}, fmt.Errorf(
656 "Error while parsing property: %q. %s",
657 propertyName,
658 err)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800659 }
660 if prettyPrintedValue != "" {
661 ret[propertyName] = prettyPrintedValue
662 }
663 }
664
Alix94e26032022-08-16 20:37:33 +0000665 return ret, nil
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800666}
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}