modules.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. // 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. package soongconfig
  15. import (
  16. "fmt"
  17. "io"
  18. "reflect"
  19. "sort"
  20. "strings"
  21. "sync"
  22. "github.com/google/blueprint"
  23. "github.com/google/blueprint/parser"
  24. "github.com/google/blueprint/proptools"
  25. "android/soong/starlark_fmt"
  26. )
  27. const conditionsDefault = "conditions_default"
  28. var SoongConfigProperty = proptools.FieldNameForProperty("soong_config_variables")
  29. // loadSoongConfigModuleTypeDefinition loads module types from an Android.bp file. It caches the
  30. // result so each file is only parsed once.
  31. func Parse(r io.Reader, from string) (*SoongConfigDefinition, []error) {
  32. scope := parser.NewScope(nil)
  33. file, errs := parser.ParseAndEval(from, r, scope)
  34. if len(errs) > 0 {
  35. return nil, errs
  36. }
  37. mtDef := &SoongConfigDefinition{
  38. ModuleTypes: make(map[string]*ModuleType),
  39. variables: make(map[string]soongConfigVariable),
  40. }
  41. for _, def := range file.Defs {
  42. switch def := def.(type) {
  43. case *parser.Module:
  44. newErrs := processImportModuleDef(mtDef, def)
  45. if len(newErrs) > 0 {
  46. errs = append(errs, newErrs...)
  47. }
  48. case *parser.Assignment:
  49. // Already handled via Scope object
  50. default:
  51. panic("unknown definition type")
  52. }
  53. }
  54. if len(errs) > 0 {
  55. return nil, errs
  56. }
  57. for name, moduleType := range mtDef.ModuleTypes {
  58. for _, varName := range moduleType.variableNames {
  59. if v, ok := mtDef.variables[varName]; ok {
  60. moduleType.Variables = append(moduleType.Variables, v)
  61. } else {
  62. return nil, []error{
  63. fmt.Errorf("unknown variable %q in module type %q", varName, name),
  64. }
  65. }
  66. }
  67. }
  68. return mtDef, nil
  69. }
  70. func processImportModuleDef(v *SoongConfigDefinition, def *parser.Module) (errs []error) {
  71. switch def.Type {
  72. case "soong_config_module_type":
  73. return processModuleTypeDef(v, def)
  74. case "soong_config_string_variable":
  75. return processStringVariableDef(v, def)
  76. case "soong_config_bool_variable":
  77. return processBoolVariableDef(v, def)
  78. default:
  79. // Unknown module types will be handled when the file is parsed as a normal
  80. // Android.bp file.
  81. }
  82. return nil
  83. }
  84. type ModuleTypeProperties struct {
  85. // the name of the new module type. Unlike most modules, this name does not need to be unique,
  86. // although only one module type with any name will be importable into an Android.bp file.
  87. Name string
  88. // the module type that this module type will extend.
  89. Module_type string
  90. // the SOONG_CONFIG_NAMESPACE value from a BoardConfig.mk that this module type will read
  91. // configuration variables from.
  92. Config_namespace string
  93. // the list of SOONG_CONFIG variables that this module type will read
  94. Variables []string
  95. // the list of boolean SOONG_CONFIG variables that this module type will read
  96. Bool_variables []string
  97. // the list of SOONG_CONFIG variables that this module type will read. The value will be
  98. // inserted into the properties with %s substitution.
  99. Value_variables []string
  100. // the list of properties that this module type will extend.
  101. Properties []string
  102. }
  103. func processModuleTypeDef(v *SoongConfigDefinition, def *parser.Module) (errs []error) {
  104. props := &ModuleTypeProperties{}
  105. _, errs = proptools.UnpackProperties(def.Properties, props)
  106. if len(errs) > 0 {
  107. return errs
  108. }
  109. if props.Name == "" {
  110. errs = append(errs, fmt.Errorf("name property must be set"))
  111. }
  112. if props.Config_namespace == "" {
  113. errs = append(errs, fmt.Errorf("config_namespace property must be set"))
  114. }
  115. if props.Module_type == "" {
  116. errs = append(errs, fmt.Errorf("module_type property must be set"))
  117. }
  118. if len(errs) > 0 {
  119. return errs
  120. }
  121. if mt, errs := newModuleType(props); len(errs) > 0 {
  122. return errs
  123. } else {
  124. v.ModuleTypes[props.Name] = mt
  125. }
  126. return nil
  127. }
  128. type VariableProperties struct {
  129. Name string
  130. }
  131. type StringVariableProperties struct {
  132. Values []string
  133. }
  134. func processStringVariableDef(v *SoongConfigDefinition, def *parser.Module) (errs []error) {
  135. stringProps := &StringVariableProperties{}
  136. base, errs := processVariableDef(def, stringProps)
  137. if len(errs) > 0 {
  138. return errs
  139. }
  140. if len(stringProps.Values) == 0 {
  141. return []error{fmt.Errorf("values property must be set")}
  142. }
  143. vals := make(map[string]bool, len(stringProps.Values))
  144. for _, name := range stringProps.Values {
  145. if err := checkVariableName(name); err != nil {
  146. return []error{fmt.Errorf("soong_config_string_variable: values property error %s", err)}
  147. } else if _, ok := vals[name]; ok {
  148. return []error{fmt.Errorf("soong_config_string_variable: values property error: duplicate value: %q", name)}
  149. }
  150. vals[name] = true
  151. }
  152. v.variables[base.variable] = &stringVariable{
  153. baseVariable: base,
  154. values: CanonicalizeToProperties(stringProps.Values),
  155. }
  156. return nil
  157. }
  158. func processBoolVariableDef(v *SoongConfigDefinition, def *parser.Module) (errs []error) {
  159. base, errs := processVariableDef(def)
  160. if len(errs) > 0 {
  161. return errs
  162. }
  163. v.variables[base.variable] = &boolVariable{
  164. baseVariable: base,
  165. }
  166. return nil
  167. }
  168. func processVariableDef(def *parser.Module,
  169. extraProps ...interface{}) (cond baseVariable, errs []error) {
  170. props := &VariableProperties{}
  171. allProps := append([]interface{}{props}, extraProps...)
  172. _, errs = proptools.UnpackProperties(def.Properties, allProps...)
  173. if len(errs) > 0 {
  174. return baseVariable{}, errs
  175. }
  176. if props.Name == "" {
  177. return baseVariable{}, []error{fmt.Errorf("name property must be set")}
  178. }
  179. return baseVariable{
  180. variable: props.Name,
  181. }, nil
  182. }
  183. type SoongConfigDefinition struct {
  184. ModuleTypes map[string]*ModuleType
  185. variables map[string]soongConfigVariable
  186. }
  187. // Bp2BuildSoongConfigDefinition keeps a global record of all soong config
  188. // string vars, bool vars and value vars created by every
  189. // soong_config_module_type in this build.
  190. type Bp2BuildSoongConfigDefinitions struct {
  191. // varCache contains a cache of string variables namespace + property
  192. // The same variable may be used in multiple module types (for example, if need support
  193. // for cc_default and java_default), only need to process once
  194. varCache map[string]bool
  195. StringVars map[string][]string
  196. BoolVars map[string]bool
  197. ValueVars map[string]bool
  198. }
  199. var bp2buildSoongConfigVarsLock sync.Mutex
  200. // SoongConfigVariablesForBp2build extracts information from a
  201. // SoongConfigDefinition that bp2build needs to generate constraint settings and
  202. // values for, in order to migrate soong_config_module_type usages to Bazel.
  203. func (defs *Bp2BuildSoongConfigDefinitions) AddVars(mtDef SoongConfigDefinition) {
  204. // In bp2build mode, this method is called concurrently in goroutines from
  205. // loadhooks while parsing soong_config_module_type, so add a mutex to
  206. // prevent concurrent map writes. See b/207572723
  207. bp2buildSoongConfigVarsLock.Lock()
  208. defer bp2buildSoongConfigVarsLock.Unlock()
  209. if defs.StringVars == nil {
  210. defs.StringVars = make(map[string][]string)
  211. }
  212. if defs.BoolVars == nil {
  213. defs.BoolVars = make(map[string]bool)
  214. }
  215. if defs.ValueVars == nil {
  216. defs.ValueVars = make(map[string]bool)
  217. }
  218. if defs.varCache == nil {
  219. defs.varCache = make(map[string]bool)
  220. }
  221. for _, moduleType := range mtDef.ModuleTypes {
  222. for _, v := range moduleType.Variables {
  223. key := strings.Join([]string{moduleType.ConfigNamespace, v.variableProperty()}, "__")
  224. // The same variable may be used in multiple module types (for example, if need support
  225. // for cc_default and java_default), only need to process once
  226. if _, keyInCache := defs.varCache[key]; keyInCache {
  227. continue
  228. } else {
  229. defs.varCache[key] = true
  230. }
  231. if strVar, ok := v.(*stringVariable); ok {
  232. for _, value := range strVar.values {
  233. defs.StringVars[key] = append(defs.StringVars[key], value)
  234. }
  235. } else if _, ok := v.(*boolVariable); ok {
  236. defs.BoolVars[key] = true
  237. } else if _, ok := v.(*valueVariable); ok {
  238. defs.ValueVars[key] = true
  239. } else {
  240. panic(fmt.Errorf("Unsupported variable type: %+v", v))
  241. }
  242. }
  243. }
  244. }
  245. // This is a copy of the one available in soong/android/util.go, but depending
  246. // on the android package causes a cyclic dependency. A refactoring here is to
  247. // extract common utils out from android/utils.go for other packages like this.
  248. func sortedStringKeys(m interface{}) []string {
  249. v := reflect.ValueOf(m)
  250. if v.Kind() != reflect.Map {
  251. panic(fmt.Sprintf("%#v is not a map", m))
  252. }
  253. keys := v.MapKeys()
  254. s := make([]string, 0, len(keys))
  255. for _, key := range keys {
  256. s = append(s, key.String())
  257. }
  258. sort.Strings(s)
  259. return s
  260. }
  261. // String emits the Soong config variable definitions as Starlark dictionaries.
  262. func (defs Bp2BuildSoongConfigDefinitions) String() string {
  263. ret := ""
  264. ret += "soong_config_bool_variables = "
  265. ret += starlark_fmt.PrintBoolDict(defs.BoolVars, 0)
  266. ret += "\n\n"
  267. ret += "soong_config_value_variables = "
  268. ret += starlark_fmt.PrintBoolDict(defs.ValueVars, 0)
  269. ret += "\n\n"
  270. ret += "soong_config_string_variables = "
  271. ret += starlark_fmt.PrintStringListDict(defs.StringVars, 0)
  272. return ret
  273. }
  274. // CreateProperties returns a reflect.Value of a newly constructed type that contains the desired
  275. // property layout for the Soong config variables, with each possible value an interface{} that
  276. // contains a nil pointer to another newly constructed type that contains the affectable properties.
  277. // The reflect.Value will be cloned for each call to the Soong config module type's factory method.
  278. //
  279. // For example, the acme_cc_defaults example above would
  280. // produce a reflect.Value whose type is:
  281. //
  282. // *struct {
  283. // Soong_config_variables struct {
  284. // Board struct {
  285. // Soc_a interface{}
  286. // Soc_b interface{}
  287. // }
  288. // }
  289. // }
  290. //
  291. // And whose value is:
  292. //
  293. // &{
  294. // Soong_config_variables: {
  295. // Board: {
  296. // Soc_a: (*struct{ Cflags []string })(nil),
  297. // Soc_b: (*struct{ Cflags []string })(nil),
  298. // },
  299. // },
  300. // }
  301. func CreateProperties(factory blueprint.ModuleFactory, moduleType *ModuleType) reflect.Value {
  302. var fields []reflect.StructField
  303. _, factoryProps := factory()
  304. affectablePropertiesType := createAffectablePropertiesType(moduleType.affectableProperties, factoryProps)
  305. if affectablePropertiesType == nil {
  306. return reflect.Value{}
  307. }
  308. for _, c := range moduleType.Variables {
  309. fields = append(fields, reflect.StructField{
  310. Name: proptools.FieldNameForProperty(c.variableProperty()),
  311. Type: c.variableValuesType(),
  312. })
  313. }
  314. typ := reflect.StructOf([]reflect.StructField{{
  315. Name: SoongConfigProperty,
  316. Type: reflect.StructOf(fields),
  317. }})
  318. props := reflect.New(typ)
  319. structConditions := props.Elem().FieldByName(SoongConfigProperty)
  320. for i, c := range moduleType.Variables {
  321. c.initializeProperties(structConditions.Field(i), affectablePropertiesType)
  322. }
  323. return props
  324. }
  325. // createAffectablePropertiesType creates a reflect.Type of a struct that has a field for each affectable property
  326. // that exists in factoryProps.
  327. func createAffectablePropertiesType(affectableProperties []string, factoryProps []interface{}) reflect.Type {
  328. affectableProperties = append([]string(nil), affectableProperties...)
  329. sort.Strings(affectableProperties)
  330. var recurse func(prefix string, aps []string) ([]string, reflect.Type)
  331. recurse = func(prefix string, aps []string) ([]string, reflect.Type) {
  332. var fields []reflect.StructField
  333. // Iterate while the list is non-empty so it can be modified in the loop.
  334. for len(affectableProperties) > 0 {
  335. p := affectableProperties[0]
  336. if !strings.HasPrefix(affectableProperties[0], prefix) {
  337. // The properties are sorted and recurse is always called with a prefix that matches
  338. // the first property in the list, so if we've reached one that doesn't match the
  339. // prefix we are done with this prefix.
  340. break
  341. }
  342. nestedProperty := strings.TrimPrefix(p, prefix)
  343. if i := strings.IndexRune(nestedProperty, '.'); i >= 0 {
  344. var nestedType reflect.Type
  345. nestedPrefix := nestedProperty[:i+1]
  346. // Recurse to handle the properties with the found prefix. This will return
  347. // an updated affectableProperties with the handled entries removed from the front
  348. // of the list, and the type that contains the handled entries. The type may be
  349. // nil if none of the entries matched factoryProps.
  350. affectableProperties, nestedType = recurse(prefix+nestedPrefix, affectableProperties)
  351. if nestedType != nil {
  352. nestedFieldName := proptools.FieldNameForProperty(strings.TrimSuffix(nestedPrefix, "."))
  353. fields = append(fields, reflect.StructField{
  354. Name: nestedFieldName,
  355. Type: nestedType,
  356. })
  357. }
  358. } else {
  359. typ := typeForPropertyFromPropertyStructs(factoryProps, p)
  360. if typ != nil {
  361. fields = append(fields, reflect.StructField{
  362. Name: proptools.FieldNameForProperty(nestedProperty),
  363. Type: typ,
  364. })
  365. }
  366. // The first element in the list has been handled, remove it from the list.
  367. affectableProperties = affectableProperties[1:]
  368. }
  369. }
  370. var typ reflect.Type
  371. if len(fields) > 0 {
  372. typ = reflect.StructOf(fields)
  373. }
  374. return affectableProperties, typ
  375. }
  376. affectableProperties, typ := recurse("", affectableProperties)
  377. if len(affectableProperties) > 0 {
  378. panic(fmt.Errorf("didn't handle all affectable properties"))
  379. }
  380. if typ != nil {
  381. return reflect.PtrTo(typ)
  382. }
  383. return nil
  384. }
  385. func typeForPropertyFromPropertyStructs(psList []interface{}, property string) reflect.Type {
  386. for _, ps := range psList {
  387. if typ := typeForPropertyFromPropertyStruct(ps, property); typ != nil {
  388. return typ
  389. }
  390. }
  391. return nil
  392. }
  393. func typeForPropertyFromPropertyStruct(ps interface{}, property string) reflect.Type {
  394. v := reflect.ValueOf(ps)
  395. for len(property) > 0 {
  396. if !v.IsValid() {
  397. return nil
  398. }
  399. if v.Kind() == reflect.Interface {
  400. if v.IsNil() {
  401. return nil
  402. } else {
  403. v = v.Elem()
  404. }
  405. }
  406. if v.Kind() == reflect.Ptr {
  407. if v.IsNil() {
  408. v = reflect.Zero(v.Type().Elem())
  409. } else {
  410. v = v.Elem()
  411. }
  412. }
  413. if v.Kind() != reflect.Struct {
  414. return nil
  415. }
  416. if index := strings.IndexRune(property, '.'); index >= 0 {
  417. prefix := property[:index]
  418. property = property[index+1:]
  419. v = v.FieldByName(proptools.FieldNameForProperty(prefix))
  420. } else {
  421. f := v.FieldByName(proptools.FieldNameForProperty(property))
  422. if !f.IsValid() {
  423. return nil
  424. }
  425. return f.Type()
  426. }
  427. }
  428. return nil
  429. }
  430. // PropertiesToApply returns the applicable properties from a ModuleType that should be applied
  431. // based on SoongConfig values.
  432. // Expects that props contains a struct field with name soong_config_variables. The fields within
  433. // soong_config_variables are expected to be in the same order as moduleType.Variables.
  434. func PropertiesToApply(moduleType *ModuleType, props reflect.Value, config SoongConfig) ([]interface{}, error) {
  435. var ret []interface{}
  436. props = props.Elem().FieldByName(SoongConfigProperty)
  437. for i, c := range moduleType.Variables {
  438. if ps, err := c.PropertiesToApply(config, props.Field(i)); err != nil {
  439. return nil, err
  440. } else if ps != nil {
  441. ret = append(ret, ps)
  442. }
  443. }
  444. return ret, nil
  445. }
  446. type ModuleType struct {
  447. BaseModuleType string
  448. ConfigNamespace string
  449. Variables []soongConfigVariable
  450. affectableProperties []string
  451. variableNames []string
  452. }
  453. func newModuleType(props *ModuleTypeProperties) (*ModuleType, []error) {
  454. mt := &ModuleType{
  455. affectableProperties: props.Properties,
  456. ConfigNamespace: props.Config_namespace,
  457. BaseModuleType: props.Module_type,
  458. variableNames: props.Variables,
  459. }
  460. for _, name := range props.Bool_variables {
  461. if err := checkVariableName(name); err != nil {
  462. return nil, []error{fmt.Errorf("bool_variables %s", err)}
  463. }
  464. mt.Variables = append(mt.Variables, newBoolVariable(name))
  465. }
  466. for _, name := range props.Value_variables {
  467. if err := checkVariableName(name); err != nil {
  468. return nil, []error{fmt.Errorf("value_variables %s", err)}
  469. }
  470. mt.Variables = append(mt.Variables, &valueVariable{
  471. baseVariable: baseVariable{
  472. variable: name,
  473. },
  474. })
  475. }
  476. return mt, nil
  477. }
  478. func checkVariableName(name string) error {
  479. if name == "" {
  480. return fmt.Errorf("name must not be blank")
  481. } else if name == conditionsDefault {
  482. return fmt.Errorf("%q is reserved", conditionsDefault)
  483. }
  484. return nil
  485. }
  486. type soongConfigVariable interface {
  487. // variableProperty returns the name of the variable.
  488. variableProperty() string
  489. // conditionalValuesType returns a reflect.Type that contains an interface{} for each possible value.
  490. variableValuesType() reflect.Type
  491. // initializeProperties is passed a reflect.Value of the reflect.Type returned by conditionalValuesType and a
  492. // reflect.Type of the affectable properties, and should initialize each interface{} in the reflect.Value with
  493. // the zero value of the affectable properties type.
  494. initializeProperties(v reflect.Value, typ reflect.Type)
  495. // PropertiesToApply should return one of the interface{} values set by initializeProperties to be applied
  496. // to the module.
  497. PropertiesToApply(config SoongConfig, values reflect.Value) (interface{}, error)
  498. }
  499. type baseVariable struct {
  500. variable string
  501. }
  502. func (c *baseVariable) variableProperty() string {
  503. return CanonicalizeToProperty(c.variable)
  504. }
  505. type stringVariable struct {
  506. baseVariable
  507. values []string
  508. }
  509. func (s *stringVariable) variableValuesType() reflect.Type {
  510. var fields []reflect.StructField
  511. var values []string
  512. values = append(values, s.values...)
  513. values = append(values, conditionsDefault)
  514. for _, v := range values {
  515. fields = append(fields, reflect.StructField{
  516. Name: proptools.FieldNameForProperty(v),
  517. Type: emptyInterfaceType,
  518. })
  519. }
  520. return reflect.StructOf(fields)
  521. }
  522. // initializeProperties initializes properties to zero value of typ for supported values and a final
  523. // conditions default field.
  524. func (s *stringVariable) initializeProperties(v reflect.Value, typ reflect.Type) {
  525. for i := range s.values {
  526. v.Field(i).Set(reflect.Zero(typ))
  527. }
  528. v.Field(len(s.values)).Set(reflect.Zero(typ)) // conditions default is the final value
  529. }
  530. // Extracts an interface from values containing the properties to apply based on config.
  531. // If config does not match a value with a non-nil property set, the default value will be returned.
  532. func (s *stringVariable) PropertiesToApply(config SoongConfig, values reflect.Value) (interface{}, error) {
  533. for j, v := range s.values {
  534. f := values.Field(j)
  535. if config.String(s.variable) == v && !f.Elem().IsNil() {
  536. return f.Interface(), nil
  537. }
  538. }
  539. // if we have reached this point, we have checked all valid values of string and either:
  540. // * the value was not set
  541. // * the value was set but that value was not specified in the Android.bp file
  542. return values.Field(len(s.values)).Interface(), nil
  543. }
  544. // Struct to allow conditions set based on a boolean variable
  545. type boolVariable struct {
  546. baseVariable
  547. }
  548. // newBoolVariable constructs a boolVariable with the given name
  549. func newBoolVariable(name string) *boolVariable {
  550. return &boolVariable{
  551. baseVariable{
  552. variable: name,
  553. },
  554. }
  555. }
  556. func (b boolVariable) variableValuesType() reflect.Type {
  557. return emptyInterfaceType
  558. }
  559. // initializeProperties initializes a property to zero value of typ with an additional conditions
  560. // default field.
  561. func (b boolVariable) initializeProperties(v reflect.Value, typ reflect.Type) {
  562. initializePropertiesWithDefault(v, typ)
  563. }
  564. // initializePropertiesWithDefault, initialize with zero value, v to contain a field for each field
  565. // in typ, with an additional field for defaults of type typ. This should be used to initialize
  566. // boolVariable, valueVariable, or any future implementations of soongConfigVariable which support
  567. // one variable and a default.
  568. func initializePropertiesWithDefault(v reflect.Value, typ reflect.Type) {
  569. sTyp := typ.Elem()
  570. var fields []reflect.StructField
  571. for i := 0; i < sTyp.NumField(); i++ {
  572. fields = append(fields, sTyp.Field(i))
  573. }
  574. // create conditions_default field
  575. nestedFieldName := proptools.FieldNameForProperty(conditionsDefault)
  576. fields = append(fields, reflect.StructField{
  577. Name: nestedFieldName,
  578. Type: typ,
  579. })
  580. newTyp := reflect.PtrTo(reflect.StructOf(fields))
  581. v.Set(reflect.Zero(newTyp))
  582. }
  583. // conditionsDefaultField extracts the conditions_default field from v. This is always the final
  584. // field if initialized with initializePropertiesWithDefault.
  585. func conditionsDefaultField(v reflect.Value) reflect.Value {
  586. return v.Field(v.NumField() - 1)
  587. }
  588. // removeDefault removes the conditions_default field from values while retaining values from all
  589. // other fields. This allows
  590. func removeDefault(values reflect.Value) reflect.Value {
  591. v := values.Elem().Elem()
  592. s := conditionsDefaultField(v)
  593. // if conditions_default field was not set, there will be no issues extending properties.
  594. if !s.IsValid() {
  595. return v
  596. }
  597. // If conditions_default field was set, it has the correct type for our property. Create a new
  598. // reflect.Value of the conditions_default type and copy all fields (except for
  599. // conditions_default) based on values to the result.
  600. res := reflect.New(s.Type().Elem())
  601. for i := 0; i < res.Type().Elem().NumField(); i++ {
  602. val := v.Field(i)
  603. res.Elem().Field(i).Set(val)
  604. }
  605. return res
  606. }
  607. // PropertiesToApply returns an interface{} value based on initializeProperties to be applied to
  608. // the module. If the value was not set, conditions_default interface will be returned; otherwise,
  609. // the interface in values, without conditions_default will be returned.
  610. func (b boolVariable) PropertiesToApply(config SoongConfig, values reflect.Value) (interface{}, error) {
  611. // If this variable was not referenced in the module, there are no properties to apply.
  612. if values.Elem().IsZero() {
  613. return nil, nil
  614. }
  615. if config.Bool(b.variable) {
  616. values = removeDefault(values)
  617. return values.Interface(), nil
  618. }
  619. v := values.Elem().Elem()
  620. if f := conditionsDefaultField(v); f.IsValid() {
  621. return f.Interface(), nil
  622. }
  623. return nil, nil
  624. }
  625. // Struct to allow conditions set based on a value variable, supporting string substitution.
  626. type valueVariable struct {
  627. baseVariable
  628. }
  629. func (s *valueVariable) variableValuesType() reflect.Type {
  630. return emptyInterfaceType
  631. }
  632. // initializeProperties initializes a property to zero value of typ with an additional conditions
  633. // default field.
  634. func (s *valueVariable) initializeProperties(v reflect.Value, typ reflect.Type) {
  635. initializePropertiesWithDefault(v, typ)
  636. }
  637. // PropertiesToApply returns an interface{} value based on initializeProperties to be applied to
  638. // the module. If the variable was not set, conditions_default interface will be returned;
  639. // otherwise, the interface in values, without conditions_default will be returned with all
  640. // appropriate string substitutions based on variable being set.
  641. func (s *valueVariable) PropertiesToApply(config SoongConfig, values reflect.Value) (interface{}, error) {
  642. // If this variable was not referenced in the module, there are no properties to apply.
  643. if !values.IsValid() || values.Elem().IsZero() {
  644. return nil, nil
  645. }
  646. if !config.IsSet(s.variable) {
  647. return conditionsDefaultField(values.Elem().Elem()).Interface(), nil
  648. }
  649. configValue := config.String(s.variable)
  650. values = removeDefault(values)
  651. propStruct := values.Elem()
  652. if !propStruct.IsValid() {
  653. return nil, nil
  654. }
  655. for i := 0; i < propStruct.NumField(); i++ {
  656. field := propStruct.Field(i)
  657. kind := field.Kind()
  658. if kind == reflect.Ptr {
  659. if field.IsNil() {
  660. continue
  661. }
  662. field = field.Elem()
  663. }
  664. switch kind {
  665. case reflect.String:
  666. err := printfIntoProperty(field, configValue)
  667. if err != nil {
  668. return nil, fmt.Errorf("soong_config_variables.%s.%s: %s", s.variable, propStruct.Type().Field(i).Name, err)
  669. }
  670. case reflect.Slice:
  671. for j := 0; j < field.Len(); j++ {
  672. err := printfIntoProperty(field.Index(j), configValue)
  673. if err != nil {
  674. return nil, fmt.Errorf("soong_config_variables.%s.%s: %s", s.variable, propStruct.Type().Field(i).Name, err)
  675. }
  676. }
  677. case reflect.Bool:
  678. // Nothing to do
  679. default:
  680. return nil, fmt.Errorf("soong_config_variables.%s.%s: unsupported property type %q", s.variable, propStruct.Type().Field(i).Name, kind)
  681. }
  682. }
  683. return values.Interface(), nil
  684. }
  685. func printfIntoProperty(propertyValue reflect.Value, configValue string) error {
  686. s := propertyValue.String()
  687. count := strings.Count(s, "%")
  688. if count == 0 {
  689. return nil
  690. }
  691. if count > 1 {
  692. return fmt.Errorf("value variable properties only support a single '%%'")
  693. }
  694. if !strings.Contains(s, "%s") {
  695. return fmt.Errorf("unsupported %% in value variable property")
  696. }
  697. propertyValue.Set(reflect.ValueOf(fmt.Sprintf(s, configValue)))
  698. return nil
  699. }
  700. func CanonicalizeToProperty(v string) string {
  701. return strings.Map(func(r rune) rune {
  702. switch {
  703. case r >= 'A' && r <= 'Z',
  704. r >= 'a' && r <= 'z',
  705. r >= '0' && r <= '9',
  706. r == '_':
  707. return r
  708. default:
  709. return '_'
  710. }
  711. }, v)
  712. }
  713. func CanonicalizeToProperties(values []string) []string {
  714. ret := make([]string, len(values))
  715. for i, v := range values {
  716. ret[i] = CanonicalizeToProperty(v)
  717. }
  718. return ret
  719. }
  720. type emptyInterfaceStruct struct {
  721. i interface{}
  722. }
  723. var emptyInterfaceType = reflect.TypeOf(emptyInterfaceStruct{}).Field(0).Type