blob: fcad6862176922440f59a75d25444aa96a324d2a [file] [log] [blame]
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001// 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
15package bp2build
16
17import (
18 "android/soong/android"
Liz Kammer356f7d42021-01-26 09:18:53 -050019 "android/soong/bazel"
Liz Kammer2dd9ca42020-11-25 16:06:39 -080020 "fmt"
21 "reflect"
Jingwen Chen40067de2021-01-26 21:58:43 -050022 "strconv"
Liz Kammer2dd9ca42020-11-25 16:06:39 -080023 "strings"
24
25 "github.com/google/blueprint"
26 "github.com/google/blueprint/proptools"
27)
28
29type BazelAttributes struct {
30 Attrs map[string]string
31}
32
33type BazelTarget struct {
Jingwen Chen40067de2021-01-26 21:58:43 -050034 name string
35 content string
36 ruleClass string
37 bzlLoadLocation string
38}
39
40// IsLoadedFromStarlark determines if the BazelTarget's rule class is loaded from a .bzl file,
41// as opposed to a native rule built into Bazel.
42func (t BazelTarget) IsLoadedFromStarlark() bool {
43 return t.bzlLoadLocation != ""
44}
45
46// BazelTargets is a typedef for a slice of BazelTarget objects.
47type BazelTargets []BazelTarget
48
49// String returns the string representation of BazelTargets, without load
50// statements (use LoadStatements for that), since the targets are usually not
51// adjacent to the load statements at the top of the BUILD file.
52func (targets BazelTargets) String() string {
53 var res string
54 for i, target := range targets {
55 res += target.content
56 if i != len(targets)-1 {
57 res += "\n\n"
58 }
59 }
60 return res
61}
62
63// LoadStatements return the string representation of the sorted and deduplicated
64// Starlark rule load statements needed by a group of BazelTargets.
65func (targets BazelTargets) LoadStatements() string {
66 bzlToLoadedSymbols := map[string][]string{}
67 for _, target := range targets {
68 if target.IsLoadedFromStarlark() {
69 bzlToLoadedSymbols[target.bzlLoadLocation] =
70 append(bzlToLoadedSymbols[target.bzlLoadLocation], target.ruleClass)
71 }
72 }
73
74 var loadStatements []string
75 for bzl, ruleClasses := range bzlToLoadedSymbols {
76 loadStatement := "load(\""
77 loadStatement += bzl
78 loadStatement += "\", "
79 ruleClasses = android.SortedUniqueStrings(ruleClasses)
80 for i, ruleClass := range ruleClasses {
81 loadStatement += "\"" + ruleClass + "\""
82 if i != len(ruleClasses)-1 {
83 loadStatement += ", "
84 }
85 }
86 loadStatement += ")"
87 loadStatements = append(loadStatements, loadStatement)
88 }
89 return strings.Join(android.SortedUniqueStrings(loadStatements), "\n")
Liz Kammer2dd9ca42020-11-25 16:06:39 -080090}
91
92type bpToBuildContext interface {
93 ModuleName(module blueprint.Module) string
94 ModuleDir(module blueprint.Module) string
95 ModuleSubDir(module blueprint.Module) string
96 ModuleType(module blueprint.Module) string
97
Jingwen Chendaa54bc2020-12-14 02:58:54 -050098 VisitAllModules(visit func(blueprint.Module))
99 VisitDirectDeps(module blueprint.Module, visit func(blueprint.Module))
100}
101
102type CodegenContext struct {
103 config android.Config
104 context android.Context
Jingwen Chen33832f92021-01-24 22:55:54 -0500105 mode CodegenMode
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500106}
107
Jingwen Chen164e0862021-02-19 00:48:40 -0500108func (c *CodegenContext) Mode() CodegenMode {
109 return c.mode
110}
111
Jingwen Chen33832f92021-01-24 22:55:54 -0500112// CodegenMode is an enum to differentiate code-generation modes.
113type CodegenMode int
114
115const (
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 Chendcc329a2021-01-26 02:49:03 -0500130func (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
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500141func (ctx CodegenContext) AddNinjaFileDeps(...string) {}
142func (ctx CodegenContext) Config() android.Config { return ctx.config }
143func (ctx CodegenContext) Context() android.Context { return ctx.context }
144
145// NewCodegenContext creates a wrapper context that conforms to PathContext for
146// writing BUILD files in the output directory.
Jingwen Chen33832f92021-01-24 22:55:54 -0500147func NewCodegenContext(config android.Config, context android.Context, mode CodegenMode) CodegenContext {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500148 return CodegenContext{
149 context: context,
150 config: config,
Jingwen Chen33832f92021-01-24 22:55:54 -0500151 mode: mode,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500152 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800153}
154
155// props is an unsorted map. This function ensures that
156// the generated attributes are sorted to ensure determinism.
157func propsToAttributes(props map[string]string) string {
158 var attributes string
159 for _, propName := range android.SortedStringKeys(props) {
160 if shouldGenerateAttribute(propName) {
161 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
162 }
163 }
164 return attributes
165}
166
Jingwen Chen164e0862021-02-19 00:48:40 -0500167func GenerateBazelTargets(ctx CodegenContext) (map[string]BazelTargets, CodegenMetrics) {
Jingwen Chen40067de2021-01-26 21:58:43 -0500168 buildFileToTargets := make(map[string]BazelTargets)
Jingwen Chen164e0862021-02-19 00:48:40 -0500169
170 // Simple metrics tracking for bp2build
171 totalModuleCount := 0
172 ruleClassCount := make(map[string]int)
173
174 bpCtx := ctx.Context()
175 bpCtx.VisitAllModules(func(m blueprint.Module) {
176 dir := bpCtx.ModuleDir(m)
Jingwen Chen73850672020-12-14 08:25:34 -0500177 var t BazelTarget
178
Jingwen Chen164e0862021-02-19 00:48:40 -0500179 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500180 case Bp2Build:
Jingwen Chen73850672020-12-14 08:25:34 -0500181 if _, ok := m.(android.BazelTargetModule); !ok {
Jingwen Chen164e0862021-02-19 00:48:40 -0500182 // Only include regular Soong modules (non-BazelTargetModules) into the total count.
183 totalModuleCount += 1
Jingwen Chen73850672020-12-14 08:25:34 -0500184 return
185 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500186 t = generateBazelTarget(bpCtx, m)
187 ruleClassCount[t.ruleClass] += 1
Jingwen Chen33832f92021-01-24 22:55:54 -0500188 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500189 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500190 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500191 // package module name contain slashes, and thus cannot
192 // be mapped cleanly to a bazel label.
193 return
194 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500195 t = generateSoongModuleTarget(bpCtx, m)
Jingwen Chen33832f92021-01-24 22:55:54 -0500196 default:
Jingwen Chen164e0862021-02-19 00:48:40 -0500197 panic(fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
Jingwen Chen73850672020-12-14 08:25:34 -0500198 }
199
Liz Kammer356f7d42021-01-26 09:18:53 -0500200 buildFileToTargets[dir] = append(buildFileToTargets[dir], t)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800201 })
Jingwen Chen164e0862021-02-19 00:48:40 -0500202
203 metrics := CodegenMetrics{
204 TotalModuleCount: totalModuleCount,
205 RuleClassCount: ruleClassCount,
206 }
207
208 return buildFileToTargets, metrics
209}
210
211// Helper method for tests to easily access the targets in a dir.
212func GenerateBazelTargetsForDir(codegenCtx CodegenContext, dir string) BazelTargets {
213 bazelTargetsMap, _ := GenerateBazelTargets(codegenCtx)
214 return bazelTargetsMap[dir]
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800215}
216
Jingwen Chen40067de2021-01-26 21:58:43 -0500217// Helper method to trim quotes around strings.
218func trimQuotes(s string) string {
219 if s == "" {
220 // strconv.Unquote would error out on empty strings, but this method
221 // allows them, so return the empty string directly.
222 return ""
223 }
224 ret, err := strconv.Unquote(s)
225 if err != nil {
226 // Panic the error immediately.
227 panic(fmt.Errorf("Trying to unquote '%s', but got error: %s", s, err))
228 }
229 return ret
230}
231
Jingwen Chen73850672020-12-14 08:25:34 -0500232func generateBazelTarget(ctx bpToBuildContext, m blueprint.Module) BazelTarget {
233 // extract the bazel attributes from the module.
234 props := getBuildProperties(ctx, m)
235
236 // extract the rule class name from the attributes. Since the string value
237 // will be string-quoted, remove the quotes here.
Jingwen Chen40067de2021-01-26 21:58:43 -0500238 ruleClass := trimQuotes(props.Attrs["rule_class"])
Jingwen Chen73850672020-12-14 08:25:34 -0500239 // Delete it from being generated in the BUILD file.
240 delete(props.Attrs, "rule_class")
241
Jingwen Chen40067de2021-01-26 21:58:43 -0500242 // extract the bzl_load_location, and also remove the quotes around it here.
243 bzlLoadLocation := trimQuotes(props.Attrs["bzl_load_location"])
244 // Delete it from being generated in the BUILD file.
245 delete(props.Attrs, "bzl_load_location")
246
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500247 delete(props.Attrs, "bp2build_available")
248
Jingwen Chen73850672020-12-14 08:25:34 -0500249 // Return the Bazel target with rule class and attributes, ready to be
250 // code-generated.
251 attributes := propsToAttributes(props.Attrs)
252 targetName := targetNameForBp2Build(ctx, m)
253 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500254 name: targetName,
255 ruleClass: ruleClass,
256 bzlLoadLocation: bzlLoadLocation,
Jingwen Chen73850672020-12-14 08:25:34 -0500257 content: fmt.Sprintf(
258 bazelTarget,
259 ruleClass,
260 targetName,
261 attributes,
262 ),
263 }
264}
265
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800266// Convert a module and its deps and props into a Bazel macro/rule
267// representation in the BUILD file.
268func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) BazelTarget {
269 props := getBuildProperties(ctx, m)
270
271 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
272 // items, if the modules are added using different DependencyTag. Figure
273 // out the implications of that.
274 depLabels := map[string]bool{}
275 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500276 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800277 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
278 })
279 }
280 attributes := propsToAttributes(props.Attrs)
281
282 depLabelList := "[\n"
283 for depLabel, _ := range depLabels {
284 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
285 }
286 depLabelList += " ]"
287
288 targetName := targetNameWithVariant(ctx, m)
289 return BazelTarget{
290 name: targetName,
291 content: fmt.Sprintf(
292 soongModuleTarget,
293 targetName,
294 ctx.ModuleName(m),
295 canonicalizeModuleType(ctx.ModuleType(m)),
296 ctx.ModuleSubDir(m),
297 depLabelList,
298 attributes),
299 }
300}
301
302func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) BazelAttributes {
303 var allProps map[string]string
304 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
305 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
306 if aModule, ok := m.(android.Module); ok {
307 allProps = ExtractModuleProperties(aModule)
308 }
309
310 return BazelAttributes{
311 Attrs: allProps,
312 }
313}
314
315// Generically extract module properties and types into a map, keyed by the module property name.
316func ExtractModuleProperties(aModule android.Module) map[string]string {
317 ret := map[string]string{}
318
319 // Iterate over this android.Module's property structs.
320 for _, properties := range aModule.GetProperties() {
321 propertiesValue := reflect.ValueOf(properties)
322 // Check that propertiesValue is a pointer to the Properties struct, like
323 // *cc.BaseLinkerProperties or *java.CompilerProperties.
324 //
325 // propertiesValue can also be type-asserted to the structs to
326 // manipulate internal props, if needed.
327 if isStructPtr(propertiesValue.Type()) {
328 structValue := propertiesValue.Elem()
329 for k, v := range extractStructProperties(structValue, 0) {
330 ret[k] = v
331 }
332 } else {
333 panic(fmt.Errorf(
334 "properties must be a pointer to a struct, got %T",
335 propertiesValue.Interface()))
336 }
337 }
338
339 return ret
340}
341
342func isStructPtr(t reflect.Type) bool {
343 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
344}
345
346// prettyPrint a property value into the equivalent Starlark representation
347// recursively.
348func prettyPrint(propertyValue reflect.Value, indent int) (string, error) {
349 if isZero(propertyValue) {
350 // A property value being set or unset actually matters -- Soong does set default
351 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
352 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
353 //
354 // In Bazel-parlance, we would use "attr.<type>(default = <default value>)" to set the default
355 // value of unset attributes.
356 return "", nil
357 }
358
359 var ret string
360 switch propertyValue.Kind() {
361 case reflect.String:
362 ret = fmt.Sprintf("\"%v\"", escapeString(propertyValue.String()))
363 case reflect.Bool:
364 ret = strings.Title(fmt.Sprintf("%v", propertyValue.Interface()))
365 case reflect.Int, reflect.Uint, reflect.Int64:
366 ret = fmt.Sprintf("%v", propertyValue.Interface())
367 case reflect.Ptr:
368 return prettyPrint(propertyValue.Elem(), indent)
369 case reflect.Slice:
370 ret = "[\n"
371 for i := 0; i < propertyValue.Len(); i++ {
372 indexedValue, err := prettyPrint(propertyValue.Index(i), indent+1)
373 if err != nil {
374 return "", err
375 }
376
377 if indexedValue != "" {
378 ret += makeIndent(indent + 1)
379 ret += indexedValue
380 ret += ",\n"
381 }
382 }
383 ret += makeIndent(indent)
384 ret += "]"
385 case reflect.Struct:
Liz Kammer356f7d42021-01-26 09:18:53 -0500386 if labels, ok := propertyValue.Interface().(bazel.LabelList); ok {
387 // TODO(b/165114590): convert glob syntax
388 return prettyPrint(reflect.ValueOf(labels.Includes), indent)
389 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
390 return fmt.Sprintf("%q", label.Label), nil
391 }
392
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800393 ret = "{\n"
394 // Sort and print the struct props by the key.
395 structProps := extractStructProperties(propertyValue, indent)
396 for _, k := range android.SortedStringKeys(structProps) {
397 ret += makeIndent(indent + 1)
398 ret += fmt.Sprintf("%q: %s,\n", k, structProps[k])
399 }
400 ret += makeIndent(indent)
401 ret += "}"
402 case reflect.Interface:
403 // TODO(b/164227191): implement pretty print for interfaces.
404 // Interfaces are used for for arch, multilib and target properties.
405 return "", nil
406 default:
407 return "", fmt.Errorf(
408 "unexpected kind for property struct field: %s", propertyValue.Kind())
409 }
410 return ret, nil
411}
412
413// Converts a reflected property struct value into a map of property names and property values,
414// which each property value correctly pretty-printed and indented at the right nest level,
415// since property structs can be nested. In Starlark, nested structs are represented as nested
416// dicts: https://docs.bazel.build/skylark/lib/dict.html
417func extractStructProperties(structValue reflect.Value, indent int) map[string]string {
418 if structValue.Kind() != reflect.Struct {
419 panic(fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind()))
420 }
421
422 ret := map[string]string{}
423 structType := structValue.Type()
424 for i := 0; i < structValue.NumField(); i++ {
425 field := structType.Field(i)
426 if shouldSkipStructField(field) {
427 continue
428 }
429
430 fieldValue := structValue.Field(i)
431 if isZero(fieldValue) {
432 // Ignore zero-valued fields
433 continue
434 }
435
436 propertyName := proptools.PropertyNameForField(field.Name)
437 prettyPrintedValue, err := prettyPrint(fieldValue, indent+1)
438 if err != nil {
439 panic(
440 fmt.Errorf(
441 "Error while parsing property: %q. %s",
442 propertyName,
443 err))
444 }
445 if prettyPrintedValue != "" {
446 ret[propertyName] = prettyPrintedValue
447 }
448 }
449
450 return ret
451}
452
453func isZero(value reflect.Value) bool {
454 switch value.Kind() {
455 case reflect.Func, reflect.Map, reflect.Slice:
456 return value.IsNil()
457 case reflect.Array:
458 valueIsZero := true
459 for i := 0; i < value.Len(); i++ {
460 valueIsZero = valueIsZero && isZero(value.Index(i))
461 }
462 return valueIsZero
463 case reflect.Struct:
464 valueIsZero := true
465 for i := 0; i < value.NumField(); i++ {
466 if value.Field(i).CanSet() {
467 valueIsZero = valueIsZero && isZero(value.Field(i))
468 }
469 }
470 return valueIsZero
471 case reflect.Ptr:
472 if !value.IsNil() {
473 return isZero(reflect.Indirect(value))
474 } else {
475 return true
476 }
477 default:
478 zeroValue := reflect.Zero(value.Type())
479 result := value.Interface() == zeroValue.Interface()
480 return result
481 }
482}
483
484func escapeString(s string) string {
485 s = strings.ReplaceAll(s, "\\", "\\\\")
486 return strings.ReplaceAll(s, "\"", "\\\"")
487}
488
489func makeIndent(indent int) string {
490 if indent < 0 {
491 panic(fmt.Errorf("indent column cannot be less than 0, but got %d", indent))
492 }
493 return strings.Repeat(" ", indent)
494}
495
Jingwen Chen73850672020-12-14 08:25:34 -0500496func targetNameForBp2Build(c bpToBuildContext, logicModule blueprint.Module) string {
Jingwen Chenfb4692a2021-02-07 10:05:16 -0500497 return strings.Replace(c.ModuleName(logicModule), bazel.BazelTargetModuleNamePrefix, "", 1)
Jingwen Chen73850672020-12-14 08:25:34 -0500498}
499
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800500func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
501 name := ""
502 if c.ModuleSubDir(logicModule) != "" {
503 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
504 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
505 } else {
506 name = c.ModuleName(logicModule)
507 }
508
509 return strings.Replace(name, "//", "", 1)
510}
511
512func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
513 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
514}