blob: 41ad409cc1ca959b07b1e75ec7bbc6f974228096 [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
Jingwen Chen40067de2021-01-26 21:58:43 -0500211// Helper method to trim quotes around strings.
212func trimQuotes(s string) string {
213 if s == "" {
214 // strconv.Unquote would error out on empty strings, but this method
215 // allows them, so return the empty string directly.
216 return ""
217 }
218 ret, err := strconv.Unquote(s)
219 if err != nil {
220 // Panic the error immediately.
221 panic(fmt.Errorf("Trying to unquote '%s', but got error: %s", s, err))
222 }
223 return ret
224}
225
Jingwen Chen73850672020-12-14 08:25:34 -0500226func generateBazelTarget(ctx bpToBuildContext, m blueprint.Module) BazelTarget {
227 // extract the bazel attributes from the module.
228 props := getBuildProperties(ctx, m)
229
230 // extract the rule class name from the attributes. Since the string value
231 // will be string-quoted, remove the quotes here.
Jingwen Chen40067de2021-01-26 21:58:43 -0500232 ruleClass := trimQuotes(props.Attrs["rule_class"])
Jingwen Chen73850672020-12-14 08:25:34 -0500233 // Delete it from being generated in the BUILD file.
234 delete(props.Attrs, "rule_class")
235
Jingwen Chen40067de2021-01-26 21:58:43 -0500236 // extract the bzl_load_location, and also remove the quotes around it here.
237 bzlLoadLocation := trimQuotes(props.Attrs["bzl_load_location"])
238 // Delete it from being generated in the BUILD file.
239 delete(props.Attrs, "bzl_load_location")
240
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500241 delete(props.Attrs, "bp2build_available")
242
Jingwen Chen73850672020-12-14 08:25:34 -0500243 // Return the Bazel target with rule class and attributes, ready to be
244 // code-generated.
245 attributes := propsToAttributes(props.Attrs)
246 targetName := targetNameForBp2Build(ctx, m)
247 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500248 name: targetName,
249 ruleClass: ruleClass,
250 bzlLoadLocation: bzlLoadLocation,
Jingwen Chen73850672020-12-14 08:25:34 -0500251 content: fmt.Sprintf(
252 bazelTarget,
253 ruleClass,
254 targetName,
255 attributes,
256 ),
257 }
258}
259
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800260// Convert a module and its deps and props into a Bazel macro/rule
261// representation in the BUILD file.
262func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) BazelTarget {
263 props := getBuildProperties(ctx, m)
264
265 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
266 // items, if the modules are added using different DependencyTag. Figure
267 // out the implications of that.
268 depLabels := map[string]bool{}
269 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500270 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800271 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
272 })
273 }
274 attributes := propsToAttributes(props.Attrs)
275
276 depLabelList := "[\n"
277 for depLabel, _ := range depLabels {
278 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
279 }
280 depLabelList += " ]"
281
282 targetName := targetNameWithVariant(ctx, m)
283 return BazelTarget{
284 name: targetName,
285 content: fmt.Sprintf(
286 soongModuleTarget,
287 targetName,
288 ctx.ModuleName(m),
289 canonicalizeModuleType(ctx.ModuleType(m)),
290 ctx.ModuleSubDir(m),
291 depLabelList,
292 attributes),
293 }
294}
295
296func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) BazelAttributes {
297 var allProps map[string]string
298 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
299 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
300 if aModule, ok := m.(android.Module); ok {
301 allProps = ExtractModuleProperties(aModule)
302 }
303
304 return BazelAttributes{
305 Attrs: allProps,
306 }
307}
308
309// Generically extract module properties and types into a map, keyed by the module property name.
310func ExtractModuleProperties(aModule android.Module) map[string]string {
311 ret := map[string]string{}
312
313 // Iterate over this android.Module's property structs.
314 for _, properties := range aModule.GetProperties() {
315 propertiesValue := reflect.ValueOf(properties)
316 // Check that propertiesValue is a pointer to the Properties struct, like
317 // *cc.BaseLinkerProperties or *java.CompilerProperties.
318 //
319 // propertiesValue can also be type-asserted to the structs to
320 // manipulate internal props, if needed.
321 if isStructPtr(propertiesValue.Type()) {
322 structValue := propertiesValue.Elem()
323 for k, v := range extractStructProperties(structValue, 0) {
324 ret[k] = v
325 }
326 } else {
327 panic(fmt.Errorf(
328 "properties must be a pointer to a struct, got %T",
329 propertiesValue.Interface()))
330 }
331 }
332
333 return ret
334}
335
336func isStructPtr(t reflect.Type) bool {
337 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
338}
339
340// prettyPrint a property value into the equivalent Starlark representation
341// recursively.
342func prettyPrint(propertyValue reflect.Value, indent int) (string, error) {
343 if isZero(propertyValue) {
344 // A property value being set or unset actually matters -- Soong does set default
345 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
346 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
347 //
348 // In Bazel-parlance, we would use "attr.<type>(default = <default value>)" to set the default
349 // value of unset attributes.
350 return "", nil
351 }
352
353 var ret string
354 switch propertyValue.Kind() {
355 case reflect.String:
356 ret = fmt.Sprintf("\"%v\"", escapeString(propertyValue.String()))
357 case reflect.Bool:
358 ret = strings.Title(fmt.Sprintf("%v", propertyValue.Interface()))
359 case reflect.Int, reflect.Uint, reflect.Int64:
360 ret = fmt.Sprintf("%v", propertyValue.Interface())
361 case reflect.Ptr:
362 return prettyPrint(propertyValue.Elem(), indent)
363 case reflect.Slice:
364 ret = "[\n"
365 for i := 0; i < propertyValue.Len(); i++ {
366 indexedValue, err := prettyPrint(propertyValue.Index(i), indent+1)
367 if err != nil {
368 return "", err
369 }
370
371 if indexedValue != "" {
372 ret += makeIndent(indent + 1)
373 ret += indexedValue
374 ret += ",\n"
375 }
376 }
377 ret += makeIndent(indent)
378 ret += "]"
379 case reflect.Struct:
Liz Kammer356f7d42021-01-26 09:18:53 -0500380 if labels, ok := propertyValue.Interface().(bazel.LabelList); ok {
381 // TODO(b/165114590): convert glob syntax
382 return prettyPrint(reflect.ValueOf(labels.Includes), indent)
383 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
384 return fmt.Sprintf("%q", label.Label), nil
385 }
386
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800387 ret = "{\n"
388 // Sort and print the struct props by the key.
389 structProps := extractStructProperties(propertyValue, indent)
390 for _, k := range android.SortedStringKeys(structProps) {
391 ret += makeIndent(indent + 1)
392 ret += fmt.Sprintf("%q: %s,\n", k, structProps[k])
393 }
394 ret += makeIndent(indent)
395 ret += "}"
396 case reflect.Interface:
397 // TODO(b/164227191): implement pretty print for interfaces.
398 // Interfaces are used for for arch, multilib and target properties.
399 return "", nil
400 default:
401 return "", fmt.Errorf(
402 "unexpected kind for property struct field: %s", propertyValue.Kind())
403 }
404 return ret, nil
405}
406
407// Converts a reflected property struct value into a map of property names and property values,
408// which each property value correctly pretty-printed and indented at the right nest level,
409// since property structs can be nested. In Starlark, nested structs are represented as nested
410// dicts: https://docs.bazel.build/skylark/lib/dict.html
411func extractStructProperties(structValue reflect.Value, indent int) map[string]string {
412 if structValue.Kind() != reflect.Struct {
413 panic(fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind()))
414 }
415
416 ret := map[string]string{}
417 structType := structValue.Type()
418 for i := 0; i < structValue.NumField(); i++ {
419 field := structType.Field(i)
420 if shouldSkipStructField(field) {
421 continue
422 }
423
424 fieldValue := structValue.Field(i)
425 if isZero(fieldValue) {
426 // Ignore zero-valued fields
427 continue
428 }
429
430 propertyName := proptools.PropertyNameForField(field.Name)
431 prettyPrintedValue, err := prettyPrint(fieldValue, indent+1)
432 if err != nil {
433 panic(
434 fmt.Errorf(
435 "Error while parsing property: %q. %s",
436 propertyName,
437 err))
438 }
439 if prettyPrintedValue != "" {
440 ret[propertyName] = prettyPrintedValue
441 }
442 }
443
444 return ret
445}
446
447func isZero(value reflect.Value) bool {
448 switch value.Kind() {
449 case reflect.Func, reflect.Map, reflect.Slice:
450 return value.IsNil()
451 case reflect.Array:
452 valueIsZero := true
453 for i := 0; i < value.Len(); i++ {
454 valueIsZero = valueIsZero && isZero(value.Index(i))
455 }
456 return valueIsZero
457 case reflect.Struct:
458 valueIsZero := true
459 for i := 0; i < value.NumField(); i++ {
460 if value.Field(i).CanSet() {
461 valueIsZero = valueIsZero && isZero(value.Field(i))
462 }
463 }
464 return valueIsZero
465 case reflect.Ptr:
466 if !value.IsNil() {
467 return isZero(reflect.Indirect(value))
468 } else {
469 return true
470 }
471 default:
472 zeroValue := reflect.Zero(value.Type())
473 result := value.Interface() == zeroValue.Interface()
474 return result
475 }
476}
477
478func escapeString(s string) string {
479 s = strings.ReplaceAll(s, "\\", "\\\\")
480 return strings.ReplaceAll(s, "\"", "\\\"")
481}
482
483func makeIndent(indent int) string {
484 if indent < 0 {
485 panic(fmt.Errorf("indent column cannot be less than 0, but got %d", indent))
486 }
487 return strings.Repeat(" ", indent)
488}
489
Jingwen Chen73850672020-12-14 08:25:34 -0500490func targetNameForBp2Build(c bpToBuildContext, logicModule blueprint.Module) string {
Jingwen Chenfb4692a2021-02-07 10:05:16 -0500491 return strings.Replace(c.ModuleName(logicModule), bazel.BazelTargetModuleNamePrefix, "", 1)
Jingwen Chen73850672020-12-14 08:25:34 -0500492}
493
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800494func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
495 name := ""
496 if c.ModuleSubDir(logicModule) != "" {
497 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
498 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
499 } else {
500 name = c.ModuleName(logicModule)
501 }
502
503 return strings.Replace(name, "//", "", 1)
504}
505
506func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
507 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
508}