blob: 41bcaca819bec3aa6e98c616348b4f8dcdc967d7 [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
Liz Kammer74deed42021-06-02 13:02:03 -040097func (ll *LabelList) deepCopy() LabelList {
98 return LabelList{
99 Includes: ll.Includes[:],
100 Excludes: ll.Excludes[:],
101 }
102}
103
Jingwen Chen63930982021-03-24 10:04:33 -0400104// uniqueParentDirectories returns a list of the unique parent directories for
105// all files in ll.Includes.
106func (ll *LabelList) uniqueParentDirectories() []string {
107 dirMap := map[string]bool{}
108 for _, label := range ll.Includes {
109 dirMap[filepath.Dir(label.Label)] = true
110 }
111 dirs := []string{}
112 for dir := range dirMap {
113 dirs = append(dirs, dir)
114 }
115 return dirs
116}
117
Liz Kammer12615db2021-09-28 09:19:17 -0400118// Add inserts the label Label at the end of the LabelList.
119func (ll *LabelList) Add(label *Label) {
120 if label == nil {
121 return
122 }
123 ll.Includes = append(ll.Includes, *label)
124}
125
Liz Kammer356f7d42021-01-26 09:18:53 -0500126// Append appends the fields of other labelList to the corresponding fields of ll.
127func (ll *LabelList) Append(other LabelList) {
128 if len(ll.Includes) > 0 || len(other.Includes) > 0 {
129 ll.Includes = append(ll.Includes, other.Includes...)
130 }
131 if len(ll.Excludes) > 0 || len(other.Excludes) > 0 {
132 ll.Excludes = append(other.Excludes, other.Excludes...)
133 }
134}
Jingwen Chen5d864492021-02-24 07:20:12 -0500135
Jingwen Chened9c17d2021-04-13 07:14:55 +0000136// UniqueSortedBazelLabels takes a []Label and deduplicates the labels, and returns
137// the slice in a sorted order.
138func UniqueSortedBazelLabels(originalLabels []Label) []Label {
Rupert Shuttleworth2e4219b2021-03-12 11:04:21 +0000139 uniqueLabelsSet := make(map[Label]bool)
140 for _, l := range originalLabels {
141 uniqueLabelsSet[l] = true
142 }
143 var uniqueLabels []Label
144 for l, _ := range uniqueLabelsSet {
145 uniqueLabels = append(uniqueLabels, l)
146 }
147 sort.SliceStable(uniqueLabels, func(i, j int) bool {
148 return uniqueLabels[i].Label < uniqueLabels[j].Label
149 })
150 return uniqueLabels
151}
152
Liz Kammer9abd62d2021-05-21 08:37:59 -0400153func FirstUniqueBazelLabels(originalLabels []Label) []Label {
154 var labels []Label
155 found := make(map[Label]bool, len(originalLabels))
156 for _, l := range originalLabels {
157 if _, ok := found[l]; ok {
158 continue
159 }
160 labels = append(labels, l)
161 found[l] = true
162 }
163 return labels
164}
165
166func FirstUniqueBazelLabelList(originalLabelList LabelList) LabelList {
167 var uniqueLabelList LabelList
168 uniqueLabelList.Includes = FirstUniqueBazelLabels(originalLabelList.Includes)
169 uniqueLabelList.Excludes = FirstUniqueBazelLabels(originalLabelList.Excludes)
170 return uniqueLabelList
171}
172
173func UniqueSortedBazelLabelList(originalLabelList LabelList) LabelList {
Rupert Shuttleworth2e4219b2021-03-12 11:04:21 +0000174 var uniqueLabelList LabelList
Jingwen Chened9c17d2021-04-13 07:14:55 +0000175 uniqueLabelList.Includes = UniqueSortedBazelLabels(originalLabelList.Includes)
176 uniqueLabelList.Excludes = UniqueSortedBazelLabels(originalLabelList.Excludes)
Rupert Shuttleworth2e4219b2021-03-12 11:04:21 +0000177 return uniqueLabelList
178}
179
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000180// Subtract needle from haystack
181func SubtractStrings(haystack []string, needle []string) []string {
182 // This is really a set
Liz Kammer9bad9d62021-10-11 15:40:35 -0400183 needleMap := make(map[string]bool)
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000184 for _, s := range needle {
Liz Kammer9bad9d62021-10-11 15:40:35 -0400185 needleMap[s] = true
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000186 }
187
188 var strings []string
Liz Kammer9bad9d62021-10-11 15:40:35 -0400189 for _, s := range haystack {
190 if exclude := needleMap[s]; !exclude {
191 strings = append(strings, s)
192 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000193 }
194
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000195 return strings
196}
197
198// Subtract needle from haystack
199func SubtractBazelLabels(haystack []Label, needle []Label) []Label {
200 // This is really a set
Liz Kammer9bad9d62021-10-11 15:40:35 -0400201 needleMap := make(map[Label]bool)
202 for _, s := range needle {
203 needleMap[s] = true
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000204 }
205
206 var labels []Label
Liz Kammer9bad9d62021-10-11 15:40:35 -0400207 for _, label := range haystack {
208 if exclude := needleMap[label]; !exclude {
209 labels = append(labels, label)
210 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000211 }
212
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000213 return labels
214}
215
Chris Parsons484e50a2021-05-13 15:13:04 -0400216// Appends two LabelLists, returning the combined list.
217func AppendBazelLabelLists(a LabelList, b LabelList) LabelList {
218 var result LabelList
219 result.Includes = append(a.Includes, b.Includes...)
220 result.Excludes = append(a.Excludes, b.Excludes...)
221 return result
222}
223
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000224// Subtract needle from haystack
225func SubtractBazelLabelList(haystack LabelList, needle LabelList) LabelList {
226 var result LabelList
227 result.Includes = SubtractBazelLabels(haystack.Includes, needle.Includes)
228 // NOTE: Excludes are intentionally not subtracted
229 result.Excludes = haystack.Excludes
230 return result
231}
232
Jingwen Chenc1c26502021-04-05 10:35:13 +0000233type Attribute interface {
234 HasConfigurableValues() bool
235}
236
Liz Kammer9abd62d2021-05-21 08:37:59 -0400237type labelSelectValues map[string]*Label
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400238
Liz Kammer9abd62d2021-05-21 08:37:59 -0400239type configurableLabels map[ConfigurationAxis]labelSelectValues
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400240
Liz Kammer9abd62d2021-05-21 08:37:59 -0400241func (cl configurableLabels) setValueForAxis(axis ConfigurationAxis, config string, value *Label) {
242 if cl[axis] == nil {
243 cl[axis] = make(labelSelectValues)
244 }
245 cl[axis][config] = value
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400246}
247
248// Represents an attribute whose value is a single label
249type LabelAttribute struct {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400250 Value *Label
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400251
Liz Kammer9abd62d2021-05-21 08:37:59 -0400252 ConfigurableValues configurableLabels
Lukacs T. Berki1353e592021-04-30 15:35:09 +0200253}
254
Chris Parsons58852a02021-12-09 18:10:18 -0500255func (la *LabelAttribute) axisTypes() map[configurationType]bool {
256 types := map[configurationType]bool{}
257 for k := range la.ConfigurableValues {
258 if len(la.ConfigurableValues[k]) > 0 {
259 types[k.configurationType] = true
260 }
261 }
262 return types
263}
264
265// Collapse reduces the configurable axes of the label attribute to a single axis.
266// This is necessary for final writing to bp2build, as a configurable label
267// attribute can only be comprised by a single select.
268func (la *LabelAttribute) Collapse() error {
269 axisTypes := la.axisTypes()
270 _, containsOs := axisTypes[os]
271 _, containsArch := axisTypes[arch]
272 _, containsOsArch := axisTypes[osArch]
273 _, containsProductVariables := axisTypes[productVariables]
274 if containsProductVariables {
275 if containsOs || containsArch || containsOsArch {
276 return fmt.Errorf("label attribute could not be collapsed as it has two or more unrelated axes")
277 }
278 }
279 if (containsOs && containsArch) || (containsOsArch && (containsOs || containsArch)) {
280 // If a bool attribute has both os and arch configuration axes, the only
281 // way to successfully union their values is to increase the granularity
282 // of the configuration criteria to os_arch.
283 for osType, supportedArchs := range osToArchMap {
284 for _, supportedArch := range supportedArchs {
285 osArch := osArchString(osType, supportedArch)
286 if archOsVal := la.SelectValue(OsArchConfigurationAxis, osArch); archOsVal != nil {
287 // Do nothing, as the arch_os is explicitly defined already.
288 } else {
289 archVal := la.SelectValue(ArchConfigurationAxis, supportedArch)
290 osVal := la.SelectValue(OsConfigurationAxis, osType)
291 if osVal != nil && archVal != nil {
292 // In this case, arch takes precedence. (This fits legacy Soong behavior, as arch mutator
293 // runs after os mutator.
294 la.SetSelectValue(OsArchConfigurationAxis, osArch, *archVal)
295 } else if osVal != nil && archVal == nil {
296 la.SetSelectValue(OsArchConfigurationAxis, osArch, *osVal)
297 } else if osVal == nil && archVal != nil {
298 la.SetSelectValue(OsArchConfigurationAxis, osArch, *archVal)
299 }
300 }
301 }
302 }
303 // All os_arch values are now set. Clear os and arch axes.
304 delete(la.ConfigurableValues, ArchConfigurationAxis)
305 delete(la.ConfigurableValues, OsConfigurationAxis)
306 }
307 return nil
308}
309
Liz Kammer9abd62d2021-05-21 08:37:59 -0400310// HasConfigurableValues returns whether there are configurable values set for this label.
311func (la LabelAttribute) HasConfigurableValues() bool {
Chris Parsons58852a02021-12-09 18:10:18 -0500312 for _, selectValues := range la.ConfigurableValues {
313 if len(selectValues) > 0 {
314 return true
315 }
316 }
317 return false
Lukacs T. Berki598dd002021-05-05 09:00:01 +0200318}
319
Liz Kammer9abd62d2021-05-21 08:37:59 -0400320// SetValue sets the base, non-configured value for the Label
321func (la *LabelAttribute) SetValue(value Label) {
322 la.SetSelectValue(NoConfigAxis, "", value)
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400323}
324
Liz Kammer9abd62d2021-05-21 08:37:59 -0400325// SetSelectValue set a value for a bazel select for the given axis, config and value.
326func (la *LabelAttribute) SetSelectValue(axis ConfigurationAxis, config string, value Label) {
327 axis.validateConfig(config)
328 switch axis.configurationType {
329 case noConfig:
330 la.Value = &value
Chris Parsons2dde0cb2021-10-01 14:45:30 -0400331 case arch, os, osArch, productVariables:
Liz Kammer9abd62d2021-05-21 08:37:59 -0400332 if la.ConfigurableValues == nil {
333 la.ConfigurableValues = make(configurableLabels)
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400334 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400335 la.ConfigurableValues.setValueForAxis(axis, config, &value)
336 default:
337 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
338 }
339}
340
341// SelectValue gets a value for a bazel select for the given axis and config.
Chris Parsons58852a02021-12-09 18:10:18 -0500342func (la *LabelAttribute) SelectValue(axis ConfigurationAxis, config string) *Label {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400343 axis.validateConfig(config)
344 switch axis.configurationType {
345 case noConfig:
Chris Parsons58852a02021-12-09 18:10:18 -0500346 return la.Value
Chris Parsons2dde0cb2021-10-01 14:45:30 -0400347 case arch, os, osArch, productVariables:
Chris Parsons58852a02021-12-09 18:10:18 -0500348 return la.ConfigurableValues[axis][config]
Liz Kammer9abd62d2021-05-21 08:37:59 -0400349 default:
350 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
351 }
352}
353
354// SortedConfigurationAxes returns all the used ConfigurationAxis in sorted order.
355func (la *LabelAttribute) SortedConfigurationAxes() []ConfigurationAxis {
356 keys := make([]ConfigurationAxis, 0, len(la.ConfigurableValues))
357 for k := range la.ConfigurableValues {
358 keys = append(keys, k)
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400359 }
360
Liz Kammer9abd62d2021-05-21 08:37:59 -0400361 sort.Slice(keys, func(i, j int) bool { return keys[i].less(keys[j]) })
362 return keys
363}
364
Sam Delmericoc0161432022-02-25 21:34:51 +0000365// MakeLabelAttribute turns a string into a LabelAttribute
366func MakeLabelAttribute(label string) *LabelAttribute {
367 return &LabelAttribute{
368 Value: &Label{
369 Label: label,
370 },
371 }
372}
373
Liz Kammerd366c902021-06-03 13:43:01 -0400374type configToBools map[string]bool
375
376func (ctb configToBools) setValue(config string, value *bool) {
377 if value == nil {
378 if _, ok := ctb[config]; ok {
379 delete(ctb, config)
380 }
381 return
382 }
383 ctb[config] = *value
384}
385
386type configurableBools map[ConfigurationAxis]configToBools
387
388func (cb configurableBools) setValueForAxis(axis ConfigurationAxis, config string, value *bool) {
389 if cb[axis] == nil {
390 cb[axis] = make(configToBools)
391 }
392 cb[axis].setValue(config, value)
393}
394
395// BoolAttribute represents an attribute whose value is a single bool but may be configurable..
396type BoolAttribute struct {
397 Value *bool
398
399 ConfigurableValues configurableBools
400}
401
402// HasConfigurableValues returns whether there are configurable values for this attribute.
403func (ba BoolAttribute) HasConfigurableValues() bool {
Chris Parsons58852a02021-12-09 18:10:18 -0500404 for _, cfgToBools := range ba.ConfigurableValues {
405 if len(cfgToBools) > 0 {
406 return true
407 }
408 }
409 return false
Liz Kammerd366c902021-06-03 13:43:01 -0400410}
411
412// SetSelectValue sets value for the given axis/config.
413func (ba *BoolAttribute) SetSelectValue(axis ConfigurationAxis, config string, value *bool) {
414 axis.validateConfig(config)
415 switch axis.configurationType {
416 case noConfig:
417 ba.Value = value
Chris Parsons2dde0cb2021-10-01 14:45:30 -0400418 case arch, os, osArch, productVariables:
Liz Kammerd366c902021-06-03 13:43:01 -0400419 if ba.ConfigurableValues == nil {
420 ba.ConfigurableValues = make(configurableBools)
421 }
422 ba.ConfigurableValues.setValueForAxis(axis, config, value)
423 default:
424 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
425 }
426}
427
Chris Parsons58852a02021-12-09 18:10:18 -0500428// ToLabelListAttribute creates and returns a LabelListAttribute from this
429// bool attribute, where each bool in this attribute corresponds to a
430// label list value in the resultant attribute.
431func (ba *BoolAttribute) ToLabelListAttribute(falseVal LabelList, trueVal LabelList) (LabelListAttribute, error) {
432 getLabelList := func(boolPtr *bool) LabelList {
433 if boolPtr == nil {
434 return LabelList{nil, nil}
435 } else if *boolPtr {
436 return trueVal
437 } else {
438 return falseVal
439 }
440 }
441
442 mainVal := getLabelList(ba.Value)
443 if !ba.HasConfigurableValues() {
444 return MakeLabelListAttribute(mainVal), nil
445 }
446
447 result := LabelListAttribute{}
448 if err := ba.Collapse(); err != nil {
449 return result, err
450 }
451
452 for axis, configToBools := range ba.ConfigurableValues {
453 if len(configToBools) < 1 {
454 continue
455 }
456 for config, boolPtr := range configToBools {
457 val := getLabelList(&boolPtr)
458 if !val.Equals(mainVal) {
459 result.SetSelectValue(axis, config, val)
460 }
461 }
462 result.SetSelectValue(axis, ConditionsDefaultConfigKey, mainVal)
463 }
464
465 return result, nil
466}
467
468// Collapse reduces the configurable axes of the boolean attribute to a single axis.
469// This is necessary for final writing to bp2build, as a configurable boolean
470// attribute can only be comprised by a single select.
471func (ba *BoolAttribute) Collapse() error {
472 axisTypes := ba.axisTypes()
473 _, containsOs := axisTypes[os]
474 _, containsArch := axisTypes[arch]
475 _, containsOsArch := axisTypes[osArch]
476 _, containsProductVariables := axisTypes[productVariables]
477 if containsProductVariables {
478 if containsOs || containsArch || containsOsArch {
479 return fmt.Errorf("boolean attribute could not be collapsed as it has two or more unrelated axes")
480 }
481 }
482 if (containsOs && containsArch) || (containsOsArch && (containsOs || containsArch)) {
483 // If a bool attribute has both os and arch configuration axes, the only
484 // way to successfully union their values is to increase the granularity
485 // of the configuration criteria to os_arch.
486 for osType, supportedArchs := range osToArchMap {
487 for _, supportedArch := range supportedArchs {
488 osArch := osArchString(osType, supportedArch)
489 if archOsVal := ba.SelectValue(OsArchConfigurationAxis, osArch); archOsVal != nil {
490 // Do nothing, as the arch_os is explicitly defined already.
491 } else {
492 archVal := ba.SelectValue(ArchConfigurationAxis, supportedArch)
493 osVal := ba.SelectValue(OsConfigurationAxis, osType)
494 if osVal != nil && archVal != nil {
495 // In this case, arch takes precedence. (This fits legacy Soong behavior, as arch mutator
496 // runs after os mutator.
497 ba.SetSelectValue(OsArchConfigurationAxis, osArch, archVal)
498 } else if osVal != nil && archVal == nil {
499 ba.SetSelectValue(OsArchConfigurationAxis, osArch, osVal)
500 } else if osVal == nil && archVal != nil {
501 ba.SetSelectValue(OsArchConfigurationAxis, osArch, archVal)
502 }
503 }
504 }
505 }
506 // All os_arch values are now set. Clear os and arch axes.
507 delete(ba.ConfigurableValues, ArchConfigurationAxis)
508 delete(ba.ConfigurableValues, OsConfigurationAxis)
509 // Verify post-condition; this should never fail, provided no additional
510 // axes are introduced.
511 if len(ba.ConfigurableValues) > 1 {
Liz Kammer07e106f2022-01-13 17:00:10 -0500512 panic(fmt.Errorf("error in collapsing attribute: %#v", ba))
Chris Parsons58852a02021-12-09 18:10:18 -0500513 }
514 }
515 return nil
516}
517
518func (ba *BoolAttribute) axisTypes() map[configurationType]bool {
519 types := map[configurationType]bool{}
520 for k := range ba.ConfigurableValues {
521 if len(ba.ConfigurableValues[k]) > 0 {
522 types[k.configurationType] = true
523 }
524 }
525 return types
526}
527
Liz Kammerd366c902021-06-03 13:43:01 -0400528// SelectValue gets the value for the given axis/config.
529func (ba BoolAttribute) SelectValue(axis ConfigurationAxis, config string) *bool {
530 axis.validateConfig(config)
531 switch axis.configurationType {
532 case noConfig:
533 return ba.Value
Chris Parsons2dde0cb2021-10-01 14:45:30 -0400534 case arch, os, osArch, productVariables:
Liz Kammerd366c902021-06-03 13:43:01 -0400535 if v, ok := ba.ConfigurableValues[axis][config]; ok {
536 return &v
537 } else {
538 return nil
539 }
540 default:
541 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
542 }
543}
544
545// SortedConfigurationAxes returns all the used ConfigurationAxis in sorted order.
546func (ba *BoolAttribute) SortedConfigurationAxes() []ConfigurationAxis {
547 keys := make([]ConfigurationAxis, 0, len(ba.ConfigurableValues))
548 for k := range ba.ConfigurableValues {
549 keys = append(keys, k)
550 }
551
552 sort.Slice(keys, func(i, j int) bool { return keys[i].less(keys[j]) })
553 return keys
554}
555
Liz Kammer9abd62d2021-05-21 08:37:59 -0400556// labelListSelectValues supports config-specific label_list typed Bazel attribute values.
557type labelListSelectValues map[string]LabelList
558
Liz Kammer12615db2021-09-28 09:19:17 -0400559func (ll labelListSelectValues) addSelects(label labelSelectValues) {
560 for k, v := range label {
561 if label == nil {
562 continue
563 }
564 l := ll[k]
565 (&l).Add(v)
566 ll[k] = l
567 }
568}
569
Chris Parsons77acf2e2021-12-03 17:27:16 -0500570func (ll labelListSelectValues) appendSelects(other labelListSelectValues, forceSpecifyEmptyList bool) {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400571 for k, v := range other {
572 l := ll[k]
Chris Parsons77acf2e2021-12-03 17:27:16 -0500573 if forceSpecifyEmptyList && l.IsNil() && !v.IsNil() {
574 l.Includes = []Label{}
575 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400576 (&l).Append(v)
577 ll[k] = l
578 }
579}
580
581// HasConfigurableValues returns whether there are configurable values within this set of selects.
582func (ll labelListSelectValues) HasConfigurableValues() bool {
583 for _, v := range ll {
Chris Parsons51f8c392021-08-03 21:01:05 -0400584 if v.Includes != nil {
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400585 return true
586 }
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400587 }
588 return false
589}
590
Jingwen Chen07027912021-03-15 06:02:43 -0400591// LabelListAttribute is used to represent a list of Bazel labels as an
592// attribute.
593type LabelListAttribute struct {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400594 // The non-configured attribute label list Value. Required.
Jingwen Chen07027912021-03-15 06:02:43 -0400595 Value LabelList
596
Liz Kammer9abd62d2021-05-21 08:37:59 -0400597 // The configured attribute label list Values. Optional
598 // a map of independent configurability axes
599 ConfigurableValues configurableLabelLists
Chris Parsons51f8c392021-08-03 21:01:05 -0400600
601 // If true, differentiate between "nil" and "empty" list. nil means that
602 // this attribute should not be specified at all, and "empty" means that
603 // the attribute should be explicitly specified as an empty list.
604 // This mode facilitates use of attribute defaults: an empty list should
605 // override the default.
606 ForceSpecifyEmptyList bool
Jingwen Chen58ff6802021-11-17 12:14:41 +0000607
608 // If true, signal the intent to the code generator to emit all select keys,
609 // even if the Includes list for that key is empty. This mode facilitates
610 // specific select statements where an empty list for a non-default select
611 // key has a meaning.
612 EmitEmptyList bool
Liz Kammer9abd62d2021-05-21 08:37:59 -0400613}
Jingwen Chen91220d72021-03-24 02:18:33 -0400614
Liz Kammer9abd62d2021-05-21 08:37:59 -0400615type configurableLabelLists map[ConfigurationAxis]labelListSelectValues
616
617func (cll configurableLabelLists) setValueForAxis(axis ConfigurationAxis, config string, list LabelList) {
618 if list.IsNil() {
619 if _, ok := cll[axis][config]; ok {
620 delete(cll[axis], config)
621 }
622 return
623 }
624 if cll[axis] == nil {
625 cll[axis] = make(labelListSelectValues)
626 }
627
628 cll[axis][config] = list
629}
630
Chris Parsons77acf2e2021-12-03 17:27:16 -0500631func (cll configurableLabelLists) Append(other configurableLabelLists, forceSpecifyEmptyList bool) {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400632 for axis, otherSelects := range other {
633 selects := cll[axis]
634 if selects == nil {
635 selects = make(labelListSelectValues, len(otherSelects))
636 }
Chris Parsons77acf2e2021-12-03 17:27:16 -0500637 selects.appendSelects(otherSelects, forceSpecifyEmptyList)
Liz Kammer9abd62d2021-05-21 08:37:59 -0400638 cll[axis] = selects
639 }
Jingwen Chen07027912021-03-15 06:02:43 -0400640}
641
Chris Parsons77acf2e2021-12-03 17:27:16 -0500642func (lla *LabelListAttribute) Clone() *LabelListAttribute {
643 result := &LabelListAttribute{ForceSpecifyEmptyList: lla.ForceSpecifyEmptyList}
644 return result.Append(*lla)
645}
646
Jingwen Chen07027912021-03-15 06:02:43 -0400647// MakeLabelListAttribute initializes a LabelListAttribute with the non-arch specific value.
648func MakeLabelListAttribute(value LabelList) LabelListAttribute {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400649 return LabelListAttribute{
650 Value: value,
651 ConfigurableValues: make(configurableLabelLists),
652 }
653}
654
Cole Faust53b62092022-05-12 15:37:02 -0700655// MakeSingleLabelListAttribute initializes a LabelListAttribute as a non-arch specific list with 1 element, the given Label.
656func MakeSingleLabelListAttribute(value Label) LabelListAttribute {
657 return MakeLabelListAttribute(MakeLabelList([]Label{value}))
658}
659
Liz Kammer9abd62d2021-05-21 08:37:59 -0400660func (lla *LabelListAttribute) SetValue(list LabelList) {
661 lla.SetSelectValue(NoConfigAxis, "", list)
662}
663
664// SetSelectValue set a value for a bazel select for the given axis, config and value.
665func (lla *LabelListAttribute) SetSelectValue(axis ConfigurationAxis, config string, list LabelList) {
666 axis.validateConfig(config)
667 switch axis.configurationType {
668 case noConfig:
669 lla.Value = list
Chris Parsons2dde0cb2021-10-01 14:45:30 -0400670 case arch, os, osArch, productVariables:
Liz Kammer9abd62d2021-05-21 08:37:59 -0400671 if lla.ConfigurableValues == nil {
672 lla.ConfigurableValues = make(configurableLabelLists)
673 }
674 lla.ConfigurableValues.setValueForAxis(axis, config, list)
675 default:
676 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
677 }
678}
679
680// SelectValue gets a value for a bazel select for the given axis and config.
681func (lla *LabelListAttribute) SelectValue(axis ConfigurationAxis, config string) LabelList {
682 axis.validateConfig(config)
683 switch axis.configurationType {
684 case noConfig:
685 return lla.Value
Chris Parsons2dde0cb2021-10-01 14:45:30 -0400686 case arch, os, osArch, productVariables:
Liz Kammer9abd62d2021-05-21 08:37:59 -0400687 return lla.ConfigurableValues[axis][config]
688 default:
689 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
690 }
691}
692
693// SortedConfigurationAxes returns all the used ConfigurationAxis in sorted order.
694func (lla *LabelListAttribute) SortedConfigurationAxes() []ConfigurationAxis {
695 keys := make([]ConfigurationAxis, 0, len(lla.ConfigurableValues))
696 for k := range lla.ConfigurableValues {
697 keys = append(keys, k)
698 }
699
700 sort.Slice(keys, func(i, j int) bool { return keys[i].less(keys[j]) })
701 return keys
Jingwen Chen07027912021-03-15 06:02:43 -0400702}
703
Jingwen Chened9c17d2021-04-13 07:14:55 +0000704// Append all values, including os and arch specific ones, from another
Chris Parsons77acf2e2021-12-03 17:27:16 -0500705// LabelListAttribute to this LabelListAttribute. Returns this LabelListAttribute.
706func (lla *LabelListAttribute) Append(other LabelListAttribute) *LabelListAttribute {
707 forceSpecifyEmptyList := lla.ForceSpecifyEmptyList || other.ForceSpecifyEmptyList
708 if forceSpecifyEmptyList && lla.Value.IsNil() && !other.Value.IsNil() {
Chris Parsons51f8c392021-08-03 21:01:05 -0400709 lla.Value.Includes = []Label{}
710 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400711 lla.Value.Append(other.Value)
712 if lla.ConfigurableValues == nil {
713 lla.ConfigurableValues = make(configurableLabelLists)
Jingwen Chen63930982021-03-24 10:04:33 -0400714 }
Chris Parsons77acf2e2021-12-03 17:27:16 -0500715 lla.ConfigurableValues.Append(other.ConfigurableValues, forceSpecifyEmptyList)
716 return lla
Jingwen Chen63930982021-03-24 10:04:33 -0400717}
718
Liz Kammer12615db2021-09-28 09:19:17 -0400719// Add inserts the labels for each axis of LabelAttribute at the end of corresponding axis's
720// LabelList within the LabelListAttribute
721func (lla *LabelListAttribute) Add(label *LabelAttribute) {
722 if label == nil {
723 return
724 }
725
726 lla.Value.Add(label.Value)
727 if lla.ConfigurableValues == nil && label.ConfigurableValues != nil {
728 lla.ConfigurableValues = make(configurableLabelLists)
729 }
730 for axis, _ := range label.ConfigurableValues {
731 if _, exists := lla.ConfigurableValues[axis]; !exists {
732 lla.ConfigurableValues[axis] = make(labelListSelectValues)
733 }
734 lla.ConfigurableValues[axis].addSelects(label.ConfigurableValues[axis])
735 }
736}
737
Liz Kammer9abd62d2021-05-21 08:37:59 -0400738// HasConfigurableValues returns true if the attribute contains axis-specific label list values.
739func (lla LabelListAttribute) HasConfigurableValues() bool {
Chris Parsons58852a02021-12-09 18:10:18 -0500740 for _, selectValues := range lla.ConfigurableValues {
741 if len(selectValues) > 0 {
742 return true
743 }
744 }
745 return false
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -0400746}
747
Chris Parsons69fa9f92021-07-13 11:47:44 -0400748// IsEmpty returns true if the attribute has no values under any configuration.
749func (lla LabelListAttribute) IsEmpty() bool {
750 if len(lla.Value.Includes) > 0 {
751 return false
752 }
753 for axis, _ := range lla.ConfigurableValues {
754 if lla.ConfigurableValues[axis].HasConfigurableValues() {
755 return false
756 }
757 }
758 return true
759}
760
Liz Kammer54309532021-12-14 12:21:22 -0500761// IsNil returns true if the attribute has not been set for any configuration.
762func (lla LabelListAttribute) IsNil() bool {
763 if lla.Value.Includes != nil {
764 return false
765 }
766 return !lla.HasConfigurableValues()
767}
768
769// Exclude for the given axis, config, removes Includes in labelList from Includes and appends them
770// to Excludes. This is to special case any excludes that are not specified in a bp file but need to
771// be removed, e.g. if they could cause duplicate element failures.
772func (lla *LabelListAttribute) Exclude(axis ConfigurationAxis, config string, labelList LabelList) {
773 val := lla.SelectValue(axis, config)
774 newList := SubtractBazelLabelList(val, labelList)
775 newList.Excludes = append(newList.Excludes, labelList.Includes...)
776 lla.SetSelectValue(axis, config, newList)
777}
778
Liz Kammer74deed42021-06-02 13:02:03 -0400779// ResolveExcludes handles excludes across the various axes, ensuring that items are removed from
780// the base value and included in default values as appropriate.
781func (lla *LabelListAttribute) ResolveExcludes() {
782 for axis, configToLabels := range lla.ConfigurableValues {
783 baseLabels := lla.Value.deepCopy()
784 for config, val := range configToLabels {
785 // Exclude config-specific excludes from base value
786 lla.Value = SubtractBazelLabelList(lla.Value, LabelList{Includes: val.Excludes})
787
788 // add base values to config specific to add labels excluded by others in this axis
789 // then remove all config-specific excludes
790 allLabels := baseLabels.deepCopy()
791 allLabels.Append(val)
792 lla.ConfigurableValues[axis][config] = SubtractBazelLabelList(allLabels, LabelList{Includes: val.Excludes})
793 }
794
795 // After going through all configs, delete the duplicates in the config
796 // values that are already in the base Value.
797 for config, val := range configToLabels {
798 lla.ConfigurableValues[axis][config] = SubtractBazelLabelList(val, lla.Value)
799 }
800
Jingwen Chen9af49a42021-11-02 10:27:17 +0000801 // Now that the Value list is finalized for this axis, compare it with
802 // the original list, and union the difference with the default
803 // condition for the axis.
804 difference := SubtractBazelLabelList(baseLabels, lla.Value)
805 existingDefaults := lla.ConfigurableValues[axis][ConditionsDefaultConfigKey]
806 existingDefaults.Append(difference)
807 lla.ConfigurableValues[axis][ConditionsDefaultConfigKey] = FirstUniqueBazelLabelList(existingDefaults)
Liz Kammer74deed42021-06-02 13:02:03 -0400808
809 // if everything ends up without includes, just delete the axis
810 if !lla.ConfigurableValues[axis].HasConfigurableValues() {
811 delete(lla.ConfigurableValues, axis)
812 }
813 }
814}
815
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400816// OtherModuleContext is a limited context that has methods with information about other modules.
817type OtherModuleContext interface {
818 ModuleFromName(name string) (blueprint.Module, bool)
819 OtherModuleType(m blueprint.Module) string
820 OtherModuleName(m blueprint.Module) string
821 OtherModuleDir(m blueprint.Module) string
822 ModuleErrorf(fmt string, args ...interface{})
823}
824
825// LabelMapper is a function that takes a OtherModuleContext and returns a (potentially changed)
826// label and whether it was changed.
Liz Kammer12615db2021-09-28 09:19:17 -0400827type LabelMapper func(OtherModuleContext, Label) (string, bool)
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400828
829// LabelPartition contains descriptions of a partition for labels
830type LabelPartition struct {
831 // Extensions to include in this partition
832 Extensions []string
833 // LabelMapper is a function that can map a label to a new label, and indicate whether to include
834 // the mapped label in the partition
835 LabelMapper LabelMapper
836 // Whether to store files not included in any other partition in a group of LabelPartitions
837 // Only one partition in a group of LabelPartitions can enabled Keep_remainder
838 Keep_remainder bool
839}
840
841// LabelPartitions is a map of partition name to a LabelPartition describing the elements of the
842// partition
843type LabelPartitions map[string]LabelPartition
844
845// filter returns a pointer to a label if the label should be included in the partition or nil if
846// not.
847func (lf LabelPartition) filter(ctx OtherModuleContext, label Label) *Label {
848 if lf.LabelMapper != nil {
Liz Kammer12615db2021-09-28 09:19:17 -0400849 if newLabel, changed := lf.LabelMapper(ctx, label); changed {
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400850 return &Label{newLabel, label.OriginalModuleName}
851 }
852 }
853 for _, ext := range lf.Extensions {
854 if strings.HasSuffix(label.Label, ext) {
855 return &label
856 }
857 }
858
859 return nil
860}
861
862// PartitionToLabelListAttribute is map of partition name to a LabelListAttribute
863type PartitionToLabelListAttribute map[string]LabelListAttribute
864
865type partitionToLabelList map[string]*LabelList
866
867func (p partitionToLabelList) appendIncludes(partition string, label Label) {
868 if _, ok := p[partition]; !ok {
869 p[partition] = &LabelList{}
870 }
871 p[partition].Includes = append(p[partition].Includes, label)
872}
873
874func (p partitionToLabelList) excludes(partition string, excludes []Label) {
875 if _, ok := p[partition]; !ok {
876 p[partition] = &LabelList{}
877 }
878 p[partition].Excludes = excludes
879}
880
881// PartitionLabelListAttribute partitions a LabelListAttribute into the requested partitions
882func PartitionLabelListAttribute(ctx OtherModuleContext, lla *LabelListAttribute, partitions LabelPartitions) PartitionToLabelListAttribute {
883 ret := PartitionToLabelListAttribute{}
884 var partitionNames []string
885 // Stored as a pointer to distinguish nil (no remainder partition) from empty string partition
886 var remainderPartition *string
887 for p, f := range partitions {
888 partitionNames = append(partitionNames, p)
889 if f.Keep_remainder {
890 if remainderPartition != nil {
891 panic("only one partition can store the remainder")
892 }
893 // If we take the address of p in a loop, we'll end up with the last value of p in
894 // remainderPartition, we want the requested partition
895 capturePartition := p
896 remainderPartition = &capturePartition
897 }
898 }
899
900 partitionLabelList := func(axis ConfigurationAxis, config string) {
901 value := lla.SelectValue(axis, config)
902 partitionToLabels := partitionToLabelList{}
903 for _, item := range value.Includes {
904 wasFiltered := false
905 var inPartition *string
906 for partition, f := range partitions {
907 filtered := f.filter(ctx, item)
908 if filtered == nil {
909 // did not match this filter, keep looking
910 continue
911 }
912 wasFiltered = true
913 partitionToLabels.appendIncludes(partition, *filtered)
914 // don't need to check other partitions if this filter used the item,
915 // continue checking if mapped to another name
916 if *filtered == item {
917 if inPartition != nil {
918 ctx.ModuleErrorf("%q was found in multiple partitions: %q, %q", item.Label, *inPartition, partition)
919 }
920 capturePartition := partition
921 inPartition = &capturePartition
922 }
923 }
924
925 // if not specified in a partition, add to remainder partition if one exists
926 if !wasFiltered && remainderPartition != nil {
927 partitionToLabels.appendIncludes(*remainderPartition, item)
928 }
929 }
930
931 // ensure empty lists are maintained
932 if value.Excludes != nil {
933 for _, partition := range partitionNames {
934 partitionToLabels.excludes(partition, value.Excludes)
935 }
936 }
937
938 for partition, list := range partitionToLabels {
939 val := ret[partition]
940 (&val).SetSelectValue(axis, config, *list)
941 ret[partition] = val
942 }
943 }
944
945 partitionLabelList(NoConfigAxis, "")
946 for axis, configToList := range lla.ConfigurableValues {
947 for config, _ := range configToList {
948 partitionLabelList(axis, config)
949 }
950 }
951 return ret
952}
953
Jingwen Chen5d864492021-02-24 07:20:12 -0500954// StringListAttribute corresponds to the string_list Bazel attribute type with
955// support for additional metadata, like configurations.
956type StringListAttribute struct {
957 // The base value of the string list attribute.
958 Value []string
959
Liz Kammer9abd62d2021-05-21 08:37:59 -0400960 // The configured attribute label list Values. Optional
961 // a map of independent configurability axes
962 ConfigurableValues configurableStringLists
963}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000964
Liz Kammer9abd62d2021-05-21 08:37:59 -0400965type configurableStringLists map[ConfigurationAxis]stringListSelectValues
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400966
Liz Kammer9abd62d2021-05-21 08:37:59 -0400967func (csl configurableStringLists) Append(other configurableStringLists) {
968 for axis, otherSelects := range other {
969 selects := csl[axis]
970 if selects == nil {
971 selects = make(stringListSelectValues, len(otherSelects))
972 }
973 selects.appendSelects(otherSelects)
974 csl[axis] = selects
975 }
976}
977
978func (csl configurableStringLists) setValueForAxis(axis ConfigurationAxis, config string, list []string) {
979 if csl[axis] == nil {
980 csl[axis] = make(stringListSelectValues)
981 }
982 csl[axis][config] = list
983}
984
985type stringListSelectValues map[string][]string
986
987func (sl stringListSelectValues) appendSelects(other stringListSelectValues) {
988 for k, v := range other {
989 sl[k] = append(sl[k], v...)
990 }
991}
992
993func (sl stringListSelectValues) hasConfigurableValues(other stringListSelectValues) bool {
994 for _, val := range sl {
995 if len(val) > 0 {
996 return true
997 }
998 }
999 return false
Jingwen Chen5d864492021-02-24 07:20:12 -05001000}
1001
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001002// MakeStringListAttribute initializes a StringListAttribute with the non-arch specific value.
1003func MakeStringListAttribute(value []string) StringListAttribute {
1004 // NOTE: These strings are not necessarily unique or sorted.
Liz Kammer9abd62d2021-05-21 08:37:59 -04001005 return StringListAttribute{
1006 Value: value,
1007 ConfigurableValues: make(configurableStringLists),
Jingwen Chen91220d72021-03-24 02:18:33 -04001008 }
1009}
1010
Liz Kammer9abd62d2021-05-21 08:37:59 -04001011// HasConfigurableValues returns true if the attribute contains axis-specific string_list values.
1012func (sla StringListAttribute) HasConfigurableValues() bool {
Chris Parsons58852a02021-12-09 18:10:18 -05001013 for _, selectValues := range sla.ConfigurableValues {
1014 if len(selectValues) > 0 {
1015 return true
1016 }
1017 }
1018 return false
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -04001019}
1020
Jingwen Chened9c17d2021-04-13 07:14:55 +00001021// Append appends all values, including os and arch specific ones, from another
1022// StringListAttribute to this StringListAttribute
Chris Parsons77acf2e2021-12-03 17:27:16 -05001023func (sla *StringListAttribute) Append(other StringListAttribute) *StringListAttribute {
Liz Kammer9abd62d2021-05-21 08:37:59 -04001024 sla.Value = append(sla.Value, other.Value...)
1025 if sla.ConfigurableValues == nil {
1026 sla.ConfigurableValues = make(configurableStringLists)
1027 }
1028 sla.ConfigurableValues.Append(other.ConfigurableValues)
Chris Parsons77acf2e2021-12-03 17:27:16 -05001029 return sla
1030}
1031
1032func (sla *StringListAttribute) Clone() *StringListAttribute {
1033 result := &StringListAttribute{}
1034 return result.Append(*sla)
Liz Kammer9abd62d2021-05-21 08:37:59 -04001035}
1036
1037// SetSelectValue set a value for a bazel select for the given axis, config and value.
1038func (sla *StringListAttribute) SetSelectValue(axis ConfigurationAxis, config string, list []string) {
1039 axis.validateConfig(config)
1040 switch axis.configurationType {
1041 case noConfig:
1042 sla.Value = list
Chris Parsons2dde0cb2021-10-01 14:45:30 -04001043 case arch, os, osArch, productVariables:
Liz Kammer9abd62d2021-05-21 08:37:59 -04001044 if sla.ConfigurableValues == nil {
1045 sla.ConfigurableValues = make(configurableStringLists)
1046 }
1047 sla.ConfigurableValues.setValueForAxis(axis, config, list)
1048 default:
1049 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
1050 }
1051}
1052
1053// SelectValue gets a value for a bazel select for the given axis and config.
1054func (sla *StringListAttribute) SelectValue(axis ConfigurationAxis, config string) []string {
1055 axis.validateConfig(config)
1056 switch axis.configurationType {
1057 case noConfig:
1058 return sla.Value
Chris Parsons2dde0cb2021-10-01 14:45:30 -04001059 case arch, os, osArch, productVariables:
Liz Kammer9abd62d2021-05-21 08:37:59 -04001060 return sla.ConfigurableValues[axis][config]
1061 default:
1062 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
1063 }
1064}
1065
1066// SortedConfigurationAxes returns all the used ConfigurationAxis in sorted order.
1067func (sla *StringListAttribute) SortedConfigurationAxes() []ConfigurationAxis {
1068 keys := make([]ConfigurationAxis, 0, len(sla.ConfigurableValues))
1069 for k := range sla.ConfigurableValues {
1070 keys = append(keys, k)
Jingwen Chened9c17d2021-04-13 07:14:55 +00001071 }
1072
Liz Kammer9abd62d2021-05-21 08:37:59 -04001073 sort.Slice(keys, func(i, j int) bool { return keys[i].less(keys[j]) })
1074 return keys
Jingwen Chened9c17d2021-04-13 07:14:55 +00001075}
1076
Liz Kammer5fad5012021-09-09 14:08:21 -04001077// DeduplicateAxesFromBase ensures no duplication of items between the no-configuration value and
1078// configuration-specific values. For example, if we would convert this StringListAttribute as:
1079// ["a", "b", "c"] + select({
1080// "//condition:one": ["a", "d"],
1081// "//conditions:default": [],
1082// })
1083// after this function, we would convert this StringListAttribute as:
1084// ["a", "b", "c"] + select({
1085// "//condition:one": ["d"],
1086// "//conditions:default": [],
1087// })
1088func (sla *StringListAttribute) DeduplicateAxesFromBase() {
1089 base := sla.Value
1090 for axis, configToList := range sla.ConfigurableValues {
1091 for config, list := range configToList {
1092 remaining := SubtractStrings(list, base)
1093 if len(remaining) == 0 {
1094 delete(sla.ConfigurableValues[axis], config)
1095 } else {
1096 sla.ConfigurableValues[axis][config] = remaining
1097 }
1098 }
1099 }
1100}
1101
Liz Kammera060c452021-03-24 10:14:47 -04001102// TryVariableSubstitution, replace string substitution formatting within each string in slice with
1103// Starlark string.format compatible tag for productVariable.
1104func TryVariableSubstitutions(slice []string, productVariable string) ([]string, bool) {
1105 ret := make([]string, 0, len(slice))
1106 changesMade := false
1107 for _, s := range slice {
1108 newS, changed := TryVariableSubstitution(s, productVariable)
1109 ret = append(ret, newS)
1110 changesMade = changesMade || changed
1111 }
1112 return ret, changesMade
1113}
1114
1115// TryVariableSubstitution, replace string substitution formatting within s with Starlark
1116// string.format compatible tag for productVariable.
1117func TryVariableSubstitution(s string, productVariable string) (string, bool) {
Liz Kammerba7a9c52021-05-26 08:45:30 -04001118 sub := productVariableSubstitutionPattern.ReplaceAllString(s, "$("+productVariable+")")
Liz Kammera060c452021-03-24 10:14:47 -04001119 return sub, s != sub
1120}