blob: 74053fefb43d03f9d8f4f86443eedbc4f6093f4c [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 Faust1cc08852022-02-28 11:12:08 -080072 "abspath": &simpleCallParser{name: baseName + ".abspath", returnType: starlarkTypeString},
73 "add-product-dex-preopt-module-config": &simpleCallParser{name: baseName + ".add_product_dex_preopt_module_config", returnType: starlarkTypeString, addHandle: true},
74 "add_soong_config_namespace": &simpleCallParser{name: baseName + ".soong_config_namespace", returnType: starlarkTypeVoid, addGlobals: true},
75 "add_soong_config_var_value": &simpleCallParser{name: baseName + ".soong_config_set", returnType: starlarkTypeVoid, addGlobals: true},
76 soongConfigAssign: &simpleCallParser{name: baseName + ".soong_config_set", returnType: starlarkTypeVoid, addGlobals: true},
77 soongConfigAppend: &simpleCallParser{name: baseName + ".soong_config_append", returnType: starlarkTypeVoid, addGlobals: true},
78 "soong_config_get": &simpleCallParser{name: baseName + ".soong_config_get", returnType: starlarkTypeString, addGlobals: true},
79 "add-to-product-copy-files-if-exists": &simpleCallParser{name: baseName + ".copy_if_exists", returnType: starlarkTypeList},
80 "addprefix": &simpleCallParser{name: baseName + ".addprefix", returnType: starlarkTypeList},
81 "addsuffix": &simpleCallParser{name: baseName + ".addsuffix", returnType: starlarkTypeList},
82 "copy-files": &simpleCallParser{name: baseName + ".copy_files", returnType: starlarkTypeList},
83 "dir": &simpleCallParser{name: baseName + ".dir", returnType: starlarkTypeList},
84 "dist-for-goals": &simpleCallParser{name: baseName + ".mkdist_for_goals", returnType: starlarkTypeVoid, addGlobals: true},
85 "enforce-product-packages-exist": &simpleCallParser{name: baseName + ".enforce_product_packages_exist", returnType: starlarkTypeVoid},
86 "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},
91 "firstword": &firstOrLastwordCallParser{isLastWord: false},
92 "foreach": &foreachCallPaser{},
93 "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{},
102 "lastword": &firstOrLastwordCallParser{isLastWord: true},
103 "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{},
110 "patsubst": &substCallParser{fname: "patsubst"},
111 "product-copy-files-by-pattern": &simpleCallParser{name: baseName + ".product_copy_files_by_pattern", returnType: starlarkTypeList},
112 "require-artifacts-in-path": &simpleCallParser{name: baseName + ".require_artifacts_in_path", returnType: starlarkTypeVoid},
113 "require-artifacts-in-path-relaxed": &simpleCallParser{name: baseName + ".require_artifacts_in_path_relaxed", returnType: starlarkTypeVoid},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800114 // TODO(asmundak): remove it once all calls are removed from configuration makefiles. see b/183161002
Cole Faust9ebf6e42021-12-13 14:08:34 -0800115 "shell": &shellCallParser{},
Cole Faust1cc08852022-02-28 11:12:08 -0800116 "strip": &simpleCallParser{name: baseName + ".mkstrip", returnType: starlarkTypeString},
Cole Faust9ebf6e42021-12-13 14:08:34 -0800117 "subst": &substCallParser{fname: "subst"},
118 "warning": &makeControlFuncParser{name: baseName + ".mkwarning"},
119 "word": &wordCallParser{},
Cole Faust1cc08852022-02-28 11:12:08 -0800120 "wildcard": &simpleCallParser{name: baseName + ".expand_wildcard", returnType: starlarkTypeList},
Cole Faust9ebf6e42021-12-13 14:08:34 -0800121}
122
123// These are functions that we don't implement conversions for, but
124// we allow seeing their definitions in the product config files.
125var ignoredDefines = map[string]bool{
126 "find-word-in-list": true, // internal macro
127 "get-vendor-board-platforms": true, // internal macro, used by is-board-platform, etc.
128 "is-android-codename": true, // unused by product config
129 "is-android-codename-in-list": true, // unused by product config
130 "is-chipset-in-board-platform": true, // unused by product config
131 "is-chipset-prefix-in-board-platform": true, // unused by product config
132 "is-not-board-platform": true, // defined but never used
133 "is-platform-sdk-version-at-least": true, // unused by product config
134 "match-prefix": true, // internal macro
135 "match-word": true, // internal macro
136 "match-word-in-list": true, // internal macro
137 "tb-modules": true, // defined in hardware/amlogic/tb_modules/tb_detect.mk, unused
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800138}
139
Cole Faustb0d32ab2021-12-09 14:00:59 -0800140var identifierFullMatchRegex = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$")
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800141
142// Conversion request parameters
143type Request struct {
Sasha Smundak422b6142021-11-11 18:31:59 -0800144 MkFile string // file to convert
145 Reader io.Reader // if set, read input from this stream instead
Sasha Smundak422b6142021-11-11 18:31:59 -0800146 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
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800373// Information about the generated Starlark script.
374type StarlarkScript struct {
Sasha Smundak422b6142021-11-11 18:31:59 -0800375 mkFile string
376 moduleName string
377 mkPos scanner.Position
378 nodes []starlarkNode
379 inherited []*moduleInfo
380 hasErrors bool
Sasha Smundak422b6142021-11-11 18:31:59 -0800381 traceCalls bool // print enter/exit each init function
382 sourceFS fs.FS
383 makefileFinder MakefileFinder
384 nodeLocator func(pos mkparser.Pos) int
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800385}
386
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800387// varAssignmentScope points to the last assignment for each variable
388// in the current block. It is used during the parsing to chain
389// the assignments to a variable together.
390type varAssignmentScope struct {
391 outer *varAssignmentScope
392 vars map[string]*assignmentNode
393}
394
395// parseContext holds the script we are generating and all the ephemeral data
396// needed during the parsing.
397type parseContext struct {
398 script *StarlarkScript
399 nodes []mkparser.Node // Makefile as parsed by mkparser
400 currentNodeIndex int // Node in it we are processing
401 ifNestLevel int
402 moduleNameCount map[string]int // count of imported modules with given basename
403 fatalError error
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800404 outputSuffix string
Sasha Smundak7d934b92021-11-10 12:20:01 -0800405 errorLogger ErrorLogger
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800406 tracedVariables map[string]bool // variables to be traced in the generated script
407 variables map[string]variable
408 varAssignments *varAssignmentScope
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800409 outputDir string
Sasha Smundak6609ba72021-07-22 18:32:56 -0700410 dependentModules map[string]*moduleInfo
Sasha Smundak3deb9682021-07-26 18:42:25 -0700411 soongNamespaces map[string]map[string]bool
Sasha Smundak6d852dd2021-09-27 20:34:39 -0700412 includeTops []string
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800413}
414
415func newParseContext(ss *StarlarkScript, nodes []mkparser.Node) *parseContext {
416 predefined := []struct{ name, value string }{
417 {"SRC_TARGET_DIR", filepath.Join("build", "make", "target")},
418 {"LOCAL_PATH", filepath.Dir(ss.mkFile)},
Cole Faust9b6111a2022-02-02 15:38:33 -0800419 {"TOPDIR", ""}, // TOPDIR is just set to an empty string in cleanbuild.mk and core.mk
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800420 // TODO(asmundak): maybe read it from build/make/core/envsetup.mk?
421 {"TARGET_COPY_OUT_SYSTEM", "system"},
422 {"TARGET_COPY_OUT_SYSTEM_OTHER", "system_other"},
423 {"TARGET_COPY_OUT_DATA", "data"},
424 {"TARGET_COPY_OUT_ASAN", filepath.Join("data", "asan")},
425 {"TARGET_COPY_OUT_OEM", "oem"},
426 {"TARGET_COPY_OUT_RAMDISK", "ramdisk"},
427 {"TARGET_COPY_OUT_DEBUG_RAMDISK", "debug_ramdisk"},
428 {"TARGET_COPY_OUT_VENDOR_DEBUG_RAMDISK", "vendor_debug_ramdisk"},
429 {"TARGET_COPY_OUT_TEST_HARNESS_RAMDISK", "test_harness_ramdisk"},
430 {"TARGET_COPY_OUT_ROOT", "root"},
431 {"TARGET_COPY_OUT_RECOVERY", "recovery"},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800432 {"TARGET_COPY_OUT_VENDOR_RAMDISK", "vendor_ramdisk"},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800433 // TODO(asmundak): to process internal config files, we need the following variables:
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800434 // TARGET_VENDOR
435 // target_base_product
436 //
437
438 // the following utility variables are set in build/make/common/core.mk:
439 {"empty", ""},
440 {"space", " "},
441 {"comma", ","},
442 {"newline", "\n"},
443 {"pound", "#"},
444 {"backslash", "\\"},
445 }
446 ctx := &parseContext{
447 script: ss,
448 nodes: nodes,
449 currentNodeIndex: 0,
450 ifNestLevel: 0,
451 moduleNameCount: make(map[string]int),
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800452 variables: make(map[string]variable),
Sasha Smundak6609ba72021-07-22 18:32:56 -0700453 dependentModules: make(map[string]*moduleInfo),
Sasha Smundak3deb9682021-07-26 18:42:25 -0700454 soongNamespaces: make(map[string]map[string]bool),
Cole Faust6c934f62022-01-06 15:51:12 -0800455 includeTops: []string{},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800456 }
457 ctx.pushVarAssignments()
458 for _, item := range predefined {
459 ctx.variables[item.name] = &predefinedVariable{
460 baseVariable: baseVariable{nam: item.name, typ: starlarkTypeString},
461 value: &stringLiteralExpr{item.value},
462 }
463 }
464
465 return ctx
466}
467
468func (ctx *parseContext) lastAssignment(name string) *assignmentNode {
469 for va := ctx.varAssignments; va != nil; va = va.outer {
470 if v, ok := va.vars[name]; ok {
471 return v
472 }
473 }
474 return nil
475}
476
477func (ctx *parseContext) setLastAssignment(name string, asgn *assignmentNode) {
478 ctx.varAssignments.vars[name] = asgn
479}
480
481func (ctx *parseContext) pushVarAssignments() {
482 va := &varAssignmentScope{
483 outer: ctx.varAssignments,
484 vars: make(map[string]*assignmentNode),
485 }
486 ctx.varAssignments = va
487}
488
489func (ctx *parseContext) popVarAssignments() {
490 ctx.varAssignments = ctx.varAssignments.outer
491}
492
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800493func (ctx *parseContext) hasNodes() bool {
494 return ctx.currentNodeIndex < len(ctx.nodes)
495}
496
497func (ctx *parseContext) getNode() mkparser.Node {
498 if !ctx.hasNodes() {
499 return nil
500 }
501 node := ctx.nodes[ctx.currentNodeIndex]
502 ctx.currentNodeIndex++
503 return node
504}
505
506func (ctx *parseContext) backNode() {
507 if ctx.currentNodeIndex <= 0 {
508 panic("Cannot back off")
509 }
510 ctx.currentNodeIndex--
511}
512
Cole Faustdd569ae2022-01-31 15:48:29 -0800513func (ctx *parseContext) handleAssignment(a *mkparser.Assignment) []starlarkNode {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800514 // Handle only simple variables
515 if !a.Name.Const() {
Cole Faustdd569ae2022-01-31 15:48:29 -0800516 return []starlarkNode{ctx.newBadNode(a, "Only simple variables are handled")}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800517 }
518 name := a.Name.Strings[0]
Sasha Smundakea3bc3a2021-11-10 13:06:42 -0800519 // The `override` directive
520 // override FOO :=
521 // is parsed as an assignment to a variable named `override FOO`.
522 // There are very few places where `override` is used, just flag it.
523 if strings.HasPrefix(name, "override ") {
Cole Faustdd569ae2022-01-31 15:48:29 -0800524 return []starlarkNode{ctx.newBadNode(a, "cannot handle override directive")}
Sasha Smundakea3bc3a2021-11-10 13:06:42 -0800525 }
526
Cole Faustc00184e2021-11-08 12:08:57 -0800527 // Soong configuration
Sasha Smundak3deb9682021-07-26 18:42:25 -0700528 if strings.HasPrefix(name, soongNsPrefix) {
Cole Faustdd569ae2022-01-31 15:48:29 -0800529 return ctx.handleSoongNsAssignment(strings.TrimPrefix(name, soongNsPrefix), a)
Sasha Smundak3deb9682021-07-26 18:42:25 -0700530 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800531 lhs := ctx.addVariable(name)
532 if lhs == nil {
Cole Faustdd569ae2022-01-31 15:48:29 -0800533 return []starlarkNode{ctx.newBadNode(a, "unknown variable %s", name)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800534 }
535 _, isTraced := ctx.tracedVariables[name]
Sasha Smundak422b6142021-11-11 18:31:59 -0800536 asgn := &assignmentNode{lhs: lhs, mkValue: a.Value, isTraced: isTraced, location: ctx.errorLocation(a)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800537 if lhs.valueType() == starlarkTypeUnknown {
538 // Try to divine variable type from the RHS
539 asgn.value = ctx.parseMakeString(a, a.Value)
540 if xBad, ok := asgn.value.(*badExpr); ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800541 return []starlarkNode{&exprNode{xBad}}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800542 }
543 inferred_type := asgn.value.typ()
544 if inferred_type != starlarkTypeUnknown {
Sasha Smundak9d011ab2021-07-09 16:00:57 -0700545 lhs.setValueType(inferred_type)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800546 }
547 }
548 if lhs.valueType() == starlarkTypeList {
Cole Faustdd569ae2022-01-31 15:48:29 -0800549 xConcat, xBad := ctx.buildConcatExpr(a)
550 if xBad != nil {
551 return []starlarkNode{&exprNode{expr: xBad}}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800552 }
553 switch len(xConcat.items) {
554 case 0:
555 asgn.value = &listExpr{}
556 case 1:
557 asgn.value = xConcat.items[0]
558 default:
559 asgn.value = xConcat
560 }
561 } else {
562 asgn.value = ctx.parseMakeString(a, a.Value)
563 if xBad, ok := asgn.value.(*badExpr); ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800564 return []starlarkNode{&exprNode{expr: xBad}}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800565 }
566 }
567
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800568 asgn.previous = ctx.lastAssignment(name)
569 ctx.setLastAssignment(name, asgn)
570 switch a.Type {
571 case "=", ":=":
572 asgn.flavor = asgnSet
573 case "+=":
574 if asgn.previous == nil && !asgn.lhs.isPreset() {
575 asgn.flavor = asgnMaybeAppend
576 } else {
577 asgn.flavor = asgnAppend
578 }
579 case "?=":
580 asgn.flavor = asgnMaybeSet
581 default:
582 panic(fmt.Errorf("unexpected assignment type %s", a.Type))
583 }
584
Cole Faustdd569ae2022-01-31 15:48:29 -0800585 return []starlarkNode{asgn}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800586}
587
Cole Faustdd569ae2022-01-31 15:48:29 -0800588func (ctx *parseContext) handleSoongNsAssignment(name string, asgn *mkparser.Assignment) []starlarkNode {
Sasha Smundak3deb9682021-07-26 18:42:25 -0700589 val := ctx.parseMakeString(asgn, asgn.Value)
590 if xBad, ok := val.(*badExpr); ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800591 return []starlarkNode{&exprNode{expr: xBad}}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700592 }
Sasha Smundak3deb9682021-07-26 18:42:25 -0700593
594 // Unfortunately, Soong namespaces can be set up by directly setting corresponding Make
595 // variables instead of via add_soong_config_namespace + add_soong_config_var_value.
596 // Try to divine the call from the assignment as follows:
597 if name == "NAMESPACES" {
598 // Upon seeng
599 // SOONG_CONFIG_NAMESPACES += foo
600 // remember that there is a namespace `foo` and act as we saw
601 // $(call add_soong_config_namespace,foo)
602 s, ok := maybeString(val)
603 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800604 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 -0700605 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800606 result := make([]starlarkNode, 0)
Sasha Smundak3deb9682021-07-26 18:42:25 -0700607 for _, ns := range strings.Fields(s) {
608 ctx.addSoongNamespace(ns)
Cole Faustdd569ae2022-01-31 15:48:29 -0800609 result = append(result, &exprNode{&callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -0800610 name: baseName + ".soong_config_namespace",
611 args: []starlarkExpr{&globalsExpr{}, &stringLiteralExpr{ns}},
Sasha Smundak3deb9682021-07-26 18:42:25 -0700612 returnType: starlarkTypeVoid,
613 }})
614 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800615 return result
Sasha Smundak3deb9682021-07-26 18:42:25 -0700616 } else {
617 // Upon seeing
618 // SOONG_CONFIG_x_y = v
619 // find a namespace called `x` and act as if we encountered
Cole Faustc00184e2021-11-08 12:08:57 -0800620 // $(call soong_config_set,x,y,v)
Sasha Smundak3deb9682021-07-26 18:42:25 -0700621 // or check that `x_y` is a namespace, and then add the RHS of this assignment as variables in
622 // it.
623 // Emit an error in the ambiguous situation (namespaces `foo_bar` with a variable `baz`
624 // and `foo` with a variable `bar_baz`.
625 namespaceName := ""
626 if ctx.hasSoongNamespace(name) {
627 namespaceName = name
628 }
629 var varName string
630 for pos, ch := range name {
631 if !(ch == '_' && ctx.hasSoongNamespace(name[0:pos])) {
632 continue
633 }
634 if namespaceName != "" {
Cole Faustdd569ae2022-01-31 15:48:29 -0800635 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 -0700636 }
637 namespaceName = name[0:pos]
638 varName = name[pos+1:]
639 }
640 if namespaceName == "" {
Cole Faustdd569ae2022-01-31 15:48:29 -0800641 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 -0700642 }
643 if varName == "" {
644 // Remember variables in this namespace
645 s, ok := maybeString(val)
646 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800647 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 -0700648 }
649 ctx.updateSoongNamespace(asgn.Type != "+=", namespaceName, strings.Fields(s))
Cole Faustdd569ae2022-01-31 15:48:29 -0800650 return []starlarkNode{}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700651 }
652
653 // Finally, handle assignment to a namespace variable
654 if !ctx.hasNamespaceVar(namespaceName, varName) {
Cole Faustdd569ae2022-01-31 15:48:29 -0800655 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 -0700656 }
Cole Faust9ebf6e42021-12-13 14:08:34 -0800657 fname := baseName + "." + soongConfigAssign
Sasha Smundak65b547e2021-09-17 15:35:41 -0700658 if asgn.Type == "+=" {
Cole Faust9ebf6e42021-12-13 14:08:34 -0800659 fname = baseName + "." + soongConfigAppend
Sasha Smundak65b547e2021-09-17 15:35:41 -0700660 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800661 return []starlarkNode{&exprNode{&callExpr{
Sasha Smundak65b547e2021-09-17 15:35:41 -0700662 name: fname,
Cole Faust9ebf6e42021-12-13 14:08:34 -0800663 args: []starlarkExpr{&globalsExpr{}, &stringLiteralExpr{namespaceName}, &stringLiteralExpr{varName}, val},
Sasha Smundak3deb9682021-07-26 18:42:25 -0700664 returnType: starlarkTypeVoid,
Cole Faustdd569ae2022-01-31 15:48:29 -0800665 }}}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700666 }
667}
668
Cole Faustdd569ae2022-01-31 15:48:29 -0800669func (ctx *parseContext) buildConcatExpr(a *mkparser.Assignment) (*concatExpr, *badExpr) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800670 xConcat := &concatExpr{}
671 var xItemList *listExpr
672 addToItemList := func(x ...starlarkExpr) {
673 if xItemList == nil {
674 xItemList = &listExpr{[]starlarkExpr{}}
675 }
676 xItemList.items = append(xItemList.items, x...)
677 }
678 finishItemList := func() {
679 if xItemList != nil {
680 xConcat.items = append(xConcat.items, xItemList)
681 xItemList = nil
682 }
683 }
684
685 items := a.Value.Words()
686 for _, item := range items {
687 // A function call in RHS is supposed to return a list, all other item
688 // expressions return individual elements.
689 switch x := ctx.parseMakeString(a, item).(type) {
690 case *badExpr:
Cole Faustdd569ae2022-01-31 15:48:29 -0800691 return nil, x
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800692 case *stringLiteralExpr:
693 addToItemList(maybeConvertToStringList(x).(*listExpr).items...)
694 default:
695 switch x.typ() {
696 case starlarkTypeList:
697 finishItemList()
698 xConcat.items = append(xConcat.items, x)
699 case starlarkTypeString:
700 finishItemList()
701 xConcat.items = append(xConcat.items, &callExpr{
702 object: x,
703 name: "split",
704 args: nil,
705 returnType: starlarkTypeList,
706 })
707 default:
708 addToItemList(x)
709 }
710 }
711 }
712 if xItemList != nil {
713 xConcat.items = append(xConcat.items, xItemList)
714 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800715 return xConcat, nil
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800716}
717
Sasha Smundak6609ba72021-07-22 18:32:56 -0700718func (ctx *parseContext) newDependentModule(path string, optional bool) *moduleInfo {
719 modulePath := ctx.loadedModulePath(path)
720 if mi, ok := ctx.dependentModules[modulePath]; ok {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700721 mi.optional = mi.optional && optional
Sasha Smundak6609ba72021-07-22 18:32:56 -0700722 return mi
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800723 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800724 moduleName := moduleNameForFile(path)
725 moduleLocalName := "_" + moduleName
726 n, found := ctx.moduleNameCount[moduleName]
727 if found {
728 moduleLocalName += fmt.Sprintf("%d", n)
729 }
730 ctx.moduleNameCount[moduleName] = n + 1
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800731 _, err := fs.Stat(ctx.script.sourceFS, path)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700732 mi := &moduleInfo{
733 path: modulePath,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800734 originalPath: path,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800735 moduleLocalName: moduleLocalName,
Sasha Smundak6609ba72021-07-22 18:32:56 -0700736 optional: optional,
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800737 missing: err != nil,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800738 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700739 ctx.dependentModules[modulePath] = mi
740 ctx.script.inherited = append(ctx.script.inherited, mi)
741 return mi
742}
743
744func (ctx *parseContext) handleSubConfig(
Cole Faustdd569ae2022-01-31 15:48:29 -0800745 v mkparser.Node, pathExpr starlarkExpr, loadAlways bool, processModule func(inheritedModule) starlarkNode) []starlarkNode {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700746
747 // In a simple case, the name of a module to inherit/include is known statically.
748 if path, ok := maybeString(pathExpr); ok {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700749 // Note that even if this directive loads a module unconditionally, a module may be
750 // absent without causing any harm if this directive is inside an if/else block.
751 moduleShouldExist := loadAlways && ctx.ifNestLevel == 0
Sasha Smundak6609ba72021-07-22 18:32:56 -0700752 if strings.Contains(path, "*") {
753 if paths, err := fs.Glob(ctx.script.sourceFS, path); err == nil {
Cole Faustdd569ae2022-01-31 15:48:29 -0800754 result := make([]starlarkNode, 0)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700755 for _, p := range paths {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700756 mi := ctx.newDependentModule(p, !moduleShouldExist)
Cole Faustdd569ae2022-01-31 15:48:29 -0800757 result = append(result, processModule(inheritedStaticModule{mi, loadAlways}))
Sasha Smundak6609ba72021-07-22 18:32:56 -0700758 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800759 return result
Sasha Smundak6609ba72021-07-22 18:32:56 -0700760 } else {
Cole Faustdd569ae2022-01-31 15:48:29 -0800761 return []starlarkNode{ctx.newBadNode(v, "cannot glob wildcard argument")}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700762 }
763 } else {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700764 mi := ctx.newDependentModule(path, !moduleShouldExist)
Cole Faustdd569ae2022-01-31 15:48:29 -0800765 return []starlarkNode{processModule(inheritedStaticModule{mi, loadAlways})}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700766 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700767 }
768
769 // If module path references variables (e.g., $(v1)/foo/$(v2)/device-config.mk), find all the paths in the
770 // source tree that may be a match and the corresponding variable values. For instance, if the source tree
771 // contains vendor1/foo/abc/dev.mk and vendor2/foo/def/dev.mk, the first one will be inherited when
772 // (v1, v2) == ('vendor1', 'abc'), and the second one when (v1, v2) == ('vendor2', 'def').
773 // We then emit the code that loads all of them, e.g.:
774 // load("//vendor1/foo/abc:dev.rbc", _dev1_init="init")
775 // load("//vendor2/foo/def/dev.rbc", _dev2_init="init")
776 // And then inherit it as follows:
777 // _e = {
778 // "vendor1/foo/abc/dev.mk": ("vendor1/foo/abc/dev", _dev1_init),
779 // "vendor2/foo/def/dev.mk": ("vendor2/foo/def/dev", _dev_init2) }.get("%s/foo/%s/dev.mk" % (v1, v2))
780 // if _e:
781 // rblf.inherit(handle, _e[0], _e[1])
782 //
783 var matchingPaths []string
784 varPath, ok := pathExpr.(*interpolateExpr)
785 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800786 return []starlarkNode{ctx.newBadNode(v, "inherit-product/include argument is too complex")}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700787 }
788
789 pathPattern := []string{varPath.chunks[0]}
790 for _, chunk := range varPath.chunks[1:] {
791 if chunk != "" {
792 pathPattern = append(pathPattern, chunk)
793 }
794 }
Cole Faust069aba62022-01-26 17:47:33 -0800795 if pathPattern[0] == "" && len(ctx.includeTops) > 0 {
Sasha Smundak6d852dd2021-09-27 20:34:39 -0700796 // If pattern starts from the top. restrict it to the directories where
797 // we know inherit-product uses dynamically calculated path.
798 for _, p := range ctx.includeTops {
799 pathPattern[0] = p
800 matchingPaths = append(matchingPaths, ctx.findMatchingPaths(pathPattern)...)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700801 }
Sasha Smundak6d852dd2021-09-27 20:34:39 -0700802 } else {
803 matchingPaths = ctx.findMatchingPaths(pathPattern)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700804 }
805 // Safeguard against $(call inherit-product,$(PRODUCT_PATH))
Sasha Smundak90be8c52021-08-03 11:06:10 -0700806 const maxMatchingFiles = 150
Sasha Smundak6609ba72021-07-22 18:32:56 -0700807 if len(matchingPaths) > maxMatchingFiles {
Cole Faustdd569ae2022-01-31 15:48:29 -0800808 return []starlarkNode{ctx.newBadNode(v, "there are >%d files matching the pattern, please rewrite it", maxMatchingFiles)}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700809 }
Cole Faust93f8d392022-03-02 13:31:30 -0800810
811 needsWarning := pathPattern[0] == "" && len(ctx.includeTops) == 0
812 res := inheritedDynamicModule{*varPath, []*moduleInfo{}, loadAlways, ctx.errorLocation(v), needsWarning}
813 for _, p := range matchingPaths {
814 // A product configuration files discovered dynamically may attempt to inherit
815 // from another one which does not exist in this source tree. Prevent load errors
816 // by always loading the dynamic files as optional.
817 res.candidateModules = append(res.candidateModules, ctx.newDependentModule(p, true))
Sasha Smundak6609ba72021-07-22 18:32:56 -0700818 }
Cole Faust93f8d392022-03-02 13:31:30 -0800819 return []starlarkNode{processModule(res)}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700820}
821
822func (ctx *parseContext) findMatchingPaths(pattern []string) []string {
Cole Faust9b6111a2022-02-02 15:38:33 -0800823 files := ctx.script.makefileFinder.Find(".")
Sasha Smundak6609ba72021-07-22 18:32:56 -0700824 if len(pattern) == 0 {
825 return files
826 }
827
828 // Create regular expression from the pattern
829 s_regexp := "^" + regexp.QuoteMeta(pattern[0])
830 for _, s := range pattern[1:] {
831 s_regexp += ".*" + regexp.QuoteMeta(s)
832 }
833 s_regexp += "$"
834 rex := regexp.MustCompile(s_regexp)
835
836 // Now match
837 var res []string
838 for _, p := range files {
839 if rex.MatchString(p) {
840 res = append(res, p)
841 }
842 }
843 return res
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800844}
845
Cole Faustdd569ae2022-01-31 15:48:29 -0800846func (ctx *parseContext) handleInheritModule(v mkparser.Node, args *mkparser.MakeString, loadAlways bool) []starlarkNode {
Cole Faust9ebf6e42021-12-13 14:08:34 -0800847 args.TrimLeftSpaces()
848 args.TrimRightSpaces()
849 pathExpr := ctx.parseMakeString(v, args)
850 if _, ok := pathExpr.(*badExpr); ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800851 return []starlarkNode{ctx.newBadNode(v, "Unable to parse argument to inherit")}
Cole Faust9ebf6e42021-12-13 14:08:34 -0800852 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800853 return ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) starlarkNode {
854 return &inheritNode{im, loadAlways}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700855 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800856}
857
Cole Faustdd569ae2022-01-31 15:48:29 -0800858func (ctx *parseContext) handleInclude(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) []starlarkNode {
859 return ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) starlarkNode {
860 return &includeNode{im, loadAlways}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700861 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800862}
863
Cole Faustdd569ae2022-01-31 15:48:29 -0800864func (ctx *parseContext) handleVariable(v *mkparser.Variable) []starlarkNode {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800865 // Handle:
866 // $(call inherit-product,...)
867 // $(call inherit-product-if-exists,...)
868 // $(info xxx)
869 // $(warning xxx)
870 // $(error xxx)
Cole Faust9ebf6e42021-12-13 14:08:34 -0800871 // $(call other-custom-functions,...)
872
873 // inherit-product(-if-exists) gets converted to a series of statements,
874 // not just a single expression like parseReference returns. So handle it
875 // separately at the beginning here.
876 if strings.HasPrefix(v.Name.Dump(), "call inherit-product,") {
877 args := v.Name.Clone()
878 args.ReplaceLiteral("call inherit-product,", "")
Cole Faustdd569ae2022-01-31 15:48:29 -0800879 return ctx.handleInheritModule(v, args, true)
Cole Faust9ebf6e42021-12-13 14:08:34 -0800880 }
881 if strings.HasPrefix(v.Name.Dump(), "call inherit-product-if-exists,") {
882 args := v.Name.Clone()
883 args.ReplaceLiteral("call inherit-product-if-exists,", "")
Cole Faustdd569ae2022-01-31 15:48:29 -0800884 return ctx.handleInheritModule(v, args, false)
Cole Faust9ebf6e42021-12-13 14:08:34 -0800885 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800886 return []starlarkNode{&exprNode{expr: ctx.parseReference(v, v.Name)}}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800887}
888
Cole Faustdd569ae2022-01-31 15:48:29 -0800889func (ctx *parseContext) maybeHandleDefine(directive *mkparser.Directive) starlarkNode {
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700890 macro_name := strings.Fields(directive.Args.Strings[0])[0]
891 // Ignore the macros that we handle
Cole Faust9ebf6e42021-12-13 14:08:34 -0800892 _, ignored := ignoredDefines[macro_name]
893 _, known := knownFunctions[macro_name]
894 if !ignored && !known {
Cole Faustdd569ae2022-01-31 15:48:29 -0800895 return ctx.newBadNode(directive, "define is not supported: %s", macro_name)
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700896 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800897 return nil
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800898}
899
Cole Faustdd569ae2022-01-31 15:48:29 -0800900func (ctx *parseContext) handleIfBlock(ifDirective *mkparser.Directive) starlarkNode {
901 ssSwitch := &switchNode{
902 ssCases: []*switchCase{ctx.processBranch(ifDirective)},
903 }
904 for ctx.hasNodes() && ctx.fatalError == nil {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800905 node := ctx.getNode()
906 switch x := node.(type) {
907 case *mkparser.Directive:
908 switch x.Name {
909 case "else", "elifdef", "elifndef", "elifeq", "elifneq":
Cole Faustdd569ae2022-01-31 15:48:29 -0800910 ssSwitch.ssCases = append(ssSwitch.ssCases, ctx.processBranch(x))
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800911 case "endif":
Cole Faustdd569ae2022-01-31 15:48:29 -0800912 return ssSwitch
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800913 default:
Cole Faustdd569ae2022-01-31 15:48:29 -0800914 return ctx.newBadNode(node, "unexpected directive %s", x.Name)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800915 }
916 default:
Cole Faustdd569ae2022-01-31 15:48:29 -0800917 return ctx.newBadNode(ifDirective, "unexpected statement")
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800918 }
919 }
920 if ctx.fatalError == nil {
921 ctx.fatalError = fmt.Errorf("no matching endif for %s", ifDirective.Dump())
922 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800923 return ctx.newBadNode(ifDirective, "no matching endif for %s", ifDirective.Dump())
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800924}
925
926// processBranch processes a single branch (if/elseif/else) until the next directive
927// on the same level.
Cole Faustdd569ae2022-01-31 15:48:29 -0800928func (ctx *parseContext) processBranch(check *mkparser.Directive) *switchCase {
929 block := &switchCase{gate: ctx.parseCondition(check)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800930 defer func() {
931 ctx.popVarAssignments()
932 ctx.ifNestLevel--
933
934 }()
935 ctx.pushVarAssignments()
936 ctx.ifNestLevel++
937
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800938 for ctx.hasNodes() {
939 node := ctx.getNode()
Cole Faust591a1fe2021-11-08 15:37:57 -0800940 if d, ok := node.(*mkparser.Directive); ok {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800941 switch d.Name {
942 case "else", "elifdef", "elifndef", "elifeq", "elifneq", "endif":
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800943 ctx.backNode()
Cole Faustdd569ae2022-01-31 15:48:29 -0800944 return block
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800945 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800946 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800947 block.nodes = append(block.nodes, ctx.handleSimpleStatement(node)...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800948 }
949 ctx.fatalError = fmt.Errorf("no matching endif for %s", check.Dump())
Cole Faustdd569ae2022-01-31 15:48:29 -0800950 return block
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800951}
952
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800953func (ctx *parseContext) parseCondition(check *mkparser.Directive) starlarkNode {
954 switch check.Name {
955 case "ifdef", "ifndef", "elifdef", "elifndef":
Cole Faust71514c02022-01-27 17:21:41 -0800956 if !check.Args.Const() {
Cole Faustdd569ae2022-01-31 15:48:29 -0800957 return ctx.newBadNode(check, "ifdef variable ref too complex: %s", check.Args.Dump())
Cole Faust71514c02022-01-27 17:21:41 -0800958 }
959 v := NewVariableRefExpr(ctx.addVariable(check.Args.Strings[0]), false)
960 if strings.HasSuffix(check.Name, "ndef") {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800961 v = &notExpr{v}
962 }
963 return &ifNode{
964 isElif: strings.HasPrefix(check.Name, "elif"),
965 expr: v,
966 }
967 case "ifeq", "ifneq", "elifeq", "elifneq":
968 return &ifNode{
969 isElif: strings.HasPrefix(check.Name, "elif"),
970 expr: ctx.parseCompare(check),
971 }
972 case "else":
973 return &elseNode{}
974 default:
975 panic(fmt.Errorf("%s: unknown directive: %s", ctx.script.mkFile, check.Dump()))
976 }
977}
978
979func (ctx *parseContext) newBadExpr(node mkparser.Node, text string, args ...interface{}) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800980 if ctx.errorLogger != nil {
Sasha Smundak422b6142021-11-11 18:31:59 -0800981 ctx.errorLogger.NewError(ctx.errorLocation(node), node, text, args...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800982 }
983 ctx.script.hasErrors = true
Cole Faustdd569ae2022-01-31 15:48:29 -0800984 return &badExpr{errorLocation: ctx.errorLocation(node), message: fmt.Sprintf(text, args...)}
985}
986
987// records that the given node failed to be converted and includes an explanatory message
988func (ctx *parseContext) newBadNode(failedNode mkparser.Node, message string, args ...interface{}) starlarkNode {
989 return &exprNode{ctx.newBadExpr(failedNode, message, args...)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800990}
991
992func (ctx *parseContext) parseCompare(cond *mkparser.Directive) starlarkExpr {
993 // Strip outer parentheses
994 mkArg := cloneMakeString(cond.Args)
995 mkArg.Strings[0] = strings.TrimLeft(mkArg.Strings[0], "( ")
996 n := len(mkArg.Strings)
997 mkArg.Strings[n-1] = strings.TrimRight(mkArg.Strings[n-1], ") ")
998 args := mkArg.Split(",")
999 // TODO(asmundak): handle the case where the arguments are in quotes and space-separated
1000 if len(args) != 2 {
1001 return ctx.newBadExpr(cond, "ifeq/ifneq len(args) != 2 %s", cond.Dump())
1002 }
1003 args[0].TrimRightSpaces()
1004 args[1].TrimLeftSpaces()
1005
1006 isEq := !strings.HasSuffix(cond.Name, "neq")
Cole Faustf8320212021-11-10 15:05:07 -08001007 xLeft := ctx.parseMakeString(cond, args[0])
1008 xRight := ctx.parseMakeString(cond, args[1])
1009 if bad, ok := xLeft.(*badExpr); ok {
1010 return bad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001011 }
Cole Faustf8320212021-11-10 15:05:07 -08001012 if bad, ok := xRight.(*badExpr); ok {
1013 return bad
1014 }
1015
1016 if expr, ok := ctx.parseCompareSpecialCases(cond, xLeft, xRight); ok {
1017 return expr
1018 }
1019
Cole Faust9ebf6e42021-12-13 14:08:34 -08001020 var stringOperand string
1021 var otherOperand starlarkExpr
1022 if s, ok := maybeString(xLeft); ok {
1023 stringOperand = s
1024 otherOperand = xRight
1025 } else if s, ok := maybeString(xRight); ok {
1026 stringOperand = s
1027 otherOperand = xLeft
1028 }
1029
1030 not := func(expr starlarkExpr) starlarkExpr {
1031 switch typedExpr := expr.(type) {
1032 case *inExpr:
1033 typedExpr.isNot = !typedExpr.isNot
1034 return typedExpr
1035 case *eqExpr:
1036 typedExpr.isEq = !typedExpr.isEq
1037 return typedExpr
Cole Faustb1103e22022-01-06 15:22:05 -08001038 case *binaryOpExpr:
1039 switch typedExpr.op {
1040 case ">":
1041 typedExpr.op = "<="
1042 return typedExpr
1043 case "<":
1044 typedExpr.op = ">="
1045 return typedExpr
1046 case ">=":
1047 typedExpr.op = "<"
1048 return typedExpr
1049 case "<=":
1050 typedExpr.op = ">"
1051 return typedExpr
1052 default:
1053 return &notExpr{expr: expr}
1054 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001055 default:
1056 return &notExpr{expr: expr}
1057 }
1058 }
1059
1060 // If we've identified one of the operands as being a string literal, check
1061 // for some special cases we can do to simplify the resulting expression.
1062 if otherOperand != nil {
1063 if stringOperand == "" {
1064 if isEq {
1065 return not(otherOperand)
1066 } else {
1067 return otherOperand
1068 }
1069 }
1070 if stringOperand == "true" && otherOperand.typ() == starlarkTypeBool {
1071 if !isEq {
1072 return not(otherOperand)
1073 } else {
1074 return otherOperand
1075 }
1076 }
Cole Faustb1103e22022-01-06 15:22:05 -08001077 if intOperand, err := strconv.Atoi(strings.TrimSpace(stringOperand)); err == nil && otherOperand.typ() == starlarkTypeInt {
1078 return &eqExpr{
1079 left: otherOperand,
1080 right: &intLiteralExpr{literal: intOperand},
1081 isEq: isEq,
1082 }
1083 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001084 }
1085
Cole Faustf8320212021-11-10 15:05:07 -08001086 return &eqExpr{left: xLeft, right: xRight, isEq: isEq}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001087}
1088
Cole Faustf8320212021-11-10 15:05:07 -08001089// Given an if statement's directive and the left/right starlarkExprs,
1090// check if the starlarkExprs are one of a few hardcoded special cases
Cole Faust9932f752022-02-08 11:56:25 -08001091// that can be converted to a simpler equality expression than simply comparing
Cole Faustf8320212021-11-10 15:05:07 -08001092// the two.
1093func (ctx *parseContext) parseCompareSpecialCases(directive *mkparser.Directive, left starlarkExpr,
1094 right starlarkExpr) (starlarkExpr, bool) {
1095 isEq := !strings.HasSuffix(directive.Name, "neq")
1096
1097 // All the special cases require a call on one side and a
1098 // string literal/variable on the other. Turn the left/right variables into
1099 // call/value variables, and return false if that's not possible.
1100 var value starlarkExpr = nil
1101 call, ok := left.(*callExpr)
1102 if ok {
1103 switch right.(type) {
1104 case *stringLiteralExpr, *variableRefExpr:
1105 value = right
1106 }
1107 } else {
1108 call, _ = right.(*callExpr)
1109 switch left.(type) {
1110 case *stringLiteralExpr, *variableRefExpr:
1111 value = left
1112 }
1113 }
1114
1115 if call == nil || value == nil {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001116 return nil, false
1117 }
Cole Faustf8320212021-11-10 15:05:07 -08001118
Cole Faustf8320212021-11-10 15:05:07 -08001119 switch call.name {
Cole Faust9932f752022-02-08 11:56:25 -08001120 case baseName + ".filter":
1121 return ctx.parseCompareFilterFuncResult(directive, call, value, isEq)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001122 case baseName + ".expand_wildcard":
Cole Faustf8320212021-11-10 15:05:07 -08001123 return ctx.parseCompareWildcardFuncResult(directive, call, value, !isEq), true
Cole Faust9ebf6e42021-12-13 14:08:34 -08001124 case baseName + ".findstring":
Cole Faustf8320212021-11-10 15:05:07 -08001125 return ctx.parseCheckFindstringFuncResult(directive, call, value, !isEq), true
Cole Faust9ebf6e42021-12-13 14:08:34 -08001126 case baseName + ".strip":
Cole Faustf8320212021-11-10 15:05:07 -08001127 return ctx.parseCompareStripFuncResult(directive, call, value, !isEq), true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001128 }
Cole Faustf8320212021-11-10 15:05:07 -08001129 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001130}
1131
1132func (ctx *parseContext) parseCompareFilterFuncResult(cond *mkparser.Directive,
Cole Faust9932f752022-02-08 11:56:25 -08001133 filterFuncCall *callExpr, xValue starlarkExpr, negate bool) (starlarkExpr, bool) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001134 // We handle:
Sasha Smundak0554d762021-07-08 18:26:12 -07001135 // * ifeq/ifneq (,$(filter v1 v2 ..., EXPR) becomes if EXPR not in/in ["v1", "v2", ...]
1136 // * ifeq/ifneq (,$(filter EXPR, v1 v2 ...) becomes if EXPR not in/in ["v1", "v2", ...]
Cole Faust9932f752022-02-08 11:56:25 -08001137 if x, ok := xValue.(*stringLiteralExpr); !ok || x.literal != "" {
1138 return nil, false
1139 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001140 xPattern := filterFuncCall.args[0]
1141 xText := filterFuncCall.args[1]
1142 var xInList *stringLiteralExpr
Sasha Smundak0554d762021-07-08 18:26:12 -07001143 var expr starlarkExpr
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001144 var ok bool
Cole Faust9932f752022-02-08 11:56:25 -08001145 if xInList, ok = xPattern.(*stringLiteralExpr); ok && !strings.ContainsRune(xInList.literal, '%') && xText.typ() == starlarkTypeList {
1146 expr = xText
1147 } else if xInList, ok = xText.(*stringLiteralExpr); ok {
1148 expr = xPattern
1149 } else {
1150 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001151 }
Cole Faust9932f752022-02-08 11:56:25 -08001152 slExpr := newStringListExpr(strings.Fields(xInList.literal))
1153 // Generate simpler code for the common cases:
1154 if expr.typ() == starlarkTypeList {
1155 if len(slExpr.items) == 1 {
1156 // Checking that a string belongs to list
1157 return &inExpr{isNot: negate, list: expr, expr: slExpr.items[0]}, true
Sasha Smundak0554d762021-07-08 18:26:12 -07001158 } else {
Cole Faust9932f752022-02-08 11:56:25 -08001159 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001160 }
Cole Faust9932f752022-02-08 11:56:25 -08001161 } else if len(slExpr.items) == 1 {
1162 return &eqExpr{left: expr, right: slExpr.items[0], isEq: !negate}, true
1163 } else {
1164 return &inExpr{isNot: negate, list: newStringListExpr(strings.Fields(xInList.literal)), expr: expr}, true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001165 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001166}
1167
1168func (ctx *parseContext) parseCompareWildcardFuncResult(directive *mkparser.Directive,
1169 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001170 if !isEmptyString(xValue) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001171 return ctx.newBadExpr(directive, "wildcard result can be compared only to empty: %s", xValue)
1172 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001173 callFunc := baseName + ".file_wildcard_exists"
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001174 if s, ok := xCall.args[0].(*stringLiteralExpr); ok && !strings.ContainsAny(s.literal, "*?{[") {
Cole Faust9ebf6e42021-12-13 14:08:34 -08001175 callFunc = baseName + ".file_exists"
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001176 }
1177 var cc starlarkExpr = &callExpr{name: callFunc, args: xCall.args, returnType: starlarkTypeBool}
1178 if !negate {
1179 cc = &notExpr{cc}
1180 }
1181 return cc
1182}
1183
1184func (ctx *parseContext) parseCheckFindstringFuncResult(directive *mkparser.Directive,
1185 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001186 if isEmptyString(xValue) {
1187 return &eqExpr{
1188 left: &callExpr{
1189 object: xCall.args[1],
1190 name: "find",
1191 args: []starlarkExpr{xCall.args[0]},
1192 returnType: starlarkTypeInt,
1193 },
1194 right: &intLiteralExpr{-1},
1195 isEq: !negate,
1196 }
Cole Faust0e9418c2021-12-13 16:33:25 -08001197 } else if s, ok := maybeString(xValue); ok {
1198 if s2, ok := maybeString(xCall.args[0]); ok && s == s2 {
1199 return &eqExpr{
1200 left: &callExpr{
1201 object: xCall.args[1],
1202 name: "find",
1203 args: []starlarkExpr{xCall.args[0]},
1204 returnType: starlarkTypeInt,
1205 },
1206 right: &intLiteralExpr{-1},
1207 isEq: negate,
1208 }
1209 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001210 }
Cole Faust0e9418c2021-12-13 16:33:25 -08001211 return ctx.newBadExpr(directive, "$(findstring) can only be compared to nothing or its first argument")
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001212}
1213
1214func (ctx *parseContext) parseCompareStripFuncResult(directive *mkparser.Directive,
1215 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
1216 if _, ok := xValue.(*stringLiteralExpr); !ok {
1217 return ctx.newBadExpr(directive, "strip result can be compared only to string: %s", xValue)
1218 }
1219 return &eqExpr{
1220 left: &callExpr{
1221 name: "strip",
1222 args: xCall.args,
1223 returnType: starlarkTypeString,
1224 },
1225 right: xValue, isEq: !negate}
1226}
1227
1228// parses $(...), returning an expression
1229func (ctx *parseContext) parseReference(node mkparser.Node, ref *mkparser.MakeString) starlarkExpr {
1230 ref.TrimLeftSpaces()
1231 ref.TrimRightSpaces()
1232 refDump := ref.Dump()
1233
1234 // Handle only the case where the first (or only) word is constant
1235 words := ref.SplitN(" ", 2)
1236 if !words[0].Const() {
1237 return ctx.newBadExpr(node, "reference is too complex: %s", refDump)
1238 }
1239
1240 // If it is a single word, it can be a simple variable
1241 // reference or a function call
Cole Faust9ebf6e42021-12-13 14:08:34 -08001242 if len(words) == 1 && !isMakeControlFunc(refDump) && refDump != "shell" {
Sasha Smundak65b547e2021-09-17 15:35:41 -07001243 if strings.HasPrefix(refDump, soongNsPrefix) {
1244 // TODO (asmundak): if we find many, maybe handle them.
Cole Faustc00184e2021-11-08 12:08:57 -08001245 return ctx.newBadExpr(node, "SOONG_CONFIG_ variables cannot be referenced, use soong_config_get instead: %s", refDump)
Sasha Smundak65b547e2021-09-17 15:35:41 -07001246 }
Cole Faustc36c9622021-12-07 15:20:45 -08001247 // Handle substitution references: https://www.gnu.org/software/make/manual/html_node/Substitution-Refs.html
1248 if strings.Contains(refDump, ":") {
1249 parts := strings.SplitN(refDump, ":", 2)
1250 substParts := strings.SplitN(parts[1], "=", 2)
1251 if len(substParts) < 2 || strings.Count(substParts[0], "%") > 1 {
1252 return ctx.newBadExpr(node, "Invalid substitution reference")
1253 }
1254 if !strings.Contains(substParts[0], "%") {
1255 if strings.Contains(substParts[1], "%") {
1256 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.")
1257 }
1258 substParts[0] = "%" + substParts[0]
1259 substParts[1] = "%" + substParts[1]
1260 }
1261 v := ctx.addVariable(parts[0])
1262 if v == nil {
1263 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1264 }
1265 return &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001266 name: baseName + ".mkpatsubst",
1267 returnType: starlarkTypeString,
Cole Faustc36c9622021-12-07 15:20:45 -08001268 args: []starlarkExpr{
1269 &stringLiteralExpr{literal: substParts[0]},
1270 &stringLiteralExpr{literal: substParts[1]},
Cole Faustfc438682021-12-14 12:46:32 -08001271 NewVariableRefExpr(v, ctx.lastAssignment(v.name()) != nil),
Cole Faustc36c9622021-12-07 15:20:45 -08001272 },
1273 }
1274 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001275 if v := ctx.addVariable(refDump); v != nil {
Cole Faustfc438682021-12-14 12:46:32 -08001276 return NewVariableRefExpr(v, ctx.lastAssignment(v.name()) != nil)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001277 }
1278 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1279 }
1280
1281 expr := &callExpr{name: words[0].Dump(), returnType: starlarkTypeUnknown}
Cole Faust9ebf6e42021-12-13 14:08:34 -08001282 args := mkparser.SimpleMakeString("", words[0].Pos())
1283 if len(words) >= 2 {
1284 args = words[1]
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001285 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001286 args.TrimLeftSpaces()
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001287 if expr.name == "call" {
1288 words = args.SplitN(",", 2)
1289 if words[0].Empty() || !words[0].Const() {
Sasha Smundakf2c9f8b2021-07-27 10:44:48 -07001290 return ctx.newBadExpr(node, "cannot handle %s", refDump)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001291 }
1292 expr.name = words[0].Dump()
1293 if len(words) < 2 {
Sasha Smundak6609ba72021-07-22 18:32:56 -07001294 args = &mkparser.MakeString{}
1295 } else {
1296 args = words[1]
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001297 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001298 }
1299 if kf, found := knownFunctions[expr.name]; found {
Cole Faust9ebf6e42021-12-13 14:08:34 -08001300 return kf.parse(ctx, node, args)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001301 } else {
1302 return ctx.newBadExpr(node, "cannot handle invoking %s", expr.name)
1303 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001304}
1305
1306type simpleCallParser struct {
1307 name string
1308 returnType starlarkType
1309 addGlobals bool
Cole Faust1cc08852022-02-28 11:12:08 -08001310 addHandle bool
Cole Faust9ebf6e42021-12-13 14:08:34 -08001311}
1312
1313func (p *simpleCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1314 expr := &callExpr{name: p.name, returnType: p.returnType}
1315 if p.addGlobals {
1316 expr.args = append(expr.args, &globalsExpr{})
1317 }
Cole Faust1cc08852022-02-28 11:12:08 -08001318 if p.addHandle {
1319 expr.args = append(expr.args, &identifierExpr{name: "handle"})
1320 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001321 for _, arg := range args.Split(",") {
1322 arg.TrimLeftSpaces()
1323 arg.TrimRightSpaces()
1324 x := ctx.parseMakeString(node, arg)
1325 if xBad, ok := x.(*badExpr); ok {
1326 return xBad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001327 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001328 expr.args = append(expr.args, x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001329 }
1330 return expr
1331}
1332
Cole Faust9ebf6e42021-12-13 14:08:34 -08001333type makeControlFuncParser struct {
1334 name string
1335}
1336
1337func (p *makeControlFuncParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1338 // Make control functions need special treatment as everything
1339 // after the name is a single text argument
1340 x := ctx.parseMakeString(node, args)
1341 if xBad, ok := x.(*badExpr); ok {
1342 return xBad
1343 }
1344 return &callExpr{
1345 name: p.name,
1346 args: []starlarkExpr{
1347 &stringLiteralExpr{ctx.script.mkFile},
1348 x,
1349 },
1350 returnType: starlarkTypeUnknown,
1351 }
1352}
1353
1354type shellCallParser struct{}
1355
1356func (p *shellCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1357 // Shell functions need special treatment as everything
1358 // after the name is a single text argument
1359 x := ctx.parseMakeString(node, args)
1360 if xBad, ok := x.(*badExpr); ok {
1361 return xBad
1362 }
1363 return &callExpr{
1364 name: baseName + ".shell",
1365 args: []starlarkExpr{x},
1366 returnType: starlarkTypeUnknown,
1367 }
1368}
1369
1370type myDirCallParser struct{}
1371
1372func (p *myDirCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1373 if !args.Empty() {
1374 return ctx.newBadExpr(node, "my-dir function cannot have any arguments passed to it.")
1375 }
1376 return &variableRefExpr{ctx.addVariable("LOCAL_PATH"), true}
1377}
1378
Cole Faust9ebf6e42021-12-13 14:08:34 -08001379type isProductInListCallParser struct{}
1380
1381func (p *isProductInListCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1382 if args.Empty() {
1383 return ctx.newBadExpr(node, "is-product-in-list requires an argument")
1384 }
1385 return &inExpr{
1386 expr: &variableRefExpr{ctx.addVariable("TARGET_PRODUCT"), true},
1387 list: maybeConvertToStringList(ctx.parseMakeString(node, args)),
1388 isNot: false,
1389 }
1390}
1391
1392type isVendorBoardPlatformCallParser struct{}
1393
1394func (p *isVendorBoardPlatformCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1395 if args.Empty() || !identifierFullMatchRegex.MatchString(args.Dump()) {
1396 return ctx.newBadExpr(node, "cannot handle non-constant argument to is-vendor-board-platform")
1397 }
1398 return &inExpr{
1399 expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
1400 list: &variableRefExpr{ctx.addVariable(args.Dump() + "_BOARD_PLATFORMS"), true},
1401 isNot: false,
1402 }
1403}
1404
1405type isVendorBoardQcomCallParser struct{}
1406
1407func (p *isVendorBoardQcomCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1408 if !args.Empty() {
1409 return ctx.newBadExpr(node, "is-vendor-board-qcom does not accept any arguments")
1410 }
1411 return &inExpr{
1412 expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
1413 list: &variableRefExpr{ctx.addVariable("QCOM_BOARD_PLATFORMS"), true},
1414 isNot: false,
1415 }
1416}
1417
1418type substCallParser struct {
1419 fname string
1420}
1421
1422func (p *substCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001423 words := args.Split(",")
1424 if len(words) != 3 {
Cole Faust9ebf6e42021-12-13 14:08:34 -08001425 return ctx.newBadExpr(node, "%s function should have 3 arguments", p.fname)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001426 }
Sasha Smundak35434ed2021-11-05 16:29:56 -07001427 from := ctx.parseMakeString(node, words[0])
1428 if xBad, ok := from.(*badExpr); ok {
1429 return xBad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001430 }
Sasha Smundak35434ed2021-11-05 16:29:56 -07001431 to := ctx.parseMakeString(node, words[1])
1432 if xBad, ok := to.(*badExpr); ok {
1433 return xBad
1434 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001435 words[2].TrimLeftSpaces()
1436 words[2].TrimRightSpaces()
1437 obj := ctx.parseMakeString(node, words[2])
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001438 typ := obj.typ()
Cole Faust9ebf6e42021-12-13 14:08:34 -08001439 if typ == starlarkTypeString && p.fname == "subst" {
Sasha Smundak94b41c72021-07-12 18:30:42 -07001440 // Optimization: if it's $(subst from, to, string), emit string.replace(from, to)
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001441 return &callExpr{
1442 object: obj,
1443 name: "replace",
Sasha Smundak35434ed2021-11-05 16:29:56 -07001444 args: []starlarkExpr{from, to},
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001445 returnType: typ,
1446 }
1447 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001448 return &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001449 name: baseName + ".mk" + p.fname,
Sasha Smundak35434ed2021-11-05 16:29:56 -07001450 args: []starlarkExpr{from, to, obj},
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001451 returnType: obj.typ(),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001452 }
1453}
1454
Cole Faust9ebf6e42021-12-13 14:08:34 -08001455type ifCallParser struct{}
1456
1457func (p *ifCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Cole Faust4eadba72021-12-07 11:54:52 -08001458 words := args.Split(",")
1459 if len(words) != 2 && len(words) != 3 {
1460 return ctx.newBadExpr(node, "if function should have 2 or 3 arguments, found "+strconv.Itoa(len(words)))
1461 }
1462 condition := ctx.parseMakeString(node, words[0])
1463 ifTrue := ctx.parseMakeString(node, words[1])
1464 var ifFalse starlarkExpr
1465 if len(words) == 3 {
1466 ifFalse = ctx.parseMakeString(node, words[2])
1467 } else {
1468 switch ifTrue.typ() {
1469 case starlarkTypeList:
1470 ifFalse = &listExpr{items: []starlarkExpr{}}
1471 case starlarkTypeInt:
1472 ifFalse = &intLiteralExpr{literal: 0}
1473 case starlarkTypeBool:
1474 ifFalse = &boolLiteralExpr{literal: false}
1475 default:
1476 ifFalse = &stringLiteralExpr{literal: ""}
1477 }
1478 }
1479 return &ifExpr{
1480 condition,
1481 ifTrue,
1482 ifFalse,
1483 }
1484}
1485
Cole Faust9ebf6e42021-12-13 14:08:34 -08001486type foreachCallPaser struct{}
1487
1488func (p *foreachCallPaser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Cole Faustb0d32ab2021-12-09 14:00:59 -08001489 words := args.Split(",")
1490 if len(words) != 3 {
1491 return ctx.newBadExpr(node, "foreach function should have 3 arguments, found "+strconv.Itoa(len(words)))
1492 }
1493 if !words[0].Const() || words[0].Empty() || !identifierFullMatchRegex.MatchString(words[0].Strings[0]) {
1494 return ctx.newBadExpr(node, "first argument to foreach function must be a simple string identifier")
1495 }
1496 loopVarName := words[0].Strings[0]
1497 list := ctx.parseMakeString(node, words[1])
1498 action := ctx.parseMakeString(node, words[2]).transform(func(expr starlarkExpr) starlarkExpr {
1499 if varRefExpr, ok := expr.(*variableRefExpr); ok && varRefExpr.ref.name() == loopVarName {
1500 return &identifierExpr{loopVarName}
1501 }
1502 return nil
1503 })
1504
1505 if list.typ() != starlarkTypeList {
1506 list = &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001507 name: baseName + ".words",
1508 returnType: starlarkTypeList,
Cole Faustb0d32ab2021-12-09 14:00:59 -08001509 args: []starlarkExpr{list},
1510 }
1511 }
1512
1513 return &foreachExpr{
1514 varName: loopVarName,
1515 list: list,
1516 action: action,
1517 }
1518}
1519
Cole Faust9ebf6e42021-12-13 14:08:34 -08001520type wordCallParser struct{}
1521
1522func (p *wordCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001523 words := args.Split(",")
1524 if len(words) != 2 {
1525 return ctx.newBadExpr(node, "word function should have 2 arguments")
1526 }
1527 var index uint64 = 0
1528 if words[0].Const() {
1529 index, _ = strconv.ParseUint(strings.TrimSpace(words[0].Strings[0]), 10, 64)
1530 }
1531 if index < 1 {
1532 return ctx.newBadExpr(node, "word index should be constant positive integer")
1533 }
1534 words[1].TrimLeftSpaces()
1535 words[1].TrimRightSpaces()
1536 array := ctx.parseMakeString(node, words[1])
1537 if xBad, ok := array.(*badExpr); ok {
1538 return xBad
1539 }
1540 if array.typ() != starlarkTypeList {
1541 array = &callExpr{object: array, name: "split", returnType: starlarkTypeList}
1542 }
Cole Faustb0d32ab2021-12-09 14:00:59 -08001543 return &indexExpr{array, &intLiteralExpr{int(index - 1)}}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001544}
1545
Cole Faust9ebf6e42021-12-13 14:08:34 -08001546type firstOrLastwordCallParser struct {
1547 isLastWord bool
1548}
1549
1550func (p *firstOrLastwordCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundak16e07732021-07-23 11:38:23 -07001551 arg := ctx.parseMakeString(node, args)
1552 if bad, ok := arg.(*badExpr); ok {
1553 return bad
1554 }
1555 index := &intLiteralExpr{0}
Cole Faust9ebf6e42021-12-13 14:08:34 -08001556 if p.isLastWord {
Sasha Smundak16e07732021-07-23 11:38:23 -07001557 if v, ok := arg.(*variableRefExpr); ok && v.ref.name() == "MAKEFILE_LIST" {
1558 return &stringLiteralExpr{ctx.script.mkFile}
1559 }
1560 index.literal = -1
1561 }
1562 if arg.typ() == starlarkTypeList {
1563 return &indexExpr{arg, index}
1564 }
1565 return &indexExpr{&callExpr{object: arg, name: "split", returnType: starlarkTypeList}, index}
1566}
1567
Cole Faustb1103e22022-01-06 15:22:05 -08001568func parseIntegerArguments(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString, expectedArgs int) ([]starlarkExpr, error) {
1569 parsedArgs := make([]starlarkExpr, 0)
1570 for _, arg := range args.Split(",") {
1571 expr := ctx.parseMakeString(node, arg)
1572 if expr.typ() == starlarkTypeList {
1573 return nil, fmt.Errorf("argument to math argument has type list, which cannot be converted to int")
1574 }
1575 if s, ok := maybeString(expr); ok {
1576 intVal, err := strconv.Atoi(strings.TrimSpace(s))
1577 if err != nil {
1578 return nil, err
1579 }
1580 expr = &intLiteralExpr{literal: intVal}
1581 } else if expr.typ() != starlarkTypeInt {
1582 expr = &callExpr{
1583 name: "int",
1584 args: []starlarkExpr{expr},
1585 returnType: starlarkTypeInt,
1586 }
1587 }
1588 parsedArgs = append(parsedArgs, expr)
1589 }
1590 if len(parsedArgs) != expectedArgs {
1591 return nil, fmt.Errorf("function should have %d arguments", expectedArgs)
1592 }
1593 return parsedArgs, nil
1594}
1595
1596type mathComparisonCallParser struct {
1597 op string
1598}
1599
1600func (p *mathComparisonCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1601 parsedArgs, err := parseIntegerArguments(ctx, node, args, 2)
1602 if err != nil {
1603 return ctx.newBadExpr(node, err.Error())
1604 }
1605 return &binaryOpExpr{
1606 left: parsedArgs[0],
1607 right: parsedArgs[1],
1608 op: p.op,
1609 returnType: starlarkTypeBool,
1610 }
1611}
1612
1613type mathMaxOrMinCallParser struct {
1614 function string
1615}
1616
1617func (p *mathMaxOrMinCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1618 parsedArgs, err := parseIntegerArguments(ctx, node, args, 2)
1619 if err != nil {
1620 return ctx.newBadExpr(node, err.Error())
1621 }
1622 return &callExpr{
1623 object: nil,
1624 name: p.function,
1625 args: parsedArgs,
1626 returnType: starlarkTypeInt,
1627 }
1628}
1629
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001630func (ctx *parseContext) parseMakeString(node mkparser.Node, mk *mkparser.MakeString) starlarkExpr {
1631 if mk.Const() {
1632 return &stringLiteralExpr{mk.Dump()}
1633 }
1634 if mkRef, ok := mk.SingleVariable(); ok {
1635 return ctx.parseReference(node, mkRef)
1636 }
1637 // If we reached here, it's neither string literal nor a simple variable,
1638 // we need a full-blown interpolation node that will generate
1639 // "a%b%c" % (X, Y) for a$(X)b$(Y)c
Cole Faustfc438682021-12-14 12:46:32 -08001640 parts := make([]starlarkExpr, len(mk.Variables)+len(mk.Strings))
1641 for i := 0; i < len(parts); i++ {
1642 if i%2 == 0 {
1643 parts[i] = &stringLiteralExpr{literal: mk.Strings[i/2]}
1644 } else {
1645 parts[i] = ctx.parseReference(node, mk.Variables[i/2].Name)
1646 if x, ok := parts[i].(*badExpr); ok {
1647 return x
1648 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001649 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001650 }
Cole Faustfc438682021-12-14 12:46:32 -08001651 return NewInterpolateExpr(parts)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001652}
1653
1654// Handles the statements whose treatment is the same in all contexts: comment,
1655// assignment, variable (which is a macro call in reality) and all constructs that
1656// do not handle in any context ('define directive and any unrecognized stuff).
Cole Faustdd569ae2022-01-31 15:48:29 -08001657func (ctx *parseContext) handleSimpleStatement(node mkparser.Node) []starlarkNode {
1658 var result []starlarkNode
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001659 switch x := node.(type) {
1660 case *mkparser.Comment:
Cole Faustdd569ae2022-01-31 15:48:29 -08001661 if n, handled := ctx.maybeHandleAnnotation(x); handled && n != nil {
1662 result = []starlarkNode{n}
1663 } else if !handled {
1664 result = []starlarkNode{&commentNode{strings.TrimSpace("#" + x.Comment)}}
Cole Faust7940c6a2022-01-31 15:54:05 -08001665 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001666 case *mkparser.Assignment:
Cole Faustdd569ae2022-01-31 15:48:29 -08001667 result = ctx.handleAssignment(x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001668 case *mkparser.Variable:
Cole Faustdd569ae2022-01-31 15:48:29 -08001669 result = ctx.handleVariable(x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001670 case *mkparser.Directive:
1671 switch x.Name {
1672 case "define":
Cole Faustdd569ae2022-01-31 15:48:29 -08001673 if res := ctx.maybeHandleDefine(x); res != nil {
1674 result = []starlarkNode{res}
1675 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001676 case "include", "-include":
Cole Faustdd569ae2022-01-31 15:48:29 -08001677 result = ctx.handleInclude(node, ctx.parseMakeString(node, x.Args), x.Name[0] != '-')
Cole Faust591a1fe2021-11-08 15:37:57 -08001678 case "ifeq", "ifneq", "ifdef", "ifndef":
Cole Faustdd569ae2022-01-31 15:48:29 -08001679 result = []starlarkNode{ctx.handleIfBlock(x)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001680 default:
Cole Faustdd569ae2022-01-31 15:48:29 -08001681 result = []starlarkNode{ctx.newBadNode(x, "unexpected directive %s", x.Name)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001682 }
1683 default:
Cole Faustdd569ae2022-01-31 15:48:29 -08001684 result = []starlarkNode{ctx.newBadNode(x, "unsupported line %s", strings.ReplaceAll(x.Dump(), "\n", "\n#"))}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001685 }
Cole Faust6c934f62022-01-06 15:51:12 -08001686
1687 // Clear the includeTops after each non-comment statement
1688 // so that include annotations placed on certain statements don't apply
1689 // globally for the rest of the makefile was well.
1690 if _, wasComment := node.(*mkparser.Comment); !wasComment && len(ctx.includeTops) > 0 {
1691 ctx.includeTops = []string{}
1692 }
Cole Faustdd569ae2022-01-31 15:48:29 -08001693
1694 if result == nil {
1695 result = []starlarkNode{}
1696 }
1697 return result
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001698}
1699
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001700// Processes annotation. An annotation is a comment that starts with #RBC# and provides
1701// a conversion hint -- say, where to look for the dynamically calculated inherit/include
Cole Faust7940c6a2022-01-31 15:54:05 -08001702// paths. Returns true if the comment was a successfully-handled annotation.
Cole Faustdd569ae2022-01-31 15:48:29 -08001703func (ctx *parseContext) maybeHandleAnnotation(cnode *mkparser.Comment) (starlarkNode, bool) {
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001704 maybeTrim := func(s, prefix string) (string, bool) {
1705 if strings.HasPrefix(s, prefix) {
1706 return strings.TrimSpace(strings.TrimPrefix(s, prefix)), true
1707 }
1708 return s, false
1709 }
1710 annotation, ok := maybeTrim(cnode.Comment, annotationCommentPrefix)
1711 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -08001712 return nil, false
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001713 }
1714 if p, ok := maybeTrim(annotation, "include_top"); ok {
Cole Faustf7ed5342021-12-21 14:15:12 -08001715 // Don't allow duplicate include tops, because then we will generate
1716 // invalid starlark code. (duplicate keys in the _entry dictionary)
1717 for _, top := range ctx.includeTops {
1718 if top == p {
Cole Faustdd569ae2022-01-31 15:48:29 -08001719 return nil, true
Cole Faustf7ed5342021-12-21 14:15:12 -08001720 }
1721 }
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001722 ctx.includeTops = append(ctx.includeTops, p)
Cole Faustdd569ae2022-01-31 15:48:29 -08001723 return nil, true
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001724 }
Cole Faustdd569ae2022-01-31 15:48:29 -08001725 return ctx.newBadNode(cnode, "unsupported annotation %s", cnode.Comment), true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001726}
1727
1728func (ctx *parseContext) loadedModulePath(path string) string {
1729 // During the transition to Roboleaf some of the product configuration files
1730 // will be converted and checked in while the others will be generated on the fly
1731 // and run. The runner (rbcrun application) accommodates this by allowing three
1732 // different ways to specify the loaded file location:
1733 // 1) load(":<file>",...) loads <file> from the same directory
1734 // 2) load("//path/relative/to/source/root:<file>", ...) loads <file> source tree
1735 // 3) load("/absolute/path/to/<file> absolute path
1736 // If the file being generated and the file it wants to load are in the same directory,
1737 // generate option 1.
1738 // Otherwise, if output directory is not specified, generate 2)
1739 // Finally, if output directory has been specified and the file being generated and
1740 // the file it wants to load from are in the different directories, generate 2) or 3):
1741 // * if the file being loaded exists in the source tree, generate 2)
1742 // * otherwise, generate 3)
1743 // Finally, figure out the loaded module path and name and create a node for it
1744 loadedModuleDir := filepath.Dir(path)
1745 base := filepath.Base(path)
1746 loadedModuleName := strings.TrimSuffix(base, filepath.Ext(base)) + ctx.outputSuffix
1747 if loadedModuleDir == filepath.Dir(ctx.script.mkFile) {
1748 return ":" + loadedModuleName
1749 }
1750 if ctx.outputDir == "" {
1751 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1752 }
1753 if _, err := os.Stat(filepath.Join(loadedModuleDir, loadedModuleName)); err == nil {
1754 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1755 }
1756 return filepath.Join(ctx.outputDir, loadedModuleDir, loadedModuleName)
1757}
1758
Sasha Smundak3deb9682021-07-26 18:42:25 -07001759func (ctx *parseContext) addSoongNamespace(ns string) {
1760 if _, ok := ctx.soongNamespaces[ns]; ok {
1761 return
1762 }
1763 ctx.soongNamespaces[ns] = make(map[string]bool)
1764}
1765
1766func (ctx *parseContext) hasSoongNamespace(name string) bool {
1767 _, ok := ctx.soongNamespaces[name]
1768 return ok
1769}
1770
1771func (ctx *parseContext) updateSoongNamespace(replace bool, namespaceName string, varNames []string) {
1772 ctx.addSoongNamespace(namespaceName)
1773 vars := ctx.soongNamespaces[namespaceName]
1774 if replace {
1775 vars = make(map[string]bool)
1776 ctx.soongNamespaces[namespaceName] = vars
1777 }
1778 for _, v := range varNames {
1779 vars[v] = true
1780 }
1781}
1782
1783func (ctx *parseContext) hasNamespaceVar(namespaceName string, varName string) bool {
1784 vars, ok := ctx.soongNamespaces[namespaceName]
1785 if ok {
1786 _, ok = vars[varName]
1787 }
1788 return ok
1789}
1790
Sasha Smundak422b6142021-11-11 18:31:59 -08001791func (ctx *parseContext) errorLocation(node mkparser.Node) ErrorLocation {
1792 return ErrorLocation{ctx.script.mkFile, ctx.script.nodeLocator(node.Pos())}
1793}
1794
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001795func (ss *StarlarkScript) String() string {
1796 return NewGenerateContext(ss).emit()
1797}
1798
1799func (ss *StarlarkScript) SubConfigFiles() []string {
Sasha Smundak6609ba72021-07-22 18:32:56 -07001800
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001801 var subs []string
1802 for _, src := range ss.inherited {
1803 subs = append(subs, src.originalPath)
1804 }
1805 return subs
1806}
1807
1808func (ss *StarlarkScript) HasErrors() bool {
1809 return ss.hasErrors
1810}
1811
1812// Convert reads and parses a makefile. If successful, parsed tree
1813// is returned and then can be passed to String() to get the generated
1814// Starlark file.
1815func Convert(req Request) (*StarlarkScript, error) {
1816 reader := req.Reader
1817 if reader == nil {
1818 mkContents, err := ioutil.ReadFile(req.MkFile)
1819 if err != nil {
1820 return nil, err
1821 }
1822 reader = bytes.NewBuffer(mkContents)
1823 }
1824 parser := mkparser.NewParser(req.MkFile, reader)
1825 nodes, errs := parser.Parse()
1826 if len(errs) > 0 {
1827 for _, e := range errs {
1828 fmt.Fprintln(os.Stderr, "ERROR:", e)
1829 }
1830 return nil, fmt.Errorf("bad makefile %s", req.MkFile)
1831 }
1832 starScript := &StarlarkScript{
Sasha Smundak422b6142021-11-11 18:31:59 -08001833 moduleName: moduleNameForFile(req.MkFile),
1834 mkFile: req.MkFile,
Sasha Smundak422b6142021-11-11 18:31:59 -08001835 traceCalls: req.TraceCalls,
1836 sourceFS: req.SourceFS,
1837 makefileFinder: req.MakefileFinder,
1838 nodeLocator: func(pos mkparser.Pos) int { return parser.Unpack(pos).Line },
Cole Faustdd569ae2022-01-31 15:48:29 -08001839 nodes: make([]starlarkNode, 0),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001840 }
1841 ctx := newParseContext(starScript, nodes)
1842 ctx.outputSuffix = req.OutputSuffix
1843 ctx.outputDir = req.OutputDir
1844 ctx.errorLogger = req.ErrorLogger
1845 if len(req.TracedVariables) > 0 {
1846 ctx.tracedVariables = make(map[string]bool)
1847 for _, v := range req.TracedVariables {
1848 ctx.tracedVariables[v] = true
1849 }
1850 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001851 for ctx.hasNodes() && ctx.fatalError == nil {
Cole Faustdd569ae2022-01-31 15:48:29 -08001852 starScript.nodes = append(starScript.nodes, ctx.handleSimpleStatement(ctx.getNode())...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001853 }
1854 if ctx.fatalError != nil {
1855 return nil, ctx.fatalError
1856 }
1857 return starScript, nil
1858}
1859
Cole Faust864028a2021-12-01 13:43:17 -08001860func Launcher(mainModuleUri, inputVariablesUri, mainModuleName string) string {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001861 var buf bytes.Buffer
1862 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
Cole Faust864028a2021-12-01 13:43:17 -08001863 fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri)
Sasha Smundakd7d07ad2021-09-10 15:42:34 -07001864 fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri)
Cole Faust864028a2021-12-01 13:43:17 -08001865 fmt.Fprintf(&buf, "%s(%s(%q, init, input_variables_init))\n", cfnPrintVars, cfnMain, mainModuleName)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001866 return buf.String()
1867}
1868
Cole Faust6ed7cb42021-10-07 17:08:46 -07001869func BoardLauncher(mainModuleUri string, inputVariablesUri string) string {
1870 var buf bytes.Buffer
1871 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
1872 fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri)
1873 fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri)
Cole Fausta0604662022-02-28 11:53:58 -08001874 fmt.Fprintf(&buf, "%s(%s(init, input_variables_init))\n", cfnPrintVars, cfnBoardMain)
Cole Faust6ed7cb42021-10-07 17:08:46 -07001875 return buf.String()
1876}
1877
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001878func MakePath2ModuleName(mkPath string) string {
1879 return strings.TrimSuffix(mkPath, filepath.Ext(mkPath))
1880}