blob: 8225df60d42b40efe46e577bc93a4897b0831b39 [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] != '-'
944 return ctx.handleSubConfig(v, ctx.parseMakeString(v, v.Args), loadAlways, func(im inheritedModule) starlarkNode {
Cole Faustdd569ae2022-01-31 15:48:29 -0800945 return &includeNode{im, loadAlways}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700946 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800947}
948
Cole Faustdd569ae2022-01-31 15:48:29 -0800949func (ctx *parseContext) handleVariable(v *mkparser.Variable) []starlarkNode {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800950 // Handle:
951 // $(call inherit-product,...)
952 // $(call inherit-product-if-exists,...)
953 // $(info xxx)
954 // $(warning xxx)
955 // $(error xxx)
Cole Faust9ebf6e42021-12-13 14:08:34 -0800956 // $(call other-custom-functions,...)
957
Cole Faustf035d402022-03-28 14:02:50 -0700958 if name, args, ok := ctx.maybeParseFunctionCall(v, v.Name); ok {
959 if kf, ok := knownNodeFunctions[name]; ok {
960 return kf.parse(ctx, v, args)
961 }
Cole Faust9ebf6e42021-12-13 14:08:34 -0800962 }
Cole Faustf035d402022-03-28 14:02:50 -0700963
Cole Faustdd569ae2022-01-31 15:48:29 -0800964 return []starlarkNode{&exprNode{expr: ctx.parseReference(v, v.Name)}}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800965}
966
Cole Faustdd569ae2022-01-31 15:48:29 -0800967func (ctx *parseContext) maybeHandleDefine(directive *mkparser.Directive) starlarkNode {
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700968 macro_name := strings.Fields(directive.Args.Strings[0])[0]
969 // Ignore the macros that we handle
Cole Faust9ebf6e42021-12-13 14:08:34 -0800970 _, ignored := ignoredDefines[macro_name]
971 _, known := knownFunctions[macro_name]
972 if !ignored && !known {
Cole Faustdd569ae2022-01-31 15:48:29 -0800973 return ctx.newBadNode(directive, "define is not supported: %s", macro_name)
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700974 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800975 return nil
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800976}
977
Cole Faustdd569ae2022-01-31 15:48:29 -0800978func (ctx *parseContext) handleIfBlock(ifDirective *mkparser.Directive) starlarkNode {
979 ssSwitch := &switchNode{
980 ssCases: []*switchCase{ctx.processBranch(ifDirective)},
981 }
982 for ctx.hasNodes() && ctx.fatalError == nil {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800983 node := ctx.getNode()
984 switch x := node.(type) {
985 case *mkparser.Directive:
986 switch x.Name {
987 case "else", "elifdef", "elifndef", "elifeq", "elifneq":
Cole Faustdd569ae2022-01-31 15:48:29 -0800988 ssSwitch.ssCases = append(ssSwitch.ssCases, ctx.processBranch(x))
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800989 case "endif":
Cole Faustdd569ae2022-01-31 15:48:29 -0800990 return ssSwitch
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800991 default:
Cole Faustdd569ae2022-01-31 15:48:29 -0800992 return ctx.newBadNode(node, "unexpected directive %s", x.Name)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800993 }
994 default:
Cole Faustdd569ae2022-01-31 15:48:29 -0800995 return ctx.newBadNode(ifDirective, "unexpected statement")
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800996 }
997 }
998 if ctx.fatalError == nil {
999 ctx.fatalError = fmt.Errorf("no matching endif for %s", ifDirective.Dump())
1000 }
Cole Faustdd569ae2022-01-31 15:48:29 -08001001 return ctx.newBadNode(ifDirective, "no matching endif for %s", ifDirective.Dump())
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001002}
1003
1004// processBranch processes a single branch (if/elseif/else) until the next directive
1005// on the same level.
Cole Faustdd569ae2022-01-31 15:48:29 -08001006func (ctx *parseContext) processBranch(check *mkparser.Directive) *switchCase {
1007 block := &switchCase{gate: ctx.parseCondition(check)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001008 defer func() {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001009 ctx.ifNestLevel--
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001010 }()
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001011 ctx.ifNestLevel++
1012
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001013 for ctx.hasNodes() {
1014 node := ctx.getNode()
Cole Faust591a1fe2021-11-08 15:37:57 -08001015 if d, ok := node.(*mkparser.Directive); ok {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001016 switch d.Name {
1017 case "else", "elifdef", "elifndef", "elifeq", "elifneq", "endif":
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001018 ctx.backNode()
Cole Faustdd569ae2022-01-31 15:48:29 -08001019 return block
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001020 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001021 }
Cole Faustdd569ae2022-01-31 15:48:29 -08001022 block.nodes = append(block.nodes, ctx.handleSimpleStatement(node)...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001023 }
1024 ctx.fatalError = fmt.Errorf("no matching endif for %s", check.Dump())
Cole Faustdd569ae2022-01-31 15:48:29 -08001025 return block
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001026}
1027
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001028func (ctx *parseContext) parseCondition(check *mkparser.Directive) starlarkNode {
1029 switch check.Name {
1030 case "ifdef", "ifndef", "elifdef", "elifndef":
Cole Faust71514c02022-01-27 17:21:41 -08001031 if !check.Args.Const() {
Cole Faustdd569ae2022-01-31 15:48:29 -08001032 return ctx.newBadNode(check, "ifdef variable ref too complex: %s", check.Args.Dump())
Cole Faust71514c02022-01-27 17:21:41 -08001033 }
Cole Faustf0632662022-04-07 13:59:24 -07001034 v := NewVariableRefExpr(ctx.addVariable(check.Args.Strings[0]))
Cole Faust71514c02022-01-27 17:21:41 -08001035 if strings.HasSuffix(check.Name, "ndef") {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001036 v = &notExpr{v}
1037 }
1038 return &ifNode{
1039 isElif: strings.HasPrefix(check.Name, "elif"),
1040 expr: v,
1041 }
1042 case "ifeq", "ifneq", "elifeq", "elifneq":
1043 return &ifNode{
1044 isElif: strings.HasPrefix(check.Name, "elif"),
1045 expr: ctx.parseCompare(check),
1046 }
1047 case "else":
1048 return &elseNode{}
1049 default:
1050 panic(fmt.Errorf("%s: unknown directive: %s", ctx.script.mkFile, check.Dump()))
1051 }
1052}
1053
1054func (ctx *parseContext) newBadExpr(node mkparser.Node, text string, args ...interface{}) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001055 if ctx.errorLogger != nil {
Sasha Smundak422b6142021-11-11 18:31:59 -08001056 ctx.errorLogger.NewError(ctx.errorLocation(node), node, text, args...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001057 }
1058 ctx.script.hasErrors = true
Cole Faustdd569ae2022-01-31 15:48:29 -08001059 return &badExpr{errorLocation: ctx.errorLocation(node), message: fmt.Sprintf(text, args...)}
1060}
1061
1062// records that the given node failed to be converted and includes an explanatory message
1063func (ctx *parseContext) newBadNode(failedNode mkparser.Node, message string, args ...interface{}) starlarkNode {
1064 return &exprNode{ctx.newBadExpr(failedNode, message, args...)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001065}
1066
1067func (ctx *parseContext) parseCompare(cond *mkparser.Directive) starlarkExpr {
1068 // Strip outer parentheses
1069 mkArg := cloneMakeString(cond.Args)
1070 mkArg.Strings[0] = strings.TrimLeft(mkArg.Strings[0], "( ")
1071 n := len(mkArg.Strings)
1072 mkArg.Strings[n-1] = strings.TrimRight(mkArg.Strings[n-1], ") ")
1073 args := mkArg.Split(",")
1074 // TODO(asmundak): handle the case where the arguments are in quotes and space-separated
1075 if len(args) != 2 {
1076 return ctx.newBadExpr(cond, "ifeq/ifneq len(args) != 2 %s", cond.Dump())
1077 }
1078 args[0].TrimRightSpaces()
1079 args[1].TrimLeftSpaces()
1080
1081 isEq := !strings.HasSuffix(cond.Name, "neq")
Cole Faustf8320212021-11-10 15:05:07 -08001082 xLeft := ctx.parseMakeString(cond, args[0])
1083 xRight := ctx.parseMakeString(cond, args[1])
1084 if bad, ok := xLeft.(*badExpr); ok {
1085 return bad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001086 }
Cole Faustf8320212021-11-10 15:05:07 -08001087 if bad, ok := xRight.(*badExpr); ok {
1088 return bad
1089 }
1090
1091 if expr, ok := ctx.parseCompareSpecialCases(cond, xLeft, xRight); ok {
1092 return expr
1093 }
1094
Cole Faust9ebf6e42021-12-13 14:08:34 -08001095 var stringOperand string
1096 var otherOperand starlarkExpr
1097 if s, ok := maybeString(xLeft); ok {
1098 stringOperand = s
1099 otherOperand = xRight
1100 } else if s, ok := maybeString(xRight); ok {
1101 stringOperand = s
1102 otherOperand = xLeft
1103 }
1104
Cole Faust9ebf6e42021-12-13 14:08:34 -08001105 // If we've identified one of the operands as being a string literal, check
1106 // for some special cases we can do to simplify the resulting expression.
1107 if otherOperand != nil {
1108 if stringOperand == "" {
1109 if isEq {
Cole Faustf035d402022-03-28 14:02:50 -07001110 return negateExpr(otherOperand)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001111 } else {
1112 return otherOperand
1113 }
1114 }
1115 if stringOperand == "true" && otherOperand.typ() == starlarkTypeBool {
1116 if !isEq {
Cole Faustf035d402022-03-28 14:02:50 -07001117 return negateExpr(otherOperand)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001118 } else {
1119 return otherOperand
1120 }
1121 }
Cole Fausta99afdf2022-04-26 12:06:49 -07001122 if otherOperand.typ() == starlarkTypeList {
1123 fields := strings.Fields(stringOperand)
1124 elements := make([]starlarkExpr, len(fields))
1125 for i, s := range fields {
1126 elements[i] = &stringLiteralExpr{literal: s}
1127 }
1128 return &eqExpr{
1129 left: otherOperand,
1130 right: &listExpr{elements},
1131 isEq: isEq,
1132 }
1133 }
Cole Faustb1103e22022-01-06 15:22:05 -08001134 if intOperand, err := strconv.Atoi(strings.TrimSpace(stringOperand)); err == nil && otherOperand.typ() == starlarkTypeInt {
1135 return &eqExpr{
1136 left: otherOperand,
1137 right: &intLiteralExpr{literal: intOperand},
1138 isEq: isEq,
1139 }
1140 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001141 }
1142
Cole Faustf8320212021-11-10 15:05:07 -08001143 return &eqExpr{left: xLeft, right: xRight, isEq: isEq}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001144}
1145
Cole Faustf8320212021-11-10 15:05:07 -08001146// Given an if statement's directive and the left/right starlarkExprs,
1147// check if the starlarkExprs are one of a few hardcoded special cases
Cole Faust9932f752022-02-08 11:56:25 -08001148// that can be converted to a simpler equality expression than simply comparing
Cole Faustf8320212021-11-10 15:05:07 -08001149// the two.
1150func (ctx *parseContext) parseCompareSpecialCases(directive *mkparser.Directive, left starlarkExpr,
1151 right starlarkExpr) (starlarkExpr, bool) {
1152 isEq := !strings.HasSuffix(directive.Name, "neq")
1153
1154 // All the special cases require a call on one side and a
1155 // string literal/variable on the other. Turn the left/right variables into
1156 // call/value variables, and return false if that's not possible.
1157 var value starlarkExpr = nil
1158 call, ok := left.(*callExpr)
1159 if ok {
1160 switch right.(type) {
1161 case *stringLiteralExpr, *variableRefExpr:
1162 value = right
1163 }
1164 } else {
1165 call, _ = right.(*callExpr)
1166 switch left.(type) {
1167 case *stringLiteralExpr, *variableRefExpr:
1168 value = left
1169 }
1170 }
1171
1172 if call == nil || value == nil {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001173 return nil, false
1174 }
Cole Faustf8320212021-11-10 15:05:07 -08001175
Cole Faustf8320212021-11-10 15:05:07 -08001176 switch call.name {
Cole Faust9932f752022-02-08 11:56:25 -08001177 case baseName + ".filter":
1178 return ctx.parseCompareFilterFuncResult(directive, call, value, isEq)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001179 case baseName + ".findstring":
Cole Faustf8320212021-11-10 15:05:07 -08001180 return ctx.parseCheckFindstringFuncResult(directive, call, value, !isEq), true
Cole Faust9ebf6e42021-12-13 14:08:34 -08001181 case baseName + ".strip":
Cole Faustf8320212021-11-10 15:05:07 -08001182 return ctx.parseCompareStripFuncResult(directive, call, value, !isEq), true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001183 }
Cole Faustf8320212021-11-10 15:05:07 -08001184 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001185}
1186
1187func (ctx *parseContext) parseCompareFilterFuncResult(cond *mkparser.Directive,
Cole Faust9932f752022-02-08 11:56:25 -08001188 filterFuncCall *callExpr, xValue starlarkExpr, negate bool) (starlarkExpr, bool) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001189 // We handle:
Sasha Smundak0554d762021-07-08 18:26:12 -07001190 // * ifeq/ifneq (,$(filter v1 v2 ..., EXPR) becomes if EXPR not in/in ["v1", "v2", ...]
1191 // * ifeq/ifneq (,$(filter EXPR, v1 v2 ...) becomes if EXPR not in/in ["v1", "v2", ...]
Cole Faust9932f752022-02-08 11:56:25 -08001192 if x, ok := xValue.(*stringLiteralExpr); !ok || x.literal != "" {
1193 return nil, false
1194 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001195 xPattern := filterFuncCall.args[0]
1196 xText := filterFuncCall.args[1]
1197 var xInList *stringLiteralExpr
Sasha Smundak0554d762021-07-08 18:26:12 -07001198 var expr starlarkExpr
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001199 var ok bool
Cole Faust9932f752022-02-08 11:56:25 -08001200 if xInList, ok = xPattern.(*stringLiteralExpr); ok && !strings.ContainsRune(xInList.literal, '%') && xText.typ() == starlarkTypeList {
1201 expr = xText
1202 } else if xInList, ok = xText.(*stringLiteralExpr); ok {
1203 expr = xPattern
1204 } else {
1205 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001206 }
Cole Faust9932f752022-02-08 11:56:25 -08001207 slExpr := newStringListExpr(strings.Fields(xInList.literal))
1208 // Generate simpler code for the common cases:
1209 if expr.typ() == starlarkTypeList {
1210 if len(slExpr.items) == 1 {
1211 // Checking that a string belongs to list
1212 return &inExpr{isNot: negate, list: expr, expr: slExpr.items[0]}, true
Sasha Smundak0554d762021-07-08 18:26:12 -07001213 } else {
Cole Faust9932f752022-02-08 11:56:25 -08001214 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001215 }
Cole Faust9932f752022-02-08 11:56:25 -08001216 } else if len(slExpr.items) == 1 {
1217 return &eqExpr{left: expr, right: slExpr.items[0], isEq: !negate}, true
1218 } else {
1219 return &inExpr{isNot: negate, list: newStringListExpr(strings.Fields(xInList.literal)), expr: expr}, true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001220 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001221}
1222
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001223func (ctx *parseContext) parseCheckFindstringFuncResult(directive *mkparser.Directive,
1224 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001225 if isEmptyString(xValue) {
1226 return &eqExpr{
1227 left: &callExpr{
1228 object: xCall.args[1],
1229 name: "find",
1230 args: []starlarkExpr{xCall.args[0]},
1231 returnType: starlarkTypeInt,
1232 },
1233 right: &intLiteralExpr{-1},
1234 isEq: !negate,
1235 }
Cole Faust0e9418c2021-12-13 16:33:25 -08001236 } else if s, ok := maybeString(xValue); ok {
1237 if s2, ok := maybeString(xCall.args[0]); ok && s == s2 {
1238 return &eqExpr{
1239 left: &callExpr{
1240 object: xCall.args[1],
1241 name: "find",
1242 args: []starlarkExpr{xCall.args[0]},
1243 returnType: starlarkTypeInt,
1244 },
1245 right: &intLiteralExpr{-1},
1246 isEq: negate,
1247 }
1248 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001249 }
Cole Faust0e9418c2021-12-13 16:33:25 -08001250 return ctx.newBadExpr(directive, "$(findstring) can only be compared to nothing or its first argument")
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001251}
1252
1253func (ctx *parseContext) parseCompareStripFuncResult(directive *mkparser.Directive,
1254 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
1255 if _, ok := xValue.(*stringLiteralExpr); !ok {
1256 return ctx.newBadExpr(directive, "strip result can be compared only to string: %s", xValue)
1257 }
1258 return &eqExpr{
1259 left: &callExpr{
1260 name: "strip",
1261 args: xCall.args,
1262 returnType: starlarkTypeString,
1263 },
1264 right: xValue, isEq: !negate}
1265}
1266
Cole Faustf035d402022-03-28 14:02:50 -07001267func (ctx *parseContext) maybeParseFunctionCall(node mkparser.Node, ref *mkparser.MakeString) (name string, args *mkparser.MakeString, ok bool) {
1268 ref.TrimLeftSpaces()
1269 ref.TrimRightSpaces()
1270
1271 words := ref.SplitN(" ", 2)
1272 if !words[0].Const() {
1273 return "", nil, false
1274 }
1275
1276 name = words[0].Dump()
1277 args = mkparser.SimpleMakeString("", words[0].Pos())
1278 if len(words) >= 2 {
1279 args = words[1]
1280 }
1281 args.TrimLeftSpaces()
1282 if name == "call" {
1283 words = args.SplitN(",", 2)
1284 if words[0].Empty() || !words[0].Const() {
1285 return "", nil, false
1286 }
1287 name = words[0].Dump()
1288 if len(words) < 2 {
Cole Faust6c41b8a2022-04-13 13:53:48 -07001289 args = mkparser.SimpleMakeString("", words[0].Pos())
Cole Faustf035d402022-03-28 14:02:50 -07001290 } else {
1291 args = words[1]
1292 }
1293 }
1294 ok = true
1295 return
1296}
1297
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001298// parses $(...), returning an expression
1299func (ctx *parseContext) parseReference(node mkparser.Node, ref *mkparser.MakeString) starlarkExpr {
1300 ref.TrimLeftSpaces()
1301 ref.TrimRightSpaces()
1302 refDump := ref.Dump()
1303
1304 // Handle only the case where the first (or only) word is constant
1305 words := ref.SplitN(" ", 2)
1306 if !words[0].Const() {
Cole Faust13238772022-04-28 14:29:57 -07001307 if len(words) == 1 {
1308 expr := ctx.parseMakeString(node, ref)
1309 return &callExpr{
1310 object: &identifierExpr{"cfg"},
1311 name: "get",
1312 args: []starlarkExpr{
1313 expr,
1314 &callExpr{
1315 object: &identifierExpr{"g"},
1316 name: "get",
1317 args: []starlarkExpr{
1318 expr,
1319 &stringLiteralExpr{literal: ""},
1320 },
1321 returnType: starlarkTypeUnknown,
1322 },
1323 },
1324 returnType: starlarkTypeUnknown,
1325 }
1326 } else {
1327 return ctx.newBadExpr(node, "reference is too complex: %s", refDump)
1328 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001329 }
1330
Cole Faust1e275862022-04-26 14:28:04 -07001331 if name, _, ok := ctx.maybeParseFunctionCall(node, ref); ok {
1332 if _, unsupported := unsupportedFunctions[name]; unsupported {
1333 return ctx.newBadExpr(node, "%s is not supported", refDump)
1334 }
1335 }
1336
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001337 // If it is a single word, it can be a simple variable
1338 // reference or a function call
Cole Faustf035d402022-03-28 14:02:50 -07001339 if len(words) == 1 && !isMakeControlFunc(refDump) && refDump != "shell" && refDump != "eval" {
Sasha Smundak65b547e2021-09-17 15:35:41 -07001340 if strings.HasPrefix(refDump, soongNsPrefix) {
1341 // TODO (asmundak): if we find many, maybe handle them.
Cole Faustc00184e2021-11-08 12:08:57 -08001342 return ctx.newBadExpr(node, "SOONG_CONFIG_ variables cannot be referenced, use soong_config_get instead: %s", refDump)
Sasha Smundak65b547e2021-09-17 15:35:41 -07001343 }
Cole Faustc36c9622021-12-07 15:20:45 -08001344 // Handle substitution references: https://www.gnu.org/software/make/manual/html_node/Substitution-Refs.html
1345 if strings.Contains(refDump, ":") {
1346 parts := strings.SplitN(refDump, ":", 2)
1347 substParts := strings.SplitN(parts[1], "=", 2)
1348 if len(substParts) < 2 || strings.Count(substParts[0], "%") > 1 {
1349 return ctx.newBadExpr(node, "Invalid substitution reference")
1350 }
1351 if !strings.Contains(substParts[0], "%") {
1352 if strings.Contains(substParts[1], "%") {
1353 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.")
1354 }
1355 substParts[0] = "%" + substParts[0]
1356 substParts[1] = "%" + substParts[1]
1357 }
1358 v := ctx.addVariable(parts[0])
1359 if v == nil {
1360 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1361 }
1362 return &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001363 name: baseName + ".mkpatsubst",
1364 returnType: starlarkTypeString,
Cole Faustc36c9622021-12-07 15:20:45 -08001365 args: []starlarkExpr{
1366 &stringLiteralExpr{literal: substParts[0]},
1367 &stringLiteralExpr{literal: substParts[1]},
Cole Faustf0632662022-04-07 13:59:24 -07001368 NewVariableRefExpr(v),
Cole Faustc36c9622021-12-07 15:20:45 -08001369 },
1370 }
1371 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001372 if v := ctx.addVariable(refDump); v != nil {
Cole Faustf0632662022-04-07 13:59:24 -07001373 return NewVariableRefExpr(v)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001374 }
1375 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1376 }
1377
Cole Faustf035d402022-03-28 14:02:50 -07001378 if name, args, ok := ctx.maybeParseFunctionCall(node, ref); ok {
1379 if kf, found := knownFunctions[name]; found {
1380 return kf.parse(ctx, node, args)
Sasha Smundak6609ba72021-07-22 18:32:56 -07001381 } else {
Cole Faustf035d402022-03-28 14:02:50 -07001382 return ctx.newBadExpr(node, "cannot handle invoking %s", name)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001383 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001384 }
Cole Faust1e275862022-04-26 14:28:04 -07001385 return ctx.newBadExpr(node, "cannot handle %s", refDump)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001386}
1387
1388type simpleCallParser struct {
1389 name string
1390 returnType starlarkType
1391 addGlobals bool
Cole Faust1cc08852022-02-28 11:12:08 -08001392 addHandle bool
Cole Faust9ebf6e42021-12-13 14:08:34 -08001393}
1394
1395func (p *simpleCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1396 expr := &callExpr{name: p.name, returnType: p.returnType}
1397 if p.addGlobals {
1398 expr.args = append(expr.args, &globalsExpr{})
1399 }
Cole Faust1cc08852022-02-28 11:12:08 -08001400 if p.addHandle {
1401 expr.args = append(expr.args, &identifierExpr{name: "handle"})
1402 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001403 for _, arg := range args.Split(",") {
1404 arg.TrimLeftSpaces()
1405 arg.TrimRightSpaces()
1406 x := ctx.parseMakeString(node, arg)
1407 if xBad, ok := x.(*badExpr); ok {
1408 return xBad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001409 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001410 expr.args = append(expr.args, x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001411 }
1412 return expr
1413}
1414
Cole Faust9ebf6e42021-12-13 14:08:34 -08001415type makeControlFuncParser struct {
1416 name string
1417}
1418
1419func (p *makeControlFuncParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1420 // Make control functions need special treatment as everything
1421 // after the name is a single text argument
1422 x := ctx.parseMakeString(node, args)
1423 if xBad, ok := x.(*badExpr); ok {
1424 return xBad
1425 }
1426 return &callExpr{
1427 name: p.name,
1428 args: []starlarkExpr{
1429 &stringLiteralExpr{ctx.script.mkFile},
1430 x,
1431 },
1432 returnType: starlarkTypeUnknown,
1433 }
1434}
1435
1436type shellCallParser struct{}
1437
1438func (p *shellCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1439 // Shell functions need special treatment as everything
1440 // after the name is a single text argument
1441 x := ctx.parseMakeString(node, args)
1442 if xBad, ok := x.(*badExpr); ok {
1443 return xBad
1444 }
1445 return &callExpr{
1446 name: baseName + ".shell",
1447 args: []starlarkExpr{x},
1448 returnType: starlarkTypeUnknown,
1449 }
1450}
1451
1452type myDirCallParser struct{}
1453
1454func (p *myDirCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1455 if !args.Empty() {
1456 return ctx.newBadExpr(node, "my-dir function cannot have any arguments passed to it.")
1457 }
Cole Faustf5adedc2022-03-18 14:05:06 -07001458 return &stringLiteralExpr{literal: filepath.Dir(ctx.script.mkFile)}
Cole Faust9ebf6e42021-12-13 14:08:34 -08001459}
1460
Cole Faustd2daabf2022-12-12 17:38:01 -08001461type andOrParser struct {
1462 isAnd bool
1463}
1464
1465func (p *andOrParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1466 if args.Empty() {
1467 return ctx.newBadExpr(node, "and/or function must have at least 1 argument")
1468 }
1469 op := "or"
1470 if p.isAnd {
1471 op = "and"
1472 }
1473
1474 argsParsed := make([]starlarkExpr, 0)
1475
1476 for _, arg := range args.Split(",") {
1477 arg.TrimLeftSpaces()
1478 arg.TrimRightSpaces()
1479 x := ctx.parseMakeString(node, arg)
1480 if xBad, ok := x.(*badExpr); ok {
1481 return xBad
1482 }
1483 argsParsed = append(argsParsed, x)
1484 }
1485 typ := starlarkTypeUnknown
1486 for _, arg := range argsParsed {
1487 if typ != arg.typ() && arg.typ() != starlarkTypeUnknown && typ != starlarkTypeUnknown {
1488 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())
1489 }
1490 if arg.typ() != starlarkTypeUnknown {
1491 typ = arg.typ()
1492 }
1493 }
1494 result := argsParsed[0]
1495 for _, arg := range argsParsed[1:] {
1496 result = &binaryOpExpr{
1497 left: result,
1498 right: arg,
1499 op: op,
1500 returnType: typ,
1501 }
1502 }
1503 return result
1504}
1505
Cole Faust9ebf6e42021-12-13 14:08:34 -08001506type isProductInListCallParser struct{}
1507
1508func (p *isProductInListCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1509 if args.Empty() {
1510 return ctx.newBadExpr(node, "is-product-in-list requires an argument")
1511 }
1512 return &inExpr{
Cole Faustf0632662022-04-07 13:59:24 -07001513 expr: NewVariableRefExpr(ctx.addVariable("TARGET_PRODUCT")),
Cole Faust9ebf6e42021-12-13 14:08:34 -08001514 list: maybeConvertToStringList(ctx.parseMakeString(node, args)),
1515 isNot: false,
1516 }
1517}
1518
1519type isVendorBoardPlatformCallParser struct{}
1520
1521func (p *isVendorBoardPlatformCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1522 if args.Empty() || !identifierFullMatchRegex.MatchString(args.Dump()) {
1523 return ctx.newBadExpr(node, "cannot handle non-constant argument to is-vendor-board-platform")
1524 }
1525 return &inExpr{
Cole Faustf0632662022-04-07 13:59:24 -07001526 expr: NewVariableRefExpr(ctx.addVariable("TARGET_BOARD_PLATFORM")),
1527 list: NewVariableRefExpr(ctx.addVariable(args.Dump() + "_BOARD_PLATFORMS")),
Cole Faust9ebf6e42021-12-13 14:08:34 -08001528 isNot: false,
1529 }
1530}
1531
1532type isVendorBoardQcomCallParser struct{}
1533
1534func (p *isVendorBoardQcomCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1535 if !args.Empty() {
1536 return ctx.newBadExpr(node, "is-vendor-board-qcom does not accept any arguments")
1537 }
1538 return &inExpr{
Cole Faustf0632662022-04-07 13:59:24 -07001539 expr: NewVariableRefExpr(ctx.addVariable("TARGET_BOARD_PLATFORM")),
1540 list: NewVariableRefExpr(ctx.addVariable("QCOM_BOARD_PLATFORMS")),
Cole Faust9ebf6e42021-12-13 14:08:34 -08001541 isNot: false,
1542 }
1543}
1544
1545type substCallParser struct {
1546 fname string
1547}
1548
1549func (p *substCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001550 words := args.Split(",")
1551 if len(words) != 3 {
Cole Faust9ebf6e42021-12-13 14:08:34 -08001552 return ctx.newBadExpr(node, "%s function should have 3 arguments", p.fname)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001553 }
Sasha Smundak35434ed2021-11-05 16:29:56 -07001554 from := ctx.parseMakeString(node, words[0])
1555 if xBad, ok := from.(*badExpr); ok {
1556 return xBad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001557 }
Sasha Smundak35434ed2021-11-05 16:29:56 -07001558 to := ctx.parseMakeString(node, words[1])
1559 if xBad, ok := to.(*badExpr); ok {
1560 return xBad
1561 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001562 words[2].TrimLeftSpaces()
1563 words[2].TrimRightSpaces()
1564 obj := ctx.parseMakeString(node, words[2])
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001565 typ := obj.typ()
Cole Faust9ebf6e42021-12-13 14:08:34 -08001566 if typ == starlarkTypeString && p.fname == "subst" {
Sasha Smundak94b41c72021-07-12 18:30:42 -07001567 // Optimization: if it's $(subst from, to, string), emit string.replace(from, to)
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001568 return &callExpr{
1569 object: obj,
1570 name: "replace",
Sasha Smundak35434ed2021-11-05 16:29:56 -07001571 args: []starlarkExpr{from, to},
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001572 returnType: typ,
1573 }
1574 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001575 return &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001576 name: baseName + ".mk" + p.fname,
Sasha Smundak35434ed2021-11-05 16:29:56 -07001577 args: []starlarkExpr{from, to, obj},
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001578 returnType: obj.typ(),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001579 }
1580}
1581
Cole Faust9ebf6e42021-12-13 14:08:34 -08001582type ifCallParser struct{}
1583
1584func (p *ifCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Cole Faust4eadba72021-12-07 11:54:52 -08001585 words := args.Split(",")
1586 if len(words) != 2 && len(words) != 3 {
1587 return ctx.newBadExpr(node, "if function should have 2 or 3 arguments, found "+strconv.Itoa(len(words)))
1588 }
1589 condition := ctx.parseMakeString(node, words[0])
1590 ifTrue := ctx.parseMakeString(node, words[1])
1591 var ifFalse starlarkExpr
1592 if len(words) == 3 {
1593 ifFalse = ctx.parseMakeString(node, words[2])
1594 } else {
1595 switch ifTrue.typ() {
1596 case starlarkTypeList:
1597 ifFalse = &listExpr{items: []starlarkExpr{}}
1598 case starlarkTypeInt:
1599 ifFalse = &intLiteralExpr{literal: 0}
1600 case starlarkTypeBool:
1601 ifFalse = &boolLiteralExpr{literal: false}
1602 default:
1603 ifFalse = &stringLiteralExpr{literal: ""}
1604 }
1605 }
1606 return &ifExpr{
1607 condition,
1608 ifTrue,
1609 ifFalse,
1610 }
1611}
1612
Cole Faustf035d402022-03-28 14:02:50 -07001613type ifCallNodeParser struct{}
Cole Faust9ebf6e42021-12-13 14:08:34 -08001614
Cole Faustf035d402022-03-28 14:02:50 -07001615func (p *ifCallNodeParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode {
1616 words := args.Split(",")
1617 if len(words) != 2 && len(words) != 3 {
1618 return []starlarkNode{ctx.newBadNode(node, "if function should have 2 or 3 arguments, found "+strconv.Itoa(len(words)))}
1619 }
1620
1621 ifn := &ifNode{expr: ctx.parseMakeString(node, words[0])}
1622 cases := []*switchCase{
1623 {
1624 gate: ifn,
1625 nodes: ctx.parseNodeMakeString(node, words[1]),
1626 },
1627 }
1628 if len(words) == 3 {
1629 cases = append(cases, &switchCase{
1630 gate: &elseNode{},
1631 nodes: ctx.parseNodeMakeString(node, words[2]),
1632 })
1633 }
1634 if len(cases) == 2 {
1635 if len(cases[1].nodes) == 0 {
1636 // Remove else branch if it has no contents
1637 cases = cases[:1]
1638 } else if len(cases[0].nodes) == 0 {
1639 // If the if branch has no contents but the else does,
1640 // move them to the if and negate its condition
1641 ifn.expr = negateExpr(ifn.expr)
1642 cases[0].nodes = cases[1].nodes
1643 cases = cases[:1]
1644 }
1645 }
1646
1647 return []starlarkNode{&switchNode{ssCases: cases}}
1648}
1649
1650type foreachCallParser struct{}
1651
1652func (p *foreachCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Cole Faustb0d32ab2021-12-09 14:00:59 -08001653 words := args.Split(",")
1654 if len(words) != 3 {
1655 return ctx.newBadExpr(node, "foreach function should have 3 arguments, found "+strconv.Itoa(len(words)))
1656 }
1657 if !words[0].Const() || words[0].Empty() || !identifierFullMatchRegex.MatchString(words[0].Strings[0]) {
1658 return ctx.newBadExpr(node, "first argument to foreach function must be a simple string identifier")
1659 }
1660 loopVarName := words[0].Strings[0]
1661 list := ctx.parseMakeString(node, words[1])
1662 action := ctx.parseMakeString(node, words[2]).transform(func(expr starlarkExpr) starlarkExpr {
1663 if varRefExpr, ok := expr.(*variableRefExpr); ok && varRefExpr.ref.name() == loopVarName {
1664 return &identifierExpr{loopVarName}
1665 }
1666 return nil
1667 })
1668
1669 if list.typ() != starlarkTypeList {
1670 list = &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001671 name: baseName + ".words",
1672 returnType: starlarkTypeList,
Cole Faustb0d32ab2021-12-09 14:00:59 -08001673 args: []starlarkExpr{list},
1674 }
1675 }
1676
Cole Faust72374fc2022-05-05 11:45:04 -07001677 var result starlarkExpr = &foreachExpr{
Cole Faustb0d32ab2021-12-09 14:00:59 -08001678 varName: loopVarName,
1679 list: list,
1680 action: action,
1681 }
Cole Faust72374fc2022-05-05 11:45:04 -07001682
1683 if action.typ() == starlarkTypeList {
1684 result = &callExpr{
1685 name: baseName + ".flatten_2d_list",
1686 args: []starlarkExpr{result},
1687 returnType: starlarkTypeList,
1688 }
1689 }
1690
1691 return result
Cole Faustb0d32ab2021-12-09 14:00:59 -08001692}
1693
Cole Faustf035d402022-03-28 14:02:50 -07001694func transformNode(node starlarkNode, transformer func(expr starlarkExpr) starlarkExpr) {
1695 switch a := node.(type) {
1696 case *ifNode:
1697 a.expr = a.expr.transform(transformer)
1698 case *switchCase:
1699 transformNode(a.gate, transformer)
1700 for _, n := range a.nodes {
1701 transformNode(n, transformer)
1702 }
1703 case *switchNode:
1704 for _, n := range a.ssCases {
1705 transformNode(n, transformer)
1706 }
1707 case *exprNode:
1708 a.expr = a.expr.transform(transformer)
1709 case *assignmentNode:
1710 a.value = a.value.transform(transformer)
1711 case *foreachNode:
1712 a.list = a.list.transform(transformer)
1713 for _, n := range a.actions {
1714 transformNode(n, transformer)
1715 }
Cole Faust9df1d732022-04-26 16:27:22 -07001716 case *inheritNode:
1717 if b, ok := a.module.(inheritedDynamicModule); ok {
1718 b.path = b.path.transform(transformer)
1719 a.module = b
1720 }
1721 case *includeNode:
1722 if b, ok := a.module.(inheritedDynamicModule); ok {
1723 b.path = b.path.transform(transformer)
1724 a.module = b
1725 }
Cole Faustf035d402022-03-28 14:02:50 -07001726 }
1727}
1728
1729type foreachCallNodeParser struct{}
1730
1731func (p *foreachCallNodeParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode {
1732 words := args.Split(",")
1733 if len(words) != 3 {
1734 return []starlarkNode{ctx.newBadNode(node, "foreach function should have 3 arguments, found "+strconv.Itoa(len(words)))}
1735 }
1736 if !words[0].Const() || words[0].Empty() || !identifierFullMatchRegex.MatchString(words[0].Strings[0]) {
1737 return []starlarkNode{ctx.newBadNode(node, "first argument to foreach function must be a simple string identifier")}
1738 }
1739
1740 loopVarName := words[0].Strings[0]
1741
1742 list := ctx.parseMakeString(node, words[1])
1743 if list.typ() != starlarkTypeList {
1744 list = &callExpr{
1745 name: baseName + ".words",
1746 returnType: starlarkTypeList,
1747 args: []starlarkExpr{list},
1748 }
1749 }
1750
1751 actions := ctx.parseNodeMakeString(node, words[2])
1752 // TODO(colefaust): Replace transforming code with something more elegant
1753 for _, action := range actions {
1754 transformNode(action, func(expr starlarkExpr) starlarkExpr {
1755 if varRefExpr, ok := expr.(*variableRefExpr); ok && varRefExpr.ref.name() == loopVarName {
1756 return &identifierExpr{loopVarName}
1757 }
1758 return nil
1759 })
1760 }
1761
1762 return []starlarkNode{&foreachNode{
1763 varName: loopVarName,
1764 list: list,
1765 actions: actions,
1766 }}
1767}
1768
Cole Faust9ebf6e42021-12-13 14:08:34 -08001769type wordCallParser struct{}
1770
1771func (p *wordCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001772 words := args.Split(",")
1773 if len(words) != 2 {
1774 return ctx.newBadExpr(node, "word function should have 2 arguments")
1775 }
Cole Faust94c4a9a2022-04-22 17:43:52 -07001776 var index = 0
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001777 if words[0].Const() {
Cole Faust94c4a9a2022-04-22 17:43:52 -07001778 if i, err := strconv.Atoi(strings.TrimSpace(words[0].Strings[0])); err == nil {
1779 index = i
1780 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001781 }
1782 if index < 1 {
1783 return ctx.newBadExpr(node, "word index should be constant positive integer")
1784 }
1785 words[1].TrimLeftSpaces()
1786 words[1].TrimRightSpaces()
1787 array := ctx.parseMakeString(node, words[1])
Cole Faust94c4a9a2022-04-22 17:43:52 -07001788 if bad, ok := array.(*badExpr); ok {
1789 return bad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001790 }
1791 if array.typ() != starlarkTypeList {
Cole Faust94c4a9a2022-04-22 17:43:52 -07001792 array = &callExpr{
1793 name: baseName + ".words",
1794 args: []starlarkExpr{array},
1795 returnType: starlarkTypeList,
1796 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001797 }
Cole Faust94c4a9a2022-04-22 17:43:52 -07001798 return &indexExpr{array, &intLiteralExpr{index - 1}}
1799}
1800
1801type wordsCallParser struct{}
1802
1803func (p *wordsCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1804 args.TrimLeftSpaces()
1805 args.TrimRightSpaces()
1806 array := ctx.parseMakeString(node, args)
1807 if bad, ok := array.(*badExpr); ok {
1808 return bad
1809 }
1810 if array.typ() != starlarkTypeList {
1811 array = &callExpr{
1812 name: baseName + ".words",
1813 args: []starlarkExpr{array},
1814 returnType: starlarkTypeList,
1815 }
1816 }
1817 return &callExpr{
1818 name: "len",
1819 args: []starlarkExpr{array},
1820 returnType: starlarkTypeInt,
1821 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001822}
1823
Cole Faustb1103e22022-01-06 15:22:05 -08001824func parseIntegerArguments(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString, expectedArgs int) ([]starlarkExpr, error) {
1825 parsedArgs := make([]starlarkExpr, 0)
1826 for _, arg := range args.Split(",") {
1827 expr := ctx.parseMakeString(node, arg)
1828 if expr.typ() == starlarkTypeList {
1829 return nil, fmt.Errorf("argument to math argument has type list, which cannot be converted to int")
1830 }
1831 if s, ok := maybeString(expr); ok {
1832 intVal, err := strconv.Atoi(strings.TrimSpace(s))
1833 if err != nil {
1834 return nil, err
1835 }
1836 expr = &intLiteralExpr{literal: intVal}
1837 } else if expr.typ() != starlarkTypeInt {
1838 expr = &callExpr{
1839 name: "int",
1840 args: []starlarkExpr{expr},
1841 returnType: starlarkTypeInt,
1842 }
1843 }
1844 parsedArgs = append(parsedArgs, expr)
1845 }
1846 if len(parsedArgs) != expectedArgs {
1847 return nil, fmt.Errorf("function should have %d arguments", expectedArgs)
1848 }
1849 return parsedArgs, nil
1850}
1851
1852type mathComparisonCallParser struct {
1853 op string
1854}
1855
1856func (p *mathComparisonCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1857 parsedArgs, err := parseIntegerArguments(ctx, node, args, 2)
1858 if err != nil {
1859 return ctx.newBadExpr(node, err.Error())
1860 }
1861 return &binaryOpExpr{
1862 left: parsedArgs[0],
1863 right: parsedArgs[1],
1864 op: p.op,
1865 returnType: starlarkTypeBool,
1866 }
1867}
1868
1869type mathMaxOrMinCallParser struct {
1870 function string
1871}
1872
1873func (p *mathMaxOrMinCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1874 parsedArgs, err := parseIntegerArguments(ctx, node, args, 2)
1875 if err != nil {
1876 return ctx.newBadExpr(node, err.Error())
1877 }
1878 return &callExpr{
1879 object: nil,
1880 name: p.function,
1881 args: parsedArgs,
1882 returnType: starlarkTypeInt,
1883 }
1884}
1885
Cole Faustf035d402022-03-28 14:02:50 -07001886type evalNodeParser struct{}
1887
1888func (p *evalNodeParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode {
1889 parser := mkparser.NewParser("Eval expression", strings.NewReader(args.Dump()))
1890 nodes, errs := parser.Parse()
1891 if errs != nil {
1892 return []starlarkNode{ctx.newBadNode(node, "Unable to parse eval statement")}
1893 }
1894
1895 if len(nodes) == 0 {
1896 return []starlarkNode{}
1897 } else if len(nodes) == 1 {
Cole Faust73660422023-01-05 11:07:47 -08001898 // Replace the nodeLocator with one that just returns the location of
1899 // the $(eval) node. Otherwise, statements inside an $(eval) will show as
1900 // being on line 1 of the file, because they're on line 1 of
1901 // strings.NewReader(args.Dump())
1902 oldNodeLocator := ctx.script.nodeLocator
1903 ctx.script.nodeLocator = func(pos mkparser.Pos) int {
1904 return oldNodeLocator(node.Pos())
1905 }
1906 defer func() {
1907 ctx.script.nodeLocator = oldNodeLocator
1908 }()
1909
Cole Faustf035d402022-03-28 14:02:50 -07001910 switch n := nodes[0].(type) {
1911 case *mkparser.Assignment:
1912 if n.Name.Const() {
1913 return ctx.handleAssignment(n)
1914 }
1915 case *mkparser.Comment:
1916 return []starlarkNode{&commentNode{strings.TrimSpace("#" + n.Comment)}}
Cole Faust20052982022-04-22 14:43:55 -07001917 case *mkparser.Directive:
1918 if n.Name == "include" || n.Name == "-include" {
1919 return ctx.handleInclude(n)
1920 }
1921 case *mkparser.Variable:
1922 // Technically inherit-product(-if-exists) don't need to be put inside
1923 // an eval, but some makefiles do it, presumably because they copy+pasted
1924 // from a $(eval include ...)
1925 if name, _, ok := ctx.maybeParseFunctionCall(n, n.Name); ok {
1926 if name == "inherit-product" || name == "inherit-product-if-exists" {
1927 return ctx.handleVariable(n)
1928 }
1929 }
Cole Faustf035d402022-03-28 14:02:50 -07001930 }
1931 }
1932
Cole Faust20052982022-04-22 14:43:55 -07001933 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 -07001934}
1935
Cole Faust2dee63d2022-12-12 18:11:00 -08001936type lowerUpperParser struct {
1937 isUpper bool
1938}
1939
1940func (p *lowerUpperParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1941 fn := "lower"
1942 if p.isUpper {
1943 fn = "upper"
1944 }
1945 arg := ctx.parseMakeString(node, args)
1946
1947 return &callExpr{
1948 object: arg,
1949 name: fn,
1950 returnType: starlarkTypeString,
1951 }
1952}
1953
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001954func (ctx *parseContext) parseMakeString(node mkparser.Node, mk *mkparser.MakeString) starlarkExpr {
1955 if mk.Const() {
1956 return &stringLiteralExpr{mk.Dump()}
1957 }
1958 if mkRef, ok := mk.SingleVariable(); ok {
1959 return ctx.parseReference(node, mkRef)
1960 }
1961 // If we reached here, it's neither string literal nor a simple variable,
1962 // we need a full-blown interpolation node that will generate
1963 // "a%b%c" % (X, Y) for a$(X)b$(Y)c
Cole Faustfc438682021-12-14 12:46:32 -08001964 parts := make([]starlarkExpr, len(mk.Variables)+len(mk.Strings))
1965 for i := 0; i < len(parts); i++ {
1966 if i%2 == 0 {
1967 parts[i] = &stringLiteralExpr{literal: mk.Strings[i/2]}
1968 } else {
1969 parts[i] = ctx.parseReference(node, mk.Variables[i/2].Name)
1970 if x, ok := parts[i].(*badExpr); ok {
1971 return x
1972 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001973 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001974 }
Cole Faustfc438682021-12-14 12:46:32 -08001975 return NewInterpolateExpr(parts)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001976}
1977
Cole Faustf035d402022-03-28 14:02:50 -07001978func (ctx *parseContext) parseNodeMakeString(node mkparser.Node, mk *mkparser.MakeString) []starlarkNode {
1979 // Discard any constant values in the make string, as they would be top level
1980 // string literals and do nothing.
1981 result := make([]starlarkNode, 0, len(mk.Variables))
1982 for i := range mk.Variables {
1983 result = append(result, ctx.handleVariable(&mk.Variables[i])...)
1984 }
1985 return result
1986}
1987
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001988// Handles the statements whose treatment is the same in all contexts: comment,
1989// assignment, variable (which is a macro call in reality) and all constructs that
1990// do not handle in any context ('define directive and any unrecognized stuff).
Cole Faustdd569ae2022-01-31 15:48:29 -08001991func (ctx *parseContext) handleSimpleStatement(node mkparser.Node) []starlarkNode {
1992 var result []starlarkNode
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001993 switch x := node.(type) {
1994 case *mkparser.Comment:
Cole Faustdd569ae2022-01-31 15:48:29 -08001995 if n, handled := ctx.maybeHandleAnnotation(x); handled && n != nil {
1996 result = []starlarkNode{n}
1997 } else if !handled {
1998 result = []starlarkNode{&commentNode{strings.TrimSpace("#" + x.Comment)}}
Cole Faust7940c6a2022-01-31 15:54:05 -08001999 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002000 case *mkparser.Assignment:
Cole Faustdd569ae2022-01-31 15:48:29 -08002001 result = ctx.handleAssignment(x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002002 case *mkparser.Variable:
Cole Faustdd569ae2022-01-31 15:48:29 -08002003 result = ctx.handleVariable(x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002004 case *mkparser.Directive:
2005 switch x.Name {
2006 case "define":
Cole Faustdd569ae2022-01-31 15:48:29 -08002007 if res := ctx.maybeHandleDefine(x); res != nil {
2008 result = []starlarkNode{res}
2009 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002010 case "include", "-include":
Cole Faust20052982022-04-22 14:43:55 -07002011 result = ctx.handleInclude(x)
Cole Faust591a1fe2021-11-08 15:37:57 -08002012 case "ifeq", "ifneq", "ifdef", "ifndef":
Cole Faustdd569ae2022-01-31 15:48:29 -08002013 result = []starlarkNode{ctx.handleIfBlock(x)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002014 default:
Cole Faustdd569ae2022-01-31 15:48:29 -08002015 result = []starlarkNode{ctx.newBadNode(x, "unexpected directive %s", x.Name)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002016 }
2017 default:
Cole Faustdd569ae2022-01-31 15:48:29 -08002018 result = []starlarkNode{ctx.newBadNode(x, "unsupported line %s", strings.ReplaceAll(x.Dump(), "\n", "\n#"))}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002019 }
Cole Faust6c934f62022-01-06 15:51:12 -08002020
2021 // Clear the includeTops after each non-comment statement
2022 // so that include annotations placed on certain statements don't apply
2023 // globally for the rest of the makefile was well.
Cole Faustf92c9f22022-03-14 14:35:50 -07002024 if _, wasComment := node.(*mkparser.Comment); !wasComment {
2025 ctx.atTopOfMakefile = false
Cole Faust6c934f62022-01-06 15:51:12 -08002026 ctx.includeTops = []string{}
2027 }
Cole Faustdd569ae2022-01-31 15:48:29 -08002028
2029 if result == nil {
2030 result = []starlarkNode{}
2031 }
Cole Faustf035d402022-03-28 14:02:50 -07002032
Cole Faustdd569ae2022-01-31 15:48:29 -08002033 return result
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002034}
2035
Cole Faustf92c9f22022-03-14 14:35:50 -07002036// The types allowed in a type_hint
2037var typeHintMap = map[string]starlarkType{
2038 "string": starlarkTypeString,
2039 "list": starlarkTypeList,
2040}
2041
Sasha Smundak6d852dd2021-09-27 20:34:39 -07002042// Processes annotation. An annotation is a comment that starts with #RBC# and provides
2043// a conversion hint -- say, where to look for the dynamically calculated inherit/include
Cole Faust7940c6a2022-01-31 15:54:05 -08002044// paths. Returns true if the comment was a successfully-handled annotation.
Cole Faustdd569ae2022-01-31 15:48:29 -08002045func (ctx *parseContext) maybeHandleAnnotation(cnode *mkparser.Comment) (starlarkNode, bool) {
Sasha Smundak6d852dd2021-09-27 20:34:39 -07002046 maybeTrim := func(s, prefix string) (string, bool) {
2047 if strings.HasPrefix(s, prefix) {
2048 return strings.TrimSpace(strings.TrimPrefix(s, prefix)), true
2049 }
2050 return s, false
2051 }
2052 annotation, ok := maybeTrim(cnode.Comment, annotationCommentPrefix)
2053 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -08002054 return nil, false
Sasha Smundak6d852dd2021-09-27 20:34:39 -07002055 }
2056 if p, ok := maybeTrim(annotation, "include_top"); ok {
Cole Faustf7ed5342021-12-21 14:15:12 -08002057 // Don't allow duplicate include tops, because then we will generate
2058 // invalid starlark code. (duplicate keys in the _entry dictionary)
2059 for _, top := range ctx.includeTops {
2060 if top == p {
Cole Faustdd569ae2022-01-31 15:48:29 -08002061 return nil, true
Cole Faustf7ed5342021-12-21 14:15:12 -08002062 }
2063 }
Sasha Smundak6d852dd2021-09-27 20:34:39 -07002064 ctx.includeTops = append(ctx.includeTops, p)
Cole Faustdd569ae2022-01-31 15:48:29 -08002065 return nil, true
Cole Faustf92c9f22022-03-14 14:35:50 -07002066 } else if p, ok := maybeTrim(annotation, "type_hint"); ok {
2067 // Type hints must come at the beginning the file, to avoid confusion
2068 // if a type hint was specified later and thus only takes effect for half
2069 // of the file.
2070 if !ctx.atTopOfMakefile {
2071 return ctx.newBadNode(cnode, "type_hint annotations must come before the first Makefile statement"), true
2072 }
2073
2074 parts := strings.Fields(p)
2075 if len(parts) <= 1 {
2076 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
2077 }
2078
2079 var varType starlarkType
2080 if varType, ok = typeHintMap[parts[0]]; !ok {
2081 varType = starlarkTypeUnknown
2082 }
2083 if varType == starlarkTypeUnknown {
2084 return ctx.newBadNode(cnode, "Invalid type_hint annotation. Only list/string types are accepted, found %s", parts[0]), true
2085 }
2086
2087 for _, name := range parts[1:] {
2088 // Don't allow duplicate type hints
2089 if _, ok := ctx.typeHints[name]; ok {
2090 return ctx.newBadNode(cnode, "Duplicate type hint for variable %s", name), true
2091 }
2092 ctx.typeHints[name] = varType
2093 }
2094 return nil, true
Sasha Smundak6d852dd2021-09-27 20:34:39 -07002095 }
Cole Faustdd569ae2022-01-31 15:48:29 -08002096 return ctx.newBadNode(cnode, "unsupported annotation %s", cnode.Comment), true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002097}
2098
2099func (ctx *parseContext) loadedModulePath(path string) string {
2100 // During the transition to Roboleaf some of the product configuration files
2101 // will be converted and checked in while the others will be generated on the fly
2102 // and run. The runner (rbcrun application) accommodates this by allowing three
2103 // different ways to specify the loaded file location:
2104 // 1) load(":<file>",...) loads <file> from the same directory
2105 // 2) load("//path/relative/to/source/root:<file>", ...) loads <file> source tree
2106 // 3) load("/absolute/path/to/<file> absolute path
2107 // If the file being generated and the file it wants to load are in the same directory,
2108 // generate option 1.
2109 // Otherwise, if output directory is not specified, generate 2)
2110 // Finally, if output directory has been specified and the file being generated and
2111 // the file it wants to load from are in the different directories, generate 2) or 3):
2112 // * if the file being loaded exists in the source tree, generate 2)
2113 // * otherwise, generate 3)
2114 // Finally, figure out the loaded module path and name and create a node for it
2115 loadedModuleDir := filepath.Dir(path)
2116 base := filepath.Base(path)
2117 loadedModuleName := strings.TrimSuffix(base, filepath.Ext(base)) + ctx.outputSuffix
2118 if loadedModuleDir == filepath.Dir(ctx.script.mkFile) {
2119 return ":" + loadedModuleName
2120 }
2121 if ctx.outputDir == "" {
2122 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
2123 }
2124 if _, err := os.Stat(filepath.Join(loadedModuleDir, loadedModuleName)); err == nil {
2125 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
2126 }
2127 return filepath.Join(ctx.outputDir, loadedModuleDir, loadedModuleName)
2128}
2129
Sasha Smundak3deb9682021-07-26 18:42:25 -07002130func (ctx *parseContext) addSoongNamespace(ns string) {
2131 if _, ok := ctx.soongNamespaces[ns]; ok {
2132 return
2133 }
2134 ctx.soongNamespaces[ns] = make(map[string]bool)
2135}
2136
2137func (ctx *parseContext) hasSoongNamespace(name string) bool {
2138 _, ok := ctx.soongNamespaces[name]
2139 return ok
2140}
2141
2142func (ctx *parseContext) updateSoongNamespace(replace bool, namespaceName string, varNames []string) {
2143 ctx.addSoongNamespace(namespaceName)
2144 vars := ctx.soongNamespaces[namespaceName]
2145 if replace {
2146 vars = make(map[string]bool)
2147 ctx.soongNamespaces[namespaceName] = vars
2148 }
2149 for _, v := range varNames {
2150 vars[v] = true
2151 }
2152}
2153
2154func (ctx *parseContext) hasNamespaceVar(namespaceName string, varName string) bool {
2155 vars, ok := ctx.soongNamespaces[namespaceName]
2156 if ok {
2157 _, ok = vars[varName]
2158 }
2159 return ok
2160}
2161
Sasha Smundak422b6142021-11-11 18:31:59 -08002162func (ctx *parseContext) errorLocation(node mkparser.Node) ErrorLocation {
2163 return ErrorLocation{ctx.script.mkFile, ctx.script.nodeLocator(node.Pos())}
2164}
2165
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002166func (ss *StarlarkScript) String() string {
2167 return NewGenerateContext(ss).emit()
2168}
2169
2170func (ss *StarlarkScript) SubConfigFiles() []string {
Sasha Smundak6609ba72021-07-22 18:32:56 -07002171
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002172 var subs []string
2173 for _, src := range ss.inherited {
2174 subs = append(subs, src.originalPath)
2175 }
2176 return subs
2177}
2178
2179func (ss *StarlarkScript) HasErrors() bool {
2180 return ss.hasErrors
2181}
2182
2183// Convert reads and parses a makefile. If successful, parsed tree
2184// is returned and then can be passed to String() to get the generated
2185// Starlark file.
2186func Convert(req Request) (*StarlarkScript, error) {
2187 reader := req.Reader
2188 if reader == nil {
2189 mkContents, err := ioutil.ReadFile(req.MkFile)
2190 if err != nil {
2191 return nil, err
2192 }
2193 reader = bytes.NewBuffer(mkContents)
2194 }
2195 parser := mkparser.NewParser(req.MkFile, reader)
2196 nodes, errs := parser.Parse()
2197 if len(errs) > 0 {
2198 for _, e := range errs {
2199 fmt.Fprintln(os.Stderr, "ERROR:", e)
2200 }
2201 return nil, fmt.Errorf("bad makefile %s", req.MkFile)
2202 }
2203 starScript := &StarlarkScript{
Sasha Smundak422b6142021-11-11 18:31:59 -08002204 moduleName: moduleNameForFile(req.MkFile),
2205 mkFile: req.MkFile,
Sasha Smundak422b6142021-11-11 18:31:59 -08002206 traceCalls: req.TraceCalls,
2207 sourceFS: req.SourceFS,
2208 makefileFinder: req.MakefileFinder,
2209 nodeLocator: func(pos mkparser.Pos) int { return parser.Unpack(pos).Line },
Cole Faustdd569ae2022-01-31 15:48:29 -08002210 nodes: make([]starlarkNode, 0),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002211 }
2212 ctx := newParseContext(starScript, nodes)
2213 ctx.outputSuffix = req.OutputSuffix
2214 ctx.outputDir = req.OutputDir
2215 ctx.errorLogger = req.ErrorLogger
2216 if len(req.TracedVariables) > 0 {
2217 ctx.tracedVariables = make(map[string]bool)
2218 for _, v := range req.TracedVariables {
2219 ctx.tracedVariables[v] = true
2220 }
2221 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002222 for ctx.hasNodes() && ctx.fatalError == nil {
Cole Faustdd569ae2022-01-31 15:48:29 -08002223 starScript.nodes = append(starScript.nodes, ctx.handleSimpleStatement(ctx.getNode())...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002224 }
2225 if ctx.fatalError != nil {
2226 return nil, ctx.fatalError
2227 }
2228 return starScript, nil
2229}
2230
Cole Faust864028a2021-12-01 13:43:17 -08002231func Launcher(mainModuleUri, inputVariablesUri, mainModuleName string) string {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002232 var buf bytes.Buffer
2233 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
Cole Faust864028a2021-12-01 13:43:17 -08002234 fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri)
Sasha Smundakd7d07ad2021-09-10 15:42:34 -07002235 fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri)
Cole Faust864028a2021-12-01 13:43:17 -08002236 fmt.Fprintf(&buf, "%s(%s(%q, init, input_variables_init))\n", cfnPrintVars, cfnMain, mainModuleName)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002237 return buf.String()
2238}
2239
Cole Faust6ed7cb42021-10-07 17:08:46 -07002240func BoardLauncher(mainModuleUri string, inputVariablesUri string) string {
2241 var buf bytes.Buffer
2242 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
2243 fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri)
2244 fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri)
Cole Fausta0604662022-02-28 11:53:58 -08002245 fmt.Fprintf(&buf, "%s(%s(init, input_variables_init))\n", cfnPrintVars, cfnBoardMain)
Cole Faust6ed7cb42021-10-07 17:08:46 -07002246 return buf.String()
2247}
2248
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002249func MakePath2ModuleName(mkPath string) string {
2250 return strings.TrimSuffix(mkPath, filepath.Ext(mkPath))
2251}