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