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