blob: 76450dc7bd8bd0db4271ce455938ab8fd628458c [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
Spandan Das4238c652022-09-09 01:38:47 +000076// MakeLabelListFromTargetNames creates a LabelList from unqualified target names
77// This is a utiltity function for bp2build converters of Soong modules that have 1:many generated targets
78func MakeLabelListFromTargetNames(targetNames []string) LabelList {
79 labels := []Label{}
80 for _, name := range targetNames {
81 label := Label{Label: ":" + name}
82 labels = append(labels, label)
83 }
84 return MakeLabelList(labels)
85}
86
Chris Parsons51f8c392021-08-03 21:01:05 -040087func (ll *LabelList) Equals(other LabelList) bool {
88 if len(ll.Includes) != len(other.Includes) || len(ll.Excludes) != len(other.Excludes) {
89 return false
90 }
91 for i, _ := range ll.Includes {
92 if ll.Includes[i] != other.Includes[i] {
93 return false
94 }
95 }
96 for i, _ := range ll.Excludes {
97 if ll.Excludes[i] != other.Excludes[i] {
98 return false
99 }
100 }
101 return true
102}
103
Liz Kammer9abd62d2021-05-21 08:37:59 -0400104func (ll *LabelList) IsNil() bool {
105 return ll.Includes == nil && ll.Excludes == nil
106}
107
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000108func (ll *LabelList) IsEmpty() bool {
109 return len(ll.Includes) == 0 && len(ll.Excludes) == 0
110}
111
Liz Kammer74deed42021-06-02 13:02:03 -0400112func (ll *LabelList) deepCopy() LabelList {
113 return LabelList{
114 Includes: ll.Includes[:],
115 Excludes: ll.Excludes[:],
116 }
117}
118
Jingwen Chen63930982021-03-24 10:04:33 -0400119// uniqueParentDirectories returns a list of the unique parent directories for
120// all files in ll.Includes.
121func (ll *LabelList) uniqueParentDirectories() []string {
122 dirMap := map[string]bool{}
123 for _, label := range ll.Includes {
124 dirMap[filepath.Dir(label.Label)] = true
125 }
126 dirs := []string{}
127 for dir := range dirMap {
128 dirs = append(dirs, dir)
129 }
130 return dirs
131}
132
Sam Delmericoc1130dc2022-08-25 14:43:54 -0400133// Add inserts the label Label at the end of the LabelList.Includes.
Liz Kammer12615db2021-09-28 09:19:17 -0400134func (ll *LabelList) Add(label *Label) {
135 if label == nil {
136 return
137 }
138 ll.Includes = append(ll.Includes, *label)
139}
140
Sam Delmericoc1130dc2022-08-25 14:43:54 -0400141// AddExclude inserts the label Label at the end of the LabelList.Excludes.
142func (ll *LabelList) AddExclude(label *Label) {
143 if label == nil {
144 return
145 }
146 ll.Excludes = append(ll.Excludes, *label)
147}
148
Liz Kammer356f7d42021-01-26 09:18:53 -0500149// Append appends the fields of other labelList to the corresponding fields of ll.
150func (ll *LabelList) Append(other LabelList) {
151 if len(ll.Includes) > 0 || len(other.Includes) > 0 {
152 ll.Includes = append(ll.Includes, other.Includes...)
153 }
154 if len(ll.Excludes) > 0 || len(other.Excludes) > 0 {
155 ll.Excludes = append(other.Excludes, other.Excludes...)
156 }
157}
Jingwen Chen5d864492021-02-24 07:20:12 -0500158
Sam Delmericoc1130dc2022-08-25 14:43:54 -0400159// Partition splits a LabelList into two LabelLists depending on the return value
160// of the predicate.
161// This function preserves the Includes and Excludes, but it does not provide
162// that information to the partition function.
163func (ll *LabelList) Partition(predicate func(label Label) bool) (LabelList, LabelList) {
164 predicated := LabelList{}
165 unpredicated := LabelList{}
166 for _, include := range ll.Includes {
167 if predicate(include) {
168 predicated.Add(&include)
169 } else {
170 unpredicated.Add(&include)
171 }
172 }
173 for _, exclude := range ll.Excludes {
174 if predicate(exclude) {
175 predicated.AddExclude(&exclude)
176 } else {
177 unpredicated.AddExclude(&exclude)
178 }
179 }
180 return predicated, unpredicated
181}
182
Jingwen Chened9c17d2021-04-13 07:14:55 +0000183// UniqueSortedBazelLabels takes a []Label and deduplicates the labels, and returns
184// the slice in a sorted order.
185func UniqueSortedBazelLabels(originalLabels []Label) []Label {
Rupert Shuttleworth2e4219b2021-03-12 11:04:21 +0000186 uniqueLabelsSet := make(map[Label]bool)
187 for _, l := range originalLabels {
188 uniqueLabelsSet[l] = true
189 }
190 var uniqueLabels []Label
191 for l, _ := range uniqueLabelsSet {
192 uniqueLabels = append(uniqueLabels, l)
193 }
194 sort.SliceStable(uniqueLabels, func(i, j int) bool {
195 return uniqueLabels[i].Label < uniqueLabels[j].Label
196 })
197 return uniqueLabels
198}
199
Liz Kammer9abd62d2021-05-21 08:37:59 -0400200func FirstUniqueBazelLabels(originalLabels []Label) []Label {
201 var labels []Label
202 found := make(map[Label]bool, len(originalLabels))
203 for _, l := range originalLabels {
204 if _, ok := found[l]; ok {
205 continue
206 }
207 labels = append(labels, l)
208 found[l] = true
209 }
210 return labels
211}
212
213func FirstUniqueBazelLabelList(originalLabelList LabelList) LabelList {
214 var uniqueLabelList LabelList
215 uniqueLabelList.Includes = FirstUniqueBazelLabels(originalLabelList.Includes)
216 uniqueLabelList.Excludes = FirstUniqueBazelLabels(originalLabelList.Excludes)
217 return uniqueLabelList
218}
219
220func UniqueSortedBazelLabelList(originalLabelList LabelList) LabelList {
Rupert Shuttleworth2e4219b2021-03-12 11:04:21 +0000221 var uniqueLabelList LabelList
Jingwen Chened9c17d2021-04-13 07:14:55 +0000222 uniqueLabelList.Includes = UniqueSortedBazelLabels(originalLabelList.Includes)
223 uniqueLabelList.Excludes = UniqueSortedBazelLabels(originalLabelList.Excludes)
Rupert Shuttleworth2e4219b2021-03-12 11:04:21 +0000224 return uniqueLabelList
225}
226
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000227// Subtract needle from haystack
228func SubtractStrings(haystack []string, needle []string) []string {
229 // This is really a set
Liz Kammer9bad9d62021-10-11 15:40:35 -0400230 needleMap := make(map[string]bool)
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000231 for _, s := range needle {
Liz Kammer9bad9d62021-10-11 15:40:35 -0400232 needleMap[s] = true
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000233 }
234
235 var strings []string
Liz Kammer9bad9d62021-10-11 15:40:35 -0400236 for _, s := range haystack {
237 if exclude := needleMap[s]; !exclude {
238 strings = append(strings, s)
239 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000240 }
241
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000242 return strings
243}
244
245// Subtract needle from haystack
246func SubtractBazelLabels(haystack []Label, needle []Label) []Label {
247 // This is really a set
Liz Kammer9bad9d62021-10-11 15:40:35 -0400248 needleMap := make(map[Label]bool)
249 for _, s := range needle {
250 needleMap[s] = true
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000251 }
252
253 var labels []Label
Liz Kammer9bad9d62021-10-11 15:40:35 -0400254 for _, label := range haystack {
255 if exclude := needleMap[label]; !exclude {
256 labels = append(labels, label)
257 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000258 }
259
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000260 return labels
261}
262
Chris Parsons484e50a2021-05-13 15:13:04 -0400263// Appends two LabelLists, returning the combined list.
264func AppendBazelLabelLists(a LabelList, b LabelList) LabelList {
265 var result LabelList
266 result.Includes = append(a.Includes, b.Includes...)
267 result.Excludes = append(a.Excludes, b.Excludes...)
268 return result
269}
270
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000271// Subtract needle from haystack
272func SubtractBazelLabelList(haystack LabelList, needle LabelList) LabelList {
273 var result LabelList
274 result.Includes = SubtractBazelLabels(haystack.Includes, needle.Includes)
275 // NOTE: Excludes are intentionally not subtracted
276 result.Excludes = haystack.Excludes
277 return result
278}
279
Jingwen Chenc1c26502021-04-05 10:35:13 +0000280type Attribute interface {
281 HasConfigurableValues() bool
282}
283
Liz Kammer9abd62d2021-05-21 08:37:59 -0400284type labelSelectValues map[string]*Label
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400285
Liz Kammer9abd62d2021-05-21 08:37:59 -0400286type configurableLabels map[ConfigurationAxis]labelSelectValues
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400287
Liz Kammer9abd62d2021-05-21 08:37:59 -0400288func (cl configurableLabels) setValueForAxis(axis ConfigurationAxis, config string, value *Label) {
289 if cl[axis] == nil {
290 cl[axis] = make(labelSelectValues)
291 }
292 cl[axis][config] = value
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400293}
294
295// Represents an attribute whose value is a single label
296type LabelAttribute struct {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400297 Value *Label
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400298
Liz Kammer9abd62d2021-05-21 08:37:59 -0400299 ConfigurableValues configurableLabels
Lukacs T. Berki1353e592021-04-30 15:35:09 +0200300}
301
Chris Parsons58852a02021-12-09 18:10:18 -0500302func (la *LabelAttribute) axisTypes() map[configurationType]bool {
303 types := map[configurationType]bool{}
304 for k := range la.ConfigurableValues {
305 if len(la.ConfigurableValues[k]) > 0 {
306 types[k.configurationType] = true
307 }
308 }
309 return types
310}
311
312// Collapse reduces the configurable axes of the label attribute to a single axis.
313// This is necessary for final writing to bp2build, as a configurable label
314// attribute can only be comprised by a single select.
315func (la *LabelAttribute) Collapse() error {
316 axisTypes := la.axisTypes()
317 _, containsOs := axisTypes[os]
318 _, containsArch := axisTypes[arch]
319 _, containsOsArch := axisTypes[osArch]
320 _, containsProductVariables := axisTypes[productVariables]
321 if containsProductVariables {
322 if containsOs || containsArch || containsOsArch {
Alixbbfd5382022-06-09 18:52:05 +0000323 if containsArch {
324 allProductVariablesAreArchVariant := true
325 for k := range la.ConfigurableValues {
326 if k.configurationType == productVariables && k.outerAxisType != arch {
327 allProductVariablesAreArchVariant = false
328 }
329 }
330 if !allProductVariablesAreArchVariant {
331 return fmt.Errorf("label attribute could not be collapsed as it has two or more unrelated axes")
332 }
333 } else {
334 return fmt.Errorf("label attribute could not be collapsed as it has two or more unrelated axes")
335 }
Chris Parsons58852a02021-12-09 18:10:18 -0500336 }
337 }
338 if (containsOs && containsArch) || (containsOsArch && (containsOs || containsArch)) {
339 // If a bool attribute has both os and arch configuration axes, the only
340 // way to successfully union their values is to increase the granularity
341 // of the configuration criteria to os_arch.
342 for osType, supportedArchs := range osToArchMap {
343 for _, supportedArch := range supportedArchs {
344 osArch := osArchString(osType, supportedArch)
345 if archOsVal := la.SelectValue(OsArchConfigurationAxis, osArch); archOsVal != nil {
346 // Do nothing, as the arch_os is explicitly defined already.
347 } else {
348 archVal := la.SelectValue(ArchConfigurationAxis, supportedArch)
349 osVal := la.SelectValue(OsConfigurationAxis, osType)
350 if osVal != nil && archVal != nil {
351 // In this case, arch takes precedence. (This fits legacy Soong behavior, as arch mutator
352 // runs after os mutator.
353 la.SetSelectValue(OsArchConfigurationAxis, osArch, *archVal)
354 } else if osVal != nil && archVal == nil {
355 la.SetSelectValue(OsArchConfigurationAxis, osArch, *osVal)
356 } else if osVal == nil && archVal != nil {
357 la.SetSelectValue(OsArchConfigurationAxis, osArch, *archVal)
358 }
359 }
360 }
361 }
362 // All os_arch values are now set. Clear os and arch axes.
363 delete(la.ConfigurableValues, ArchConfigurationAxis)
364 delete(la.ConfigurableValues, OsConfigurationAxis)
365 }
366 return nil
367}
368
Liz Kammer9abd62d2021-05-21 08:37:59 -0400369// HasConfigurableValues returns whether there are configurable values set for this label.
370func (la LabelAttribute) HasConfigurableValues() bool {
Chris Parsons58852a02021-12-09 18:10:18 -0500371 for _, selectValues := range la.ConfigurableValues {
372 if len(selectValues) > 0 {
373 return true
374 }
375 }
376 return false
Lukacs T. Berki598dd002021-05-05 09:00:01 +0200377}
378
Liz Kammer9abd62d2021-05-21 08:37:59 -0400379// SetValue sets the base, non-configured value for the Label
380func (la *LabelAttribute) SetValue(value Label) {
381 la.SetSelectValue(NoConfigAxis, "", value)
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400382}
383
Liz Kammer9abd62d2021-05-21 08:37:59 -0400384// SetSelectValue set a value for a bazel select for the given axis, config and value.
385func (la *LabelAttribute) SetSelectValue(axis ConfigurationAxis, config string, value Label) {
386 axis.validateConfig(config)
387 switch axis.configurationType {
388 case noConfig:
389 la.Value = &value
Wei Li81852ca2022-07-27 00:22:06 -0700390 case arch, os, osArch, productVariables, osAndInApex:
Liz Kammer9abd62d2021-05-21 08:37:59 -0400391 if la.ConfigurableValues == nil {
392 la.ConfigurableValues = make(configurableLabels)
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400393 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400394 la.ConfigurableValues.setValueForAxis(axis, config, &value)
395 default:
396 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
397 }
398}
399
400// SelectValue gets a value for a bazel select for the given axis and config.
Chris Parsons58852a02021-12-09 18:10:18 -0500401func (la *LabelAttribute) SelectValue(axis ConfigurationAxis, config string) *Label {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400402 axis.validateConfig(config)
403 switch axis.configurationType {
404 case noConfig:
Chris Parsons58852a02021-12-09 18:10:18 -0500405 return la.Value
Wei Li81852ca2022-07-27 00:22:06 -0700406 case arch, os, osArch, productVariables, osAndInApex:
Chris Parsons58852a02021-12-09 18:10:18 -0500407 return la.ConfigurableValues[axis][config]
Liz Kammer9abd62d2021-05-21 08:37:59 -0400408 default:
409 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
410 }
411}
412
413// SortedConfigurationAxes returns all the used ConfigurationAxis in sorted order.
414func (la *LabelAttribute) SortedConfigurationAxes() []ConfigurationAxis {
415 keys := make([]ConfigurationAxis, 0, len(la.ConfigurableValues))
416 for k := range la.ConfigurableValues {
417 keys = append(keys, k)
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400418 }
419
Liz Kammer9abd62d2021-05-21 08:37:59 -0400420 sort.Slice(keys, func(i, j int) bool { return keys[i].less(keys[j]) })
421 return keys
422}
423
Sam Delmericoc0161432022-02-25 21:34:51 +0000424// MakeLabelAttribute turns a string into a LabelAttribute
425func MakeLabelAttribute(label string) *LabelAttribute {
426 return &LabelAttribute{
427 Value: &Label{
428 Label: label,
429 },
430 }
431}
432
Liz Kammerd366c902021-06-03 13:43:01 -0400433type configToBools map[string]bool
434
435func (ctb configToBools) setValue(config string, value *bool) {
436 if value == nil {
437 if _, ok := ctb[config]; ok {
438 delete(ctb, config)
439 }
440 return
441 }
442 ctb[config] = *value
443}
444
445type configurableBools map[ConfigurationAxis]configToBools
446
447func (cb configurableBools) setValueForAxis(axis ConfigurationAxis, config string, value *bool) {
448 if cb[axis] == nil {
449 cb[axis] = make(configToBools)
450 }
451 cb[axis].setValue(config, value)
452}
453
454// BoolAttribute represents an attribute whose value is a single bool but may be configurable..
455type BoolAttribute struct {
456 Value *bool
457
458 ConfigurableValues configurableBools
459}
460
461// HasConfigurableValues returns whether there are configurable values for this attribute.
462func (ba BoolAttribute) HasConfigurableValues() bool {
Chris Parsons58852a02021-12-09 18:10:18 -0500463 for _, cfgToBools := range ba.ConfigurableValues {
464 if len(cfgToBools) > 0 {
465 return true
466 }
467 }
468 return false
Liz Kammerd366c902021-06-03 13:43:01 -0400469}
470
Liz Kammerdfeb1202022-05-13 17:20:20 -0400471// SetValue sets value for the no config axis
472func (ba *BoolAttribute) SetValue(value *bool) {
473 ba.SetSelectValue(NoConfigAxis, "", value)
474}
475
Liz Kammerd366c902021-06-03 13:43:01 -0400476// SetSelectValue sets value for the given axis/config.
477func (ba *BoolAttribute) SetSelectValue(axis ConfigurationAxis, config string, value *bool) {
478 axis.validateConfig(config)
479 switch axis.configurationType {
480 case noConfig:
481 ba.Value = value
Wei Li81852ca2022-07-27 00:22:06 -0700482 case arch, os, osArch, productVariables, osAndInApex:
Liz Kammerd366c902021-06-03 13:43:01 -0400483 if ba.ConfigurableValues == nil {
484 ba.ConfigurableValues = make(configurableBools)
485 }
486 ba.ConfigurableValues.setValueForAxis(axis, config, value)
487 default:
488 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
489 }
490}
491
Chris Parsons58852a02021-12-09 18:10:18 -0500492// ToLabelListAttribute creates and returns a LabelListAttribute from this
493// bool attribute, where each bool in this attribute corresponds to a
494// label list value in the resultant attribute.
495func (ba *BoolAttribute) ToLabelListAttribute(falseVal LabelList, trueVal LabelList) (LabelListAttribute, error) {
496 getLabelList := func(boolPtr *bool) LabelList {
497 if boolPtr == nil {
498 return LabelList{nil, nil}
499 } else if *boolPtr {
500 return trueVal
501 } else {
502 return falseVal
503 }
504 }
505
506 mainVal := getLabelList(ba.Value)
507 if !ba.HasConfigurableValues() {
508 return MakeLabelListAttribute(mainVal), nil
509 }
510
511 result := LabelListAttribute{}
512 if err := ba.Collapse(); err != nil {
513 return result, err
514 }
515
516 for axis, configToBools := range ba.ConfigurableValues {
517 if len(configToBools) < 1 {
518 continue
519 }
520 for config, boolPtr := range configToBools {
521 val := getLabelList(&boolPtr)
522 if !val.Equals(mainVal) {
523 result.SetSelectValue(axis, config, val)
524 }
525 }
526 result.SetSelectValue(axis, ConditionsDefaultConfigKey, mainVal)
527 }
528
529 return result, nil
530}
531
532// Collapse reduces the configurable axes of the boolean attribute to a single axis.
533// This is necessary for final writing to bp2build, as a configurable boolean
534// attribute can only be comprised by a single select.
535func (ba *BoolAttribute) Collapse() error {
536 axisTypes := ba.axisTypes()
537 _, containsOs := axisTypes[os]
538 _, containsArch := axisTypes[arch]
539 _, containsOsArch := axisTypes[osArch]
540 _, containsProductVariables := axisTypes[productVariables]
541 if containsProductVariables {
542 if containsOs || containsArch || containsOsArch {
543 return fmt.Errorf("boolean attribute could not be collapsed as it has two or more unrelated axes")
544 }
545 }
546 if (containsOs && containsArch) || (containsOsArch && (containsOs || containsArch)) {
547 // If a bool attribute has both os and arch configuration axes, the only
548 // way to successfully union their values is to increase the granularity
549 // of the configuration criteria to os_arch.
550 for osType, supportedArchs := range osToArchMap {
551 for _, supportedArch := range supportedArchs {
552 osArch := osArchString(osType, supportedArch)
553 if archOsVal := ba.SelectValue(OsArchConfigurationAxis, osArch); archOsVal != nil {
554 // Do nothing, as the arch_os is explicitly defined already.
555 } else {
556 archVal := ba.SelectValue(ArchConfigurationAxis, supportedArch)
557 osVal := ba.SelectValue(OsConfigurationAxis, osType)
558 if osVal != nil && archVal != nil {
559 // In this case, arch takes precedence. (This fits legacy Soong behavior, as arch mutator
560 // runs after os mutator.
561 ba.SetSelectValue(OsArchConfigurationAxis, osArch, archVal)
562 } else if osVal != nil && archVal == nil {
563 ba.SetSelectValue(OsArchConfigurationAxis, osArch, osVal)
564 } else if osVal == nil && archVal != nil {
565 ba.SetSelectValue(OsArchConfigurationAxis, osArch, archVal)
566 }
567 }
568 }
569 }
570 // All os_arch values are now set. Clear os and arch axes.
571 delete(ba.ConfigurableValues, ArchConfigurationAxis)
572 delete(ba.ConfigurableValues, OsConfigurationAxis)
573 // Verify post-condition; this should never fail, provided no additional
574 // axes are introduced.
575 if len(ba.ConfigurableValues) > 1 {
Liz Kammer07e106f2022-01-13 17:00:10 -0500576 panic(fmt.Errorf("error in collapsing attribute: %#v", ba))
Chris Parsons58852a02021-12-09 18:10:18 -0500577 }
578 }
579 return nil
580}
581
582func (ba *BoolAttribute) axisTypes() map[configurationType]bool {
583 types := map[configurationType]bool{}
584 for k := range ba.ConfigurableValues {
585 if len(ba.ConfigurableValues[k]) > 0 {
586 types[k.configurationType] = true
587 }
588 }
589 return types
590}
591
Liz Kammerd366c902021-06-03 13:43:01 -0400592// SelectValue gets the value for the given axis/config.
593func (ba BoolAttribute) SelectValue(axis ConfigurationAxis, config string) *bool {
594 axis.validateConfig(config)
595 switch axis.configurationType {
596 case noConfig:
597 return ba.Value
Wei Li81852ca2022-07-27 00:22:06 -0700598 case arch, os, osArch, productVariables, osAndInApex:
Liz Kammerd366c902021-06-03 13:43:01 -0400599 if v, ok := ba.ConfigurableValues[axis][config]; ok {
600 return &v
601 } else {
602 return nil
603 }
604 default:
605 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
606 }
607}
608
609// SortedConfigurationAxes returns all the used ConfigurationAxis in sorted order.
610func (ba *BoolAttribute) SortedConfigurationAxes() []ConfigurationAxis {
611 keys := make([]ConfigurationAxis, 0, len(ba.ConfigurableValues))
612 for k := range ba.ConfigurableValues {
613 keys = append(keys, k)
614 }
615
616 sort.Slice(keys, func(i, j int) bool { return keys[i].less(keys[j]) })
617 return keys
618}
619
Liz Kammer9abd62d2021-05-21 08:37:59 -0400620// labelListSelectValues supports config-specific label_list typed Bazel attribute values.
621type labelListSelectValues map[string]LabelList
622
Liz Kammer12615db2021-09-28 09:19:17 -0400623func (ll labelListSelectValues) addSelects(label labelSelectValues) {
624 for k, v := range label {
625 if label == nil {
626 continue
627 }
628 l := ll[k]
629 (&l).Add(v)
630 ll[k] = l
631 }
632}
633
Chris Parsons77acf2e2021-12-03 17:27:16 -0500634func (ll labelListSelectValues) appendSelects(other labelListSelectValues, forceSpecifyEmptyList bool) {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400635 for k, v := range other {
636 l := ll[k]
Chris Parsons77acf2e2021-12-03 17:27:16 -0500637 if forceSpecifyEmptyList && l.IsNil() && !v.IsNil() {
638 l.Includes = []Label{}
639 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400640 (&l).Append(v)
641 ll[k] = l
642 }
643}
644
645// HasConfigurableValues returns whether there are configurable values within this set of selects.
646func (ll labelListSelectValues) HasConfigurableValues() bool {
647 for _, v := range ll {
Chris Parsons51f8c392021-08-03 21:01:05 -0400648 if v.Includes != nil {
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400649 return true
650 }
Rupert Shuttleworth22cd2eb2021-05-27 02:15:54 -0400651 }
652 return false
653}
654
Jingwen Chen07027912021-03-15 06:02:43 -0400655// LabelListAttribute is used to represent a list of Bazel labels as an
656// attribute.
657type LabelListAttribute struct {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400658 // The non-configured attribute label list Value. Required.
Jingwen Chen07027912021-03-15 06:02:43 -0400659 Value LabelList
660
Liz Kammer9abd62d2021-05-21 08:37:59 -0400661 // The configured attribute label list Values. Optional
662 // a map of independent configurability axes
663 ConfigurableValues configurableLabelLists
Chris Parsons51f8c392021-08-03 21:01:05 -0400664
665 // If true, differentiate between "nil" and "empty" list. nil means that
666 // this attribute should not be specified at all, and "empty" means that
667 // the attribute should be explicitly specified as an empty list.
668 // This mode facilitates use of attribute defaults: an empty list should
669 // override the default.
670 ForceSpecifyEmptyList bool
Jingwen Chen58ff6802021-11-17 12:14:41 +0000671
672 // If true, signal the intent to the code generator to emit all select keys,
673 // even if the Includes list for that key is empty. This mode facilitates
674 // specific select statements where an empty list for a non-default select
675 // key has a meaning.
676 EmitEmptyList bool
Zi Wang9f609db2023-01-04 11:06:54 -0800677
678 // If a property has struct tag "variant_prepend", this value should
679 // be set to True, so that when bp2build generates BUILD.bazel, variant
680 // properties(select ...) come before general properties.
681 Prepend bool
Liz Kammer9abd62d2021-05-21 08:37:59 -0400682}
Jingwen Chen91220d72021-03-24 02:18:33 -0400683
Liz Kammer9abd62d2021-05-21 08:37:59 -0400684type configurableLabelLists map[ConfigurationAxis]labelListSelectValues
685
686func (cll configurableLabelLists) setValueForAxis(axis ConfigurationAxis, config string, list LabelList) {
687 if list.IsNil() {
688 if _, ok := cll[axis][config]; ok {
689 delete(cll[axis], config)
690 }
691 return
692 }
693 if cll[axis] == nil {
694 cll[axis] = make(labelListSelectValues)
695 }
696
697 cll[axis][config] = list
698}
699
Chris Parsons77acf2e2021-12-03 17:27:16 -0500700func (cll configurableLabelLists) Append(other configurableLabelLists, forceSpecifyEmptyList bool) {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400701 for axis, otherSelects := range other {
702 selects := cll[axis]
703 if selects == nil {
704 selects = make(labelListSelectValues, len(otherSelects))
705 }
Chris Parsons77acf2e2021-12-03 17:27:16 -0500706 selects.appendSelects(otherSelects, forceSpecifyEmptyList)
Liz Kammer9abd62d2021-05-21 08:37:59 -0400707 cll[axis] = selects
708 }
Jingwen Chen07027912021-03-15 06:02:43 -0400709}
710
Chris Parsons77acf2e2021-12-03 17:27:16 -0500711func (lla *LabelListAttribute) Clone() *LabelListAttribute {
712 result := &LabelListAttribute{ForceSpecifyEmptyList: lla.ForceSpecifyEmptyList}
713 return result.Append(*lla)
714}
715
Jingwen Chen07027912021-03-15 06:02:43 -0400716// MakeLabelListAttribute initializes a LabelListAttribute with the non-arch specific value.
717func MakeLabelListAttribute(value LabelList) LabelListAttribute {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400718 return LabelListAttribute{
719 Value: value,
720 ConfigurableValues: make(configurableLabelLists),
721 }
722}
723
Cole Faust53b62092022-05-12 15:37:02 -0700724// MakeSingleLabelListAttribute initializes a LabelListAttribute as a non-arch specific list with 1 element, the given Label.
725func MakeSingleLabelListAttribute(value Label) LabelListAttribute {
726 return MakeLabelListAttribute(MakeLabelList([]Label{value}))
727}
728
Liz Kammer9abd62d2021-05-21 08:37:59 -0400729func (lla *LabelListAttribute) SetValue(list LabelList) {
730 lla.SetSelectValue(NoConfigAxis, "", list)
731}
732
733// SetSelectValue set a value for a bazel select for the given axis, config and value.
734func (lla *LabelListAttribute) SetSelectValue(axis ConfigurationAxis, config string, list LabelList) {
735 axis.validateConfig(config)
736 switch axis.configurationType {
737 case noConfig:
738 lla.Value = list
Vinh Tran85fb07c2022-09-16 16:17:48 -0400739 case arch, os, osArch, productVariables, osAndInApex, inApex:
Liz Kammer9abd62d2021-05-21 08:37:59 -0400740 if lla.ConfigurableValues == nil {
741 lla.ConfigurableValues = make(configurableLabelLists)
742 }
743 lla.ConfigurableValues.setValueForAxis(axis, config, list)
744 default:
745 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
746 }
747}
748
749// SelectValue gets a value for a bazel select for the given axis and config.
750func (lla *LabelListAttribute) SelectValue(axis ConfigurationAxis, config string) LabelList {
751 axis.validateConfig(config)
752 switch axis.configurationType {
753 case noConfig:
754 return lla.Value
Vinh Tran85fb07c2022-09-16 16:17:48 -0400755 case arch, os, osArch, productVariables, osAndInApex, inApex:
Cole Faustc843b992022-08-02 18:06:50 -0700756 return lla.ConfigurableValues[axis][config]
Liz Kammer9abd62d2021-05-21 08:37:59 -0400757 default:
758 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
759 }
760}
761
762// SortedConfigurationAxes returns all the used ConfigurationAxis in sorted order.
763func (lla *LabelListAttribute) SortedConfigurationAxes() []ConfigurationAxis {
764 keys := make([]ConfigurationAxis, 0, len(lla.ConfigurableValues))
765 for k := range lla.ConfigurableValues {
766 keys = append(keys, k)
767 }
768
769 sort.Slice(keys, func(i, j int) bool { return keys[i].less(keys[j]) })
770 return keys
Jingwen Chen07027912021-03-15 06:02:43 -0400771}
772
Jingwen Chened9c17d2021-04-13 07:14:55 +0000773// Append all values, including os and arch specific ones, from another
Chris Parsons77acf2e2021-12-03 17:27:16 -0500774// LabelListAttribute to this LabelListAttribute. Returns this LabelListAttribute.
775func (lla *LabelListAttribute) Append(other LabelListAttribute) *LabelListAttribute {
776 forceSpecifyEmptyList := lla.ForceSpecifyEmptyList || other.ForceSpecifyEmptyList
777 if forceSpecifyEmptyList && lla.Value.IsNil() && !other.Value.IsNil() {
Chris Parsons51f8c392021-08-03 21:01:05 -0400778 lla.Value.Includes = []Label{}
779 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400780 lla.Value.Append(other.Value)
781 if lla.ConfigurableValues == nil {
782 lla.ConfigurableValues = make(configurableLabelLists)
Jingwen Chen63930982021-03-24 10:04:33 -0400783 }
Chris Parsons77acf2e2021-12-03 17:27:16 -0500784 lla.ConfigurableValues.Append(other.ConfigurableValues, forceSpecifyEmptyList)
785 return lla
Jingwen Chen63930982021-03-24 10:04:33 -0400786}
787
Liz Kammer12615db2021-09-28 09:19:17 -0400788// Add inserts the labels for each axis of LabelAttribute at the end of corresponding axis's
789// LabelList within the LabelListAttribute
790func (lla *LabelListAttribute) Add(label *LabelAttribute) {
791 if label == nil {
792 return
793 }
794
795 lla.Value.Add(label.Value)
796 if lla.ConfigurableValues == nil && label.ConfigurableValues != nil {
797 lla.ConfigurableValues = make(configurableLabelLists)
798 }
799 for axis, _ := range label.ConfigurableValues {
800 if _, exists := lla.ConfigurableValues[axis]; !exists {
801 lla.ConfigurableValues[axis] = make(labelListSelectValues)
802 }
803 lla.ConfigurableValues[axis].addSelects(label.ConfigurableValues[axis])
804 }
805}
806
Liz Kammer9abd62d2021-05-21 08:37:59 -0400807// HasConfigurableValues returns true if the attribute contains axis-specific label list values.
808func (lla LabelListAttribute) HasConfigurableValues() bool {
Chris Parsons58852a02021-12-09 18:10:18 -0500809 for _, selectValues := range lla.ConfigurableValues {
810 if len(selectValues) > 0 {
811 return true
812 }
813 }
814 return false
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -0400815}
816
Chris Parsons69fa9f92021-07-13 11:47:44 -0400817// IsEmpty returns true if the attribute has no values under any configuration.
818func (lla LabelListAttribute) IsEmpty() bool {
819 if len(lla.Value.Includes) > 0 {
820 return false
821 }
822 for axis, _ := range lla.ConfigurableValues {
823 if lla.ConfigurableValues[axis].HasConfigurableValues() {
824 return false
825 }
826 }
827 return true
828}
829
Liz Kammer54309532021-12-14 12:21:22 -0500830// IsNil returns true if the attribute has not been set for any configuration.
831func (lla LabelListAttribute) IsNil() bool {
832 if lla.Value.Includes != nil {
833 return false
834 }
835 return !lla.HasConfigurableValues()
836}
837
838// Exclude for the given axis, config, removes Includes in labelList from Includes and appends them
839// to Excludes. This is to special case any excludes that are not specified in a bp file but need to
840// be removed, e.g. if they could cause duplicate element failures.
841func (lla *LabelListAttribute) Exclude(axis ConfigurationAxis, config string, labelList LabelList) {
842 val := lla.SelectValue(axis, config)
843 newList := SubtractBazelLabelList(val, labelList)
844 newList.Excludes = append(newList.Excludes, labelList.Includes...)
845 lla.SetSelectValue(axis, config, newList)
846}
847
Liz Kammer74deed42021-06-02 13:02:03 -0400848// ResolveExcludes handles excludes across the various axes, ensuring that items are removed from
849// the base value and included in default values as appropriate.
850func (lla *LabelListAttribute) ResolveExcludes() {
Liz Kammerffc17e42022-11-23 09:42:05 -0500851 // If there are OsAndInApexAxis, we need to use
852 // * includes from the OS & in APEX Axis for non-Android configs for libraries that need to be
853 // included in non-Android OSes
854 // * excludes from the OS Axis for non-Android configs, to exclude libraries that should _not_
855 // be included in the non-Android OSes
856 if _, ok := lla.ConfigurableValues[OsAndInApexAxis]; ok {
857 inApexLabels := lla.ConfigurableValues[OsAndInApexAxis][ConditionsDefaultConfigKey]
858 for config, labels := range lla.ConfigurableValues[OsConfigurationAxis] {
859 // OsAndroid has already handled its excludes.
860 // We only need to copy the excludes from other arches, so if there are none, skip it.
861 if config == OsAndroid || len(labels.Excludes) == 0 {
862 continue
863 }
864 lla.ConfigurableValues[OsAndInApexAxis][config] = LabelList{
865 Includes: inApexLabels.Includes,
866 Excludes: labels.Excludes,
867 }
868 }
869 }
870
Liz Kammer74deed42021-06-02 13:02:03 -0400871 for axis, configToLabels := range lla.ConfigurableValues {
872 baseLabels := lla.Value.deepCopy()
873 for config, val := range configToLabels {
874 // Exclude config-specific excludes from base value
875 lla.Value = SubtractBazelLabelList(lla.Value, LabelList{Includes: val.Excludes})
876
877 // add base values to config specific to add labels excluded by others in this axis
878 // then remove all config-specific excludes
879 allLabels := baseLabels.deepCopy()
880 allLabels.Append(val)
881 lla.ConfigurableValues[axis][config] = SubtractBazelLabelList(allLabels, LabelList{Includes: val.Excludes})
882 }
883
884 // After going through all configs, delete the duplicates in the config
885 // values that are already in the base Value.
886 for config, val := range configToLabels {
887 lla.ConfigurableValues[axis][config] = SubtractBazelLabelList(val, lla.Value)
888 }
889
Jingwen Chen9af49a42021-11-02 10:27:17 +0000890 // Now that the Value list is finalized for this axis, compare it with
891 // the original list, and union the difference with the default
892 // condition for the axis.
893 difference := SubtractBazelLabelList(baseLabels, lla.Value)
894 existingDefaults := lla.ConfigurableValues[axis][ConditionsDefaultConfigKey]
895 existingDefaults.Append(difference)
896 lla.ConfigurableValues[axis][ConditionsDefaultConfigKey] = FirstUniqueBazelLabelList(existingDefaults)
Liz Kammer74deed42021-06-02 13:02:03 -0400897
898 // if everything ends up without includes, just delete the axis
899 if !lla.ConfigurableValues[axis].HasConfigurableValues() {
900 delete(lla.ConfigurableValues, axis)
901 }
902 }
903}
904
Sam Delmericoc1130dc2022-08-25 14:43:54 -0400905// Partition splits a LabelListAttribute into two LabelListAttributes depending
906// on the return value of the predicate.
907// This function preserves the Includes and Excludes, but it does not provide
908// that information to the partition function.
909func (lla LabelListAttribute) Partition(predicate func(label Label) bool) (LabelListAttribute, LabelListAttribute) {
910 predicated := LabelListAttribute{}
911 unpredicated := LabelListAttribute{}
912
913 valuePartitionTrue, valuePartitionFalse := lla.Value.Partition(predicate)
914 predicated.SetValue(valuePartitionTrue)
915 unpredicated.SetValue(valuePartitionFalse)
916
917 for axis, selectValueLabelLists := range lla.ConfigurableValues {
918 for config, labelList := range selectValueLabelLists {
919 configPredicated, configUnpredicated := labelList.Partition(predicate)
920 predicated.SetSelectValue(axis, config, configPredicated)
921 unpredicated.SetSelectValue(axis, config, configUnpredicated)
922 }
923 }
924
925 return predicated, unpredicated
926}
927
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400928// OtherModuleContext is a limited context that has methods with information about other modules.
929type OtherModuleContext interface {
930 ModuleFromName(name string) (blueprint.Module, bool)
931 OtherModuleType(m blueprint.Module) string
932 OtherModuleName(m blueprint.Module) string
933 OtherModuleDir(m blueprint.Module) string
934 ModuleErrorf(fmt string, args ...interface{})
935}
936
937// LabelMapper is a function that takes a OtherModuleContext and returns a (potentially changed)
938// label and whether it was changed.
Liz Kammer12615db2021-09-28 09:19:17 -0400939type LabelMapper func(OtherModuleContext, Label) (string, bool)
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400940
941// LabelPartition contains descriptions of a partition for labels
942type LabelPartition struct {
943 // Extensions to include in this partition
944 Extensions []string
945 // LabelMapper is a function that can map a label to a new label, and indicate whether to include
946 // the mapped label in the partition
947 LabelMapper LabelMapper
948 // Whether to store files not included in any other partition in a group of LabelPartitions
949 // Only one partition in a group of LabelPartitions can enabled Keep_remainder
950 Keep_remainder bool
951}
952
953// LabelPartitions is a map of partition name to a LabelPartition describing the elements of the
954// partition
955type LabelPartitions map[string]LabelPartition
956
957// filter returns a pointer to a label if the label should be included in the partition or nil if
958// not.
959func (lf LabelPartition) filter(ctx OtherModuleContext, label Label) *Label {
960 if lf.LabelMapper != nil {
Liz Kammer12615db2021-09-28 09:19:17 -0400961 if newLabel, changed := lf.LabelMapper(ctx, label); changed {
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400962 return &Label{newLabel, label.OriginalModuleName}
963 }
964 }
965 for _, ext := range lf.Extensions {
966 if strings.HasSuffix(label.Label, ext) {
967 return &label
968 }
969 }
970
971 return nil
972}
973
974// PartitionToLabelListAttribute is map of partition name to a LabelListAttribute
975type PartitionToLabelListAttribute map[string]LabelListAttribute
976
977type partitionToLabelList map[string]*LabelList
978
979func (p partitionToLabelList) appendIncludes(partition string, label Label) {
980 if _, ok := p[partition]; !ok {
981 p[partition] = &LabelList{}
982 }
983 p[partition].Includes = append(p[partition].Includes, label)
984}
985
986func (p partitionToLabelList) excludes(partition string, excludes []Label) {
987 if _, ok := p[partition]; !ok {
988 p[partition] = &LabelList{}
989 }
990 p[partition].Excludes = excludes
991}
992
993// PartitionLabelListAttribute partitions a LabelListAttribute into the requested partitions
994func PartitionLabelListAttribute(ctx OtherModuleContext, lla *LabelListAttribute, partitions LabelPartitions) PartitionToLabelListAttribute {
995 ret := PartitionToLabelListAttribute{}
996 var partitionNames []string
997 // Stored as a pointer to distinguish nil (no remainder partition) from empty string partition
998 var remainderPartition *string
999 for p, f := range partitions {
1000 partitionNames = append(partitionNames, p)
1001 if f.Keep_remainder {
1002 if remainderPartition != nil {
1003 panic("only one partition can store the remainder")
1004 }
1005 // If we take the address of p in a loop, we'll end up with the last value of p in
1006 // remainderPartition, we want the requested partition
1007 capturePartition := p
1008 remainderPartition = &capturePartition
1009 }
1010 }
1011
1012 partitionLabelList := func(axis ConfigurationAxis, config string) {
1013 value := lla.SelectValue(axis, config)
1014 partitionToLabels := partitionToLabelList{}
1015 for _, item := range value.Includes {
1016 wasFiltered := false
1017 var inPartition *string
1018 for partition, f := range partitions {
1019 filtered := f.filter(ctx, item)
1020 if filtered == nil {
1021 // did not match this filter, keep looking
1022 continue
1023 }
1024 wasFiltered = true
1025 partitionToLabels.appendIncludes(partition, *filtered)
1026 // don't need to check other partitions if this filter used the item,
1027 // continue checking if mapped to another name
1028 if *filtered == item {
1029 if inPartition != nil {
1030 ctx.ModuleErrorf("%q was found in multiple partitions: %q, %q", item.Label, *inPartition, partition)
1031 }
1032 capturePartition := partition
1033 inPartition = &capturePartition
1034 }
1035 }
1036
1037 // if not specified in a partition, add to remainder partition if one exists
1038 if !wasFiltered && remainderPartition != nil {
1039 partitionToLabels.appendIncludes(*remainderPartition, item)
1040 }
1041 }
1042
1043 // ensure empty lists are maintained
1044 if value.Excludes != nil {
1045 for _, partition := range partitionNames {
1046 partitionToLabels.excludes(partition, value.Excludes)
1047 }
1048 }
1049
1050 for partition, list := range partitionToLabels {
1051 val := ret[partition]
1052 (&val).SetSelectValue(axis, config, *list)
1053 ret[partition] = val
1054 }
1055 }
1056
1057 partitionLabelList(NoConfigAxis, "")
1058 for axis, configToList := range lla.ConfigurableValues {
1059 for config, _ := range configToList {
1060 partitionLabelList(axis, config)
1061 }
1062 }
1063 return ret
1064}
1065
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +00001066// StringAttribute corresponds to the string Bazel attribute type with
1067// support for additional metadata, like configurations.
1068type StringAttribute struct {
1069 // The base value of the string attribute.
1070 Value *string
1071
1072 // The configured attribute label list Values. Optional
1073 // a map of independent configurability axes
1074 ConfigurableValues configurableStrings
1075}
1076
1077type configurableStrings map[ConfigurationAxis]stringSelectValues
1078
1079func (cs configurableStrings) setValueForAxis(axis ConfigurationAxis, config string, str *string) {
1080 if cs[axis] == nil {
1081 cs[axis] = make(stringSelectValues)
1082 }
1083 var v = ""
1084 if str != nil {
1085 v = *str
1086 }
1087 cs[axis][config] = v
1088}
1089
1090type stringSelectValues map[string]string
1091
1092// HasConfigurableValues returns true if the attribute contains axis-specific string values.
1093func (sa StringAttribute) HasConfigurableValues() bool {
1094 for _, selectValues := range sa.ConfigurableValues {
1095 if len(selectValues) > 0 {
1096 return true
1097 }
1098 }
1099 return false
1100}
1101
1102// SetSelectValue set a value for a bazel select for the given axis, config and value.
1103func (sa *StringAttribute) SetSelectValue(axis ConfigurationAxis, config string, str *string) {
1104 axis.validateConfig(config)
1105 switch axis.configurationType {
1106 case noConfig:
1107 sa.Value = str
1108 case arch, os, osArch, productVariables:
1109 if sa.ConfigurableValues == nil {
1110 sa.ConfigurableValues = make(configurableStrings)
1111 }
1112 sa.ConfigurableValues.setValueForAxis(axis, config, str)
1113 default:
1114 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
1115 }
1116}
1117
1118// SelectValue gets a value for a bazel select for the given axis and config.
1119func (sa *StringAttribute) SelectValue(axis ConfigurationAxis, config string) *string {
1120 axis.validateConfig(config)
1121 switch axis.configurationType {
1122 case noConfig:
1123 return sa.Value
1124 case arch, os, osArch, productVariables:
1125 if v, ok := sa.ConfigurableValues[axis][config]; ok {
1126 return &v
1127 } else {
1128 return nil
1129 }
1130 default:
1131 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
1132 }
1133}
1134
1135// SortedConfigurationAxes returns all the used ConfigurationAxis in sorted order.
1136func (sa *StringAttribute) SortedConfigurationAxes() []ConfigurationAxis {
1137 keys := make([]ConfigurationAxis, 0, len(sa.ConfigurableValues))
1138 for k := range sa.ConfigurableValues {
1139 keys = append(keys, k)
1140 }
1141
1142 sort.Slice(keys, func(i, j int) bool { return keys[i].less(keys[j]) })
1143 return keys
1144}
1145
1146// Collapse reduces the configurable axes of the string attribute to a single axis.
1147// This is necessary for final writing to bp2build, as a configurable string
1148// attribute can only be comprised by a single select.
1149func (sa *StringAttribute) Collapse() error {
1150 axisTypes := sa.axisTypes()
1151 _, containsOs := axisTypes[os]
1152 _, containsArch := axisTypes[arch]
1153 _, containsOsArch := axisTypes[osArch]
1154 _, containsProductVariables := axisTypes[productVariables]
1155 if containsProductVariables {
1156 if containsOs || containsArch || containsOsArch {
1157 return fmt.Errorf("boolean attribute could not be collapsed as it has two or more unrelated axes")
1158 }
1159 }
1160 if (containsOs && containsArch) || (containsOsArch && (containsOs || containsArch)) {
1161 // If a bool attribute has both os and arch configuration axes, the only
1162 // way to successfully union their values is to increase the granularity
1163 // of the configuration criteria to os_arch.
1164 for osType, supportedArchs := range osToArchMap {
1165 for _, supportedArch := range supportedArchs {
1166 osArch := osArchString(osType, supportedArch)
1167 if archOsVal := sa.SelectValue(OsArchConfigurationAxis, osArch); archOsVal != nil {
1168 // Do nothing, as the arch_os is explicitly defined already.
1169 } else {
1170 archVal := sa.SelectValue(ArchConfigurationAxis, supportedArch)
1171 osVal := sa.SelectValue(OsConfigurationAxis, osType)
1172 if osVal != nil && archVal != nil {
1173 // In this case, arch takes precedence. (This fits legacy Soong behavior, as arch mutator
1174 // runs after os mutator.
1175 sa.SetSelectValue(OsArchConfigurationAxis, osArch, archVal)
1176 } else if osVal != nil && archVal == nil {
1177 sa.SetSelectValue(OsArchConfigurationAxis, osArch, osVal)
1178 } else if osVal == nil && archVal != nil {
1179 sa.SetSelectValue(OsArchConfigurationAxis, osArch, archVal)
1180 }
1181 }
1182 }
1183 }
1184 // All os_arch values are now set. Clear os and arch axes.
1185 delete(sa.ConfigurableValues, ArchConfigurationAxis)
1186 delete(sa.ConfigurableValues, OsConfigurationAxis)
1187 // Verify post-condition; this should never fail, provided no additional
1188 // axes are introduced.
1189 if len(sa.ConfigurableValues) > 1 {
1190 panic(fmt.Errorf("error in collapsing attribute: %#v", sa))
1191 }
1192 }
1193 return nil
1194}
1195
1196func (sa *StringAttribute) axisTypes() map[configurationType]bool {
1197 types := map[configurationType]bool{}
1198 for k := range sa.ConfigurableValues {
1199 if strs := sa.ConfigurableValues[k]; len(strs) > 0 {
1200 types[k.configurationType] = true
1201 }
1202 }
1203 return types
1204}
1205
Jingwen Chen5d864492021-02-24 07:20:12 -05001206// StringListAttribute corresponds to the string_list Bazel attribute type with
1207// support for additional metadata, like configurations.
1208type StringListAttribute struct {
1209 // The base value of the string list attribute.
1210 Value []string
1211
Liz Kammer9abd62d2021-05-21 08:37:59 -04001212 // The configured attribute label list Values. Optional
1213 // a map of independent configurability axes
1214 ConfigurableValues configurableStringLists
Zi Wang1cb11802022-12-09 16:08:54 -08001215
1216 // If a property has struct tag "variant_prepend", this value should
1217 // be set to True, so that when bp2build generates BUILD.bazel, variant
1218 // properties(select ...) come before general properties.
1219 Prepend bool
Liz Kammer9abd62d2021-05-21 08:37:59 -04001220}
Jingwen Chenc1c26502021-04-05 10:35:13 +00001221
Spandan Das4238c652022-09-09 01:38:47 +00001222// IsEmpty returns true if the attribute has no values under any configuration.
1223func (sla StringListAttribute) IsEmpty() bool {
1224 return len(sla.Value) == 0 && !sla.HasConfigurableValues()
1225}
1226
Liz Kammer9abd62d2021-05-21 08:37:59 -04001227type configurableStringLists map[ConfigurationAxis]stringListSelectValues
Liz Kammer6fd7b3f2021-05-06 13:54:29 -04001228
Liz Kammer9abd62d2021-05-21 08:37:59 -04001229func (csl configurableStringLists) Append(other configurableStringLists) {
1230 for axis, otherSelects := range other {
1231 selects := csl[axis]
1232 if selects == nil {
1233 selects = make(stringListSelectValues, len(otherSelects))
1234 }
1235 selects.appendSelects(otherSelects)
1236 csl[axis] = selects
1237 }
1238}
1239
1240func (csl configurableStringLists) setValueForAxis(axis ConfigurationAxis, config string, list []string) {
1241 if csl[axis] == nil {
1242 csl[axis] = make(stringListSelectValues)
1243 }
1244 csl[axis][config] = list
1245}
1246
1247type stringListSelectValues map[string][]string
1248
1249func (sl stringListSelectValues) appendSelects(other stringListSelectValues) {
1250 for k, v := range other {
1251 sl[k] = append(sl[k], v...)
1252 }
1253}
1254
1255func (sl stringListSelectValues) hasConfigurableValues(other stringListSelectValues) bool {
1256 for _, val := range sl {
1257 if len(val) > 0 {
1258 return true
1259 }
1260 }
1261 return false
Jingwen Chen5d864492021-02-24 07:20:12 -05001262}
1263
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001264// MakeStringListAttribute initializes a StringListAttribute with the non-arch specific value.
1265func MakeStringListAttribute(value []string) StringListAttribute {
1266 // NOTE: These strings are not necessarily unique or sorted.
Liz Kammer9abd62d2021-05-21 08:37:59 -04001267 return StringListAttribute{
1268 Value: value,
1269 ConfigurableValues: make(configurableStringLists),
Jingwen Chen91220d72021-03-24 02:18:33 -04001270 }
1271}
1272
Liz Kammer9abd62d2021-05-21 08:37:59 -04001273// HasConfigurableValues returns true if the attribute contains axis-specific string_list values.
1274func (sla StringListAttribute) HasConfigurableValues() bool {
Chris Parsons58852a02021-12-09 18:10:18 -05001275 for _, selectValues := range sla.ConfigurableValues {
1276 if len(selectValues) > 0 {
1277 return true
1278 }
1279 }
1280 return false
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -04001281}
1282
Jingwen Chened9c17d2021-04-13 07:14:55 +00001283// Append appends all values, including os and arch specific ones, from another
1284// StringListAttribute to this StringListAttribute
Chris Parsons77acf2e2021-12-03 17:27:16 -05001285func (sla *StringListAttribute) Append(other StringListAttribute) *StringListAttribute {
Liz Kammer9abd62d2021-05-21 08:37:59 -04001286 sla.Value = append(sla.Value, other.Value...)
1287 if sla.ConfigurableValues == nil {
1288 sla.ConfigurableValues = make(configurableStringLists)
1289 }
1290 sla.ConfigurableValues.Append(other.ConfigurableValues)
Chris Parsons77acf2e2021-12-03 17:27:16 -05001291 return sla
1292}
1293
1294func (sla *StringListAttribute) Clone() *StringListAttribute {
1295 result := &StringListAttribute{}
1296 return result.Append(*sla)
Liz Kammer9abd62d2021-05-21 08:37:59 -04001297}
1298
1299// SetSelectValue set a value for a bazel select for the given axis, config and value.
1300func (sla *StringListAttribute) SetSelectValue(axis ConfigurationAxis, config string, list []string) {
1301 axis.validateConfig(config)
1302 switch axis.configurationType {
1303 case noConfig:
1304 sla.Value = list
Wei Li81852ca2022-07-27 00:22:06 -07001305 case arch, os, osArch, productVariables, osAndInApex:
Liz Kammer9abd62d2021-05-21 08:37:59 -04001306 if sla.ConfigurableValues == nil {
1307 sla.ConfigurableValues = make(configurableStringLists)
1308 }
1309 sla.ConfigurableValues.setValueForAxis(axis, config, list)
1310 default:
1311 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
1312 }
1313}
1314
1315// SelectValue gets a value for a bazel select for the given axis and config.
1316func (sla *StringListAttribute) SelectValue(axis ConfigurationAxis, config string) []string {
1317 axis.validateConfig(config)
1318 switch axis.configurationType {
1319 case noConfig:
1320 return sla.Value
Wei Li81852ca2022-07-27 00:22:06 -07001321 case arch, os, osArch, productVariables, osAndInApex:
Liz Kammer9abd62d2021-05-21 08:37:59 -04001322 return sla.ConfigurableValues[axis][config]
1323 default:
1324 panic(fmt.Errorf("Unrecognized ConfigurationAxis %s", axis))
1325 }
1326}
1327
1328// SortedConfigurationAxes returns all the used ConfigurationAxis in sorted order.
1329func (sla *StringListAttribute) SortedConfigurationAxes() []ConfigurationAxis {
1330 keys := make([]ConfigurationAxis, 0, len(sla.ConfigurableValues))
1331 for k := range sla.ConfigurableValues {
1332 keys = append(keys, k)
Jingwen Chened9c17d2021-04-13 07:14:55 +00001333 }
1334
Liz Kammer9abd62d2021-05-21 08:37:59 -04001335 sort.Slice(keys, func(i, j int) bool { return keys[i].less(keys[j]) })
1336 return keys
Jingwen Chened9c17d2021-04-13 07:14:55 +00001337}
1338
Liz Kammer5fad5012021-09-09 14:08:21 -04001339// DeduplicateAxesFromBase ensures no duplication of items between the no-configuration value and
1340// configuration-specific values. For example, if we would convert this StringListAttribute as:
Colin Crossd079e0b2022-08-16 10:27:33 -07001341//
1342// ["a", "b", "c"] + select({
1343// "//condition:one": ["a", "d"],
1344// "//conditions:default": [],
1345// })
1346//
Liz Kammer5fad5012021-09-09 14:08:21 -04001347// after this function, we would convert this StringListAttribute as:
Colin Crossd079e0b2022-08-16 10:27:33 -07001348//
1349// ["a", "b", "c"] + select({
1350// "//condition:one": ["d"],
1351// "//conditions:default": [],
1352// })
Liz Kammer5fad5012021-09-09 14:08:21 -04001353func (sla *StringListAttribute) DeduplicateAxesFromBase() {
1354 base := sla.Value
1355 for axis, configToList := range sla.ConfigurableValues {
1356 for config, list := range configToList {
1357 remaining := SubtractStrings(list, base)
1358 if len(remaining) == 0 {
1359 delete(sla.ConfigurableValues[axis], config)
1360 } else {
1361 sla.ConfigurableValues[axis][config] = remaining
1362 }
1363 }
1364 }
1365}
1366
Liz Kammera060c452021-03-24 10:14:47 -04001367// TryVariableSubstitution, replace string substitution formatting within each string in slice with
1368// Starlark string.format compatible tag for productVariable.
1369func TryVariableSubstitutions(slice []string, productVariable string) ([]string, bool) {
1370 ret := make([]string, 0, len(slice))
1371 changesMade := false
1372 for _, s := range slice {
1373 newS, changed := TryVariableSubstitution(s, productVariable)
1374 ret = append(ret, newS)
1375 changesMade = changesMade || changed
1376 }
1377 return ret, changesMade
1378}
1379
1380// TryVariableSubstitution, replace string substitution formatting within s with Starlark
1381// string.format compatible tag for productVariable.
1382func TryVariableSubstitution(s string, productVariable string) (string, bool) {
Liz Kammerba7a9c52021-05-26 08:45:30 -04001383 sub := productVariableSubstitutionPattern.ReplaceAllString(s, "$("+productVariable+")")
Liz Kammera060c452021-03-24 10:14:47 -04001384 return sub, s != sub
1385}