blob: d6b2bcf975308dc6a95320f28e766c7d3ba3c89c [file] [log] [blame]
Sam Delmerico7f889562022-03-25 14:55:40 +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 android
16
17import (
18 "fmt"
19 "reflect"
20 "regexp"
21 "sort"
22 "strings"
23
24 "android/soong/bazel"
25 "android/soong/starlark_fmt"
26
27 "github.com/google/blueprint"
28)
29
30// BazelVarExporter is a collection of configuration variables that can be exported for use in Bazel rules
31type BazelVarExporter interface {
32 // asBazel expands strings of configuration variables into their concrete values
33 asBazel(Config, ExportedStringVariables, ExportedStringListVariables, ExportedConfigDependingVariables) []bazelConstant
34}
35
36// ExportedVariables is a collection of interdependent configuration variables
37type ExportedVariables struct {
38 // Maps containing toolchain variables that are independent of the
39 // environment variables of the build.
40 exportedStringVars ExportedStringVariables
41 exportedStringListVars ExportedStringListVariables
42 exportedStringListDictVars ExportedStringListDictVariables
43
44 exportedVariableReferenceDictVars ExportedVariableReferenceDictVariables
45
46 /// Maps containing variables that are dependent on the build config.
47 exportedConfigDependingVars ExportedConfigDependingVariables
48
49 pctx PackageContext
50}
51
52// NewExportedVariables creats an empty ExportedVariables struct with non-nil maps
53func NewExportedVariables(pctx PackageContext) ExportedVariables {
54 return ExportedVariables{
55 exportedStringVars: ExportedStringVariables{},
56 exportedStringListVars: ExportedStringListVariables{},
57 exportedStringListDictVars: ExportedStringListDictVariables{},
58 exportedVariableReferenceDictVars: ExportedVariableReferenceDictVariables{},
59 exportedConfigDependingVars: ExportedConfigDependingVariables{},
60 pctx: pctx,
61 }
62}
63
64func (ev ExportedVariables) asBazel(config Config,
65 stringVars ExportedStringVariables, stringListVars ExportedStringListVariables, cfgDepVars ExportedConfigDependingVariables) []bazelConstant {
66 ret := []bazelConstant{}
67 ret = append(ret, ev.exportedStringVars.asBazel(config, stringVars, stringListVars, cfgDepVars)...)
68 ret = append(ret, ev.exportedStringListVars.asBazel(config, stringVars, stringListVars, cfgDepVars)...)
69 ret = append(ret, ev.exportedStringListDictVars.asBazel(config, stringVars, stringListVars, cfgDepVars)...)
70 // Note: ExportedVariableReferenceDictVars collections can only contain references to other variables and must be printed last
71 ret = append(ret, ev.exportedVariableReferenceDictVars.asBazel(config, stringVars, stringListVars, cfgDepVars)...)
72 return ret
73}
74
75// ExportStringStaticVariable declares a static string variable and exports it to
76// Bazel's toolchain.
77func (ev ExportedVariables) ExportStringStaticVariable(name string, value string) {
78 ev.pctx.StaticVariable(name, value)
79 ev.exportedStringVars.set(name, value)
80}
81
82// ExportStringListStaticVariable declares a static variable and exports it to
83// Bazel's toolchain.
84func (ev ExportedVariables) ExportStringListStaticVariable(name string, value []string) {
85 ev.pctx.StaticVariable(name, strings.Join(value, " "))
86 ev.exportedStringListVars.set(name, value)
87}
88
89// ExportVariableConfigMethod declares a variable whose value is evaluated at
90// runtime via a function with access to the Config and exports it to Bazel's
91// toolchain.
92func (ev ExportedVariables) ExportVariableConfigMethod(name string, method interface{}) blueprint.Variable {
93 ev.exportedConfigDependingVars.set(name, method)
94 return ev.pctx.VariableConfigMethod(name, method)
95}
96
97// ExportSourcePathVariable declares a static "source path" variable and exports
98// it to Bazel's toolchain.
99func (ev ExportedVariables) ExportSourcePathVariable(name string, value string) {
100 ev.pctx.SourcePathVariable(name, value)
101 ev.exportedStringVars.set(name, value)
102}
103
Sam Delmerico932c01c2022-03-25 16:33:26 +0000104// ExportVariableFuncVariable declares a variable whose value is evaluated at
105// runtime via a function and exports it to Bazel's toolchain.
106func (ev ExportedVariables) ExportVariableFuncVariable(name string, f func() string) {
107 ev.exportedConfigDependingVars.set(name, func(config Config) string {
108 return f()
109 })
110 ev.pctx.VariableFunc(name, func(PackageVarContext) string {
111 return f()
112 })
113}
114
Sam Delmerico7f889562022-03-25 14:55:40 +0000115// ExportString only exports a variable to Bazel, but does not declare it in Soong
116func (ev ExportedVariables) ExportString(name string, value string) {
117 ev.exportedStringVars.set(name, value)
118}
119
120// ExportStringList only exports a variable to Bazel, but does not declare it in Soong
121func (ev ExportedVariables) ExportStringList(name string, value []string) {
122 ev.exportedStringListVars.set(name, value)
123}
124
125// ExportStringListDict only exports a variable to Bazel, but does not declare it in Soong
126func (ev ExportedVariables) ExportStringListDict(name string, value map[string][]string) {
127 ev.exportedStringListDictVars.set(name, value)
128}
129
130// ExportVariableReferenceDict only exports a variable to Bazel, but does not declare it in Soong
131func (ev ExportedVariables) ExportVariableReferenceDict(name string, value map[string]string) {
132 ev.exportedVariableReferenceDictVars.set(name, value)
133}
134
135// ExportedConfigDependingVariables is a mapping of variable names to functions
136// of type func(config Config) string which return the runtime-evaluated string
137// value of a particular variable
138type ExportedConfigDependingVariables map[string]interface{}
139
140func (m ExportedConfigDependingVariables) set(k string, v interface{}) {
141 m[k] = v
142}
143
144// Ensure that string s has no invalid characters to be generated into the bzl file.
145func validateCharacters(s string) string {
146 for _, c := range []string{`\n`, `"`, `\`} {
147 if strings.Contains(s, c) {
148 panic(fmt.Errorf("%s contains illegal character %s", s, c))
149 }
150 }
151 return s
152}
153
154type bazelConstant struct {
155 variableName string
156 internalDefinition string
157 sortLast bool
158}
159
160// ExportedStringVariables is a mapping of variable names to string values
161type ExportedStringVariables map[string]string
162
163func (m ExportedStringVariables) set(k string, v string) {
164 m[k] = v
165}
166
167func (m ExportedStringVariables) asBazel(config Config,
168 stringVars ExportedStringVariables, stringListVars ExportedStringListVariables, cfgDepVars ExportedConfigDependingVariables) []bazelConstant {
169 ret := make([]bazelConstant, 0, len(m))
170 for k, variableValue := range m {
171 expandedVar, err := expandVar(config, variableValue, stringVars, stringListVars, cfgDepVars)
172 if err != nil {
173 panic(fmt.Errorf("error expanding config variable %s: %s", k, err))
174 }
175 if len(expandedVar) > 1 {
176 panic(fmt.Errorf("%s expands to more than one string value: %s", variableValue, expandedVar))
177 }
178 ret = append(ret, bazelConstant{
179 variableName: k,
180 internalDefinition: fmt.Sprintf(`"%s"`, validateCharacters(expandedVar[0])),
181 })
182 }
183 return ret
184}
185
186// ExportedStringListVariables is a mapping of variable names to a list of strings
187type ExportedStringListVariables map[string][]string
188
189func (m ExportedStringListVariables) set(k string, v []string) {
190 m[k] = v
191}
192
193func (m ExportedStringListVariables) asBazel(config Config,
194 stringScope ExportedStringVariables, stringListScope ExportedStringListVariables,
195 exportedVars ExportedConfigDependingVariables) []bazelConstant {
196 ret := make([]bazelConstant, 0, len(m))
197 // For each exported variable, recursively expand elements in the variableValue
198 // list to ensure that interpolated variables are expanded according to their values
199 // in the variable scope.
200 for k, variableValue := range m {
201 var expandedVars []string
202 for _, v := range variableValue {
203 expandedVar, err := expandVar(config, v, stringScope, stringListScope, exportedVars)
204 if err != nil {
205 panic(fmt.Errorf("Error expanding config variable %s=%s: %s", k, v, err))
206 }
207 expandedVars = append(expandedVars, expandedVar...)
208 }
209 // Assign the list as a bzl-private variable; this variable will be exported
210 // out through a constants struct later.
211 ret = append(ret, bazelConstant{
212 variableName: k,
213 internalDefinition: starlark_fmt.PrintStringList(expandedVars, 0),
214 })
215 }
216 return ret
217}
218
219// ExportedStringListDictVariables is a mapping from variable names to a
220// dictionary which maps keys to lists of strings
221type ExportedStringListDictVariables map[string]map[string][]string
222
223func (m ExportedStringListDictVariables) set(k string, v map[string][]string) {
224 m[k] = v
225}
226
227// Since dictionaries are not supported in Ninja, we do not expand variables for dictionaries
228func (m ExportedStringListDictVariables) asBazel(_ Config, _ ExportedStringVariables,
229 _ ExportedStringListVariables, _ ExportedConfigDependingVariables) []bazelConstant {
230 ret := make([]bazelConstant, 0, len(m))
231 for k, dict := range m {
232 ret = append(ret, bazelConstant{
233 variableName: k,
234 internalDefinition: starlark_fmt.PrintStringListDict(dict, 0),
235 })
236 }
237 return ret
238}
239
240// ExportedVariableReferenceDictVariables is a mapping from variable names to a
241// dictionary which references previously defined variables. This is used to
242// create a Starlark output such as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700243//
244// string_var1 = "string1
245// var_ref_dict_var1 = {
246// "key1": string_var1
247// }
248//
Sam Delmerico7f889562022-03-25 14:55:40 +0000249// This type of variable collection must be expanded last so that it recognizes
250// previously defined variables.
251type ExportedVariableReferenceDictVariables map[string]map[string]string
252
253func (m ExportedVariableReferenceDictVariables) set(k string, v map[string]string) {
254 m[k] = v
255}
256
257func (m ExportedVariableReferenceDictVariables) asBazel(_ Config, _ ExportedStringVariables,
258 _ ExportedStringListVariables, _ ExportedConfigDependingVariables) []bazelConstant {
259 ret := make([]bazelConstant, 0, len(m))
260 for n, dict := range m {
261 for k, v := range dict {
262 matches, err := variableReference(v)
263 if err != nil {
264 panic(err)
265 } else if !matches.matches {
266 panic(fmt.Errorf("Expected a variable reference, got %q", v))
267 } else if len(matches.fullVariableReference) != len(v) {
268 panic(fmt.Errorf("Expected only a variable reference, got %q", v))
269 }
270 dict[k] = "_" + matches.variable
271 }
272 ret = append(ret, bazelConstant{
273 variableName: n,
274 internalDefinition: starlark_fmt.PrintDict(dict, 0),
275 sortLast: true,
276 })
277 }
278 return ret
279}
280
281// BazelToolchainVars expands an ExportedVariables collection and returns a string
282// of formatted Starlark variable definitions
283func BazelToolchainVars(config Config, exportedVars ExportedVariables) string {
284 results := exportedVars.asBazel(
285 config,
286 exportedVars.exportedStringVars,
287 exportedVars.exportedStringListVars,
288 exportedVars.exportedConfigDependingVars,
289 )
290
291 sort.Slice(results, func(i, j int) bool {
292 if results[i].sortLast != results[j].sortLast {
293 return !results[i].sortLast
294 }
295 return results[i].variableName < results[j].variableName
296 })
297
298 definitions := make([]string, 0, len(results))
299 constants := make([]string, 0, len(results))
300 for _, b := range results {
301 definitions = append(definitions,
302 fmt.Sprintf("_%s = %s", b.variableName, b.internalDefinition))
303 constants = append(constants,
304 fmt.Sprintf("%[1]s%[2]s = _%[2]s,", starlark_fmt.Indention(1), b.variableName))
305 }
306
307 // Build the exported constants struct.
308 ret := bazel.GeneratedBazelFileWarning
309 ret += "\n\n"
310 ret += strings.Join(definitions, "\n\n")
311 ret += "\n\n"
312 ret += "constants = struct(\n"
313 ret += strings.Join(constants, "\n")
314 ret += "\n)"
315
316 return ret
317}
318
319type match struct {
320 matches bool
321 fullVariableReference string
322 variable string
323}
324
325func variableReference(input string) (match, error) {
326 // e.g. "${ExternalCflags}"
327 r := regexp.MustCompile(`\${(?:config\.)?([a-zA-Z0-9_]+)}`)
328
329 matches := r.FindStringSubmatch(input)
330 if len(matches) == 0 {
331 return match{}, nil
332 }
333 if len(matches) != 2 {
334 return match{}, fmt.Errorf("Expected to only match 1 subexpression in %s, got %d", input, len(matches)-1)
335 }
336 return match{
337 matches: true,
338 fullVariableReference: matches[0],
339 // Index 1 of FindStringSubmatch contains the subexpression match
340 // (variable name) of the capture group.
341 variable: matches[1],
342 }, nil
343}
344
345// expandVar recursively expand interpolated variables in the exportedVars scope.
346//
347// We're using a string slice to track the seen variables to avoid
348// stackoverflow errors with infinite recursion. it's simpler to use a
349// string slice than to handle a pass-by-referenced map, which would make it
350// quite complex to track depth-first interpolations. It's also unlikely the
351// interpolation stacks are deep (n > 1).
352func expandVar(config Config, toExpand string, stringScope ExportedStringVariables,
353 stringListScope ExportedStringListVariables, exportedVars ExportedConfigDependingVariables) ([]string, error) {
354
355 // Internal recursive function.
356 var expandVarInternal func(string, map[string]bool) (string, error)
357 expandVarInternal = func(toExpand string, seenVars map[string]bool) (string, error) {
358 var ret string
359 remainingString := toExpand
360 for len(remainingString) > 0 {
361 matches, err := variableReference(remainingString)
362 if err != nil {
363 panic(err)
364 }
365 if !matches.matches {
366 return ret + remainingString, nil
367 }
368 matchIndex := strings.Index(remainingString, matches.fullVariableReference)
369 ret += remainingString[:matchIndex]
370 remainingString = remainingString[matchIndex+len(matches.fullVariableReference):]
371
372 variable := matches.variable
373 // toExpand contains a variable.
374 if _, ok := seenVars[variable]; ok {
375 return ret, fmt.Errorf(
376 "Unbounded recursive interpolation of variable: %s", variable)
377 }
378 // A map is passed-by-reference. Create a new map for
379 // this scope to prevent variables seen in one depth-first expansion
380 // to be also treated as "seen" in other depth-first traversals.
381 newSeenVars := map[string]bool{}
382 for k := range seenVars {
383 newSeenVars[k] = true
384 }
385 newSeenVars[variable] = true
386 if unexpandedVars, ok := stringListScope[variable]; ok {
387 expandedVars := []string{}
388 for _, unexpandedVar := range unexpandedVars {
389 expandedVar, err := expandVarInternal(unexpandedVar, newSeenVars)
390 if err != nil {
391 return ret, err
392 }
393 expandedVars = append(expandedVars, expandedVar)
394 }
395 ret += strings.Join(expandedVars, " ")
396 } else if unexpandedVar, ok := stringScope[variable]; ok {
397 expandedVar, err := expandVarInternal(unexpandedVar, newSeenVars)
398 if err != nil {
399 return ret, err
400 }
401 ret += expandedVar
402 } else if unevaluatedVar, ok := exportedVars[variable]; ok {
403 evalFunc := reflect.ValueOf(unevaluatedVar)
404 validateVariableMethod(variable, evalFunc)
405 evaluatedResult := evalFunc.Call([]reflect.Value{reflect.ValueOf(config)})
406 evaluatedValue := evaluatedResult[0].Interface().(string)
407 expandedVar, err := expandVarInternal(evaluatedValue, newSeenVars)
408 if err != nil {
409 return ret, err
410 }
411 ret += expandedVar
412 } else {
413 return "", fmt.Errorf("Unbound config variable %s", variable)
414 }
415 }
416 return ret, nil
417 }
418 var ret []string
Sam Delmerico932c01c2022-03-25 16:33:26 +0000419 stringFields := splitStringKeepingQuotedSubstring(toExpand, ' ')
420 for _, v := range stringFields {
Sam Delmerico7f889562022-03-25 14:55:40 +0000421 val, err := expandVarInternal(v, map[string]bool{})
422 if err != nil {
423 return ret, err
424 }
425 ret = append(ret, val)
426 }
427
428 return ret, nil
429}
430
Sam Delmerico932c01c2022-03-25 16:33:26 +0000431// splitStringKeepingQuotedSubstring splits a string on a provided separator,
432// but it will not split substrings inside unescaped double quotes. If the double
433// quotes are escaped, then the returned string will only include the quote, and
434// not the escape.
435func splitStringKeepingQuotedSubstring(s string, delimiter byte) []string {
436 var ret []string
437 quote := byte('"')
438
439 var substring []byte
440 quoted := false
441 escaped := false
442
443 for i := range s {
444 if !quoted && s[i] == delimiter {
445 ret = append(ret, string(substring))
446 substring = []byte{}
447 continue
448 }
449
450 characterIsEscape := i < len(s)-1 && s[i] == '\\' && s[i+1] == quote
451 if characterIsEscape {
452 escaped = true
453 continue
454 }
455
456 if s[i] == quote {
457 if !escaped {
458 quoted = !quoted
459 }
460 escaped = false
461 }
462
463 substring = append(substring, s[i])
464 }
465
466 ret = append(ret, string(substring))
467
468 return ret
469}
470
Sam Delmerico7f889562022-03-25 14:55:40 +0000471func validateVariableMethod(name string, methodValue reflect.Value) {
472 methodType := methodValue.Type()
473 if methodType.Kind() != reflect.Func {
474 panic(fmt.Errorf("method given for variable %s is not a function",
475 name))
476 }
477 if n := methodType.NumIn(); n != 1 {
478 panic(fmt.Errorf("method for variable %s has %d inputs (should be 1)",
479 name, n))
480 }
481 if n := methodType.NumOut(); n != 1 {
482 panic(fmt.Errorf("method for variable %s has %d outputs (should be 1)",
483 name, n))
484 }
485 if kind := methodType.Out(0).Kind(); kind != reflect.String {
486 panic(fmt.Errorf("method for variable %s does not return a string",
487 name))
488 }
489}