blob: 7fa49968339b782cb4702a6e16a6f4f2a9c9fe15 [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"
22 "strings"
23
24 "github.com/google/blueprint"
25 "github.com/google/blueprint/proptools"
26)
27
28type BazelAttributes struct {
29 Attrs map[string]string
30}
31
32type BazelTarget struct {
Jingwen Chen40067de2021-01-26 21:58:43 -050033 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.
41func (t BazelTarget) IsLoadedFromStarlark() bool {
42 return t.bzlLoadLocation != ""
43}
44
45// BazelTargets is a typedef for a slice of BazelTarget objects.
46type 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.
51func (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.
64func (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 Kammer2dd9ca42020-11-25 16:06:39 -080089}
90
91type 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 Chendaa54bc2020-12-14 02:58:54 -050097 VisitAllModules(visit func(blueprint.Module))
98 VisitDirectDeps(module blueprint.Module, visit func(blueprint.Module))
99}
100
101type CodegenContext struct {
102 config android.Config
103 context android.Context
Jingwen Chen33832f92021-01-24 22:55:54 -0500104 mode CodegenMode
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500105}
106
Jingwen Chen164e0862021-02-19 00:48:40 -0500107func (c *CodegenContext) Mode() CodegenMode {
108 return c.mode
109}
110
Jingwen Chen33832f92021-01-24 22:55:54 -0500111// CodegenMode is an enum to differentiate code-generation modes.
112type CodegenMode int
113
114const (
115 // Bp2Build: generate BUILD files with targets buildable by Bazel directly.
116 //
117 // This mode is used for the Soong->Bazel build definition conversion.
118 Bp2Build CodegenMode = iota
119
120 // QueryView: generate BUILD files with targets representing fully mutated
121 // Soong modules, representing the fully configured Soong module graph with
122 // variants and dependency endges.
123 //
124 // This mode is used for discovering and introspecting the existing Soong
125 // module graph.
126 QueryView
127)
128
Jingwen Chendcc329a2021-01-26 02:49:03 -0500129func (mode CodegenMode) String() string {
130 switch mode {
131 case Bp2Build:
132 return "Bp2Build"
133 case QueryView:
134 return "QueryView"
135 default:
136 return fmt.Sprintf("%d", mode)
137 }
138}
139
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500140func (ctx CodegenContext) AddNinjaFileDeps(...string) {}
141func (ctx CodegenContext) Config() android.Config { return ctx.config }
142func (ctx CodegenContext) Context() android.Context { return ctx.context }
143
144// NewCodegenContext creates a wrapper context that conforms to PathContext for
145// writing BUILD files in the output directory.
Jingwen Chen33832f92021-01-24 22:55:54 -0500146func NewCodegenContext(config android.Config, context android.Context, mode CodegenMode) CodegenContext {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500147 return CodegenContext{
148 context: context,
149 config: config,
Jingwen Chen33832f92021-01-24 22:55:54 -0500150 mode: mode,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500151 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800152}
153
154// props is an unsorted map. This function ensures that
155// the generated attributes are sorted to ensure determinism.
156func propsToAttributes(props map[string]string) string {
157 var attributes string
158 for _, propName := range android.SortedStringKeys(props) {
159 if shouldGenerateAttribute(propName) {
160 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
161 }
162 }
163 return attributes
164}
165
Jingwen Chen164e0862021-02-19 00:48:40 -0500166func GenerateBazelTargets(ctx CodegenContext) (map[string]BazelTargets, CodegenMetrics) {
Jingwen Chen40067de2021-01-26 21:58:43 -0500167 buildFileToTargets := make(map[string]BazelTargets)
Jingwen Chen164e0862021-02-19 00:48:40 -0500168
169 // Simple metrics tracking for bp2build
170 totalModuleCount := 0
171 ruleClassCount := make(map[string]int)
172
173 bpCtx := ctx.Context()
174 bpCtx.VisitAllModules(func(m blueprint.Module) {
175 dir := bpCtx.ModuleDir(m)
Jingwen Chen73850672020-12-14 08:25:34 -0500176 var t BazelTarget
177
Jingwen Chen164e0862021-02-19 00:48:40 -0500178 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500179 case Bp2Build:
Liz Kammerfc46bc12021-02-19 11:06:17 -0500180 if b, ok := m.(android.BazelTargetModule); !ok {
Jingwen Chen164e0862021-02-19 00:48:40 -0500181 // Only include regular Soong modules (non-BazelTargetModules) into the total count.
182 totalModuleCount += 1
Jingwen Chen73850672020-12-14 08:25:34 -0500183 return
Liz Kammerfc46bc12021-02-19 11:06:17 -0500184 } else {
185 t = generateBazelTarget(bpCtx, m, b)
186 ruleClassCount[t.ruleClass] += 1
Jingwen Chen73850672020-12-14 08:25:34 -0500187 }
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
Liz Kammerfc46bc12021-02-19 11:06:17 -0500211func generateBazelTarget(ctx bpToBuildContext, m blueprint.Module, b android.BazelTargetModule) BazelTarget {
212 ruleClass := b.RuleClass()
213 bzlLoadLocation := b.BzlLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500214
Jingwen Chen73850672020-12-14 08:25:34 -0500215 // extract the bazel attributes from the module.
216 props := getBuildProperties(ctx, m)
217
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500218 delete(props.Attrs, "bp2build_available")
219
Jingwen Chen73850672020-12-14 08:25:34 -0500220 // Return the Bazel target with rule class and attributes, ready to be
221 // code-generated.
222 attributes := propsToAttributes(props.Attrs)
223 targetName := targetNameForBp2Build(ctx, m)
224 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500225 name: targetName,
226 ruleClass: ruleClass,
227 bzlLoadLocation: bzlLoadLocation,
Jingwen Chen73850672020-12-14 08:25:34 -0500228 content: fmt.Sprintf(
229 bazelTarget,
230 ruleClass,
231 targetName,
232 attributes,
233 ),
234 }
235}
236
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800237// Convert a module and its deps and props into a Bazel macro/rule
238// representation in the BUILD file.
239func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) BazelTarget {
240 props := getBuildProperties(ctx, m)
241
242 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
243 // items, if the modules are added using different DependencyTag. Figure
244 // out the implications of that.
245 depLabels := map[string]bool{}
246 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500247 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800248 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
249 })
250 }
251 attributes := propsToAttributes(props.Attrs)
252
253 depLabelList := "[\n"
254 for depLabel, _ := range depLabels {
255 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
256 }
257 depLabelList += " ]"
258
259 targetName := targetNameWithVariant(ctx, m)
260 return BazelTarget{
261 name: targetName,
262 content: fmt.Sprintf(
263 soongModuleTarget,
264 targetName,
265 ctx.ModuleName(m),
266 canonicalizeModuleType(ctx.ModuleType(m)),
267 ctx.ModuleSubDir(m),
268 depLabelList,
269 attributes),
270 }
271}
272
273func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) BazelAttributes {
274 var allProps map[string]string
275 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
276 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
277 if aModule, ok := m.(android.Module); ok {
278 allProps = ExtractModuleProperties(aModule)
279 }
280
281 return BazelAttributes{
282 Attrs: allProps,
283 }
284}
285
286// Generically extract module properties and types into a map, keyed by the module property name.
287func ExtractModuleProperties(aModule android.Module) map[string]string {
288 ret := map[string]string{}
289
290 // Iterate over this android.Module's property structs.
291 for _, properties := range aModule.GetProperties() {
292 propertiesValue := reflect.ValueOf(properties)
293 // Check that propertiesValue is a pointer to the Properties struct, like
294 // *cc.BaseLinkerProperties or *java.CompilerProperties.
295 //
296 // propertiesValue can also be type-asserted to the structs to
297 // manipulate internal props, if needed.
298 if isStructPtr(propertiesValue.Type()) {
299 structValue := propertiesValue.Elem()
300 for k, v := range extractStructProperties(structValue, 0) {
301 ret[k] = v
302 }
303 } else {
304 panic(fmt.Errorf(
305 "properties must be a pointer to a struct, got %T",
306 propertiesValue.Interface()))
307 }
308 }
309
310 return ret
311}
312
313func isStructPtr(t reflect.Type) bool {
314 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
315}
316
317// prettyPrint a property value into the equivalent Starlark representation
318// recursively.
319func prettyPrint(propertyValue reflect.Value, indent int) (string, error) {
320 if isZero(propertyValue) {
321 // A property value being set or unset actually matters -- Soong does set default
322 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
323 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
324 //
325 // In Bazel-parlance, we would use "attr.<type>(default = <default value>)" to set the default
326 // value of unset attributes.
327 return "", nil
328 }
329
330 var ret string
331 switch propertyValue.Kind() {
332 case reflect.String:
333 ret = fmt.Sprintf("\"%v\"", escapeString(propertyValue.String()))
334 case reflect.Bool:
335 ret = strings.Title(fmt.Sprintf("%v", propertyValue.Interface()))
336 case reflect.Int, reflect.Uint, reflect.Int64:
337 ret = fmt.Sprintf("%v", propertyValue.Interface())
338 case reflect.Ptr:
339 return prettyPrint(propertyValue.Elem(), indent)
340 case reflect.Slice:
341 ret = "[\n"
342 for i := 0; i < propertyValue.Len(); i++ {
343 indexedValue, err := prettyPrint(propertyValue.Index(i), indent+1)
344 if err != nil {
345 return "", err
346 }
347
348 if indexedValue != "" {
349 ret += makeIndent(indent + 1)
350 ret += indexedValue
351 ret += ",\n"
352 }
353 }
354 ret += makeIndent(indent)
355 ret += "]"
356 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -0500357 // Special cases where the bp2build sends additional information to the codegenerator
358 // by wrapping the attributes in a custom struct type.
Liz Kammer356f7d42021-01-26 09:18:53 -0500359 if labels, ok := propertyValue.Interface().(bazel.LabelList); ok {
360 // TODO(b/165114590): convert glob syntax
361 return prettyPrint(reflect.ValueOf(labels.Includes), indent)
362 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
363 return fmt.Sprintf("%q", label.Label), nil
Jingwen Chen5d864492021-02-24 07:20:12 -0500364 } else if stringList, ok := propertyValue.Interface().(bazel.StringListAttribute); ok {
365 // A Bazel string_list attribute that may contain a select statement.
366 ret, err := prettyPrint(reflect.ValueOf(stringList.Value), indent)
367 if err != nil {
368 return ret, err
369 }
370
371 if !stringList.HasArchSpecificValues() {
372 // Select statement not needed.
373 return ret, nil
374 }
375
376 ret += " + " + "select({\n"
377 for _, arch := range android.ArchTypeList() {
378 value := stringList.GetValueForArch(arch.Name)
379 if len(value) > 0 {
380 ret += makeIndent(indent + 1)
381 list, _ := prettyPrint(reflect.ValueOf(value), indent+1)
382 ret += fmt.Sprintf("\"%s\": %s,\n", platformArchMap[arch], list)
383 }
384 }
385
386 ret += makeIndent(indent + 1)
387 list, _ := prettyPrint(reflect.ValueOf(stringList.GetValueForArch("default")), indent+1)
388 ret += fmt.Sprintf("\"%s\": %s,\n", "//conditions:default", list)
389
390 ret += makeIndent(indent)
391 ret += "})"
392 return ret, err
Liz Kammer356f7d42021-01-26 09:18:53 -0500393 }
394
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800395 ret = "{\n"
396 // Sort and print the struct props by the key.
397 structProps := extractStructProperties(propertyValue, indent)
398 for _, k := range android.SortedStringKeys(structProps) {
399 ret += makeIndent(indent + 1)
400 ret += fmt.Sprintf("%q: %s,\n", k, structProps[k])
401 }
402 ret += makeIndent(indent)
403 ret += "}"
404 case reflect.Interface:
405 // TODO(b/164227191): implement pretty print for interfaces.
406 // Interfaces are used for for arch, multilib and target properties.
407 return "", nil
408 default:
409 return "", fmt.Errorf(
410 "unexpected kind for property struct field: %s", propertyValue.Kind())
411 }
412 return ret, nil
413}
414
415// Converts a reflected property struct value into a map of property names and property values,
416// which each property value correctly pretty-printed and indented at the right nest level,
417// since property structs can be nested. In Starlark, nested structs are represented as nested
418// dicts: https://docs.bazel.build/skylark/lib/dict.html
419func extractStructProperties(structValue reflect.Value, indent int) map[string]string {
420 if structValue.Kind() != reflect.Struct {
421 panic(fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind()))
422 }
423
424 ret := map[string]string{}
425 structType := structValue.Type()
426 for i := 0; i < structValue.NumField(); i++ {
427 field := structType.Field(i)
428 if shouldSkipStructField(field) {
429 continue
430 }
431
432 fieldValue := structValue.Field(i)
433 if isZero(fieldValue) {
434 // Ignore zero-valued fields
435 continue
436 }
437
438 propertyName := proptools.PropertyNameForField(field.Name)
439 prettyPrintedValue, err := prettyPrint(fieldValue, indent+1)
440 if err != nil {
441 panic(
442 fmt.Errorf(
443 "Error while parsing property: %q. %s",
444 propertyName,
445 err))
446 }
447 if prettyPrintedValue != "" {
448 ret[propertyName] = prettyPrintedValue
449 }
450 }
451
452 return ret
453}
454
455func isZero(value reflect.Value) bool {
456 switch value.Kind() {
457 case reflect.Func, reflect.Map, reflect.Slice:
458 return value.IsNil()
459 case reflect.Array:
460 valueIsZero := true
461 for i := 0; i < value.Len(); i++ {
462 valueIsZero = valueIsZero && isZero(value.Index(i))
463 }
464 return valueIsZero
465 case reflect.Struct:
466 valueIsZero := true
467 for i := 0; i < value.NumField(); i++ {
468 if value.Field(i).CanSet() {
469 valueIsZero = valueIsZero && isZero(value.Field(i))
470 }
471 }
472 return valueIsZero
473 case reflect.Ptr:
474 if !value.IsNil() {
475 return isZero(reflect.Indirect(value))
476 } else {
477 return true
478 }
479 default:
480 zeroValue := reflect.Zero(value.Type())
481 result := value.Interface() == zeroValue.Interface()
482 return result
483 }
484}
485
486func escapeString(s string) string {
487 s = strings.ReplaceAll(s, "\\", "\\\\")
488 return strings.ReplaceAll(s, "\"", "\\\"")
489}
490
491func makeIndent(indent int) string {
492 if indent < 0 {
493 panic(fmt.Errorf("indent column cannot be less than 0, but got %d", indent))
494 }
495 return strings.Repeat(" ", indent)
496}
497
Jingwen Chen73850672020-12-14 08:25:34 -0500498func targetNameForBp2Build(c bpToBuildContext, logicModule blueprint.Module) string {
Jingwen Chenfb4692a2021-02-07 10:05:16 -0500499 return strings.Replace(c.ModuleName(logicModule), bazel.BazelTargetModuleNamePrefix, "", 1)
Jingwen Chen73850672020-12-14 08:25:34 -0500500}
501
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800502func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
503 name := ""
504 if c.ModuleSubDir(logicModule) != "" {
505 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
506 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
507 } else {
508 name = c.ModuleName(logicModule)
509 }
510
511 return strings.Replace(name, "//", "", 1)
512}
513
514func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
515 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
516}