blob: 59af22dfc27c6464dcef6804dbebc4f4c4065435 [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 Chen33832f92021-01-24 22:55:54 -0500108// CodegenMode is an enum to differentiate code-generation modes.
109type CodegenMode int
110
111const (
112 // Bp2Build: generate BUILD files with targets buildable by Bazel directly.
113 //
114 // This mode is used for the Soong->Bazel build definition conversion.
115 Bp2Build CodegenMode = iota
116
117 // QueryView: generate BUILD files with targets representing fully mutated
118 // Soong modules, representing the fully configured Soong module graph with
119 // variants and dependency endges.
120 //
121 // This mode is used for discovering and introspecting the existing Soong
122 // module graph.
123 QueryView
124)
125
Jingwen Chendcc329a2021-01-26 02:49:03 -0500126func (mode CodegenMode) String() string {
127 switch mode {
128 case Bp2Build:
129 return "Bp2Build"
130 case QueryView:
131 return "QueryView"
132 default:
133 return fmt.Sprintf("%d", mode)
134 }
135}
136
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500137func (ctx CodegenContext) AddNinjaFileDeps(...string) {}
138func (ctx CodegenContext) Config() android.Config { return ctx.config }
139func (ctx CodegenContext) Context() android.Context { return ctx.context }
140
141// NewCodegenContext creates a wrapper context that conforms to PathContext for
142// writing BUILD files in the output directory.
Jingwen Chen33832f92021-01-24 22:55:54 -0500143func NewCodegenContext(config android.Config, context android.Context, mode CodegenMode) CodegenContext {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500144 return CodegenContext{
145 context: context,
146 config: config,
Jingwen Chen33832f92021-01-24 22:55:54 -0500147 mode: mode,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500148 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800149}
150
151// props is an unsorted map. This function ensures that
152// the generated attributes are sorted to ensure determinism.
153func propsToAttributes(props map[string]string) string {
154 var attributes string
155 for _, propName := range android.SortedStringKeys(props) {
156 if shouldGenerateAttribute(propName) {
157 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
158 }
159 }
160 return attributes
161}
162
Jingwen Chen4d2c0872021-02-02 07:06:56 -0500163func GenerateBazelTargets(ctx bpToBuildContext, codegenMode CodegenMode) map[string]BazelTargets {
Jingwen Chen40067de2021-01-26 21:58:43 -0500164 buildFileToTargets := make(map[string]BazelTargets)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500165 ctx.VisitAllModules(func(m blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800166 dir := ctx.ModuleDir(m)
Jingwen Chen73850672020-12-14 08:25:34 -0500167 var t BazelTarget
168
Jingwen Chen33832f92021-01-24 22:55:54 -0500169 switch codegenMode {
170 case Bp2Build:
Jingwen Chen73850672020-12-14 08:25:34 -0500171 if _, ok := m.(android.BazelTargetModule); !ok {
172 return
173 }
174 t = generateBazelTarget(ctx, m)
Jingwen Chen33832f92021-01-24 22:55:54 -0500175 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500176 // Blocklist certain module types from being generated.
177 if canonicalizeModuleType(ctx.ModuleType(m)) == "package" {
178 // package module name contain slashes, and thus cannot
179 // be mapped cleanly to a bazel label.
180 return
181 }
Jingwen Chen73850672020-12-14 08:25:34 -0500182 t = generateSoongModuleTarget(ctx, m)
Jingwen Chen33832f92021-01-24 22:55:54 -0500183 default:
184 panic(fmt.Errorf("Unknown code-generation mode: %s", codegenMode))
Jingwen Chen73850672020-12-14 08:25:34 -0500185 }
186
Liz Kammer356f7d42021-01-26 09:18:53 -0500187 buildFileToTargets[dir] = append(buildFileToTargets[dir], t)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800188 })
189 return buildFileToTargets
190}
191
Jingwen Chen40067de2021-01-26 21:58:43 -0500192// Helper method to trim quotes around strings.
193func trimQuotes(s string) string {
194 if s == "" {
195 // strconv.Unquote would error out on empty strings, but this method
196 // allows them, so return the empty string directly.
197 return ""
198 }
199 ret, err := strconv.Unquote(s)
200 if err != nil {
201 // Panic the error immediately.
202 panic(fmt.Errorf("Trying to unquote '%s', but got error: %s", s, err))
203 }
204 return ret
205}
206
Jingwen Chen73850672020-12-14 08:25:34 -0500207func generateBazelTarget(ctx bpToBuildContext, m blueprint.Module) BazelTarget {
208 // extract the bazel attributes from the module.
209 props := getBuildProperties(ctx, m)
210
211 // extract the rule class name from the attributes. Since the string value
212 // will be string-quoted, remove the quotes here.
Jingwen Chen40067de2021-01-26 21:58:43 -0500213 ruleClass := trimQuotes(props.Attrs["rule_class"])
Jingwen Chen73850672020-12-14 08:25:34 -0500214 // Delete it from being generated in the BUILD file.
215 delete(props.Attrs, "rule_class")
216
Jingwen Chen40067de2021-01-26 21:58:43 -0500217 // extract the bzl_load_location, and also remove the quotes around it here.
218 bzlLoadLocation := trimQuotes(props.Attrs["bzl_load_location"])
219 // Delete it from being generated in the BUILD file.
220 delete(props.Attrs, "bzl_load_location")
221
Jingwen Chen73850672020-12-14 08:25:34 -0500222 // Return the Bazel target with rule class and attributes, ready to be
223 // code-generated.
224 attributes := propsToAttributes(props.Attrs)
225 targetName := targetNameForBp2Build(ctx, m)
226 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500227 name: targetName,
228 ruleClass: ruleClass,
229 bzlLoadLocation: bzlLoadLocation,
Jingwen Chen73850672020-12-14 08:25:34 -0500230 content: fmt.Sprintf(
231 bazelTarget,
232 ruleClass,
233 targetName,
234 attributes,
235 ),
236 }
237}
238
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800239// Convert a module and its deps and props into a Bazel macro/rule
240// representation in the BUILD file.
241func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) BazelTarget {
242 props := getBuildProperties(ctx, m)
243
244 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
245 // items, if the modules are added using different DependencyTag. Figure
246 // out the implications of that.
247 depLabels := map[string]bool{}
248 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500249 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800250 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
251 })
252 }
253 attributes := propsToAttributes(props.Attrs)
254
255 depLabelList := "[\n"
256 for depLabel, _ := range depLabels {
257 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
258 }
259 depLabelList += " ]"
260
261 targetName := targetNameWithVariant(ctx, m)
262 return BazelTarget{
263 name: targetName,
264 content: fmt.Sprintf(
265 soongModuleTarget,
266 targetName,
267 ctx.ModuleName(m),
268 canonicalizeModuleType(ctx.ModuleType(m)),
269 ctx.ModuleSubDir(m),
270 depLabelList,
271 attributes),
272 }
273}
274
275func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) BazelAttributes {
276 var allProps map[string]string
277 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
278 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
279 if aModule, ok := m.(android.Module); ok {
280 allProps = ExtractModuleProperties(aModule)
281 }
282
283 return BazelAttributes{
284 Attrs: allProps,
285 }
286}
287
288// Generically extract module properties and types into a map, keyed by the module property name.
289func ExtractModuleProperties(aModule android.Module) map[string]string {
290 ret := map[string]string{}
291
292 // Iterate over this android.Module's property structs.
293 for _, properties := range aModule.GetProperties() {
294 propertiesValue := reflect.ValueOf(properties)
295 // Check that propertiesValue is a pointer to the Properties struct, like
296 // *cc.BaseLinkerProperties or *java.CompilerProperties.
297 //
298 // propertiesValue can also be type-asserted to the structs to
299 // manipulate internal props, if needed.
300 if isStructPtr(propertiesValue.Type()) {
301 structValue := propertiesValue.Elem()
302 for k, v := range extractStructProperties(structValue, 0) {
303 ret[k] = v
304 }
305 } else {
306 panic(fmt.Errorf(
307 "properties must be a pointer to a struct, got %T",
308 propertiesValue.Interface()))
309 }
310 }
311
312 return ret
313}
314
315func isStructPtr(t reflect.Type) bool {
316 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
317}
318
319// prettyPrint a property value into the equivalent Starlark representation
320// recursively.
321func prettyPrint(propertyValue reflect.Value, indent int) (string, error) {
322 if isZero(propertyValue) {
323 // A property value being set or unset actually matters -- Soong does set default
324 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
325 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
326 //
327 // In Bazel-parlance, we would use "attr.<type>(default = <default value>)" to set the default
328 // value of unset attributes.
329 return "", nil
330 }
331
332 var ret string
333 switch propertyValue.Kind() {
334 case reflect.String:
335 ret = fmt.Sprintf("\"%v\"", escapeString(propertyValue.String()))
336 case reflect.Bool:
337 ret = strings.Title(fmt.Sprintf("%v", propertyValue.Interface()))
338 case reflect.Int, reflect.Uint, reflect.Int64:
339 ret = fmt.Sprintf("%v", propertyValue.Interface())
340 case reflect.Ptr:
341 return prettyPrint(propertyValue.Elem(), indent)
342 case reflect.Slice:
343 ret = "[\n"
344 for i := 0; i < propertyValue.Len(); i++ {
345 indexedValue, err := prettyPrint(propertyValue.Index(i), indent+1)
346 if err != nil {
347 return "", err
348 }
349
350 if indexedValue != "" {
351 ret += makeIndent(indent + 1)
352 ret += indexedValue
353 ret += ",\n"
354 }
355 }
356 ret += makeIndent(indent)
357 ret += "]"
358 case reflect.Struct:
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
364 }
365
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800366 ret = "{\n"
367 // Sort and print the struct props by the key.
368 structProps := extractStructProperties(propertyValue, indent)
369 for _, k := range android.SortedStringKeys(structProps) {
370 ret += makeIndent(indent + 1)
371 ret += fmt.Sprintf("%q: %s,\n", k, structProps[k])
372 }
373 ret += makeIndent(indent)
374 ret += "}"
375 case reflect.Interface:
376 // TODO(b/164227191): implement pretty print for interfaces.
377 // Interfaces are used for for arch, multilib and target properties.
378 return "", nil
379 default:
380 return "", fmt.Errorf(
381 "unexpected kind for property struct field: %s", propertyValue.Kind())
382 }
383 return ret, nil
384}
385
386// Converts a reflected property struct value into a map of property names and property values,
387// which each property value correctly pretty-printed and indented at the right nest level,
388// since property structs can be nested. In Starlark, nested structs are represented as nested
389// dicts: https://docs.bazel.build/skylark/lib/dict.html
390func extractStructProperties(structValue reflect.Value, indent int) map[string]string {
391 if structValue.Kind() != reflect.Struct {
392 panic(fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind()))
393 }
394
395 ret := map[string]string{}
396 structType := structValue.Type()
397 for i := 0; i < structValue.NumField(); i++ {
398 field := structType.Field(i)
399 if shouldSkipStructField(field) {
400 continue
401 }
402
403 fieldValue := structValue.Field(i)
404 if isZero(fieldValue) {
405 // Ignore zero-valued fields
406 continue
407 }
408
409 propertyName := proptools.PropertyNameForField(field.Name)
410 prettyPrintedValue, err := prettyPrint(fieldValue, indent+1)
411 if err != nil {
412 panic(
413 fmt.Errorf(
414 "Error while parsing property: %q. %s",
415 propertyName,
416 err))
417 }
418 if prettyPrintedValue != "" {
419 ret[propertyName] = prettyPrintedValue
420 }
421 }
422
423 return ret
424}
425
426func isZero(value reflect.Value) bool {
427 switch value.Kind() {
428 case reflect.Func, reflect.Map, reflect.Slice:
429 return value.IsNil()
430 case reflect.Array:
431 valueIsZero := true
432 for i := 0; i < value.Len(); i++ {
433 valueIsZero = valueIsZero && isZero(value.Index(i))
434 }
435 return valueIsZero
436 case reflect.Struct:
437 valueIsZero := true
438 for i := 0; i < value.NumField(); i++ {
439 if value.Field(i).CanSet() {
440 valueIsZero = valueIsZero && isZero(value.Field(i))
441 }
442 }
443 return valueIsZero
444 case reflect.Ptr:
445 if !value.IsNil() {
446 return isZero(reflect.Indirect(value))
447 } else {
448 return true
449 }
450 default:
451 zeroValue := reflect.Zero(value.Type())
452 result := value.Interface() == zeroValue.Interface()
453 return result
454 }
455}
456
457func escapeString(s string) string {
458 s = strings.ReplaceAll(s, "\\", "\\\\")
459 return strings.ReplaceAll(s, "\"", "\\\"")
460}
461
462func makeIndent(indent int) string {
463 if indent < 0 {
464 panic(fmt.Errorf("indent column cannot be less than 0, but got %d", indent))
465 }
466 return strings.Repeat(" ", indent)
467}
468
Jingwen Chen73850672020-12-14 08:25:34 -0500469func targetNameForBp2Build(c bpToBuildContext, logicModule blueprint.Module) string {
470 return strings.Replace(c.ModuleName(logicModule), "__bp2build__", "", 1)
471}
472
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800473func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
474 name := ""
475 if c.ModuleSubDir(logicModule) != "" {
476 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
477 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
478 } else {
479 name = c.ModuleName(logicModule)
480 }
481
482 return strings.Replace(name, "//", "", 1)
483}
484
485func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
486 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
487}