blob: 17d3c21858922f637fc3b195e60c090381520066 [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:
17// * comments
18// * simple variable assignments
19// * $(call init-product,<file>)
20// * $(call inherit-product-if-exists
21// * if directives
22// All other constructs are carried over to the output starlark file as comments.
23//
24package 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"
35 "strconv"
36 "strings"
37 "text/scanner"
38
39 mkparser "android/soong/androidmk/parser"
40)
41
42const (
Sasha Smundak6d852dd2021-09-27 20:34:39 -070043 annotationCommentPrefix = "RBC#"
44 baseUri = "//build/make/core:product_config.rbc"
Sasha Smundakb051c4e2020-11-05 20:45:07 -080045 // The name of the struct exported by the product_config.rbc
46 // that contains the functions and variables available to
47 // product configuration Starlark files.
48 baseName = "rblf"
49
Sasha Smundak65b547e2021-09-17 15:35:41 -070050 soongNsPrefix = "SOONG_CONFIG_"
51
Sasha Smundakb051c4e2020-11-05 20:45:07 -080052 // And here are the functions and variables:
53 cfnGetCfg = baseName + ".cfg"
54 cfnMain = baseName + ".product_configuration"
Cole Faust6ed7cb42021-10-07 17:08:46 -070055 cfnBoardMain = baseName + ".board_configuration"
Sasha Smundakb051c4e2020-11-05 20:45:07 -080056 cfnPrintVars = baseName + ".printvars"
57 cfnWarning = baseName + ".warning"
58 cfnLocalAppend = baseName + ".local_append"
59 cfnLocalSetDefault = baseName + ".local_set_default"
60 cfnInherit = baseName + ".inherit"
61 cfnSetListDefault = baseName + ".setdefault"
62)
63
64const (
Cole Faust9ebf6e42021-12-13 14:08:34 -080065 soongConfigAppend = "soong_config_append"
66 soongConfigAssign = "soong_config_set"
Sasha Smundakb051c4e2020-11-05 20:45:07 -080067)
68
Cole Faust9ebf6e42021-12-13 14:08:34 -080069var knownFunctions = map[string]interface {
70 parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr
Sasha Smundakb051c4e2020-11-05 20:45:07 -080071}{
Cole Faust9ebf6e42021-12-13 14:08:34 -080072 "abspath": &simpleCallParser{name: baseName + ".abspath", returnType: starlarkTypeString, addGlobals: false},
73 "add_soong_config_namespace": &simpleCallParser{name: baseName + ".soong_config_namespace", returnType: starlarkTypeVoid, addGlobals: true},
74 "add_soong_config_var_value": &simpleCallParser{name: baseName + ".soong_config_set", returnType: starlarkTypeVoid, addGlobals: true},
75 soongConfigAssign: &simpleCallParser{name: baseName + ".soong_config_set", returnType: starlarkTypeVoid, addGlobals: true},
76 soongConfigAppend: &simpleCallParser{name: baseName + ".soong_config_append", returnType: starlarkTypeVoid, addGlobals: true},
77 "soong_config_get": &simpleCallParser{name: baseName + ".soong_config_get", returnType: starlarkTypeString, addGlobals: true},
78 "add-to-product-copy-files-if-exists": &simpleCallParser{name: baseName + ".copy_if_exists", returnType: starlarkTypeList, addGlobals: false},
79 "addprefix": &simpleCallParser{name: baseName + ".addprefix", returnType: starlarkTypeList, addGlobals: false},
80 "addsuffix": &simpleCallParser{name: baseName + ".addsuffix", returnType: starlarkTypeList, addGlobals: false},
81 "copy-files": &simpleCallParser{name: baseName + ".copy_files", returnType: starlarkTypeList, addGlobals: false},
82 "dir": &simpleCallParser{name: baseName + ".dir", returnType: starlarkTypeList, addGlobals: false},
83 "dist-for-goals": &simpleCallParser{name: baseName + ".mkdist_for_goals", returnType: starlarkTypeVoid, addGlobals: true},
84 "enforce-product-packages-exist": &simpleCallParser{name: baseName + ".enforce_product_packages_exist", returnType: starlarkTypeVoid, addGlobals: false},
85 "error": &makeControlFuncParser{name: baseName + ".mkerror"},
86 "findstring": &simpleCallParser{name: baseName + ".findstring", returnType: starlarkTypeInt, addGlobals: false},
87 "find-copy-subdir-files": &simpleCallParser{name: baseName + ".find_and_copy", returnType: starlarkTypeList, addGlobals: false},
88 "filter": &simpleCallParser{name: baseName + ".filter", returnType: starlarkTypeList, addGlobals: false},
89 "filter-out": &simpleCallParser{name: baseName + ".filter_out", returnType: starlarkTypeList, addGlobals: false},
90 "firstword": &firstOrLastwordCallParser{isLastWord: false},
91 "foreach": &foreachCallPaser{},
92 "if": &ifCallParser{},
93 "info": &makeControlFuncParser{name: baseName + ".mkinfo"},
Cole Faustb2e0b602022-01-07 15:46:58 -080094 "is-board-platform": &simpleCallParser{name: baseName + ".board_platform_is", returnType: starlarkTypeBool, addGlobals: true},
Cole Faust9ebf6e42021-12-13 14:08:34 -080095 "is-board-platform2": &simpleCallParser{name: baseName + ".board_platform_is", returnType: starlarkTypeBool, addGlobals: true},
Cole Faustb2e0b602022-01-07 15:46:58 -080096 "is-board-platform-in-list": &simpleCallParser{name: baseName + ".board_platform_in", returnType: starlarkTypeBool, addGlobals: true},
Cole Faust9ebf6e42021-12-13 14:08:34 -080097 "is-board-platform-in-list2": &simpleCallParser{name: baseName + ".board_platform_in", returnType: starlarkTypeBool, addGlobals: true},
98 "is-product-in-list": &isProductInListCallParser{},
99 "is-vendor-board-platform": &isVendorBoardPlatformCallParser{},
100 "is-vendor-board-qcom": &isVendorBoardQcomCallParser{},
101 "lastword": &firstOrLastwordCallParser{isLastWord: true},
102 "notdir": &simpleCallParser{name: baseName + ".notdir", returnType: starlarkTypeString, addGlobals: false},
Cole Faustb1103e22022-01-06 15:22:05 -0800103 "math_max": &mathMaxOrMinCallParser{function: "max"},
104 "math_min": &mathMaxOrMinCallParser{function: "min"},
105 "math_gt_or_eq": &mathComparisonCallParser{op: ">="},
106 "math_gt": &mathComparisonCallParser{op: ">"},
107 "math_lt": &mathComparisonCallParser{op: "<"},
Cole Faust9ebf6e42021-12-13 14:08:34 -0800108 "my-dir": &myDirCallParser{},
109 "patsubst": &substCallParser{fname: "patsubst"},
110 "product-copy-files-by-pattern": &simpleCallParser{name: baseName + ".product_copy_files_by_pattern", returnType: starlarkTypeList, addGlobals: false},
111 "require-artifacts-in-path": &simpleCallParser{name: baseName + ".require_artifacts_in_path", returnType: starlarkTypeVoid, addGlobals: false},
112 "require-artifacts-in-path-relaxed": &simpleCallParser{name: baseName + ".require_artifacts_in_path_relaxed", returnType: starlarkTypeVoid, addGlobals: false},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800113 // TODO(asmundak): remove it once all calls are removed from configuration makefiles. see b/183161002
Cole Faust9ebf6e42021-12-13 14:08:34 -0800114 "shell": &shellCallParser{},
115 "strip": &simpleCallParser{name: baseName + ".mkstrip", returnType: starlarkTypeString, addGlobals: false},
116 "subst": &substCallParser{fname: "subst"},
117 "warning": &makeControlFuncParser{name: baseName + ".mkwarning"},
118 "word": &wordCallParser{},
119 "wildcard": &simpleCallParser{name: baseName + ".expand_wildcard", returnType: starlarkTypeList, addGlobals: false},
120}
121
122// These are functions that we don't implement conversions for, but
123// we allow seeing their definitions in the product config files.
124var ignoredDefines = map[string]bool{
125 "find-word-in-list": true, // internal macro
126 "get-vendor-board-platforms": true, // internal macro, used by is-board-platform, etc.
127 "is-android-codename": true, // unused by product config
128 "is-android-codename-in-list": true, // unused by product config
129 "is-chipset-in-board-platform": true, // unused by product config
130 "is-chipset-prefix-in-board-platform": true, // unused by product config
131 "is-not-board-platform": true, // defined but never used
132 "is-platform-sdk-version-at-least": true, // unused by product config
133 "match-prefix": true, // internal macro
134 "match-word": true, // internal macro
135 "match-word-in-list": true, // internal macro
136 "tb-modules": true, // defined in hardware/amlogic/tb_modules/tb_detect.mk, unused
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800137}
138
Cole Faustb0d32ab2021-12-09 14:00:59 -0800139var identifierFullMatchRegex = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$")
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800140
141// Conversion request parameters
142type Request struct {
Sasha Smundak422b6142021-11-11 18:31:59 -0800143 MkFile string // file to convert
144 Reader io.Reader // if set, read input from this stream instead
145 RootDir string // root directory path used to resolve included files
146 OutputSuffix string // generated Starlark files suffix
147 OutputDir string // if set, root of the output hierarchy
148 ErrorLogger ErrorLogger
149 TracedVariables []string // trace assignment to these variables
150 TraceCalls bool
151 SourceFS fs.FS
152 MakefileFinder MakefileFinder
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800153}
154
Sasha Smundak7d934b92021-11-10 12:20:01 -0800155// ErrorLogger prints errors and gathers error statistics.
156// Its NewError function is called on every error encountered during the conversion.
157type ErrorLogger interface {
Sasha Smundak422b6142021-11-11 18:31:59 -0800158 NewError(el ErrorLocation, node mkparser.Node, text string, args ...interface{})
159}
160
161type ErrorLocation struct {
162 MkFile string
163 MkLine int
164}
165
166func (el ErrorLocation) String() string {
167 return fmt.Sprintf("%s:%d", el.MkFile, el.MkLine)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800168}
169
170// Derives module name for a given file. It is base name
171// (file name without suffix), with some characters replaced to make it a Starlark identifier
172func moduleNameForFile(mkFile string) string {
173 base := strings.TrimSuffix(filepath.Base(mkFile), filepath.Ext(mkFile))
174 // TODO(asmundak): what else can be in the product file names?
Sasha Smundak6609ba72021-07-22 18:32:56 -0700175 return strings.NewReplacer("-", "_", ".", "_").Replace(base)
176
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800177}
178
179func cloneMakeString(mkString *mkparser.MakeString) *mkparser.MakeString {
180 r := &mkparser.MakeString{StringPos: mkString.StringPos}
181 r.Strings = append(r.Strings, mkString.Strings...)
182 r.Variables = append(r.Variables, mkString.Variables...)
183 return r
184}
185
186func isMakeControlFunc(s string) bool {
187 return s == "error" || s == "warning" || s == "info"
188}
189
190// Starlark output generation context
191type generationContext struct {
192 buf strings.Builder
193 starScript *StarlarkScript
194 indentLevel int
195 inAssignment bool
196 tracedCount int
197}
198
199func NewGenerateContext(ss *StarlarkScript) *generationContext {
200 return &generationContext{starScript: ss}
201}
202
203// emit returns generated script
204func (gctx *generationContext) emit() string {
205 ss := gctx.starScript
206
207 // The emitted code has the following layout:
208 // <initial comments>
209 // preamble, i.e.,
210 // load statement for the runtime support
211 // load statement for each unique submodule pulled in by this one
212 // def init(g, handle):
213 // cfg = rblf.cfg(handle)
214 // <statements>
215 // <warning if conversion was not clean>
216
217 iNode := len(ss.nodes)
218 for i, node := range ss.nodes {
219 if _, ok := node.(*commentNode); !ok {
220 iNode = i
221 break
222 }
223 node.emit(gctx)
224 }
225
226 gctx.emitPreamble()
227
228 gctx.newLine()
229 // The arguments passed to the init function are the global dictionary
230 // ('g') and the product configuration dictionary ('cfg')
231 gctx.write("def init(g, handle):")
232 gctx.indentLevel++
233 if gctx.starScript.traceCalls {
234 gctx.newLine()
235 gctx.writef(`print(">%s")`, gctx.starScript.mkFile)
236 }
237 gctx.newLine()
238 gctx.writef("cfg = %s(handle)", cfnGetCfg)
239 for _, node := range ss.nodes[iNode:] {
240 node.emit(gctx)
241 }
242
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800243 if gctx.starScript.traceCalls {
244 gctx.newLine()
245 gctx.writef(`print("<%s")`, gctx.starScript.mkFile)
246 }
247 gctx.indentLevel--
248 gctx.write("\n")
249 return gctx.buf.String()
250}
251
252func (gctx *generationContext) emitPreamble() {
253 gctx.newLine()
254 gctx.writef("load(%q, %q)", baseUri, baseName)
255 // Emit exactly one load statement for each URI.
256 loadedSubConfigs := make(map[string]string)
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800257 for _, mi := range gctx.starScript.inherited {
258 uri := mi.path
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800259 if m, ok := loadedSubConfigs[uri]; ok {
260 // No need to emit load statement, but fix module name.
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800261 mi.moduleLocalName = m
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800262 continue
263 }
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800264 if mi.optional || mi.missing {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800265 uri += "|init"
266 }
267 gctx.newLine()
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800268 gctx.writef("load(%q, %s = \"init\")", uri, mi.entryName())
269 loadedSubConfigs[uri] = mi.moduleLocalName
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800270 }
271 gctx.write("\n")
272}
273
274func (gctx *generationContext) emitPass() {
275 gctx.newLine()
276 gctx.write("pass")
277}
278
279func (gctx *generationContext) write(ss ...string) {
280 for _, s := range ss {
281 gctx.buf.WriteString(s)
282 }
283}
284
285func (gctx *generationContext) writef(format string, args ...interface{}) {
286 gctx.write(fmt.Sprintf(format, args...))
287}
288
289func (gctx *generationContext) newLine() {
290 if gctx.buf.Len() == 0 {
291 return
292 }
293 gctx.write("\n")
294 gctx.writef("%*s", 2*gctx.indentLevel, "")
295}
296
Sasha Smundak422b6142021-11-11 18:31:59 -0800297func (gctx *generationContext) emitConversionError(el ErrorLocation, message string) {
298 gctx.writef(`rblf.mk2rbc_error("%s", %q)`, el, message)
299}
300
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800301func (gctx *generationContext) emitLoadCheck(im inheritedModule) {
302 if !im.needsLoadCheck() {
303 return
304 }
305 gctx.newLine()
306 gctx.writef("if not %s:", im.entryName())
307 gctx.indentLevel++
308 gctx.newLine()
309 gctx.write(`rblf.mkerror("`, gctx.starScript.mkFile, `", "Cannot find %s" % (`)
310 im.pathExpr().emit(gctx)
311 gctx.write("))")
312 gctx.indentLevel--
313}
314
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800315type knownVariable struct {
316 name string
317 class varClass
318 valueType starlarkType
319}
320
321type knownVariables map[string]knownVariable
322
323func (pcv knownVariables) NewVariable(name string, varClass varClass, valueType starlarkType) {
324 v, exists := pcv[name]
325 if !exists {
326 pcv[name] = knownVariable{name, varClass, valueType}
327 return
328 }
329 // Conflict resolution:
330 // * config class trumps everything
331 // * any type trumps unknown type
332 match := varClass == v.class
333 if !match {
334 if varClass == VarClassConfig {
335 v.class = VarClassConfig
336 match = true
337 } else if v.class == VarClassConfig {
338 match = true
339 }
340 }
341 if valueType != v.valueType {
342 if valueType != starlarkTypeUnknown {
343 if v.valueType == starlarkTypeUnknown {
344 v.valueType = valueType
345 } else {
346 match = false
347 }
348 }
349 }
350 if !match {
351 fmt.Fprintf(os.Stderr, "cannot redefine %s as %v/%v (already defined as %v/%v)\n",
352 name, varClass, valueType, v.class, v.valueType)
353 }
354}
355
356// All known product variables.
357var KnownVariables = make(knownVariables)
358
359func init() {
360 for _, kv := range []string{
361 // Kernel-related variables that we know are lists.
362 "BOARD_VENDOR_KERNEL_MODULES",
363 "BOARD_VENDOR_RAMDISK_KERNEL_MODULES",
364 "BOARD_VENDOR_RAMDISK_KERNEL_MODULES_LOAD",
365 "BOARD_RECOVERY_KERNEL_MODULES",
366 // Other variables we knwo are lists
367 "ART_APEX_JARS",
368 } {
369 KnownVariables.NewVariable(kv, VarClassSoong, starlarkTypeList)
370 }
371}
372
373type nodeReceiver interface {
374 newNode(node starlarkNode)
375}
376
377// Information about the generated Starlark script.
378type StarlarkScript struct {
Sasha Smundak422b6142021-11-11 18:31:59 -0800379 mkFile string
380 moduleName string
381 mkPos scanner.Position
382 nodes []starlarkNode
383 inherited []*moduleInfo
384 hasErrors bool
385 topDir string
386 traceCalls bool // print enter/exit each init function
387 sourceFS fs.FS
388 makefileFinder MakefileFinder
389 nodeLocator func(pos mkparser.Pos) int
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800390}
391
392func (ss *StarlarkScript) newNode(node starlarkNode) {
393 ss.nodes = append(ss.nodes, node)
394}
395
396// varAssignmentScope points to the last assignment for each variable
397// in the current block. It is used during the parsing to chain
398// the assignments to a variable together.
399type varAssignmentScope struct {
400 outer *varAssignmentScope
401 vars map[string]*assignmentNode
402}
403
404// parseContext holds the script we are generating and all the ephemeral data
405// needed during the parsing.
406type parseContext struct {
407 script *StarlarkScript
408 nodes []mkparser.Node // Makefile as parsed by mkparser
409 currentNodeIndex int // Node in it we are processing
410 ifNestLevel int
411 moduleNameCount map[string]int // count of imported modules with given basename
412 fatalError error
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800413 outputSuffix string
Sasha Smundak7d934b92021-11-10 12:20:01 -0800414 errorLogger ErrorLogger
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800415 tracedVariables map[string]bool // variables to be traced in the generated script
416 variables map[string]variable
417 varAssignments *varAssignmentScope
418 receiver nodeReceiver // receptacle for the generated starlarkNode's
419 receiverStack []nodeReceiver
420 outputDir string
Sasha Smundak6609ba72021-07-22 18:32:56 -0700421 dependentModules map[string]*moduleInfo
Sasha Smundak3deb9682021-07-26 18:42:25 -0700422 soongNamespaces map[string]map[string]bool
Sasha Smundak6d852dd2021-09-27 20:34:39 -0700423 includeTops []string
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800424}
425
426func newParseContext(ss *StarlarkScript, nodes []mkparser.Node) *parseContext {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700427 topdir, _ := filepath.Split(filepath.Join(ss.topDir, "foo"))
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800428 predefined := []struct{ name, value string }{
429 {"SRC_TARGET_DIR", filepath.Join("build", "make", "target")},
430 {"LOCAL_PATH", filepath.Dir(ss.mkFile)},
Sasha Smundak6609ba72021-07-22 18:32:56 -0700431 {"TOPDIR", topdir},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800432 // TODO(asmundak): maybe read it from build/make/core/envsetup.mk?
433 {"TARGET_COPY_OUT_SYSTEM", "system"},
434 {"TARGET_COPY_OUT_SYSTEM_OTHER", "system_other"},
435 {"TARGET_COPY_OUT_DATA", "data"},
436 {"TARGET_COPY_OUT_ASAN", filepath.Join("data", "asan")},
437 {"TARGET_COPY_OUT_OEM", "oem"},
438 {"TARGET_COPY_OUT_RAMDISK", "ramdisk"},
439 {"TARGET_COPY_OUT_DEBUG_RAMDISK", "debug_ramdisk"},
440 {"TARGET_COPY_OUT_VENDOR_DEBUG_RAMDISK", "vendor_debug_ramdisk"},
441 {"TARGET_COPY_OUT_TEST_HARNESS_RAMDISK", "test_harness_ramdisk"},
442 {"TARGET_COPY_OUT_ROOT", "root"},
443 {"TARGET_COPY_OUT_RECOVERY", "recovery"},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800444 {"TARGET_COPY_OUT_VENDOR_RAMDISK", "vendor_ramdisk"},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800445 // TODO(asmundak): to process internal config files, we need the following variables:
446 // BOARD_CONFIG_VENDOR_PATH
447 // TARGET_VENDOR
448 // target_base_product
449 //
450
451 // the following utility variables are set in build/make/common/core.mk:
452 {"empty", ""},
453 {"space", " "},
454 {"comma", ","},
455 {"newline", "\n"},
456 {"pound", "#"},
457 {"backslash", "\\"},
458 }
459 ctx := &parseContext{
460 script: ss,
461 nodes: nodes,
462 currentNodeIndex: 0,
463 ifNestLevel: 0,
464 moduleNameCount: make(map[string]int),
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800465 variables: make(map[string]variable),
Sasha Smundak6609ba72021-07-22 18:32:56 -0700466 dependentModules: make(map[string]*moduleInfo),
Sasha Smundak3deb9682021-07-26 18:42:25 -0700467 soongNamespaces: make(map[string]map[string]bool),
Cole Faust6c934f62022-01-06 15:51:12 -0800468 includeTops: []string{},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800469 }
470 ctx.pushVarAssignments()
471 for _, item := range predefined {
472 ctx.variables[item.name] = &predefinedVariable{
473 baseVariable: baseVariable{nam: item.name, typ: starlarkTypeString},
474 value: &stringLiteralExpr{item.value},
475 }
476 }
477
478 return ctx
479}
480
481func (ctx *parseContext) lastAssignment(name string) *assignmentNode {
482 for va := ctx.varAssignments; va != nil; va = va.outer {
483 if v, ok := va.vars[name]; ok {
484 return v
485 }
486 }
487 return nil
488}
489
490func (ctx *parseContext) setLastAssignment(name string, asgn *assignmentNode) {
491 ctx.varAssignments.vars[name] = asgn
492}
493
494func (ctx *parseContext) pushVarAssignments() {
495 va := &varAssignmentScope{
496 outer: ctx.varAssignments,
497 vars: make(map[string]*assignmentNode),
498 }
499 ctx.varAssignments = va
500}
501
502func (ctx *parseContext) popVarAssignments() {
503 ctx.varAssignments = ctx.varAssignments.outer
504}
505
506func (ctx *parseContext) pushReceiver(rcv nodeReceiver) {
507 ctx.receiverStack = append(ctx.receiverStack, ctx.receiver)
508 ctx.receiver = rcv
509}
510
511func (ctx *parseContext) popReceiver() {
512 last := len(ctx.receiverStack) - 1
513 if last < 0 {
514 panic(fmt.Errorf("popReceiver: receiver stack empty"))
515 }
516 ctx.receiver = ctx.receiverStack[last]
517 ctx.receiverStack = ctx.receiverStack[0:last]
518}
519
520func (ctx *parseContext) hasNodes() bool {
521 return ctx.currentNodeIndex < len(ctx.nodes)
522}
523
524func (ctx *parseContext) getNode() mkparser.Node {
525 if !ctx.hasNodes() {
526 return nil
527 }
528 node := ctx.nodes[ctx.currentNodeIndex]
529 ctx.currentNodeIndex++
530 return node
531}
532
533func (ctx *parseContext) backNode() {
534 if ctx.currentNodeIndex <= 0 {
535 panic("Cannot back off")
536 }
537 ctx.currentNodeIndex--
538}
539
540func (ctx *parseContext) handleAssignment(a *mkparser.Assignment) {
541 // Handle only simple variables
542 if !a.Name.Const() {
543 ctx.errorf(a, "Only simple variables are handled")
544 return
545 }
546 name := a.Name.Strings[0]
Sasha Smundakea3bc3a2021-11-10 13:06:42 -0800547 // The `override` directive
548 // override FOO :=
549 // is parsed as an assignment to a variable named `override FOO`.
550 // There are very few places where `override` is used, just flag it.
551 if strings.HasPrefix(name, "override ") {
552 ctx.errorf(a, "cannot handle override directive")
553 }
554
Cole Faustc00184e2021-11-08 12:08:57 -0800555 // Soong configuration
Sasha Smundak3deb9682021-07-26 18:42:25 -0700556 if strings.HasPrefix(name, soongNsPrefix) {
557 ctx.handleSoongNsAssignment(strings.TrimPrefix(name, soongNsPrefix), a)
558 return
559 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800560 lhs := ctx.addVariable(name)
561 if lhs == nil {
562 ctx.errorf(a, "unknown variable %s", name)
563 return
564 }
565 _, isTraced := ctx.tracedVariables[name]
Sasha Smundak422b6142021-11-11 18:31:59 -0800566 asgn := &assignmentNode{lhs: lhs, mkValue: a.Value, isTraced: isTraced, location: ctx.errorLocation(a)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800567 if lhs.valueType() == starlarkTypeUnknown {
568 // Try to divine variable type from the RHS
569 asgn.value = ctx.parseMakeString(a, a.Value)
570 if xBad, ok := asgn.value.(*badExpr); ok {
571 ctx.wrapBadExpr(xBad)
572 return
573 }
574 inferred_type := asgn.value.typ()
575 if inferred_type != starlarkTypeUnknown {
Sasha Smundak9d011ab2021-07-09 16:00:57 -0700576 lhs.setValueType(inferred_type)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800577 }
578 }
579 if lhs.valueType() == starlarkTypeList {
580 xConcat := ctx.buildConcatExpr(a)
581 if xConcat == nil {
582 return
583 }
584 switch len(xConcat.items) {
585 case 0:
586 asgn.value = &listExpr{}
587 case 1:
588 asgn.value = xConcat.items[0]
589 default:
590 asgn.value = xConcat
591 }
592 } else {
593 asgn.value = ctx.parseMakeString(a, a.Value)
594 if xBad, ok := asgn.value.(*badExpr); ok {
595 ctx.wrapBadExpr(xBad)
596 return
597 }
598 }
599
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800600 asgn.previous = ctx.lastAssignment(name)
601 ctx.setLastAssignment(name, asgn)
602 switch a.Type {
603 case "=", ":=":
604 asgn.flavor = asgnSet
605 case "+=":
606 if asgn.previous == nil && !asgn.lhs.isPreset() {
607 asgn.flavor = asgnMaybeAppend
608 } else {
609 asgn.flavor = asgnAppend
610 }
611 case "?=":
612 asgn.flavor = asgnMaybeSet
613 default:
614 panic(fmt.Errorf("unexpected assignment type %s", a.Type))
615 }
616
617 ctx.receiver.newNode(asgn)
618}
619
Sasha Smundak3deb9682021-07-26 18:42:25 -0700620func (ctx *parseContext) handleSoongNsAssignment(name string, asgn *mkparser.Assignment) {
621 val := ctx.parseMakeString(asgn, asgn.Value)
622 if xBad, ok := val.(*badExpr); ok {
623 ctx.wrapBadExpr(xBad)
624 return
625 }
Sasha Smundak3deb9682021-07-26 18:42:25 -0700626
627 // Unfortunately, Soong namespaces can be set up by directly setting corresponding Make
628 // variables instead of via add_soong_config_namespace + add_soong_config_var_value.
629 // Try to divine the call from the assignment as follows:
630 if name == "NAMESPACES" {
631 // Upon seeng
632 // SOONG_CONFIG_NAMESPACES += foo
633 // remember that there is a namespace `foo` and act as we saw
634 // $(call add_soong_config_namespace,foo)
635 s, ok := maybeString(val)
636 if !ok {
637 ctx.errorf(asgn, "cannot handle variables in SOONG_CONFIG_NAMESPACES assignment, please use add_soong_config_namespace instead")
638 return
639 }
640 for _, ns := range strings.Fields(s) {
641 ctx.addSoongNamespace(ns)
642 ctx.receiver.newNode(&exprNode{&callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -0800643 name: baseName + ".soong_config_namespace",
644 args: []starlarkExpr{&globalsExpr{}, &stringLiteralExpr{ns}},
Sasha Smundak3deb9682021-07-26 18:42:25 -0700645 returnType: starlarkTypeVoid,
646 }})
647 }
648 } else {
649 // Upon seeing
650 // SOONG_CONFIG_x_y = v
651 // find a namespace called `x` and act as if we encountered
Cole Faustc00184e2021-11-08 12:08:57 -0800652 // $(call soong_config_set,x,y,v)
Sasha Smundak3deb9682021-07-26 18:42:25 -0700653 // or check that `x_y` is a namespace, and then add the RHS of this assignment as variables in
654 // it.
655 // Emit an error in the ambiguous situation (namespaces `foo_bar` with a variable `baz`
656 // and `foo` with a variable `bar_baz`.
657 namespaceName := ""
658 if ctx.hasSoongNamespace(name) {
659 namespaceName = name
660 }
661 var varName string
662 for pos, ch := range name {
663 if !(ch == '_' && ctx.hasSoongNamespace(name[0:pos])) {
664 continue
665 }
666 if namespaceName != "" {
667 ctx.errorf(asgn, "ambiguous soong namespace (may be either `%s` or `%s`)", namespaceName, name[0:pos])
668 return
669 }
670 namespaceName = name[0:pos]
671 varName = name[pos+1:]
672 }
673 if namespaceName == "" {
674 ctx.errorf(asgn, "cannot figure out Soong namespace, please use add_soong_config_var_value macro instead")
675 return
676 }
677 if varName == "" {
678 // Remember variables in this namespace
679 s, ok := maybeString(val)
680 if !ok {
681 ctx.errorf(asgn, "cannot handle variables in SOONG_CONFIG_ assignment, please use add_soong_config_var_value instead")
682 return
683 }
684 ctx.updateSoongNamespace(asgn.Type != "+=", namespaceName, strings.Fields(s))
685 return
686 }
687
688 // Finally, handle assignment to a namespace variable
689 if !ctx.hasNamespaceVar(namespaceName, varName) {
690 ctx.errorf(asgn, "no %s variable in %s namespace, please use add_soong_config_var_value instead", varName, namespaceName)
691 return
692 }
Cole Faust9ebf6e42021-12-13 14:08:34 -0800693 fname := baseName + "." + soongConfigAssign
Sasha Smundak65b547e2021-09-17 15:35:41 -0700694 if asgn.Type == "+=" {
Cole Faust9ebf6e42021-12-13 14:08:34 -0800695 fname = baseName + "." + soongConfigAppend
Sasha Smundak65b547e2021-09-17 15:35:41 -0700696 }
Sasha Smundak3deb9682021-07-26 18:42:25 -0700697 ctx.receiver.newNode(&exprNode{&callExpr{
Sasha Smundak65b547e2021-09-17 15:35:41 -0700698 name: fname,
Cole Faust9ebf6e42021-12-13 14:08:34 -0800699 args: []starlarkExpr{&globalsExpr{}, &stringLiteralExpr{namespaceName}, &stringLiteralExpr{varName}, val},
Sasha Smundak3deb9682021-07-26 18:42:25 -0700700 returnType: starlarkTypeVoid,
701 }})
702 }
703}
704
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800705func (ctx *parseContext) buildConcatExpr(a *mkparser.Assignment) *concatExpr {
706 xConcat := &concatExpr{}
707 var xItemList *listExpr
708 addToItemList := func(x ...starlarkExpr) {
709 if xItemList == nil {
710 xItemList = &listExpr{[]starlarkExpr{}}
711 }
712 xItemList.items = append(xItemList.items, x...)
713 }
714 finishItemList := func() {
715 if xItemList != nil {
716 xConcat.items = append(xConcat.items, xItemList)
717 xItemList = nil
718 }
719 }
720
721 items := a.Value.Words()
722 for _, item := range items {
723 // A function call in RHS is supposed to return a list, all other item
724 // expressions return individual elements.
725 switch x := ctx.parseMakeString(a, item).(type) {
726 case *badExpr:
727 ctx.wrapBadExpr(x)
728 return nil
729 case *stringLiteralExpr:
730 addToItemList(maybeConvertToStringList(x).(*listExpr).items...)
731 default:
732 switch x.typ() {
733 case starlarkTypeList:
734 finishItemList()
735 xConcat.items = append(xConcat.items, x)
736 case starlarkTypeString:
737 finishItemList()
738 xConcat.items = append(xConcat.items, &callExpr{
739 object: x,
740 name: "split",
741 args: nil,
742 returnType: starlarkTypeList,
743 })
744 default:
745 addToItemList(x)
746 }
747 }
748 }
749 if xItemList != nil {
750 xConcat.items = append(xConcat.items, xItemList)
751 }
752 return xConcat
753}
754
Sasha Smundak6609ba72021-07-22 18:32:56 -0700755func (ctx *parseContext) newDependentModule(path string, optional bool) *moduleInfo {
756 modulePath := ctx.loadedModulePath(path)
757 if mi, ok := ctx.dependentModules[modulePath]; ok {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700758 mi.optional = mi.optional && optional
Sasha Smundak6609ba72021-07-22 18:32:56 -0700759 return mi
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800760 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800761 moduleName := moduleNameForFile(path)
762 moduleLocalName := "_" + moduleName
763 n, found := ctx.moduleNameCount[moduleName]
764 if found {
765 moduleLocalName += fmt.Sprintf("%d", n)
766 }
767 ctx.moduleNameCount[moduleName] = n + 1
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800768 _, err := fs.Stat(ctx.script.sourceFS, path)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700769 mi := &moduleInfo{
770 path: modulePath,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800771 originalPath: path,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800772 moduleLocalName: moduleLocalName,
Sasha Smundak6609ba72021-07-22 18:32:56 -0700773 optional: optional,
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800774 missing: err != nil,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800775 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700776 ctx.dependentModules[modulePath] = mi
777 ctx.script.inherited = append(ctx.script.inherited, mi)
778 return mi
779}
780
781func (ctx *parseContext) handleSubConfig(
782 v mkparser.Node, pathExpr starlarkExpr, loadAlways bool, processModule func(inheritedModule)) {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700783
784 // In a simple case, the name of a module to inherit/include is known statically.
785 if path, ok := maybeString(pathExpr); ok {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700786 // Note that even if this directive loads a module unconditionally, a module may be
787 // absent without causing any harm if this directive is inside an if/else block.
788 moduleShouldExist := loadAlways && ctx.ifNestLevel == 0
Sasha Smundak6609ba72021-07-22 18:32:56 -0700789 if strings.Contains(path, "*") {
790 if paths, err := fs.Glob(ctx.script.sourceFS, path); err == nil {
791 for _, p := range paths {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700792 mi := ctx.newDependentModule(p, !moduleShouldExist)
793 processModule(inheritedStaticModule{mi, loadAlways})
Sasha Smundak6609ba72021-07-22 18:32:56 -0700794 }
795 } else {
796 ctx.errorf(v, "cannot glob wildcard argument")
797 }
798 } else {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700799 mi := ctx.newDependentModule(path, !moduleShouldExist)
800 processModule(inheritedStaticModule{mi, loadAlways})
Sasha Smundak6609ba72021-07-22 18:32:56 -0700801 }
802 return
803 }
804
805 // If module path references variables (e.g., $(v1)/foo/$(v2)/device-config.mk), find all the paths in the
806 // source tree that may be a match and the corresponding variable values. For instance, if the source tree
807 // contains vendor1/foo/abc/dev.mk and vendor2/foo/def/dev.mk, the first one will be inherited when
808 // (v1, v2) == ('vendor1', 'abc'), and the second one when (v1, v2) == ('vendor2', 'def').
809 // We then emit the code that loads all of them, e.g.:
810 // load("//vendor1/foo/abc:dev.rbc", _dev1_init="init")
811 // load("//vendor2/foo/def/dev.rbc", _dev2_init="init")
812 // And then inherit it as follows:
813 // _e = {
814 // "vendor1/foo/abc/dev.mk": ("vendor1/foo/abc/dev", _dev1_init),
815 // "vendor2/foo/def/dev.mk": ("vendor2/foo/def/dev", _dev_init2) }.get("%s/foo/%s/dev.mk" % (v1, v2))
816 // if _e:
817 // rblf.inherit(handle, _e[0], _e[1])
818 //
819 var matchingPaths []string
820 varPath, ok := pathExpr.(*interpolateExpr)
821 if !ok {
822 ctx.errorf(v, "inherit-product/include argument is too complex")
823 return
824 }
825
826 pathPattern := []string{varPath.chunks[0]}
827 for _, chunk := range varPath.chunks[1:] {
828 if chunk != "" {
829 pathPattern = append(pathPattern, chunk)
830 }
831 }
Sasha Smundak6d852dd2021-09-27 20:34:39 -0700832 if pathPattern[0] == "" {
Cole Faust6c934f62022-01-06 15:51:12 -0800833 if len(ctx.includeTops) == 0 {
834 ctx.errorf(v, "inherit-product/include statements must not be prefixed with a variable, or must include a #RBC# include_top comment beforehand giving a root directory to search.")
835 return
836 }
Sasha Smundak6d852dd2021-09-27 20:34:39 -0700837 // If pattern starts from the top. restrict it to the directories where
838 // we know inherit-product uses dynamically calculated path.
839 for _, p := range ctx.includeTops {
840 pathPattern[0] = p
841 matchingPaths = append(matchingPaths, ctx.findMatchingPaths(pathPattern)...)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700842 }
Sasha Smundak6d852dd2021-09-27 20:34:39 -0700843 } else {
844 matchingPaths = ctx.findMatchingPaths(pathPattern)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700845 }
846 // Safeguard against $(call inherit-product,$(PRODUCT_PATH))
Sasha Smundak90be8c52021-08-03 11:06:10 -0700847 const maxMatchingFiles = 150
Sasha Smundak6609ba72021-07-22 18:32:56 -0700848 if len(matchingPaths) > maxMatchingFiles {
849 ctx.errorf(v, "there are >%d files matching the pattern, please rewrite it", maxMatchingFiles)
850 return
851 }
852 res := inheritedDynamicModule{*varPath, []*moduleInfo{}, loadAlways}
853 for _, p := range matchingPaths {
854 // A product configuration files discovered dynamically may attempt to inherit
855 // from another one which does not exist in this source tree. Prevent load errors
856 // by always loading the dynamic files as optional.
857 res.candidateModules = append(res.candidateModules, ctx.newDependentModule(p, true))
858 }
859 processModule(res)
860}
861
862func (ctx *parseContext) findMatchingPaths(pattern []string) []string {
863 files := ctx.script.makefileFinder.Find(ctx.script.topDir)
864 if len(pattern) == 0 {
865 return files
866 }
867
868 // Create regular expression from the pattern
869 s_regexp := "^" + regexp.QuoteMeta(pattern[0])
870 for _, s := range pattern[1:] {
871 s_regexp += ".*" + regexp.QuoteMeta(s)
872 }
873 s_regexp += "$"
874 rex := regexp.MustCompile(s_regexp)
875
876 // Now match
877 var res []string
878 for _, p := range files {
879 if rex.MatchString(p) {
880 res = append(res, p)
881 }
882 }
883 return res
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800884}
885
Cole Faust9ebf6e42021-12-13 14:08:34 -0800886func (ctx *parseContext) handleInheritModule(v mkparser.Node, args *mkparser.MakeString, loadAlways bool) {
887 args.TrimLeftSpaces()
888 args.TrimRightSpaces()
889 pathExpr := ctx.parseMakeString(v, args)
890 if _, ok := pathExpr.(*badExpr); ok {
891 ctx.errorf(v, "Unable to parse argument to inherit")
892 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700893 ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700894 ctx.receiver.newNode(&inheritNode{im, loadAlways})
Sasha Smundak6609ba72021-07-22 18:32:56 -0700895 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800896}
897
898func (ctx *parseContext) handleInclude(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700899 ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700900 ctx.receiver.newNode(&includeNode{im, loadAlways})
Sasha Smundak6609ba72021-07-22 18:32:56 -0700901 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800902}
903
904func (ctx *parseContext) handleVariable(v *mkparser.Variable) {
905 // Handle:
906 // $(call inherit-product,...)
907 // $(call inherit-product-if-exists,...)
908 // $(info xxx)
909 // $(warning xxx)
910 // $(error xxx)
Cole Faust9ebf6e42021-12-13 14:08:34 -0800911 // $(call other-custom-functions,...)
912
913 // inherit-product(-if-exists) gets converted to a series of statements,
914 // not just a single expression like parseReference returns. So handle it
915 // separately at the beginning here.
916 if strings.HasPrefix(v.Name.Dump(), "call inherit-product,") {
917 args := v.Name.Clone()
918 args.ReplaceLiteral("call inherit-product,", "")
919 ctx.handleInheritModule(v, args, true)
920 return
921 }
922 if strings.HasPrefix(v.Name.Dump(), "call inherit-product-if-exists,") {
923 args := v.Name.Clone()
924 args.ReplaceLiteral("call inherit-product-if-exists,", "")
925 ctx.handleInheritModule(v, args, false)
926 return
927 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800928 expr := ctx.parseReference(v, v.Name)
929 switch x := expr.(type) {
930 case *callExpr:
Cole Faust9ebf6e42021-12-13 14:08:34 -0800931 ctx.receiver.newNode(&exprNode{expr})
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800932 case *badExpr:
933 ctx.wrapBadExpr(x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800934 default:
935 ctx.errorf(v, "cannot handle %s", v.Dump())
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800936 }
937}
938
939func (ctx *parseContext) handleDefine(directive *mkparser.Directive) {
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700940 macro_name := strings.Fields(directive.Args.Strings[0])[0]
941 // Ignore the macros that we handle
Cole Faust9ebf6e42021-12-13 14:08:34 -0800942 _, ignored := ignoredDefines[macro_name]
943 _, known := knownFunctions[macro_name]
944 if !ignored && !known {
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700945 ctx.errorf(directive, "define is not supported: %s", macro_name)
946 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800947}
948
949func (ctx *parseContext) handleIfBlock(ifDirective *mkparser.Directive) {
950 ssSwitch := &switchNode{}
951 ctx.pushReceiver(ssSwitch)
952 for ctx.processBranch(ifDirective); ctx.hasNodes() && ctx.fatalError == nil; {
953 node := ctx.getNode()
954 switch x := node.(type) {
955 case *mkparser.Directive:
956 switch x.Name {
957 case "else", "elifdef", "elifndef", "elifeq", "elifneq":
958 ctx.processBranch(x)
959 case "endif":
960 ctx.popReceiver()
961 ctx.receiver.newNode(ssSwitch)
962 return
963 default:
964 ctx.errorf(node, "unexpected directive %s", x.Name)
965 }
966 default:
967 ctx.errorf(ifDirective, "unexpected statement")
968 }
969 }
970 if ctx.fatalError == nil {
971 ctx.fatalError = fmt.Errorf("no matching endif for %s", ifDirective.Dump())
972 }
973 ctx.popReceiver()
974}
975
976// processBranch processes a single branch (if/elseif/else) until the next directive
977// on the same level.
978func (ctx *parseContext) processBranch(check *mkparser.Directive) {
979 block := switchCase{gate: ctx.parseCondition(check)}
980 defer func() {
981 ctx.popVarAssignments()
982 ctx.ifNestLevel--
983
984 }()
985 ctx.pushVarAssignments()
986 ctx.ifNestLevel++
987
988 ctx.pushReceiver(&block)
989 for ctx.hasNodes() {
990 node := ctx.getNode()
Cole Faust591a1fe2021-11-08 15:37:57 -0800991 if d, ok := node.(*mkparser.Directive); ok {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800992 switch d.Name {
993 case "else", "elifdef", "elifndef", "elifeq", "elifneq", "endif":
994 ctx.popReceiver()
995 ctx.receiver.newNode(&block)
996 ctx.backNode()
997 return
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800998 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800999 }
Cole Faust591a1fe2021-11-08 15:37:57 -08001000 ctx.handleSimpleStatement(node)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001001 }
1002 ctx.fatalError = fmt.Errorf("no matching endif for %s", check.Dump())
1003 ctx.popReceiver()
1004}
1005
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001006func (ctx *parseContext) parseCondition(check *mkparser.Directive) starlarkNode {
1007 switch check.Name {
1008 case "ifdef", "ifndef", "elifdef", "elifndef":
Cole Faust71514c02022-01-27 17:21:41 -08001009 if !check.Args.Const() {
1010 return &exprNode{expr: ctx.newBadExpr(check, "ifdef variable ref too complex: %s", check.Args.Dump())}
1011 }
1012 v := NewVariableRefExpr(ctx.addVariable(check.Args.Strings[0]), false)
1013 if strings.HasSuffix(check.Name, "ndef") {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001014 v = &notExpr{v}
1015 }
1016 return &ifNode{
1017 isElif: strings.HasPrefix(check.Name, "elif"),
1018 expr: v,
1019 }
1020 case "ifeq", "ifneq", "elifeq", "elifneq":
1021 return &ifNode{
1022 isElif: strings.HasPrefix(check.Name, "elif"),
1023 expr: ctx.parseCompare(check),
1024 }
1025 case "else":
1026 return &elseNode{}
1027 default:
1028 panic(fmt.Errorf("%s: unknown directive: %s", ctx.script.mkFile, check.Dump()))
1029 }
1030}
1031
1032func (ctx *parseContext) newBadExpr(node mkparser.Node, text string, args ...interface{}) starlarkExpr {
1033 message := fmt.Sprintf(text, args...)
1034 if ctx.errorLogger != nil {
Sasha Smundak422b6142021-11-11 18:31:59 -08001035 ctx.errorLogger.NewError(ctx.errorLocation(node), node, text, args...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001036 }
1037 ctx.script.hasErrors = true
Sasha Smundak422b6142021-11-11 18:31:59 -08001038 return &badExpr{errorLocation: ctx.errorLocation(node), message: message}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001039}
1040
1041func (ctx *parseContext) parseCompare(cond *mkparser.Directive) starlarkExpr {
1042 // Strip outer parentheses
1043 mkArg := cloneMakeString(cond.Args)
1044 mkArg.Strings[0] = strings.TrimLeft(mkArg.Strings[0], "( ")
1045 n := len(mkArg.Strings)
1046 mkArg.Strings[n-1] = strings.TrimRight(mkArg.Strings[n-1], ") ")
1047 args := mkArg.Split(",")
1048 // TODO(asmundak): handle the case where the arguments are in quotes and space-separated
1049 if len(args) != 2 {
1050 return ctx.newBadExpr(cond, "ifeq/ifneq len(args) != 2 %s", cond.Dump())
1051 }
1052 args[0].TrimRightSpaces()
1053 args[1].TrimLeftSpaces()
1054
1055 isEq := !strings.HasSuffix(cond.Name, "neq")
Cole Faustf8320212021-11-10 15:05:07 -08001056 xLeft := ctx.parseMakeString(cond, args[0])
1057 xRight := ctx.parseMakeString(cond, args[1])
1058 if bad, ok := xLeft.(*badExpr); ok {
1059 return bad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001060 }
Cole Faustf8320212021-11-10 15:05:07 -08001061 if bad, ok := xRight.(*badExpr); ok {
1062 return bad
1063 }
1064
1065 if expr, ok := ctx.parseCompareSpecialCases(cond, xLeft, xRight); ok {
1066 return expr
1067 }
1068
Cole Faust9ebf6e42021-12-13 14:08:34 -08001069 var stringOperand string
1070 var otherOperand starlarkExpr
1071 if s, ok := maybeString(xLeft); ok {
1072 stringOperand = s
1073 otherOperand = xRight
1074 } else if s, ok := maybeString(xRight); ok {
1075 stringOperand = s
1076 otherOperand = xLeft
1077 }
1078
1079 not := func(expr starlarkExpr) starlarkExpr {
1080 switch typedExpr := expr.(type) {
1081 case *inExpr:
1082 typedExpr.isNot = !typedExpr.isNot
1083 return typedExpr
1084 case *eqExpr:
1085 typedExpr.isEq = !typedExpr.isEq
1086 return typedExpr
Cole Faustb1103e22022-01-06 15:22:05 -08001087 case *binaryOpExpr:
1088 switch typedExpr.op {
1089 case ">":
1090 typedExpr.op = "<="
1091 return typedExpr
1092 case "<":
1093 typedExpr.op = ">="
1094 return typedExpr
1095 case ">=":
1096 typedExpr.op = "<"
1097 return typedExpr
1098 case "<=":
1099 typedExpr.op = ">"
1100 return typedExpr
1101 default:
1102 return &notExpr{expr: expr}
1103 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001104 default:
1105 return &notExpr{expr: expr}
1106 }
1107 }
1108
1109 // If we've identified one of the operands as being a string literal, check
1110 // for some special cases we can do to simplify the resulting expression.
1111 if otherOperand != nil {
1112 if stringOperand == "" {
1113 if isEq {
1114 return not(otherOperand)
1115 } else {
1116 return otherOperand
1117 }
1118 }
1119 if stringOperand == "true" && otherOperand.typ() == starlarkTypeBool {
1120 if !isEq {
1121 return not(otherOperand)
1122 } else {
1123 return otherOperand
1124 }
1125 }
Cole Faustb1103e22022-01-06 15:22:05 -08001126 if intOperand, err := strconv.Atoi(strings.TrimSpace(stringOperand)); err == nil && otherOperand.typ() == starlarkTypeInt {
1127 return &eqExpr{
1128 left: otherOperand,
1129 right: &intLiteralExpr{literal: intOperand},
1130 isEq: isEq,
1131 }
1132 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001133 }
1134
Cole Faustf8320212021-11-10 15:05:07 -08001135 return &eqExpr{left: xLeft, right: xRight, isEq: isEq}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001136}
1137
Cole Faustf8320212021-11-10 15:05:07 -08001138// Given an if statement's directive and the left/right starlarkExprs,
1139// check if the starlarkExprs are one of a few hardcoded special cases
1140// that can be converted to a simpler equalify expression than simply comparing
1141// the two.
1142func (ctx *parseContext) parseCompareSpecialCases(directive *mkparser.Directive, left starlarkExpr,
1143 right starlarkExpr) (starlarkExpr, bool) {
1144 isEq := !strings.HasSuffix(directive.Name, "neq")
1145
1146 // All the special cases require a call on one side and a
1147 // string literal/variable on the other. Turn the left/right variables into
1148 // call/value variables, and return false if that's not possible.
1149 var value starlarkExpr = nil
1150 call, ok := left.(*callExpr)
1151 if ok {
1152 switch right.(type) {
1153 case *stringLiteralExpr, *variableRefExpr:
1154 value = right
1155 }
1156 } else {
1157 call, _ = right.(*callExpr)
1158 switch left.(type) {
1159 case *stringLiteralExpr, *variableRefExpr:
1160 value = left
1161 }
1162 }
1163
1164 if call == nil || value == nil {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001165 return nil, false
1166 }
Cole Faustf8320212021-11-10 15:05:07 -08001167
Cole Faustf8320212021-11-10 15:05:07 -08001168 switch call.name {
Cole Faust9ebf6e42021-12-13 14:08:34 -08001169 case baseName + ".filter", baseName + ".filter-out":
Cole Faustf8320212021-11-10 15:05:07 -08001170 return ctx.parseCompareFilterFuncResult(directive, call, value, isEq), true
Cole Faust9ebf6e42021-12-13 14:08:34 -08001171 case baseName + ".expand_wildcard":
Cole Faustf8320212021-11-10 15:05:07 -08001172 return ctx.parseCompareWildcardFuncResult(directive, call, value, !isEq), true
Cole Faust9ebf6e42021-12-13 14:08:34 -08001173 case baseName + ".findstring":
Cole Faustf8320212021-11-10 15:05:07 -08001174 return ctx.parseCheckFindstringFuncResult(directive, call, value, !isEq), true
Cole Faust9ebf6e42021-12-13 14:08:34 -08001175 case baseName + ".strip":
Cole Faustf8320212021-11-10 15:05:07 -08001176 return ctx.parseCompareStripFuncResult(directive, call, value, !isEq), true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001177 }
Cole Faustf8320212021-11-10 15:05:07 -08001178 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001179}
1180
1181func (ctx *parseContext) parseCompareFilterFuncResult(cond *mkparser.Directive,
1182 filterFuncCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
1183 // We handle:
Sasha Smundak0554d762021-07-08 18:26:12 -07001184 // * ifeq/ifneq (,$(filter v1 v2 ..., EXPR) becomes if EXPR not in/in ["v1", "v2", ...]
1185 // * ifeq/ifneq (,$(filter EXPR, v1 v2 ...) becomes if EXPR not in/in ["v1", "v2", ...]
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001186 // * ifeq/ifneq ($(VAR),$(filter $(VAR), v1 v2 ...) becomes if VAR in/not in ["v1", "v2"]
1187 // TODO(Asmundak): check the last case works for filter-out, too.
1188 xPattern := filterFuncCall.args[0]
1189 xText := filterFuncCall.args[1]
1190 var xInList *stringLiteralExpr
Sasha Smundak0554d762021-07-08 18:26:12 -07001191 var expr starlarkExpr
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001192 var ok bool
1193 switch x := xValue.(type) {
1194 case *stringLiteralExpr:
1195 if x.literal != "" {
1196 return ctx.newBadExpr(cond, "filter comparison to non-empty value: %s", xValue)
1197 }
1198 // Either pattern or text should be const, and the
1199 // non-const one should be varRefExpr
Sasha Smundak5f463be2021-09-15 18:43:36 -07001200 if xInList, ok = xPattern.(*stringLiteralExpr); ok && !strings.ContainsRune(xInList.literal, '%') && xText.typ() == starlarkTypeList {
Sasha Smundak0554d762021-07-08 18:26:12 -07001201 expr = xText
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001202 } else if xInList, ok = xText.(*stringLiteralExpr); ok {
Sasha Smundak0554d762021-07-08 18:26:12 -07001203 expr = xPattern
1204 } else {
Sasha Smundak5f463be2021-09-15 18:43:36 -07001205 expr = &callExpr{
Sasha Smundak0554d762021-07-08 18:26:12 -07001206 object: nil,
1207 name: filterFuncCall.name,
1208 args: filterFuncCall.args,
1209 returnType: starlarkTypeBool,
1210 }
Sasha Smundak5f463be2021-09-15 18:43:36 -07001211 if negate {
1212 expr = &notExpr{expr: expr}
1213 }
1214 return expr
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001215 }
1216 case *variableRefExpr:
1217 if v, ok := xPattern.(*variableRefExpr); ok {
1218 if xInList, ok = xText.(*stringLiteralExpr); ok && v.ref.name() == x.ref.name() {
1219 // ifeq/ifneq ($(VAR),$(filter $(VAR), v1 v2 ...), flip negate,
1220 // it's the opposite to what is done when comparing to empty.
Sasha Smundak0554d762021-07-08 18:26:12 -07001221 expr = xPattern
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001222 negate = !negate
1223 }
1224 }
1225 }
Sasha Smundak0554d762021-07-08 18:26:12 -07001226 if expr != nil && xInList != nil {
1227 slExpr := newStringListExpr(strings.Fields(xInList.literal))
1228 // Generate simpler code for the common cases:
1229 if expr.typ() == starlarkTypeList {
1230 if len(slExpr.items) == 1 {
1231 // Checking that a string belongs to list
1232 return &inExpr{isNot: negate, list: expr, expr: slExpr.items[0]}
1233 } else {
1234 // TODO(asmundak):
1235 panic("TBD")
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001236 }
Sasha Smundak0554d762021-07-08 18:26:12 -07001237 } else if len(slExpr.items) == 1 {
1238 return &eqExpr{left: expr, right: slExpr.items[0], isEq: !negate}
1239 } else {
1240 return &inExpr{isNot: negate, list: newStringListExpr(strings.Fields(xInList.literal)), expr: expr}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001241 }
1242 }
1243 return ctx.newBadExpr(cond, "filter arguments are too complex: %s", cond.Dump())
1244}
1245
1246func (ctx *parseContext) parseCompareWildcardFuncResult(directive *mkparser.Directive,
1247 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001248 if !isEmptyString(xValue) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001249 return ctx.newBadExpr(directive, "wildcard result can be compared only to empty: %s", xValue)
1250 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001251 callFunc := baseName + ".file_wildcard_exists"
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001252 if s, ok := xCall.args[0].(*stringLiteralExpr); ok && !strings.ContainsAny(s.literal, "*?{[") {
Cole Faust9ebf6e42021-12-13 14:08:34 -08001253 callFunc = baseName + ".file_exists"
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001254 }
1255 var cc starlarkExpr = &callExpr{name: callFunc, args: xCall.args, returnType: starlarkTypeBool}
1256 if !negate {
1257 cc = &notExpr{cc}
1258 }
1259 return cc
1260}
1261
1262func (ctx *parseContext) parseCheckFindstringFuncResult(directive *mkparser.Directive,
1263 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001264 if isEmptyString(xValue) {
1265 return &eqExpr{
1266 left: &callExpr{
1267 object: xCall.args[1],
1268 name: "find",
1269 args: []starlarkExpr{xCall.args[0]},
1270 returnType: starlarkTypeInt,
1271 },
1272 right: &intLiteralExpr{-1},
1273 isEq: !negate,
1274 }
Cole Faust0e9418c2021-12-13 16:33:25 -08001275 } else if s, ok := maybeString(xValue); ok {
1276 if s2, ok := maybeString(xCall.args[0]); ok && s == s2 {
1277 return &eqExpr{
1278 left: &callExpr{
1279 object: xCall.args[1],
1280 name: "find",
1281 args: []starlarkExpr{xCall.args[0]},
1282 returnType: starlarkTypeInt,
1283 },
1284 right: &intLiteralExpr{-1},
1285 isEq: negate,
1286 }
1287 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001288 }
Cole Faust0e9418c2021-12-13 16:33:25 -08001289 return ctx.newBadExpr(directive, "$(findstring) can only be compared to nothing or its first argument")
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001290}
1291
1292func (ctx *parseContext) parseCompareStripFuncResult(directive *mkparser.Directive,
1293 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
1294 if _, ok := xValue.(*stringLiteralExpr); !ok {
1295 return ctx.newBadExpr(directive, "strip result can be compared only to string: %s", xValue)
1296 }
1297 return &eqExpr{
1298 left: &callExpr{
1299 name: "strip",
1300 args: xCall.args,
1301 returnType: starlarkTypeString,
1302 },
1303 right: xValue, isEq: !negate}
1304}
1305
1306// parses $(...), returning an expression
1307func (ctx *parseContext) parseReference(node mkparser.Node, ref *mkparser.MakeString) starlarkExpr {
1308 ref.TrimLeftSpaces()
1309 ref.TrimRightSpaces()
1310 refDump := ref.Dump()
1311
1312 // Handle only the case where the first (or only) word is constant
1313 words := ref.SplitN(" ", 2)
1314 if !words[0].Const() {
1315 return ctx.newBadExpr(node, "reference is too complex: %s", refDump)
1316 }
1317
1318 // If it is a single word, it can be a simple variable
1319 // reference or a function call
Cole Faust9ebf6e42021-12-13 14:08:34 -08001320 if len(words) == 1 && !isMakeControlFunc(refDump) && refDump != "shell" {
Sasha Smundak65b547e2021-09-17 15:35:41 -07001321 if strings.HasPrefix(refDump, soongNsPrefix) {
1322 // TODO (asmundak): if we find many, maybe handle them.
Cole Faustc00184e2021-11-08 12:08:57 -08001323 return ctx.newBadExpr(node, "SOONG_CONFIG_ variables cannot be referenced, use soong_config_get instead: %s", refDump)
Sasha Smundak65b547e2021-09-17 15:35:41 -07001324 }
Cole Faustc36c9622021-12-07 15:20:45 -08001325 // Handle substitution references: https://www.gnu.org/software/make/manual/html_node/Substitution-Refs.html
1326 if strings.Contains(refDump, ":") {
1327 parts := strings.SplitN(refDump, ":", 2)
1328 substParts := strings.SplitN(parts[1], "=", 2)
1329 if len(substParts) < 2 || strings.Count(substParts[0], "%") > 1 {
1330 return ctx.newBadExpr(node, "Invalid substitution reference")
1331 }
1332 if !strings.Contains(substParts[0], "%") {
1333 if strings.Contains(substParts[1], "%") {
1334 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.")
1335 }
1336 substParts[0] = "%" + substParts[0]
1337 substParts[1] = "%" + substParts[1]
1338 }
1339 v := ctx.addVariable(parts[0])
1340 if v == nil {
1341 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1342 }
1343 return &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001344 name: baseName + ".mkpatsubst",
1345 returnType: starlarkTypeString,
Cole Faustc36c9622021-12-07 15:20:45 -08001346 args: []starlarkExpr{
1347 &stringLiteralExpr{literal: substParts[0]},
1348 &stringLiteralExpr{literal: substParts[1]},
Cole Faustfc438682021-12-14 12:46:32 -08001349 NewVariableRefExpr(v, ctx.lastAssignment(v.name()) != nil),
Cole Faustc36c9622021-12-07 15:20:45 -08001350 },
1351 }
1352 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001353 if v := ctx.addVariable(refDump); v != nil {
Cole Faustfc438682021-12-14 12:46:32 -08001354 return NewVariableRefExpr(v, ctx.lastAssignment(v.name()) != nil)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001355 }
1356 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1357 }
1358
1359 expr := &callExpr{name: words[0].Dump(), returnType: starlarkTypeUnknown}
Cole Faust9ebf6e42021-12-13 14:08:34 -08001360 args := mkparser.SimpleMakeString("", words[0].Pos())
1361 if len(words) >= 2 {
1362 args = words[1]
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001363 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001364 args.TrimLeftSpaces()
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001365 if expr.name == "call" {
1366 words = args.SplitN(",", 2)
1367 if words[0].Empty() || !words[0].Const() {
Sasha Smundakf2c9f8b2021-07-27 10:44:48 -07001368 return ctx.newBadExpr(node, "cannot handle %s", refDump)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001369 }
1370 expr.name = words[0].Dump()
1371 if len(words) < 2 {
Sasha Smundak6609ba72021-07-22 18:32:56 -07001372 args = &mkparser.MakeString{}
1373 } else {
1374 args = words[1]
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001375 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001376 }
1377 if kf, found := knownFunctions[expr.name]; found {
Cole Faust9ebf6e42021-12-13 14:08:34 -08001378 return kf.parse(ctx, node, args)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001379 } else {
1380 return ctx.newBadExpr(node, "cannot handle invoking %s", expr.name)
1381 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001382}
1383
1384type simpleCallParser struct {
1385 name string
1386 returnType starlarkType
1387 addGlobals bool
1388}
1389
1390func (p *simpleCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1391 expr := &callExpr{name: p.name, returnType: p.returnType}
1392 if p.addGlobals {
1393 expr.args = append(expr.args, &globalsExpr{})
1394 }
1395 for _, arg := range args.Split(",") {
1396 arg.TrimLeftSpaces()
1397 arg.TrimRightSpaces()
1398 x := ctx.parseMakeString(node, arg)
1399 if xBad, ok := x.(*badExpr); ok {
1400 return xBad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001401 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001402 expr.args = append(expr.args, x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001403 }
1404 return expr
1405}
1406
Cole Faust9ebf6e42021-12-13 14:08:34 -08001407type makeControlFuncParser struct {
1408 name string
1409}
1410
1411func (p *makeControlFuncParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1412 // Make control functions need special treatment as everything
1413 // after the name is a single text argument
1414 x := ctx.parseMakeString(node, args)
1415 if xBad, ok := x.(*badExpr); ok {
1416 return xBad
1417 }
1418 return &callExpr{
1419 name: p.name,
1420 args: []starlarkExpr{
1421 &stringLiteralExpr{ctx.script.mkFile},
1422 x,
1423 },
1424 returnType: starlarkTypeUnknown,
1425 }
1426}
1427
1428type shellCallParser struct{}
1429
1430func (p *shellCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1431 // Shell functions need special treatment as everything
1432 // after the name is a single text argument
1433 x := ctx.parseMakeString(node, args)
1434 if xBad, ok := x.(*badExpr); ok {
1435 return xBad
1436 }
1437 return &callExpr{
1438 name: baseName + ".shell",
1439 args: []starlarkExpr{x},
1440 returnType: starlarkTypeUnknown,
1441 }
1442}
1443
1444type myDirCallParser struct{}
1445
1446func (p *myDirCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1447 if !args.Empty() {
1448 return ctx.newBadExpr(node, "my-dir function cannot have any arguments passed to it.")
1449 }
1450 return &variableRefExpr{ctx.addVariable("LOCAL_PATH"), true}
1451}
1452
Cole Faust9ebf6e42021-12-13 14:08:34 -08001453type isProductInListCallParser struct{}
1454
1455func (p *isProductInListCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1456 if args.Empty() {
1457 return ctx.newBadExpr(node, "is-product-in-list requires an argument")
1458 }
1459 return &inExpr{
1460 expr: &variableRefExpr{ctx.addVariable("TARGET_PRODUCT"), true},
1461 list: maybeConvertToStringList(ctx.parseMakeString(node, args)),
1462 isNot: false,
1463 }
1464}
1465
1466type isVendorBoardPlatformCallParser struct{}
1467
1468func (p *isVendorBoardPlatformCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1469 if args.Empty() || !identifierFullMatchRegex.MatchString(args.Dump()) {
1470 return ctx.newBadExpr(node, "cannot handle non-constant argument to is-vendor-board-platform")
1471 }
1472 return &inExpr{
1473 expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
1474 list: &variableRefExpr{ctx.addVariable(args.Dump() + "_BOARD_PLATFORMS"), true},
1475 isNot: false,
1476 }
1477}
1478
1479type isVendorBoardQcomCallParser struct{}
1480
1481func (p *isVendorBoardQcomCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1482 if !args.Empty() {
1483 return ctx.newBadExpr(node, "is-vendor-board-qcom does not accept any arguments")
1484 }
1485 return &inExpr{
1486 expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
1487 list: &variableRefExpr{ctx.addVariable("QCOM_BOARD_PLATFORMS"), true},
1488 isNot: false,
1489 }
1490}
1491
1492type substCallParser struct {
1493 fname string
1494}
1495
1496func (p *substCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001497 words := args.Split(",")
1498 if len(words) != 3 {
Cole Faust9ebf6e42021-12-13 14:08:34 -08001499 return ctx.newBadExpr(node, "%s function should have 3 arguments", p.fname)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001500 }
Sasha Smundak35434ed2021-11-05 16:29:56 -07001501 from := ctx.parseMakeString(node, words[0])
1502 if xBad, ok := from.(*badExpr); ok {
1503 return xBad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001504 }
Sasha Smundak35434ed2021-11-05 16:29:56 -07001505 to := ctx.parseMakeString(node, words[1])
1506 if xBad, ok := to.(*badExpr); ok {
1507 return xBad
1508 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001509 words[2].TrimLeftSpaces()
1510 words[2].TrimRightSpaces()
1511 obj := ctx.parseMakeString(node, words[2])
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001512 typ := obj.typ()
Cole Faust9ebf6e42021-12-13 14:08:34 -08001513 if typ == starlarkTypeString && p.fname == "subst" {
Sasha Smundak94b41c72021-07-12 18:30:42 -07001514 // Optimization: if it's $(subst from, to, string), emit string.replace(from, to)
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001515 return &callExpr{
1516 object: obj,
1517 name: "replace",
Sasha Smundak35434ed2021-11-05 16:29:56 -07001518 args: []starlarkExpr{from, to},
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001519 returnType: typ,
1520 }
1521 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001522 return &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001523 name: baseName + ".mk" + p.fname,
Sasha Smundak35434ed2021-11-05 16:29:56 -07001524 args: []starlarkExpr{from, to, obj},
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001525 returnType: obj.typ(),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001526 }
1527}
1528
Cole Faust9ebf6e42021-12-13 14:08:34 -08001529type ifCallParser struct{}
1530
1531func (p *ifCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Cole Faust4eadba72021-12-07 11:54:52 -08001532 words := args.Split(",")
1533 if len(words) != 2 && len(words) != 3 {
1534 return ctx.newBadExpr(node, "if function should have 2 or 3 arguments, found "+strconv.Itoa(len(words)))
1535 }
1536 condition := ctx.parseMakeString(node, words[0])
1537 ifTrue := ctx.parseMakeString(node, words[1])
1538 var ifFalse starlarkExpr
1539 if len(words) == 3 {
1540 ifFalse = ctx.parseMakeString(node, words[2])
1541 } else {
1542 switch ifTrue.typ() {
1543 case starlarkTypeList:
1544 ifFalse = &listExpr{items: []starlarkExpr{}}
1545 case starlarkTypeInt:
1546 ifFalse = &intLiteralExpr{literal: 0}
1547 case starlarkTypeBool:
1548 ifFalse = &boolLiteralExpr{literal: false}
1549 default:
1550 ifFalse = &stringLiteralExpr{literal: ""}
1551 }
1552 }
1553 return &ifExpr{
1554 condition,
1555 ifTrue,
1556 ifFalse,
1557 }
1558}
1559
Cole Faust9ebf6e42021-12-13 14:08:34 -08001560type foreachCallPaser struct{}
1561
1562func (p *foreachCallPaser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Cole Faustb0d32ab2021-12-09 14:00:59 -08001563 words := args.Split(",")
1564 if len(words) != 3 {
1565 return ctx.newBadExpr(node, "foreach function should have 3 arguments, found "+strconv.Itoa(len(words)))
1566 }
1567 if !words[0].Const() || words[0].Empty() || !identifierFullMatchRegex.MatchString(words[0].Strings[0]) {
1568 return ctx.newBadExpr(node, "first argument to foreach function must be a simple string identifier")
1569 }
1570 loopVarName := words[0].Strings[0]
1571 list := ctx.parseMakeString(node, words[1])
1572 action := ctx.parseMakeString(node, words[2]).transform(func(expr starlarkExpr) starlarkExpr {
1573 if varRefExpr, ok := expr.(*variableRefExpr); ok && varRefExpr.ref.name() == loopVarName {
1574 return &identifierExpr{loopVarName}
1575 }
1576 return nil
1577 })
1578
1579 if list.typ() != starlarkTypeList {
1580 list = &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001581 name: baseName + ".words",
1582 returnType: starlarkTypeList,
Cole Faustb0d32ab2021-12-09 14:00:59 -08001583 args: []starlarkExpr{list},
1584 }
1585 }
1586
1587 return &foreachExpr{
1588 varName: loopVarName,
1589 list: list,
1590 action: action,
1591 }
1592}
1593
Cole Faust9ebf6e42021-12-13 14:08:34 -08001594type wordCallParser struct{}
1595
1596func (p *wordCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001597 words := args.Split(",")
1598 if len(words) != 2 {
1599 return ctx.newBadExpr(node, "word function should have 2 arguments")
1600 }
1601 var index uint64 = 0
1602 if words[0].Const() {
1603 index, _ = strconv.ParseUint(strings.TrimSpace(words[0].Strings[0]), 10, 64)
1604 }
1605 if index < 1 {
1606 return ctx.newBadExpr(node, "word index should be constant positive integer")
1607 }
1608 words[1].TrimLeftSpaces()
1609 words[1].TrimRightSpaces()
1610 array := ctx.parseMakeString(node, words[1])
1611 if xBad, ok := array.(*badExpr); ok {
1612 return xBad
1613 }
1614 if array.typ() != starlarkTypeList {
1615 array = &callExpr{object: array, name: "split", returnType: starlarkTypeList}
1616 }
Cole Faustb0d32ab2021-12-09 14:00:59 -08001617 return &indexExpr{array, &intLiteralExpr{int(index - 1)}}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001618}
1619
Cole Faust9ebf6e42021-12-13 14:08:34 -08001620type firstOrLastwordCallParser struct {
1621 isLastWord bool
1622}
1623
1624func (p *firstOrLastwordCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundak16e07732021-07-23 11:38:23 -07001625 arg := ctx.parseMakeString(node, args)
1626 if bad, ok := arg.(*badExpr); ok {
1627 return bad
1628 }
1629 index := &intLiteralExpr{0}
Cole Faust9ebf6e42021-12-13 14:08:34 -08001630 if p.isLastWord {
Sasha Smundak16e07732021-07-23 11:38:23 -07001631 if v, ok := arg.(*variableRefExpr); ok && v.ref.name() == "MAKEFILE_LIST" {
1632 return &stringLiteralExpr{ctx.script.mkFile}
1633 }
1634 index.literal = -1
1635 }
1636 if arg.typ() == starlarkTypeList {
1637 return &indexExpr{arg, index}
1638 }
1639 return &indexExpr{&callExpr{object: arg, name: "split", returnType: starlarkTypeList}, index}
1640}
1641
Cole Faustb1103e22022-01-06 15:22:05 -08001642func parseIntegerArguments(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString, expectedArgs int) ([]starlarkExpr, error) {
1643 parsedArgs := make([]starlarkExpr, 0)
1644 for _, arg := range args.Split(",") {
1645 expr := ctx.parseMakeString(node, arg)
1646 if expr.typ() == starlarkTypeList {
1647 return nil, fmt.Errorf("argument to math argument has type list, which cannot be converted to int")
1648 }
1649 if s, ok := maybeString(expr); ok {
1650 intVal, err := strconv.Atoi(strings.TrimSpace(s))
1651 if err != nil {
1652 return nil, err
1653 }
1654 expr = &intLiteralExpr{literal: intVal}
1655 } else if expr.typ() != starlarkTypeInt {
1656 expr = &callExpr{
1657 name: "int",
1658 args: []starlarkExpr{expr},
1659 returnType: starlarkTypeInt,
1660 }
1661 }
1662 parsedArgs = append(parsedArgs, expr)
1663 }
1664 if len(parsedArgs) != expectedArgs {
1665 return nil, fmt.Errorf("function should have %d arguments", expectedArgs)
1666 }
1667 return parsedArgs, nil
1668}
1669
1670type mathComparisonCallParser struct {
1671 op string
1672}
1673
1674func (p *mathComparisonCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1675 parsedArgs, err := parseIntegerArguments(ctx, node, args, 2)
1676 if err != nil {
1677 return ctx.newBadExpr(node, err.Error())
1678 }
1679 return &binaryOpExpr{
1680 left: parsedArgs[0],
1681 right: parsedArgs[1],
1682 op: p.op,
1683 returnType: starlarkTypeBool,
1684 }
1685}
1686
1687type mathMaxOrMinCallParser struct {
1688 function string
1689}
1690
1691func (p *mathMaxOrMinCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1692 parsedArgs, err := parseIntegerArguments(ctx, node, args, 2)
1693 if err != nil {
1694 return ctx.newBadExpr(node, err.Error())
1695 }
1696 return &callExpr{
1697 object: nil,
1698 name: p.function,
1699 args: parsedArgs,
1700 returnType: starlarkTypeInt,
1701 }
1702}
1703
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001704func (ctx *parseContext) parseMakeString(node mkparser.Node, mk *mkparser.MakeString) starlarkExpr {
1705 if mk.Const() {
1706 return &stringLiteralExpr{mk.Dump()}
1707 }
1708 if mkRef, ok := mk.SingleVariable(); ok {
1709 return ctx.parseReference(node, mkRef)
1710 }
1711 // If we reached here, it's neither string literal nor a simple variable,
1712 // we need a full-blown interpolation node that will generate
1713 // "a%b%c" % (X, Y) for a$(X)b$(Y)c
Cole Faustfc438682021-12-14 12:46:32 -08001714 parts := make([]starlarkExpr, len(mk.Variables)+len(mk.Strings))
1715 for i := 0; i < len(parts); i++ {
1716 if i%2 == 0 {
1717 parts[i] = &stringLiteralExpr{literal: mk.Strings[i/2]}
1718 } else {
1719 parts[i] = ctx.parseReference(node, mk.Variables[i/2].Name)
1720 if x, ok := parts[i].(*badExpr); ok {
1721 return x
1722 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001723 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001724 }
Cole Faustfc438682021-12-14 12:46:32 -08001725 return NewInterpolateExpr(parts)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001726}
1727
1728// Handles the statements whose treatment is the same in all contexts: comment,
1729// assignment, variable (which is a macro call in reality) and all constructs that
1730// do not handle in any context ('define directive and any unrecognized stuff).
Cole Faust591a1fe2021-11-08 15:37:57 -08001731func (ctx *parseContext) handleSimpleStatement(node mkparser.Node) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001732 switch x := node.(type) {
1733 case *mkparser.Comment:
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001734 ctx.maybeHandleAnnotation(x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001735 ctx.insertComment("#" + x.Comment)
1736 case *mkparser.Assignment:
1737 ctx.handleAssignment(x)
1738 case *mkparser.Variable:
1739 ctx.handleVariable(x)
1740 case *mkparser.Directive:
1741 switch x.Name {
1742 case "define":
1743 ctx.handleDefine(x)
1744 case "include", "-include":
1745 ctx.handleInclude(node, ctx.parseMakeString(node, x.Args), x.Name[0] != '-')
Cole Faust591a1fe2021-11-08 15:37:57 -08001746 case "ifeq", "ifneq", "ifdef", "ifndef":
1747 ctx.handleIfBlock(x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001748 default:
Cole Faust591a1fe2021-11-08 15:37:57 -08001749 ctx.errorf(x, "unexpected directive %s", x.Name)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001750 }
1751 default:
Sasha Smundak2afb9d72021-10-24 15:16:59 -07001752 ctx.errorf(x, "unsupported line %s", strings.ReplaceAll(x.Dump(), "\n", "\n#"))
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001753 }
Cole Faust6c934f62022-01-06 15:51:12 -08001754
1755 // Clear the includeTops after each non-comment statement
1756 // so that include annotations placed on certain statements don't apply
1757 // globally for the rest of the makefile was well.
1758 if _, wasComment := node.(*mkparser.Comment); !wasComment && len(ctx.includeTops) > 0 {
1759 ctx.includeTops = []string{}
1760 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001761}
1762
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001763// Processes annotation. An annotation is a comment that starts with #RBC# and provides
1764// a conversion hint -- say, where to look for the dynamically calculated inherit/include
1765// paths.
1766func (ctx *parseContext) maybeHandleAnnotation(cnode *mkparser.Comment) {
1767 maybeTrim := func(s, prefix string) (string, bool) {
1768 if strings.HasPrefix(s, prefix) {
1769 return strings.TrimSpace(strings.TrimPrefix(s, prefix)), true
1770 }
1771 return s, false
1772 }
1773 annotation, ok := maybeTrim(cnode.Comment, annotationCommentPrefix)
1774 if !ok {
1775 return
1776 }
1777 if p, ok := maybeTrim(annotation, "include_top"); ok {
Cole Faustf7ed5342021-12-21 14:15:12 -08001778 // Don't allow duplicate include tops, because then we will generate
1779 // invalid starlark code. (duplicate keys in the _entry dictionary)
1780 for _, top := range ctx.includeTops {
1781 if top == p {
1782 return
1783 }
1784 }
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001785 ctx.includeTops = append(ctx.includeTops, p)
1786 return
1787 }
1788 ctx.errorf(cnode, "unsupported annotation %s", cnode.Comment)
1789
1790}
1791
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001792func (ctx *parseContext) insertComment(s string) {
1793 ctx.receiver.newNode(&commentNode{strings.TrimSpace(s)})
1794}
1795
1796func (ctx *parseContext) carryAsComment(failedNode mkparser.Node) {
1797 for _, line := range strings.Split(failedNode.Dump(), "\n") {
1798 ctx.insertComment("# " + line)
1799 }
1800}
1801
1802// records that the given node failed to be converted and includes an explanatory message
1803func (ctx *parseContext) errorf(failedNode mkparser.Node, message string, args ...interface{}) {
1804 if ctx.errorLogger != nil {
Sasha Smundak422b6142021-11-11 18:31:59 -08001805 ctx.errorLogger.NewError(ctx.errorLocation(failedNode), failedNode, message, args...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001806 }
Sasha Smundak422b6142021-11-11 18:31:59 -08001807 ctx.receiver.newNode(&exprNode{ctx.newBadExpr(failedNode, message, args...)})
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001808 ctx.script.hasErrors = true
1809}
1810
1811func (ctx *parseContext) wrapBadExpr(xBad *badExpr) {
Sasha Smundak422b6142021-11-11 18:31:59 -08001812 ctx.receiver.newNode(&exprNode{xBad})
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001813}
1814
1815func (ctx *parseContext) loadedModulePath(path string) string {
1816 // During the transition to Roboleaf some of the product configuration files
1817 // will be converted and checked in while the others will be generated on the fly
1818 // and run. The runner (rbcrun application) accommodates this by allowing three
1819 // different ways to specify the loaded file location:
1820 // 1) load(":<file>",...) loads <file> from the same directory
1821 // 2) load("//path/relative/to/source/root:<file>", ...) loads <file> source tree
1822 // 3) load("/absolute/path/to/<file> absolute path
1823 // If the file being generated and the file it wants to load are in the same directory,
1824 // generate option 1.
1825 // Otherwise, if output directory is not specified, generate 2)
1826 // Finally, if output directory has been specified and the file being generated and
1827 // the file it wants to load from are in the different directories, generate 2) or 3):
1828 // * if the file being loaded exists in the source tree, generate 2)
1829 // * otherwise, generate 3)
1830 // Finally, figure out the loaded module path and name and create a node for it
1831 loadedModuleDir := filepath.Dir(path)
1832 base := filepath.Base(path)
1833 loadedModuleName := strings.TrimSuffix(base, filepath.Ext(base)) + ctx.outputSuffix
1834 if loadedModuleDir == filepath.Dir(ctx.script.mkFile) {
1835 return ":" + loadedModuleName
1836 }
1837 if ctx.outputDir == "" {
1838 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1839 }
1840 if _, err := os.Stat(filepath.Join(loadedModuleDir, loadedModuleName)); err == nil {
1841 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1842 }
1843 return filepath.Join(ctx.outputDir, loadedModuleDir, loadedModuleName)
1844}
1845
Sasha Smundak3deb9682021-07-26 18:42:25 -07001846func (ctx *parseContext) addSoongNamespace(ns string) {
1847 if _, ok := ctx.soongNamespaces[ns]; ok {
1848 return
1849 }
1850 ctx.soongNamespaces[ns] = make(map[string]bool)
1851}
1852
1853func (ctx *parseContext) hasSoongNamespace(name string) bool {
1854 _, ok := ctx.soongNamespaces[name]
1855 return ok
1856}
1857
1858func (ctx *parseContext) updateSoongNamespace(replace bool, namespaceName string, varNames []string) {
1859 ctx.addSoongNamespace(namespaceName)
1860 vars := ctx.soongNamespaces[namespaceName]
1861 if replace {
1862 vars = make(map[string]bool)
1863 ctx.soongNamespaces[namespaceName] = vars
1864 }
1865 for _, v := range varNames {
1866 vars[v] = true
1867 }
1868}
1869
1870func (ctx *parseContext) hasNamespaceVar(namespaceName string, varName string) bool {
1871 vars, ok := ctx.soongNamespaces[namespaceName]
1872 if ok {
1873 _, ok = vars[varName]
1874 }
1875 return ok
1876}
1877
Sasha Smundak422b6142021-11-11 18:31:59 -08001878func (ctx *parseContext) errorLocation(node mkparser.Node) ErrorLocation {
1879 return ErrorLocation{ctx.script.mkFile, ctx.script.nodeLocator(node.Pos())}
1880}
1881
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001882func (ss *StarlarkScript) String() string {
1883 return NewGenerateContext(ss).emit()
1884}
1885
1886func (ss *StarlarkScript) SubConfigFiles() []string {
Sasha Smundak6609ba72021-07-22 18:32:56 -07001887
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001888 var subs []string
1889 for _, src := range ss.inherited {
1890 subs = append(subs, src.originalPath)
1891 }
1892 return subs
1893}
1894
1895func (ss *StarlarkScript) HasErrors() bool {
1896 return ss.hasErrors
1897}
1898
1899// Convert reads and parses a makefile. If successful, parsed tree
1900// is returned and then can be passed to String() to get the generated
1901// Starlark file.
1902func Convert(req Request) (*StarlarkScript, error) {
1903 reader := req.Reader
1904 if reader == nil {
1905 mkContents, err := ioutil.ReadFile(req.MkFile)
1906 if err != nil {
1907 return nil, err
1908 }
1909 reader = bytes.NewBuffer(mkContents)
1910 }
1911 parser := mkparser.NewParser(req.MkFile, reader)
1912 nodes, errs := parser.Parse()
1913 if len(errs) > 0 {
1914 for _, e := range errs {
1915 fmt.Fprintln(os.Stderr, "ERROR:", e)
1916 }
1917 return nil, fmt.Errorf("bad makefile %s", req.MkFile)
1918 }
1919 starScript := &StarlarkScript{
Sasha Smundak422b6142021-11-11 18:31:59 -08001920 moduleName: moduleNameForFile(req.MkFile),
1921 mkFile: req.MkFile,
1922 topDir: req.RootDir,
1923 traceCalls: req.TraceCalls,
1924 sourceFS: req.SourceFS,
1925 makefileFinder: req.MakefileFinder,
1926 nodeLocator: func(pos mkparser.Pos) int { return parser.Unpack(pos).Line },
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001927 }
1928 ctx := newParseContext(starScript, nodes)
1929 ctx.outputSuffix = req.OutputSuffix
1930 ctx.outputDir = req.OutputDir
1931 ctx.errorLogger = req.ErrorLogger
1932 if len(req.TracedVariables) > 0 {
1933 ctx.tracedVariables = make(map[string]bool)
1934 for _, v := range req.TracedVariables {
1935 ctx.tracedVariables[v] = true
1936 }
1937 }
1938 ctx.pushReceiver(starScript)
1939 for ctx.hasNodes() && ctx.fatalError == nil {
Cole Faust591a1fe2021-11-08 15:37:57 -08001940 ctx.handleSimpleStatement(ctx.getNode())
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001941 }
1942 if ctx.fatalError != nil {
1943 return nil, ctx.fatalError
1944 }
1945 return starScript, nil
1946}
1947
Cole Faust864028a2021-12-01 13:43:17 -08001948func Launcher(mainModuleUri, inputVariablesUri, mainModuleName string) string {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001949 var buf bytes.Buffer
1950 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
Cole Faust864028a2021-12-01 13:43:17 -08001951 fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri)
Sasha Smundakd7d07ad2021-09-10 15:42:34 -07001952 fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri)
Cole Faust864028a2021-12-01 13:43:17 -08001953 fmt.Fprintf(&buf, "%s(%s(%q, init, input_variables_init))\n", cfnPrintVars, cfnMain, mainModuleName)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001954 return buf.String()
1955}
1956
Cole Faust6ed7cb42021-10-07 17:08:46 -07001957func BoardLauncher(mainModuleUri string, inputVariablesUri string) string {
1958 var buf bytes.Buffer
1959 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
1960 fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri)
1961 fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri)
1962 fmt.Fprintf(&buf, "globals, cfg, globals_base = %s(init, input_variables_init)\n", cfnBoardMain)
1963 fmt.Fprintf(&buf, "# TODO: Some product config variables need to be printed, but most are readonly so we can't just print cfg here.\n")
Cole Faust3c1868b2021-11-22 16:34:11 -08001964 fmt.Fprintf(&buf, "%s((globals, cfg, globals_base))\n", cfnPrintVars)
Cole Faust6ed7cb42021-10-07 17:08:46 -07001965 return buf.String()
1966}
1967
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001968func MakePath2ModuleName(mkPath string) string {
1969 return strings.TrimSuffix(mkPath, filepath.Ext(mkPath))
1970}