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