Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 1 | // 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 | |
| 15 | package bp2build |
| 16 | |
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux | 0da7ce6 | 2021-08-23 17:04:20 +0000 | [diff] [blame] | 17 | /* |
| 18 | For shareable/common functionality for conversion from soong-module to build files |
| 19 | for queryview/bp2build |
| 20 | */ |
| 21 | |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 22 | import ( |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 23 | "fmt" |
| 24 | "reflect" |
Jingwen Chen | 4910976 | 2021-05-25 05:16:48 +0000 | [diff] [blame] | 25 | "sort" |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 26 | "strings" |
| 27 | |
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux | 0da7ce6 | 2021-08-23 17:04:20 +0000 | [diff] [blame] | 28 | "android/soong/android" |
| 29 | "android/soong/bazel" |
Liz Kammer | 72beb34 | 2022-02-03 08:42:10 -0500 | [diff] [blame] | 30 | "android/soong/starlark_fmt" |
Chris Parsons | 39a1697 | 2023-06-08 14:28:51 +0000 | [diff] [blame] | 31 | "android/soong/ui/metrics/bp2build_metrics_proto" |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 32 | "github.com/google/blueprint" |
Spandan Das | ea2abba | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 33 | "github.com/google/blueprint/bootstrap" |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 34 | "github.com/google/blueprint/proptools" |
| 35 | ) |
| 36 | |
| 37 | type BazelAttributes struct { |
| 38 | Attrs map[string]string |
| 39 | } |
| 40 | |
| 41 | type BazelTarget struct { |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 42 | name string |
Jingwen Chen | c63677b | 2021-06-17 05:43:19 +0000 | [diff] [blame] | 43 | packageName string |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 44 | content string |
| 45 | ruleClass string |
| 46 | bzlLoadLocation string |
| 47 | } |
| 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. |
| 51 | func (t BazelTarget) IsLoadedFromStarlark() bool { |
| 52 | return t.bzlLoadLocation != "" |
| 53 | } |
| 54 | |
Jingwen Chen | c63677b | 2021-06-17 05:43:19 +0000 | [diff] [blame] | 55 | // Label is the fully qualified Bazel label constructed from the BazelTarget's |
| 56 | // package name and target name. |
| 57 | func (t BazelTarget) Label() string { |
| 58 | if t.packageName == "." { |
| 59 | return "//:" + t.name |
| 60 | } else { |
| 61 | return "//" + t.packageName + ":" + t.name |
| 62 | } |
| 63 | } |
| 64 | |
Spandan Das | abedff0 | 2023-03-07 19:24:34 +0000 | [diff] [blame] | 65 | // PackageName returns the package of the Bazel target. |
| 66 | // Defaults to root of tree. |
| 67 | func (t BazelTarget) PackageName() string { |
| 68 | if t.packageName == "" { |
| 69 | return "." |
| 70 | } |
| 71 | return t.packageName |
| 72 | } |
| 73 | |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 74 | // BazelTargets is a typedef for a slice of BazelTarget objects. |
| 75 | type BazelTargets []BazelTarget |
| 76 | |
Sasha Smundak | 8bea267 | 2022-08-04 13:31:14 -0700 | [diff] [blame] | 77 | func (targets BazelTargets) packageRule() *BazelTarget { |
| 78 | for _, target := range targets { |
| 79 | if target.ruleClass == "package" { |
| 80 | return &target |
| 81 | } |
| 82 | } |
| 83 | return nil |
| 84 | } |
| 85 | |
| 86 | // sort a list of BazelTargets in-place, by name, and by generated/handcrafted types. |
Jingwen Chen | 4910976 | 2021-05-25 05:16:48 +0000 | [diff] [blame] | 87 | func (targets BazelTargets) sort() { |
| 88 | sort.Slice(targets, func(i, j int) bool { |
Jingwen Chen | 4910976 | 2021-05-25 05:16:48 +0000 | [diff] [blame] | 89 | return targets[i].name < targets[j].name |
| 90 | }) |
| 91 | } |
| 92 | |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 93 | // String returns the string representation of BazelTargets, without load |
| 94 | // statements (use LoadStatements for that), since the targets are usually not |
| 95 | // adjacent to the load statements at the top of the BUILD file. |
| 96 | func (targets BazelTargets) String() string { |
| 97 | var res string |
| 98 | for i, target := range targets { |
Sasha Smundak | 8bea267 | 2022-08-04 13:31:14 -0700 | [diff] [blame] | 99 | if target.ruleClass != "package" { |
| 100 | res += target.content |
| 101 | } |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 102 | if i != len(targets)-1 { |
| 103 | res += "\n\n" |
| 104 | } |
| 105 | } |
| 106 | return res |
| 107 | } |
| 108 | |
| 109 | // LoadStatements return the string representation of the sorted and deduplicated |
| 110 | // Starlark rule load statements needed by a group of BazelTargets. |
| 111 | func (targets BazelTargets) LoadStatements() string { |
| 112 | bzlToLoadedSymbols := map[string][]string{} |
| 113 | for _, target := range targets { |
| 114 | if target.IsLoadedFromStarlark() { |
| 115 | bzlToLoadedSymbols[target.bzlLoadLocation] = |
| 116 | append(bzlToLoadedSymbols[target.bzlLoadLocation], target.ruleClass) |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | var loadStatements []string |
| 121 | for bzl, ruleClasses := range bzlToLoadedSymbols { |
| 122 | loadStatement := "load(\"" |
| 123 | loadStatement += bzl |
| 124 | loadStatement += "\", " |
| 125 | ruleClasses = android.SortedUniqueStrings(ruleClasses) |
| 126 | for i, ruleClass := range ruleClasses { |
| 127 | loadStatement += "\"" + ruleClass + "\"" |
| 128 | if i != len(ruleClasses)-1 { |
| 129 | loadStatement += ", " |
| 130 | } |
| 131 | } |
| 132 | loadStatement += ")" |
| 133 | loadStatements = append(loadStatements, loadStatement) |
| 134 | } |
| 135 | return strings.Join(android.SortedUniqueStrings(loadStatements), "\n") |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 136 | } |
| 137 | |
| 138 | type bpToBuildContext interface { |
| 139 | ModuleName(module blueprint.Module) string |
| 140 | ModuleDir(module blueprint.Module) string |
| 141 | ModuleSubDir(module blueprint.Module) string |
| 142 | ModuleType(module blueprint.Module) string |
| 143 | |
Jingwen Chen | daa54bc | 2020-12-14 02:58:54 -0500 | [diff] [blame] | 144 | VisitAllModules(visit func(blueprint.Module)) |
| 145 | VisitDirectDeps(module blueprint.Module, visit func(blueprint.Module)) |
| 146 | } |
| 147 | |
| 148 | type CodegenContext struct { |
Jingwen Chen | 16d90a8 | 2021-09-17 07:16:13 +0000 | [diff] [blame] | 149 | config android.Config |
Paul Duffin | c639059 | 2022-11-04 13:35:21 +0000 | [diff] [blame] | 150 | context *android.Context |
Jingwen Chen | 16d90a8 | 2021-09-17 07:16:13 +0000 | [diff] [blame] | 151 | mode CodegenMode |
| 152 | additionalDeps []string |
Liz Kammer | 6eff323 | 2021-08-26 08:37:59 -0400 | [diff] [blame] | 153 | unconvertedDepMode unconvertedDepsMode |
Cole Faust | b85d1a1 | 2022-11-08 18:14:01 -0800 | [diff] [blame] | 154 | topDir string |
Jingwen Chen | daa54bc | 2020-12-14 02:58:54 -0500 | [diff] [blame] | 155 | } |
| 156 | |
Usta Shrestha | db46a9b | 2022-07-11 11:29:56 -0400 | [diff] [blame] | 157 | func (ctx *CodegenContext) Mode() CodegenMode { |
| 158 | return ctx.mode |
Jingwen Chen | 164e086 | 2021-02-19 00:48:40 -0500 | [diff] [blame] | 159 | } |
| 160 | |
Jingwen Chen | 33832f9 | 2021-01-24 22:55:54 -0500 | [diff] [blame] | 161 | // CodegenMode is an enum to differentiate code-generation modes. |
| 162 | type CodegenMode int |
| 163 | |
| 164 | const ( |
Usta Shrestha | db46a9b | 2022-07-11 11:29:56 -0400 | [diff] [blame] | 165 | // Bp2Build - generate BUILD files with targets buildable by Bazel directly. |
Jingwen Chen | 33832f9 | 2021-01-24 22:55:54 -0500 | [diff] [blame] | 166 | // |
| 167 | // This mode is used for the Soong->Bazel build definition conversion. |
| 168 | Bp2Build CodegenMode = iota |
| 169 | |
Usta Shrestha | db46a9b | 2022-07-11 11:29:56 -0400 | [diff] [blame] | 170 | // QueryView - generate BUILD files with targets representing fully mutated |
Jingwen Chen | 33832f9 | 2021-01-24 22:55:54 -0500 | [diff] [blame] | 171 | // Soong modules, representing the fully configured Soong module graph with |
Usta Shrestha | db46a9b | 2022-07-11 11:29:56 -0400 | [diff] [blame] | 172 | // variants and dependency edges. |
Jingwen Chen | 33832f9 | 2021-01-24 22:55:54 -0500 | [diff] [blame] | 173 | // |
| 174 | // This mode is used for discovering and introspecting the existing Soong |
| 175 | // module graph. |
| 176 | QueryView |
Spandan Das | 5af0bd3 | 2022-09-28 20:43:08 +0000 | [diff] [blame] | 177 | |
| 178 | // ApiBp2build - generate BUILD files for API contribution targets |
| 179 | ApiBp2build |
Jingwen Chen | 33832f9 | 2021-01-24 22:55:54 -0500 | [diff] [blame] | 180 | ) |
| 181 | |
Liz Kammer | 6eff323 | 2021-08-26 08:37:59 -0400 | [diff] [blame] | 182 | type unconvertedDepsMode int |
| 183 | |
| 184 | const ( |
| 185 | // Include a warning in conversion metrics about converted modules with unconverted direct deps |
| 186 | warnUnconvertedDeps unconvertedDepsMode = iota |
| 187 | // Error and fail conversion if encountering a module with unconverted direct deps |
| 188 | // Enabled by setting environment variable `BP2BUILD_ERROR_UNCONVERTED` |
| 189 | errorModulesUnconvertedDeps |
| 190 | ) |
| 191 | |
Jingwen Chen | dcc329a | 2021-01-26 02:49:03 -0500 | [diff] [blame] | 192 | func (mode CodegenMode) String() string { |
| 193 | switch mode { |
| 194 | case Bp2Build: |
| 195 | return "Bp2Build" |
| 196 | case QueryView: |
| 197 | return "QueryView" |
Spandan Das | 5af0bd3 | 2022-09-28 20:43:08 +0000 | [diff] [blame] | 198 | case ApiBp2build: |
| 199 | return "ApiBp2build" |
Jingwen Chen | dcc329a | 2021-01-26 02:49:03 -0500 | [diff] [blame] | 200 | default: |
| 201 | return fmt.Sprintf("%d", mode) |
| 202 | } |
| 203 | } |
| 204 | |
Liz Kammer | ba3ea16 | 2021-02-17 13:22:03 -0500 | [diff] [blame] | 205 | // AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The |
| 206 | // primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the |
| 207 | // PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also |
| 208 | // call AdditionalNinjaDeps and add them manually to the ninja file. |
| 209 | func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) { |
| 210 | ctx.additionalDeps = append(ctx.additionalDeps, deps...) |
| 211 | } |
| 212 | |
| 213 | // AdditionalNinjaDeps returns additional ninja deps added by CodegenContext |
| 214 | func (ctx *CodegenContext) AdditionalNinjaDeps() []string { |
| 215 | return ctx.additionalDeps |
| 216 | } |
| 217 | |
Paul Duffin | c639059 | 2022-11-04 13:35:21 +0000 | [diff] [blame] | 218 | func (ctx *CodegenContext) Config() android.Config { return ctx.config } |
| 219 | func (ctx *CodegenContext) Context() *android.Context { return ctx.context } |
Jingwen Chen | daa54bc | 2020-12-14 02:58:54 -0500 | [diff] [blame] | 220 | |
| 221 | // NewCodegenContext creates a wrapper context that conforms to PathContext for |
| 222 | // writing BUILD files in the output directory. |
Cole Faust | b85d1a1 | 2022-11-08 18:14:01 -0800 | [diff] [blame] | 223 | func NewCodegenContext(config android.Config, context *android.Context, mode CodegenMode, topDir string) *CodegenContext { |
Liz Kammer | 6eff323 | 2021-08-26 08:37:59 -0400 | [diff] [blame] | 224 | var unconvertedDeps unconvertedDepsMode |
| 225 | if config.IsEnvTrue("BP2BUILD_ERROR_UNCONVERTED") { |
| 226 | unconvertedDeps = errorModulesUnconvertedDeps |
| 227 | } |
Liz Kammer | ba3ea16 | 2021-02-17 13:22:03 -0500 | [diff] [blame] | 228 | return &CodegenContext{ |
Liz Kammer | 6eff323 | 2021-08-26 08:37:59 -0400 | [diff] [blame] | 229 | context: context, |
| 230 | config: config, |
| 231 | mode: mode, |
| 232 | unconvertedDepMode: unconvertedDeps, |
Cole Faust | b85d1a1 | 2022-11-08 18:14:01 -0800 | [diff] [blame] | 233 | topDir: topDir, |
Jingwen Chen | daa54bc | 2020-12-14 02:58:54 -0500 | [diff] [blame] | 234 | } |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 235 | } |
| 236 | |
| 237 | // props is an unsorted map. This function ensures that |
| 238 | // the generated attributes are sorted to ensure determinism. |
| 239 | func propsToAttributes(props map[string]string) string { |
| 240 | var attributes string |
Cole Faust | 18994c7 | 2023-02-28 16:02:16 -0800 | [diff] [blame] | 241 | for _, propName := range android.SortedKeys(props) { |
Liz Kammer | 0eae52e | 2021-10-06 10:32:26 -0400 | [diff] [blame] | 242 | attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName]) |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 243 | } |
| 244 | return attributes |
| 245 | } |
| 246 | |
Liz Kammer | 6eff323 | 2021-08-26 08:37:59 -0400 | [diff] [blame] | 247 | type conversionResults struct { |
| 248 | buildFileToTargets map[string]BazelTargets |
| 249 | metrics CodegenMetrics |
Liz Kammer | 6eff323 | 2021-08-26 08:37:59 -0400 | [diff] [blame] | 250 | } |
| 251 | |
| 252 | func (r conversionResults) BuildDirToTargets() map[string]BazelTargets { |
| 253 | return r.buildFileToTargets |
| 254 | } |
| 255 | |
Spandan Das | ea2abba | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 256 | // struct to store state of go bazel targets |
| 257 | // this implements bp2buildModule interface and is passed to generateBazelTargets |
| 258 | type goBazelTarget struct { |
| 259 | targetName string |
| 260 | targetPackage string |
| 261 | bazelRuleClass string |
| 262 | bazelRuleLoadLocation string |
| 263 | bazelAttributes []interface{} |
| 264 | } |
| 265 | |
| 266 | var _ bp2buildModule = (*goBazelTarget)(nil) |
| 267 | |
| 268 | func (g goBazelTarget) TargetName() string { |
| 269 | return g.targetName |
| 270 | } |
| 271 | |
| 272 | func (g goBazelTarget) TargetPackage() string { |
| 273 | return g.targetPackage |
| 274 | } |
| 275 | |
| 276 | func (g goBazelTarget) BazelRuleClass() string { |
| 277 | return g.bazelRuleClass |
| 278 | } |
| 279 | |
| 280 | func (g goBazelTarget) BazelRuleLoadLocation() string { |
| 281 | return g.bazelRuleLoadLocation |
| 282 | } |
| 283 | |
| 284 | func (g goBazelTarget) BazelAttributes() []interface{} { |
| 285 | return g.bazelAttributes |
| 286 | } |
| 287 | |
| 288 | // Creates a target_compatible_with entry that is *not* compatible with android |
| 289 | func targetNotCompatibleWithAndroid() bazel.LabelListAttribute { |
| 290 | ret := bazel.LabelListAttribute{} |
| 291 | ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsAndroid, |
| 292 | bazel.MakeLabelList( |
| 293 | []bazel.Label{ |
| 294 | bazel.Label{ |
| 295 | Label: "@platforms//:incompatible", |
| 296 | }, |
| 297 | }, |
| 298 | ), |
| 299 | ) |
| 300 | return ret |
| 301 | } |
| 302 | |
| 303 | // helper function to return labels for srcs used in bootstrap_go_package and bootstrap_go_binary |
| 304 | // this function has the following limitations which make it unsuitable for widespread use |
Spandan Das | 0a8a275 | 2023-06-21 01:50:33 +0000 | [diff] [blame] | 305 | // - wildcard patterns in srcs |
| 306 | // This is ok for go since build/blueprint does not support it. |
Spandan Das | ea2abba | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 307 | // |
| 308 | // Prefer to use `BazelLabelForModuleSrc` instead |
Spandan Das | 0a8a275 | 2023-06-21 01:50:33 +0000 | [diff] [blame] | 309 | func goSrcLabels(cfg android.Config, moduleDir string, srcs []string, linuxSrcs, darwinSrcs []string) bazel.LabelListAttribute { |
Spandan Das | ea2abba | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 310 | labels := func(srcs []string) bazel.LabelList { |
| 311 | ret := []bazel.Label{} |
| 312 | for _, src := range srcs { |
| 313 | srcLabel := bazel.Label{ |
Spandan Das | 0a8a275 | 2023-06-21 01:50:33 +0000 | [diff] [blame] | 314 | Label: src, |
Spandan Das | ea2abba | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 315 | } |
| 316 | ret = append(ret, srcLabel) |
| 317 | } |
Spandan Das | 0a8a275 | 2023-06-21 01:50:33 +0000 | [diff] [blame] | 318 | // Respect package boundaries |
| 319 | return android.TransformSubpackagePaths( |
| 320 | cfg, |
| 321 | moduleDir, |
| 322 | bazel.MakeLabelList(ret), |
| 323 | ) |
Spandan Das | ea2abba | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 324 | } |
| 325 | |
| 326 | ret := bazel.LabelListAttribute{} |
| 327 | // common |
| 328 | ret.SetSelectValue(bazel.NoConfigAxis, "", labels(srcs)) |
| 329 | // linux |
| 330 | ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsLinux, labels(linuxSrcs)) |
| 331 | // darwin |
| 332 | ret.SetSelectValue(bazel.OsConfigurationAxis, bazel.OsDarwin, labels(darwinSrcs)) |
| 333 | return ret |
| 334 | } |
| 335 | |
| 336 | func goDepLabels(deps []string, goModulesMap nameToGoLibraryModule) bazel.LabelListAttribute { |
| 337 | labels := []bazel.Label{} |
| 338 | for _, dep := range deps { |
| 339 | moduleDir := goModulesMap[dep].Dir |
| 340 | if moduleDir == "." { |
| 341 | moduleDir = "" |
| 342 | } |
| 343 | label := bazel.Label{ |
| 344 | Label: fmt.Sprintf("//%s:%s", moduleDir, dep), |
| 345 | } |
| 346 | labels = append(labels, label) |
| 347 | } |
| 348 | return bazel.MakeLabelListAttribute(bazel.MakeLabelList(labels)) |
| 349 | } |
| 350 | |
| 351 | // attributes common to blueprint_go_binary and bootstap_go_package |
| 352 | type goAttributes struct { |
| 353 | Importpath bazel.StringAttribute |
| 354 | Srcs bazel.LabelListAttribute |
| 355 | Deps bazel.LabelListAttribute |
Spandan Das | 682e786 | 2023-06-22 22:22:11 +0000 | [diff] [blame^] | 356 | Data bazel.LabelListAttribute |
Spandan Das | ea2abba | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 357 | Target_compatible_with bazel.LabelListAttribute |
Spandan Das | 682e786 | 2023-06-22 22:22:11 +0000 | [diff] [blame^] | 358 | |
| 359 | // attributes for the dynamically generated go_test target |
| 360 | Embed bazel.LabelListAttribute |
Spandan Das | ea2abba | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 361 | } |
| 362 | |
Spandan Das | 682e786 | 2023-06-22 22:22:11 +0000 | [diff] [blame^] | 363 | type goTestProperties struct { |
| 364 | name string |
| 365 | dir string |
| 366 | testSrcs []string |
| 367 | linuxTestSrcs []string |
| 368 | darwinTestSrcs []string |
| 369 | testData []string |
| 370 | // Name of the target that should be compiled together with the test |
| 371 | embedName string |
| 372 | } |
| 373 | |
| 374 | // Creates a go_test target for bootstrap_go_package / blueprint_go_binary |
| 375 | func generateBazelTargetsGoTest(ctx *android.Context, goModulesMap nameToGoLibraryModule, gp goTestProperties) (BazelTarget, error) { |
| 376 | ca := android.CommonAttributes{ |
| 377 | Name: gp.name, |
| 378 | } |
| 379 | ga := goAttributes{ |
| 380 | Srcs: goSrcLabels(ctx.Config(), gp.dir, gp.testSrcs, gp.linuxTestSrcs, gp.darwinTestSrcs), |
| 381 | Data: goSrcLabels(ctx.Config(), gp.dir, gp.testData, []string{}, []string{}), |
| 382 | Embed: bazel.MakeLabelListAttribute( |
| 383 | bazel.MakeLabelList( |
| 384 | []bazel.Label{bazel.Label{Label: ":" + gp.embedName}}, |
| 385 | ), |
| 386 | ), |
| 387 | Target_compatible_with: targetNotCompatibleWithAndroid(), |
| 388 | } |
| 389 | |
| 390 | libTest := goBazelTarget{ |
| 391 | targetName: gp.name, |
| 392 | targetPackage: gp.dir, |
| 393 | bazelRuleClass: "go_test", |
| 394 | bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl", |
| 395 | bazelAttributes: []interface{}{&ca, &ga}, |
| 396 | } |
| 397 | return generateBazelTarget(ctx, libTest) |
| 398 | } |
| 399 | |
| 400 | // TODO - b/288491147: testSrcs of certain bootstrap_go_package/blueprint_go_binary are not hermetic and depend on |
| 401 | // testdata checked into the filesystem. |
| 402 | // Denylist the generation of go_test targets for these Soong modules. |
| 403 | // The go_library/go_binary will still be generated, since those are hermitic. |
| 404 | var ( |
| 405 | goTestsDenylist = []string{ |
| 406 | "android-archive-zip", |
| 407 | "bazel_notice_gen", |
| 408 | "blueprint-bootstrap-bpdoc", |
| 409 | "blueprint-microfactory", |
| 410 | "blueprint-pathtools", |
| 411 | "bssl_ar", |
| 412 | "compliance_checkmetadata", |
| 413 | "compliance_checkshare", |
| 414 | "compliance_dumpgraph", |
| 415 | "compliance_dumpresolutions", |
| 416 | "compliance_listshare", |
| 417 | "compliance-module", |
| 418 | "compliancenotice_bom", |
| 419 | "compliancenotice_shippedlibs", |
| 420 | "compliance_rtrace", |
| 421 | "compliance_sbom", |
| 422 | "golang-protobuf-internal-fuzz-jsonfuzz", |
| 423 | "golang-protobuf-internal-fuzz-textfuzz", |
| 424 | "golang-protobuf-internal-fuzz-wirefuzz", |
| 425 | "htmlnotice", |
| 426 | "protoc-gen-go", |
| 427 | "rbcrun-module", |
| 428 | "spdx-tools-builder", |
| 429 | "spdx-tools-builder2v1", |
| 430 | "spdx-tools-builder2v2", |
| 431 | "spdx-tools-builder2v3", |
| 432 | "spdx-tools-idsearcher", |
| 433 | "spdx-tools-spdx-json", |
| 434 | "spdx-tools-utils", |
| 435 | "soong-ui-build", |
| 436 | "textnotice", |
| 437 | "xmlnotice", |
| 438 | } |
| 439 | ) |
| 440 | |
Spandan Das | ea2abba | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 441 | func generateBazelTargetsGoPackage(ctx *android.Context, g *bootstrap.GoPackage, goModulesMap nameToGoLibraryModule) ([]BazelTarget, []error) { |
| 442 | ca := android.CommonAttributes{ |
| 443 | Name: g.Name(), |
| 444 | } |
Spandan Das | de62329 | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 445 | |
| 446 | // For this bootstrap_go_package dep chain, |
| 447 | // A --> B --> C ( ---> depends on) |
| 448 | // Soong provides the convenience of only listing B as deps of A even if a src file of A imports C |
| 449 | // Bazel OTOH |
| 450 | // 1. requires C to be listed in `deps` expllicity. |
| 451 | // 2. does not require C to be listed if src of A does not import C |
| 452 | // |
| 453 | // bp2build does not have sufficient info on whether C is a direct dep of A or not, so for now collect all transitive deps and add them to deps |
| 454 | transitiveDeps := transitiveGoDeps(g.Deps(), goModulesMap) |
| 455 | |
Spandan Das | ea2abba | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 456 | ga := goAttributes{ |
| 457 | Importpath: bazel.StringAttribute{ |
| 458 | Value: proptools.StringPtr(g.GoPkgPath()), |
| 459 | }, |
Spandan Das | 0a8a275 | 2023-06-21 01:50:33 +0000 | [diff] [blame] | 460 | Srcs: goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs()), |
| 461 | Deps: goDepLabels( |
| 462 | android.FirstUniqueStrings(transitiveDeps), |
| 463 | goModulesMap, |
| 464 | ), |
Spandan Das | ea2abba | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 465 | Target_compatible_with: targetNotCompatibleWithAndroid(), |
| 466 | } |
| 467 | |
| 468 | lib := goBazelTarget{ |
| 469 | targetName: g.Name(), |
| 470 | targetPackage: ctx.ModuleDir(g), |
| 471 | bazelRuleClass: "go_library", |
| 472 | bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl", |
| 473 | bazelAttributes: []interface{}{&ca, &ga}, |
| 474 | } |
Spandan Das | 682e786 | 2023-06-22 22:22:11 +0000 | [diff] [blame^] | 475 | retTargets := []BazelTarget{} |
| 476 | var retErrs []error |
| 477 | if libTarget, err := generateBazelTarget(ctx, lib); err == nil { |
| 478 | retTargets = append(retTargets, libTarget) |
| 479 | } else { |
| 480 | retErrs = []error{err} |
Spandan Das | ea2abba | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 481 | } |
Spandan Das | 682e786 | 2023-06-22 22:22:11 +0000 | [diff] [blame^] | 482 | |
| 483 | // If the library contains test srcs, create an additional go_test target |
| 484 | if !android.InList(g.Name(), goTestsDenylist) && (len(g.TestSrcs()) > 0 || len(g.LinuxTestSrcs()) > 0 || len(g.DarwinTestSrcs()) > 0) { |
| 485 | gp := goTestProperties{ |
| 486 | name: g.Name() + "-test", |
| 487 | dir: ctx.ModuleDir(g), |
| 488 | testSrcs: g.TestSrcs(), |
| 489 | linuxTestSrcs: g.LinuxTestSrcs(), |
| 490 | darwinTestSrcs: g.DarwinTestSrcs(), |
| 491 | testData: g.TestData(), |
| 492 | embedName: g.Name(), // embed the source go_library in the test so that its .go files are included in the compilation unit |
| 493 | } |
| 494 | if libTestTarget, err := generateBazelTargetsGoTest(ctx, goModulesMap, gp); err == nil { |
| 495 | retTargets = append(retTargets, libTestTarget) |
| 496 | } else { |
| 497 | retErrs = append(retErrs, err) |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | return retTargets, retErrs |
Spandan Das | ea2abba | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 502 | } |
| 503 | |
| 504 | type goLibraryModule struct { |
| 505 | Dir string |
| 506 | Deps []string |
| 507 | } |
| 508 | |
| 509 | type nameToGoLibraryModule map[string]goLibraryModule |
| 510 | |
| 511 | // Visit each module in the graph |
| 512 | // If a module is of type `bootstrap_go_package`, return a map containing metadata like its dir and deps |
| 513 | func createGoLibraryModuleMap(ctx *android.Context) nameToGoLibraryModule { |
| 514 | ret := nameToGoLibraryModule{} |
| 515 | ctx.VisitAllModules(func(m blueprint.Module) { |
| 516 | moduleType := ctx.ModuleType(m) |
| 517 | // We do not need to store information about blueprint_go_binary since it does not have any rdeps |
| 518 | if moduleType == "bootstrap_go_package" { |
| 519 | ret[m.Name()] = goLibraryModule{ |
| 520 | Dir: ctx.ModuleDir(m), |
| 521 | Deps: m.(*bootstrap.GoPackage).Deps(), |
| 522 | } |
| 523 | } |
| 524 | }) |
| 525 | return ret |
| 526 | } |
| 527 | |
Spandan Das | de62329 | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 528 | // Returns the deps in the transitive closure of a go target |
| 529 | func transitiveGoDeps(directDeps []string, goModulesMap nameToGoLibraryModule) []string { |
| 530 | allDeps := directDeps |
| 531 | i := 0 |
| 532 | for i < len(allDeps) { |
| 533 | curr := allDeps[i] |
| 534 | allDeps = append(allDeps, goModulesMap[curr].Deps...) |
| 535 | i += 1 |
| 536 | } |
| 537 | allDeps = android.SortedUniqueStrings(allDeps) |
| 538 | return allDeps |
| 539 | } |
| 540 | |
| 541 | func generateBazelTargetsGoBinary(ctx *android.Context, g *bootstrap.GoBinary, goModulesMap nameToGoLibraryModule) ([]BazelTarget, []error) { |
| 542 | ca := android.CommonAttributes{ |
| 543 | Name: g.Name(), |
| 544 | } |
| 545 | |
Spandan Das | 682e786 | 2023-06-22 22:22:11 +0000 | [diff] [blame^] | 546 | retTargets := []BazelTarget{} |
| 547 | var retErrs []error |
| 548 | |
Spandan Das | de62329 | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 549 | // For this bootstrap_go_package dep chain, |
| 550 | // A --> B --> C ( ---> depends on) |
| 551 | // Soong provides the convenience of only listing B as deps of A even if a src file of A imports C |
| 552 | // Bazel OTOH |
| 553 | // 1. requires C to be listed in `deps` expllicity. |
| 554 | // 2. does not require C to be listed if src of A does not import C |
| 555 | // |
| 556 | // bp2build does not have sufficient info on whether C is a direct dep of A or not, so for now collect all transitive deps and add them to deps |
| 557 | transitiveDeps := transitiveGoDeps(g.Deps(), goModulesMap) |
| 558 | |
Spandan Das | 682e786 | 2023-06-22 22:22:11 +0000 | [diff] [blame^] | 559 | goSource := "" |
| 560 | // If the library contains test srcs, create an additional go_test target |
| 561 | // The go_test target will embed a go_source containining the source .go files it tests |
| 562 | if !android.InList(g.Name(), goTestsDenylist) && (len(g.TestSrcs()) > 0 || len(g.LinuxTestSrcs()) > 0 || len(g.DarwinTestSrcs()) > 0) { |
| 563 | // Create a go_source containing the source .go files of go_library |
| 564 | // This target will be an `embed` of the go_binary and go_test |
| 565 | goSource = g.Name() + "-source" |
| 566 | ca := android.CommonAttributes{ |
| 567 | Name: goSource, |
| 568 | } |
| 569 | ga := goAttributes{ |
| 570 | Srcs: goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs()), |
| 571 | Deps: goDepLabels(transitiveDeps, goModulesMap), |
| 572 | Target_compatible_with: targetNotCompatibleWithAndroid(), |
| 573 | } |
| 574 | libTestSource := goBazelTarget{ |
| 575 | targetName: goSource, |
| 576 | targetPackage: ctx.ModuleDir(g), |
| 577 | bazelRuleClass: "go_source", |
| 578 | bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl", |
| 579 | bazelAttributes: []interface{}{&ca, &ga}, |
| 580 | } |
| 581 | if libSourceTarget, err := generateBazelTarget(ctx, libTestSource); err == nil { |
| 582 | retTargets = append(retTargets, libSourceTarget) |
| 583 | } else { |
| 584 | retErrs = append(retErrs, err) |
| 585 | } |
| 586 | |
| 587 | // Create a go_test target |
| 588 | gp := goTestProperties{ |
| 589 | name: g.Name() + "-test", |
| 590 | dir: ctx.ModuleDir(g), |
| 591 | testSrcs: g.TestSrcs(), |
| 592 | linuxTestSrcs: g.LinuxTestSrcs(), |
| 593 | darwinTestSrcs: g.DarwinTestSrcs(), |
| 594 | testData: g.TestData(), |
| 595 | // embed the go_source in the test |
| 596 | embedName: g.Name() + "-source", |
| 597 | } |
| 598 | if libTestTarget, err := generateBazelTargetsGoTest(ctx, goModulesMap, gp); err == nil { |
| 599 | retTargets = append(retTargets, libTestTarget) |
| 600 | } else { |
| 601 | retErrs = append(retErrs, err) |
| 602 | } |
| 603 | |
| 604 | } |
| 605 | |
| 606 | // Create a go_binary target |
Spandan Das | de62329 | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 607 | ga := goAttributes{ |
Spandan Das | de62329 | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 608 | Deps: goDepLabels(transitiveDeps, goModulesMap), |
| 609 | Target_compatible_with: targetNotCompatibleWithAndroid(), |
| 610 | } |
| 611 | |
Spandan Das | 682e786 | 2023-06-22 22:22:11 +0000 | [diff] [blame^] | 612 | // If the binary has testSrcs, embed the common `go_source` |
| 613 | if goSource != "" { |
| 614 | ga.Embed = bazel.MakeLabelListAttribute( |
| 615 | bazel.MakeLabelList( |
| 616 | []bazel.Label{bazel.Label{Label: ":" + goSource}}, |
| 617 | ), |
| 618 | ) |
| 619 | } else { |
| 620 | ga.Srcs = goSrcLabels(ctx.Config(), ctx.ModuleDir(g), g.Srcs(), g.LinuxSrcs(), g.DarwinSrcs()) |
| 621 | } |
| 622 | |
Spandan Das | de62329 | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 623 | bin := goBazelTarget{ |
| 624 | targetName: g.Name(), |
| 625 | targetPackage: ctx.ModuleDir(g), |
| 626 | bazelRuleClass: "go_binary", |
| 627 | bazelRuleLoadLocation: "@io_bazel_rules_go//go:def.bzl", |
| 628 | bazelAttributes: []interface{}{&ca, &ga}, |
| 629 | } |
Spandan Das | 682e786 | 2023-06-22 22:22:11 +0000 | [diff] [blame^] | 630 | |
| 631 | if binTarget, err := generateBazelTarget(ctx, bin); err == nil { |
| 632 | retTargets = append(retTargets, binTarget) |
| 633 | } else { |
| 634 | retErrs = []error{err} |
Spandan Das | de62329 | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 635 | } |
Spandan Das | 682e786 | 2023-06-22 22:22:11 +0000 | [diff] [blame^] | 636 | |
| 637 | return retTargets, retErrs |
Spandan Das | de62329 | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 638 | } |
| 639 | |
Liz Kammer | 6eff323 | 2021-08-26 08:37:59 -0400 | [diff] [blame] | 640 | func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (conversionResults, []error) { |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 641 | buildFileToTargets := make(map[string]BazelTargets) |
Jingwen Chen | 164e086 | 2021-02-19 00:48:40 -0500 | [diff] [blame] | 642 | |
| 643 | // Simple metrics tracking for bp2build |
usta | 4f5d2c1 | 2022-10-28 23:32:01 -0400 | [diff] [blame] | 644 | metrics := CreateCodegenMetrics() |
Jingwen Chen | 164e086 | 2021-02-19 00:48:40 -0500 | [diff] [blame] | 645 | |
Rupert Shuttleworth | 2a4fc3e | 2021-04-21 07:10:09 -0400 | [diff] [blame] | 646 | dirs := make(map[string]bool) |
| 647 | |
Liz Kammer | 6eff323 | 2021-08-26 08:37:59 -0400 | [diff] [blame] | 648 | var errs []error |
| 649 | |
Spandan Das | ea2abba | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 650 | // Visit go libraries in a pre-run and store its state in a map |
| 651 | // The time complexity remains O(N), and this does not add significant wall time. |
| 652 | nameToGoLibMap := createGoLibraryModuleMap(ctx.Context()) |
| 653 | |
Jingwen Chen | 164e086 | 2021-02-19 00:48:40 -0500 | [diff] [blame] | 654 | bpCtx := ctx.Context() |
| 655 | bpCtx.VisitAllModules(func(m blueprint.Module) { |
| 656 | dir := bpCtx.ModuleDir(m) |
Chris Parsons | 492bd91 | 2022-01-20 12:55:05 -0500 | [diff] [blame] | 657 | moduleType := bpCtx.ModuleType(m) |
Rupert Shuttleworth | 2a4fc3e | 2021-04-21 07:10:09 -0400 | [diff] [blame] | 658 | dirs[dir] = true |
| 659 | |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame] | 660 | var targets []BazelTarget |
Spandan Das | ea2abba | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 661 | var targetErrs []error |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 662 | |
Jingwen Chen | 164e086 | 2021-02-19 00:48:40 -0500 | [diff] [blame] | 663 | switch ctx.Mode() { |
Jingwen Chen | 33832f9 | 2021-01-24 22:55:54 -0500 | [diff] [blame] | 664 | case Bp2Build: |
Jingwen Chen | 310bc8f | 2021-09-20 10:54:27 +0000 | [diff] [blame] | 665 | // There are two main ways of converting a Soong module to Bazel: |
| 666 | // 1) Manually handcrafting a Bazel target and associating the module with its label |
| 667 | // 2) Automatically generating with bp2build converters |
| 668 | // |
| 669 | // bp2build converters are used for the majority of modules. |
Liz Kammer | ba3ea16 | 2021-02-17 13:22:03 -0500 | [diff] [blame] | 670 | if b, ok := m.(android.Bazelable); ok && b.HasHandcraftedLabel() { |
Jingwen Chen | 310bc8f | 2021-09-20 10:54:27 +0000 | [diff] [blame] | 671 | // Handle modules converted to handcrafted targets. |
| 672 | // |
| 673 | // Since these modules are associated with some handcrafted |
Cole Faust | ea602c5 | 2022-08-31 14:48:26 -0700 | [diff] [blame] | 674 | // target in a BUILD file, we don't autoconvert them. |
Jingwen Chen | 310bc8f | 2021-09-20 10:54:27 +0000 | [diff] [blame] | 675 | |
| 676 | // Log the module. |
Chris Parsons | 39a1697 | 2023-06-08 14:28:51 +0000 | [diff] [blame] | 677 | metrics.AddUnconvertedModule(m, moduleType, dir, |
| 678 | android.UnconvertedReason{ |
| 679 | ReasonType: int(bp2build_metrics_proto.UnconvertedReasonType_DEFINED_IN_BUILD_FILE), |
| 680 | }) |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame] | 681 | } else if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() { |
Jingwen Chen | 310bc8f | 2021-09-20 10:54:27 +0000 | [diff] [blame] | 682 | // Handle modules converted to generated targets. |
| 683 | |
| 684 | // Log the module. |
Chris Parsons | 39a1697 | 2023-06-08 14:28:51 +0000 | [diff] [blame] | 685 | metrics.AddConvertedModule(aModule, moduleType, dir) |
Jingwen Chen | 310bc8f | 2021-09-20 10:54:27 +0000 | [diff] [blame] | 686 | |
| 687 | // Handle modules with unconverted deps. By default, emit a warning. |
Liz Kammer | 6eff323 | 2021-08-26 08:37:59 -0400 | [diff] [blame] | 688 | if unconvertedDeps := aModule.GetUnconvertedBp2buildDeps(); len(unconvertedDeps) > 0 { |
Sasha Smundak | f2bb26f | 2022-08-04 11:28:15 -0700 | [diff] [blame] | 689 | msg := fmt.Sprintf("%s %s:%s depends on unconverted modules: %s", |
| 690 | moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", ")) |
Usta Shrestha | c605715 | 2022-09-24 00:23:31 -0400 | [diff] [blame] | 691 | switch ctx.unconvertedDepMode { |
| 692 | case warnUnconvertedDeps: |
Liz Kammer | 6eff323 | 2021-08-26 08:37:59 -0400 | [diff] [blame] | 693 | metrics.moduleWithUnconvertedDepsMsgs = append(metrics.moduleWithUnconvertedDepsMsgs, msg) |
Usta Shrestha | c605715 | 2022-09-24 00:23:31 -0400 | [diff] [blame] | 694 | case errorModulesUnconvertedDeps: |
Liz Kammer | 6eff323 | 2021-08-26 08:37:59 -0400 | [diff] [blame] | 695 | errs = append(errs, fmt.Errorf(msg)) |
| 696 | return |
| 697 | } |
| 698 | } |
Liz Kammer | daa09ef | 2021-12-15 15:35:38 -0500 | [diff] [blame] | 699 | if unconvertedDeps := aModule.GetMissingBp2buildDeps(); len(unconvertedDeps) > 0 { |
Sasha Smundak | f2bb26f | 2022-08-04 11:28:15 -0700 | [diff] [blame] | 700 | msg := fmt.Sprintf("%s %s:%s depends on missing modules: %s", |
| 701 | moduleType, bpCtx.ModuleDir(m), m.Name(), strings.Join(unconvertedDeps, ", ")) |
Usta Shrestha | c605715 | 2022-09-24 00:23:31 -0400 | [diff] [blame] | 702 | switch ctx.unconvertedDepMode { |
| 703 | case warnUnconvertedDeps: |
Liz Kammer | daa09ef | 2021-12-15 15:35:38 -0500 | [diff] [blame] | 704 | metrics.moduleWithMissingDepsMsgs = append(metrics.moduleWithMissingDepsMsgs, msg) |
Usta Shrestha | c605715 | 2022-09-24 00:23:31 -0400 | [diff] [blame] | 705 | case errorModulesUnconvertedDeps: |
Liz Kammer | daa09ef | 2021-12-15 15:35:38 -0500 | [diff] [blame] | 706 | errs = append(errs, fmt.Errorf(msg)) |
| 707 | return |
| 708 | } |
| 709 | } |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 710 | targets, targetErrs = generateBazelTargets(bpCtx, aModule) |
| 711 | errs = append(errs, targetErrs...) |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame] | 712 | for _, t := range targets { |
Jingwen Chen | 310bc8f | 2021-09-20 10:54:27 +0000 | [diff] [blame] | 713 | // A module can potentially generate more than 1 Bazel |
| 714 | // target, each of a different rule class. |
| 715 | metrics.IncrementRuleClassCount(t.ruleClass) |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame] | 716 | } |
MarkDacek | 9c094ca | 2023-03-16 19:15:19 +0000 | [diff] [blame] | 717 | } else if _, ok := ctx.Config().BazelModulesForceEnabledByFlag()[m.Name()]; ok && m.Name() != "" { |
| 718 | err := fmt.Errorf("Force Enabled Module %s not converted", m.Name()) |
| 719 | errs = append(errs, err) |
Chris Parsons | 39a1697 | 2023-06-08 14:28:51 +0000 | [diff] [blame] | 720 | } else if aModule, ok := m.(android.Module); ok { |
| 721 | reason := aModule.GetUnconvertedReason() |
| 722 | if reason == nil { |
| 723 | panic(fmt.Errorf("module '%s' was neither converted nor marked unconvertible with bp2build", aModule.Name())) |
| 724 | } else { |
| 725 | metrics.AddUnconvertedModule(m, moduleType, dir, *reason) |
| 726 | } |
| 727 | return |
Spandan Das | ea2abba | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 728 | } else if glib, ok := m.(*bootstrap.GoPackage); ok { |
| 729 | targets, targetErrs = generateBazelTargetsGoPackage(bpCtx, glib, nameToGoLibMap) |
| 730 | errs = append(errs, targetErrs...) |
| 731 | metrics.IncrementRuleClassCount("go_library") |
Spandan Das | 2a55cea | 2023-06-14 17:56:10 +0000 | [diff] [blame] | 732 | } else if gbin, ok := m.(*bootstrap.GoBinary); ok { |
Spandan Das | de62329 | 2023-06-14 21:30:38 +0000 | [diff] [blame] | 733 | targets, targetErrs = generateBazelTargetsGoBinary(bpCtx, gbin, nameToGoLibMap) |
| 734 | errs = append(errs, targetErrs...) |
| 735 | metrics.IncrementRuleClassCount("go_binary") |
Liz Kammer | fc46bc1 | 2021-02-19 11:06:17 -0500 | [diff] [blame] | 736 | } else { |
Chris Parsons | 39a1697 | 2023-06-08 14:28:51 +0000 | [diff] [blame] | 737 | metrics.AddUnconvertedModule(m, moduleType, dir, android.UnconvertedReason{ |
| 738 | ReasonType: int(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED), |
| 739 | }) |
Liz Kammer | ba3ea16 | 2021-02-17 13:22:03 -0500 | [diff] [blame] | 740 | return |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 741 | } |
Jingwen Chen | 33832f9 | 2021-01-24 22:55:54 -0500 | [diff] [blame] | 742 | case QueryView: |
Jingwen Chen | 96af35b | 2021-02-08 00:49:32 -0500 | [diff] [blame] | 743 | // Blocklist certain module types from being generated. |
Jingwen Chen | 164e086 | 2021-02-19 00:48:40 -0500 | [diff] [blame] | 744 | if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" { |
Jingwen Chen | 96af35b | 2021-02-08 00:49:32 -0500 | [diff] [blame] | 745 | // package module name contain slashes, and thus cannot |
| 746 | // be mapped cleanly to a bazel label. |
| 747 | return |
| 748 | } |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 749 | t, err := generateSoongModuleTarget(bpCtx, m) |
| 750 | if err != nil { |
| 751 | errs = append(errs, err) |
| 752 | } |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame] | 753 | targets = append(targets, t) |
Spandan Das | 5af0bd3 | 2022-09-28 20:43:08 +0000 | [diff] [blame] | 754 | case ApiBp2build: |
| 755 | if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() { |
| 756 | targets, errs = generateBazelTargets(bpCtx, aModule) |
| 757 | } |
Jingwen Chen | 33832f9 | 2021-01-24 22:55:54 -0500 | [diff] [blame] | 758 | default: |
Liz Kammer | 6eff323 | 2021-08-26 08:37:59 -0400 | [diff] [blame] | 759 | errs = append(errs, fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode())) |
| 760 | return |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 761 | } |
| 762 | |
Spandan Das | abedff0 | 2023-03-07 19:24:34 +0000 | [diff] [blame] | 763 | for _, target := range targets { |
| 764 | targetDir := target.PackageName() |
| 765 | buildFileToTargets[targetDir] = append(buildFileToTargets[targetDir], target) |
| 766 | } |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 767 | }) |
Liz Kammer | 6eff323 | 2021-08-26 08:37:59 -0400 | [diff] [blame] | 768 | |
| 769 | if len(errs) > 0 { |
| 770 | return conversionResults{}, errs |
| 771 | } |
| 772 | |
Rupert Shuttleworth | 2a4fc3e | 2021-04-21 07:10:09 -0400 | [diff] [blame] | 773 | if generateFilegroups { |
| 774 | // Add a filegroup target that exposes all sources in the subtree of this package |
| 775 | // NOTE: This also means we generate a BUILD file for every Android.bp file (as long as it has at least one module) |
Cole Faust | 324a92e | 2022-08-23 15:29:05 -0700 | [diff] [blame] | 776 | // |
| 777 | // This works because: https://bazel.build/reference/be/functions#exports_files |
| 778 | // "As a legacy behaviour, also files mentioned as input to a rule are exported with the |
| 779 | // default visibility until the flag --incompatible_no_implicit_file_export is flipped. However, this behavior |
| 780 | // should not be relied upon and actively migrated away from." |
| 781 | // |
| 782 | // TODO(b/198619163): We should change this to export_files(glob(["**/*"])) instead, but doing that causes these errors: |
| 783 | // "Error in exports_files: generated label '//external/avb:avbtool' conflicts with existing py_binary rule" |
| 784 | // So we need to solve all the "target ... is both a rule and a file" warnings first. |
Usta Shrestha | c605715 | 2022-09-24 00:23:31 -0400 | [diff] [blame] | 785 | for dir := range dirs { |
Rupert Shuttleworth | 2a4fc3e | 2021-04-21 07:10:09 -0400 | [diff] [blame] | 786 | buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{ |
| 787 | name: "bp2build_all_srcs", |
| 788 | content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]))`, |
| 789 | ruleClass: "filegroup", |
| 790 | }) |
| 791 | } |
| 792 | } |
Jingwen Chen | 164e086 | 2021-02-19 00:48:40 -0500 | [diff] [blame] | 793 | |
Liz Kammer | 6eff323 | 2021-08-26 08:37:59 -0400 | [diff] [blame] | 794 | return conversionResults{ |
| 795 | buildFileToTargets: buildFileToTargets, |
| 796 | metrics: metrics, |
Liz Kammer | 6eff323 | 2021-08-26 08:37:59 -0400 | [diff] [blame] | 797 | }, errs |
Jingwen Chen | 164e086 | 2021-02-19 00:48:40 -0500 | [diff] [blame] | 798 | } |
| 799 | |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 800 | func generateBazelTargets(ctx bpToBuildContext, m android.Module) ([]BazelTarget, []error) { |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame] | 801 | var targets []BazelTarget |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 802 | var errs []error |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame] | 803 | for _, m := range m.Bp2buildTargets() { |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 804 | target, err := generateBazelTarget(ctx, m) |
| 805 | if err != nil { |
| 806 | errs = append(errs, err) |
| 807 | return targets, errs |
| 808 | } |
| 809 | targets = append(targets, target) |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame] | 810 | } |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 811 | return targets, errs |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame] | 812 | } |
| 813 | |
| 814 | type bp2buildModule interface { |
| 815 | TargetName() string |
| 816 | TargetPackage() string |
| 817 | BazelRuleClass() string |
| 818 | BazelRuleLoadLocation() string |
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux | 447f6c9 | 2021-08-31 20:30:36 +0000 | [diff] [blame] | 819 | BazelAttributes() []interface{} |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame] | 820 | } |
| 821 | |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 822 | func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) (BazelTarget, error) { |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame] | 823 | ruleClass := m.BazelRuleClass() |
| 824 | bzlLoadLocation := m.BazelRuleLoadLocation() |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 825 | |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 826 | // extract the bazel attributes from the module. |
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux | 447f6c9 | 2021-08-31 20:30:36 +0000 | [diff] [blame] | 827 | attrs := m.BazelAttributes() |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 828 | props, err := extractModuleProperties(attrs, true) |
| 829 | if err != nil { |
| 830 | return BazelTarget{}, err |
| 831 | } |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 832 | |
Liz Kammer | 0eae52e | 2021-10-06 10:32:26 -0400 | [diff] [blame] | 833 | // name is handled in a special manner |
| 834 | delete(props.Attrs, "name") |
Jingwen Chen | 77e8b7b | 2021-02-05 03:03:24 -0500 | [diff] [blame] | 835 | |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 836 | // Return the Bazel target with rule class and attributes, ready to be |
| 837 | // code-generated. |
| 838 | attributes := propsToAttributes(props.Attrs) |
Sasha Smundak | fb58949 | 2022-08-04 11:13:27 -0700 | [diff] [blame] | 839 | var content string |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame] | 840 | targetName := m.TargetName() |
Sasha Smundak | fb58949 | 2022-08-04 11:13:27 -0700 | [diff] [blame] | 841 | if targetName != "" { |
| 842 | content = fmt.Sprintf(ruleTargetTemplate, ruleClass, targetName, attributes) |
| 843 | } else { |
| 844 | content = fmt.Sprintf(unnamedRuleTargetTemplate, ruleClass, attributes) |
| 845 | } |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 846 | return BazelTarget{ |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 847 | name: targetName, |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame] | 848 | packageName: m.TargetPackage(), |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 849 | ruleClass: ruleClass, |
| 850 | bzlLoadLocation: bzlLoadLocation, |
Sasha Smundak | fb58949 | 2022-08-04 11:13:27 -0700 | [diff] [blame] | 851 | content: content, |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 852 | }, nil |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 853 | } |
| 854 | |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 855 | // Convert a module and its deps and props into a Bazel macro/rule |
| 856 | // representation in the BUILD file. |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 857 | func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) (BazelTarget, error) { |
| 858 | props, err := getBuildProperties(ctx, m) |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 859 | |
| 860 | // TODO(b/163018919): DirectDeps can have duplicate (module, variant) |
| 861 | // items, if the modules are added using different DependencyTag. Figure |
| 862 | // out the implications of that. |
| 863 | depLabels := map[string]bool{} |
| 864 | if aModule, ok := m.(android.Module); ok { |
Jingwen Chen | daa54bc | 2020-12-14 02:58:54 -0500 | [diff] [blame] | 865 | ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) { |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 866 | depLabels[qualifiedTargetLabel(ctx, depModule)] = true |
| 867 | }) |
| 868 | } |
Liz Kammer | 0eae52e | 2021-10-06 10:32:26 -0400 | [diff] [blame] | 869 | |
Usta Shrestha | db46a9b | 2022-07-11 11:29:56 -0400 | [diff] [blame] | 870 | for p := range ignoredPropNames { |
Liz Kammer | 0eae52e | 2021-10-06 10:32:26 -0400 | [diff] [blame] | 871 | delete(props.Attrs, p) |
| 872 | } |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 873 | attributes := propsToAttributes(props.Attrs) |
| 874 | |
| 875 | depLabelList := "[\n" |
Usta Shrestha | db46a9b | 2022-07-11 11:29:56 -0400 | [diff] [blame] | 876 | for depLabel := range depLabels { |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 877 | depLabelList += fmt.Sprintf(" %q,\n", depLabel) |
| 878 | } |
| 879 | depLabelList += " ]" |
| 880 | |
| 881 | targetName := targetNameWithVariant(ctx, m) |
| 882 | return BazelTarget{ |
Spandan Das | abedff0 | 2023-03-07 19:24:34 +0000 | [diff] [blame] | 883 | name: targetName, |
| 884 | packageName: ctx.ModuleDir(m), |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 885 | content: fmt.Sprintf( |
Sasha Smundak | fb58949 | 2022-08-04 11:13:27 -0700 | [diff] [blame] | 886 | soongModuleTargetTemplate, |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 887 | targetName, |
| 888 | ctx.ModuleName(m), |
| 889 | canonicalizeModuleType(ctx.ModuleType(m)), |
| 890 | ctx.ModuleSubDir(m), |
| 891 | depLabelList, |
| 892 | attributes), |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 893 | }, err |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 894 | } |
| 895 | |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 896 | func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) (BazelAttributes, error) { |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 897 | // TODO: this omits properties for blueprint modules (blueprint_go_binary, |
| 898 | // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately. |
| 899 | if aModule, ok := m.(android.Module); ok { |
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux | 447f6c9 | 2021-08-31 20:30:36 +0000 | [diff] [blame] | 900 | return extractModuleProperties(aModule.GetProperties(), false) |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 901 | } |
| 902 | |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 903 | return BazelAttributes{}, nil |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 904 | } |
| 905 | |
| 906 | // Generically extract module properties and types into a map, keyed by the module property name. |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 907 | func extractModuleProperties(props []interface{}, checkForDuplicateProperties bool) (BazelAttributes, error) { |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 908 | ret := map[string]string{} |
| 909 | |
| 910 | // Iterate over this android.Module's property structs. |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame] | 911 | for _, properties := range props { |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 912 | propertiesValue := reflect.ValueOf(properties) |
| 913 | // Check that propertiesValue is a pointer to the Properties struct, like |
| 914 | // *cc.BaseLinkerProperties or *java.CompilerProperties. |
| 915 | // |
| 916 | // propertiesValue can also be type-asserted to the structs to |
| 917 | // manipulate internal props, if needed. |
| 918 | if isStructPtr(propertiesValue.Type()) { |
| 919 | structValue := propertiesValue.Elem() |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 920 | ok, err := extractStructProperties(structValue, 0) |
| 921 | if err != nil { |
| 922 | return BazelAttributes{}, err |
| 923 | } |
| 924 | for k, v := range ok { |
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux | 447f6c9 | 2021-08-31 20:30:36 +0000 | [diff] [blame] | 925 | if existing, exists := ret[k]; checkForDuplicateProperties && exists { |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 926 | return BazelAttributes{}, fmt.Errorf( |
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux | 447f6c9 | 2021-08-31 20:30:36 +0000 | [diff] [blame] | 927 | "%s (%v) is present in properties whereas it should be consolidated into a commonAttributes", |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 928 | k, existing) |
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux | 447f6c9 | 2021-08-31 20:30:36 +0000 | [diff] [blame] | 929 | } |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 930 | ret[k] = v |
| 931 | } |
| 932 | } else { |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 933 | return BazelAttributes{}, |
| 934 | fmt.Errorf( |
| 935 | "properties must be a pointer to a struct, got %T", |
| 936 | propertiesValue.Interface()) |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 937 | } |
| 938 | } |
| 939 | |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame] | 940 | return BazelAttributes{ |
| 941 | Attrs: ret, |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 942 | }, nil |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 943 | } |
| 944 | |
| 945 | func isStructPtr(t reflect.Type) bool { |
| 946 | return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct |
| 947 | } |
| 948 | |
| 949 | // prettyPrint a property value into the equivalent Starlark representation |
| 950 | // recursively. |
Jingwen Chen | 58ff680 | 2021-11-17 12:14:41 +0000 | [diff] [blame] | 951 | func prettyPrint(propertyValue reflect.Value, indent int, emitZeroValues bool) (string, error) { |
| 952 | if !emitZeroValues && isZero(propertyValue) { |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 953 | // A property value being set or unset actually matters -- Soong does set default |
| 954 | // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at |
| 955 | // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480 |
| 956 | // |
Jingwen Chen | fc490bd | 2021-03-30 10:24:19 +0000 | [diff] [blame] | 957 | // In Bazel-parlance, we would use "attr.<type>(default = <default |
| 958 | // value>)" to set the default value of unset attributes. In the cases |
| 959 | // where the bp2build converter didn't set the default value within the |
| 960 | // mutator when creating the BazelTargetModule, this would be a zero |
Jingwen Chen | 6393098 | 2021-03-24 10:04:33 -0400 | [diff] [blame] | 961 | // value. For those cases, we return an empty string so we don't |
| 962 | // unnecessarily generate empty values. |
| 963 | return "", nil |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 964 | } |
| 965 | |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 966 | switch propertyValue.Kind() { |
| 967 | case reflect.String: |
Liz Kammer | 72beb34 | 2022-02-03 08:42:10 -0500 | [diff] [blame] | 968 | return fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())), nil |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 969 | case reflect.Bool: |
Liz Kammer | 72beb34 | 2022-02-03 08:42:10 -0500 | [diff] [blame] | 970 | return starlark_fmt.PrintBool(propertyValue.Bool()), nil |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 971 | case reflect.Int, reflect.Uint, reflect.Int64: |
Liz Kammer | 72beb34 | 2022-02-03 08:42:10 -0500 | [diff] [blame] | 972 | return fmt.Sprintf("%v", propertyValue.Interface()), nil |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 973 | case reflect.Ptr: |
Jingwen Chen | 58ff680 | 2021-11-17 12:14:41 +0000 | [diff] [blame] | 974 | return prettyPrint(propertyValue.Elem(), indent, emitZeroValues) |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 975 | case reflect.Slice: |
Liz Kammer | 72beb34 | 2022-02-03 08:42:10 -0500 | [diff] [blame] | 976 | elements := make([]string, 0, propertyValue.Len()) |
| 977 | for i := 0; i < propertyValue.Len(); i++ { |
| 978 | val, err := prettyPrint(propertyValue.Index(i), indent, emitZeroValues) |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 979 | if err != nil { |
| 980 | return "", err |
| 981 | } |
Liz Kammer | 72beb34 | 2022-02-03 08:42:10 -0500 | [diff] [blame] | 982 | if val != "" { |
| 983 | elements = append(elements, val) |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 984 | } |
| 985 | } |
Sam Delmerico | 932c01c | 2022-03-25 16:33:26 +0000 | [diff] [blame] | 986 | return starlark_fmt.PrintList(elements, indent, func(s string) string { |
| 987 | return "%s" |
| 988 | }), nil |
Jingwen Chen | b4628eb | 2021-04-08 14:40:57 +0000 | [diff] [blame] | 989 | |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 990 | case reflect.Struct: |
Jingwen Chen | 5d86449 | 2021-02-24 07:20:12 -0500 | [diff] [blame] | 991 | // Special cases where the bp2build sends additional information to the codegenerator |
| 992 | // by wrapping the attributes in a custom struct type. |
Jingwen Chen | c1c2650 | 2021-04-05 10:35:13 +0000 | [diff] [blame] | 993 | if attr, ok := propertyValue.Interface().(bazel.Attribute); ok { |
| 994 | return prettyPrintAttribute(attr, indent) |
Liz Kammer | 356f7d4 | 2021-01-26 09:18:53 -0500 | [diff] [blame] | 995 | } else if label, ok := propertyValue.Interface().(bazel.Label); ok { |
| 996 | return fmt.Sprintf("%q", label.Label), nil |
| 997 | } |
| 998 | |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 999 | // Sort and print the struct props by the key. |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 1000 | structProps, err := extractStructProperties(propertyValue, indent) |
| 1001 | |
| 1002 | if err != nil { |
| 1003 | return "", err |
| 1004 | } |
| 1005 | |
Jingwen Chen | 3d383bb | 2021-06-09 07:18:37 +0000 | [diff] [blame] | 1006 | if len(structProps) == 0 { |
| 1007 | return "", nil |
| 1008 | } |
Liz Kammer | 72beb34 | 2022-02-03 08:42:10 -0500 | [diff] [blame] | 1009 | return starlark_fmt.PrintDict(structProps, indent), nil |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 1010 | case reflect.Interface: |
| 1011 | // TODO(b/164227191): implement pretty print for interfaces. |
| 1012 | // Interfaces are used for for arch, multilib and target properties. |
| 1013 | return "", nil |
Spandan Das | 6a448ec | 2023-04-19 17:36:12 +0000 | [diff] [blame] | 1014 | case reflect.Map: |
| 1015 | if v, ok := propertyValue.Interface().(bazel.StringMapAttribute); ok { |
| 1016 | return starlark_fmt.PrintStringStringDict(v, indent), nil |
| 1017 | } |
| 1018 | return "", fmt.Errorf("bp2build expects map of type map[string]string for field: %s", propertyValue) |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 1019 | default: |
| 1020 | return "", fmt.Errorf( |
| 1021 | "unexpected kind for property struct field: %s", propertyValue.Kind()) |
| 1022 | } |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 1023 | } |
| 1024 | |
| 1025 | // Converts a reflected property struct value into a map of property names and property values, |
| 1026 | // which each property value correctly pretty-printed and indented at the right nest level, |
| 1027 | // since property structs can be nested. In Starlark, nested structs are represented as nested |
| 1028 | // dicts: https://docs.bazel.build/skylark/lib/dict.html |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 1029 | func extractStructProperties(structValue reflect.Value, indent int) (map[string]string, error) { |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 1030 | if structValue.Kind() != reflect.Struct { |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 1031 | return map[string]string{}, fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind()) |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 1032 | } |
| 1033 | |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 1034 | var err error |
| 1035 | |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 1036 | ret := map[string]string{} |
| 1037 | structType := structValue.Type() |
| 1038 | for i := 0; i < structValue.NumField(); i++ { |
| 1039 | field := structType.Field(i) |
| 1040 | if shouldSkipStructField(field) { |
| 1041 | continue |
| 1042 | } |
| 1043 | |
| 1044 | fieldValue := structValue.Field(i) |
| 1045 | if isZero(fieldValue) { |
| 1046 | // Ignore zero-valued fields |
| 1047 | continue |
| 1048 | } |
Liz Kammer | 7a210ac | 2021-09-22 15:52:58 -0400 | [diff] [blame] | 1049 | |
Liz Kammer | 32a0339 | 2021-09-14 11:17:21 -0400 | [diff] [blame] | 1050 | // if the struct is embedded (anonymous), flatten the properties into the containing struct |
| 1051 | if field.Anonymous { |
| 1052 | if field.Type.Kind() == reflect.Ptr { |
| 1053 | fieldValue = fieldValue.Elem() |
| 1054 | } |
| 1055 | if fieldValue.Type().Kind() == reflect.Struct { |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 1056 | propsToMerge, err := extractStructProperties(fieldValue, indent) |
| 1057 | if err != nil { |
| 1058 | return map[string]string{}, err |
| 1059 | } |
Liz Kammer | 32a0339 | 2021-09-14 11:17:21 -0400 | [diff] [blame] | 1060 | for prop, value := range propsToMerge { |
| 1061 | ret[prop] = value |
| 1062 | } |
| 1063 | continue |
| 1064 | } |
| 1065 | } |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 1066 | |
| 1067 | propertyName := proptools.PropertyNameForField(field.Name) |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 1068 | var prettyPrintedValue string |
| 1069 | prettyPrintedValue, err = prettyPrint(fieldValue, indent+1, false) |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 1070 | if err != nil { |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 1071 | return map[string]string{}, fmt.Errorf( |
| 1072 | "Error while parsing property: %q. %s", |
| 1073 | propertyName, |
| 1074 | err) |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 1075 | } |
| 1076 | if prettyPrintedValue != "" { |
| 1077 | ret[propertyName] = prettyPrintedValue |
| 1078 | } |
| 1079 | } |
| 1080 | |
Alix | 94e2603 | 2022-08-16 20:37:33 +0000 | [diff] [blame] | 1081 | return ret, nil |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 1082 | } |
| 1083 | |
| 1084 | func isZero(value reflect.Value) bool { |
| 1085 | switch value.Kind() { |
| 1086 | case reflect.Func, reflect.Map, reflect.Slice: |
| 1087 | return value.IsNil() |
| 1088 | case reflect.Array: |
| 1089 | valueIsZero := true |
| 1090 | for i := 0; i < value.Len(); i++ { |
| 1091 | valueIsZero = valueIsZero && isZero(value.Index(i)) |
| 1092 | } |
| 1093 | return valueIsZero |
| 1094 | case reflect.Struct: |
| 1095 | valueIsZero := true |
| 1096 | for i := 0; i < value.NumField(); i++ { |
Lukacs T. Berki | 1353e59 | 2021-04-30 15:35:09 +0200 | [diff] [blame] | 1097 | valueIsZero = valueIsZero && isZero(value.Field(i)) |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 1098 | } |
| 1099 | return valueIsZero |
| 1100 | case reflect.Ptr: |
| 1101 | if !value.IsNil() { |
| 1102 | return isZero(reflect.Indirect(value)) |
| 1103 | } else { |
| 1104 | return true |
| 1105 | } |
Liz Kammer | 46fb7ab | 2021-12-01 10:09:34 -0500 | [diff] [blame] | 1106 | // Always print bool/strings, if you want a bool/string attribute to be able to take the default value, use a |
| 1107 | // pointer instead |
| 1108 | case reflect.Bool, reflect.String: |
Liz Kammer | d366c90 | 2021-06-03 13:43:01 -0400 | [diff] [blame] | 1109 | return false |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 1110 | default: |
Rupert Shuttleworth | c194ffb | 2021-05-19 06:49:02 -0400 | [diff] [blame] | 1111 | if !value.IsValid() { |
| 1112 | return true |
| 1113 | } |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 1114 | zeroValue := reflect.Zero(value.Type()) |
| 1115 | result := value.Interface() == zeroValue.Interface() |
| 1116 | return result |
| 1117 | } |
| 1118 | } |
| 1119 | |
| 1120 | func escapeString(s string) string { |
| 1121 | s = strings.ReplaceAll(s, "\\", "\\\\") |
Jingwen Chen | 58a12b8 | 2021-03-30 13:08:36 +0000 | [diff] [blame] | 1122 | |
| 1123 | // b/184026959: Reverse the application of some common control sequences. |
| 1124 | // These must be generated literally in the BUILD file. |
| 1125 | s = strings.ReplaceAll(s, "\t", "\\t") |
| 1126 | s = strings.ReplaceAll(s, "\n", "\\n") |
| 1127 | s = strings.ReplaceAll(s, "\r", "\\r") |
| 1128 | |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 1129 | return strings.ReplaceAll(s, "\"", "\\\"") |
| 1130 | } |
| 1131 | |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 1132 | func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string { |
| 1133 | name := "" |
| 1134 | if c.ModuleSubDir(logicModule) != "" { |
| 1135 | // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes. |
| 1136 | name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule) |
| 1137 | } else { |
| 1138 | name = c.ModuleName(logicModule) |
| 1139 | } |
| 1140 | |
| 1141 | return strings.Replace(name, "//", "", 1) |
| 1142 | } |
| 1143 | |
| 1144 | func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string { |
| 1145 | return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule)) |
| 1146 | } |