blob: e93b3dca18fbed5d0b630e9d275d959a2bc7beb9 [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 {
Liz Kammerba3ea162021-02-17 13:22:03 -0500102 config android.Config
103 context android.Context
104 mode CodegenMode
105 additionalDeps []string
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500106}
107
Jingwen Chen164e0862021-02-19 00:48:40 -0500108func (c *CodegenContext) Mode() CodegenMode {
109 return c.mode
110}
111
Jingwen Chen33832f92021-01-24 22:55:54 -0500112// CodegenMode is an enum to differentiate code-generation modes.
113type CodegenMode int
114
115const (
116 // Bp2Build: generate BUILD files with targets buildable by Bazel directly.
117 //
118 // This mode is used for the Soong->Bazel build definition conversion.
119 Bp2Build CodegenMode = iota
120
121 // QueryView: generate BUILD files with targets representing fully mutated
122 // Soong modules, representing the fully configured Soong module graph with
123 // variants and dependency endges.
124 //
125 // This mode is used for discovering and introspecting the existing Soong
126 // module graph.
127 QueryView
128)
129
Jingwen Chendcc329a2021-01-26 02:49:03 -0500130func (mode CodegenMode) String() string {
131 switch mode {
132 case Bp2Build:
133 return "Bp2Build"
134 case QueryView:
135 return "QueryView"
136 default:
137 return fmt.Sprintf("%d", mode)
138 }
139}
140
Liz Kammerba3ea162021-02-17 13:22:03 -0500141// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
142// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
143// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
144// call AdditionalNinjaDeps and add them manually to the ninja file.
145func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
146 ctx.additionalDeps = append(ctx.additionalDeps, deps...)
147}
148
149// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
150func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
151 return ctx.additionalDeps
152}
153
154func (ctx *CodegenContext) Config() android.Config { return ctx.config }
155func (ctx *CodegenContext) Context() android.Context { return ctx.context }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500156
157// NewCodegenContext creates a wrapper context that conforms to PathContext for
158// writing BUILD files in the output directory.
Liz Kammerba3ea162021-02-17 13:22:03 -0500159func NewCodegenContext(config android.Config, context android.Context, mode CodegenMode) *CodegenContext {
160 return &CodegenContext{
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500161 context: context,
162 config: config,
Jingwen Chen33832f92021-01-24 22:55:54 -0500163 mode: mode,
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500164 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800165}
166
167// props is an unsorted map. This function ensures that
168// the generated attributes are sorted to ensure determinism.
169func propsToAttributes(props map[string]string) string {
170 var attributes string
171 for _, propName := range android.SortedStringKeys(props) {
172 if shouldGenerateAttribute(propName) {
173 attributes += fmt.Sprintf(" %s = %s,\n", propName, props[propName])
174 }
175 }
176 return attributes
177}
178
Liz Kammerba3ea162021-02-17 13:22:03 -0500179func GenerateBazelTargets(ctx *CodegenContext) (map[string]BazelTargets, CodegenMetrics) {
Jingwen Chen40067de2021-01-26 21:58:43 -0500180 buildFileToTargets := make(map[string]BazelTargets)
Liz Kammerba3ea162021-02-17 13:22:03 -0500181 buildFileToAppend := make(map[string]bool)
Jingwen Chen164e0862021-02-19 00:48:40 -0500182
183 // Simple metrics tracking for bp2build
Liz Kammerba3ea162021-02-17 13:22:03 -0500184 metrics := CodegenMetrics{
185 RuleClassCount: make(map[string]int),
186 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500187
188 bpCtx := ctx.Context()
189 bpCtx.VisitAllModules(func(m blueprint.Module) {
190 dir := bpCtx.ModuleDir(m)
Jingwen Chen73850672020-12-14 08:25:34 -0500191 var t BazelTarget
192
Jingwen Chen164e0862021-02-19 00:48:40 -0500193 switch ctx.Mode() {
Jingwen Chen33832f92021-01-24 22:55:54 -0500194 case Bp2Build:
Liz Kammerba3ea162021-02-17 13:22:03 -0500195 if b, ok := m.(android.Bazelable); ok && b.HasHandcraftedLabel() {
196 metrics.handCraftedTargetCount += 1
197 metrics.TotalModuleCount += 1
198 pathToBuildFile := getBazelPackagePath(b)
199 // We are using the entire contents of handcrafted build file, so if multiple targets within
200 // a package have handcrafted targets, we only want to include the contents one time.
201 if _, exists := buildFileToAppend[pathToBuildFile]; exists {
202 return
203 }
204 var err error
205 t, err = getHandcraftedBuildContent(ctx, b, pathToBuildFile)
206 if err != nil {
207 panic(fmt.Errorf("Error converting %s: %s", bpCtx.ModuleName(m), err))
208 }
209 // TODO(b/181575318): currently we append the whole BUILD file, let's change that to do
210 // something more targeted based on the rule type and target
211 buildFileToAppend[pathToBuildFile] = true
212 } else if btm, ok := m.(android.BazelTargetModule); ok {
213 t = generateBazelTarget(bpCtx, m, btm)
214 metrics.RuleClassCount[t.ruleClass] += 1
Liz Kammerfc46bc12021-02-19 11:06:17 -0500215 } else {
Liz Kammerba3ea162021-02-17 13:22:03 -0500216 metrics.TotalModuleCount += 1
217 return
Jingwen Chen73850672020-12-14 08:25:34 -0500218 }
Jingwen Chen33832f92021-01-24 22:55:54 -0500219 case QueryView:
Jingwen Chen96af35b2021-02-08 00:49:32 -0500220 // Blocklist certain module types from being generated.
Jingwen Chen164e0862021-02-19 00:48:40 -0500221 if canonicalizeModuleType(bpCtx.ModuleType(m)) == "package" {
Jingwen Chen96af35b2021-02-08 00:49:32 -0500222 // package module name contain slashes, and thus cannot
223 // be mapped cleanly to a bazel label.
224 return
225 }
Jingwen Chen164e0862021-02-19 00:48:40 -0500226 t = generateSoongModuleTarget(bpCtx, m)
Jingwen Chen33832f92021-01-24 22:55:54 -0500227 default:
Jingwen Chen164e0862021-02-19 00:48:40 -0500228 panic(fmt.Errorf("Unknown code-generation mode: %s", ctx.Mode()))
Jingwen Chen73850672020-12-14 08:25:34 -0500229 }
230
Liz Kammer356f7d42021-01-26 09:18:53 -0500231 buildFileToTargets[dir] = append(buildFileToTargets[dir], t)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800232 })
Jingwen Chen164e0862021-02-19 00:48:40 -0500233
Jingwen Chen164e0862021-02-19 00:48:40 -0500234 return buildFileToTargets, metrics
235}
236
Liz Kammerba3ea162021-02-17 13:22:03 -0500237func getBazelPackagePath(b android.Bazelable) string {
Liz Kammerbdc60992021-02-24 16:55:11 -0500238 label := b.HandcraftedLabel()
Liz Kammerba3ea162021-02-17 13:22:03 -0500239 pathToBuildFile := strings.TrimPrefix(label, "//")
240 pathToBuildFile = strings.Split(pathToBuildFile, ":")[0]
241 return pathToBuildFile
242}
243
244func getHandcraftedBuildContent(ctx *CodegenContext, b android.Bazelable, pathToBuildFile string) (BazelTarget, error) {
245 p := android.ExistentPathForSource(ctx, pathToBuildFile, HandcraftedBuildFileName)
246 if !p.Valid() {
247 return BazelTarget{}, fmt.Errorf("Could not find file %q for handcrafted target.", pathToBuildFile)
248 }
249 c, err := b.GetBazelBuildFileContents(ctx.Config(), pathToBuildFile, HandcraftedBuildFileName)
250 if err != nil {
251 return BazelTarget{}, err
252 }
253 // TODO(b/181575318): once this is more targeted, we need to include name, rule class, etc
254 return BazelTarget{
255 content: c,
256 }, nil
257}
258
259func generateBazelTarget(ctx bpToBuildContext, m blueprint.Module, btm android.BazelTargetModule) BazelTarget {
260 ruleClass := btm.RuleClass()
261 bzlLoadLocation := btm.BzlLoadLocation()
Jingwen Chen40067de2021-01-26 21:58:43 -0500262
Jingwen Chen73850672020-12-14 08:25:34 -0500263 // extract the bazel attributes from the module.
264 props := getBuildProperties(ctx, m)
265
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500266 delete(props.Attrs, "bp2build_available")
267
Jingwen Chen73850672020-12-14 08:25:34 -0500268 // Return the Bazel target with rule class and attributes, ready to be
269 // code-generated.
270 attributes := propsToAttributes(props.Attrs)
271 targetName := targetNameForBp2Build(ctx, m)
272 return BazelTarget{
Jingwen Chen40067de2021-01-26 21:58:43 -0500273 name: targetName,
274 ruleClass: ruleClass,
275 bzlLoadLocation: bzlLoadLocation,
Jingwen Chen73850672020-12-14 08:25:34 -0500276 content: fmt.Sprintf(
277 bazelTarget,
278 ruleClass,
279 targetName,
280 attributes,
281 ),
282 }
283}
284
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800285// Convert a module and its deps and props into a Bazel macro/rule
286// representation in the BUILD file.
287func generateSoongModuleTarget(ctx bpToBuildContext, m blueprint.Module) BazelTarget {
288 props := getBuildProperties(ctx, m)
289
290 // TODO(b/163018919): DirectDeps can have duplicate (module, variant)
291 // items, if the modules are added using different DependencyTag. Figure
292 // out the implications of that.
293 depLabels := map[string]bool{}
294 if aModule, ok := m.(android.Module); ok {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500295 ctx.VisitDirectDeps(aModule, func(depModule blueprint.Module) {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800296 depLabels[qualifiedTargetLabel(ctx, depModule)] = true
297 })
298 }
299 attributes := propsToAttributes(props.Attrs)
300
301 depLabelList := "[\n"
302 for depLabel, _ := range depLabels {
303 depLabelList += fmt.Sprintf(" %q,\n", depLabel)
304 }
305 depLabelList += " ]"
306
307 targetName := targetNameWithVariant(ctx, m)
308 return BazelTarget{
309 name: targetName,
310 content: fmt.Sprintf(
311 soongModuleTarget,
312 targetName,
313 ctx.ModuleName(m),
314 canonicalizeModuleType(ctx.ModuleType(m)),
315 ctx.ModuleSubDir(m),
316 depLabelList,
317 attributes),
318 }
319}
320
321func getBuildProperties(ctx bpToBuildContext, m blueprint.Module) BazelAttributes {
322 var allProps map[string]string
323 // TODO: this omits properties for blueprint modules (blueprint_go_binary,
324 // bootstrap_go_binary, bootstrap_go_package), which will have to be handled separately.
325 if aModule, ok := m.(android.Module); ok {
326 allProps = ExtractModuleProperties(aModule)
327 }
328
329 return BazelAttributes{
330 Attrs: allProps,
331 }
332}
333
334// Generically extract module properties and types into a map, keyed by the module property name.
335func ExtractModuleProperties(aModule android.Module) map[string]string {
336 ret := map[string]string{}
337
338 // Iterate over this android.Module's property structs.
339 for _, properties := range aModule.GetProperties() {
340 propertiesValue := reflect.ValueOf(properties)
341 // Check that propertiesValue is a pointer to the Properties struct, like
342 // *cc.BaseLinkerProperties or *java.CompilerProperties.
343 //
344 // propertiesValue can also be type-asserted to the structs to
345 // manipulate internal props, if needed.
346 if isStructPtr(propertiesValue.Type()) {
347 structValue := propertiesValue.Elem()
348 for k, v := range extractStructProperties(structValue, 0) {
349 ret[k] = v
350 }
351 } else {
352 panic(fmt.Errorf(
353 "properties must be a pointer to a struct, got %T",
354 propertiesValue.Interface()))
355 }
356 }
357
358 return ret
359}
360
361func isStructPtr(t reflect.Type) bool {
362 return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
363}
364
365// prettyPrint a property value into the equivalent Starlark representation
366// recursively.
367func prettyPrint(propertyValue reflect.Value, indent int) (string, error) {
368 if isZero(propertyValue) {
369 // A property value being set or unset actually matters -- Soong does set default
370 // values for unset properties, like system_shared_libs = ["libc", "libm", "libdl"] at
371 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=281-287;drc=f70926eef0b9b57faf04c17a1062ce50d209e480
372 //
Jingwen Chenfc490bd2021-03-30 10:24:19 +0000373 // In Bazel-parlance, we would use "attr.<type>(default = <default
374 // value>)" to set the default value of unset attributes. In the cases
375 // where the bp2build converter didn't set the default value within the
376 // mutator when creating the BazelTargetModule, this would be a zero
377 // value. For those cases, we return a non-surprising default value so
378 // generated BUILD files are syntactically correct.
379 switch propertyValue.Kind() {
380 case reflect.Slice:
381 return "[]", nil
382 case reflect.Map:
383 return "{}", nil
384 default:
385 return "", nil
386 }
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800387 }
388
389 var ret string
390 switch propertyValue.Kind() {
391 case reflect.String:
392 ret = fmt.Sprintf("\"%v\"", escapeString(propertyValue.String()))
393 case reflect.Bool:
394 ret = strings.Title(fmt.Sprintf("%v", propertyValue.Interface()))
395 case reflect.Int, reflect.Uint, reflect.Int64:
396 ret = fmt.Sprintf("%v", propertyValue.Interface())
397 case reflect.Ptr:
398 return prettyPrint(propertyValue.Elem(), indent)
399 case reflect.Slice:
400 ret = "[\n"
401 for i := 0; i < propertyValue.Len(); i++ {
402 indexedValue, err := prettyPrint(propertyValue.Index(i), indent+1)
403 if err != nil {
404 return "", err
405 }
406
407 if indexedValue != "" {
408 ret += makeIndent(indent + 1)
409 ret += indexedValue
410 ret += ",\n"
411 }
412 }
413 ret += makeIndent(indent)
414 ret += "]"
415 case reflect.Struct:
Jingwen Chen5d864492021-02-24 07:20:12 -0500416 // Special cases where the bp2build sends additional information to the codegenerator
417 // by wrapping the attributes in a custom struct type.
Jingwen Chen07027912021-03-15 06:02:43 -0400418 if labels, ok := propertyValue.Interface().(bazel.LabelListAttribute); ok {
Liz Kammer356f7d42021-01-26 09:18:53 -0500419 // TODO(b/165114590): convert glob syntax
Jingwen Chen07027912021-03-15 06:02:43 -0400420 ret, err := prettyPrint(reflect.ValueOf(labels.Value.Includes), indent)
421 if err != nil {
422 return ret, err
423 }
424
425 if !labels.HasArchSpecificValues() {
426 // Select statement not needed.
427 return ret, nil
428 }
429
430 ret += " + " + "select({\n"
431 for _, arch := range android.ArchTypeList() {
432 value := labels.GetValueForArch(arch.Name)
433 if len(value.Includes) > 0 {
434 ret += makeIndent(indent + 1)
435 list, _ := prettyPrint(reflect.ValueOf(value.Includes), indent+1)
436 ret += fmt.Sprintf("\"%s\": %s,\n", platformArchMap[arch], list)
437 }
438 }
439
440 ret += makeIndent(indent + 1)
441 ret += fmt.Sprintf("\"%s\": [],\n", "//conditions:default")
442
443 ret += makeIndent(indent)
444 ret += "})"
445 return ret, err
Liz Kammer356f7d42021-01-26 09:18:53 -0500446 } else if label, ok := propertyValue.Interface().(bazel.Label); ok {
447 return fmt.Sprintf("%q", label.Label), nil
Jingwen Chen5d864492021-02-24 07:20:12 -0500448 } else if stringList, ok := propertyValue.Interface().(bazel.StringListAttribute); ok {
449 // A Bazel string_list attribute that may contain a select statement.
450 ret, err := prettyPrint(reflect.ValueOf(stringList.Value), indent)
451 if err != nil {
452 return ret, err
453 }
454
455 if !stringList.HasArchSpecificValues() {
456 // Select statement not needed.
457 return ret, nil
458 }
459
460 ret += " + " + "select({\n"
461 for _, arch := range android.ArchTypeList() {
462 value := stringList.GetValueForArch(arch.Name)
463 if len(value) > 0 {
464 ret += makeIndent(indent + 1)
465 list, _ := prettyPrint(reflect.ValueOf(value), indent+1)
466 ret += fmt.Sprintf("\"%s\": %s,\n", platformArchMap[arch], list)
467 }
468 }
469
470 ret += makeIndent(indent + 1)
Jingwen Chen07027912021-03-15 06:02:43 -0400471 ret += fmt.Sprintf("\"%s\": [],\n", "//conditions:default")
Jingwen Chen5d864492021-02-24 07:20:12 -0500472
473 ret += makeIndent(indent)
474 ret += "})"
475 return ret, err
Liz Kammer356f7d42021-01-26 09:18:53 -0500476 }
477
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800478 ret = "{\n"
479 // Sort and print the struct props by the key.
480 structProps := extractStructProperties(propertyValue, indent)
481 for _, k := range android.SortedStringKeys(structProps) {
482 ret += makeIndent(indent + 1)
483 ret += fmt.Sprintf("%q: %s,\n", k, structProps[k])
484 }
485 ret += makeIndent(indent)
486 ret += "}"
487 case reflect.Interface:
488 // TODO(b/164227191): implement pretty print for interfaces.
489 // Interfaces are used for for arch, multilib and target properties.
490 return "", nil
491 default:
492 return "", fmt.Errorf(
493 "unexpected kind for property struct field: %s", propertyValue.Kind())
494 }
495 return ret, nil
496}
497
498// Converts a reflected property struct value into a map of property names and property values,
499// which each property value correctly pretty-printed and indented at the right nest level,
500// since property structs can be nested. In Starlark, nested structs are represented as nested
501// dicts: https://docs.bazel.build/skylark/lib/dict.html
502func extractStructProperties(structValue reflect.Value, indent int) map[string]string {
503 if structValue.Kind() != reflect.Struct {
504 panic(fmt.Errorf("Expected a reflect.Struct type, but got %s", structValue.Kind()))
505 }
506
507 ret := map[string]string{}
508 structType := structValue.Type()
509 for i := 0; i < structValue.NumField(); i++ {
510 field := structType.Field(i)
511 if shouldSkipStructField(field) {
512 continue
513 }
514
515 fieldValue := structValue.Field(i)
516 if isZero(fieldValue) {
517 // Ignore zero-valued fields
518 continue
519 }
520
521 propertyName := proptools.PropertyNameForField(field.Name)
522 prettyPrintedValue, err := prettyPrint(fieldValue, indent+1)
523 if err != nil {
524 panic(
525 fmt.Errorf(
526 "Error while parsing property: %q. %s",
527 propertyName,
528 err))
529 }
530 if prettyPrintedValue != "" {
531 ret[propertyName] = prettyPrintedValue
532 }
533 }
534
535 return ret
536}
537
538func isZero(value reflect.Value) bool {
539 switch value.Kind() {
540 case reflect.Func, reflect.Map, reflect.Slice:
541 return value.IsNil()
542 case reflect.Array:
543 valueIsZero := true
544 for i := 0; i < value.Len(); i++ {
545 valueIsZero = valueIsZero && isZero(value.Index(i))
546 }
547 return valueIsZero
548 case reflect.Struct:
549 valueIsZero := true
550 for i := 0; i < value.NumField(); i++ {
551 if value.Field(i).CanSet() {
552 valueIsZero = valueIsZero && isZero(value.Field(i))
553 }
554 }
555 return valueIsZero
556 case reflect.Ptr:
557 if !value.IsNil() {
558 return isZero(reflect.Indirect(value))
559 } else {
560 return true
561 }
562 default:
563 zeroValue := reflect.Zero(value.Type())
564 result := value.Interface() == zeroValue.Interface()
565 return result
566 }
567}
568
569func escapeString(s string) string {
570 s = strings.ReplaceAll(s, "\\", "\\\\")
Jingwen Chen58a12b82021-03-30 13:08:36 +0000571
572 // b/184026959: Reverse the application of some common control sequences.
573 // These must be generated literally in the BUILD file.
574 s = strings.ReplaceAll(s, "\t", "\\t")
575 s = strings.ReplaceAll(s, "\n", "\\n")
576 s = strings.ReplaceAll(s, "\r", "\\r")
577
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800578 return strings.ReplaceAll(s, "\"", "\\\"")
579}
580
581func makeIndent(indent int) string {
582 if indent < 0 {
583 panic(fmt.Errorf("indent column cannot be less than 0, but got %d", indent))
584 }
585 return strings.Repeat(" ", indent)
586}
587
Jingwen Chen73850672020-12-14 08:25:34 -0500588func targetNameForBp2Build(c bpToBuildContext, logicModule blueprint.Module) string {
Jingwen Chenfb4692a2021-02-07 10:05:16 -0500589 return strings.Replace(c.ModuleName(logicModule), bazel.BazelTargetModuleNamePrefix, "", 1)
Jingwen Chen73850672020-12-14 08:25:34 -0500590}
591
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800592func targetNameWithVariant(c bpToBuildContext, logicModule blueprint.Module) string {
593 name := ""
594 if c.ModuleSubDir(logicModule) != "" {
595 // TODO(b/162720883): Figure out a way to drop the "--" variant suffixes.
596 name = c.ModuleName(logicModule) + "--" + c.ModuleSubDir(logicModule)
597 } else {
598 name = c.ModuleName(logicModule)
599 }
600
601 return strings.Replace(name, "//", "", 1)
602}
603
604func qualifiedTargetLabel(c bpToBuildContext, logicModule blueprint.Module) string {
605 return fmt.Sprintf("//%s:%s", c.ModuleDir(logicModule), targetNameWithVariant(c, logicModule))
606}