blob: 73f65f539fa7eaa612f01831c41452e2e59e2f17 [file] [log] [blame]
Jingwen Chenbf61afb2021-05-06 13:31:18 +00001// Copyright 2021 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 config
16
17import (
Jingwen Chenbf61afb2021-05-06 13:31:18 +000018 "fmt"
Chris Parsons3b1f83d2021-10-14 14:08:38 -040019 "reflect"
Jingwen Chenbf61afb2021-05-06 13:31:18 +000020 "regexp"
Liz Kammer82ad8cc2021-08-02 10:41:48 -040021 "sort"
Jingwen Chenbf61afb2021-05-06 13:31:18 +000022 "strings"
Chris Parsons3b1f83d2021-10-14 14:08:38 -040023
24 "android/soong/android"
Liz Kammer72beb342022-02-03 08:42:10 -050025 "android/soong/starlark_fmt"
Jingwen Chen341f7352022-01-11 05:42:49 +000026
Chris Parsons3b1f83d2021-10-14 14:08:38 -040027 "github.com/google/blueprint"
Jingwen Chenbf61afb2021-05-06 13:31:18 +000028)
29
Liz Kammer82ad8cc2021-08-02 10:41:48 -040030type bazelVarExporter interface {
Chris Parsons3b1f83d2021-10-14 14:08:38 -040031 asBazel(android.Config, exportedStringVariables, exportedStringListVariables, exportedConfigDependingVariables) []bazelConstant
Liz Kammer82ad8cc2021-08-02 10:41:48 -040032}
33
Jingwen Chenbf61afb2021-05-06 13:31:18 +000034// Helpers for exporting cc configuration information to Bazel.
Jingwen Chenbf61afb2021-05-06 13:31:18 +000035var (
Chris Parsons3b1f83d2021-10-14 14:08:38 -040036 // Maps containing toolchain variables that are independent of the
Jingwen Chenbf61afb2021-05-06 13:31:18 +000037 // environment variables of the build.
Liz Kammer82ad8cc2021-08-02 10:41:48 -040038 exportedStringListVars = exportedStringListVariables{}
39 exportedStringVars = exportedStringVariables{}
40 exportedStringListDictVars = exportedStringListDictVariables{}
Liz Kammere8303bd2022-02-16 09:02:48 -050041 // Note: these can only contain references to other variables and must be printed last
42 exportedVariableReferenceDictVars = exportedVariableReferenceDictVariables{}
Chris Parsons3b1f83d2021-10-14 14:08:38 -040043
44 /// Maps containing variables that are dependent on the build config.
45 exportedConfigDependingVars = exportedConfigDependingVariables{}
Jingwen Chenbf61afb2021-05-06 13:31:18 +000046)
47
Chris Parsons3b1f83d2021-10-14 14:08:38 -040048type exportedConfigDependingVariables map[string]interface{}
49
50func (m exportedConfigDependingVariables) Set(k string, v interface{}) {
51 m[k] = v
52}
53
Liz Kammer82ad8cc2021-08-02 10:41:48 -040054// Ensure that string s has no invalid characters to be generated into the bzl file.
55func validateCharacters(s string) string {
56 for _, c := range []string{`\n`, `"`, `\`} {
57 if strings.Contains(s, c) {
58 panic(fmt.Errorf("%s contains illegal character %s", s, c))
59 }
60 }
61 return s
62}
63
64type bazelConstant struct {
65 variableName string
66 internalDefinition string
Liz Kammere8303bd2022-02-16 09:02:48 -050067 sortLast bool
Liz Kammer82ad8cc2021-08-02 10:41:48 -040068}
69
Jingwen Chen51a1e1c2021-05-20 13:40:14 +000070type exportedStringVariables map[string]string
Jingwen Chenbf61afb2021-05-06 13:31:18 +000071
Jingwen Chen51a1e1c2021-05-20 13:40:14 +000072func (m exportedStringVariables) Set(k string, v string) {
Jingwen Chenbf61afb2021-05-06 13:31:18 +000073 m[k] = v
74}
75
Chris Parsons3b1f83d2021-10-14 14:08:38 -040076func (m exportedStringVariables) asBazel(config android.Config,
77 stringVars exportedStringVariables, stringListVars exportedStringListVariables, cfgDepVars exportedConfigDependingVariables) []bazelConstant {
Liz Kammer82ad8cc2021-08-02 10:41:48 -040078 ret := make([]bazelConstant, 0, len(m))
79 for k, variableValue := range m {
Chris Parsons3b1f83d2021-10-14 14:08:38 -040080 expandedVar, err := expandVar(config, variableValue, stringVars, stringListVars, cfgDepVars)
81 if err != nil {
82 panic(fmt.Errorf("error expanding config variable %s: %s", k, err))
83 }
Liz Kammer82ad8cc2021-08-02 10:41:48 -040084 if len(expandedVar) > 1 {
85 panic(fmt.Errorf("%s expands to more than one string value: %s", variableValue, expandedVar))
86 }
87 ret = append(ret, bazelConstant{
88 variableName: k,
89 internalDefinition: fmt.Sprintf(`"%s"`, validateCharacters(expandedVar[0])),
90 })
91 }
92 return ret
93}
94
Jingwen Chenbf61afb2021-05-06 13:31:18 +000095// Convenience function to declare a static variable and export it to Bazel's cc_toolchain.
Jingwen Chen51a1e1c2021-05-20 13:40:14 +000096func exportStringStaticVariable(name string, value string) {
97 pctx.StaticVariable(name, value)
98 exportedStringVars.Set(name, value)
99}
100
Liz Kammer82ad8cc2021-08-02 10:41:48 -0400101type exportedStringListVariables map[string][]string
102
Jingwen Chen51a1e1c2021-05-20 13:40:14 +0000103func (m exportedStringListVariables) Set(k string, v []string) {
104 m[k] = v
105}
106
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400107func (m exportedStringListVariables) asBazel(config android.Config,
108 stringScope exportedStringVariables, stringListScope exportedStringListVariables,
109 exportedVars exportedConfigDependingVariables) []bazelConstant {
Liz Kammer82ad8cc2021-08-02 10:41:48 -0400110 ret := make([]bazelConstant, 0, len(m))
111 // For each exported variable, recursively expand elements in the variableValue
112 // list to ensure that interpolated variables are expanded according to their values
113 // in the variable scope.
114 for k, variableValue := range m {
115 var expandedVars []string
116 for _, v := range variableValue {
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400117 expandedVar, err := expandVar(config, v, stringScope, stringListScope, exportedVars)
118 if err != nil {
119 panic(fmt.Errorf("Error expanding config variable %s=%s: %s", k, v, err))
120 }
121 expandedVars = append(expandedVars, expandedVar...)
Liz Kammer82ad8cc2021-08-02 10:41:48 -0400122 }
123 // Assign the list as a bzl-private variable; this variable will be exported
124 // out through a constants struct later.
125 ret = append(ret, bazelConstant{
126 variableName: k,
Liz Kammer72beb342022-02-03 08:42:10 -0500127 internalDefinition: starlark_fmt.PrintStringList(expandedVars, 0),
Liz Kammer82ad8cc2021-08-02 10:41:48 -0400128 })
129 }
130 return ret
131}
132
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400133// Convenience function to declare a static "source path" variable and export it to Bazel's cc_toolchain.
134func exportVariableConfigMethod(name string, method interface{}) blueprint.Variable {
135 exportedConfigDependingVars.Set(name, method)
136 return pctx.VariableConfigMethod(name, method)
137}
138
139// Convenience function to declare a static "source path" variable and export it to Bazel's cc_toolchain.
140func exportSourcePathVariable(name string, value string) {
141 pctx.SourcePathVariable(name, value)
142 exportedStringVars.Set(name, value)
143}
144
Jingwen Chen51a1e1c2021-05-20 13:40:14 +0000145// Convenience function to declare a static variable and export it to Bazel's cc_toolchain.
146func exportStringListStaticVariable(name string, value []string) {
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000147 pctx.StaticVariable(name, strings.Join(value, " "))
Jingwen Chen51a1e1c2021-05-20 13:40:14 +0000148 exportedStringListVars.Set(name, value)
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000149}
150
Jingwen Chen341f7352022-01-11 05:42:49 +0000151func ExportStringList(name string, value []string) {
152 exportedStringListVars.Set(name, value)
153}
154
Liz Kammer82ad8cc2021-08-02 10:41:48 -0400155type exportedStringListDictVariables map[string]map[string][]string
156
157func (m exportedStringListDictVariables) Set(k string, v map[string][]string) {
158 m[k] = v
159}
160
Liz Kammer82ad8cc2021-08-02 10:41:48 -0400161// Since dictionaries are not supported in Ninja, we do not expand variables for dictionaries
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400162func (m exportedStringListDictVariables) asBazel(_ android.Config, _ exportedStringVariables,
163 _ exportedStringListVariables, _ exportedConfigDependingVariables) []bazelConstant {
Liz Kammer82ad8cc2021-08-02 10:41:48 -0400164 ret := make([]bazelConstant, 0, len(m))
165 for k, dict := range m {
166 ret = append(ret, bazelConstant{
167 variableName: k,
Liz Kammer72beb342022-02-03 08:42:10 -0500168 internalDefinition: starlark_fmt.PrintStringListDict(dict, 0),
Liz Kammer82ad8cc2021-08-02 10:41:48 -0400169 })
170 }
171 return ret
172}
173
Liz Kammere8303bd2022-02-16 09:02:48 -0500174type exportedVariableReferenceDictVariables map[string]map[string]string
175
176func (m exportedVariableReferenceDictVariables) Set(k string, v map[string]string) {
177 m[k] = v
178}
179
180func (m exportedVariableReferenceDictVariables) asBazel(_ android.Config, _ exportedStringVariables,
181 _ exportedStringListVariables, _ exportedConfigDependingVariables) []bazelConstant {
182 ret := make([]bazelConstant, 0, len(m))
183 for n, dict := range m {
184 for k, v := range dict {
185 matches, err := variableReference(v)
186 if err != nil {
187 panic(err)
188 } else if !matches.matches {
189 panic(fmt.Errorf("Expected a variable reference, got %q", v))
190 } else if len(matches.fullVariableReference) != len(v) {
191 panic(fmt.Errorf("Expected only a variable reference, got %q", v))
192 }
193 dict[k] = "_" + matches.variable
194 }
195 ret = append(ret, bazelConstant{
196 variableName: n,
197 internalDefinition: starlark_fmt.PrintDict(dict, 0),
198 sortLast: true,
199 })
200 }
201 return ret
202}
203
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000204// BazelCcToolchainVars generates bzl file content containing variables for
205// Bazel's cc_toolchain configuration.
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400206func BazelCcToolchainVars(config android.Config) string {
Liz Kammer82ad8cc2021-08-02 10:41:48 -0400207 return bazelToolchainVars(
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400208 config,
Liz Kammer82ad8cc2021-08-02 10:41:48 -0400209 exportedStringListDictVars,
210 exportedStringListVars,
Liz Kammere8303bd2022-02-16 09:02:48 -0500211 exportedStringVars,
212 exportedVariableReferenceDictVars)
Liz Kammer82ad8cc2021-08-02 10:41:48 -0400213}
214
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400215func bazelToolchainVars(config android.Config, vars ...bazelVarExporter) string {
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000216 ret := "# GENERATED FOR BAZEL FROM SOONG. DO NOT EDIT.\n\n"
217
Liz Kammer82ad8cc2021-08-02 10:41:48 -0400218 results := []bazelConstant{}
219 for _, v := range vars {
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400220 results = append(results, v.asBazel(config, exportedStringVars, exportedStringListVars, exportedConfigDependingVars)...)
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000221 }
222
Liz Kammere8303bd2022-02-16 09:02:48 -0500223 sort.Slice(results, func(i, j int) bool {
224 if results[i].sortLast != results[j].sortLast {
225 return !results[i].sortLast
226 }
227 return results[i].variableName < results[j].variableName
228 })
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000229
Liz Kammer82ad8cc2021-08-02 10:41:48 -0400230 definitions := make([]string, 0, len(results))
231 constants := make([]string, 0, len(results))
232 for _, b := range results {
233 definitions = append(definitions,
234 fmt.Sprintf("_%s = %s", b.variableName, b.internalDefinition))
235 constants = append(constants,
Liz Kammer72beb342022-02-03 08:42:10 -0500236 fmt.Sprintf("%[1]s%[2]s = _%[2]s,", starlark_fmt.Indention(1), b.variableName))
Jingwen Chen51a1e1c2021-05-20 13:40:14 +0000237 }
238
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000239 // Build the exported constants struct.
Liz Kammer82ad8cc2021-08-02 10:41:48 -0400240 ret += strings.Join(definitions, "\n\n")
241 ret += "\n\n"
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000242 ret += "constants = struct(\n"
Liz Kammer82ad8cc2021-08-02 10:41:48 -0400243 ret += strings.Join(constants, "\n")
244 ret += "\n)"
245
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000246 return ret
247}
248
Liz Kammere8303bd2022-02-16 09:02:48 -0500249type match struct {
250 matches bool
251 fullVariableReference string
252 variable string
253}
254
255func variableReference(input string) (match, error) {
256 // e.g. "${ExternalCflags}"
257 r := regexp.MustCompile(`\${(?:config\.)?([a-zA-Z0-9_]+)}`)
258
259 matches := r.FindStringSubmatch(input)
260 if len(matches) == 0 {
261 return match{}, nil
262 }
263 if len(matches) != 2 {
264 return match{}, fmt.Errorf("Expected to only match 1 subexpression in %s, got %d", input, len(matches)-1)
265 }
266 return match{
267 matches: true,
268 fullVariableReference: matches[0],
269 // Index 1 of FindStringSubmatch contains the subexpression match
270 // (variable name) of the capture group.
271 variable: matches[1],
272 }, nil
273}
274
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000275// expandVar recursively expand interpolated variables in the exportedVars scope.
276//
277// We're using a string slice to track the seen variables to avoid
278// stackoverflow errors with infinite recursion. it's simpler to use a
279// string slice than to handle a pass-by-referenced map, which would make it
280// quite complex to track depth-first interpolations. It's also unlikely the
281// interpolation stacks are deep (n > 1).
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400282func expandVar(config android.Config, toExpand string, stringScope exportedStringVariables,
283 stringListScope exportedStringListVariables, exportedVars exportedConfigDependingVariables) ([]string, error) {
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000284
285 // Internal recursive function.
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400286 var expandVarInternal func(string, map[string]bool) (string, error)
287 expandVarInternal = func(toExpand string, seenVars map[string]bool) (string, error) {
288 var ret string
289 remainingString := toExpand
290 for len(remainingString) > 0 {
Liz Kammere8303bd2022-02-16 09:02:48 -0500291 matches, err := variableReference(remainingString)
292 if err != nil {
293 panic(err)
294 }
295 if !matches.matches {
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400296 return ret + remainingString, nil
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000297 }
Liz Kammere8303bd2022-02-16 09:02:48 -0500298 matchIndex := strings.Index(remainingString, matches.fullVariableReference)
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400299 ret += remainingString[:matchIndex]
Liz Kammere8303bd2022-02-16 09:02:48 -0500300 remainingString = remainingString[matchIndex+len(matches.fullVariableReference):]
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000301
Liz Kammere8303bd2022-02-16 09:02:48 -0500302 variable := matches.variable
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000303 // toExpand contains a variable.
304 if _, ok := seenVars[variable]; ok {
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400305 return ret, fmt.Errorf(
306 "Unbounded recursive interpolation of variable: %s", variable)
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000307 }
308 // A map is passed-by-reference. Create a new map for
309 // this scope to prevent variables seen in one depth-first expansion
310 // to be also treated as "seen" in other depth-first traversals.
311 newSeenVars := map[string]bool{}
312 for k := range seenVars {
313 newSeenVars[k] = true
314 }
315 newSeenVars[variable] = true
Jingwen Chen51a1e1c2021-05-20 13:40:14 +0000316 if unexpandedVars, ok := stringListScope[variable]; ok {
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400317 expandedVars := []string{}
Jingwen Chen51a1e1c2021-05-20 13:40:14 +0000318 for _, unexpandedVar := range unexpandedVars {
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400319 expandedVar, err := expandVarInternal(unexpandedVar, newSeenVars)
320 if err != nil {
321 return ret, err
322 }
323 expandedVars = append(expandedVars, expandedVar)
Jingwen Chen51a1e1c2021-05-20 13:40:14 +0000324 }
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400325 ret += strings.Join(expandedVars, " ")
Jingwen Chen51a1e1c2021-05-20 13:40:14 +0000326 } else if unexpandedVar, ok := stringScope[variable]; ok {
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400327 expandedVar, err := expandVarInternal(unexpandedVar, newSeenVars)
328 if err != nil {
329 return ret, err
330 }
331 ret += expandedVar
332 } else if unevaluatedVar, ok := exportedVars[variable]; ok {
333 evalFunc := reflect.ValueOf(unevaluatedVar)
334 validateVariableMethod(variable, evalFunc)
335 evaluatedResult := evalFunc.Call([]reflect.Value{reflect.ValueOf(config)})
336 evaluatedValue := evaluatedResult[0].Interface().(string)
337 expandedVar, err := expandVarInternal(evaluatedValue, newSeenVars)
338 if err != nil {
339 return ret, err
340 }
341 ret += expandedVar
342 } else {
343 return "", fmt.Errorf("Unbound config variable %s", variable)
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000344 }
345 }
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400346 return ret, nil
347 }
348 var ret []string
349 for _, v := range strings.Split(toExpand, " ") {
350 val, err := expandVarInternal(v, map[string]bool{})
351 if err != nil {
352 return ret, err
353 }
354 ret = append(ret, val)
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000355 }
356
Chris Parsons3b1f83d2021-10-14 14:08:38 -0400357 return ret, nil
358}
359
360func validateVariableMethod(name string, methodValue reflect.Value) {
361 methodType := methodValue.Type()
362 if methodType.Kind() != reflect.Func {
363 panic(fmt.Errorf("method given for variable %s is not a function",
364 name))
365 }
366 if n := methodType.NumIn(); n != 1 {
367 panic(fmt.Errorf("method for variable %s has %d inputs (should be 1)",
368 name, n))
369 }
370 if n := methodType.NumOut(); n != 1 {
371 panic(fmt.Errorf("method for variable %s has %d outputs (should be 1)",
372 name, n))
373 }
374 if kind := methodType.Out(0).Kind(); kind != reflect.String {
375 panic(fmt.Errorf("method for variable %s does not return a string",
376 name))
377 }
Jingwen Chenbf61afb2021-05-06 13:31:18 +0000378}