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