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