blob: d82fa6417e0904d8d92140ec7413a3361ae4a1f3 [file] [log] [blame]
Jingwen Chen30f5aaa2020-11-19 05:38:02 -05001// 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 bazel
16
Rupert Shuttleworth2e4219b2021-03-12 11:04:21 +000017import (
18 "fmt"
Jingwen Chen63930982021-03-24 10:04:33 -040019 "path/filepath"
Liz Kammera060c452021-03-24 10:14:47 -040020 "regexp"
Rupert Shuttleworth2e4219b2021-03-12 11:04:21 +000021 "sort"
Liz Kammer57e2e7a2021-09-20 12:55:02 -040022 "strings"
23
24 "github.com/google/blueprint"
Rupert Shuttleworth2e4219b2021-03-12 11:04:21 +000025)
Jingwen Chen5d864492021-02-24 07:20:12 -050026
Jingwen Chen73850672020-12-14 08:25:34 -050027// BazelTargetModuleProperties contain properties and metadata used for
28// Blueprint to BUILD file conversion.
29type BazelTargetModuleProperties struct {
30 // The Bazel rule class for this target.
Liz Kammerfc46bc12021-02-19 11:06:17 -050031 Rule_class string `blueprint:"mutated"`
Jingwen Chen40067de2021-01-26 21:58:43 -050032
33 // The target label for the bzl file containing the definition of the rule class.
Liz Kammerfc46bc12021-02-19 11:06:17 -050034 Bzl_load_location string `blueprint:"mutated"`
Jingwen Chen73850672020-12-14 08:25:34 -050035}
Liz Kammer356f7d42021-01-26 09:18:53 -050036
Liz Kammera060c452021-03-24 10:14:47 -040037var productVariableSubstitutionPattern = regexp.MustCompile("%(d|s)")
38
Jingwen Chen38e62642021-04-19 05:00:15 +000039// Label is used to represent a Bazel compatible Label. Also stores the original
40// bp text to support string replacement.
Liz Kammer356f7d42021-01-26 09:18:53 -050041type Label struct {
Jingwen Chen38e62642021-04-19 05:00:15 +000042 // The string representation of a Bazel target label. This can be a relative
43 // or fully qualified label. These labels are used for generating BUILD
44 // files with bp2build.
45 Label string
46
47 // The original Soong/Blueprint module name that the label was derived from.
48 // This is used for replacing references to the original name with the new
49 // label, for example in genrule cmds.
50 //
51 // While there is a reversible 1:1 mapping from the module name to Bazel
52 // label with bp2build that could make computing the original module name
53 // from the label automatic, it is not the case for handcrafted targets,
54 // where modules can have a custom label mapping through the { bazel_module:
55 // { label: <label> } } property.
56 //
57 // With handcrafted labels, those modules don't go through bp2build
58 // conversion, but relies on handcrafted targets in the source tree.
59 OriginalModuleName string
Liz Kammer356f7d42021-01-26 09:18:53 -050060}
61
62// LabelList is used to represent a list of Bazel labels.
63type LabelList struct {
64 Includes []Label
65 Excludes []Label
66}
67
Sam Delmericoc0161432022-02-25 21:34:51 +000068// MakeLabelList creates a LabelList from a list Label
69func MakeLabelList(labels []Label) LabelList {
70 return LabelList{
71 Includes: labels,
72 Excludes: nil,
73 }
74}
75
Chris Parsons51f8c392021-08-03 21:01:05 -040076func (ll *LabelList) Equals(other LabelList) bool {
77 if len(ll.Includes) != len(other.Includes) || len(ll.Excludes) != len(other.Excludes) {
78 return false
79 }
80 for i, _ := range ll.Includes {
81 if ll.Includes[i] != other.Includes[i] {
82 return false
83 }
84 }
85 for i, _ := range ll.Excludes {
86 if ll.Excludes[i] != other.Excludes[i] {
87 return false
88 }
89 }
90 return true
91}
92
Liz Kammer9abd62d2021-05-21 08:37:59 -040093func (ll *LabelList) IsNil() bool {
94 return ll.Includes == nil && ll.Excludes == nil
95}
96
Sam Delmerico3177a6e2022-06-21 19:28:33 +000097func (ll *LabelList) IsEmpty() bool {
98 return len(ll.Includes) == 0 && len(ll.Excludes) == 0
99}
100
Liz Kammer74deed42021-06-02 13:02:03 -0400101func (ll *LabelList) deepCopy() LabelList {
102 return LabelList{
103 Includes: ll.Includes[:],
104 Excludes: ll.Excludes[:],
105 }
106}
107
Jingwen Chen63930982021-03-24 10:04:33 -0400108// uniqueParentDirectories returns a list of the unique parent directories for
109// all files in ll.Includes.
110func (ll *LabelList) uniqueParentDirectories() []string {
111 dirMap := map[string]bool{}
112 for _, label := range ll.Includes {
113 dirMap[filepath.Dir(label.Label)] = true
114 }
115 dirs := []string{}
116 for dir := range dirMap {
117 dirs = append(dirs, dir)
118 }
119 return dirs
120}
121
Sam Delmericoc1130dc2022-08-25 14:43:54 -0400122// Add inserts the label Label at the end of the LabelList.Includes.
Liz Kammer12615db2021-09-28 09:19:17 -0400123func (ll *LabelList) Add(label *Label) {
124 if label == nil {
125 return
126 }
127 ll.Includes = append(ll.Includes, *label)
128}
129
Sam Delmericoc1130dc2022-08-25 14:43:54 -0400130// AddExclude inserts the label Label at the end of the LabelList.Excludes.
131func (ll *LabelList) AddExclude(label *Label) {
132 if label == nil {
133 return
134 }
135 ll.Excludes = append(ll.Excludes, *label)
136}
137
Liz Kammer356f7d42021-01-26 09:18:53 -0500138// Append appends the fields of other labelList to the corresponding fields of ll.
139func (ll *LabelList) Append(other LabelList) {
140 if len(ll.Includes) > 0 || len(other.Includes) > 0 {
141 ll.Includes = append(ll.Includes, other.Includes...)
142 }
143 if len(ll.Excludes) > 0 || len(other.Excludes) > 0 {
144 ll.Excludes = append(other.Excludes, other.Excludes...)
145 }
146}
Jingwen Chen5d864492021-02-24 07:20:12 -0500147
Sam Delmericoc1130dc2022-08-25 14:43:54 -0400148// Partition splits a LabelList into two LabelLists depending on the return value
149// of the predicate.
150// This function preserves the Includes and Excludes, but it does not provide
151// that information to the partition function.
152func (ll *LabelList) Partition(predicate func(label Label) bool) (LabelList, LabelList) {
153 predicated := LabelList{}
154 unpredicated := LabelList{}
155 for _, include := range ll.Includes {
156 if predicate(include) {
157 predicated.Add(&include)
158 } else {
159 unpredicated.Add(&include)
160 }
161 }
162 for _, exclude := range ll.Excludes {
163 if predicate(exclude) {
164 predicated.AddExclude(&exclude)
165 } else {
166 unpredicated.AddExclude(&exclude)
167 }
168 }
169 return predicated, unpredicated
170}
171
Jingwen Chened9c17d2021-04-13 07:14:55 +0000172// UniqueSortedBazelLabels takes a []Label and deduplicates the labels, and returns
173// the slice in a sorted order.
174func UniqueSortedBazelLabels(originalLabels []Label) []Label {
Rupert Shuttleworth2e4219b2021-03-12 11:04:21 +0000175 uniqueLabelsSet := make(map[Label]bool)
176 for _, l := range originalLabels {
177 uniqueLabelsSet[l] = true
178 }
179 var uniqueLabels []Label
180 for l, _ := range uniqueLabelsSet {
181 uniqueLabels = append(uniqueLabels, l)
182 }
183 sort.SliceStable(uniqueLabels, func(i, j int) bool {
184 return uniqueLabels[i].Label < uniqueLabels[j].Label
185 })
186 return uniqueLabels
187}
188
Liz Kammer9abd62d2021-05-21 08:37:59 -0400189func FirstUniqueBazelLabels(originalLabels []Label) []Label {
190 var labels []Label
191 found := make(map[Label]bool, len(originalLabels))
192 for _, l := range originalLabels {
193 if _, ok := found[l]; ok {
194 continue
195 }
196 labels = append(labels, l)
197 found[l] = true
198 }
199 return labels
200}
201
202func FirstUniqueBazelLabelList(originalLabelList LabelList) LabelList {
203 var uniqueLabelList LabelList
204 uniqueLabelList.Includes = FirstUniqueBazelLabels(originalLabelList.Includes)
205 uniqueLabelList.Excludes = FirstUniqueBazelLabels(originalLabelList.Excludes)
206 return uniqueLabelList
207}
208
209func UniqueSortedBazelLabelList(originalLabelList LabelList) LabelList {
Rupert Shuttleworth2e4219b2021-03-12 11:04:21 +0000210 var uniqueLabelList LabelList
Jingwen Chened9c17d2021-04-13 07:14:55 +0000211 uniqueLabelList.Includes = UniqueSortedBazelLabels(originalLabelList.Includes)
212 uniqueLabelList.Excludes = UniqueSortedBazelLabels(originalLabelList.Excludes)
Rupert Shuttleworth2e4219b2021-03-12 11:04:21 +0000213 return uniqueLabelList
214}
215
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000216// Subtract needle from haystack
217func SubtractStrings(haystack []string, needle []string) []string {
218 // This is really a set
Liz Kammer9bad9d62021-10-11 15:40:35 -0400219 needleMap := make(map[string]bool)
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000220 for _, s := range needle {
Liz Kammer9bad9d62021-10-11 15:40:35 -0400221 needleMap[s] = true
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000222 }
223
224 var strings []string
Liz Kammer9bad9d62021-10-11 15:40:35 -0400225 for _, s := range haystack {
226 if exclude := needleMap[s]; !exclude {
227 strings = append(strings, s)
228 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000229 }
230
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000231 return strings
232}
233
234// Subtract needle from haystack
235func SubtractBazelLabels(haystack []Label, needle []Label) []Label {
236 // This is really a set
Liz Kammer9bad9d62021-10-11 15:40:35 -0400237 needleMap := make(map[Label]bool)
238 for _, s := range needle {
239 needleMap[s] = true
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000240 }
241
242 var labels []Label
Liz Kammer9bad9d62021-10-11 15:40:35 -0400243 for _, label := range haystack {
244 if exclude := needleMap[label]; !exclude {
245 labels = append(labels, label)
246 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000247 }
248
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000249 return labels
250}
251
Chris Parsons484e50a2021-05-13 15:13:04 -0400252// Appends two LabelLists, returning the combined list.
253func AppendBazelLabelLists(a LabelList, b LabelList) LabelList {
254 var result LabelList
255 result.Includes = append(a.Includes, b.Includes...)
256 result.Excludes = append(a.Excludes, b.Excludes...)
257 return result
258}
259
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000260// Subtract needle from haystack
261func SubtractBazelLabelList(haystack LabelList, needle LabelList) LabelList {
262 var result LabelList
263 result.Includes = SubtractBazelLabels(haystack.Includes, needle.Includes)
264 // NOTE: Excludes are intentionally not subtracted
265 result.Excludes = haystack.Excludes
266 return result
267}
268
Jingwen Chenc1c26502021-04-05 10:35:13 +0000269type Attribute interface {
270 HasConfigurableValues() bool
271}
272
Liz Kammer9abd62d2021-05-21 08:37:59 -0400273type labelSelectValues map[string]*Label
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400274
Liz Kammer9abd62d2021-05-21 08:37:59 -0400275type configurableLabels map[ConfigurationAxis]labelSelectValues
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400276
Liz Kammer9abd62d2021-05-21 08:37:59 -0400277func (cl configurableLabels) setValueForAxis(axis ConfigurationAxis, config string, value *Label) {
278 if cl[axis] == nil {
279 cl[axis] = make(labelSelectValues)
280 }
281 cl[axis][config] = value
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400282}
283
284// Represents an attribute whose value is a single label
285type LabelAttribute struct {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400286 Value *Label
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400287
Liz Kammer9abd62d2021-05-21 08:37:59 -0400288 ConfigurableValues configurableLabels
Lukacs T. Berki1353e592021-04-30 15:35:09 +0200289}
290
Chris Parsons58852a02021-12-09 18:10:18 -0500291func (la *LabelAttribute) axisTypes() map[configurationType]bool {
292 types := map[configurationType]bool{}
293 for k := range la.ConfigurableValues {
294 if len(la.ConfigurableValues[k]) > 0 {
295 types[k.configurationType] = true
296 }
297 }
298 return types
299}
300
301// Collapse reduces the configurable axes of the label attribute to a single axis.
302// This is necessary for final writing to bp2build, as a configurable label
303// attribute can only be comprised by a single select.
304func (la *LabelAttribute) Collapse() error {
305 axisTypes := la.axisTypes()
306 _, containsOs := axisTypes[os]
307 _, containsArch := axisTypes[arch]
308 _, containsOsArch := axisTypes[osArch]
309 _, containsProductVariables := axisTypes[productVariables]
310 if containsProductVariables {
311 if containsOs || containsArch || containsOsArch {
312 return fmt.Errorf("label attribute could not be collapsed as it has two or more unrelated axes")
313 }
314 }
315 if (containsOs && containsArch) || (containsOsArch && (containsOs || containsArch)) {
316 // If a bool attribute has both os and arch configuration axes, the only
317 // way to successfully union their values is to increase the granularity
318 // of the configuration criteria to os_arch.
319 for osType, supportedArchs := range osToArchMap {
320 for _, supportedArch := range supportedArchs {
321 osArch := osArchString(osType, supportedArch)
322 if archOsVal := la.SelectValue(OsArchConfigurationAxis, osArch); archOsVal != nil {
323 // Do nothing, as the arch_os is explicitly defined already.
324 } else {
325 archVal := la.SelectValue(ArchConfigurationAxis, supportedArch)
326 osVal := la.SelectValue(OsConfigurationAxis, osType)
327 if osVal != nil && archVal != nil {
328 // In this case, arch takes precedence. (This fits legacy Soong behavior, as arch mutator
329 // runs after os mutator.
330 la.SetSelectValue(OsArchConfigurationAxis, osArch, *archVal)
331 } else if osVal != nil && archVal == nil {
332 la.SetSelectValue(OsArchConfigurationAxis, osArch, *osVal)
333 } else if osVal == nil && archVal != nil {
334 la.SetSelectValue(OsArchConfigurationAxis, osArch, *archVal)
335 }
336 }
337 }
338 }
339 // All os_arch values are now set. Clear os and arch axes.
340 delete(la.ConfigurableValues, ArchConfigurationAxis)
341 delete(la.ConfigurableValues, OsConfigurationAxis)
342 }
343 return nil
344}
345
Liz Kammer9abd62d2021-05-21 08:37:59 -0400346// HasConfigurableValues returns whether there are configurable values set for this label.
347func (la LabelAttribute) HasConfigurableValues() bool {
Chris Parsons58852a02021-12-09 18:10:18 -0500348 for _, selectValues := range la.ConfigurableValues {
349 if len(selectValues) > 0 {
350 return true
351 }
352 }
353 return false
Lukacs T. Berki598dd002021-05-05 09:00:01 +0200354}
355
Liz Kammer9abd62d2021-05-21 08:37:59 -0400356// SetValue sets the base, non-configured value for the Label
357func (la *LabelAttribute) SetValue(value Label) {
358 la.SetSelectValue(NoConfigAxis, "", value)
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400359}
360
Liz Kammer9abd62d2021-05-21 08:37:59 -0400361// SetSelectValue set a value for a bazel select for the given axis, config and value.
362func (la *LabelAttribute) SetSelectValue(axis ConfigurationAxis, config string, value Label) {
363 axis.validateConfig(config)
364 switch axis.configurationType {
365 case noConfig:
366 la.Value = &value
Wei Li81852ca2022-07-27 00:22:06 -0700367 case arch, os, osArch, productVariables, osAndInApex:
Liz Kammer9abd62d2021-05-21 08:37:59 -0400368 if la.ConfigurableValues == nil {
369 la.ConfigurableValues = make(configurableLabels)
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400370 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400371 la.ConfigurableValues.setValueForAxis(axis, config, &value)
372 default:
373 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
374 }
375}
376
377// SelectValue gets a value for a bazel select for the given axis and config.
Chris Parsons58852a02021-12-09 18:10:18 -0500378func (la *LabelAttribute) SelectValue(axis ConfigurationAxis, config string) *Label {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400379 axis.validateConfig(config)
380 switch axis.configurationType {
381 case noConfig:
Chris Parsons58852a02021-12-09 18:10:18 -0500382 return la.Value
Wei Li81852ca2022-07-27 00:22:06 -0700383 case arch, os, osArch, productVariables, osAndInApex:
Chris Parsons58852a02021-12-09 18:10:18 -0500384 return la.ConfigurableValues[axis][config]
Liz Kammer9abd62d2021-05-21 08:37:59 -0400385 default:
386 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
387 }
388}
389
390// SortedConfigurationAxes returns all the used ConfigurationAxis in sorted order.
391func (la *LabelAttribute) SortedConfigurationAxes() []ConfigurationAxis {
392 keys := make([]ConfigurationAxis, 0, len(la.ConfigurableValues))
393 for k := range la.ConfigurableValues {
394 keys = append(keys, k)
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400395 }
396
Liz Kammer9abd62d2021-05-21 08:37:59 -0400397 sort.Slice(keys, func(i, j int) bool { return keys[i].less(keys[j]) })
398 return keys
399}
400
Sam Delmericoc0161432022-02-25 21:34:51 +0000401// MakeLabelAttribute turns a string into a LabelAttribute
402func MakeLabelAttribute(label string) *LabelAttribute {
403 return &LabelAttribute{
404 Value: &Label{
405 Label: label,
406 },
407 }
408}
409
Liz Kammerd366c902021-06-03 13:43:01 -0400410type configToBools map[string]bool
411
412func (ctb configToBools) setValue(config string, value *bool) {
413 if value == nil {
414 if _, ok := ctb[config]; ok {
415 delete(ctb, config)
416 }
417 return
418 }
419 ctb[config] = *value
420}
421
422type configurableBools map[ConfigurationAxis]configToBools
423
424func (cb configurableBools) setValueForAxis(axis ConfigurationAxis, config string, value *bool) {
425 if cb[axis] == nil {
426 cb[axis] = make(configToBools)
427 }
428 cb[axis].setValue(config, value)
429}
430
431// BoolAttribute represents an attribute whose value is a single bool but may be configurable..
432type BoolAttribute struct {
433 Value *bool
434
435 ConfigurableValues configurableBools
436}
437
438// HasConfigurableValues returns whether there are configurable values for this attribute.
439func (ba BoolAttribute) HasConfigurableValues() bool {
Chris Parsons58852a02021-12-09 18:10:18 -0500440 for _, cfgToBools := range ba.ConfigurableValues {
441 if len(cfgToBools) > 0 {
442 return true
443 }
444 }
445 return false
Liz Kammerd366c902021-06-03 13:43:01 -0400446}
447
Liz Kammerdfeb1202022-05-13 17:20:20 -0400448// SetValue sets value for the no config axis
449func (ba *BoolAttribute) SetValue(value *bool) {
450 ba.SetSelectValue(NoConfigAxis, "", value)
451}
452
Liz Kammerd366c902021-06-03 13:43:01 -0400453// SetSelectValue sets value for the given axis/config.
454func (ba *BoolAttribute) SetSelectValue(axis ConfigurationAxis, config string, value *bool) {
455 axis.validateConfig(config)
456 switch axis.configurationType {
457 case noConfig:
458 ba.Value = value
Wei Li81852ca2022-07-27 00:22:06 -0700459 case arch, os, osArch, productVariables, osAndInApex:
Liz Kammerd366c902021-06-03 13:43:01 -0400460 if ba.ConfigurableValues == nil {
461 ba.ConfigurableValues = make(configurableBools)
462 }
463 ba.ConfigurableValues.setValueForAxis(axis, config, value)
464 default:
465 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
466 }
467}
468
Chris Parsons58852a02021-12-09 18:10:18 -0500469// ToLabelListAttribute creates and returns a LabelListAttribute from this
470// bool attribute, where each bool in this attribute corresponds to a
471// label list value in the resultant attribute.
472func (ba *BoolAttribute) ToLabelListAttribute(falseVal LabelList, trueVal LabelList) (LabelListAttribute, error) {
473 getLabelList := func(boolPtr *bool) LabelList {
474 if boolPtr == nil {
475 return LabelList{nil, nil}
476 } else if *boolPtr {
477 return trueVal
478 } else {
479 return falseVal
480 }
481 }
482
483 mainVal := getLabelList(ba.Value)
484 if !ba.HasConfigurableValues() {
485 return MakeLabelListAttribute(mainVal), nil
486 }
487
488 result := LabelListAttribute{}
489 if err := ba.Collapse(); err != nil {
490 return result, err
491 }
492
493 for axis, configToBools := range ba.ConfigurableValues {
494 if len(configToBools) < 1 {
495 continue
496 }
497 for config, boolPtr := range configToBools {
498 val := getLabelList(&boolPtr)
499 if !val.Equals(mainVal) {
500 result.SetSelectValue(axis, config, val)
501 }
502 }
503 result.SetSelectValue(axis, ConditionsDefaultConfigKey, mainVal)
504 }
505
506 return result, nil
507}
508
509// Collapse reduces the configurable axes of the boolean attribute to a single axis.
510// This is necessary for final writing to bp2build, as a configurable boolean
511// attribute can only be comprised by a single select.
512func (ba *BoolAttribute) Collapse() error {
513 axisTypes := ba.axisTypes()
514 _, containsOs := axisTypes[os]
515 _, containsArch := axisTypes[arch]
516 _, containsOsArch := axisTypes[osArch]
517 _, containsProductVariables := axisTypes[productVariables]
518 if containsProductVariables {
519 if containsOs || containsArch || containsOsArch {
520 return fmt.Errorf("boolean attribute could not be collapsed as it has two or more unrelated axes")
521 }
522 }
523 if (containsOs && containsArch) || (containsOsArch && (containsOs || containsArch)) {
524 // If a bool attribute has both os and arch configuration axes, the only
525 // way to successfully union their values is to increase the granularity
526 // of the configuration criteria to os_arch.
527 for osType, supportedArchs := range osToArchMap {
528 for _, supportedArch := range supportedArchs {
529 osArch := osArchString(osType, supportedArch)
530 if archOsVal := ba.SelectValue(OsArchConfigurationAxis, osArch); archOsVal != nil {
531 // Do nothing, as the arch_os is explicitly defined already.
532 } else {
533 archVal := ba.SelectValue(ArchConfigurationAxis, supportedArch)
534 osVal := ba.SelectValue(OsConfigurationAxis, osType)
535 if osVal != nil && archVal != nil {
536 // In this case, arch takes precedence. (This fits legacy Soong behavior, as arch mutator
537 // runs after os mutator.
538 ba.SetSelectValue(OsArchConfigurationAxis, osArch, archVal)
539 } else if osVal != nil && archVal == nil {
540 ba.SetSelectValue(OsArchConfigurationAxis, osArch, osVal)
541 } else if osVal == nil && archVal != nil {
542 ba.SetSelectValue(OsArchConfigurationAxis, osArch, archVal)
543 }
544 }
545 }
546 }
547 // All os_arch values are now set. Clear os and arch axes.
548 delete(ba.ConfigurableValues, ArchConfigurationAxis)
549 delete(ba.ConfigurableValues, OsConfigurationAxis)
550 // Verify post-condition; this should never fail, provided no additional
551 // axes are introduced.
552 if len(ba.ConfigurableValues) > 1 {
Liz Kammer07e106f2022-01-13 17:00:10 -0500553 panic(fmt.Errorf("error in collapsing attribute: %#v", ba))
Chris Parsons58852a02021-12-09 18:10:18 -0500554 }
555 }
556 return nil
557}
558
559func (ba *BoolAttribute) axisTypes() map[configurationType]bool {
560 types := map[configurationType]bool{}
561 for k := range ba.ConfigurableValues {
562 if len(ba.ConfigurableValues[k]) > 0 {
563 types[k.configurationType] = true
564 }
565 }
566 return types
567}
568
Liz Kammerd366c902021-06-03 13:43:01 -0400569// SelectValue gets the value for the given axis/config.
570func (ba BoolAttribute) SelectValue(axis ConfigurationAxis, config string) *bool {
571 axis.validateConfig(config)
572 switch axis.configurationType {
573 case noConfig:
574 return ba.Value
Wei Li81852ca2022-07-27 00:22:06 -0700575 case arch, os, osArch, productVariables, osAndInApex:
Liz Kammerd366c902021-06-03 13:43:01 -0400576 if v, ok := ba.ConfigurableValues[axis][config]; ok {
577 return &v
578 } else {
579 return nil
580 }
581 default:
582 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
583 }
584}
585
586// SortedConfigurationAxes returns all the used ConfigurationAxis in sorted order.
587func (ba *BoolAttribute) SortedConfigurationAxes() []ConfigurationAxis {
588 keys := make([]ConfigurationAxis, 0, len(ba.ConfigurableValues))
589 for k := range ba.ConfigurableValues {
590 keys = append(keys, k)
591 }
592
593 sort.Slice(keys, func(i, j int) bool { return keys[i].less(keys[j]) })
594 return keys
595}
596
Liz Kammer9abd62d2021-05-21 08:37:59 -0400597// labelListSelectValues supports config-specific label_list typed Bazel attribute values.
598type labelListSelectValues map[string]LabelList
599
Liz Kammer12615db2021-09-28 09:19:17 -0400600func (ll labelListSelectValues) addSelects(label labelSelectValues) {
601 for k, v := range label {
602 if label == nil {
603 continue
604 }
605 l := ll[k]
606 (&l).Add(v)
607 ll[k] = l
608 }
609}
610
Chris Parsons77acf2e2021-12-03 17:27:16 -0500611func (ll labelListSelectValues) appendSelects(other labelListSelectValues, forceSpecifyEmptyList bool) {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400612 for k, v := range other {
613 l := ll[k]
Chris Parsons77acf2e2021-12-03 17:27:16 -0500614 if forceSpecifyEmptyList && l.IsNil() && !v.IsNil() {
615 l.Includes = []Label{}
616 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400617 (&l).Append(v)
618 ll[k] = l
619 }
620}
621
622// HasConfigurableValues returns whether there are configurable values within this set of selects.
623func (ll labelListSelectValues) HasConfigurableValues() bool {
624 for _, v := range ll {
Chris Parsons51f8c392021-08-03 21:01:05 -0400625 if v.Includes != nil {
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400626 return true
627 }
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400628 }
629 return false
630}
631
Jingwen Chen07027912021-03-15 06:02:43 -0400632// LabelListAttribute is used to represent a list of Bazel labels as an
633// attribute.
634type LabelListAttribute struct {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400635 // The non-configured attribute label list Value. Required.
Jingwen Chen07027912021-03-15 06:02:43 -0400636 Value LabelList
637
Liz Kammer9abd62d2021-05-21 08:37:59 -0400638 // The configured attribute label list Values. Optional
639 // a map of independent configurability axes
640 ConfigurableValues configurableLabelLists
Chris Parsons51f8c392021-08-03 21:01:05 -0400641
642 // If true, differentiate between "nil" and "empty" list. nil means that
643 // this attribute should not be specified at all, and "empty" means that
644 // the attribute should be explicitly specified as an empty list.
645 // This mode facilitates use of attribute defaults: an empty list should
646 // override the default.
647 ForceSpecifyEmptyList bool
Jingwen Chen58ff6802021-11-17 12:14:41 +0000648
649 // If true, signal the intent to the code generator to emit all select keys,
650 // even if the Includes list for that key is empty. This mode facilitates
651 // specific select statements where an empty list for a non-default select
652 // key has a meaning.
653 EmitEmptyList bool
Liz Kammer9abd62d2021-05-21 08:37:59 -0400654}
Jingwen Chen91220d72021-03-24 02:18:33 -0400655
Liz Kammer9abd62d2021-05-21 08:37:59 -0400656type configurableLabelLists map[ConfigurationAxis]labelListSelectValues
657
658func (cll configurableLabelLists) setValueForAxis(axis ConfigurationAxis, config string, list LabelList) {
659 if list.IsNil() {
660 if _, ok := cll[axis][config]; ok {
661 delete(cll[axis], config)
662 }
663 return
664 }
665 if cll[axis] == nil {
666 cll[axis] = make(labelListSelectValues)
667 }
668
669 cll[axis][config] = list
670}
671
Chris Parsons77acf2e2021-12-03 17:27:16 -0500672func (cll configurableLabelLists) Append(other configurableLabelLists, forceSpecifyEmptyList bool) {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400673 for axis, otherSelects := range other {
674 selects := cll[axis]
675 if selects == nil {
676 selects = make(labelListSelectValues, len(otherSelects))
677 }
Chris Parsons77acf2e2021-12-03 17:27:16 -0500678 selects.appendSelects(otherSelects, forceSpecifyEmptyList)
Liz Kammer9abd62d2021-05-21 08:37:59 -0400679 cll[axis] = selects
680 }
Jingwen Chen07027912021-03-15 06:02:43 -0400681}
682
Chris Parsons77acf2e2021-12-03 17:27:16 -0500683func (lla *LabelListAttribute) Clone() *LabelListAttribute {
684 result := &LabelListAttribute{ForceSpecifyEmptyList: lla.ForceSpecifyEmptyList}
685 return result.Append(*lla)
686}
687
Jingwen Chen07027912021-03-15 06:02:43 -0400688// MakeLabelListAttribute initializes a LabelListAttribute with the non-arch specific value.
689func MakeLabelListAttribute(value LabelList) LabelListAttribute {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400690 return LabelListAttribute{
691 Value: value,
692 ConfigurableValues: make(configurableLabelLists),
693 }
694}
695
Cole Faust53b62092022-05-12 15:37:02 -0700696// MakeSingleLabelListAttribute initializes a LabelListAttribute as a non-arch specific list with 1 element, the given Label.
697func MakeSingleLabelListAttribute(value Label) LabelListAttribute {
698 return MakeLabelListAttribute(MakeLabelList([]Label{value}))
699}
700
Liz Kammer9abd62d2021-05-21 08:37:59 -0400701func (lla *LabelListAttribute) SetValue(list LabelList) {
702 lla.SetSelectValue(NoConfigAxis, "", list)
703}
704
705// SetSelectValue set a value for a bazel select for the given axis, config and value.
706func (lla *LabelListAttribute) SetSelectValue(axis ConfigurationAxis, config string, list LabelList) {
707 axis.validateConfig(config)
708 switch axis.configurationType {
709 case noConfig:
710 lla.Value = list
Wei Li81852ca2022-07-27 00:22:06 -0700711 case arch, os, osArch, productVariables, osAndInApex:
Liz Kammer9abd62d2021-05-21 08:37:59 -0400712 if lla.ConfigurableValues == nil {
713 lla.ConfigurableValues = make(configurableLabelLists)
714 }
715 lla.ConfigurableValues.setValueForAxis(axis, config, list)
716 default:
717 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
718 }
719}
720
721// SelectValue gets a value for a bazel select for the given axis and config.
722func (lla *LabelListAttribute) SelectValue(axis ConfigurationAxis, config string) LabelList {
723 axis.validateConfig(config)
724 switch axis.configurationType {
725 case noConfig:
726 return lla.Value
Wei Li81852ca2022-07-27 00:22:06 -0700727 case arch, os, osArch, productVariables, osAndInApex:
Cole Faustc843b992022-08-02 18:06:50 -0700728 return lla.ConfigurableValues[axis][config]
Liz Kammer9abd62d2021-05-21 08:37:59 -0400729 default:
730 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
731 }
732}
733
734// SortedConfigurationAxes returns all the used ConfigurationAxis in sorted order.
735func (lla *LabelListAttribute) SortedConfigurationAxes() []ConfigurationAxis {
736 keys := make([]ConfigurationAxis, 0, len(lla.ConfigurableValues))
737 for k := range lla.ConfigurableValues {
738 keys = append(keys, k)
739 }
740
741 sort.Slice(keys, func(i, j int) bool { return keys[i].less(keys[j]) })
742 return keys
Jingwen Chen07027912021-03-15 06:02:43 -0400743}
744
Jingwen Chened9c17d2021-04-13 07:14:55 +0000745// Append all values, including os and arch specific ones, from another
Chris Parsons77acf2e2021-12-03 17:27:16 -0500746// LabelListAttribute to this LabelListAttribute. Returns this LabelListAttribute.
747func (lla *LabelListAttribute) Append(other LabelListAttribute) *LabelListAttribute {
748 forceSpecifyEmptyList := lla.ForceSpecifyEmptyList || other.ForceSpecifyEmptyList
749 if forceSpecifyEmptyList && lla.Value.IsNil() && !other.Value.IsNil() {
Chris Parsons51f8c392021-08-03 21:01:05 -0400750 lla.Value.Includes = []Label{}
751 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400752 lla.Value.Append(other.Value)
753 if lla.ConfigurableValues == nil {
754 lla.ConfigurableValues = make(configurableLabelLists)
Jingwen Chen63930982021-03-24 10:04:33 -0400755 }
Chris Parsons77acf2e2021-12-03 17:27:16 -0500756 lla.ConfigurableValues.Append(other.ConfigurableValues, forceSpecifyEmptyList)
757 return lla
Jingwen Chen63930982021-03-24 10:04:33 -0400758}
759
Liz Kammer12615db2021-09-28 09:19:17 -0400760// Add inserts the labels for each axis of LabelAttribute at the end of corresponding axis's
761// LabelList within the LabelListAttribute
762func (lla *LabelListAttribute) Add(label *LabelAttribute) {
763 if label == nil {
764 return
765 }
766
767 lla.Value.Add(label.Value)
768 if lla.ConfigurableValues == nil && label.ConfigurableValues != nil {
769 lla.ConfigurableValues = make(configurableLabelLists)
770 }
771 for axis, _ := range label.ConfigurableValues {
772 if _, exists := lla.ConfigurableValues[axis]; !exists {
773 lla.ConfigurableValues[axis] = make(labelListSelectValues)
774 }
775 lla.ConfigurableValues[axis].addSelects(label.ConfigurableValues[axis])
776 }
777}
778
Liz Kammer9abd62d2021-05-21 08:37:59 -0400779// HasConfigurableValues returns true if the attribute contains axis-specific label list values.
780func (lla LabelListAttribute) HasConfigurableValues() bool {
Chris Parsons58852a02021-12-09 18:10:18 -0500781 for _, selectValues := range lla.ConfigurableValues {
782 if len(selectValues) > 0 {
783 return true
784 }
785 }
786 return false
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -0400787}
788
Chris Parsons69fa9f92021-07-13 11:47:44 -0400789// IsEmpty returns true if the attribute has no values under any configuration.
790func (lla LabelListAttribute) IsEmpty() bool {
791 if len(lla.Value.Includes) > 0 {
792 return false
793 }
794 for axis, _ := range lla.ConfigurableValues {
795 if lla.ConfigurableValues[axis].HasConfigurableValues() {
796 return false
797 }
798 }
799 return true
800}
801
Liz Kammer54309532021-12-14 12:21:22 -0500802// IsNil returns true if the attribute has not been set for any configuration.
803func (lla LabelListAttribute) IsNil() bool {
804 if lla.Value.Includes != nil {
805 return false
806 }
807 return !lla.HasConfigurableValues()
808}
809
810// Exclude for the given axis, config, removes Includes in labelList from Includes and appends them
811// to Excludes. This is to special case any excludes that are not specified in a bp file but need to
812// be removed, e.g. if they could cause duplicate element failures.
813func (lla *LabelListAttribute) Exclude(axis ConfigurationAxis, config string, labelList LabelList) {
814 val := lla.SelectValue(axis, config)
815 newList := SubtractBazelLabelList(val, labelList)
816 newList.Excludes = append(newList.Excludes, labelList.Includes...)
817 lla.SetSelectValue(axis, config, newList)
818}
819
Liz Kammer74deed42021-06-02 13:02:03 -0400820// ResolveExcludes handles excludes across the various axes, ensuring that items are removed from
821// the base value and included in default values as appropriate.
822func (lla *LabelListAttribute) ResolveExcludes() {
823 for axis, configToLabels := range lla.ConfigurableValues {
824 baseLabels := lla.Value.deepCopy()
825 for config, val := range configToLabels {
826 // Exclude config-specific excludes from base value
827 lla.Value = SubtractBazelLabelList(lla.Value, LabelList{Includes: val.Excludes})
828
829 // add base values to config specific to add labels excluded by others in this axis
830 // then remove all config-specific excludes
831 allLabels := baseLabels.deepCopy()
832 allLabels.Append(val)
833 lla.ConfigurableValues[axis][config] = SubtractBazelLabelList(allLabels, LabelList{Includes: val.Excludes})
834 }
835
836 // After going through all configs, delete the duplicates in the config
837 // values that are already in the base Value.
838 for config, val := range configToLabels {
839 lla.ConfigurableValues[axis][config] = SubtractBazelLabelList(val, lla.Value)
840 }
841
Jingwen Chen9af49a42021-11-02 10:27:17 +0000842 // Now that the Value list is finalized for this axis, compare it with
843 // the original list, and union the difference with the default
844 // condition for the axis.
845 difference := SubtractBazelLabelList(baseLabels, lla.Value)
846 existingDefaults := lla.ConfigurableValues[axis][ConditionsDefaultConfigKey]
847 existingDefaults.Append(difference)
848 lla.ConfigurableValues[axis][ConditionsDefaultConfigKey] = FirstUniqueBazelLabelList(existingDefaults)
Liz Kammer74deed42021-06-02 13:02:03 -0400849
850 // if everything ends up without includes, just delete the axis
851 if !lla.ConfigurableValues[axis].HasConfigurableValues() {
852 delete(lla.ConfigurableValues, axis)
853 }
854 }
855}
856
Sam Delmericoc1130dc2022-08-25 14:43:54 -0400857// Partition splits a LabelListAttribute into two LabelListAttributes depending
858// on the return value of the predicate.
859// This function preserves the Includes and Excludes, but it does not provide
860// that information to the partition function.
861func (lla LabelListAttribute) Partition(predicate func(label Label) bool) (LabelListAttribute, LabelListAttribute) {
862 predicated := LabelListAttribute{}
863 unpredicated := LabelListAttribute{}
864
865 valuePartitionTrue, valuePartitionFalse := lla.Value.Partition(predicate)
866 predicated.SetValue(valuePartitionTrue)
867 unpredicated.SetValue(valuePartitionFalse)
868
869 for axis, selectValueLabelLists := range lla.ConfigurableValues {
870 for config, labelList := range selectValueLabelLists {
871 configPredicated, configUnpredicated := labelList.Partition(predicate)
872 predicated.SetSelectValue(axis, config, configPredicated)
873 unpredicated.SetSelectValue(axis, config, configUnpredicated)
874 }
875 }
876
877 return predicated, unpredicated
878}
879
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400880// OtherModuleContext is a limited context that has methods with information about other modules.
881type OtherModuleContext interface {
882 ModuleFromName(name string) (blueprint.Module, bool)
883 OtherModuleType(m blueprint.Module) string
884 OtherModuleName(m blueprint.Module) string
885 OtherModuleDir(m blueprint.Module) string
886 ModuleErrorf(fmt string, args ...interface{})
887}
888
889// LabelMapper is a function that takes a OtherModuleContext and returns a (potentially changed)
890// label and whether it was changed.
Liz Kammer12615db2021-09-28 09:19:17 -0400891type LabelMapper func(OtherModuleContext, Label) (string, bool)
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400892
893// LabelPartition contains descriptions of a partition for labels
894type LabelPartition struct {
895 // Extensions to include in this partition
896 Extensions []string
897 // LabelMapper is a function that can map a label to a new label, and indicate whether to include
898 // the mapped label in the partition
899 LabelMapper LabelMapper
900 // Whether to store files not included in any other partition in a group of LabelPartitions
901 // Only one partition in a group of LabelPartitions can enabled Keep_remainder
902 Keep_remainder bool
903}
904
905// LabelPartitions is a map of partition name to a LabelPartition describing the elements of the
906// partition
907type LabelPartitions map[string]LabelPartition
908
909// filter returns a pointer to a label if the label should be included in the partition or nil if
910// not.
911func (lf LabelPartition) filter(ctx OtherModuleContext, label Label) *Label {
912 if lf.LabelMapper != nil {
Liz Kammer12615db2021-09-28 09:19:17 -0400913 if newLabel, changed := lf.LabelMapper(ctx, label); changed {
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400914 return &Label{newLabel, label.OriginalModuleName}
915 }
916 }
917 for _, ext := range lf.Extensions {
918 if strings.HasSuffix(label.Label, ext) {
919 return &label
920 }
921 }
922
923 return nil
924}
925
926// PartitionToLabelListAttribute is map of partition name to a LabelListAttribute
927type PartitionToLabelListAttribute map[string]LabelListAttribute
928
929type partitionToLabelList map[string]*LabelList
930
931func (p partitionToLabelList) appendIncludes(partition string, label Label) {
932 if _, ok := p[partition]; !ok {
933 p[partition] = &LabelList{}
934 }
935 p[partition].Includes = append(p[partition].Includes, label)
936}
937
938func (p partitionToLabelList) excludes(partition string, excludes []Label) {
939 if _, ok := p[partition]; !ok {
940 p[partition] = &LabelList{}
941 }
942 p[partition].Excludes = excludes
943}
944
945// PartitionLabelListAttribute partitions a LabelListAttribute into the requested partitions
946func PartitionLabelListAttribute(ctx OtherModuleContext, lla *LabelListAttribute, partitions LabelPartitions) PartitionToLabelListAttribute {
947 ret := PartitionToLabelListAttribute{}
948 var partitionNames []string
949 // Stored as a pointer to distinguish nil (no remainder partition) from empty string partition
950 var remainderPartition *string
951 for p, f := range partitions {
952 partitionNames = append(partitionNames, p)
953 if f.Keep_remainder {
954 if remainderPartition != nil {
955 panic("only one partition can store the remainder")
956 }
957 // If we take the address of p in a loop, we'll end up with the last value of p in
958 // remainderPartition, we want the requested partition
959 capturePartition := p
960 remainderPartition = &capturePartition
961 }
962 }
963
964 partitionLabelList := func(axis ConfigurationAxis, config string) {
965 value := lla.SelectValue(axis, config)
966 partitionToLabels := partitionToLabelList{}
967 for _, item := range value.Includes {
968 wasFiltered := false
969 var inPartition *string
970 for partition, f := range partitions {
971 filtered := f.filter(ctx, item)
972 if filtered == nil {
973 // did not match this filter, keep looking
974 continue
975 }
976 wasFiltered = true
977 partitionToLabels.appendIncludes(partition, *filtered)
978 // don't need to check other partitions if this filter used the item,
979 // continue checking if mapped to another name
980 if *filtered == item {
981 if inPartition != nil {
982 ctx.ModuleErrorf("%q was found in multiple partitions: %q, %q", item.Label, *inPartition, partition)
983 }
984 capturePartition := partition
985 inPartition = &capturePartition
986 }
987 }
988
989 // if not specified in a partition, add to remainder partition if one exists
990 if !wasFiltered && remainderPartition != nil {
991 partitionToLabels.appendIncludes(*remainderPartition, item)
992 }
993 }
994
995 // ensure empty lists are maintained
996 if value.Excludes != nil {
997 for _, partition := range partitionNames {
998 partitionToLabels.excludes(partition, value.Excludes)
999 }
1000 }
1001
1002 for partition, list := range partitionToLabels {
1003 val := ret[partition]
1004 (&val).SetSelectValue(axis, config, *list)
1005 ret[partition] = val
1006 }
1007 }
1008
1009 partitionLabelList(NoConfigAxis, "")
1010 for axis, configToList := range lla.ConfigurableValues {
1011 for config, _ := range configToList {
1012 partitionLabelList(axis, config)
1013 }
1014 }
1015 return ret
1016}
1017
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +00001018// StringAttribute corresponds to the string Bazel attribute type with
1019// support for additional metadata, like configurations.
1020type StringAttribute struct {
1021 // The base value of the string attribute.
1022 Value *string
1023
1024 // The configured attribute label list Values. Optional
1025 // a map of independent configurability axes
1026 ConfigurableValues configurableStrings
1027}
1028
1029type configurableStrings map[ConfigurationAxis]stringSelectValues
1030
1031func (cs configurableStrings) setValueForAxis(axis ConfigurationAxis, config string, str *string) {
1032 if cs[axis] == nil {
1033 cs[axis] = make(stringSelectValues)
1034 }
1035 var v = ""
1036 if str != nil {
1037 v = *str
1038 }
1039 cs[axis][config] = v
1040}
1041
1042type stringSelectValues map[string]string
1043
1044// HasConfigurableValues returns true if the attribute contains axis-specific string values.
1045func (sa StringAttribute) HasConfigurableValues() bool {
1046 for _, selectValues := range sa.ConfigurableValues {
1047 if len(selectValues) > 0 {
1048 return true
1049 }
1050 }
1051 return false
1052}
1053
1054// SetSelectValue set a value for a bazel select for the given axis, config and value.
1055func (sa *StringAttribute) SetSelectValue(axis ConfigurationAxis, config string, str *string) {
1056 axis.validateConfig(config)
1057 switch axis.configurationType {
1058 case noConfig:
1059 sa.Value = str
1060 case arch, os, osArch, productVariables:
1061 if sa.ConfigurableValues == nil {
1062 sa.ConfigurableValues = make(configurableStrings)
1063 }
1064 sa.ConfigurableValues.setValueForAxis(axis, config, str)
1065 default:
1066 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
1067 }
1068}
1069
1070// SelectValue gets a value for a bazel select for the given axis and config.
1071func (sa *StringAttribute) SelectValue(axis ConfigurationAxis, config string) *string {
1072 axis.validateConfig(config)
1073 switch axis.configurationType {
1074 case noConfig:
1075 return sa.Value
1076 case arch, os, osArch, productVariables:
1077 if v, ok := sa.ConfigurableValues[axis][config]; ok {
1078 return &v
1079 } else {
1080 return nil
1081 }
1082 default:
1083 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
1084 }
1085}
1086
1087// SortedConfigurationAxes returns all the used ConfigurationAxis in sorted order.
1088func (sa *StringAttribute) SortedConfigurationAxes() []ConfigurationAxis {
1089 keys := make([]ConfigurationAxis, 0, len(sa.ConfigurableValues))
1090 for k := range sa.ConfigurableValues {
1091 keys = append(keys, k)
1092 }
1093
1094 sort.Slice(keys, func(i, j int) bool { return keys[i].less(keys[j]) })
1095 return keys
1096}
1097
1098// Collapse reduces the configurable axes of the string attribute to a single axis.
1099// This is necessary for final writing to bp2build, as a configurable string
1100// attribute can only be comprised by a single select.
1101func (sa *StringAttribute) Collapse() error {
1102 axisTypes := sa.axisTypes()
1103 _, containsOs := axisTypes[os]
1104 _, containsArch := axisTypes[arch]
1105 _, containsOsArch := axisTypes[osArch]
1106 _, containsProductVariables := axisTypes[productVariables]
1107 if containsProductVariables {
1108 if containsOs || containsArch || containsOsArch {
1109 return fmt.Errorf("boolean attribute could not be collapsed as it has two or more unrelated axes")
1110 }
1111 }
1112 if (containsOs && containsArch) || (containsOsArch && (containsOs || containsArch)) {
1113 // If a bool attribute has both os and arch configuration axes, the only
1114 // way to successfully union their values is to increase the granularity
1115 // of the configuration criteria to os_arch.
1116 for osType, supportedArchs := range osToArchMap {
1117 for _, supportedArch := range supportedArchs {
1118 osArch := osArchString(osType, supportedArch)
1119 if archOsVal := sa.SelectValue(OsArchConfigurationAxis, osArch); archOsVal != nil {
1120 // Do nothing, as the arch_os is explicitly defined already.
1121 } else {
1122 archVal := sa.SelectValue(ArchConfigurationAxis, supportedArch)
1123 osVal := sa.SelectValue(OsConfigurationAxis, osType)
1124 if osVal != nil && archVal != nil {
1125 // In this case, arch takes precedence. (This fits legacy Soong behavior, as arch mutator
1126 // runs after os mutator.
1127 sa.SetSelectValue(OsArchConfigurationAxis, osArch, archVal)
1128 } else if osVal != nil && archVal == nil {
1129 sa.SetSelectValue(OsArchConfigurationAxis, osArch, osVal)
1130 } else if osVal == nil && archVal != nil {
1131 sa.SetSelectValue(OsArchConfigurationAxis, osArch, archVal)
1132 }
1133 }
1134 }
1135 }
1136 // All os_arch values are now set. Clear os and arch axes.
1137 delete(sa.ConfigurableValues, ArchConfigurationAxis)
1138 delete(sa.ConfigurableValues, OsConfigurationAxis)
1139 // Verify post-condition; this should never fail, provided no additional
1140 // axes are introduced.
1141 if len(sa.ConfigurableValues) > 1 {
1142 panic(fmt.Errorf("error in collapsing attribute: %#v", sa))
1143 }
1144 }
1145 return nil
1146}
1147
1148func (sa *StringAttribute) axisTypes() map[configurationType]bool {
1149 types := map[configurationType]bool{}
1150 for k := range sa.ConfigurableValues {
1151 if strs := sa.ConfigurableValues[k]; len(strs) > 0 {
1152 types[k.configurationType] = true
1153 }
1154 }
1155 return types
1156}
1157
Jingwen Chen5d864492021-02-24 07:20:12 -05001158// StringListAttribute corresponds to the string_list Bazel attribute type with
1159// support for additional metadata, like configurations.
1160type StringListAttribute struct {
1161 // The base value of the string list attribute.
1162 Value []string
1163
Liz Kammer9abd62d2021-05-21 08:37:59 -04001164 // The configured attribute label list Values. Optional
1165 // a map of independent configurability axes
1166 ConfigurableValues configurableStringLists
1167}
Jingwen Chenc1c26502021-04-05 10:35:13 +00001168
Liz Kammer9abd62d2021-05-21 08:37:59 -04001169type configurableStringLists map[ConfigurationAxis]stringListSelectValues
Liz Kammer6fd7b3f2021-05-06 13:54:29 -04001170
Liz Kammer9abd62d2021-05-21 08:37:59 -04001171func (csl configurableStringLists) Append(other configurableStringLists) {
1172 for axis, otherSelects := range other {
1173 selects := csl[axis]
1174 if selects == nil {
1175 selects = make(stringListSelectValues, len(otherSelects))
1176 }
1177 selects.appendSelects(otherSelects)
1178 csl[axis] = selects
1179 }
1180}
1181
1182func (csl configurableStringLists) setValueForAxis(axis ConfigurationAxis, config string, list []string) {
1183 if csl[axis] == nil {
1184 csl[axis] = make(stringListSelectValues)
1185 }
1186 csl[axis][config] = list
1187}
1188
1189type stringListSelectValues map[string][]string
1190
1191func (sl stringListSelectValues) appendSelects(other stringListSelectValues) {
1192 for k, v := range other {
1193 sl[k] = append(sl[k], v...)
1194 }
1195}
1196
1197func (sl stringListSelectValues) hasConfigurableValues(other stringListSelectValues) bool {
1198 for _, val := range sl {
1199 if len(val) > 0 {
1200 return true
1201 }
1202 }
1203 return false
Jingwen Chen5d864492021-02-24 07:20:12 -05001204}
1205
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001206// MakeStringListAttribute initializes a StringListAttribute with the non-arch specific value.
1207func MakeStringListAttribute(value []string) StringListAttribute {
1208 // NOTE: These strings are not necessarily unique or sorted.
Liz Kammer9abd62d2021-05-21 08:37:59 -04001209 return StringListAttribute{
1210 Value: value,
1211 ConfigurableValues: make(configurableStringLists),
Jingwen Chen91220d72021-03-24 02:18:33 -04001212 }
1213}
1214
Liz Kammer9abd62d2021-05-21 08:37:59 -04001215// HasConfigurableValues returns true if the attribute contains axis-specific string_list values.
1216func (sla StringListAttribute) HasConfigurableValues() bool {
Chris Parsons58852a02021-12-09 18:10:18 -05001217 for _, selectValues := range sla.ConfigurableValues {
1218 if len(selectValues) > 0 {
1219 return true
1220 }
1221 }
1222 return false
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -04001223}
1224
Jingwen Chened9c17d2021-04-13 07:14:55 +00001225// Append appends all values, including os and arch specific ones, from another
1226// StringListAttribute to this StringListAttribute
Chris Parsons77acf2e2021-12-03 17:27:16 -05001227func (sla *StringListAttribute) Append(other StringListAttribute) *StringListAttribute {
Liz Kammer9abd62d2021-05-21 08:37:59 -04001228 sla.Value = append(sla.Value, other.Value...)
1229 if sla.ConfigurableValues == nil {
1230 sla.ConfigurableValues = make(configurableStringLists)
1231 }
1232 sla.ConfigurableValues.Append(other.ConfigurableValues)
Chris Parsons77acf2e2021-12-03 17:27:16 -05001233 return sla
1234}
1235
1236func (sla *StringListAttribute) Clone() *StringListAttribute {
1237 result := &StringListAttribute{}
1238 return result.Append(*sla)
Liz Kammer9abd62d2021-05-21 08:37:59 -04001239}
1240
1241// SetSelectValue set a value for a bazel select for the given axis, config and value.
1242func (sla *StringListAttribute) SetSelectValue(axis ConfigurationAxis, config string, list []string) {
1243 axis.validateConfig(config)
1244 switch axis.configurationType {
1245 case noConfig:
1246 sla.Value = list
Wei Li81852ca2022-07-27 00:22:06 -07001247 case arch, os, osArch, productVariables, osAndInApex:
Liz Kammer9abd62d2021-05-21 08:37:59 -04001248 if sla.ConfigurableValues == nil {
1249 sla.ConfigurableValues = make(configurableStringLists)
1250 }
1251 sla.ConfigurableValues.setValueForAxis(axis, config, list)
1252 default:
1253 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
1254 }
1255}
1256
1257// SelectValue gets a value for a bazel select for the given axis and config.
1258func (sla *StringListAttribute) SelectValue(axis ConfigurationAxis, config string) []string {
1259 axis.validateConfig(config)
1260 switch axis.configurationType {
1261 case noConfig:
1262 return sla.Value
Wei Li81852ca2022-07-27 00:22:06 -07001263 case arch, os, osArch, productVariables, osAndInApex:
Liz Kammer9abd62d2021-05-21 08:37:59 -04001264 return sla.ConfigurableValues[axis][config]
1265 default:
1266 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
1267 }
1268}
1269
1270// SortedConfigurationAxes returns all the used ConfigurationAxis in sorted order.
1271func (sla *StringListAttribute) SortedConfigurationAxes() []ConfigurationAxis {
1272 keys := make([]ConfigurationAxis, 0, len(sla.ConfigurableValues))
1273 for k := range sla.ConfigurableValues {
1274 keys = append(keys, k)
Jingwen Chened9c17d2021-04-13 07:14:55 +00001275 }
1276
Liz Kammer9abd62d2021-05-21 08:37:59 -04001277 sort.Slice(keys, func(i, j int) bool { return keys[i].less(keys[j]) })
1278 return keys
Jingwen Chened9c17d2021-04-13 07:14:55 +00001279}
1280
Liz Kammer5fad5012021-09-09 14:08:21 -04001281// DeduplicateAxesFromBase ensures no duplication of items between the no-configuration value and
1282// configuration-specific values. For example, if we would convert this StringListAttribute as:
Colin Crossd079e0b2022-08-16 10:27:33 -07001283//
1284// ["a", "b", "c"] + select({
1285// "//condition:one": ["a", "d"],
1286// "//conditions:default": [],
1287// })
1288//
Liz Kammer5fad5012021-09-09 14:08:21 -04001289// after this function, we would convert this StringListAttribute as:
Colin Crossd079e0b2022-08-16 10:27:33 -07001290//
1291// ["a", "b", "c"] + select({
1292// "//condition:one": ["d"],
1293// "//conditions:default": [],
1294// })
Liz Kammer5fad5012021-09-09 14:08:21 -04001295func (sla *StringListAttribute) DeduplicateAxesFromBase() {
1296 base := sla.Value
1297 for axis, configToList := range sla.ConfigurableValues {
1298 for config, list := range configToList {
1299 remaining := SubtractStrings(list, base)
1300 if len(remaining) == 0 {
1301 delete(sla.ConfigurableValues[axis], config)
1302 } else {
1303 sla.ConfigurableValues[axis][config] = remaining
1304 }
1305 }
1306 }
1307}
1308
Liz Kammera060c452021-03-24 10:14:47 -04001309// TryVariableSubstitution, replace string substitution formatting within each string in slice with
1310// Starlark string.format compatible tag for productVariable.
1311func TryVariableSubstitutions(slice []string, productVariable string) ([]string, bool) {
1312 ret := make([]string, 0, len(slice))
1313 changesMade := false
1314 for _, s := range slice {
1315 newS, changed := TryVariableSubstitution(s, productVariable)
1316 ret = append(ret, newS)
1317 changesMade = changesMade || changed
1318 }
1319 return ret, changesMade
1320}
1321
1322// TryVariableSubstitution, replace string substitution formatting within s with Starlark
1323// string.format compatible tag for productVariable.
1324func TryVariableSubstitution(s string, productVariable string) (string, bool) {
Liz Kammerba7a9c52021-05-26 08:45:30 -04001325 sub := productVariableSubstitutionPattern.ReplaceAllString(s, "$("+productVariable+")")
Liz Kammera060c452021-03-24 10:14:47 -04001326 return sub, s != sub
1327}