blob: ed4888d3d9908f99a54edfbc6f6101f66855594e [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 (
18 "fmt"
19 "io"
20 "reflect"
21 "sort"
22 "strings"
Jingwen Chen4ad40d92021-11-24 03:40:23 +000023 "sync"
Colin Cross9d34f352019-11-22 16:03:51 -080024
Colin Cross9d34f352019-11-22 16:03:51 -080025 "github.com/google/blueprint/parser"
26 "github.com/google/blueprint/proptools"
Liz Kammer72beb342022-02-03 08:42:10 -050027
28 "android/soong/starlark_fmt"
Colin Cross9d34f352019-11-22 16:03:51 -080029)
30
Liz Kammer432bd592020-12-16 12:42:02 -080031const conditionsDefault = "conditions_default"
32
Jingwen Chena47f28d2021-11-02 16:43:57 +000033var SoongConfigProperty = proptools.FieldNameForProperty("soong_config_variables")
Colin Cross9d34f352019-11-22 16:03:51 -080034
35// loadSoongConfigModuleTypeDefinition loads module types from an Android.bp file. It caches the
36// result so each file is only parsed once.
37func Parse(r io.Reader, from string) (*SoongConfigDefinition, []error) {
38 scope := parser.NewScope(nil)
39 file, errs := parser.ParseAndEval(from, r, scope)
40
41 if len(errs) > 0 {
42 return nil, errs
43 }
44
45 mtDef := &SoongConfigDefinition{
46 ModuleTypes: make(map[string]*ModuleType),
47 variables: make(map[string]soongConfigVariable),
48 }
49
50 for _, def := range file.Defs {
51 switch def := def.(type) {
52 case *parser.Module:
53 newErrs := processImportModuleDef(mtDef, def)
54
55 if len(newErrs) > 0 {
56 errs = append(errs, newErrs...)
57 }
58
59 case *parser.Assignment:
60 // Already handled via Scope object
61 default:
62 panic("unknown definition type")
63 }
64 }
65
66 if len(errs) > 0 {
67 return nil, errs
68 }
69
70 for name, moduleType := range mtDef.ModuleTypes {
71 for _, varName := range moduleType.variableNames {
72 if v, ok := mtDef.variables[varName]; ok {
73 moduleType.Variables = append(moduleType.Variables, v)
74 } else {
75 return nil, []error{
76 fmt.Errorf("unknown variable %q in module type %q", varName, name),
77 }
78 }
79 }
80 }
81
82 return mtDef, nil
83}
84
85func processImportModuleDef(v *SoongConfigDefinition, def *parser.Module) (errs []error) {
86 switch def.Type {
87 case "soong_config_module_type":
88 return processModuleTypeDef(v, def)
89 case "soong_config_string_variable":
90 return processStringVariableDef(v, def)
91 case "soong_config_bool_variable":
92 return processBoolVariableDef(v, def)
93 default:
94 // Unknown module types will be handled when the file is parsed as a normal
95 // Android.bp file.
96 }
97
98 return nil
99}
100
101type ModuleTypeProperties struct {
102 // the name of the new module type. Unlike most modules, this name does not need to be unique,
103 // although only one module type with any name will be importable into an Android.bp file.
104 Name string
105
106 // the module type that this module type will extend.
107 Module_type string
108
109 // the SOONG_CONFIG_NAMESPACE value from a BoardConfig.mk that this module type will read
110 // configuration variables from.
111 Config_namespace string
112
113 // the list of SOONG_CONFIG variables that this module type will read
114 Variables []string
115
Dan Willemsen2b8b89c2020-03-23 19:39:34 -0700116 // the list of boolean SOONG_CONFIG variables that this module type will read
117 Bool_variables []string
118
Dan Willemsenb0935db2020-03-23 19:42:18 -0700119 // the list of SOONG_CONFIG variables that this module type will read. The value will be
120 // inserted into the properties with %s substitution.
121 Value_variables []string
122
Colin Cross9d34f352019-11-22 16:03:51 -0800123 // the list of properties that this module type will extend.
124 Properties []string
125}
126
127func processModuleTypeDef(v *SoongConfigDefinition, def *parser.Module) (errs []error) {
128
129 props := &ModuleTypeProperties{}
130
131 _, errs = proptools.UnpackProperties(def.Properties, props)
132 if len(errs) > 0 {
133 return errs
134 }
135
136 if props.Name == "" {
137 errs = append(errs, fmt.Errorf("name property must be set"))
138 }
139
140 if props.Config_namespace == "" {
141 errs = append(errs, fmt.Errorf("config_namespace property must be set"))
142 }
143
144 if props.Module_type == "" {
145 errs = append(errs, fmt.Errorf("module_type property must be set"))
146 }
147
148 if len(errs) > 0 {
149 return errs
150 }
151
Liz Kammer432bd592020-12-16 12:42:02 -0800152 if mt, errs := newModuleType(props); len(errs) > 0 {
153 return errs
154 } else {
155 v.ModuleTypes[props.Name] = mt
Dan Willemsenb0935db2020-03-23 19:42:18 -0700156 }
157
Colin Cross9d34f352019-11-22 16:03:51 -0800158 return nil
159}
160
161type VariableProperties struct {
162 Name string
163}
164
165type StringVariableProperties struct {
166 Values []string
167}
168
169func processStringVariableDef(v *SoongConfigDefinition, def *parser.Module) (errs []error) {
170 stringProps := &StringVariableProperties{}
171
172 base, errs := processVariableDef(def, stringProps)
173 if len(errs) > 0 {
174 return errs
175 }
176
177 if len(stringProps.Values) == 0 {
178 return []error{fmt.Errorf("values property must be set")}
179 }
180
Liz Kammer72beb342022-02-03 08:42:10 -0500181 vals := make(map[string]bool, len(stringProps.Values))
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)}
Liz Kammer72beb342022-02-03 08:42:10 -0500185 } else if _, ok := vals[name]; ok {
186 return []error{fmt.Errorf("soong_config_string_variable: values property error: duplicate value: %q", name)}
Liz Kammer432bd592020-12-16 12:42:02 -0800187 }
Liz Kammer72beb342022-02-03 08:42:10 -0500188 vals[name] = true
Liz Kammer432bd592020-12-16 12:42:02 -0800189 }
190
Colin Cross9d34f352019-11-22 16:03:51 -0800191 v.variables[base.variable] = &stringVariable{
192 baseVariable: base,
193 values: CanonicalizeToProperties(stringProps.Values),
194 }
195
196 return nil
197}
198
199func processBoolVariableDef(v *SoongConfigDefinition, def *parser.Module) (errs []error) {
200 base, errs := processVariableDef(def)
201 if len(errs) > 0 {
202 return errs
203 }
204
205 v.variables[base.variable] = &boolVariable{
206 baseVariable: base,
207 }
208
209 return nil
210}
211
212func processVariableDef(def *parser.Module,
213 extraProps ...interface{}) (cond baseVariable, errs []error) {
214
215 props := &VariableProperties{}
216
217 allProps := append([]interface{}{props}, extraProps...)
218
219 _, errs = proptools.UnpackProperties(def.Properties, allProps...)
220 if len(errs) > 0 {
221 return baseVariable{}, errs
222 }
223
224 if props.Name == "" {
225 return baseVariable{}, []error{fmt.Errorf("name property must be set")}
226 }
227
228 return baseVariable{
229 variable: props.Name,
230 }, nil
231}
232
233type SoongConfigDefinition struct {
234 ModuleTypes map[string]*ModuleType
235
236 variables map[string]soongConfigVariable
237}
238
Jingwen Chen01812022021-11-19 14:29:43 +0000239// Bp2BuildSoongConfigDefinition keeps a global record of all soong config
240// string vars, bool vars and value vars created by every
241// soong_config_module_type in this build.
242type Bp2BuildSoongConfigDefinitions struct {
Liz Kammer72beb342022-02-03 08:42:10 -0500243 // varCache contains a cache of string variables namespace + property
244 // The same variable may be used in multiple module types (for example, if need support
245 // for cc_default and java_default), only need to process once
246 varCache map[string]bool
247
248 StringVars map[string][]string
Jingwen Chen01812022021-11-19 14:29:43 +0000249 BoolVars map[string]bool
250 ValueVars map[string]bool
251}
252
Jingwen Chen4ad40d92021-11-24 03:40:23 +0000253var bp2buildSoongConfigVarsLock sync.Mutex
254
Jingwen Chen01812022021-11-19 14:29:43 +0000255// SoongConfigVariablesForBp2build extracts information from a
256// SoongConfigDefinition that bp2build needs to generate constraint settings and
257// values for, in order to migrate soong_config_module_type usages to Bazel.
258func (defs *Bp2BuildSoongConfigDefinitions) AddVars(mtDef SoongConfigDefinition) {
Jingwen Chen4ad40d92021-11-24 03:40:23 +0000259 // In bp2build mode, this method is called concurrently in goroutines from
260 // loadhooks while parsing soong_config_module_type, so add a mutex to
261 // prevent concurrent map writes. See b/207572723
262 bp2buildSoongConfigVarsLock.Lock()
263 defer bp2buildSoongConfigVarsLock.Unlock()
264
Jingwen Chen01812022021-11-19 14:29:43 +0000265 if defs.StringVars == nil {
Liz Kammer72beb342022-02-03 08:42:10 -0500266 defs.StringVars = make(map[string][]string)
Jingwen Chen01812022021-11-19 14:29:43 +0000267 }
268 if defs.BoolVars == nil {
269 defs.BoolVars = make(map[string]bool)
270 }
271 if defs.ValueVars == nil {
272 defs.ValueVars = make(map[string]bool)
273 }
Liz Kammer72beb342022-02-03 08:42:10 -0500274 if defs.varCache == nil {
275 defs.varCache = make(map[string]bool)
276 }
Jingwen Chen01812022021-11-19 14:29:43 +0000277 for _, moduleType := range mtDef.ModuleTypes {
278 for _, v := range moduleType.Variables {
279 key := strings.Join([]string{moduleType.ConfigNamespace, v.variableProperty()}, "__")
Liz Kammer72beb342022-02-03 08:42:10 -0500280
281 // The same variable may be used in multiple module types (for example, if need support
282 // for cc_default and java_default), only need to process once
283 if _, keyInCache := defs.varCache[key]; keyInCache {
284 continue
285 } else {
286 defs.varCache[key] = true
287 }
288
Jingwen Chen01812022021-11-19 14:29:43 +0000289 if strVar, ok := v.(*stringVariable); ok {
Jingwen Chen01812022021-11-19 14:29:43 +0000290 for _, value := range strVar.values {
Liz Kammer72beb342022-02-03 08:42:10 -0500291 defs.StringVars[key] = append(defs.StringVars[key], value)
Jingwen Chen01812022021-11-19 14:29:43 +0000292 }
293 } else if _, ok := v.(*boolVariable); ok {
294 defs.BoolVars[key] = true
295 } else if _, ok := v.(*valueVariable); ok {
296 defs.ValueVars[key] = true
297 } else {
298 panic(fmt.Errorf("Unsupported variable type: %+v", v))
299 }
300 }
301 }
302}
303
304// This is a copy of the one available in soong/android/util.go, but depending
305// on the android package causes a cyclic dependency. A refactoring here is to
306// extract common utils out from android/utils.go for other packages like this.
307func sortedStringKeys(m interface{}) []string {
308 v := reflect.ValueOf(m)
309 if v.Kind() != reflect.Map {
310 panic(fmt.Sprintf("%#v is not a map", m))
311 }
312 keys := v.MapKeys()
313 s := make([]string, 0, len(keys))
314 for _, key := range keys {
315 s = append(s, key.String())
316 }
317 sort.Strings(s)
318 return s
319}
320
321// String emits the Soong config variable definitions as Starlark dictionaries.
322func (defs Bp2BuildSoongConfigDefinitions) String() string {
323 ret := ""
Liz Kammer72beb342022-02-03 08:42:10 -0500324 ret += "soong_config_bool_variables = "
325 ret += starlark_fmt.PrintBoolDict(defs.BoolVars, 0)
326 ret += "\n\n"
Jingwen Chen01812022021-11-19 14:29:43 +0000327
Liz Kammer72beb342022-02-03 08:42:10 -0500328 ret += "soong_config_value_variables = "
329 ret += starlark_fmt.PrintBoolDict(defs.ValueVars, 0)
330 ret += "\n\n"
Jingwen Chen01812022021-11-19 14:29:43 +0000331
Liz Kammer72beb342022-02-03 08:42:10 -0500332 ret += "soong_config_string_variables = "
333 ret += starlark_fmt.PrintStringListDict(defs.StringVars, 0)
Jingwen Chen01812022021-11-19 14:29:43 +0000334
335 return ret
336}
337
Colin Cross9d34f352019-11-22 16:03:51 -0800338// CreateProperties returns a reflect.Value of a newly constructed type that contains the desired
339// property layout for the Soong config variables, with each possible value an interface{} that
340// contains a nil pointer to another newly constructed type that contains the affectable properties.
341// The reflect.Value will be cloned for each call to the Soong config module type's factory method.
342//
343// For example, the acme_cc_defaults example above would
344// produce a reflect.Value whose type is:
Colin Crossd079e0b2022-08-16 10:27:33 -0700345//
346// *struct {
347// Soong_config_variables struct {
348// Board struct {
349// Soc_a interface{}
350// Soc_b interface{}
351// }
352// }
353// }
354//
Colin Cross9d34f352019-11-22 16:03:51 -0800355// And whose value is:
Colin Crossd079e0b2022-08-16 10:27:33 -0700356//
357// &{
358// Soong_config_variables: {
359// Board: {
360// Soc_a: (*struct{ Cflags []string })(nil),
361// Soc_b: (*struct{ Cflags []string })(nil),
362// },
363// },
364// }
Paul Duffine8b47682023-01-09 15:42:57 +0000365func CreateProperties(factoryProps []interface{}, moduleType *ModuleType) reflect.Value {
Colin Cross9d34f352019-11-22 16:03:51 -0800366 var fields []reflect.StructField
367
Colin Cross9d34f352019-11-22 16:03:51 -0800368 affectablePropertiesType := createAffectablePropertiesType(moduleType.affectableProperties, factoryProps)
369 if affectablePropertiesType == nil {
370 return reflect.Value{}
371 }
372
373 for _, c := range moduleType.Variables {
374 fields = append(fields, reflect.StructField{
375 Name: proptools.FieldNameForProperty(c.variableProperty()),
376 Type: c.variableValuesType(),
377 })
378 }
379
380 typ := reflect.StructOf([]reflect.StructField{{
Jingwen Chena47f28d2021-11-02 16:43:57 +0000381 Name: SoongConfigProperty,
Colin Cross9d34f352019-11-22 16:03:51 -0800382 Type: reflect.StructOf(fields),
383 }})
384
385 props := reflect.New(typ)
Jingwen Chena47f28d2021-11-02 16:43:57 +0000386 structConditions := props.Elem().FieldByName(SoongConfigProperty)
Colin Cross9d34f352019-11-22 16:03:51 -0800387
388 for i, c := range moduleType.Variables {
389 c.initializeProperties(structConditions.Field(i), affectablePropertiesType)
390 }
391
392 return props
393}
394
395// createAffectablePropertiesType creates a reflect.Type of a struct that has a field for each affectable property
396// that exists in factoryProps.
397func createAffectablePropertiesType(affectableProperties []string, factoryProps []interface{}) reflect.Type {
398 affectableProperties = append([]string(nil), affectableProperties...)
399 sort.Strings(affectableProperties)
400
401 var recurse func(prefix string, aps []string) ([]string, reflect.Type)
402 recurse = func(prefix string, aps []string) ([]string, reflect.Type) {
403 var fields []reflect.StructField
404
Colin Cross997f27a2021-03-05 17:25:41 -0800405 // Iterate while the list is non-empty so it can be modified in the loop.
Colin Cross9d34f352019-11-22 16:03:51 -0800406 for len(affectableProperties) > 0 {
407 p := affectableProperties[0]
408 if !strings.HasPrefix(affectableProperties[0], prefix) {
Colin Cross997f27a2021-03-05 17:25:41 -0800409 // The properties are sorted and recurse is always called with a prefix that matches
410 // the first property in the list, so if we've reached one that doesn't match the
411 // prefix we are done with this prefix.
Colin Cross9d34f352019-11-22 16:03:51 -0800412 break
413 }
Colin Cross9d34f352019-11-22 16:03:51 -0800414
415 nestedProperty := strings.TrimPrefix(p, prefix)
416 if i := strings.IndexRune(nestedProperty, '.'); i >= 0 {
417 var nestedType reflect.Type
418 nestedPrefix := nestedProperty[:i+1]
419
Colin Cross997f27a2021-03-05 17:25:41 -0800420 // Recurse to handle the properties with the found prefix. This will return
421 // an updated affectableProperties with the handled entries removed from the front
422 // of the list, and the type that contains the handled entries. The type may be
423 // nil if none of the entries matched factoryProps.
Colin Cross9d34f352019-11-22 16:03:51 -0800424 affectableProperties, nestedType = recurse(prefix+nestedPrefix, affectableProperties)
425
426 if nestedType != nil {
427 nestedFieldName := proptools.FieldNameForProperty(strings.TrimSuffix(nestedPrefix, "."))
428
429 fields = append(fields, reflect.StructField{
430 Name: nestedFieldName,
431 Type: nestedType,
432 })
433 }
434 } else {
435 typ := typeForPropertyFromPropertyStructs(factoryProps, p)
436 if typ != nil {
437 fields = append(fields, reflect.StructField{
438 Name: proptools.FieldNameForProperty(nestedProperty),
439 Type: typ,
440 })
441 }
Colin Cross997f27a2021-03-05 17:25:41 -0800442 // The first element in the list has been handled, remove it from the list.
443 affectableProperties = affectableProperties[1:]
Colin Cross9d34f352019-11-22 16:03:51 -0800444 }
445 }
446
447 var typ reflect.Type
448 if len(fields) > 0 {
449 typ = reflect.StructOf(fields)
450 }
451 return affectableProperties, typ
452 }
453
454 affectableProperties, typ := recurse("", affectableProperties)
455 if len(affectableProperties) > 0 {
456 panic(fmt.Errorf("didn't handle all affectable properties"))
457 }
458
459 if typ != nil {
460 return reflect.PtrTo(typ)
461 }
462
463 return nil
464}
465
466func typeForPropertyFromPropertyStructs(psList []interface{}, property string) reflect.Type {
467 for _, ps := range psList {
468 if typ := typeForPropertyFromPropertyStruct(ps, property); typ != nil {
469 return typ
470 }
471 }
472
473 return nil
474}
475
476func typeForPropertyFromPropertyStruct(ps interface{}, property string) reflect.Type {
477 v := reflect.ValueOf(ps)
478 for len(property) > 0 {
479 if !v.IsValid() {
480 return nil
481 }
482
483 if v.Kind() == reflect.Interface {
484 if v.IsNil() {
485 return nil
486 } else {
487 v = v.Elem()
488 }
489 }
490
491 if v.Kind() == reflect.Ptr {
492 if v.IsNil() {
493 v = reflect.Zero(v.Type().Elem())
494 } else {
495 v = v.Elem()
496 }
497 }
498
499 if v.Kind() != reflect.Struct {
500 return nil
501 }
502
503 if index := strings.IndexRune(property, '.'); index >= 0 {
504 prefix := property[:index]
505 property = property[index+1:]
506
507 v = v.FieldByName(proptools.FieldNameForProperty(prefix))
508 } else {
509 f := v.FieldByName(proptools.FieldNameForProperty(property))
510 if !f.IsValid() {
511 return nil
512 }
513 return f.Type()
514 }
515 }
516 return nil
517}
518
519// PropertiesToApply returns the applicable properties from a ModuleType that should be applied
520// based on SoongConfig values.
Liz Kammerfe8853d2020-12-16 09:34:33 -0800521// Expects that props contains a struct field with name soong_config_variables. The fields within
Liz Kammer432bd592020-12-16 12:42:02 -0800522// soong_config_variables are expected to be in the same order as moduleType.Variables.
Dan Willemsenb0935db2020-03-23 19:42:18 -0700523func PropertiesToApply(moduleType *ModuleType, props reflect.Value, config SoongConfig) ([]interface{}, error) {
Colin Cross9d34f352019-11-22 16:03:51 -0800524 var ret []interface{}
Jingwen Chena47f28d2021-11-02 16:43:57 +0000525 props = props.Elem().FieldByName(SoongConfigProperty)
Colin Cross9d34f352019-11-22 16:03:51 -0800526 for i, c := range moduleType.Variables {
Dan Willemsenb0935db2020-03-23 19:42:18 -0700527 if ps, err := c.PropertiesToApply(config, props.Field(i)); err != nil {
528 return nil, err
529 } else if ps != nil {
Colin Cross9d34f352019-11-22 16:03:51 -0800530 ret = append(ret, ps)
531 }
532 }
Dan Willemsenb0935db2020-03-23 19:42:18 -0700533 return ret, nil
Colin Cross9d34f352019-11-22 16:03:51 -0800534}
535
536type ModuleType struct {
537 BaseModuleType string
538 ConfigNamespace string
539 Variables []soongConfigVariable
540
541 affectableProperties []string
542 variableNames []string
543}
544
Liz Kammer432bd592020-12-16 12:42:02 -0800545func newModuleType(props *ModuleTypeProperties) (*ModuleType, []error) {
546 mt := &ModuleType{
547 affectableProperties: props.Properties,
548 ConfigNamespace: props.Config_namespace,
549 BaseModuleType: props.Module_type,
550 variableNames: props.Variables,
551 }
552
553 for _, name := range props.Bool_variables {
554 if err := checkVariableName(name); err != nil {
555 return nil, []error{fmt.Errorf("bool_variables %s", err)}
556 }
557
558 mt.Variables = append(mt.Variables, newBoolVariable(name))
559 }
560
561 for _, name := range props.Value_variables {
562 if err := checkVariableName(name); err != nil {
563 return nil, []error{fmt.Errorf("value_variables %s", err)}
564 }
565
566 mt.Variables = append(mt.Variables, &valueVariable{
567 baseVariable: baseVariable{
568 variable: name,
569 },
570 })
571 }
572
573 return mt, nil
574}
575
576func checkVariableName(name string) error {
577 if name == "" {
578 return fmt.Errorf("name must not be blank")
579 } else if name == conditionsDefault {
580 return fmt.Errorf("%q is reserved", conditionsDefault)
581 }
582 return nil
583}
584
Colin Cross9d34f352019-11-22 16:03:51 -0800585type soongConfigVariable interface {
586 // variableProperty returns the name of the variable.
587 variableProperty() string
588
589 // conditionalValuesType returns a reflect.Type that contains an interface{} for each possible value.
590 variableValuesType() reflect.Type
591
592 // initializeProperties is passed a reflect.Value of the reflect.Type returned by conditionalValuesType and a
593 // reflect.Type of the affectable properties, and should initialize each interface{} in the reflect.Value with
594 // the zero value of the affectable properties type.
595 initializeProperties(v reflect.Value, typ reflect.Type)
596
597 // PropertiesToApply should return one of the interface{} values set by initializeProperties to be applied
598 // to the module.
Dan Willemsenb0935db2020-03-23 19:42:18 -0700599 PropertiesToApply(config SoongConfig, values reflect.Value) (interface{}, error)
Colin Cross9d34f352019-11-22 16:03:51 -0800600}
601
602type baseVariable struct {
603 variable string
604}
605
606func (c *baseVariable) variableProperty() string {
607 return CanonicalizeToProperty(c.variable)
608}
609
610type stringVariable struct {
611 baseVariable
612 values []string
613}
614
615func (s *stringVariable) variableValuesType() reflect.Type {
616 var fields []reflect.StructField
617
Liz Kammer432bd592020-12-16 12:42:02 -0800618 var values []string
619 values = append(values, s.values...)
620 values = append(values, conditionsDefault)
621 for _, v := range values {
Colin Cross9d34f352019-11-22 16:03:51 -0800622 fields = append(fields, reflect.StructField{
623 Name: proptools.FieldNameForProperty(v),
624 Type: emptyInterfaceType,
625 })
626 }
627
628 return reflect.StructOf(fields)
629}
630
Liz Kammer432bd592020-12-16 12:42:02 -0800631// initializeProperties initializes properties to zero value of typ for supported values and a final
632// conditions default field.
Colin Cross9d34f352019-11-22 16:03:51 -0800633func (s *stringVariable) initializeProperties(v reflect.Value, typ reflect.Type) {
634 for i := range s.values {
635 v.Field(i).Set(reflect.Zero(typ))
636 }
Liz Kammer432bd592020-12-16 12:42:02 -0800637 v.Field(len(s.values)).Set(reflect.Zero(typ)) // conditions default is the final value
Colin Cross9d34f352019-11-22 16:03:51 -0800638}
639
Liz Kammer432bd592020-12-16 12:42:02 -0800640// Extracts an interface from values containing the properties to apply based on config.
641// 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 -0700642func (s *stringVariable) PropertiesToApply(config SoongConfig, values reflect.Value) (interface{}, error) {
Cole Faustb0a91332022-11-01 17:10:23 +0000643 configValue := config.String(s.variable)
644 if configValue != "" && !InList(configValue, s.values) {
645 return nil, fmt.Errorf("Soong config property %q must be one of %v, found %q", s.variable, s.values, configValue)
646 }
Colin Cross9d34f352019-11-22 16:03:51 -0800647 for j, v := range s.values {
Liz Kammer432bd592020-12-16 12:42:02 -0800648 f := values.Field(j)
Cole Faustb0a91332022-11-01 17:10:23 +0000649 if configValue == v && !f.Elem().IsNil() {
Liz Kammer432bd592020-12-16 12:42:02 -0800650 return f.Interface(), nil
Colin Cross9d34f352019-11-22 16:03:51 -0800651 }
652 }
Liz Kammer432bd592020-12-16 12:42:02 -0800653 // if we have reached this point, we have checked all valid values of string and either:
654 // * the value was not set
655 // * the value was set but that value was not specified in the Android.bp file
656 return values.Field(len(s.values)).Interface(), nil
Colin Cross9d34f352019-11-22 16:03:51 -0800657}
658
Liz Kammer432bd592020-12-16 12:42:02 -0800659// Struct to allow conditions set based on a boolean variable
Colin Cross9d34f352019-11-22 16:03:51 -0800660type boolVariable struct {
661 baseVariable
662}
663
Liz Kammer432bd592020-12-16 12:42:02 -0800664// newBoolVariable constructs a boolVariable with the given name
Liz Kammerfe8853d2020-12-16 09:34:33 -0800665func newBoolVariable(name string) *boolVariable {
666 return &boolVariable{
667 baseVariable{
668 variable: name,
669 },
670 }
671}
672
Colin Cross9d34f352019-11-22 16:03:51 -0800673func (b boolVariable) variableValuesType() reflect.Type {
674 return emptyInterfaceType
675}
676
Liz Kammer432bd592020-12-16 12:42:02 -0800677// initializeProperties initializes a property to zero value of typ with an additional conditions
678// default field.
Colin Cross9d34f352019-11-22 16:03:51 -0800679func (b boolVariable) initializeProperties(v reflect.Value, typ reflect.Type) {
Liz Kammer432bd592020-12-16 12:42:02 -0800680 initializePropertiesWithDefault(v, typ)
Colin Cross9d34f352019-11-22 16:03:51 -0800681}
682
Liz Kammer432bd592020-12-16 12:42:02 -0800683// initializePropertiesWithDefault, initialize with zero value, v to contain a field for each field
684// in typ, with an additional field for defaults of type typ. This should be used to initialize
685// boolVariable, valueVariable, or any future implementations of soongConfigVariable which support
686// one variable and a default.
687func initializePropertiesWithDefault(v reflect.Value, typ reflect.Type) {
688 sTyp := typ.Elem()
689 var fields []reflect.StructField
690 for i := 0; i < sTyp.NumField(); i++ {
691 fields = append(fields, sTyp.Field(i))
Colin Cross9d34f352019-11-22 16:03:51 -0800692 }
693
Liz Kammer432bd592020-12-16 12:42:02 -0800694 // create conditions_default field
695 nestedFieldName := proptools.FieldNameForProperty(conditionsDefault)
696 fields = append(fields, reflect.StructField{
697 Name: nestedFieldName,
698 Type: typ,
699 })
700
701 newTyp := reflect.PtrTo(reflect.StructOf(fields))
702 v.Set(reflect.Zero(newTyp))
703}
704
705// conditionsDefaultField extracts the conditions_default field from v. This is always the final
706// field if initialized with initializePropertiesWithDefault.
707func conditionsDefaultField(v reflect.Value) reflect.Value {
708 return v.Field(v.NumField() - 1)
709}
710
711// removeDefault removes the conditions_default field from values while retaining values from all
712// other fields. This allows
713func removeDefault(values reflect.Value) reflect.Value {
714 v := values.Elem().Elem()
715 s := conditionsDefaultField(v)
716 // if conditions_default field was not set, there will be no issues extending properties.
717 if !s.IsValid() {
718 return v
719 }
720
721 // If conditions_default field was set, it has the correct type for our property. Create a new
722 // reflect.Value of the conditions_default type and copy all fields (except for
723 // conditions_default) based on values to the result.
724 res := reflect.New(s.Type().Elem())
725 for i := 0; i < res.Type().Elem().NumField(); i++ {
726 val := v.Field(i)
727 res.Elem().Field(i).Set(val)
728 }
729
730 return res
731}
732
733// PropertiesToApply returns an interface{} value based on initializeProperties to be applied to
734// the module. If the value was not set, conditions_default interface will be returned; otherwise,
735// the interface in values, without conditions_default will be returned.
736func (b boolVariable) PropertiesToApply(config SoongConfig, values reflect.Value) (interface{}, error) {
737 // If this variable was not referenced in the module, there are no properties to apply.
738 if values.Elem().IsZero() {
739 return nil, nil
740 }
741 if config.Bool(b.variable) {
742 values = removeDefault(values)
743 return values.Interface(), nil
744 }
745 v := values.Elem().Elem()
746 if f := conditionsDefaultField(v); f.IsValid() {
747 return f.Interface(), nil
748 }
Dan Willemsenb0935db2020-03-23 19:42:18 -0700749 return nil, nil
750}
751
Liz Kammer432bd592020-12-16 12:42:02 -0800752// Struct to allow conditions set based on a value variable, supporting string substitution.
Dan Willemsenb0935db2020-03-23 19:42:18 -0700753type valueVariable struct {
754 baseVariable
755}
756
757func (s *valueVariable) variableValuesType() reflect.Type {
758 return emptyInterfaceType
759}
760
Liz Kammer432bd592020-12-16 12:42:02 -0800761// initializeProperties initializes a property to zero value of typ with an additional conditions
762// default field.
Dan Willemsenb0935db2020-03-23 19:42:18 -0700763func (s *valueVariable) initializeProperties(v reflect.Value, typ reflect.Type) {
Liz Kammer432bd592020-12-16 12:42:02 -0800764 initializePropertiesWithDefault(v, typ)
Dan Willemsenb0935db2020-03-23 19:42:18 -0700765}
766
Liz Kammer432bd592020-12-16 12:42:02 -0800767// PropertiesToApply returns an interface{} value based on initializeProperties to be applied to
768// the module. If the variable was not set, conditions_default interface will be returned;
769// otherwise, the interface in values, without conditions_default will be returned with all
770// appropriate string substitutions based on variable being set.
Dan Willemsenb0935db2020-03-23 19:42:18 -0700771func (s *valueVariable) PropertiesToApply(config SoongConfig, values reflect.Value) (interface{}, error) {
Liz Kammer432bd592020-12-16 12:42:02 -0800772 // If this variable was not referenced in the module, there are no properties to apply.
773 if !values.IsValid() || values.Elem().IsZero() {
Dan Willemsenb0935db2020-03-23 19:42:18 -0700774 return nil, nil
775 }
Liz Kammer432bd592020-12-16 12:42:02 -0800776 if !config.IsSet(s.variable) {
777 return conditionsDefaultField(values.Elem().Elem()).Interface(), nil
778 }
Dan Willemsenb0935db2020-03-23 19:42:18 -0700779 configValue := config.String(s.variable)
780
Liz Kammer432bd592020-12-16 12:42:02 -0800781 values = removeDefault(values)
782 propStruct := values.Elem()
Liz Kammer40ddfaa2020-12-16 10:59:00 -0800783 if !propStruct.IsValid() {
784 return nil, nil
785 }
Dan Willemsenb0935db2020-03-23 19:42:18 -0700786 for i := 0; i < propStruct.NumField(); i++ {
787 field := propStruct.Field(i)
788 kind := field.Kind()
789 if kind == reflect.Ptr {
790 if field.IsNil() {
791 continue
792 }
793 field = field.Elem()
794 }
795 switch kind {
796 case reflect.String:
797 err := printfIntoProperty(field, configValue)
798 if err != nil {
799 return nil, fmt.Errorf("soong_config_variables.%s.%s: %s", s.variable, propStruct.Type().Field(i).Name, err)
800 }
801 case reflect.Slice:
802 for j := 0; j < field.Len(); j++ {
803 err := printfIntoProperty(field.Index(j), configValue)
804 if err != nil {
805 return nil, fmt.Errorf("soong_config_variables.%s.%s: %s", s.variable, propStruct.Type().Field(i).Name, err)
806 }
807 }
808 case reflect.Bool:
809 // Nothing to do
810 default:
811 return nil, fmt.Errorf("soong_config_variables.%s.%s: unsupported property type %q", s.variable, propStruct.Type().Field(i).Name, kind)
812 }
813 }
814
815 return values.Interface(), nil
816}
817
818func printfIntoProperty(propertyValue reflect.Value, configValue string) error {
819 s := propertyValue.String()
820
821 count := strings.Count(s, "%")
822 if count == 0 {
823 return nil
824 }
825
826 if count > 1 {
827 return fmt.Errorf("value variable properties only support a single '%%'")
828 }
829
830 if !strings.Contains(s, "%s") {
831 return fmt.Errorf("unsupported %% in value variable property")
832 }
833
834 propertyValue.Set(reflect.ValueOf(fmt.Sprintf(s, configValue)))
835
Colin Cross9d34f352019-11-22 16:03:51 -0800836 return nil
837}
838
839func CanonicalizeToProperty(v string) string {
840 return strings.Map(func(r rune) rune {
841 switch {
842 case r >= 'A' && r <= 'Z',
843 r >= 'a' && r <= 'z',
844 r >= '0' && r <= '9',
845 r == '_':
846 return r
847 default:
848 return '_'
849 }
850 }, v)
851}
852
853func CanonicalizeToProperties(values []string) []string {
854 ret := make([]string, len(values))
855 for i, v := range values {
856 ret[i] = CanonicalizeToProperty(v)
857 }
858 return ret
859}
860
861type emptyInterfaceStruct struct {
862 i interface{}
863}
864
865var emptyInterfaceType = reflect.TypeOf(emptyInterfaceStruct{}).Field(0).Type
Cole Faustb0a91332022-11-01 17:10:23 +0000866
867// InList checks if the string belongs to the list
868func InList(s string, list []string) bool {
869 for _, s2 := range list {
870 if s2 == s {
871 return true
872 }
873 }
874 return false
875}