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