value.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. /* Copyright 2016 The Bazel Authors. All rights reserved.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package rule
  13. import (
  14. "fmt"
  15. "log"
  16. "reflect"
  17. "sort"
  18. bzl "github.com/bazelbuild/buildtools/build"
  19. )
  20. // KeyValue represents a key-value pair. This gets converted into a
  21. // rule attribute, i.e., a Skylark keyword argument.
  22. type KeyValue struct {
  23. Key string
  24. Value interface{}
  25. }
  26. // GlobValue represents a Bazel glob expression.
  27. type GlobValue struct {
  28. Patterns []string
  29. Excludes []string
  30. }
  31. // BzlExprValue is implemented by types that have custom translations
  32. // to Starlark values.
  33. type BzlExprValue interface {
  34. BzlExpr() bzl.Expr
  35. }
  36. // SelectStringListValue is a value that can be translated to a Bazel
  37. // select expression that picks a string list based on a string condition.
  38. type SelectStringListValue map[string][]string
  39. func (s SelectStringListValue) BzlExpr() bzl.Expr {
  40. defaultKey := "//conditions:default"
  41. keys := make([]string, 0, len(s))
  42. haveDefaultKey := false
  43. for key := range s {
  44. if key == defaultKey {
  45. haveDefaultKey = true
  46. } else {
  47. keys = append(keys, key)
  48. }
  49. }
  50. sort.Strings(keys)
  51. if haveDefaultKey {
  52. keys = append(keys, defaultKey)
  53. }
  54. args := make([]bzl.Expr, 0, len(s))
  55. for _, key := range keys {
  56. value := ExprFromValue(s[key])
  57. if key != defaultKey {
  58. value.(*bzl.ListExpr).ForceMultiLine = true
  59. }
  60. args = append(args, &bzl.KeyValueExpr{
  61. Key: &bzl.StringExpr{Value: key},
  62. Value: value,
  63. })
  64. }
  65. sel := &bzl.CallExpr{
  66. X: &bzl.Ident{Name: "select"},
  67. List: []bzl.Expr{&bzl.DictExpr{List: args, ForceMultiLine: true}},
  68. }
  69. return sel
  70. }
  71. // ExprFromValue converts a value into an expression that can be written into
  72. // a Bazel build file. The following types of values can be converted:
  73. //
  74. // * bools, integers, floats, strings.
  75. // * slices, arrays (converted to lists).
  76. // * maps (converted to select expressions; keys must be rules in
  77. // @io_bazel_rules_go//go/platform).
  78. // * GlobValue (converted to glob expressions).
  79. // * PlatformStrings (converted to a concatenation of a list and selects).
  80. //
  81. // Converting unsupported types will cause a panic.
  82. func ExprFromValue(val interface{}) bzl.Expr {
  83. if e, ok := val.(bzl.Expr); ok {
  84. return e
  85. }
  86. if be, ok := val.(BzlExprValue); ok {
  87. return be.BzlExpr()
  88. }
  89. rv := reflect.ValueOf(val)
  90. switch rv.Kind() {
  91. case reflect.Bool:
  92. tok := "False"
  93. if rv.Bool() {
  94. tok = "True"
  95. }
  96. return &bzl.LiteralExpr{Token: tok}
  97. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
  98. reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  99. return &bzl.LiteralExpr{Token: fmt.Sprintf("%d", val)}
  100. case reflect.Float32, reflect.Float64:
  101. return &bzl.LiteralExpr{Token: fmt.Sprintf("%f", val)}
  102. case reflect.String:
  103. return &bzl.StringExpr{Value: val.(string)}
  104. case reflect.Slice, reflect.Array:
  105. var list []bzl.Expr
  106. for i := 0; i < rv.Len(); i++ {
  107. elem := ExprFromValue(rv.Index(i).Interface())
  108. list = append(list, elem)
  109. }
  110. return &bzl.ListExpr{List: list}
  111. case reflect.Map:
  112. rkeys := rv.MapKeys()
  113. sort.Sort(byString(rkeys))
  114. args := make([]bzl.Expr, len(rkeys))
  115. for i, rk := range rkeys {
  116. k := &bzl.StringExpr{Value: mapKeyString(rk)}
  117. v := ExprFromValue(rv.MapIndex(rk).Interface())
  118. if l, ok := v.(*bzl.ListExpr); ok {
  119. l.ForceMultiLine = true
  120. }
  121. args[i] = &bzl.KeyValueExpr{Key: k, Value: v}
  122. }
  123. return &bzl.DictExpr{List: args, ForceMultiLine: true}
  124. case reflect.Struct:
  125. switch val := val.(type) {
  126. case GlobValue:
  127. patternsValue := ExprFromValue(val.Patterns)
  128. globArgs := []bzl.Expr{patternsValue}
  129. if len(val.Excludes) > 0 {
  130. excludesValue := ExprFromValue(val.Excludes)
  131. globArgs = append(globArgs, &bzl.KeyValueExpr{
  132. Key: &bzl.StringExpr{Value: "excludes"},
  133. Value: excludesValue,
  134. })
  135. }
  136. return &bzl.CallExpr{
  137. X: &bzl.LiteralExpr{Token: "glob"},
  138. List: globArgs,
  139. }
  140. }
  141. }
  142. log.Panicf("type not supported: %T", val)
  143. return nil
  144. }
  145. func mapKeyString(k reflect.Value) string {
  146. switch s := k.Interface().(type) {
  147. case string:
  148. return s
  149. default:
  150. log.Panicf("unexpected map key: %v", k)
  151. return ""
  152. }
  153. }
  154. type byString []reflect.Value
  155. var _ sort.Interface = byString{}
  156. func (s byString) Len() int {
  157. return len(s)
  158. }
  159. func (s byString) Less(i, j int) bool {
  160. return mapKeyString(s[i]) < mapKeyString(s[j])
  161. }
  162. func (s byString) Swap(i, j int) {
  163. s[i], s[j] = s[j], s[i]
  164. }