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 | |
| 17 | import ( |
| 18 | "android/soong/android" |
Liz Kammer | 356f7d4 | 2021-01-26 09:18:53 -0500 | [diff] [blame] | 19 | "android/soong/bazel" |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 20 | "fmt" |
| 21 | "reflect" |
Jingwen Chen | 4910976 | 2021-05-25 05:16:48 +0000 | [diff] [blame] | 22 | "sort" |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 23 | "strings" |
| 24 | |
| 25 | "github.com/google/blueprint" |
| 26 | "github.com/google/blueprint/proptools" |
| 27 | ) |
| 28 | |
| 29 | type BazelAttributes struct { |
| 30 | Attrs map[string]string |
| 31 | } |
| 32 | |
| 33 | type BazelTarget struct { |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 34 | name string |
Jingwen Chen | c63677b | 2021-06-17 05:43:19 +0000 | [diff] [blame] | 35 | packageName string |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 36 | content string |
| 37 | ruleClass string |
| 38 | bzlLoadLocation string |
Jingwen Chen | 4910976 | 2021-05-25 05:16:48 +0000 | [diff] [blame] | 39 | handcrafted bool |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 40 | } |
| 41 | |
| 42 | // IsLoadedFromStarlark determines if the BazelTarget's rule class is loaded from a .bzl file, |
| 43 | // as opposed to a native rule built into Bazel. |
| 44 | func (t BazelTarget) IsLoadedFromStarlark() bool { |
| 45 | return t.bzlLoadLocation != "" |
| 46 | } |
| 47 | |
Jingwen Chen | c63677b | 2021-06-17 05:43:19 +0000 | [diff] [blame] | 48 | // Label is the fully qualified Bazel label constructed from the BazelTarget's |
| 49 | // package name and target name. |
| 50 | func (t BazelTarget) Label() string { |
| 51 | if t.packageName == "." { |
| 52 | return "//:" + t.name |
| 53 | } else { |
| 54 | return "//" + t.packageName + ":" + t.name |
| 55 | } |
| 56 | } |
| 57 | |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 58 | // BazelTargets is a typedef for a slice of BazelTarget objects. |
| 59 | type BazelTargets []BazelTarget |
| 60 | |
Jingwen Chen | 4910976 | 2021-05-25 05:16:48 +0000 | [diff] [blame] | 61 | // HasHandcraftedTargetsreturns true if a set of bazel targets contain |
| 62 | // handcrafted ones. |
| 63 | func (targets BazelTargets) hasHandcraftedTargets() bool { |
| 64 | for _, target := range targets { |
| 65 | if target.handcrafted { |
| 66 | return true |
| 67 | } |
| 68 | } |
| 69 | return false |
| 70 | } |
| 71 | |
| 72 | // sort a list of BazelTargets in-place, by name, and by generated/handcrafted types. |
| 73 | func (targets BazelTargets) sort() { |
| 74 | sort.Slice(targets, func(i, j int) bool { |
| 75 | if targets[i].handcrafted != targets[j].handcrafted { |
| 76 | // Handcrafted targets will be generated after the bp2build generated targets. |
| 77 | return targets[j].handcrafted |
| 78 | } |
| 79 | // This will cover all bp2build generated targets. |
| 80 | return targets[i].name < targets[j].name |
| 81 | }) |
| 82 | } |
| 83 | |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 84 | // String returns the string representation of BazelTargets, without load |
| 85 | // statements (use LoadStatements for that), since the targets are usually not |
| 86 | // adjacent to the load statements at the top of the BUILD file. |
| 87 | func (targets BazelTargets) String() string { |
| 88 | var res string |
| 89 | for i, target := range targets { |
Jingwen Chen | 4910976 | 2021-05-25 05:16:48 +0000 | [diff] [blame] | 90 | // There is only at most 1 handcrafted "target", because its contents |
| 91 | // represent the entire BUILD file content from the tree. See |
| 92 | // build_conversion.go#getHandcraftedBuildContent for more information. |
| 93 | // |
| 94 | // Add a header to make it easy to debug where the handcrafted targets |
| 95 | // are in a generated BUILD file. |
| 96 | if target.handcrafted { |
| 97 | res += "# -----------------------------\n" |
| 98 | res += "# Section: Handcrafted targets. \n" |
| 99 | res += "# -----------------------------\n\n" |
| 100 | } |
| 101 | |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 102 | res += target.content |
| 103 | if i != len(targets)-1 { |
| 104 | res += "\n\n" |
| 105 | } |
| 106 | } |
| 107 | return res |
| 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 { |
Liz Kammer | ba3ea16 | 2021-02-17 13:22:03 -0500 | [diff] [blame] | 150 | config android.Config |
| 151 | context android.Context |
| 152 | mode CodegenMode |
| 153 | additionalDeps []string |
Jingwen Chen | daa54bc | 2020-12-14 02:58:54 -0500 | [diff] [blame] | 154 | } |
| 155 | |
Jingwen Chen | 164e086 | 2021-02-19 00:48:40 -0500 | [diff] [blame] | 156 | func (c *CodegenContext) Mode() CodegenMode { |
| 157 | return c.mode |
| 158 | } |
| 159 | |
Jingwen Chen | 33832f9 | 2021-01-24 22:55:54 -0500 | [diff] [blame] | 160 | // CodegenMode is an enum to differentiate code-generation modes. |
| 161 | type CodegenMode int |
| 162 | |
| 163 | const ( |
| 164 | // Bp2Build: generate BUILD files with targets buildable by Bazel directly. |
| 165 | // |
| 166 | // This mode is used for the Soong->Bazel build definition conversion. |
| 167 | Bp2Build CodegenMode = iota |
| 168 | |
| 169 | // QueryView: generate BUILD files with targets representing fully mutated |
| 170 | // Soong modules, representing the fully configured Soong module graph with |
| 171 | // variants and dependency endges. |
| 172 | // |
| 173 | // This mode is used for discovering and introspecting the existing Soong |
| 174 | // module graph. |
| 175 | QueryView |
| 176 | ) |
| 177 | |
Jingwen Chen | dcc329a | 2021-01-26 02:49:03 -0500 | [diff] [blame] | 178 | func (mode CodegenMode) String() string { |
| 179 | switch mode { |
| 180 | case Bp2Build: |
| 181 | return "Bp2Build" |
| 182 | case QueryView: |
| 183 | return "QueryView" |
| 184 | default: |
| 185 | return fmt.Sprintf("%d", mode) |
| 186 | } |
| 187 | } |
| 188 | |
Liz Kammer | ba3ea16 | 2021-02-17 13:22:03 -0500 | [diff] [blame] | 189 | // AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The |
| 190 | // primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the |
| 191 | // PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also |
| 192 | // call AdditionalNinjaDeps and add them manually to the ninja file. |
| 193 | func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) { |
| 194 | ctx.additionalDeps = append(ctx.additionalDeps, deps...) |
| 195 | } |
| 196 | |
| 197 | // AdditionalNinjaDeps returns additional ninja deps added by CodegenContext |
| 198 | func (ctx *CodegenContext) AdditionalNinjaDeps() []string { |
| 199 | return ctx.additionalDeps |
| 200 | } |
| 201 | |
| 202 | func (ctx *CodegenContext) Config() android.Config { return ctx.config } |
| 203 | func (ctx *CodegenContext) Context() android.Context { return ctx.context } |
Jingwen Chen | daa54bc | 2020-12-14 02:58:54 -0500 | [diff] [blame] | 204 | |
| 205 | // NewCodegenContext creates a wrapper context that conforms to PathContext for |
| 206 | // writing BUILD files in the output directory. |
Liz Kammer | ba3ea16 | 2021-02-17 13:22:03 -0500 | [diff] [blame] | 207 | func NewCodegenContext(config android.Config, context android.Context, mode CodegenMode) *CodegenContext { |
| 208 | return &CodegenContext{ |
Jingwen Chen | daa54bc | 2020-12-14 02:58:54 -0500 | [diff] [blame] | 209 | context: context, |
| 210 | config: config, |
Jingwen Chen | 33832f9 | 2021-01-24 22:55:54 -0500 | [diff] [blame] | 211 | mode: mode, |
Jingwen Chen | daa54bc | 2020-12-14 02:58:54 -0500 | [diff] [blame] | 212 | } |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 213 | } |
| 214 | |
| 215 | // props is an unsorted map. This function ensures that |
| 216 | // the generated attributes are sorted to ensure determinism. |
| 217 | func propsToAttributes(props map[string]string) string { |
| 218 | var attributes string |
| 219 | for _, propName := range android.SortedStringKeys(props) { |
| 220 | if shouldGenerateAttribute(propName) { |
| 221 | attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName]) |
| 222 | } |
| 223 | } |
| 224 | return attributes |
| 225 | } |
| 226 | |
Jingwen Chen | c63677b | 2021-06-17 05:43:19 +0000 | [diff] [blame] | 227 | func GenerateBazelTargets(ctx *CodegenContext, generateFilegroups bool) (map[string]BazelTargets, CodegenMetrics, CodegenCompatLayer) { |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 228 | buildFileToTargets := make(map[string]BazelTargets) |
Liz Kammer | ba3ea16 | 2021-02-17 13:22:03 -0500 | [diff] [blame] | 229 | buildFileToAppend := make(map[string]bool) |
Jingwen Chen | 164e086 | 2021-02-19 00:48:40 -0500 | [diff] [blame] | 230 | |
| 231 | // Simple metrics tracking for bp2build |
Liz Kammer | ba3ea16 | 2021-02-17 13:22:03 -0500 | [diff] [blame] | 232 | metrics := CodegenMetrics{ |
| 233 | RuleClassCount: make(map[string]int), |
| 234 | } |
Jingwen Chen | 164e086 | 2021-02-19 00:48:40 -0500 | [diff] [blame] | 235 | |
Jingwen Chen | c63677b | 2021-06-17 05:43:19 +0000 | [diff] [blame] | 236 | compatLayer := CodegenCompatLayer{ |
| 237 | NameToLabelMap: make(map[string]string), |
| 238 | } |
| 239 | |
Rupert Shuttleworth | 2a4fc3e | 2021-04-21 07:10:09 -0400 | [diff] [blame] | 240 | dirs := make(map[string]bool) |
| 241 | |
Jingwen Chen | 164e086 | 2021-02-19 00:48:40 -0500 | [diff] [blame] | 242 | bpCtx := ctx.Context() |
| 243 | bpCtx.VisitAllModules(func(m blueprint.Module) { |
| 244 | dir := bpCtx.ModuleDir(m) |
Rupert Shuttleworth | 2a4fc3e | 2021-04-21 07:10:09 -0400 | [diff] [blame] | 245 | dirs[dir] = true |
| 246 | |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame^] | 247 | var targets []BazelTarget |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 248 | |
Jingwen Chen | 164e086 | 2021-02-19 00:48:40 -0500 | [diff] [blame] | 249 | switch ctx.Mode() { |
Jingwen Chen | 33832f9 | 2021-01-24 22:55:54 -0500 | [diff] [blame] | 250 | case Bp2Build: |
Liz Kammer | ba3ea16 | 2021-02-17 13:22:03 -0500 | [diff] [blame] | 251 | if b, ok := m.(android.Bazelable); ok && b.HasHandcraftedLabel() { |
| 252 | metrics.handCraftedTargetCount += 1 |
| 253 | metrics.TotalModuleCount += 1 |
Jingwen Chen | c63677b | 2021-06-17 05:43:19 +0000 | [diff] [blame] | 254 | compatLayer.AddNameToLabelEntry(m.Name(), b.HandcraftedLabel()) |
Liz Kammer | ba3ea16 | 2021-02-17 13:22:03 -0500 | [diff] [blame] | 255 | pathToBuildFile := getBazelPackagePath(b) |
| 256 | // We are using the entire contents of handcrafted build file, so if multiple targets within |
| 257 | // a package have handcrafted targets, we only want to include the contents one time. |
| 258 | if _, exists := buildFileToAppend[pathToBuildFile]; exists { |
| 259 | return |
| 260 | } |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame^] | 261 | t, err := getHandcraftedBuildContent(ctx, b, pathToBuildFile) |
Liz Kammer | ba3ea16 | 2021-02-17 13:22:03 -0500 | [diff] [blame] | 262 | if err != nil { |
| 263 | panic(fmt.Errorf("Error converting %s: %s", bpCtx.ModuleName(m), err)) |
| 264 | } |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame^] | 265 | targets = append(targets, t) |
Liz Kammer | ba3ea16 | 2021-02-17 13:22:03 -0500 | [diff] [blame] | 266 | // TODO(b/181575318): currently we append the whole BUILD file, let's change that to do |
| 267 | // something more targeted based on the rule type and target |
| 268 | buildFileToAppend[pathToBuildFile] = true |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame^] | 269 | } else if aModule, ok := m.(android.Module); ok && aModule.IsConvertedByBp2build() { |
| 270 | targets = generateBazelTargets(bpCtx, aModule) |
| 271 | for _, t := range targets { |
| 272 | if t.name == m.Name() { |
| 273 | // only add targets that exist in Soong to compatibility layer |
| 274 | compatLayer.AddNameToLabelEntry(m.Name(), t.Label()) |
| 275 | } |
| 276 | metrics.RuleClassCount[t.ruleClass] += 1 |
| 277 | } |
Liz Kammer | fc46bc1 | 2021-02-19 11:06:17 -0500 | [diff] [blame] | 278 | } else { |
Liz Kammer | ba3ea16 | 2021-02-17 13:22:03 -0500 | [diff] [blame] | 279 | metrics.TotalModuleCount += 1 |
| 280 | return |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 281 | } |
Jingwen Chen | 33832f9 | 2021-01-24 22:55:54 -0500 | [diff] [blame] | 282 | case QueryView: |
Jingwen Chen | 96af35b | 2021-02-08 00:49:32 -0500 | [diff] [blame] | 283 | // Blocklist certain module types from being generated. |
Jingwen Chen | 164e086 | 2021-02-19 00:48:40 -0500 | [diff] [blame] | 284 | if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" { |
Jingwen Chen | 96af35b | 2021-02-08 00:49:32 -0500 | [diff] [blame] | 285 | // package module name contain slashes, and thus cannot |
| 286 | // be mapped cleanly to a bazel label. |
| 287 | return |
| 288 | } |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame^] | 289 | t := generateSoongModuleTarget(bpCtx, m) |
| 290 | targets = append(targets, t) |
Jingwen Chen | 33832f9 | 2021-01-24 22:55:54 -0500 | [diff] [blame] | 291 | default: |
Jingwen Chen | 164e086 | 2021-02-19 00:48:40 -0500 | [diff] [blame] | 292 | panic(fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode())) |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 293 | } |
| 294 | |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame^] | 295 | buildFileToTargets[dir] = append(buildFileToTargets[dir], targets...) |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 296 | }) |
Rupert Shuttleworth | 2a4fc3e | 2021-04-21 07:10:09 -0400 | [diff] [blame] | 297 | if generateFilegroups { |
| 298 | // Add a filegroup target that exposes all sources in the subtree of this package |
| 299 | // NOTE: This also means we generate a BUILD file for every Android.bp file (as long as it has at least one module) |
| 300 | for dir, _ := range dirs { |
| 301 | buildFileToTargets[dir] = append(buildFileToTargets[dir], BazelTarget{ |
| 302 | name: "bp2build_all_srcs", |
| 303 | content: `filegroup(name = "bp2build_all_srcs", srcs = glob(["**/*"]))`, |
| 304 | ruleClass: "filegroup", |
| 305 | }) |
| 306 | } |
| 307 | } |
Jingwen Chen | 164e086 | 2021-02-19 00:48:40 -0500 | [diff] [blame] | 308 | |
Jingwen Chen | c63677b | 2021-06-17 05:43:19 +0000 | [diff] [blame] | 309 | return buildFileToTargets, metrics, compatLayer |
Jingwen Chen | 164e086 | 2021-02-19 00:48:40 -0500 | [diff] [blame] | 310 | } |
| 311 | |
Liz Kammer | ba3ea16 | 2021-02-17 13:22:03 -0500 | [diff] [blame] | 312 | func getBazelPackagePath(b android.Bazelable) string { |
Liz Kammer | bdc6099 | 2021-02-24 16:55:11 -0500 | [diff] [blame] | 313 | label := b.HandcraftedLabel() |
Liz Kammer | ba3ea16 | 2021-02-17 13:22:03 -0500 | [diff] [blame] | 314 | pathToBuildFile := strings.TrimPrefix(label, "//") |
| 315 | pathToBuildFile = strings.Split(pathToBuildFile, ":")[0] |
| 316 | return pathToBuildFile |
| 317 | } |
| 318 | |
| 319 | func getHandcraftedBuildContent(ctx *CodegenContext, b android.Bazelable, pathToBuildFile string) (BazelTarget, error) { |
| 320 | p := android.ExistentPathForSource(ctx, pathToBuildFile, HandcraftedBuildFileName) |
| 321 | if !p.Valid() { |
| 322 | return BazelTarget{}, fmt.Errorf("Could not find file %q for handcrafted target.", pathToBuildFile) |
| 323 | } |
| 324 | c, err := b.GetBazelBuildFileContents(ctx.Config(), pathToBuildFile, HandcraftedBuildFileName) |
| 325 | if err != nil { |
| 326 | return BazelTarget{}, err |
| 327 | } |
| 328 | // TODO(b/181575318): once this is more targeted, we need to include name, rule class, etc |
| 329 | return BazelTarget{ |
Jingwen Chen | 4910976 | 2021-05-25 05:16:48 +0000 | [diff] [blame] | 330 | content: c, |
| 331 | handcrafted: true, |
Liz Kammer | ba3ea16 | 2021-02-17 13:22:03 -0500 | [diff] [blame] | 332 | }, nil |
| 333 | } |
| 334 | |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame^] | 335 | func generateBazelTargets(ctx bpToBuildContext, m android.Module) []BazelTarget { |
| 336 | var targets []BazelTarget |
| 337 | for _, m := range m.Bp2buildTargets() { |
| 338 | targets = append(targets, generateBazelTarget(ctx, m)) |
| 339 | } |
| 340 | return targets |
| 341 | } |
| 342 | |
| 343 | type bp2buildModule interface { |
| 344 | TargetName() string |
| 345 | TargetPackage() string |
| 346 | BazelRuleClass() string |
| 347 | BazelRuleLoadLocation() string |
| 348 | BazelAttributes() interface{} |
| 349 | } |
| 350 | |
| 351 | func generateBazelTarget(ctx bpToBuildContext, m bp2buildModule) BazelTarget { |
| 352 | ruleClass := m.BazelRuleClass() |
| 353 | bzlLoadLocation := m.BazelRuleLoadLocation() |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 354 | |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 355 | // extract the bazel attributes from the module. |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame^] | 356 | props := extractModuleProperties([]interface{}{m.BazelAttributes()}) |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 357 | |
Jingwen Chen | 77e8b7b | 2021-02-05 03:03:24 -0500 | [diff] [blame] | 358 | delete(props.Attrs, "bp2build_available") |
| 359 | |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 360 | // Return the Bazel target with rule class and attributes, ready to be |
| 361 | // code-generated. |
| 362 | attributes := propsToAttributes(props.Attrs) |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame^] | 363 | targetName := m.TargetName() |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 364 | return BazelTarget{ |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 365 | name: targetName, |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame^] | 366 | packageName: m.TargetPackage(), |
Jingwen Chen | 40067de | 2021-01-26 21:58:43 -0500 | [diff] [blame] | 367 | ruleClass: ruleClass, |
| 368 | bzlLoadLocation: bzlLoadLocation, |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 369 | content: fmt.Sprintf( |
| 370 | bazelTarget, |
| 371 | ruleClass, |
| 372 | targetName, |
| 373 | attributes, |
| 374 | ), |
Jingwen Chen | 4910976 | 2021-05-25 05:16:48 +0000 | [diff] [blame] | 375 | handcrafted: false, |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 376 | } |
| 377 | } |
| 378 | |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 379 | // Convert a module and its deps and props into a Bazel macro/rule |
| 380 | // representation in the BUILD file. |
| 381 | func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) BazelTarget { |
| 382 | props := getBuildProperties(ctx, m) |
| 383 | |
| 384 | // TODO(b/163018919): DirectDeps can have duplicate (module, variant) |
| 385 | // items, if the modules are added using different DependencyTag. Figure |
| 386 | // out the implications of that. |
| 387 | depLabels := map[string]bool{} |
| 388 | if aModule, ok := m.(android.Module); ok { |
Jingwen Chen | daa54bc | 2020-12-14 02:58:54 -0500 | [diff] [blame] | 389 | ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) { |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 390 | depLabels[qualifiedTargetLabel(ctx, depModule)] = true |
| 391 | }) |
| 392 | } |
| 393 | attributes := propsToAttributes(props.Attrs) |
| 394 | |
| 395 | depLabelList := "[\n" |
| 396 | for depLabel, _ := range depLabels { |
| 397 | depLabelList += fmt.Sprintf(" %q,\n", depLabel) |
| 398 | } |
| 399 | depLabelList += " ]" |
| 400 | |
| 401 | targetName := targetNameWithVariant(ctx, m) |
| 402 | return BazelTarget{ |
| 403 | name: targetName, |
| 404 | content: fmt.Sprintf( |
| 405 | soongModuleTarget, |
| 406 | targetName, |
| 407 | ctx.ModuleName(m), |
| 408 | canonicalizeModuleType(ctx.ModuleType(m)), |
| 409 | ctx.ModuleSubDir(m), |
| 410 | depLabelList, |
| 411 | attributes), |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) BazelAttributes { |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 416 | // TODO: this omits properties for blueprint modules (blueprint_go_binary, |
| 417 | // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately. |
| 418 | if aModule, ok := m.(android.Module); ok { |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame^] | 419 | return extractModuleProperties(aModule.GetProperties()) |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 420 | } |
| 421 | |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame^] | 422 | return BazelAttributes{} |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 423 | } |
| 424 | |
| 425 | // Generically extract module properties and types into a map, keyed by the module property name. |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame^] | 426 | func extractModuleProperties(props []interface{}) BazelAttributes { |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 427 | ret := map[string]string{} |
| 428 | |
| 429 | // Iterate over this android.Module's property structs. |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame^] | 430 | for _, properties := range props { |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 431 | propertiesValue := reflect.ValueOf(properties) |
| 432 | // Check that propertiesValue is a pointer to the Properties struct, like |
| 433 | // *cc.BaseLinkerProperties or *java.CompilerProperties. |
| 434 | // |
| 435 | // propertiesValue can also be type-asserted to the structs to |
| 436 | // manipulate internal props, if needed. |
| 437 | if isStructPtr(propertiesValue.Type()) { |
| 438 | structValue := propertiesValue.Elem() |
| 439 | for k, v := range extractStructProperties(structValue, 0) { |
| 440 | ret[k] = v |
| 441 | } |
| 442 | } else { |
| 443 | panic(fmt.Errorf( |
| 444 | "properties must be a pointer to a struct, got %T", |
| 445 | propertiesValue.Interface())) |
| 446 | } |
| 447 | } |
| 448 | |
Liz Kammer | 2ada09a | 2021-08-11 00:17:36 -0400 | [diff] [blame^] | 449 | return BazelAttributes{ |
| 450 | Attrs: ret, |
| 451 | } |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 452 | } |
| 453 | |
| 454 | func isStructPtr(t reflect.Type) bool { |
| 455 | return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct |
| 456 | } |
| 457 | |
| 458 | // prettyPrint a property value into the equivalent Starlark representation |
| 459 | // recursively. |
| 460 | func prettyPrint(propertyValue reflect.Value, indent int) (string, error) { |
| 461 | if isZero(propertyValue) { |
| 462 | // A property value being set or unset actually matters -- Soong does set default |
| 463 | // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at |
| 464 | // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480 |
| 465 | // |
Jingwen Chen | fc490bd | 2021-03-30 10:24:19 +0000 | [diff] [blame] | 466 | // In Bazel-parlance, we would use "attr.<type>(default = <default |
| 467 | // value>)" to set the default value of unset attributes. In the cases |
| 468 | // where the bp2build converter didn't set the default value within the |
| 469 | // mutator when creating the BazelTargetModule, this would be a zero |
Jingwen Chen | 6393098 | 2021-03-24 10:04:33 -0400 | [diff] [blame] | 470 | // value. For those cases, we return an empty string so we don't |
| 471 | // unnecessarily generate empty values. |
| 472 | return "", nil |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 473 | } |
| 474 | |
| 475 | var ret string |
| 476 | switch propertyValue.Kind() { |
| 477 | case reflect.String: |
| 478 | ret = fmt.Sprintf("\"%v\"", escapeString(propertyValue.String())) |
| 479 | case reflect.Bool: |
| 480 | ret = strings.Title(fmt.Sprintf("%v", propertyValue.Interface())) |
| 481 | case reflect.Int, reflect.Uint, reflect.Int64: |
| 482 | ret = fmt.Sprintf("%v", propertyValue.Interface()) |
| 483 | case reflect.Ptr: |
| 484 | return prettyPrint(propertyValue.Elem(), indent) |
| 485 | case reflect.Slice: |
Jingwen Chen | 6393098 | 2021-03-24 10:04:33 -0400 | [diff] [blame] | 486 | if propertyValue.Len() == 0 { |
Liz Kammer | 2b07ec7 | 2021-05-26 15:08:27 -0400 | [diff] [blame] | 487 | return "[]", nil |
Jingwen Chen | 6393098 | 2021-03-24 10:04:33 -0400 | [diff] [blame] | 488 | } |
| 489 | |
Jingwen Chen | b4628eb | 2021-04-08 14:40:57 +0000 | [diff] [blame] | 490 | if propertyValue.Len() == 1 { |
| 491 | // Single-line list for list with only 1 element |
| 492 | ret += "[" |
| 493 | indexedValue, err := prettyPrint(propertyValue.Index(0), indent) |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 494 | if err != nil { |
| 495 | return "", err |
| 496 | } |
Jingwen Chen | b4628eb | 2021-04-08 14:40:57 +0000 | [diff] [blame] | 497 | ret += indexedValue |
| 498 | ret += "]" |
| 499 | } else { |
| 500 | // otherwise, use a multiline list. |
| 501 | ret += "[\n" |
| 502 | for i := 0; i < propertyValue.Len(); i++ { |
| 503 | indexedValue, err := prettyPrint(propertyValue.Index(i), indent+1) |
| 504 | if err != nil { |
| 505 | return "", err |
| 506 | } |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 507 | |
Jingwen Chen | b4628eb | 2021-04-08 14:40:57 +0000 | [diff] [blame] | 508 | if indexedValue != "" { |
| 509 | ret += makeIndent(indent + 1) |
| 510 | ret += indexedValue |
| 511 | ret += ",\n" |
| 512 | } |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 513 | } |
Jingwen Chen | b4628eb | 2021-04-08 14:40:57 +0000 | [diff] [blame] | 514 | ret += makeIndent(indent) |
| 515 | ret += "]" |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 516 | } |
Jingwen Chen | b4628eb | 2021-04-08 14:40:57 +0000 | [diff] [blame] | 517 | |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 518 | case reflect.Struct: |
Jingwen Chen | 5d86449 | 2021-02-24 07:20:12 -0500 | [diff] [blame] | 519 | // Special cases where the bp2build sends additional information to the codegenerator |
| 520 | // by wrapping the attributes in a custom struct type. |
Jingwen Chen | c1c2650 | 2021-04-05 10:35:13 +0000 | [diff] [blame] | 521 | if attr, ok := propertyValue.Interface().(bazel.Attribute); ok { |
| 522 | return prettyPrintAttribute(attr, indent) |
Liz Kammer | 356f7d4 | 2021-01-26 09:18:53 -0500 | [diff] [blame] | 523 | } else if label, ok := propertyValue.Interface().(bazel.Label); ok { |
| 524 | return fmt.Sprintf("%q", label.Label), nil |
| 525 | } |
| 526 | |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 527 | ret = "{\n" |
| 528 | // Sort and print the struct props by the key. |
| 529 | structProps := extractStructProperties(propertyValue, indent) |
Jingwen Chen | 3d383bb | 2021-06-09 07:18:37 +0000 | [diff] [blame] | 530 | if len(structProps) == 0 { |
| 531 | return "", nil |
| 532 | } |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 533 | for _, k := range android.SortedStringKeys(structProps) { |
| 534 | ret += makeIndent(indent + 1) |
| 535 | ret += fmt.Sprintf("%q: %s,\n", k, structProps[k]) |
| 536 | } |
| 537 | ret += makeIndent(indent) |
| 538 | ret += "}" |
| 539 | case reflect.Interface: |
| 540 | // TODO(b/164227191): implement pretty print for interfaces. |
| 541 | // Interfaces are used for for arch, multilib and target properties. |
| 542 | return "", nil |
| 543 | default: |
| 544 | return "", fmt.Errorf( |
| 545 | "unexpected kind for property struct field: %s", propertyValue.Kind()) |
| 546 | } |
| 547 | return ret, nil |
| 548 | } |
| 549 | |
| 550 | // Converts a reflected property struct value into a map of property names and property values, |
| 551 | // which each property value correctly pretty-printed and indented at the right nest level, |
| 552 | // since property structs can be nested. In Starlark, nested structs are represented as nested |
| 553 | // dicts: https://docs.bazel.build/skylark/lib/dict.html |
| 554 | func extractStructProperties(structValue reflect.Value, indent int) map[string]string { |
| 555 | if structValue.Kind() != reflect.Struct { |
| 556 | panic(fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind())) |
| 557 | } |
| 558 | |
| 559 | ret := map[string]string{} |
| 560 | structType := structValue.Type() |
| 561 | for i := 0; i < structValue.NumField(); i++ { |
| 562 | field := structType.Field(i) |
| 563 | if shouldSkipStructField(field) { |
| 564 | continue |
| 565 | } |
| 566 | |
| 567 | fieldValue := structValue.Field(i) |
| 568 | if isZero(fieldValue) { |
| 569 | // Ignore zero-valued fields |
| 570 | continue |
| 571 | } |
| 572 | |
| 573 | propertyName := proptools.PropertyNameForField(field.Name) |
| 574 | prettyPrintedValue, err := prettyPrint(fieldValue, indent+1) |
| 575 | if err != nil { |
| 576 | panic( |
| 577 | fmt.Errorf( |
| 578 | "Error while parsing property: %q. %s", |
| 579 | propertyName, |
| 580 | err)) |
| 581 | } |
| 582 | if prettyPrintedValue != "" { |
| 583 | ret[propertyName] = prettyPrintedValue |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | return ret |
| 588 | } |
| 589 | |
| 590 | func isZero(value reflect.Value) bool { |
| 591 | switch value.Kind() { |
| 592 | case reflect.Func, reflect.Map, reflect.Slice: |
| 593 | return value.IsNil() |
| 594 | case reflect.Array: |
| 595 | valueIsZero := true |
| 596 | for i := 0; i < value.Len(); i++ { |
| 597 | valueIsZero = valueIsZero && isZero(value.Index(i)) |
| 598 | } |
| 599 | return valueIsZero |
| 600 | case reflect.Struct: |
| 601 | valueIsZero := true |
| 602 | for i := 0; i < value.NumField(); i++ { |
Lukacs T. Berki | 1353e59 | 2021-04-30 15:35:09 +0200 | [diff] [blame] | 603 | valueIsZero = valueIsZero && isZero(value.Field(i)) |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 604 | } |
| 605 | return valueIsZero |
| 606 | case reflect.Ptr: |
| 607 | if !value.IsNil() { |
| 608 | return isZero(reflect.Indirect(value)) |
| 609 | } else { |
| 610 | return true |
| 611 | } |
Liz Kammer | d366c90 | 2021-06-03 13:43:01 -0400 | [diff] [blame] | 612 | // Always print bools, if you want a bool attribute to be able to take the default value, use a |
| 613 | // bool pointer instead |
| 614 | case reflect.Bool: |
| 615 | return false |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 616 | default: |
Rupert Shuttleworth | c194ffb | 2021-05-19 06:49:02 -0400 | [diff] [blame] | 617 | if !value.IsValid() { |
| 618 | return true |
| 619 | } |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 620 | zeroValue := reflect.Zero(value.Type()) |
| 621 | result := value.Interface() == zeroValue.Interface() |
| 622 | return result |
| 623 | } |
| 624 | } |
| 625 | |
| 626 | func escapeString(s string) string { |
| 627 | s = strings.ReplaceAll(s, "\\", "\\\\") |
Jingwen Chen | 58a12b8 | 2021-03-30 13:08:36 +0000 | [diff] [blame] | 628 | |
| 629 | // b/184026959: Reverse the application of some common control sequences. |
| 630 | // These must be generated literally in the BUILD file. |
| 631 | s = strings.ReplaceAll(s, "\t", "\\t") |
| 632 | s = strings.ReplaceAll(s, "\n", "\\n") |
| 633 | s = strings.ReplaceAll(s, "\r", "\\r") |
| 634 | |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 635 | return strings.ReplaceAll(s, "\"", "\\\"") |
| 636 | } |
| 637 | |
| 638 | func makeIndent(indent int) string { |
| 639 | if indent < 0 { |
| 640 | panic(fmt.Errorf("indent column cannot be less than 0, but got %d", indent)) |
| 641 | } |
| 642 | return strings.Repeat(" ", indent) |
| 643 | } |
| 644 | |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 645 | func targetNameForBp2Build(c bpToBuildContext, logicModule blueprint.Module) string { |
Jingwen Chen | fb4692a | 2021-02-07 10:05:16 -0500 | [diff] [blame] | 646 | return strings.Replace(c.ModuleName(logicModule), bazel.BazelTargetModuleNamePrefix, "", 1) |
Jingwen Chen | 7385067 | 2020-12-14 08:25:34 -0500 | [diff] [blame] | 647 | } |
| 648 | |
Liz Kammer | 2dd9ca4 | 2020-11-25 16:06:39 -0800 | [diff] [blame] | 649 | func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string { |
| 650 | name := "" |
| 651 | if c.ModuleSubDir(logicModule) != "" { |
| 652 | // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes. |
| 653 | name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule) |
| 654 | } else { |
| 655 | name = c.ModuleName(logicModule) |
| 656 | } |
| 657 | |
| 658 | return strings.Replace(name, "//", "", 1) |
| 659 | } |
| 660 | |
| 661 | func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string { |
| 662 | return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule)) |
| 663 | } |