blob: 3a6854c2915c07d9fe5813ca2f74d11e57bf303a [file] [log] [blame]
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001// Copyright 2021 Google LLC
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
15// Convert makefile containing device configuration to Starlark file
16// The conversion can handle the following constructs in a makefile:
Colin Crossd079e0b2022-08-16 10:27:33 -070017// - comments
18// - simple variable assignments
19// - $(call init-product,<file>)
20// - $(call inherit-product-if-exists
21// - if directives
Sasha Smundakb051c4e2020-11-05 20:45:07 -080022//
Colin Crossd079e0b2022-08-16 10:27:33 -070023// All other constructs are carried over to the output starlark file as comments.
Sasha Smundakb051c4e2020-11-05 20:45:07 -080024package mk2rbc
25
26import (
27 "bytes"
28 "fmt"
29 "io"
Sasha Smundak6609ba72021-07-22 18:32:56 -070030 "io/fs"
Sasha Smundakb051c4e2020-11-05 20:45:07 -080031 "io/ioutil"
32 "os"
33 "path/filepath"
34 "regexp"
Cole Faust62e05112022-04-05 17:56:11 -070035 "sort"
Sasha Smundakb051c4e2020-11-05 20:45:07 -080036 "strconv"
37 "strings"
38 "text/scanner"
39
40 mkparser "android/soong/androidmk/parser"
41)
42
43const (
Sasha Smundak6d852dd2021-09-27 20:34:39 -070044 annotationCommentPrefix = "RBC#"
45 baseUri = "//build/make/core:product_config.rbc"
Sasha Smundakb051c4e2020-11-05 20:45:07 -080046 // The name of the struct exported by the product_config.rbc
47 // that contains the functions and variables available to
48 // product configuration Starlark files.
49 baseName = "rblf"
50
Sasha Smundak65b547e2021-09-17 15:35:41 -070051 soongNsPrefix = "SOONG_CONFIG_"
52
Sasha Smundakb051c4e2020-11-05 20:45:07 -080053 // And here are the functions and variables:
Cole Fauste2a37982022-03-09 16:00:17 -080054 cfnGetCfg = baseName + ".cfg"
55 cfnMain = baseName + ".product_configuration"
56 cfnBoardMain = baseName + ".board_configuration"
57 cfnPrintVars = baseName + ".printvars"
58 cfnInherit = baseName + ".inherit"
59 cfnSetListDefault = baseName + ".setdefault"
Sasha Smundakb051c4e2020-11-05 20:45:07 -080060)
61
62const (
Cole Faust9ebf6e42021-12-13 14:08:34 -080063 soongConfigAppend = "soong_config_append"
64 soongConfigAssign = "soong_config_set"
Sasha Smundakb051c4e2020-11-05 20:45:07 -080065)
66
Cole Faust9ebf6e42021-12-13 14:08:34 -080067var knownFunctions = map[string]interface {
68 parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr
Sasha Smundakb051c4e2020-11-05 20:45:07 -080069}{
Cole Faust1cc08852022-02-28 11:12:08 -080070 "abspath": &simpleCallParser{name: baseName + ".abspath", returnType: starlarkTypeString},
71 "add-product-dex-preopt-module-config": &simpleCallParser{name: baseName + ".add_product_dex_preopt_module_config", returnType: starlarkTypeString, addHandle: true},
72 "add_soong_config_namespace": &simpleCallParser{name: baseName + ".soong_config_namespace", returnType: starlarkTypeVoid, addGlobals: true},
73 "add_soong_config_var_value": &simpleCallParser{name: baseName + ".soong_config_set", returnType: starlarkTypeVoid, addGlobals: true},
74 soongConfigAssign: &simpleCallParser{name: baseName + ".soong_config_set", returnType: starlarkTypeVoid, addGlobals: true},
75 soongConfigAppend: &simpleCallParser{name: baseName + ".soong_config_append", returnType: starlarkTypeVoid, addGlobals: true},
76 "soong_config_get": &simpleCallParser{name: baseName + ".soong_config_get", returnType: starlarkTypeString, addGlobals: true},
77 "add-to-product-copy-files-if-exists": &simpleCallParser{name: baseName + ".copy_if_exists", returnType: starlarkTypeList},
78 "addprefix": &simpleCallParser{name: baseName + ".addprefix", returnType: starlarkTypeList},
79 "addsuffix": &simpleCallParser{name: baseName + ".addsuffix", returnType: starlarkTypeList},
Cole Faustd2daabf2022-12-12 17:38:01 -080080 "and": &andOrParser{isAnd: true},
Cole Faust5a3449f2022-12-12 19:00:54 -080081 "clear-var-list": &simpleCallParser{name: baseName + ".clear_var_list", returnType: starlarkTypeVoid, addGlobals: true, addHandle: true},
Cole Faust1cc08852022-02-28 11:12:08 -080082 "copy-files": &simpleCallParser{name: baseName + ".copy_files", returnType: starlarkTypeList},
Cole Faust0e2b2562022-04-01 11:46:50 -070083 "dir": &simpleCallParser{name: baseName + ".dir", returnType: starlarkTypeString},
Cole Faust1cc08852022-02-28 11:12:08 -080084 "dist-for-goals": &simpleCallParser{name: baseName + ".mkdist_for_goals", returnType: starlarkTypeVoid, addGlobals: true},
Cole Faust6c41b8a2022-04-13 13:53:48 -070085 "enforce-product-packages-exist": &simpleCallParser{name: baseName + ".enforce_product_packages_exist", returnType: starlarkTypeVoid, addHandle: true},
Cole Faust1cc08852022-02-28 11:12:08 -080086 "error": &makeControlFuncParser{name: baseName + ".mkerror"},
87 "findstring": &simpleCallParser{name: baseName + ".findstring", returnType: starlarkTypeInt},
88 "find-copy-subdir-files": &simpleCallParser{name: baseName + ".find_and_copy", returnType: starlarkTypeList},
89 "filter": &simpleCallParser{name: baseName + ".filter", returnType: starlarkTypeList},
90 "filter-out": &simpleCallParser{name: baseName + ".filter_out", returnType: starlarkTypeList},
Cole Faust5a13aaf2022-04-27 17:49:35 -070091 "firstword": &simpleCallParser{name: baseName + ".first_word", returnType: starlarkTypeString},
Cole Faustf035d402022-03-28 14:02:50 -070092 "foreach": &foreachCallParser{},
Cole Faust1cc08852022-02-28 11:12:08 -080093 "if": &ifCallParser{},
94 "info": &makeControlFuncParser{name: baseName + ".mkinfo"},
95 "is-board-platform": &simpleCallParser{name: baseName + ".board_platform_is", returnType: starlarkTypeBool, addGlobals: true},
96 "is-board-platform2": &simpleCallParser{name: baseName + ".board_platform_is", returnType: starlarkTypeBool, addGlobals: true},
97 "is-board-platform-in-list": &simpleCallParser{name: baseName + ".board_platform_in", returnType: starlarkTypeBool, addGlobals: true},
98 "is-board-platform-in-list2": &simpleCallParser{name: baseName + ".board_platform_in", returnType: starlarkTypeBool, addGlobals: true},
99 "is-product-in-list": &isProductInListCallParser{},
100 "is-vendor-board-platform": &isVendorBoardPlatformCallParser{},
101 "is-vendor-board-qcom": &isVendorBoardQcomCallParser{},
Cole Faust5a13aaf2022-04-27 17:49:35 -0700102 "lastword": &simpleCallParser{name: baseName + ".last_word", returnType: starlarkTypeString},
Cole Faust1cc08852022-02-28 11:12:08 -0800103 "notdir": &simpleCallParser{name: baseName + ".notdir", returnType: starlarkTypeString},
104 "math_max": &mathMaxOrMinCallParser{function: "max"},
105 "math_min": &mathMaxOrMinCallParser{function: "min"},
106 "math_gt_or_eq": &mathComparisonCallParser{op: ">="},
107 "math_gt": &mathComparisonCallParser{op: ">"},
108 "math_lt": &mathComparisonCallParser{op: "<"},
109 "my-dir": &myDirCallParser{},
Cole Faustd2daabf2022-12-12 17:38:01 -0800110 "or": &andOrParser{isAnd: false},
Cole Faust1cc08852022-02-28 11:12:08 -0800111 "patsubst": &substCallParser{fname: "patsubst"},
112 "product-copy-files-by-pattern": &simpleCallParser{name: baseName + ".product_copy_files_by_pattern", returnType: starlarkTypeList},
Cole Faustea9db582022-03-21 17:50:05 -0700113 "require-artifacts-in-path": &simpleCallParser{name: baseName + ".require_artifacts_in_path", returnType: starlarkTypeVoid, addHandle: true},
114 "require-artifacts-in-path-relaxed": &simpleCallParser{name: baseName + ".require_artifacts_in_path_relaxed", returnType: starlarkTypeVoid, addHandle: true},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800115 // TODO(asmundak): remove it once all calls are removed from configuration makefiles. see b/183161002
Cole Faust9ebf6e42021-12-13 14:08:34 -0800116 "shell": &shellCallParser{},
Cole Faust95b95cb2022-04-05 16:37:39 -0700117 "sort": &simpleCallParser{name: baseName + ".mksort", returnType: starlarkTypeList},
Cole Faust1cc08852022-02-28 11:12:08 -0800118 "strip": &simpleCallParser{name: baseName + ".mkstrip", returnType: starlarkTypeString},
Cole Faust9ebf6e42021-12-13 14:08:34 -0800119 "subst": &substCallParser{fname: "subst"},
Cole Faust2dee63d2022-12-12 18:11:00 -0800120 "to-lower": &lowerUpperParser{isUpper: false},
121 "to-upper": &lowerUpperParser{isUpper: true},
Cole Faust9ebf6e42021-12-13 14:08:34 -0800122 "warning": &makeControlFuncParser{name: baseName + ".mkwarning"},
123 "word": &wordCallParser{},
Cole Faust94c4a9a2022-04-22 17:43:52 -0700124 "words": &wordsCallParser{},
Cole Faust1cc08852022-02-28 11:12:08 -0800125 "wildcard": &simpleCallParser{name: baseName + ".expand_wildcard", returnType: starlarkTypeList},
Cole Faust9ebf6e42021-12-13 14:08:34 -0800126}
127
Cole Faustf035d402022-03-28 14:02:50 -0700128// The same as knownFunctions, but returns a []starlarkNode instead of a starlarkExpr
129var knownNodeFunctions = map[string]interface {
130 parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode
131}{
132 "eval": &evalNodeParser{},
133 "if": &ifCallNodeParser{},
134 "inherit-product": &inheritProductCallParser{loadAlways: true},
135 "inherit-product-if-exists": &inheritProductCallParser{loadAlways: false},
136 "foreach": &foreachCallNodeParser{},
137}
138
Cole Faust1e275862022-04-26 14:28:04 -0700139// These look like variables, but are actually functions, and would give
140// undefined variable errors if we converted them as variables. Instead,
141// emit an error instead of converting them.
142var unsupportedFunctions = map[string]bool{
143 "local-generated-sources-dir": true,
144 "local-intermediates-dir": true,
145}
146
Cole Faust9ebf6e42021-12-13 14:08:34 -0800147// These are functions that we don't implement conversions for, but
148// we allow seeing their definitions in the product config files.
149var ignoredDefines = map[string]bool{
150 "find-word-in-list": true, // internal macro
151 "get-vendor-board-platforms": true, // internal macro, used by is-board-platform, etc.
152 "is-android-codename": true, // unused by product config
153 "is-android-codename-in-list": true, // unused by product config
154 "is-chipset-in-board-platform": true, // unused by product config
155 "is-chipset-prefix-in-board-platform": true, // unused by product config
156 "is-not-board-platform": true, // defined but never used
157 "is-platform-sdk-version-at-least": true, // unused by product config
158 "match-prefix": true, // internal macro
159 "match-word": true, // internal macro
160 "match-word-in-list": true, // internal macro
161 "tb-modules": true, // defined in hardware/amlogic/tb_modules/tb_detect.mk, unused
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800162}
163
Cole Faustb0d32ab2021-12-09 14:00:59 -0800164var identifierFullMatchRegex = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$")
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800165
Cole Faustc85d08f2023-05-09 15:00:58 -0700166func RelativeToCwd(path string) (string, error) {
167 cwd, err := os.Getwd()
168 if err != nil {
169 return "", err
170 }
171 path, err = filepath.Rel(cwd, path)
172 if err != nil {
173 return "", err
174 }
175 if strings.HasPrefix(path, "../") {
176 return "", fmt.Errorf("Could not make path relative to current working directory: " + path)
177 }
178 return path, nil
179}
180
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800181// Conversion request parameters
182type Request struct {
Sasha Smundak422b6142021-11-11 18:31:59 -0800183 MkFile string // file to convert
184 Reader io.Reader // if set, read input from this stream instead
Sasha Smundak422b6142021-11-11 18:31:59 -0800185 OutputSuffix string // generated Starlark files suffix
186 OutputDir string // if set, root of the output hierarchy
187 ErrorLogger ErrorLogger
188 TracedVariables []string // trace assignment to these variables
189 TraceCalls bool
190 SourceFS fs.FS
191 MakefileFinder MakefileFinder
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800192}
193
Sasha Smundak7d934b92021-11-10 12:20:01 -0800194// ErrorLogger prints errors and gathers error statistics.
195// Its NewError function is called on every error encountered during the conversion.
196type ErrorLogger interface {
Sasha Smundak422b6142021-11-11 18:31:59 -0800197 NewError(el ErrorLocation, node mkparser.Node, text string, args ...interface{})
198}
199
200type ErrorLocation struct {
201 MkFile string
202 MkLine int
203}
204
205func (el ErrorLocation) String() string {
206 return fmt.Sprintf("%s:%d", el.MkFile, el.MkLine)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800207}
208
209// Derives module name for a given file. It is base name
210// (file name without suffix), with some characters replaced to make it a Starlark identifier
211func moduleNameForFile(mkFile string) string {
212 base := strings.TrimSuffix(filepath.Base(mkFile), filepath.Ext(mkFile))
213 // TODO(asmundak): what else can be in the product file names?
Sasha Smundak6609ba72021-07-22 18:32:56 -0700214 return strings.NewReplacer("-", "_", ".", "_").Replace(base)
215
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800216}
217
218func cloneMakeString(mkString *mkparser.MakeString) *mkparser.MakeString {
219 r := &mkparser.MakeString{StringPos: mkString.StringPos}
220 r.Strings = append(r.Strings, mkString.Strings...)
221 r.Variables = append(r.Variables, mkString.Variables...)
222 return r
223}
224
225func isMakeControlFunc(s string) bool {
226 return s == "error" || s == "warning" || s == "info"
227}
228
Cole Faustf0632662022-04-07 13:59:24 -0700229// varAssignmentScope points to the last assignment for each variable
230// in the current block. It is used during the parsing to chain
231// the assignments to a variable together.
232type varAssignmentScope struct {
233 outer *varAssignmentScope
234 vars map[string]bool
235}
236
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800237// Starlark output generation context
238type generationContext struct {
Cole Faustf0632662022-04-07 13:59:24 -0700239 buf strings.Builder
240 starScript *StarlarkScript
241 indentLevel int
242 inAssignment bool
243 tracedCount int
244 varAssignments *varAssignmentScope
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800245}
246
247func NewGenerateContext(ss *StarlarkScript) *generationContext {
Cole Faustf0632662022-04-07 13:59:24 -0700248 return &generationContext{
249 starScript: ss,
250 varAssignments: &varAssignmentScope{
251 outer: nil,
252 vars: make(map[string]bool),
253 },
254 }
255}
256
257func (gctx *generationContext) pushVariableAssignments() {
258 va := &varAssignmentScope{
259 outer: gctx.varAssignments,
260 vars: make(map[string]bool),
261 }
262 gctx.varAssignments = va
263}
264
265func (gctx *generationContext) popVariableAssignments() {
266 gctx.varAssignments = gctx.varAssignments.outer
267}
268
269func (gctx *generationContext) hasBeenAssigned(v variable) bool {
270 for va := gctx.varAssignments; va != nil; va = va.outer {
271 if _, ok := va.vars[v.name()]; ok {
272 return true
273 }
274 }
275 return false
276}
277
278func (gctx *generationContext) setHasBeenAssigned(v variable) {
279 gctx.varAssignments.vars[v.name()] = true
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800280}
281
282// emit returns generated script
283func (gctx *generationContext) emit() string {
284 ss := gctx.starScript
285
286 // The emitted code has the following layout:
287 // <initial comments>
288 // preamble, i.e.,
289 // load statement for the runtime support
290 // load statement for each unique submodule pulled in by this one
291 // def init(g, handle):
292 // cfg = rblf.cfg(handle)
293 // <statements>
294 // <warning if conversion was not clean>
295
296 iNode := len(ss.nodes)
297 for i, node := range ss.nodes {
298 if _, ok := node.(*commentNode); !ok {
299 iNode = i
300 break
301 }
302 node.emit(gctx)
303 }
304
305 gctx.emitPreamble()
306
307 gctx.newLine()
308 // The arguments passed to the init function are the global dictionary
309 // ('g') and the product configuration dictionary ('cfg')
310 gctx.write("def init(g, handle):")
311 gctx.indentLevel++
312 if gctx.starScript.traceCalls {
313 gctx.newLine()
314 gctx.writef(`print(">%s")`, gctx.starScript.mkFile)
315 }
316 gctx.newLine()
317 gctx.writef("cfg = %s(handle)", cfnGetCfg)
318 for _, node := range ss.nodes[iNode:] {
319 node.emit(gctx)
320 }
321
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800322 if gctx.starScript.traceCalls {
323 gctx.newLine()
324 gctx.writef(`print("<%s")`, gctx.starScript.mkFile)
325 }
326 gctx.indentLevel--
327 gctx.write("\n")
328 return gctx.buf.String()
329}
330
331func (gctx *generationContext) emitPreamble() {
332 gctx.newLine()
333 gctx.writef("load(%q, %q)", baseUri, baseName)
334 // Emit exactly one load statement for each URI.
335 loadedSubConfigs := make(map[string]string)
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800336 for _, mi := range gctx.starScript.inherited {
337 uri := mi.path
Cole Faustc85d08f2023-05-09 15:00:58 -0700338 if strings.HasPrefix(uri, "/") && !strings.HasPrefix(uri, "//") {
339 var err error
340 uri, err = RelativeToCwd(uri)
341 if err != nil {
342 panic(err)
343 }
344 uri = "//" + uri
345 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800346 if m, ok := loadedSubConfigs[uri]; ok {
347 // No need to emit load statement, but fix module name.
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800348 mi.moduleLocalName = m
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800349 continue
350 }
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800351 if mi.optional || mi.missing {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800352 uri += "|init"
353 }
354 gctx.newLine()
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800355 gctx.writef("load(%q, %s = \"init\")", uri, mi.entryName())
356 loadedSubConfigs[uri] = mi.moduleLocalName
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800357 }
358 gctx.write("\n")
359}
360
361func (gctx *generationContext) emitPass() {
362 gctx.newLine()
363 gctx.write("pass")
364}
365
366func (gctx *generationContext) write(ss ...string) {
367 for _, s := range ss {
368 gctx.buf.WriteString(s)
369 }
370}
371
372func (gctx *generationContext) writef(format string, args ...interface{}) {
373 gctx.write(fmt.Sprintf(format, args...))
374}
375
376func (gctx *generationContext) newLine() {
377 if gctx.buf.Len() == 0 {
378 return
379 }
380 gctx.write("\n")
381 gctx.writef("%*s", 2*gctx.indentLevel, "")
382}
383
Sasha Smundak422b6142021-11-11 18:31:59 -0800384func (gctx *generationContext) emitConversionError(el ErrorLocation, message string) {
385 gctx.writef(`rblf.mk2rbc_error("%s", %q)`, el, message)
386}
387
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800388func (gctx *generationContext) emitLoadCheck(im inheritedModule) {
389 if !im.needsLoadCheck() {
390 return
391 }
392 gctx.newLine()
393 gctx.writef("if not %s:", im.entryName())
394 gctx.indentLevel++
395 gctx.newLine()
396 gctx.write(`rblf.mkerror("`, gctx.starScript.mkFile, `", "Cannot find %s" % (`)
397 im.pathExpr().emit(gctx)
398 gctx.write("))")
399 gctx.indentLevel--
400}
401
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800402type knownVariable struct {
403 name string
404 class varClass
405 valueType starlarkType
406}
407
408type knownVariables map[string]knownVariable
409
410func (pcv knownVariables) NewVariable(name string, varClass varClass, valueType starlarkType) {
411 v, exists := pcv[name]
412 if !exists {
413 pcv[name] = knownVariable{name, varClass, valueType}
414 return
415 }
416 // Conflict resolution:
417 // * config class trumps everything
418 // * any type trumps unknown type
419 match := varClass == v.class
420 if !match {
421 if varClass == VarClassConfig {
422 v.class = VarClassConfig
423 match = true
424 } else if v.class == VarClassConfig {
425 match = true
426 }
427 }
428 if valueType != v.valueType {
429 if valueType != starlarkTypeUnknown {
430 if v.valueType == starlarkTypeUnknown {
431 v.valueType = valueType
432 } else {
433 match = false
434 }
435 }
436 }
437 if !match {
438 fmt.Fprintf(os.Stderr, "cannot redefine %s as %v/%v (already defined as %v/%v)\n",
439 name, varClass, valueType, v.class, v.valueType)
440 }
441}
442
443// All known product variables.
444var KnownVariables = make(knownVariables)
445
446func init() {
447 for _, kv := range []string{
448 // Kernel-related variables that we know are lists.
449 "BOARD_VENDOR_KERNEL_MODULES",
450 "BOARD_VENDOR_RAMDISK_KERNEL_MODULES",
451 "BOARD_VENDOR_RAMDISK_KERNEL_MODULES_LOAD",
452 "BOARD_RECOVERY_KERNEL_MODULES",
453 // Other variables we knwo are lists
454 "ART_APEX_JARS",
455 } {
456 KnownVariables.NewVariable(kv, VarClassSoong, starlarkTypeList)
457 }
458}
459
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800460// Information about the generated Starlark script.
461type StarlarkScript struct {
Sasha Smundak422b6142021-11-11 18:31:59 -0800462 mkFile string
463 moduleName string
464 mkPos scanner.Position
465 nodes []starlarkNode
466 inherited []*moduleInfo
467 hasErrors bool
Sasha Smundak422b6142021-11-11 18:31:59 -0800468 traceCalls bool // print enter/exit each init function
469 sourceFS fs.FS
470 makefileFinder MakefileFinder
471 nodeLocator func(pos mkparser.Pos) int
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800472}
473
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800474// parseContext holds the script we are generating and all the ephemeral data
475// needed during the parsing.
476type parseContext struct {
477 script *StarlarkScript
478 nodes []mkparser.Node // Makefile as parsed by mkparser
479 currentNodeIndex int // Node in it we are processing
480 ifNestLevel int
481 moduleNameCount map[string]int // count of imported modules with given basename
482 fatalError error
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800483 outputSuffix string
Sasha Smundak7d934b92021-11-10 12:20:01 -0800484 errorLogger ErrorLogger
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800485 tracedVariables map[string]bool // variables to be traced in the generated script
486 variables map[string]variable
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800487 outputDir string
Sasha Smundak6609ba72021-07-22 18:32:56 -0700488 dependentModules map[string]*moduleInfo
Sasha Smundak3deb9682021-07-26 18:42:25 -0700489 soongNamespaces map[string]map[string]bool
Sasha Smundak6d852dd2021-09-27 20:34:39 -0700490 includeTops []string
Cole Faustf92c9f22022-03-14 14:35:50 -0700491 typeHints map[string]starlarkType
492 atTopOfMakefile bool
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800493}
494
495func newParseContext(ss *StarlarkScript, nodes []mkparser.Node) *parseContext {
496 predefined := []struct{ name, value string }{
497 {"SRC_TARGET_DIR", filepath.Join("build", "make", "target")},
498 {"LOCAL_PATH", filepath.Dir(ss.mkFile)},
Cole Faust5a13aaf2022-04-27 17:49:35 -0700499 {"MAKEFILE_LIST", ss.mkFile},
Cole Faust9b6111a2022-02-02 15:38:33 -0800500 {"TOPDIR", ""}, // TOPDIR is just set to an empty string in cleanbuild.mk and core.mk
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800501 // TODO(asmundak): maybe read it from build/make/core/envsetup.mk?
502 {"TARGET_COPY_OUT_SYSTEM", "system"},
503 {"TARGET_COPY_OUT_SYSTEM_OTHER", "system_other"},
504 {"TARGET_COPY_OUT_DATA", "data"},
505 {"TARGET_COPY_OUT_ASAN", filepath.Join("data", "asan")},
506 {"TARGET_COPY_OUT_OEM", "oem"},
507 {"TARGET_COPY_OUT_RAMDISK", "ramdisk"},
508 {"TARGET_COPY_OUT_DEBUG_RAMDISK", "debug_ramdisk"},
509 {"TARGET_COPY_OUT_VENDOR_DEBUG_RAMDISK", "vendor_debug_ramdisk"},
510 {"TARGET_COPY_OUT_TEST_HARNESS_RAMDISK", "test_harness_ramdisk"},
511 {"TARGET_COPY_OUT_ROOT", "root"},
512 {"TARGET_COPY_OUT_RECOVERY", "recovery"},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800513 {"TARGET_COPY_OUT_VENDOR_RAMDISK", "vendor_ramdisk"},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800514 // TODO(asmundak): to process internal config files, we need the following variables:
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800515 // TARGET_VENDOR
516 // target_base_product
517 //
518
519 // the following utility variables are set in build/make/common/core.mk:
520 {"empty", ""},
521 {"space", " "},
522 {"comma", ","},
523 {"newline", "\n"},
524 {"pound", "#"},
525 {"backslash", "\\"},
526 }
527 ctx := &parseContext{
528 script: ss,
529 nodes: nodes,
530 currentNodeIndex: 0,
531 ifNestLevel: 0,
532 moduleNameCount: make(map[string]int),
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800533 variables: make(map[string]variable),
Sasha Smundak6609ba72021-07-22 18:32:56 -0700534 dependentModules: make(map[string]*moduleInfo),
Sasha Smundak3deb9682021-07-26 18:42:25 -0700535 soongNamespaces: make(map[string]map[string]bool),
Cole Faust6c934f62022-01-06 15:51:12 -0800536 includeTops: []string{},
Cole Faustf92c9f22022-03-14 14:35:50 -0700537 typeHints: make(map[string]starlarkType),
538 atTopOfMakefile: true,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800539 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800540 for _, item := range predefined {
541 ctx.variables[item.name] = &predefinedVariable{
542 baseVariable: baseVariable{nam: item.name, typ: starlarkTypeString},
543 value: &stringLiteralExpr{item.value},
544 }
545 }
546
547 return ctx
548}
549
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800550func (ctx *parseContext) hasNodes() bool {
551 return ctx.currentNodeIndex < len(ctx.nodes)
552}
553
554func (ctx *parseContext) getNode() mkparser.Node {
555 if !ctx.hasNodes() {
556 return nil
557 }
558 node := ctx.nodes[ctx.currentNodeIndex]
559 ctx.currentNodeIndex++
560 return node
561}
562
563func (ctx *parseContext) backNode() {
564 if ctx.currentNodeIndex <= 0 {
565 panic("Cannot back off")
566 }
567 ctx.currentNodeIndex--
568}
569
Cole Faustdd569ae2022-01-31 15:48:29 -0800570func (ctx *parseContext) handleAssignment(a *mkparser.Assignment) []starlarkNode {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800571 // Handle only simple variables
Cole Faust00afd4f2022-04-26 14:01:56 -0700572 if !a.Name.Const() || a.Target != nil {
Cole Faustdd569ae2022-01-31 15:48:29 -0800573 return []starlarkNode{ctx.newBadNode(a, "Only simple variables are handled")}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800574 }
575 name := a.Name.Strings[0]
Sasha Smundakea3bc3a2021-11-10 13:06:42 -0800576 // The `override` directive
577 // override FOO :=
578 // is parsed as an assignment to a variable named `override FOO`.
579 // There are very few places where `override` is used, just flag it.
580 if strings.HasPrefix(name, "override ") {
Cole Faustdd569ae2022-01-31 15:48:29 -0800581 return []starlarkNode{ctx.newBadNode(a, "cannot handle override directive")}
Sasha Smundakea3bc3a2021-11-10 13:06:42 -0800582 }
Cole Faust5d5fcc32022-04-26 18:02:05 -0700583 if name == ".KATI_READONLY" {
584 // Skip assignments to .KATI_READONLY. If it was in the output file, it
585 // would be an error because it would be sorted before the definition of
586 // the variable it's trying to make readonly.
587 return []starlarkNode{}
588 }
Sasha Smundakea3bc3a2021-11-10 13:06:42 -0800589
Cole Faustc00184e2021-11-08 12:08:57 -0800590 // Soong configuration
Sasha Smundak3deb9682021-07-26 18:42:25 -0700591 if strings.HasPrefix(name, soongNsPrefix) {
Cole Faustdd569ae2022-01-31 15:48:29 -0800592 return ctx.handleSoongNsAssignment(strings.TrimPrefix(name, soongNsPrefix), a)
Sasha Smundak3deb9682021-07-26 18:42:25 -0700593 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800594 lhs := ctx.addVariable(name)
595 if lhs == nil {
Cole Faustdd569ae2022-01-31 15:48:29 -0800596 return []starlarkNode{ctx.newBadNode(a, "unknown variable %s", name)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800597 }
Cole Faust3c4fc992022-02-28 16:05:01 -0800598 _, isTraced := ctx.tracedVariables[lhs.name()]
Sasha Smundak422b6142021-11-11 18:31:59 -0800599 asgn := &assignmentNode{lhs: lhs, mkValue: a.Value, isTraced: isTraced, location: ctx.errorLocation(a)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800600 if lhs.valueType() == starlarkTypeUnknown {
601 // Try to divine variable type from the RHS
602 asgn.value = ctx.parseMakeString(a, a.Value)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800603 inferred_type := asgn.value.typ()
604 if inferred_type != starlarkTypeUnknown {
Sasha Smundak9d011ab2021-07-09 16:00:57 -0700605 lhs.setValueType(inferred_type)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800606 }
607 }
608 if lhs.valueType() == starlarkTypeList {
Cole Faustdd569ae2022-01-31 15:48:29 -0800609 xConcat, xBad := ctx.buildConcatExpr(a)
610 if xBad != nil {
Cole Faust1e275862022-04-26 14:28:04 -0700611 asgn.value = xBad
612 } else {
613 switch len(xConcat.items) {
614 case 0:
615 asgn.value = &listExpr{}
616 case 1:
617 asgn.value = xConcat.items[0]
618 default:
619 asgn.value = xConcat
620 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800621 }
622 } else {
623 asgn.value = ctx.parseMakeString(a, a.Value)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800624 }
625
Cole Faust421a1922022-03-16 14:35:45 -0700626 if asgn.lhs.valueType() == starlarkTypeString &&
627 asgn.value.typ() != starlarkTypeUnknown &&
628 asgn.value.typ() != starlarkTypeString {
629 asgn.value = &toStringExpr{expr: asgn.value}
630 }
631
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800632 switch a.Type {
633 case "=", ":=":
634 asgn.flavor = asgnSet
635 case "+=":
Cole Fauste2a37982022-03-09 16:00:17 -0800636 asgn.flavor = asgnAppend
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800637 case "?=":
638 asgn.flavor = asgnMaybeSet
639 default:
640 panic(fmt.Errorf("unexpected assignment type %s", a.Type))
641 }
642
Cole Faustdd569ae2022-01-31 15:48:29 -0800643 return []starlarkNode{asgn}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800644}
645
Cole Faustdd569ae2022-01-31 15:48:29 -0800646func (ctx *parseContext) handleSoongNsAssignment(name string, asgn *mkparser.Assignment) []starlarkNode {
Sasha Smundak3deb9682021-07-26 18:42:25 -0700647 val := ctx.parseMakeString(asgn, asgn.Value)
648 if xBad, ok := val.(*badExpr); ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800649 return []starlarkNode{&exprNode{expr: xBad}}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700650 }
Sasha Smundak3deb9682021-07-26 18:42:25 -0700651
652 // Unfortunately, Soong namespaces can be set up by directly setting corresponding Make
653 // variables instead of via add_soong_config_namespace + add_soong_config_var_value.
654 // Try to divine the call from the assignment as follows:
655 if name == "NAMESPACES" {
656 // Upon seeng
657 // SOONG_CONFIG_NAMESPACES += foo
658 // remember that there is a namespace `foo` and act as we saw
659 // $(call add_soong_config_namespace,foo)
660 s, ok := maybeString(val)
661 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800662 return []starlarkNode{ctx.newBadNode(asgn, "cannot handle variables in SOONG_CONFIG_NAMESPACES assignment, please use add_soong_config_namespace instead")}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700663 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800664 result := make([]starlarkNode, 0)
Sasha Smundak3deb9682021-07-26 18:42:25 -0700665 for _, ns := range strings.Fields(s) {
666 ctx.addSoongNamespace(ns)
Cole Faustdd569ae2022-01-31 15:48:29 -0800667 result = append(result, &exprNode{&callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -0800668 name: baseName + ".soong_config_namespace",
669 args: []starlarkExpr{&globalsExpr{}, &stringLiteralExpr{ns}},
Sasha Smundak3deb9682021-07-26 18:42:25 -0700670 returnType: starlarkTypeVoid,
671 }})
672 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800673 return result
Sasha Smundak3deb9682021-07-26 18:42:25 -0700674 } else {
675 // Upon seeing
676 // SOONG_CONFIG_x_y = v
677 // find a namespace called `x` and act as if we encountered
Cole Faustc00184e2021-11-08 12:08:57 -0800678 // $(call soong_config_set,x,y,v)
Sasha Smundak3deb9682021-07-26 18:42:25 -0700679 // or check that `x_y` is a namespace, and then add the RHS of this assignment as variables in
680 // it.
681 // Emit an error in the ambiguous situation (namespaces `foo_bar` with a variable `baz`
682 // and `foo` with a variable `bar_baz`.
683 namespaceName := ""
684 if ctx.hasSoongNamespace(name) {
685 namespaceName = name
686 }
687 var varName string
688 for pos, ch := range name {
689 if !(ch == '_' && ctx.hasSoongNamespace(name[0:pos])) {
690 continue
691 }
692 if namespaceName != "" {
Cole Faustdd569ae2022-01-31 15:48:29 -0800693 return []starlarkNode{ctx.newBadNode(asgn, "ambiguous soong namespace (may be either `%s` or `%s`)", namespaceName, name[0:pos])}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700694 }
695 namespaceName = name[0:pos]
696 varName = name[pos+1:]
697 }
698 if namespaceName == "" {
Cole Faustdd569ae2022-01-31 15:48:29 -0800699 return []starlarkNode{ctx.newBadNode(asgn, "cannot figure out Soong namespace, please use add_soong_config_var_value macro instead")}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700700 }
701 if varName == "" {
702 // Remember variables in this namespace
703 s, ok := maybeString(val)
704 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800705 return []starlarkNode{ctx.newBadNode(asgn, "cannot handle variables in SOONG_CONFIG_ assignment, please use add_soong_config_var_value instead")}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700706 }
707 ctx.updateSoongNamespace(asgn.Type != "+=", namespaceName, strings.Fields(s))
Cole Faustdd569ae2022-01-31 15:48:29 -0800708 return []starlarkNode{}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700709 }
710
711 // Finally, handle assignment to a namespace variable
712 if !ctx.hasNamespaceVar(namespaceName, varName) {
Cole Faustdd569ae2022-01-31 15:48:29 -0800713 return []starlarkNode{ctx.newBadNode(asgn, "no %s variable in %s namespace, please use add_soong_config_var_value instead", varName, namespaceName)}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700714 }
Cole Faust9ebf6e42021-12-13 14:08:34 -0800715 fname := baseName + "." + soongConfigAssign
Sasha Smundak65b547e2021-09-17 15:35:41 -0700716 if asgn.Type == "+=" {
Cole Faust9ebf6e42021-12-13 14:08:34 -0800717 fname = baseName + "." + soongConfigAppend
Sasha Smundak65b547e2021-09-17 15:35:41 -0700718 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800719 return []starlarkNode{&exprNode{&callExpr{
Sasha Smundak65b547e2021-09-17 15:35:41 -0700720 name: fname,
Cole Faust9ebf6e42021-12-13 14:08:34 -0800721 args: []starlarkExpr{&globalsExpr{}, &stringLiteralExpr{namespaceName}, &stringLiteralExpr{varName}, val},
Sasha Smundak3deb9682021-07-26 18:42:25 -0700722 returnType: starlarkTypeVoid,
Cole Faustdd569ae2022-01-31 15:48:29 -0800723 }}}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700724 }
725}
726
Cole Faustdd569ae2022-01-31 15:48:29 -0800727func (ctx *parseContext) buildConcatExpr(a *mkparser.Assignment) (*concatExpr, *badExpr) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800728 xConcat := &concatExpr{}
729 var xItemList *listExpr
730 addToItemList := func(x ...starlarkExpr) {
731 if xItemList == nil {
732 xItemList = &listExpr{[]starlarkExpr{}}
733 }
734 xItemList.items = append(xItemList.items, x...)
735 }
736 finishItemList := func() {
737 if xItemList != nil {
738 xConcat.items = append(xConcat.items, xItemList)
739 xItemList = nil
740 }
741 }
742
743 items := a.Value.Words()
744 for _, item := range items {
745 // A function call in RHS is supposed to return a list, all other item
746 // expressions return individual elements.
747 switch x := ctx.parseMakeString(a, item).(type) {
748 case *badExpr:
Cole Faustdd569ae2022-01-31 15:48:29 -0800749 return nil, x
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800750 case *stringLiteralExpr:
751 addToItemList(maybeConvertToStringList(x).(*listExpr).items...)
752 default:
753 switch x.typ() {
754 case starlarkTypeList:
755 finishItemList()
756 xConcat.items = append(xConcat.items, x)
757 case starlarkTypeString:
758 finishItemList()
759 xConcat.items = append(xConcat.items, &callExpr{
760 object: x,
761 name: "split",
762 args: nil,
763 returnType: starlarkTypeList,
764 })
765 default:
766 addToItemList(x)
767 }
768 }
769 }
770 if xItemList != nil {
771 xConcat.items = append(xConcat.items, xItemList)
772 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800773 return xConcat, nil
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800774}
775
Sasha Smundak6609ba72021-07-22 18:32:56 -0700776func (ctx *parseContext) newDependentModule(path string, optional bool) *moduleInfo {
777 modulePath := ctx.loadedModulePath(path)
778 if mi, ok := ctx.dependentModules[modulePath]; ok {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700779 mi.optional = mi.optional && optional
Sasha Smundak6609ba72021-07-22 18:32:56 -0700780 return mi
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800781 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800782 moduleName := moduleNameForFile(path)
783 moduleLocalName := "_" + moduleName
784 n, found := ctx.moduleNameCount[moduleName]
785 if found {
786 moduleLocalName += fmt.Sprintf("%d", n)
787 }
788 ctx.moduleNameCount[moduleName] = n + 1
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800789 _, err := fs.Stat(ctx.script.sourceFS, path)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700790 mi := &moduleInfo{
791 path: modulePath,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800792 originalPath: path,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800793 moduleLocalName: moduleLocalName,
Sasha Smundak6609ba72021-07-22 18:32:56 -0700794 optional: optional,
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800795 missing: err != nil,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800796 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700797 ctx.dependentModules[modulePath] = mi
798 ctx.script.inherited = append(ctx.script.inherited, mi)
799 return mi
800}
801
802func (ctx *parseContext) handleSubConfig(
Cole Faustdd569ae2022-01-31 15:48:29 -0800803 v mkparser.Node, pathExpr starlarkExpr, loadAlways bool, processModule func(inheritedModule) starlarkNode) []starlarkNode {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700804
Cole Faust62e05112022-04-05 17:56:11 -0700805 // Allow seeing $(sort $(wildcard realPathExpr)) or $(wildcard realPathExpr)
806 // because those are functionally the same as not having the sort/wildcard calls.
807 if ce, ok := pathExpr.(*callExpr); ok && ce.name == "rblf.mksort" && len(ce.args) == 1 {
808 if ce2, ok2 := ce.args[0].(*callExpr); ok2 && ce2.name == "rblf.expand_wildcard" && len(ce2.args) == 1 {
809 pathExpr = ce2.args[0]
810 }
811 } else if ce2, ok2 := pathExpr.(*callExpr); ok2 && ce2.name == "rblf.expand_wildcard" && len(ce2.args) == 1 {
812 pathExpr = ce2.args[0]
813 }
814
Sasha Smundak6609ba72021-07-22 18:32:56 -0700815 // In a simple case, the name of a module to inherit/include is known statically.
816 if path, ok := maybeString(pathExpr); ok {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700817 // Note that even if this directive loads a module unconditionally, a module may be
818 // absent without causing any harm if this directive is inside an if/else block.
819 moduleShouldExist := loadAlways && ctx.ifNestLevel == 0
Sasha Smundak6609ba72021-07-22 18:32:56 -0700820 if strings.Contains(path, "*") {
821 if paths, err := fs.Glob(ctx.script.sourceFS, path); err == nil {
Cole Faust62e05112022-04-05 17:56:11 -0700822 sort.Strings(paths)
Cole Faustdd569ae2022-01-31 15:48:29 -0800823 result := make([]starlarkNode, 0)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700824 for _, p := range paths {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700825 mi := ctx.newDependentModule(p, !moduleShouldExist)
Cole Faustdd569ae2022-01-31 15:48:29 -0800826 result = append(result, processModule(inheritedStaticModule{mi, loadAlways}))
Sasha Smundak6609ba72021-07-22 18:32:56 -0700827 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800828 return result
Sasha Smundak6609ba72021-07-22 18:32:56 -0700829 } else {
Cole Faustdd569ae2022-01-31 15:48:29 -0800830 return []starlarkNode{ctx.newBadNode(v, "cannot glob wildcard argument")}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700831 }
832 } else {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700833 mi := ctx.newDependentModule(path, !moduleShouldExist)
Cole Faustdd569ae2022-01-31 15:48:29 -0800834 return []starlarkNode{processModule(inheritedStaticModule{mi, loadAlways})}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700835 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700836 }
837
838 // If module path references variables (e.g., $(v1)/foo/$(v2)/device-config.mk), find all the paths in the
839 // source tree that may be a match and the corresponding variable values. For instance, if the source tree
840 // contains vendor1/foo/abc/dev.mk and vendor2/foo/def/dev.mk, the first one will be inherited when
841 // (v1, v2) == ('vendor1', 'abc'), and the second one when (v1, v2) == ('vendor2', 'def').
842 // We then emit the code that loads all of them, e.g.:
843 // load("//vendor1/foo/abc:dev.rbc", _dev1_init="init")
844 // load("//vendor2/foo/def/dev.rbc", _dev2_init="init")
845 // And then inherit it as follows:
846 // _e = {
847 // "vendor1/foo/abc/dev.mk": ("vendor1/foo/abc/dev", _dev1_init),
848 // "vendor2/foo/def/dev.mk": ("vendor2/foo/def/dev", _dev_init2) }.get("%s/foo/%s/dev.mk" % (v1, v2))
849 // if _e:
850 // rblf.inherit(handle, _e[0], _e[1])
851 //
852 var matchingPaths []string
Cole Faust9df1d732022-04-26 16:27:22 -0700853 var needsWarning = false
854 if interpolate, ok := pathExpr.(*interpolateExpr); ok {
855 pathPattern := []string{interpolate.chunks[0]}
856 for _, chunk := range interpolate.chunks[1:] {
857 if chunk != "" {
858 pathPattern = append(pathPattern, chunk)
859 }
860 }
Cole Faust74ac0272022-06-14 12:45:26 -0700861 if len(pathPattern) == 1 {
862 pathPattern = append(pathPattern, "")
Cole Faust9df1d732022-04-26 16:27:22 -0700863 }
Cole Faust74ac0272022-06-14 12:45:26 -0700864 matchingPaths = ctx.findMatchingPaths(pathPattern)
Cole Faust9df1d732022-04-26 16:27:22 -0700865 needsWarning = pathPattern[0] == "" && len(ctx.includeTops) == 0
866 } else if len(ctx.includeTops) > 0 {
Cole Faust74ac0272022-06-14 12:45:26 -0700867 matchingPaths = append(matchingPaths, ctx.findMatchingPaths([]string{"", ""})...)
Cole Faust9df1d732022-04-26 16:27:22 -0700868 } else {
Cole Faustdd569ae2022-01-31 15:48:29 -0800869 return []starlarkNode{ctx.newBadNode(v, "inherit-product/include argument is too complex")}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700870 }
871
Sasha Smundak6609ba72021-07-22 18:32:56 -0700872 // Safeguard against $(call inherit-product,$(PRODUCT_PATH))
Cole Faust8ff3c632023-06-08 22:53:16 +0000873 const maxMatchingFiles = 150
Sasha Smundak6609ba72021-07-22 18:32:56 -0700874 if len(matchingPaths) > maxMatchingFiles {
Cole Faustdd569ae2022-01-31 15:48:29 -0800875 return []starlarkNode{ctx.newBadNode(v, "there are >%d files matching the pattern, please rewrite it", maxMatchingFiles)}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700876 }
Cole Faust93f8d392022-03-02 13:31:30 -0800877
Cole Faust9df1d732022-04-26 16:27:22 -0700878 res := inheritedDynamicModule{pathExpr, []*moduleInfo{}, loadAlways, ctx.errorLocation(v), needsWarning}
Cole Faust93f8d392022-03-02 13:31:30 -0800879 for _, p := range matchingPaths {
880 // A product configuration files discovered dynamically may attempt to inherit
881 // from another one which does not exist in this source tree. Prevent load errors
882 // by always loading the dynamic files as optional.
883 res.candidateModules = append(res.candidateModules, ctx.newDependentModule(p, true))
Sasha Smundak6609ba72021-07-22 18:32:56 -0700884 }
Cole Faust93f8d392022-03-02 13:31:30 -0800885 return []starlarkNode{processModule(res)}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700886}
887
888func (ctx *parseContext) findMatchingPaths(pattern []string) []string {
Cole Faust9b6111a2022-02-02 15:38:33 -0800889 files := ctx.script.makefileFinder.Find(".")
Sasha Smundak6609ba72021-07-22 18:32:56 -0700890 if len(pattern) == 0 {
891 return files
892 }
893
894 // Create regular expression from the pattern
Cole Faust74ac0272022-06-14 12:45:26 -0700895 regexString := "^" + regexp.QuoteMeta(pattern[0])
Sasha Smundak6609ba72021-07-22 18:32:56 -0700896 for _, s := range pattern[1:] {
Cole Faust74ac0272022-06-14 12:45:26 -0700897 regexString += ".*" + regexp.QuoteMeta(s)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700898 }
Cole Faust74ac0272022-06-14 12:45:26 -0700899 regexString += "$"
900 rex := regexp.MustCompile(regexString)
901
902 includeTopRegexString := ""
903 if len(ctx.includeTops) > 0 {
904 for i, top := range ctx.includeTops {
905 if i > 0 {
906 includeTopRegexString += "|"
907 }
908 includeTopRegexString += "^" + regexp.QuoteMeta(top)
909 }
910 } else {
911 includeTopRegexString = ".*"
912 }
913
914 includeTopRegex := regexp.MustCompile(includeTopRegexString)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700915
916 // Now match
917 var res []string
918 for _, p := range files {
Cole Faust74ac0272022-06-14 12:45:26 -0700919 if rex.MatchString(p) && includeTopRegex.MatchString(p) {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700920 res = append(res, p)
921 }
922 }
923 return res
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800924}
925
Cole Faustf035d402022-03-28 14:02:50 -0700926type inheritProductCallParser struct {
927 loadAlways bool
928}
929
930func (p *inheritProductCallParser) parse(ctx *parseContext, v mkparser.Node, args *mkparser.MakeString) []starlarkNode {
Cole Faust9ebf6e42021-12-13 14:08:34 -0800931 args.TrimLeftSpaces()
932 args.TrimRightSpaces()
933 pathExpr := ctx.parseMakeString(v, args)
934 if _, ok := pathExpr.(*badExpr); ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800935 return []starlarkNode{ctx.newBadNode(v, "Unable to parse argument to inherit")}
Cole Faust9ebf6e42021-12-13 14:08:34 -0800936 }
Cole Faustf035d402022-03-28 14:02:50 -0700937 return ctx.handleSubConfig(v, pathExpr, p.loadAlways, func(im inheritedModule) starlarkNode {
938 return &inheritNode{im, p.loadAlways}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700939 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800940}
941
Cole Faust20052982022-04-22 14:43:55 -0700942func (ctx *parseContext) handleInclude(v *mkparser.Directive) []starlarkNode {
943 loadAlways := v.Name[0] != '-'
Cole Faustb0b24572023-10-06 11:53:50 -0700944 v.Args.TrimRightSpaces()
945 v.Args.TrimLeftSpaces()
Cole Faust20052982022-04-22 14:43:55 -0700946 return ctx.handleSubConfig(v, ctx.parseMakeString(v, v.Args), loadAlways, func(im inheritedModule) starlarkNode {
Cole Faustdd569ae2022-01-31 15:48:29 -0800947 return &includeNode{im, loadAlways}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700948 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800949}
950
Cole Faustdd569ae2022-01-31 15:48:29 -0800951func (ctx *parseContext) handleVariable(v *mkparser.Variable) []starlarkNode {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800952 // Handle:
953 // $(call inherit-product,...)
954 // $(call inherit-product-if-exists,...)
955 // $(info xxx)
956 // $(warning xxx)
957 // $(error xxx)
Cole Faust9ebf6e42021-12-13 14:08:34 -0800958 // $(call other-custom-functions,...)
959
Cole Faustf035d402022-03-28 14:02:50 -0700960 if name, args, ok := ctx.maybeParseFunctionCall(v, v.Name); ok {
961 if kf, ok := knownNodeFunctions[name]; ok {
962 return kf.parse(ctx, v, args)
963 }
Cole Faust9ebf6e42021-12-13 14:08:34 -0800964 }
Cole Faustf035d402022-03-28 14:02:50 -0700965
Cole Faustdd569ae2022-01-31 15:48:29 -0800966 return []starlarkNode{&exprNode{expr: ctx.parseReference(v, v.Name)}}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800967}
968
Cole Faustdd569ae2022-01-31 15:48:29 -0800969func (ctx *parseContext) maybeHandleDefine(directive *mkparser.Directive) starlarkNode {
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700970 macro_name := strings.Fields(directive.Args.Strings[0])[0]
971 // Ignore the macros that we handle
Cole Faust9ebf6e42021-12-13 14:08:34 -0800972 _, ignored := ignoredDefines[macro_name]
973 _, known := knownFunctions[macro_name]
974 if !ignored && !known {
Cole Faustdd569ae2022-01-31 15:48:29 -0800975 return ctx.newBadNode(directive, "define is not supported: %s", macro_name)
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700976 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800977 return nil
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800978}
979
Cole Faustdd569ae2022-01-31 15:48:29 -0800980func (ctx *parseContext) handleIfBlock(ifDirective *mkparser.Directive) starlarkNode {
981 ssSwitch := &switchNode{
982 ssCases: []*switchCase{ctx.processBranch(ifDirective)},
983 }
984 for ctx.hasNodes() && ctx.fatalError == nil {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800985 node := ctx.getNode()
986 switch x := node.(type) {
987 case *mkparser.Directive:
988 switch x.Name {
989 case "else", "elifdef", "elifndef", "elifeq", "elifneq":
Cole Faustdd569ae2022-01-31 15:48:29 -0800990 ssSwitch.ssCases = append(ssSwitch.ssCases, ctx.processBranch(x))
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800991 case "endif":
Cole Faustdd569ae2022-01-31 15:48:29 -0800992 return ssSwitch
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800993 default:
Cole Faustdd569ae2022-01-31 15:48:29 -0800994 return ctx.newBadNode(node, "unexpected directive %s", x.Name)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800995 }
996 default:
Cole Faustdd569ae2022-01-31 15:48:29 -0800997 return ctx.newBadNode(ifDirective, "unexpected statement")
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800998 }
999 }
1000 if ctx.fatalError == nil {
1001 ctx.fatalError = fmt.Errorf("no matching endif for %s", ifDirective.Dump())
1002 }
Cole Faustdd569ae2022-01-31 15:48:29 -08001003 return ctx.newBadNode(ifDirective, "no matching endif for %s", ifDirective.Dump())
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001004}
1005
1006// processBranch processes a single branch (if/elseif/else) until the next directive
1007// on the same level.
Cole Faustdd569ae2022-01-31 15:48:29 -08001008func (ctx *parseContext) processBranch(check *mkparser.Directive) *switchCase {
1009 block := &switchCase{gate: ctx.parseCondition(check)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001010 defer func() {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001011 ctx.ifNestLevel--
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001012 }()
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001013 ctx.ifNestLevel++
1014
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001015 for ctx.hasNodes() {
1016 node := ctx.getNode()
Cole Faust591a1fe2021-11-08 15:37:57 -08001017 if d, ok := node.(*mkparser.Directive); ok {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001018 switch d.Name {
1019 case "else", "elifdef", "elifndef", "elifeq", "elifneq", "endif":
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001020 ctx.backNode()
Cole Faustdd569ae2022-01-31 15:48:29 -08001021 return block
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001022 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001023 }
Cole Faustdd569ae2022-01-31 15:48:29 -08001024 block.nodes = append(block.nodes, ctx.handleSimpleStatement(node)...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001025 }
1026 ctx.fatalError = fmt.Errorf("no matching endif for %s", check.Dump())
Cole Faustdd569ae2022-01-31 15:48:29 -08001027 return block
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001028}
1029
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001030func (ctx *parseContext) parseCondition(check *mkparser.Directive) starlarkNode {
1031 switch check.Name {
1032 case "ifdef", "ifndef", "elifdef", "elifndef":
Cole Faust71514c02022-01-27 17:21:41 -08001033 if !check.Args.Const() {
Cole Faustdd569ae2022-01-31 15:48:29 -08001034 return ctx.newBadNode(check, "ifdef variable ref too complex: %s", check.Args.Dump())
Cole Faust71514c02022-01-27 17:21:41 -08001035 }
Cole Faustf0632662022-04-07 13:59:24 -07001036 v := NewVariableRefExpr(ctx.addVariable(check.Args.Strings[0]))
Cole Faust71514c02022-01-27 17:21:41 -08001037 if strings.HasSuffix(check.Name, "ndef") {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001038 v = &notExpr{v}
1039 }
1040 return &ifNode{
1041 isElif: strings.HasPrefix(check.Name, "elif"),
1042 expr: v,
1043 }
1044 case "ifeq", "ifneq", "elifeq", "elifneq":
1045 return &ifNode{
1046 isElif: strings.HasPrefix(check.Name, "elif"),
1047 expr: ctx.parseCompare(check),
1048 }
1049 case "else":
1050 return &elseNode{}
1051 default:
1052 panic(fmt.Errorf("%s: unknown directive: %s", ctx.script.mkFile, check.Dump()))
1053 }
1054}
1055
1056func (ctx *parseContext) newBadExpr(node mkparser.Node, text string, args ...interface{}) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001057 if ctx.errorLogger != nil {
Sasha Smundak422b6142021-11-11 18:31:59 -08001058 ctx.errorLogger.NewError(ctx.errorLocation(node), node, text, args...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001059 }
1060 ctx.script.hasErrors = true
Cole Faustdd569ae2022-01-31 15:48:29 -08001061 return &badExpr{errorLocation: ctx.errorLocation(node), message: fmt.Sprintf(text, args...)}
1062}
1063
1064// records that the given node failed to be converted and includes an explanatory message
1065func (ctx *parseContext) newBadNode(failedNode mkparser.Node, message string, args ...interface{}) starlarkNode {
1066 return &exprNode{ctx.newBadExpr(failedNode, message, args...)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001067}
1068
1069func (ctx *parseContext) parseCompare(cond *mkparser.Directive) starlarkExpr {
1070 // Strip outer parentheses
1071 mkArg := cloneMakeString(cond.Args)
1072 mkArg.Strings[0] = strings.TrimLeft(mkArg.Strings[0], "( ")
1073 n := len(mkArg.Strings)
1074 mkArg.Strings[n-1] = strings.TrimRight(mkArg.Strings[n-1], ") ")
1075 args := mkArg.Split(",")
1076 // TODO(asmundak): handle the case where the arguments are in quotes and space-separated
1077 if len(args) != 2 {
1078 return ctx.newBadExpr(cond, "ifeq/ifneq len(args) != 2 %s", cond.Dump())
1079 }
1080 args[0].TrimRightSpaces()
1081 args[1].TrimLeftSpaces()
1082
1083 isEq := !strings.HasSuffix(cond.Name, "neq")
Cole Faustf8320212021-11-10 15:05:07 -08001084 xLeft := ctx.parseMakeString(cond, args[0])
1085 xRight := ctx.parseMakeString(cond, args[1])
1086 if bad, ok := xLeft.(*badExpr); ok {
1087 return bad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001088 }
Cole Faustf8320212021-11-10 15:05:07 -08001089 if bad, ok := xRight.(*badExpr); ok {
1090 return bad
1091 }
1092
1093 if expr, ok := ctx.parseCompareSpecialCases(cond, xLeft, xRight); ok {
1094 return expr
1095 }
1096
Cole Faust9ebf6e42021-12-13 14:08:34 -08001097 var stringOperand string
1098 var otherOperand starlarkExpr
1099 if s, ok := maybeString(xLeft); ok {
1100 stringOperand = s
1101 otherOperand = xRight
1102 } else if s, ok := maybeString(xRight); ok {
1103 stringOperand = s
1104 otherOperand = xLeft
1105 }
1106
Cole Faust9ebf6e42021-12-13 14:08:34 -08001107 // If we've identified one of the operands as being a string literal, check
1108 // for some special cases we can do to simplify the resulting expression.
1109 if otherOperand != nil {
1110 if stringOperand == "" {
1111 if isEq {
Cole Faustf035d402022-03-28 14:02:50 -07001112 return negateExpr(otherOperand)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001113 } else {
1114 return otherOperand
1115 }
1116 }
1117 if stringOperand == "true" && otherOperand.typ() == starlarkTypeBool {
1118 if !isEq {
Cole Faustf035d402022-03-28 14:02:50 -07001119 return negateExpr(otherOperand)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001120 } else {
1121 return otherOperand
1122 }
1123 }
Cole Fausta99afdf2022-04-26 12:06:49 -07001124 if otherOperand.typ() == starlarkTypeList {
1125 fields := strings.Fields(stringOperand)
1126 elements := make([]starlarkExpr, len(fields))
1127 for i, s := range fields {
1128 elements[i] = &stringLiteralExpr{literal: s}
1129 }
1130 return &eqExpr{
1131 left: otherOperand,
1132 right: &listExpr{elements},
1133 isEq: isEq,
1134 }
1135 }
Cole Faustb1103e22022-01-06 15:22:05 -08001136 if intOperand, err := strconv.Atoi(strings.TrimSpace(stringOperand)); err == nil && otherOperand.typ() == starlarkTypeInt {
1137 return &eqExpr{
1138 left: otherOperand,
1139 right: &intLiteralExpr{literal: intOperand},
1140 isEq: isEq,
1141 }
1142 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001143 }
1144
Cole Faustf8320212021-11-10 15:05:07 -08001145 return &eqExpr{left: xLeft, right: xRight, isEq: isEq}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001146}
1147
Cole Faustf8320212021-11-10 15:05:07 -08001148// Given an if statement's directive and the left/right starlarkExprs,
1149// check if the starlarkExprs are one of a few hardcoded special cases
Cole Faust9932f752022-02-08 11:56:25 -08001150// that can be converted to a simpler equality expression than simply comparing
Cole Faustf8320212021-11-10 15:05:07 -08001151// the two.
1152func (ctx *parseContext) parseCompareSpecialCases(directive *mkparser.Directive, left starlarkExpr,
1153 right starlarkExpr) (starlarkExpr, bool) {
1154 isEq := !strings.HasSuffix(directive.Name, "neq")
1155
1156 // All the special cases require a call on one side and a
1157 // string literal/variable on the other. Turn the left/right variables into
1158 // call/value variables, and return false if that's not possible.
1159 var value starlarkExpr = nil
1160 call, ok := left.(*callExpr)
1161 if ok {
1162 switch right.(type) {
1163 case *stringLiteralExpr, *variableRefExpr:
1164 value = right
1165 }
1166 } else {
1167 call, _ = right.(*callExpr)
1168 switch left.(type) {
1169 case *stringLiteralExpr, *variableRefExpr:
1170 value = left
1171 }
1172 }
1173
1174 if call == nil || value == nil {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001175 return nil, false
1176 }
Cole Faustf8320212021-11-10 15:05:07 -08001177
Cole Faustf8320212021-11-10 15:05:07 -08001178 switch call.name {
Cole Faust9932f752022-02-08 11:56:25 -08001179 case baseName + ".filter":
1180 return ctx.parseCompareFilterFuncResult(directive, call, value, isEq)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001181 case baseName + ".findstring":
Cole Faustf8320212021-11-10 15:05:07 -08001182 return ctx.parseCheckFindstringFuncResult(directive, call, value, !isEq), true
Cole Faust9ebf6e42021-12-13 14:08:34 -08001183 case baseName + ".strip":
Cole Faustf8320212021-11-10 15:05:07 -08001184 return ctx.parseCompareStripFuncResult(directive, call, value, !isEq), true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001185 }
Cole Faustf8320212021-11-10 15:05:07 -08001186 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001187}
1188
1189func (ctx *parseContext) parseCompareFilterFuncResult(cond *mkparser.Directive,
Cole Faust9932f752022-02-08 11:56:25 -08001190 filterFuncCall *callExpr, xValue starlarkExpr, negate bool) (starlarkExpr, bool) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001191 // We handle:
Sasha Smundak0554d762021-07-08 18:26:12 -07001192 // * ifeq/ifneq (,$(filter v1 v2 ..., EXPR) becomes if EXPR not in/in ["v1", "v2", ...]
1193 // * ifeq/ifneq (,$(filter EXPR, v1 v2 ...) becomes if EXPR not in/in ["v1", "v2", ...]
Cole Faust9932f752022-02-08 11:56:25 -08001194 if x, ok := xValue.(*stringLiteralExpr); !ok || x.literal != "" {
1195 return nil, false
1196 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001197 xPattern := filterFuncCall.args[0]
1198 xText := filterFuncCall.args[1]
1199 var xInList *stringLiteralExpr
Sasha Smundak0554d762021-07-08 18:26:12 -07001200 var expr starlarkExpr
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001201 var ok bool
Cole Faust9932f752022-02-08 11:56:25 -08001202 if xInList, ok = xPattern.(*stringLiteralExpr); ok && !strings.ContainsRune(xInList.literal, '%') && xText.typ() == starlarkTypeList {
1203 expr = xText
1204 } else if xInList, ok = xText.(*stringLiteralExpr); ok {
1205 expr = xPattern
1206 } else {
1207 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001208 }
Cole Faust9932f752022-02-08 11:56:25 -08001209 slExpr := newStringListExpr(strings.Fields(xInList.literal))
1210 // Generate simpler code for the common cases:
1211 if expr.typ() == starlarkTypeList {
1212 if len(slExpr.items) == 1 {
1213 // Checking that a string belongs to list
1214 return &inExpr{isNot: negate, list: expr, expr: slExpr.items[0]}, true
Sasha Smundak0554d762021-07-08 18:26:12 -07001215 } else {
Cole Faust9932f752022-02-08 11:56:25 -08001216 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001217 }
Cole Faust9932f752022-02-08 11:56:25 -08001218 } else if len(slExpr.items) == 1 {
1219 return &eqExpr{left: expr, right: slExpr.items[0], isEq: !negate}, true
1220 } else {
1221 return &inExpr{isNot: negate, list: newStringListExpr(strings.Fields(xInList.literal)), expr: expr}, true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001222 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001223}
1224
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001225func (ctx *parseContext) parseCheckFindstringFuncResult(directive *mkparser.Directive,
1226 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001227 if isEmptyString(xValue) {
1228 return &eqExpr{
1229 left: &callExpr{
1230 object: xCall.args[1],
1231 name: "find",
1232 args: []starlarkExpr{xCall.args[0]},
1233 returnType: starlarkTypeInt,
1234 },
1235 right: &intLiteralExpr{-1},
1236 isEq: !negate,
1237 }
Cole Faust0e9418c2021-12-13 16:33:25 -08001238 } else if s, ok := maybeString(xValue); ok {
1239 if s2, ok := maybeString(xCall.args[0]); ok && s == s2 {
1240 return &eqExpr{
1241 left: &callExpr{
1242 object: xCall.args[1],
1243 name: "find",
1244 args: []starlarkExpr{xCall.args[0]},
1245 returnType: starlarkTypeInt,
1246 },
1247 right: &intLiteralExpr{-1},
1248 isEq: negate,
1249 }
1250 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001251 }
Cole Faust0e9418c2021-12-13 16:33:25 -08001252 return ctx.newBadExpr(directive, "$(findstring) can only be compared to nothing or its first argument")
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001253}
1254
1255func (ctx *parseContext) parseCompareStripFuncResult(directive *mkparser.Directive,
1256 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
1257 if _, ok := xValue.(*stringLiteralExpr); !ok {
1258 return ctx.newBadExpr(directive, "strip result can be compared only to string: %s", xValue)
1259 }
1260 return &eqExpr{
1261 left: &callExpr{
1262 name: "strip",
1263 args: xCall.args,
1264 returnType: starlarkTypeString,
1265 },
1266 right: xValue, isEq: !negate}
1267}
1268
Cole Faustf035d402022-03-28 14:02:50 -07001269func (ctx *parseContext) maybeParseFunctionCall(node mkparser.Node, ref *mkparser.MakeString) (name string, args *mkparser.MakeString, ok bool) {
1270 ref.TrimLeftSpaces()
1271 ref.TrimRightSpaces()
1272
1273 words := ref.SplitN(" ", 2)
1274 if !words[0].Const() {
1275 return "", nil, false
1276 }
1277
1278 name = words[0].Dump()
1279 args = mkparser.SimpleMakeString("", words[0].Pos())
1280 if len(words) >= 2 {
1281 args = words[1]
1282 }
1283 args.TrimLeftSpaces()
1284 if name == "call" {
1285 words = args.SplitN(",", 2)
1286 if words[0].Empty() || !words[0].Const() {
1287 return "", nil, false
1288 }
1289 name = words[0].Dump()
1290 if len(words) < 2 {
Cole Faust6c41b8a2022-04-13 13:53:48 -07001291 args = mkparser.SimpleMakeString("", words[0].Pos())
Cole Faustf035d402022-03-28 14:02:50 -07001292 } else {
1293 args = words[1]
1294 }
1295 }
1296 ok = true
1297 return
1298}
1299
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001300// parses $(...), returning an expression
1301func (ctx *parseContext) parseReference(node mkparser.Node, ref *mkparser.MakeString) starlarkExpr {
1302 ref.TrimLeftSpaces()
1303 ref.TrimRightSpaces()
1304 refDump := ref.Dump()
1305
1306 // Handle only the case where the first (or only) word is constant
1307 words := ref.SplitN(" ", 2)
1308 if !words[0].Const() {
Cole Faust13238772022-04-28 14:29:57 -07001309 if len(words) == 1 {
1310 expr := ctx.parseMakeString(node, ref)
1311 return &callExpr{
1312 object: &identifierExpr{"cfg"},
1313 name: "get",
1314 args: []starlarkExpr{
1315 expr,
1316 &callExpr{
1317 object: &identifierExpr{"g"},
1318 name: "get",
1319 args: []starlarkExpr{
1320 expr,
1321 &stringLiteralExpr{literal: ""},
1322 },
1323 returnType: starlarkTypeUnknown,
1324 },
1325 },
1326 returnType: starlarkTypeUnknown,
1327 }
1328 } else {
1329 return ctx.newBadExpr(node, "reference is too complex: %s", refDump)
1330 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001331 }
1332
Cole Faust1e275862022-04-26 14:28:04 -07001333 if name, _, ok := ctx.maybeParseFunctionCall(node, ref); ok {
1334 if _, unsupported := unsupportedFunctions[name]; unsupported {
1335 return ctx.newBadExpr(node, "%s is not supported", refDump)
1336 }
1337 }
1338
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001339 // If it is a single word, it can be a simple variable
1340 // reference or a function call
Cole Faustf035d402022-03-28 14:02:50 -07001341 if len(words) == 1 && !isMakeControlFunc(refDump) && refDump != "shell" && refDump != "eval" {
Sasha Smundak65b547e2021-09-17 15:35:41 -07001342 if strings.HasPrefix(refDump, soongNsPrefix) {
1343 // TODO (asmundak): if we find many, maybe handle them.
Cole Faustc00184e2021-11-08 12:08:57 -08001344 return ctx.newBadExpr(node, "SOONG_CONFIG_ variables cannot be referenced, use soong_config_get instead: %s", refDump)
Sasha Smundak65b547e2021-09-17 15:35:41 -07001345 }
Cole Faustc36c9622021-12-07 15:20:45 -08001346 // Handle substitution references: https://www.gnu.org/software/make/manual/html_node/Substitution-Refs.html
1347 if strings.Contains(refDump, ":") {
1348 parts := strings.SplitN(refDump, ":", 2)
1349 substParts := strings.SplitN(parts[1], "=", 2)
1350 if len(substParts) < 2 || strings.Count(substParts[0], "%") > 1 {
1351 return ctx.newBadExpr(node, "Invalid substitution reference")
1352 }
1353 if !strings.Contains(substParts[0], "%") {
1354 if strings.Contains(substParts[1], "%") {
1355 return ctx.newBadExpr(node, "A substitution reference must have a %% in the \"before\" part of the substitution if it has one in the \"after\" part.")
1356 }
1357 substParts[0] = "%" + substParts[0]
1358 substParts[1] = "%" + substParts[1]
1359 }
1360 v := ctx.addVariable(parts[0])
1361 if v == nil {
1362 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1363 }
1364 return &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001365 name: baseName + ".mkpatsubst",
1366 returnType: starlarkTypeString,
Cole Faustc36c9622021-12-07 15:20:45 -08001367 args: []starlarkExpr{
1368 &stringLiteralExpr{literal: substParts[0]},
1369 &stringLiteralExpr{literal: substParts[1]},
Cole Faustf0632662022-04-07 13:59:24 -07001370 NewVariableRefExpr(v),
Cole Faustc36c9622021-12-07 15:20:45 -08001371 },
1372 }
1373 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001374 if v := ctx.addVariable(refDump); v != nil {
Cole Faustf0632662022-04-07 13:59:24 -07001375 return NewVariableRefExpr(v)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001376 }
1377 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1378 }
1379
Cole Faustf035d402022-03-28 14:02:50 -07001380 if name, args, ok := ctx.maybeParseFunctionCall(node, ref); ok {
1381 if kf, found := knownFunctions[name]; found {
1382 return kf.parse(ctx, node, args)
Sasha Smundak6609ba72021-07-22 18:32:56 -07001383 } else {
Cole Faustf035d402022-03-28 14:02:50 -07001384 return ctx.newBadExpr(node, "cannot handle invoking %s", name)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001385 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001386 }
Cole Faust1e275862022-04-26 14:28:04 -07001387 return ctx.newBadExpr(node, "cannot handle %s", refDump)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001388}
1389
1390type simpleCallParser struct {
1391 name string
1392 returnType starlarkType
1393 addGlobals bool
Cole Faust1cc08852022-02-28 11:12:08 -08001394 addHandle bool
Cole Faust9ebf6e42021-12-13 14:08:34 -08001395}
1396
1397func (p *simpleCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1398 expr := &callExpr{name: p.name, returnType: p.returnType}
1399 if p.addGlobals {
1400 expr.args = append(expr.args, &globalsExpr{})
1401 }
Cole Faust1cc08852022-02-28 11:12:08 -08001402 if p.addHandle {
1403 expr.args = append(expr.args, &identifierExpr{name: "handle"})
1404 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001405 for _, arg := range args.Split(",") {
1406 arg.TrimLeftSpaces()
1407 arg.TrimRightSpaces()
1408 x := ctx.parseMakeString(node, arg)
1409 if xBad, ok := x.(*badExpr); ok {
1410 return xBad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001411 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001412 expr.args = append(expr.args, x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001413 }
1414 return expr
1415}
1416
Cole Faust9ebf6e42021-12-13 14:08:34 -08001417type makeControlFuncParser struct {
1418 name string
1419}
1420
1421func (p *makeControlFuncParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1422 // Make control functions need special treatment as everything
1423 // after the name is a single text argument
1424 x := ctx.parseMakeString(node, args)
1425 if xBad, ok := x.(*badExpr); ok {
1426 return xBad
1427 }
1428 return &callExpr{
1429 name: p.name,
1430 args: []starlarkExpr{
1431 &stringLiteralExpr{ctx.script.mkFile},
1432 x,
1433 },
1434 returnType: starlarkTypeUnknown,
1435 }
1436}
1437
1438type shellCallParser struct{}
1439
1440func (p *shellCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1441 // Shell functions need special treatment as everything
1442 // after the name is a single text argument
1443 x := ctx.parseMakeString(node, args)
1444 if xBad, ok := x.(*badExpr); ok {
1445 return xBad
1446 }
1447 return &callExpr{
1448 name: baseName + ".shell",
1449 args: []starlarkExpr{x},
1450 returnType: starlarkTypeUnknown,
1451 }
1452}
1453
1454type myDirCallParser struct{}
1455
1456func (p *myDirCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1457 if !args.Empty() {
1458 return ctx.newBadExpr(node, "my-dir function cannot have any arguments passed to it.")
1459 }
Cole Faustf5adedc2022-03-18 14:05:06 -07001460 return &stringLiteralExpr{literal: filepath.Dir(ctx.script.mkFile)}
Cole Faust9ebf6e42021-12-13 14:08:34 -08001461}
1462
Cole Faustd2daabf2022-12-12 17:38:01 -08001463type andOrParser struct {
1464 isAnd bool
1465}
1466
1467func (p *andOrParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1468 if args.Empty() {
1469 return ctx.newBadExpr(node, "and/or function must have at least 1 argument")
1470 }
1471 op := "or"
1472 if p.isAnd {
1473 op = "and"
1474 }
1475
1476 argsParsed := make([]starlarkExpr, 0)
1477
1478 for _, arg := range args.Split(",") {
1479 arg.TrimLeftSpaces()
1480 arg.TrimRightSpaces()
1481 x := ctx.parseMakeString(node, arg)
1482 if xBad, ok := x.(*badExpr); ok {
1483 return xBad
1484 }
1485 argsParsed = append(argsParsed, x)
1486 }
1487 typ := starlarkTypeUnknown
1488 for _, arg := range argsParsed {
1489 if typ != arg.typ() && arg.typ() != starlarkTypeUnknown && typ != starlarkTypeUnknown {
1490 return ctx.newBadExpr(node, "Expected all arguments to $(or) or $(and) to have the same type, found %q and %q", typ.String(), arg.typ().String())
1491 }
1492 if arg.typ() != starlarkTypeUnknown {
1493 typ = arg.typ()
1494 }
1495 }
1496 result := argsParsed[0]
1497 for _, arg := range argsParsed[1:] {
1498 result = &binaryOpExpr{
1499 left: result,
1500 right: arg,
1501 op: op,
1502 returnType: typ,
1503 }
1504 }
1505 return result
1506}
1507
Cole Faust9ebf6e42021-12-13 14:08:34 -08001508type isProductInListCallParser struct{}
1509
1510func (p *isProductInListCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1511 if args.Empty() {
1512 return ctx.newBadExpr(node, "is-product-in-list requires an argument")
1513 }
1514 return &inExpr{
Cole Faustf0632662022-04-07 13:59:24 -07001515 expr: NewVariableRefExpr(ctx.addVariable("TARGET_PRODUCT")),
Cole Faust9ebf6e42021-12-13 14:08:34 -08001516 list: maybeConvertToStringList(ctx.parseMakeString(node, args)),
1517 isNot: false,
1518 }
1519}
1520
1521type isVendorBoardPlatformCallParser struct{}
1522
1523func (p *isVendorBoardPlatformCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1524 if args.Empty() || !identifierFullMatchRegex.MatchString(args.Dump()) {
1525 return ctx.newBadExpr(node, "cannot handle non-constant argument to is-vendor-board-platform")
1526 }
1527 return &inExpr{
Cole Faustf0632662022-04-07 13:59:24 -07001528 expr: NewVariableRefExpr(ctx.addVariable("TARGET_BOARD_PLATFORM")),
1529 list: NewVariableRefExpr(ctx.addVariable(args.Dump() + "_BOARD_PLATFORMS")),
Cole Faust9ebf6e42021-12-13 14:08:34 -08001530 isNot: false,
1531 }
1532}
1533
1534type isVendorBoardQcomCallParser struct{}
1535
1536func (p *isVendorBoardQcomCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1537 if !args.Empty() {
1538 return ctx.newBadExpr(node, "is-vendor-board-qcom does not accept any arguments")
1539 }
1540 return &inExpr{
Cole Faustf0632662022-04-07 13:59:24 -07001541 expr: NewVariableRefExpr(ctx.addVariable("TARGET_BOARD_PLATFORM")),
1542 list: NewVariableRefExpr(ctx.addVariable("QCOM_BOARD_PLATFORMS")),
Cole Faust9ebf6e42021-12-13 14:08:34 -08001543 isNot: false,
1544 }
1545}
1546
1547type substCallParser struct {
1548 fname string
1549}
1550
1551func (p *substCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001552 words := args.Split(",")
1553 if len(words) != 3 {
Cole Faust9ebf6e42021-12-13 14:08:34 -08001554 return ctx.newBadExpr(node, "%s function should have 3 arguments", p.fname)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001555 }
Sasha Smundak35434ed2021-11-05 16:29:56 -07001556 from := ctx.parseMakeString(node, words[0])
1557 if xBad, ok := from.(*badExpr); ok {
1558 return xBad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001559 }
Sasha Smundak35434ed2021-11-05 16:29:56 -07001560 to := ctx.parseMakeString(node, words[1])
1561 if xBad, ok := to.(*badExpr); ok {
1562 return xBad
1563 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001564 words[2].TrimLeftSpaces()
1565 words[2].TrimRightSpaces()
1566 obj := ctx.parseMakeString(node, words[2])
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001567 typ := obj.typ()
Cole Faust9ebf6e42021-12-13 14:08:34 -08001568 if typ == starlarkTypeString && p.fname == "subst" {
Sasha Smundak94b41c72021-07-12 18:30:42 -07001569 // Optimization: if it's $(subst from, to, string), emit string.replace(from, to)
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001570 return &callExpr{
1571 object: obj,
1572 name: "replace",
Sasha Smundak35434ed2021-11-05 16:29:56 -07001573 args: []starlarkExpr{from, to},
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001574 returnType: typ,
1575 }
1576 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001577 return &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001578 name: baseName + ".mk" + p.fname,
Sasha Smundak35434ed2021-11-05 16:29:56 -07001579 args: []starlarkExpr{from, to, obj},
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001580 returnType: obj.typ(),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001581 }
1582}
1583
Cole Faust9ebf6e42021-12-13 14:08:34 -08001584type ifCallParser struct{}
1585
1586func (p *ifCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Cole Faust4eadba72021-12-07 11:54:52 -08001587 words := args.Split(",")
1588 if len(words) != 2 && len(words) != 3 {
1589 return ctx.newBadExpr(node, "if function should have 2 or 3 arguments, found "+strconv.Itoa(len(words)))
1590 }
1591 condition := ctx.parseMakeString(node, words[0])
1592 ifTrue := ctx.parseMakeString(node, words[1])
1593 var ifFalse starlarkExpr
1594 if len(words) == 3 {
1595 ifFalse = ctx.parseMakeString(node, words[2])
1596 } else {
1597 switch ifTrue.typ() {
1598 case starlarkTypeList:
1599 ifFalse = &listExpr{items: []starlarkExpr{}}
1600 case starlarkTypeInt:
1601 ifFalse = &intLiteralExpr{literal: 0}
1602 case starlarkTypeBool:
1603 ifFalse = &boolLiteralExpr{literal: false}
1604 default:
1605 ifFalse = &stringLiteralExpr{literal: ""}
1606 }
1607 }
1608 return &ifExpr{
1609 condition,
1610 ifTrue,
1611 ifFalse,
1612 }
1613}
1614
Cole Faustf035d402022-03-28 14:02:50 -07001615type ifCallNodeParser struct{}
Cole Faust9ebf6e42021-12-13 14:08:34 -08001616
Cole Faustf035d402022-03-28 14:02:50 -07001617func (p *ifCallNodeParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode {
1618 words := args.Split(",")
1619 if len(words) != 2 && len(words) != 3 {
1620 return []starlarkNode{ctx.newBadNode(node, "if function should have 2 or 3 arguments, found "+strconv.Itoa(len(words)))}
1621 }
1622
1623 ifn := &ifNode{expr: ctx.parseMakeString(node, words[0])}
1624 cases := []*switchCase{
1625 {
1626 gate: ifn,
1627 nodes: ctx.parseNodeMakeString(node, words[1]),
1628 },
1629 }
1630 if len(words) == 3 {
1631 cases = append(cases, &switchCase{
1632 gate: &elseNode{},
1633 nodes: ctx.parseNodeMakeString(node, words[2]),
1634 })
1635 }
1636 if len(cases) == 2 {
1637 if len(cases[1].nodes) == 0 {
1638 // Remove else branch if it has no contents
1639 cases = cases[:1]
1640 } else if len(cases[0].nodes) == 0 {
1641 // If the if branch has no contents but the else does,
1642 // move them to the if and negate its condition
1643 ifn.expr = negateExpr(ifn.expr)
1644 cases[0].nodes = cases[1].nodes
1645 cases = cases[:1]
1646 }
1647 }
1648
1649 return []starlarkNode{&switchNode{ssCases: cases}}
1650}
1651
1652type foreachCallParser struct{}
1653
1654func (p *foreachCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Cole Faustb0d32ab2021-12-09 14:00:59 -08001655 words := args.Split(",")
1656 if len(words) != 3 {
1657 return ctx.newBadExpr(node, "foreach function should have 3 arguments, found "+strconv.Itoa(len(words)))
1658 }
1659 if !words[0].Const() || words[0].Empty() || !identifierFullMatchRegex.MatchString(words[0].Strings[0]) {
1660 return ctx.newBadExpr(node, "first argument to foreach function must be a simple string identifier")
1661 }
1662 loopVarName := words[0].Strings[0]
1663 list := ctx.parseMakeString(node, words[1])
1664 action := ctx.parseMakeString(node, words[2]).transform(func(expr starlarkExpr) starlarkExpr {
1665 if varRefExpr, ok := expr.(*variableRefExpr); ok && varRefExpr.ref.name() == loopVarName {
1666 return &identifierExpr{loopVarName}
1667 }
1668 return nil
1669 })
1670
1671 if list.typ() != starlarkTypeList {
1672 list = &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001673 name: baseName + ".words",
1674 returnType: starlarkTypeList,
Cole Faustb0d32ab2021-12-09 14:00:59 -08001675 args: []starlarkExpr{list},
1676 }
1677 }
1678
Cole Faust72374fc2022-05-05 11:45:04 -07001679 var result starlarkExpr = &foreachExpr{
Cole Faustb0d32ab2021-12-09 14:00:59 -08001680 varName: loopVarName,
1681 list: list,
1682 action: action,
1683 }
Cole Faust72374fc2022-05-05 11:45:04 -07001684
1685 if action.typ() == starlarkTypeList {
1686 result = &callExpr{
1687 name: baseName + ".flatten_2d_list",
1688 args: []starlarkExpr{result},
1689 returnType: starlarkTypeList,
1690 }
1691 }
1692
1693 return result
Cole Faustb0d32ab2021-12-09 14:00:59 -08001694}
1695
Cole Faustf035d402022-03-28 14:02:50 -07001696func transformNode(node starlarkNode, transformer func(expr starlarkExpr) starlarkExpr) {
1697 switch a := node.(type) {
1698 case *ifNode:
1699 a.expr = a.expr.transform(transformer)
1700 case *switchCase:
1701 transformNode(a.gate, transformer)
1702 for _, n := range a.nodes {
1703 transformNode(n, transformer)
1704 }
1705 case *switchNode:
1706 for _, n := range a.ssCases {
1707 transformNode(n, transformer)
1708 }
1709 case *exprNode:
1710 a.expr = a.expr.transform(transformer)
1711 case *assignmentNode:
1712 a.value = a.value.transform(transformer)
1713 case *foreachNode:
1714 a.list = a.list.transform(transformer)
1715 for _, n := range a.actions {
1716 transformNode(n, transformer)
1717 }
Cole Faust9df1d732022-04-26 16:27:22 -07001718 case *inheritNode:
1719 if b, ok := a.module.(inheritedDynamicModule); ok {
1720 b.path = b.path.transform(transformer)
1721 a.module = b
1722 }
1723 case *includeNode:
1724 if b, ok := a.module.(inheritedDynamicModule); ok {
1725 b.path = b.path.transform(transformer)
1726 a.module = b
1727 }
Cole Faustf035d402022-03-28 14:02:50 -07001728 }
1729}
1730
1731type foreachCallNodeParser struct{}
1732
1733func (p *foreachCallNodeParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode {
1734 words := args.Split(",")
1735 if len(words) != 3 {
1736 return []starlarkNode{ctx.newBadNode(node, "foreach function should have 3 arguments, found "+strconv.Itoa(len(words)))}
1737 }
1738 if !words[0].Const() || words[0].Empty() || !identifierFullMatchRegex.MatchString(words[0].Strings[0]) {
1739 return []starlarkNode{ctx.newBadNode(node, "first argument to foreach function must be a simple string identifier")}
1740 }
1741
1742 loopVarName := words[0].Strings[0]
1743
1744 list := ctx.parseMakeString(node, words[1])
1745 if list.typ() != starlarkTypeList {
1746 list = &callExpr{
1747 name: baseName + ".words",
1748 returnType: starlarkTypeList,
1749 args: []starlarkExpr{list},
1750 }
1751 }
1752
1753 actions := ctx.parseNodeMakeString(node, words[2])
1754 // TODO(colefaust): Replace transforming code with something more elegant
1755 for _, action := range actions {
1756 transformNode(action, func(expr starlarkExpr) starlarkExpr {
1757 if varRefExpr, ok := expr.(*variableRefExpr); ok && varRefExpr.ref.name() == loopVarName {
1758 return &identifierExpr{loopVarName}
1759 }
1760 return nil
1761 })
1762 }
1763
1764 return []starlarkNode{&foreachNode{
1765 varName: loopVarName,
1766 list: list,
1767 actions: actions,
1768 }}
1769}
1770
Cole Faust9ebf6e42021-12-13 14:08:34 -08001771type wordCallParser struct{}
1772
1773func (p *wordCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001774 words := args.Split(",")
1775 if len(words) != 2 {
1776 return ctx.newBadExpr(node, "word function should have 2 arguments")
1777 }
Cole Faust94c4a9a2022-04-22 17:43:52 -07001778 var index = 0
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001779 if words[0].Const() {
Cole Faust94c4a9a2022-04-22 17:43:52 -07001780 if i, err := strconv.Atoi(strings.TrimSpace(words[0].Strings[0])); err == nil {
1781 index = i
1782 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001783 }
1784 if index < 1 {
1785 return ctx.newBadExpr(node, "word index should be constant positive integer")
1786 }
1787 words[1].TrimLeftSpaces()
1788 words[1].TrimRightSpaces()
1789 array := ctx.parseMakeString(node, words[1])
Cole Faust94c4a9a2022-04-22 17:43:52 -07001790 if bad, ok := array.(*badExpr); ok {
1791 return bad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001792 }
1793 if array.typ() != starlarkTypeList {
Cole Faust94c4a9a2022-04-22 17:43:52 -07001794 array = &callExpr{
1795 name: baseName + ".words",
1796 args: []starlarkExpr{array},
1797 returnType: starlarkTypeList,
1798 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001799 }
Cole Faust94c4a9a2022-04-22 17:43:52 -07001800 return &indexExpr{array, &intLiteralExpr{index - 1}}
1801}
1802
1803type wordsCallParser struct{}
1804
1805func (p *wordsCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1806 args.TrimLeftSpaces()
1807 args.TrimRightSpaces()
1808 array := ctx.parseMakeString(node, args)
1809 if bad, ok := array.(*badExpr); ok {
1810 return bad
1811 }
1812 if array.typ() != starlarkTypeList {
1813 array = &callExpr{
1814 name: baseName + ".words",
1815 args: []starlarkExpr{array},
1816 returnType: starlarkTypeList,
1817 }
1818 }
1819 return &callExpr{
1820 name: "len",
1821 args: []starlarkExpr{array},
1822 returnType: starlarkTypeInt,
1823 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001824}
1825
Cole Faustb1103e22022-01-06 15:22:05 -08001826func parseIntegerArguments(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString, expectedArgs int) ([]starlarkExpr, error) {
1827 parsedArgs := make([]starlarkExpr, 0)
1828 for _, arg := range args.Split(",") {
1829 expr := ctx.parseMakeString(node, arg)
1830 if expr.typ() == starlarkTypeList {
1831 return nil, fmt.Errorf("argument to math argument has type list, which cannot be converted to int")
1832 }
1833 if s, ok := maybeString(expr); ok {
1834 intVal, err := strconv.Atoi(strings.TrimSpace(s))
1835 if err != nil {
1836 return nil, err
1837 }
1838 expr = &intLiteralExpr{literal: intVal}
1839 } else if expr.typ() != starlarkTypeInt {
1840 expr = &callExpr{
1841 name: "int",
1842 args: []starlarkExpr{expr},
1843 returnType: starlarkTypeInt,
1844 }
1845 }
1846 parsedArgs = append(parsedArgs, expr)
1847 }
1848 if len(parsedArgs) != expectedArgs {
1849 return nil, fmt.Errorf("function should have %d arguments", expectedArgs)
1850 }
1851 return parsedArgs, nil
1852}
1853
1854type mathComparisonCallParser struct {
1855 op string
1856}
1857
1858func (p *mathComparisonCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1859 parsedArgs, err := parseIntegerArguments(ctx, node, args, 2)
1860 if err != nil {
1861 return ctx.newBadExpr(node, err.Error())
1862 }
1863 return &binaryOpExpr{
1864 left: parsedArgs[0],
1865 right: parsedArgs[1],
1866 op: p.op,
1867 returnType: starlarkTypeBool,
1868 }
1869}
1870
1871type mathMaxOrMinCallParser struct {
1872 function string
1873}
1874
1875func (p *mathMaxOrMinCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1876 parsedArgs, err := parseIntegerArguments(ctx, node, args, 2)
1877 if err != nil {
1878 return ctx.newBadExpr(node, err.Error())
1879 }
1880 return &callExpr{
1881 object: nil,
1882 name: p.function,
1883 args: parsedArgs,
1884 returnType: starlarkTypeInt,
1885 }
1886}
1887
Cole Faustf035d402022-03-28 14:02:50 -07001888type evalNodeParser struct{}
1889
1890func (p *evalNodeParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode {
1891 parser := mkparser.NewParser("Eval expression", strings.NewReader(args.Dump()))
1892 nodes, errs := parser.Parse()
1893 if errs != nil {
1894 return []starlarkNode{ctx.newBadNode(node, "Unable to parse eval statement")}
1895 }
1896
1897 if len(nodes) == 0 {
1898 return []starlarkNode{}
1899 } else if len(nodes) == 1 {
Cole Faust73660422023-01-05 11:07:47 -08001900 // Replace the nodeLocator with one that just returns the location of
1901 // the $(eval) node. Otherwise, statements inside an $(eval) will show as
1902 // being on line 1 of the file, because they're on line 1 of
1903 // strings.NewReader(args.Dump())
1904 oldNodeLocator := ctx.script.nodeLocator
1905 ctx.script.nodeLocator = func(pos mkparser.Pos) int {
1906 return oldNodeLocator(node.Pos())
1907 }
1908 defer func() {
1909 ctx.script.nodeLocator = oldNodeLocator
1910 }()
1911
Cole Faustf035d402022-03-28 14:02:50 -07001912 switch n := nodes[0].(type) {
1913 case *mkparser.Assignment:
1914 if n.Name.Const() {
1915 return ctx.handleAssignment(n)
1916 }
1917 case *mkparser.Comment:
1918 return []starlarkNode{&commentNode{strings.TrimSpace("#" + n.Comment)}}
Cole Faust20052982022-04-22 14:43:55 -07001919 case *mkparser.Directive:
1920 if n.Name == "include" || n.Name == "-include" {
1921 return ctx.handleInclude(n)
1922 }
1923 case *mkparser.Variable:
1924 // Technically inherit-product(-if-exists) don't need to be put inside
1925 // an eval, but some makefiles do it, presumably because they copy+pasted
1926 // from a $(eval include ...)
1927 if name, _, ok := ctx.maybeParseFunctionCall(n, n.Name); ok {
1928 if name == "inherit-product" || name == "inherit-product-if-exists" {
1929 return ctx.handleVariable(n)
1930 }
1931 }
Cole Faustf035d402022-03-28 14:02:50 -07001932 }
1933 }
1934
Cole Faust20052982022-04-22 14:43:55 -07001935 return []starlarkNode{ctx.newBadNode(node, "Eval expression too complex; only assignments, comments, includes, and inherit-products are supported")}
Cole Faustf035d402022-03-28 14:02:50 -07001936}
1937
Cole Faust2dee63d2022-12-12 18:11:00 -08001938type lowerUpperParser struct {
1939 isUpper bool
1940}
1941
1942func (p *lowerUpperParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1943 fn := "lower"
1944 if p.isUpper {
1945 fn = "upper"
1946 }
1947 arg := ctx.parseMakeString(node, args)
1948
1949 return &callExpr{
1950 object: arg,
1951 name: fn,
1952 returnType: starlarkTypeString,
1953 }
1954}
1955
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001956func (ctx *parseContext) parseMakeString(node mkparser.Node, mk *mkparser.MakeString) starlarkExpr {
1957 if mk.Const() {
1958 return &stringLiteralExpr{mk.Dump()}
1959 }
1960 if mkRef, ok := mk.SingleVariable(); ok {
1961 return ctx.parseReference(node, mkRef)
1962 }
1963 // If we reached here, it's neither string literal nor a simple variable,
1964 // we need a full-blown interpolation node that will generate
1965 // "a%b%c" % (X, Y) for a$(X)b$(Y)c
Cole Faustfc438682021-12-14 12:46:32 -08001966 parts := make([]starlarkExpr, len(mk.Variables)+len(mk.Strings))
1967 for i := 0; i < len(parts); i++ {
1968 if i%2 == 0 {
1969 parts[i] = &stringLiteralExpr{literal: mk.Strings[i/2]}
1970 } else {
1971 parts[i] = ctx.parseReference(node, mk.Variables[i/2].Name)
1972 if x, ok := parts[i].(*badExpr); ok {
1973 return x
1974 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001975 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001976 }
Cole Faustfc438682021-12-14 12:46:32 -08001977 return NewInterpolateExpr(parts)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001978}
1979
Cole Faustf035d402022-03-28 14:02:50 -07001980func (ctx *parseContext) parseNodeMakeString(node mkparser.Node, mk *mkparser.MakeString) []starlarkNode {
1981 // Discard any constant values in the make string, as they would be top level
1982 // string literals and do nothing.
1983 result := make([]starlarkNode, 0, len(mk.Variables))
1984 for i := range mk.Variables {
1985 result = append(result, ctx.handleVariable(&mk.Variables[i])...)
1986 }
1987 return result
1988}
1989
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001990// Handles the statements whose treatment is the same in all contexts: comment,
1991// assignment, variable (which is a macro call in reality) and all constructs that
1992// do not handle in any context ('define directive and any unrecognized stuff).
Cole Faustdd569ae2022-01-31 15:48:29 -08001993func (ctx *parseContext) handleSimpleStatement(node mkparser.Node) []starlarkNode {
1994 var result []starlarkNode
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001995 switch x := node.(type) {
1996 case *mkparser.Comment:
Cole Faustdd569ae2022-01-31 15:48:29 -08001997 if n, handled := ctx.maybeHandleAnnotation(x); handled && n != nil {
1998 result = []starlarkNode{n}
1999 } else if !handled {
2000 result = []starlarkNode{&commentNode{strings.TrimSpace("#" + x.Comment)}}
Cole Faust7940c6a2022-01-31 15:54:05 -08002001 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002002 case *mkparser.Assignment:
Cole Faustdd569ae2022-01-31 15:48:29 -08002003 result = ctx.handleAssignment(x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002004 case *mkparser.Variable:
Cole Faustdd569ae2022-01-31 15:48:29 -08002005 result = ctx.handleVariable(x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002006 case *mkparser.Directive:
2007 switch x.Name {
2008 case "define":
Cole Faustdd569ae2022-01-31 15:48:29 -08002009 if res := ctx.maybeHandleDefine(x); res != nil {
2010 result = []starlarkNode{res}
2011 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002012 case "include", "-include":
Cole Faust20052982022-04-22 14:43:55 -07002013 result = ctx.handleInclude(x)
Cole Faust591a1fe2021-11-08 15:37:57 -08002014 case "ifeq", "ifneq", "ifdef", "ifndef":
Cole Faustdd569ae2022-01-31 15:48:29 -08002015 result = []starlarkNode{ctx.handleIfBlock(x)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002016 default:
Cole Faustdd569ae2022-01-31 15:48:29 -08002017 result = []starlarkNode{ctx.newBadNode(x, "unexpected directive %s", x.Name)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002018 }
2019 default:
Cole Faustdd569ae2022-01-31 15:48:29 -08002020 result = []starlarkNode{ctx.newBadNode(x, "unsupported line %s", strings.ReplaceAll(x.Dump(), "\n", "\n#"))}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002021 }
Cole Faust6c934f62022-01-06 15:51:12 -08002022
2023 // Clear the includeTops after each non-comment statement
2024 // so that include annotations placed on certain statements don't apply
2025 // globally for the rest of the makefile was well.
Cole Faustf92c9f22022-03-14 14:35:50 -07002026 if _, wasComment := node.(*mkparser.Comment); !wasComment {
2027 ctx.atTopOfMakefile = false
Cole Faust6c934f62022-01-06 15:51:12 -08002028 ctx.includeTops = []string{}
2029 }
Cole Faustdd569ae2022-01-31 15:48:29 -08002030
2031 if result == nil {
2032 result = []starlarkNode{}
2033 }
Cole Faustf035d402022-03-28 14:02:50 -07002034
Cole Faustdd569ae2022-01-31 15:48:29 -08002035 return result
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002036}
2037
Cole Faustf92c9f22022-03-14 14:35:50 -07002038// The types allowed in a type_hint
2039var typeHintMap = map[string]starlarkType{
2040 "string": starlarkTypeString,
2041 "list": starlarkTypeList,
2042}
2043
Sasha Smundak6d852dd2021-09-27 20:34:39 -07002044// Processes annotation. An annotation is a comment that starts with #RBC# and provides
2045// a conversion hint -- say, where to look for the dynamically calculated inherit/include
Cole Faust7940c6a2022-01-31 15:54:05 -08002046// paths. Returns true if the comment was a successfully-handled annotation.
Cole Faustdd569ae2022-01-31 15:48:29 -08002047func (ctx *parseContext) maybeHandleAnnotation(cnode *mkparser.Comment) (starlarkNode, bool) {
Sasha Smundak6d852dd2021-09-27 20:34:39 -07002048 maybeTrim := func(s, prefix string) (string, bool) {
2049 if strings.HasPrefix(s, prefix) {
2050 return strings.TrimSpace(strings.TrimPrefix(s, prefix)), true
2051 }
2052 return s, false
2053 }
2054 annotation, ok := maybeTrim(cnode.Comment, annotationCommentPrefix)
2055 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -08002056 return nil, false
Sasha Smundak6d852dd2021-09-27 20:34:39 -07002057 }
2058 if p, ok := maybeTrim(annotation, "include_top"); ok {
Cole Faustf7ed5342021-12-21 14:15:12 -08002059 // Don't allow duplicate include tops, because then we will generate
2060 // invalid starlark code. (duplicate keys in the _entry dictionary)
2061 for _, top := range ctx.includeTops {
2062 if top == p {
Cole Faustdd569ae2022-01-31 15:48:29 -08002063 return nil, true
Cole Faustf7ed5342021-12-21 14:15:12 -08002064 }
2065 }
Sasha Smundak6d852dd2021-09-27 20:34:39 -07002066 ctx.includeTops = append(ctx.includeTops, p)
Cole Faustdd569ae2022-01-31 15:48:29 -08002067 return nil, true
Cole Faustf92c9f22022-03-14 14:35:50 -07002068 } else if p, ok := maybeTrim(annotation, "type_hint"); ok {
2069 // Type hints must come at the beginning the file, to avoid confusion
2070 // if a type hint was specified later and thus only takes effect for half
2071 // of the file.
2072 if !ctx.atTopOfMakefile {
2073 return ctx.newBadNode(cnode, "type_hint annotations must come before the first Makefile statement"), true
2074 }
2075
2076 parts := strings.Fields(p)
2077 if len(parts) <= 1 {
2078 return ctx.newBadNode(cnode, "Invalid type_hint annotation: %s. Must be a variable type followed by a list of variables of that type", p), true
2079 }
2080
2081 var varType starlarkType
2082 if varType, ok = typeHintMap[parts[0]]; !ok {
2083 varType = starlarkTypeUnknown
2084 }
2085 if varType == starlarkTypeUnknown {
2086 return ctx.newBadNode(cnode, "Invalid type_hint annotation. Only list/string types are accepted, found %s", parts[0]), true
2087 }
2088
2089 for _, name := range parts[1:] {
2090 // Don't allow duplicate type hints
2091 if _, ok := ctx.typeHints[name]; ok {
2092 return ctx.newBadNode(cnode, "Duplicate type hint for variable %s", name), true
2093 }
2094 ctx.typeHints[name] = varType
2095 }
2096 return nil, true
Sasha Smundak6d852dd2021-09-27 20:34:39 -07002097 }
Cole Faustdd569ae2022-01-31 15:48:29 -08002098 return ctx.newBadNode(cnode, "unsupported annotation %s", cnode.Comment), true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002099}
2100
2101func (ctx *parseContext) loadedModulePath(path string) string {
2102 // During the transition to Roboleaf some of the product configuration files
2103 // will be converted and checked in while the others will be generated on the fly
2104 // and run. The runner (rbcrun application) accommodates this by allowing three
2105 // different ways to specify the loaded file location:
2106 // 1) load(":<file>",...) loads <file> from the same directory
2107 // 2) load("//path/relative/to/source/root:<file>", ...) loads <file> source tree
2108 // 3) load("/absolute/path/to/<file> absolute path
2109 // If the file being generated and the file it wants to load are in the same directory,
2110 // generate option 1.
2111 // Otherwise, if output directory is not specified, generate 2)
2112 // Finally, if output directory has been specified and the file being generated and
2113 // the file it wants to load from are in the different directories, generate 2) or 3):
2114 // * if the file being loaded exists in the source tree, generate 2)
2115 // * otherwise, generate 3)
2116 // Finally, figure out the loaded module path and name and create a node for it
2117 loadedModuleDir := filepath.Dir(path)
2118 base := filepath.Base(path)
2119 loadedModuleName := strings.TrimSuffix(base, filepath.Ext(base)) + ctx.outputSuffix
2120 if loadedModuleDir == filepath.Dir(ctx.script.mkFile) {
2121 return ":" + loadedModuleName
2122 }
2123 if ctx.outputDir == "" {
2124 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
2125 }
2126 if _, err := os.Stat(filepath.Join(loadedModuleDir, loadedModuleName)); err == nil {
2127 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
2128 }
2129 return filepath.Join(ctx.outputDir, loadedModuleDir, loadedModuleName)
2130}
2131
Sasha Smundak3deb9682021-07-26 18:42:25 -07002132func (ctx *parseContext) addSoongNamespace(ns string) {
2133 if _, ok := ctx.soongNamespaces[ns]; ok {
2134 return
2135 }
2136 ctx.soongNamespaces[ns] = make(map[string]bool)
2137}
2138
2139func (ctx *parseContext) hasSoongNamespace(name string) bool {
2140 _, ok := ctx.soongNamespaces[name]
2141 return ok
2142}
2143
2144func (ctx *parseContext) updateSoongNamespace(replace bool, namespaceName string, varNames []string) {
2145 ctx.addSoongNamespace(namespaceName)
2146 vars := ctx.soongNamespaces[namespaceName]
2147 if replace {
2148 vars = make(map[string]bool)
2149 ctx.soongNamespaces[namespaceName] = vars
2150 }
2151 for _, v := range varNames {
2152 vars[v] = true
2153 }
2154}
2155
2156func (ctx *parseContext) hasNamespaceVar(namespaceName string, varName string) bool {
2157 vars, ok := ctx.soongNamespaces[namespaceName]
2158 if ok {
2159 _, ok = vars[varName]
2160 }
2161 return ok
2162}
2163
Sasha Smundak422b6142021-11-11 18:31:59 -08002164func (ctx *parseContext) errorLocation(node mkparser.Node) ErrorLocation {
2165 return ErrorLocation{ctx.script.mkFile, ctx.script.nodeLocator(node.Pos())}
2166}
2167
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002168func (ss *StarlarkScript) String() string {
2169 return NewGenerateContext(ss).emit()
2170}
2171
2172func (ss *StarlarkScript) SubConfigFiles() []string {
Sasha Smundak6609ba72021-07-22 18:32:56 -07002173
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002174 var subs []string
2175 for _, src := range ss.inherited {
2176 subs = append(subs, src.originalPath)
2177 }
2178 return subs
2179}
2180
2181func (ss *StarlarkScript) HasErrors() bool {
2182 return ss.hasErrors
2183}
2184
2185// Convert reads and parses a makefile. If successful, parsed tree
2186// is returned and then can be passed to String() to get the generated
2187// Starlark file.
2188func Convert(req Request) (*StarlarkScript, error) {
2189 reader := req.Reader
2190 if reader == nil {
2191 mkContents, err := ioutil.ReadFile(req.MkFile)
2192 if err != nil {
2193 return nil, err
2194 }
2195 reader = bytes.NewBuffer(mkContents)
2196 }
2197 parser := mkparser.NewParser(req.MkFile, reader)
2198 nodes, errs := parser.Parse()
2199 if len(errs) > 0 {
2200 for _, e := range errs {
2201 fmt.Fprintln(os.Stderr, "ERROR:", e)
2202 }
2203 return nil, fmt.Errorf("bad makefile %s", req.MkFile)
2204 }
2205 starScript := &StarlarkScript{
Sasha Smundak422b6142021-11-11 18:31:59 -08002206 moduleName: moduleNameForFile(req.MkFile),
2207 mkFile: req.MkFile,
Sasha Smundak422b6142021-11-11 18:31:59 -08002208 traceCalls: req.TraceCalls,
2209 sourceFS: req.SourceFS,
2210 makefileFinder: req.MakefileFinder,
2211 nodeLocator: func(pos mkparser.Pos) int { return parser.Unpack(pos).Line },
Cole Faustdd569ae2022-01-31 15:48:29 -08002212 nodes: make([]starlarkNode, 0),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002213 }
2214 ctx := newParseContext(starScript, nodes)
2215 ctx.outputSuffix = req.OutputSuffix
2216 ctx.outputDir = req.OutputDir
2217 ctx.errorLogger = req.ErrorLogger
2218 if len(req.TracedVariables) > 0 {
2219 ctx.tracedVariables = make(map[string]bool)
2220 for _, v := range req.TracedVariables {
2221 ctx.tracedVariables[v] = true
2222 }
2223 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002224 for ctx.hasNodes() && ctx.fatalError == nil {
Cole Faustdd569ae2022-01-31 15:48:29 -08002225 starScript.nodes = append(starScript.nodes, ctx.handleSimpleStatement(ctx.getNode())...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002226 }
2227 if ctx.fatalError != nil {
2228 return nil, ctx.fatalError
2229 }
2230 return starScript, nil
2231}
2232
Cole Faust864028a2021-12-01 13:43:17 -08002233func Launcher(mainModuleUri, inputVariablesUri, mainModuleName string) string {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002234 var buf bytes.Buffer
2235 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
Cole Faust864028a2021-12-01 13:43:17 -08002236 fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri)
Sasha Smundakd7d07ad2021-09-10 15:42:34 -07002237 fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri)
Cole Faust864028a2021-12-01 13:43:17 -08002238 fmt.Fprintf(&buf, "%s(%s(%q, init, input_variables_init))\n", cfnPrintVars, cfnMain, mainModuleName)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002239 return buf.String()
2240}
2241
Cole Faust6ed7cb42021-10-07 17:08:46 -07002242func BoardLauncher(mainModuleUri string, inputVariablesUri string) string {
2243 var buf bytes.Buffer
2244 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
2245 fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri)
2246 fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri)
Cole Fausta0604662022-02-28 11:53:58 -08002247 fmt.Fprintf(&buf, "%s(%s(init, input_variables_init))\n", cfnPrintVars, cfnBoardMain)
Cole Faust6ed7cb42021-10-07 17:08:46 -07002248 return buf.String()
2249}
2250
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002251func MakePath2ModuleName(mkPath string) string {
2252 return strings.TrimSuffix(mkPath, filepath.Ext(mkPath))
2253}