blob: 1af89ba5d08a8051d25964c05d3b4b096cda3d71 [file] [log] [blame]
Colin Cross9d34f352019-11-22 16:03:51 -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 soongconfig
16
17import (
Jingwen Chena47f28d2021-11-02 16:43:57 +000018 "android/soong/bazel"
Colin Cross9d34f352019-11-22 16:03:51 -080019 "fmt"
20 "io"
21 "reflect"
22 "sort"
23 "strings"
24
25 "github.com/google/blueprint"
26 "github.com/google/blueprint/parser"
27 "github.com/google/blueprint/proptools"
28)
29
Liz Kammer432bd592020-12-16 12:42:02 -080030const conditionsDefault = "conditions_default"
31
Jingwen Chena47f28d2021-11-02 16:43:57 +000032var SoongConfigProperty = proptools.FieldNameForProperty("soong_config_variables")
Colin Cross9d34f352019-11-22 16:03:51 -080033
34// loadSoongConfigModuleTypeDefinition loads module types from an Android.bp file. It caches the
35// result so each file is only parsed once.
36func Parse(r io.Reader, from string) (*SoongConfigDefinition, []error) {
37 scope := parser.NewScope(nil)
38 file, errs := parser.ParseAndEval(from, r, scope)
39
40 if len(errs) > 0 {
41 return nil, errs
42 }
43
44 mtDef := &SoongConfigDefinition{
45 ModuleTypes: make(map[string]*ModuleType),
46 variables: make(map[string]soongConfigVariable),
47 }
48
49 for _, def := range file.Defs {
50 switch def := def.(type) {
51 case *parser.Module:
52 newErrs := processImportModuleDef(mtDef, def)
53
54 if len(newErrs) > 0 {
55 errs = append(errs, newErrs...)
56 }
57
58 case *parser.Assignment:
59 // Already handled via Scope object
60 default:
61 panic("unknown definition type")
62 }
63 }
64
65 if len(errs) > 0 {
66 return nil, errs
67 }
68
69 for name, moduleType := range mtDef.ModuleTypes {
70 for _, varName := range moduleType.variableNames {
71 if v, ok := mtDef.variables[varName]; ok {
72 moduleType.Variables = append(moduleType.Variables, v)
73 } else {
74 return nil, []error{
75 fmt.Errorf("unknown variable %q in module type %q", varName, name),
76 }
77 }
78 }
79 }
80
81 return mtDef, nil
82}
83
84func processImportModuleDef(v *SoongConfigDefinition, def *parser.Module) (errs []error) {
85 switch def.Type {
86 case "soong_config_module_type":
87 return processModuleTypeDef(v, def)
88 case "soong_config_string_variable":
89 return processStringVariableDef(v, def)
90 case "soong_config_bool_variable":
91 return processBoolVariableDef(v, def)
92 default:
93 // Unknown module types will be handled when the file is parsed as a normal
94 // Android.bp file.
95 }
96
97 return nil
98}
99
100type ModuleTypeProperties struct {
101 // the name of the new module type. Unlike most modules, this name does not need to be unique,
102 // although only one module type with any name will be importable into an Android.bp file.
103 Name string
104
105 // the module type that this module type will extend.
106 Module_type string
107
108 // the SOONG_CONFIG_NAMESPACE value from a BoardConfig.mk that this module type will read
109 // configuration variables from.
110 Config_namespace string
111
112 // the list of SOONG_CONFIG variables that this module type will read
113 Variables []string
114
Dan Willemsen2b8b89c2020-03-23 19:39:34 -0700115 // the list of boolean SOONG_CONFIG variables that this module type will read
116 Bool_variables []string
117
Dan Willemsenb0935db2020-03-23 19:42:18 -0700118 // the list of SOONG_CONFIG variables that this module type will read. The value will be
119 // inserted into the properties with %s substitution.
120 Value_variables []string
121
Colin Cross9d34f352019-11-22 16:03:51 -0800122 // the list of properties that this module type will extend.
123 Properties []string
Jingwen Chena47f28d2021-11-02 16:43:57 +0000124
125 Bazel_module bazel.BazelModuleProperties
Colin Cross9d34f352019-11-22 16:03:51 -0800126}
127
128func processModuleTypeDef(v *SoongConfigDefinition, def *parser.Module) (errs []error) {
129
130 props := &ModuleTypeProperties{}
131
132 _, errs = proptools.UnpackProperties(def.Properties, props)
133 if len(errs) > 0 {
134 return errs
135 }
136
137 if props.Name == "" {
138 errs = append(errs, fmt.Errorf("name property must be set"))
139 }
140
141 if props.Config_namespace == "" {
142 errs = append(errs, fmt.Errorf("config_namespace property must be set"))
143 }
144
145 if props.Module_type == "" {
146 errs = append(errs, fmt.Errorf("module_type property must be set"))
147 }
148
149 if len(errs) > 0 {
150 return errs
151 }
152
Liz Kammer432bd592020-12-16 12:42:02 -0800153 if mt, errs := newModuleType(props); len(errs) > 0 {
154 return errs
155 } else {
156 v.ModuleTypes[props.Name] = mt
Dan Willemsenb0935db2020-03-23 19:42:18 -0700157 }
158
Colin Cross9d34f352019-11-22 16:03:51 -0800159 return nil
160}
161
162type VariableProperties struct {
163 Name string
164}
165
166type StringVariableProperties struct {
167 Values []string
168}
169
170func processStringVariableDef(v *SoongConfigDefinition, def *parser.Module) (errs []error) {
171 stringProps := &StringVariableProperties{}
172
173 base, errs := processVariableDef(def, stringProps)
174 if len(errs) > 0 {
175 return errs
176 }
177
178 if len(stringProps.Values) == 0 {
179 return []error{fmt.Errorf("values property must be set")}
180 }
181
Liz Kammer432bd592020-12-16 12:42:02 -0800182 for _, name := range stringProps.Values {
183 if err := checkVariableName(name); err != nil {
184 return []error{fmt.Errorf("soong_config_string_variable: values property error %s", err)}
185 }
186 }
187
Colin Cross9d34f352019-11-22 16:03:51 -0800188 v.variables[base.variable] = &stringVariable{
189 baseVariable: base,
190 values: CanonicalizeToProperties(stringProps.Values),
191 }
192
193 return nil
194}
195
196func processBoolVariableDef(v *SoongConfigDefinition, def *parser.Module) (errs []error) {
197 base, errs := processVariableDef(def)
198 if len(errs) > 0 {
199 return errs
200 }
201
202 v.variables[base.variable] = &boolVariable{
203 baseVariable: base,
204 }
205
206 return nil
207}
208
209func processVariableDef(def *parser.Module,
210 extraProps ...interface{}) (cond baseVariable, errs []error) {
211
212 props := &VariableProperties{}
213
214 allProps := append([]interface{}{props}, extraProps...)
215
216 _, errs = proptools.UnpackProperties(def.Properties, allProps...)
217 if len(errs) > 0 {
218 return baseVariable{}, errs
219 }
220
221 if props.Name == "" {
222 return baseVariable{}, []error{fmt.Errorf("name property must be set")}
223 }
224
225 return baseVariable{
226 variable: props.Name,
227 }, nil
228}
229
230type SoongConfigDefinition struct {
231 ModuleTypes map[string]*ModuleType
232
233 variables map[string]soongConfigVariable
234}
235
236// CreateProperties returns a reflect.Value of a newly constructed type that contains the desired
237// property layout for the Soong config variables, with each possible value an interface{} that
238// contains a nil pointer to another newly constructed type that contains the affectable properties.
239// The reflect.Value will be cloned for each call to the Soong config module type's factory method.
240//
241// For example, the acme_cc_defaults example above would
242// produce a reflect.Value whose type is:
243// *struct {
244// Soong_config_variables struct {
245// Board struct {
246// Soc_a interface{}
247// Soc_b interface{}
248// }
249// }
250// }
251// And whose value is:
252// &{
253// Soong_config_variables: {
254// Board: {
255// Soc_a: (*struct{ Cflags []string })(nil),
256// Soc_b: (*struct{ Cflags []string })(nil),
257// },
258// },
259// }
260func CreateProperties(factory blueprint.ModuleFactory, moduleType *ModuleType) reflect.Value {
261 var fields []reflect.StructField
262
263 _, factoryProps := factory()
264 affectablePropertiesType := createAffectablePropertiesType(moduleType.affectableProperties, factoryProps)
265 if affectablePropertiesType == nil {
266 return reflect.Value{}
267 }
268
269 for _, c := range moduleType.Variables {
270 fields = append(fields, reflect.StructField{
271 Name: proptools.FieldNameForProperty(c.variableProperty()),
272 Type: c.variableValuesType(),
273 })
274 }
275
276 typ := reflect.StructOf([]reflect.StructField{{
Jingwen Chena47f28d2021-11-02 16:43:57 +0000277 Name: SoongConfigProperty,
Colin Cross9d34f352019-11-22 16:03:51 -0800278 Type: reflect.StructOf(fields),
279 }})
280
281 props := reflect.New(typ)
Jingwen Chena47f28d2021-11-02 16:43:57 +0000282 structConditions := props.Elem().FieldByName(SoongConfigProperty)
Colin Cross9d34f352019-11-22 16:03:51 -0800283
284 for i, c := range moduleType.Variables {
285 c.initializeProperties(structConditions.Field(i), affectablePropertiesType)
286 }
287
288 return props
289}
290
291// createAffectablePropertiesType creates a reflect.Type of a struct that has a field for each affectable property
292// that exists in factoryProps.
293func createAffectablePropertiesType(affectableProperties []string, factoryProps []interface{}) reflect.Type {
294 affectableProperties = append([]string(nil), affectableProperties...)
295 sort.Strings(affectableProperties)
296
297 var recurse func(prefix string, aps []string) ([]string, reflect.Type)
298 recurse = func(prefix string, aps []string) ([]string, reflect.Type) {
299 var fields []reflect.StructField
300
Colin Cross997f27a2021-03-05 17:25:41 -0800301 // Iterate while the list is non-empty so it can be modified in the loop.
Colin Cross9d34f352019-11-22 16:03:51 -0800302 for len(affectableProperties) > 0 {
303 p := affectableProperties[0]
304 if !strings.HasPrefix(affectableProperties[0], prefix) {
Colin Cross997f27a2021-03-05 17:25:41 -0800305 // The properties are sorted and recurse is always called with a prefix that matches
306 // the first property in the list, so if we've reached one that doesn't match the
307 // prefix we are done with this prefix.
Colin Cross9d34f352019-11-22 16:03:51 -0800308 break
309 }
Colin Cross9d34f352019-11-22 16:03:51 -0800310
311 nestedProperty := strings.TrimPrefix(p, prefix)
312 if i := strings.IndexRune(nestedProperty, '.'); i >= 0 {
313 var nestedType reflect.Type
314 nestedPrefix := nestedProperty[:i+1]
315
Colin Cross997f27a2021-03-05 17:25:41 -0800316 // Recurse to handle the properties with the found prefix. This will return
317 // an updated affectableProperties with the handled entries removed from the front
318 // of the list, and the type that contains the handled entries. The type may be
319 // nil if none of the entries matched factoryProps.
Colin Cross9d34f352019-11-22 16:03:51 -0800320 affectableProperties, nestedType = recurse(prefix+nestedPrefix, affectableProperties)
321
322 if nestedType != nil {
323 nestedFieldName := proptools.FieldNameForProperty(strings.TrimSuffix(nestedPrefix, "."))
324
325 fields = append(fields, reflect.StructField{
326 Name: nestedFieldName,
327 Type: nestedType,
328 })
329 }
330 } else {
331 typ := typeForPropertyFromPropertyStructs(factoryProps, p)
332 if typ != nil {
333 fields = append(fields, reflect.StructField{
334 Name: proptools.FieldNameForProperty(nestedProperty),
335 Type: typ,
336 })
337 }
Colin Cross997f27a2021-03-05 17:25:41 -0800338 // The first element in the list has been handled, remove it from the list.
339 affectableProperties = affectableProperties[1:]
Colin Cross9d34f352019-11-22 16:03:51 -0800340 }
341 }
342
343 var typ reflect.Type
344 if len(fields) > 0 {
345 typ = reflect.StructOf(fields)
346 }
347 return affectableProperties, typ
348 }
349
350 affectableProperties, typ := recurse("", affectableProperties)
351 if len(affectableProperties) > 0 {
352 panic(fmt.Errorf("didn't handle all affectable properties"))
353 }
354
355 if typ != nil {
356 return reflect.PtrTo(typ)
357 }
358
359 return nil
360}
361
362func typeForPropertyFromPropertyStructs(psList []interface{}, property string) reflect.Type {
363 for _, ps := range psList {
364 if typ := typeForPropertyFromPropertyStruct(ps, property); typ != nil {
365 return typ
366 }
367 }
368
369 return nil
370}
371
372func typeForPropertyFromPropertyStruct(ps interface{}, property string) reflect.Type {
373 v := reflect.ValueOf(ps)
374 for len(property) > 0 {
375 if !v.IsValid() {
376 return nil
377 }
378
379 if v.Kind() == reflect.Interface {
380 if v.IsNil() {
381 return nil
382 } else {
383 v = v.Elem()
384 }
385 }
386
387 if v.Kind() == reflect.Ptr {
388 if v.IsNil() {
389 v = reflect.Zero(v.Type().Elem())
390 } else {
391 v = v.Elem()
392 }
393 }
394
395 if v.Kind() != reflect.Struct {
396 return nil
397 }
398
399 if index := strings.IndexRune(property, '.'); index >= 0 {
400 prefix := property[:index]
401 property = property[index+1:]
402
403 v = v.FieldByName(proptools.FieldNameForProperty(prefix))
404 } else {
405 f := v.FieldByName(proptools.FieldNameForProperty(property))
406 if !f.IsValid() {
407 return nil
408 }
409 return f.Type()
410 }
411 }
412 return nil
413}
414
415// PropertiesToApply returns the applicable properties from a ModuleType that should be applied
416// based on SoongConfig values.
Liz Kammerfe8853d2020-12-16 09:34:33 -0800417// Expects that props contains a struct field with name soong_config_variables. The fields within
Liz Kammer432bd592020-12-16 12:42:02 -0800418// soong_config_variables are expected to be in the same order as moduleType.Variables.
Dan Willemsenb0935db2020-03-23 19:42:18 -0700419func PropertiesToApply(moduleType *ModuleType, props reflect.Value, config SoongConfig) ([]interface{}, error) {
Colin Cross9d34f352019-11-22 16:03:51 -0800420 var ret []interface{}
Jingwen Chena47f28d2021-11-02 16:43:57 +0000421 props = props.Elem().FieldByName(SoongConfigProperty)
Colin Cross9d34f352019-11-22 16:03:51 -0800422 for i, c := range moduleType.Variables {
Dan Willemsenb0935db2020-03-23 19:42:18 -0700423 if ps, err := c.PropertiesToApply(config, props.Field(i)); err != nil {
424 return nil, err
425 } else if ps != nil {
Colin Cross9d34f352019-11-22 16:03:51 -0800426 ret = append(ret, ps)
427 }
428 }
Dan Willemsenb0935db2020-03-23 19:42:18 -0700429 return ret, nil
Colin Cross9d34f352019-11-22 16:03:51 -0800430}
431
432type ModuleType struct {
433 BaseModuleType string
434 ConfigNamespace string
435 Variables []soongConfigVariable
436
437 affectableProperties []string
438 variableNames []string
Jingwen Chena47f28d2021-11-02 16:43:57 +0000439 Bp2buildAvailable *bool
Colin Cross9d34f352019-11-22 16:03:51 -0800440}
441
Liz Kammer432bd592020-12-16 12:42:02 -0800442func newModuleType(props *ModuleTypeProperties) (*ModuleType, []error) {
443 mt := &ModuleType{
444 affectableProperties: props.Properties,
445 ConfigNamespace: props.Config_namespace,
446 BaseModuleType: props.Module_type,
447 variableNames: props.Variables,
Jingwen Chena47f28d2021-11-02 16:43:57 +0000448 Bp2buildAvailable: props.Bazel_module.Bp2build_available,
Liz Kammer432bd592020-12-16 12:42:02 -0800449 }
450
451 for _, name := range props.Bool_variables {
452 if err := checkVariableName(name); err != nil {
453 return nil, []error{fmt.Errorf("bool_variables %s", err)}
454 }
455
456 mt.Variables = append(mt.Variables, newBoolVariable(name))
457 }
458
459 for _, name := range props.Value_variables {
460 if err := checkVariableName(name); err != nil {
461 return nil, []error{fmt.Errorf("value_variables %s", err)}
462 }
463
464 mt.Variables = append(mt.Variables, &valueVariable{
465 baseVariable: baseVariable{
466 variable: name,
467 },
468 })
469 }
470
471 return mt, nil
472}
473
474func checkVariableName(name string) error {
475 if name == "" {
476 return fmt.Errorf("name must not be blank")
477 } else if name == conditionsDefault {
478 return fmt.Errorf("%q is reserved", conditionsDefault)
479 }
480 return nil
481}
482
Colin Cross9d34f352019-11-22 16:03:51 -0800483type soongConfigVariable interface {
484 // variableProperty returns the name of the variable.
485 variableProperty() string
486
487 // conditionalValuesType returns a reflect.Type that contains an interface{} for each possible value.
488 variableValuesType() reflect.Type
489
490 // initializeProperties is passed a reflect.Value of the reflect.Type returned by conditionalValuesType and a
491 // reflect.Type of the affectable properties, and should initialize each interface{} in the reflect.Value with
492 // the zero value of the affectable properties type.
493 initializeProperties(v reflect.Value, typ reflect.Type)
494
495 // PropertiesToApply should return one of the interface{} values set by initializeProperties to be applied
496 // to the module.
Dan Willemsenb0935db2020-03-23 19:42:18 -0700497 PropertiesToApply(config SoongConfig, values reflect.Value) (interface{}, error)
Colin Cross9d34f352019-11-22 16:03:51 -0800498}
499
500type baseVariable struct {
501 variable string
502}
503
504func (c *baseVariable) variableProperty() string {
505 return CanonicalizeToProperty(c.variable)
506}
507
508type stringVariable struct {
509 baseVariable
510 values []string
511}
512
513func (s *stringVariable) variableValuesType() reflect.Type {
514 var fields []reflect.StructField
515
Liz Kammer432bd592020-12-16 12:42:02 -0800516 var values []string
517 values = append(values, s.values...)
518 values = append(values, conditionsDefault)
519 for _, v := range values {
Colin Cross9d34f352019-11-22 16:03:51 -0800520 fields = append(fields, reflect.StructField{
521 Name: proptools.FieldNameForProperty(v),
522 Type: emptyInterfaceType,
523 })
524 }
525
526 return reflect.StructOf(fields)
527}
528
Liz Kammer432bd592020-12-16 12:42:02 -0800529// initializeProperties initializes properties to zero value of typ for supported values and a final
530// conditions default field.
Colin Cross9d34f352019-11-22 16:03:51 -0800531func (s *stringVariable) initializeProperties(v reflect.Value, typ reflect.Type) {
532 for i := range s.values {
533 v.Field(i).Set(reflect.Zero(typ))
534 }
Liz Kammer432bd592020-12-16 12:42:02 -0800535 v.Field(len(s.values)).Set(reflect.Zero(typ)) // conditions default is the final value
Colin Cross9d34f352019-11-22 16:03:51 -0800536}
537
Liz Kammer432bd592020-12-16 12:42:02 -0800538// Extracts an interface from values containing the properties to apply based on config.
539// If config does not match a value with a non-nil property set, the default value will be returned.
Dan Willemsenb0935db2020-03-23 19:42:18 -0700540func (s *stringVariable) PropertiesToApply(config SoongConfig, values reflect.Value) (interface{}, error) {
Colin Cross9d34f352019-11-22 16:03:51 -0800541 for j, v := range s.values {
Liz Kammer432bd592020-12-16 12:42:02 -0800542 f := values.Field(j)
543 if config.String(s.variable) == v && !f.Elem().IsNil() {
544 return f.Interface(), nil
Colin Cross9d34f352019-11-22 16:03:51 -0800545 }
546 }
Liz Kammer432bd592020-12-16 12:42:02 -0800547 // if we have reached this point, we have checked all valid values of string and either:
548 // * the value was not set
549 // * the value was set but that value was not specified in the Android.bp file
550 return values.Field(len(s.values)).Interface(), nil
Colin Cross9d34f352019-11-22 16:03:51 -0800551}
552
Liz Kammer432bd592020-12-16 12:42:02 -0800553// Struct to allow conditions set based on a boolean variable
Colin Cross9d34f352019-11-22 16:03:51 -0800554type boolVariable struct {
555 baseVariable
556}
557
Liz Kammer432bd592020-12-16 12:42:02 -0800558// newBoolVariable constructs a boolVariable with the given name
Liz Kammerfe8853d2020-12-16 09:34:33 -0800559func newBoolVariable(name string) *boolVariable {
560 return &boolVariable{
561 baseVariable{
562 variable: name,
563 },
564 }
565}
566
Colin Cross9d34f352019-11-22 16:03:51 -0800567func (b boolVariable) variableValuesType() reflect.Type {
568 return emptyInterfaceType
569}
570
Liz Kammer432bd592020-12-16 12:42:02 -0800571// initializeProperties initializes a property to zero value of typ with an additional conditions
572// default field.
Colin Cross9d34f352019-11-22 16:03:51 -0800573func (b boolVariable) initializeProperties(v reflect.Value, typ reflect.Type) {
Liz Kammer432bd592020-12-16 12:42:02 -0800574 initializePropertiesWithDefault(v, typ)
Colin Cross9d34f352019-11-22 16:03:51 -0800575}
576
Liz Kammer432bd592020-12-16 12:42:02 -0800577// initializePropertiesWithDefault, initialize with zero value, v to contain a field for each field
578// in typ, with an additional field for defaults of type typ. This should be used to initialize
579// boolVariable, valueVariable, or any future implementations of soongConfigVariable which support
580// one variable and a default.
581func initializePropertiesWithDefault(v reflect.Value, typ reflect.Type) {
582 sTyp := typ.Elem()
583 var fields []reflect.StructField
584 for i := 0; i < sTyp.NumField(); i++ {
585 fields = append(fields, sTyp.Field(i))
Colin Cross9d34f352019-11-22 16:03:51 -0800586 }
587
Liz Kammer432bd592020-12-16 12:42:02 -0800588 // create conditions_default field
589 nestedFieldName := proptools.FieldNameForProperty(conditionsDefault)
590 fields = append(fields, reflect.StructField{
591 Name: nestedFieldName,
592 Type: typ,
593 })
594
595 newTyp := reflect.PtrTo(reflect.StructOf(fields))
596 v.Set(reflect.Zero(newTyp))
597}
598
599// conditionsDefaultField extracts the conditions_default field from v. This is always the final
600// field if initialized with initializePropertiesWithDefault.
601func conditionsDefaultField(v reflect.Value) reflect.Value {
602 return v.Field(v.NumField() - 1)
603}
604
605// removeDefault removes the conditions_default field from values while retaining values from all
606// other fields. This allows
607func removeDefault(values reflect.Value) reflect.Value {
608 v := values.Elem().Elem()
609 s := conditionsDefaultField(v)
610 // if conditions_default field was not set, there will be no issues extending properties.
611 if !s.IsValid() {
612 return v
613 }
614
615 // If conditions_default field was set, it has the correct type for our property. Create a new
616 // reflect.Value of the conditions_default type and copy all fields (except for
617 // conditions_default) based on values to the result.
618 res := reflect.New(s.Type().Elem())
619 for i := 0; i < res.Type().Elem().NumField(); i++ {
620 val := v.Field(i)
621 res.Elem().Field(i).Set(val)
622 }
623
624 return res
625}
626
627// PropertiesToApply returns an interface{} value based on initializeProperties to be applied to
628// the module. If the value was not set, conditions_default interface will be returned; otherwise,
629// the interface in values, without conditions_default will be returned.
630func (b boolVariable) PropertiesToApply(config SoongConfig, values reflect.Value) (interface{}, error) {
631 // If this variable was not referenced in the module, there are no properties to apply.
632 if values.Elem().IsZero() {
633 return nil, nil
634 }
635 if config.Bool(b.variable) {
636 values = removeDefault(values)
637 return values.Interface(), nil
638 }
639 v := values.Elem().Elem()
640 if f := conditionsDefaultField(v); f.IsValid() {
641 return f.Interface(), nil
642 }
Dan Willemsenb0935db2020-03-23 19:42:18 -0700643 return nil, nil
644}
645
Liz Kammer432bd592020-12-16 12:42:02 -0800646// Struct to allow conditions set based on a value variable, supporting string substitution.
Dan Willemsenb0935db2020-03-23 19:42:18 -0700647type valueVariable struct {
648 baseVariable
649}
650
651func (s *valueVariable) variableValuesType() reflect.Type {
652 return emptyInterfaceType
653}
654
Liz Kammer432bd592020-12-16 12:42:02 -0800655// initializeProperties initializes a property to zero value of typ with an additional conditions
656// default field.
Dan Willemsenb0935db2020-03-23 19:42:18 -0700657func (s *valueVariable) initializeProperties(v reflect.Value, typ reflect.Type) {
Liz Kammer432bd592020-12-16 12:42:02 -0800658 initializePropertiesWithDefault(v, typ)
Dan Willemsenb0935db2020-03-23 19:42:18 -0700659}
660
Liz Kammer432bd592020-12-16 12:42:02 -0800661// PropertiesToApply returns an interface{} value based on initializeProperties to be applied to
662// the module. If the variable was not set, conditions_default interface will be returned;
663// otherwise, the interface in values, without conditions_default will be returned with all
664// appropriate string substitutions based on variable being set.
Dan Willemsenb0935db2020-03-23 19:42:18 -0700665func (s *valueVariable) PropertiesToApply(config SoongConfig, values reflect.Value) (interface{}, error) {
Liz Kammer432bd592020-12-16 12:42:02 -0800666 // If this variable was not referenced in the module, there are no properties to apply.
667 if !values.IsValid() || values.Elem().IsZero() {
Dan Willemsenb0935db2020-03-23 19:42:18 -0700668 return nil, nil
669 }
Liz Kammer432bd592020-12-16 12:42:02 -0800670 if !config.IsSet(s.variable) {
671 return conditionsDefaultField(values.Elem().Elem()).Interface(), nil
672 }
Dan Willemsenb0935db2020-03-23 19:42:18 -0700673 configValue := config.String(s.variable)
674
Liz Kammer432bd592020-12-16 12:42:02 -0800675 values = removeDefault(values)
676 propStruct := values.Elem()
Liz Kammer40ddfaa2020-12-16 10:59:00 -0800677 if !propStruct.IsValid() {
678 return nil, nil
679 }
Dan Willemsenb0935db2020-03-23 19:42:18 -0700680 for i := 0; i < propStruct.NumField(); i++ {
681 field := propStruct.Field(i)
682 kind := field.Kind()
683 if kind == reflect.Ptr {
684 if field.IsNil() {
685 continue
686 }
687 field = field.Elem()
688 }
689 switch kind {
690 case reflect.String:
691 err := printfIntoProperty(field, configValue)
692 if err != nil {
693 return nil, fmt.Errorf("soong_config_variables.%s.%s: %s", s.variable, propStruct.Type().Field(i).Name, err)
694 }
695 case reflect.Slice:
696 for j := 0; j < field.Len(); j++ {
697 err := printfIntoProperty(field.Index(j), configValue)
698 if err != nil {
699 return nil, fmt.Errorf("soong_config_variables.%s.%s: %s", s.variable, propStruct.Type().Field(i).Name, err)
700 }
701 }
702 case reflect.Bool:
703 // Nothing to do
704 default:
705 return nil, fmt.Errorf("soong_config_variables.%s.%s: unsupported property type %q", s.variable, propStruct.Type().Field(i).Name, kind)
706 }
707 }
708
709 return values.Interface(), nil
710}
711
712func printfIntoProperty(propertyValue reflect.Value, configValue string) error {
713 s := propertyValue.String()
714
715 count := strings.Count(s, "%")
716 if count == 0 {
717 return nil
718 }
719
720 if count > 1 {
721 return fmt.Errorf("value variable properties only support a single '%%'")
722 }
723
724 if !strings.Contains(s, "%s") {
725 return fmt.Errorf("unsupported %% in value variable property")
726 }
727
728 propertyValue.Set(reflect.ValueOf(fmt.Sprintf(s, configValue)))
729
Colin Cross9d34f352019-11-22 16:03:51 -0800730 return nil
731}
732
733func CanonicalizeToProperty(v string) string {
734 return strings.Map(func(r rune) rune {
735 switch {
736 case r >= 'A' && r <= 'Z',
737 r >= 'a' && r <= 'z',
738 r >= '0' && r <= '9',
739 r == '_':
740 return r
741 default:
742 return '_'
743 }
744 }, v)
745}
746
747func CanonicalizeToProperties(values []string) []string {
748 ret := make([]string, len(values))
749 for i, v := range values {
750 ret[i] = CanonicalizeToProperty(v)
751 }
752 return ret
753}
754
755type emptyInterfaceStruct struct {
756 i interface{}
757}
758
759var emptyInterfaceType = reflect.TypeOf(emptyInterfaceStruct{}).Field(0).Type