blob: 57fc83fd1723f21faa3875e47b0df44684d9172f [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"
Cole Faust62e05112022-04-05 17:56:11 -070035 "sort"
Sasha Smundakb051c4e2020-11-05 20:45:07 -080036 "strconv"
37 "strings"
38 "text/scanner"
39
40 mkparser "android/soong/androidmk/parser"
41)
42
43const (
Sasha Smundak6d852dd2021-09-27 20:34:39 -070044 annotationCommentPrefix = "RBC#"
45 baseUri = "//build/make/core:product_config.rbc"
Sasha Smundakb051c4e2020-11-05 20:45:07 -080046 // The name of the struct exported by the product_config.rbc
47 // that contains the functions and variables available to
48 // product configuration Starlark files.
49 baseName = "rblf"
50
Sasha Smundak65b547e2021-09-17 15:35:41 -070051 soongNsPrefix = "SOONG_CONFIG_"
52
Sasha Smundakb051c4e2020-11-05 20:45:07 -080053 // And here are the functions and variables:
Cole Fauste2a37982022-03-09 16:00:17 -080054 cfnGetCfg = baseName + ".cfg"
55 cfnMain = baseName + ".product_configuration"
56 cfnBoardMain = baseName + ".board_configuration"
57 cfnPrintVars = baseName + ".printvars"
58 cfnInherit = baseName + ".inherit"
59 cfnSetListDefault = baseName + ".setdefault"
Sasha Smundakb051c4e2020-11-05 20:45:07 -080060)
61
62const (
Cole Faust9ebf6e42021-12-13 14:08:34 -080063 soongConfigAppend = "soong_config_append"
64 soongConfigAssign = "soong_config_set"
Sasha Smundakb051c4e2020-11-05 20:45:07 -080065)
66
Cole Faust9ebf6e42021-12-13 14:08:34 -080067var knownFunctions = map[string]interface {
68 parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr
Sasha Smundakb051c4e2020-11-05 20:45:07 -080069}{
Cole Faust1cc08852022-02-28 11:12:08 -080070 "abspath": &simpleCallParser{name: baseName + ".abspath", returnType: starlarkTypeString},
71 "add-product-dex-preopt-module-config": &simpleCallParser{name: baseName + ".add_product_dex_preopt_module_config", returnType: starlarkTypeString, addHandle: true},
72 "add_soong_config_namespace": &simpleCallParser{name: baseName + ".soong_config_namespace", returnType: starlarkTypeVoid, addGlobals: true},
73 "add_soong_config_var_value": &simpleCallParser{name: baseName + ".soong_config_set", returnType: starlarkTypeVoid, addGlobals: true},
74 soongConfigAssign: &simpleCallParser{name: baseName + ".soong_config_set", returnType: starlarkTypeVoid, addGlobals: true},
75 soongConfigAppend: &simpleCallParser{name: baseName + ".soong_config_append", returnType: starlarkTypeVoid, addGlobals: true},
76 "soong_config_get": &simpleCallParser{name: baseName + ".soong_config_get", returnType: starlarkTypeString, addGlobals: true},
77 "add-to-product-copy-files-if-exists": &simpleCallParser{name: baseName + ".copy_if_exists", returnType: starlarkTypeList},
78 "addprefix": &simpleCallParser{name: baseName + ".addprefix", returnType: starlarkTypeList},
79 "addsuffix": &simpleCallParser{name: baseName + ".addsuffix", returnType: starlarkTypeList},
80 "copy-files": &simpleCallParser{name: baseName + ".copy_files", returnType: starlarkTypeList},
Cole Faust0e2b2562022-04-01 11:46:50 -070081 "dir": &simpleCallParser{name: baseName + ".dir", returnType: starlarkTypeString},
Cole Faust1cc08852022-02-28 11:12:08 -080082 "dist-for-goals": &simpleCallParser{name: baseName + ".mkdist_for_goals", returnType: starlarkTypeVoid, addGlobals: true},
Cole Faust6c41b8a2022-04-13 13:53:48 -070083 "enforce-product-packages-exist": &simpleCallParser{name: baseName + ".enforce_product_packages_exist", returnType: starlarkTypeVoid, addHandle: true},
Cole Faust1cc08852022-02-28 11:12:08 -080084 "error": &makeControlFuncParser{name: baseName + ".mkerror"},
85 "findstring": &simpleCallParser{name: baseName + ".findstring", returnType: starlarkTypeInt},
86 "find-copy-subdir-files": &simpleCallParser{name: baseName + ".find_and_copy", returnType: starlarkTypeList},
87 "filter": &simpleCallParser{name: baseName + ".filter", returnType: starlarkTypeList},
88 "filter-out": &simpleCallParser{name: baseName + ".filter_out", returnType: starlarkTypeList},
89 "firstword": &firstOrLastwordCallParser{isLastWord: false},
Cole Faustf035d402022-03-28 14:02:50 -070090 "foreach": &foreachCallParser{},
Cole Faust1cc08852022-02-28 11:12:08 -080091 "if": &ifCallParser{},
92 "info": &makeControlFuncParser{name: baseName + ".mkinfo"},
93 "is-board-platform": &simpleCallParser{name: baseName + ".board_platform_is", returnType: starlarkTypeBool, addGlobals: true},
94 "is-board-platform2": &simpleCallParser{name: baseName + ".board_platform_is", returnType: starlarkTypeBool, addGlobals: true},
95 "is-board-platform-in-list": &simpleCallParser{name: baseName + ".board_platform_in", returnType: starlarkTypeBool, addGlobals: true},
96 "is-board-platform-in-list2": &simpleCallParser{name: baseName + ".board_platform_in", returnType: starlarkTypeBool, addGlobals: true},
97 "is-product-in-list": &isProductInListCallParser{},
98 "is-vendor-board-platform": &isVendorBoardPlatformCallParser{},
99 "is-vendor-board-qcom": &isVendorBoardQcomCallParser{},
100 "lastword": &firstOrLastwordCallParser{isLastWord: true},
101 "notdir": &simpleCallParser{name: baseName + ".notdir", returnType: starlarkTypeString},
102 "math_max": &mathMaxOrMinCallParser{function: "max"},
103 "math_min": &mathMaxOrMinCallParser{function: "min"},
104 "math_gt_or_eq": &mathComparisonCallParser{op: ">="},
105 "math_gt": &mathComparisonCallParser{op: ">"},
106 "math_lt": &mathComparisonCallParser{op: "<"},
107 "my-dir": &myDirCallParser{},
108 "patsubst": &substCallParser{fname: "patsubst"},
109 "product-copy-files-by-pattern": &simpleCallParser{name: baseName + ".product_copy_files_by_pattern", returnType: starlarkTypeList},
Cole Faustea9db582022-03-21 17:50:05 -0700110 "require-artifacts-in-path": &simpleCallParser{name: baseName + ".require_artifacts_in_path", returnType: starlarkTypeVoid, addHandle: true},
111 "require-artifacts-in-path-relaxed": &simpleCallParser{name: baseName + ".require_artifacts_in_path_relaxed", returnType: starlarkTypeVoid, addHandle: true},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800112 // TODO(asmundak): remove it once all calls are removed from configuration makefiles. see b/183161002
Cole Faust9ebf6e42021-12-13 14:08:34 -0800113 "shell": &shellCallParser{},
Cole Faust95b95cb2022-04-05 16:37:39 -0700114 "sort": &simpleCallParser{name: baseName + ".mksort", returnType: starlarkTypeList},
Cole Faust1cc08852022-02-28 11:12:08 -0800115 "strip": &simpleCallParser{name: baseName + ".mkstrip", returnType: starlarkTypeString},
Cole Faust9ebf6e42021-12-13 14:08:34 -0800116 "subst": &substCallParser{fname: "subst"},
117 "warning": &makeControlFuncParser{name: baseName + ".mkwarning"},
118 "word": &wordCallParser{},
Cole Faust1cc08852022-02-28 11:12:08 -0800119 "wildcard": &simpleCallParser{name: baseName + ".expand_wildcard", returnType: starlarkTypeList},
Cole Faust9ebf6e42021-12-13 14:08:34 -0800120}
121
Cole Faustf035d402022-03-28 14:02:50 -0700122// The same as knownFunctions, but returns a []starlarkNode instead of a starlarkExpr
123var knownNodeFunctions = map[string]interface {
124 parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode
125}{
126 "eval": &evalNodeParser{},
127 "if": &ifCallNodeParser{},
128 "inherit-product": &inheritProductCallParser{loadAlways: true},
129 "inherit-product-if-exists": &inheritProductCallParser{loadAlways: false},
130 "foreach": &foreachCallNodeParser{},
131}
132
Cole Faust9ebf6e42021-12-13 14:08:34 -0800133// These are functions that we don't implement conversions for, but
134// we allow seeing their definitions in the product config files.
135var ignoredDefines = map[string]bool{
136 "find-word-in-list": true, // internal macro
137 "get-vendor-board-platforms": true, // internal macro, used by is-board-platform, etc.
138 "is-android-codename": true, // unused by product config
139 "is-android-codename-in-list": true, // unused by product config
140 "is-chipset-in-board-platform": true, // unused by product config
141 "is-chipset-prefix-in-board-platform": true, // unused by product config
142 "is-not-board-platform": true, // defined but never used
143 "is-platform-sdk-version-at-least": true, // unused by product config
144 "match-prefix": true, // internal macro
145 "match-word": true, // internal macro
146 "match-word-in-list": true, // internal macro
147 "tb-modules": true, // defined in hardware/amlogic/tb_modules/tb_detect.mk, unused
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800148}
149
Cole Faustb0d32ab2021-12-09 14:00:59 -0800150var identifierFullMatchRegex = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$")
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800151
152// Conversion request parameters
153type Request struct {
Sasha Smundak422b6142021-11-11 18:31:59 -0800154 MkFile string // file to convert
155 Reader io.Reader // if set, read input from this stream instead
Sasha Smundak422b6142021-11-11 18:31:59 -0800156 OutputSuffix string // generated Starlark files suffix
157 OutputDir string // if set, root of the output hierarchy
158 ErrorLogger ErrorLogger
159 TracedVariables []string // trace assignment to these variables
160 TraceCalls bool
161 SourceFS fs.FS
162 MakefileFinder MakefileFinder
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800163}
164
Sasha Smundak7d934b92021-11-10 12:20:01 -0800165// ErrorLogger prints errors and gathers error statistics.
166// Its NewError function is called on every error encountered during the conversion.
167type ErrorLogger interface {
Sasha Smundak422b6142021-11-11 18:31:59 -0800168 NewError(el ErrorLocation, node mkparser.Node, text string, args ...interface{})
169}
170
171type ErrorLocation struct {
172 MkFile string
173 MkLine int
174}
175
176func (el ErrorLocation) String() string {
177 return fmt.Sprintf("%s:%d", el.MkFile, el.MkLine)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800178}
179
180// Derives module name for a given file. It is base name
181// (file name without suffix), with some characters replaced to make it a Starlark identifier
182func moduleNameForFile(mkFile string) string {
183 base := strings.TrimSuffix(filepath.Base(mkFile), filepath.Ext(mkFile))
184 // TODO(asmundak): what else can be in the product file names?
Sasha Smundak6609ba72021-07-22 18:32:56 -0700185 return strings.NewReplacer("-", "_", ".", "_").Replace(base)
186
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800187}
188
189func cloneMakeString(mkString *mkparser.MakeString) *mkparser.MakeString {
190 r := &mkparser.MakeString{StringPos: mkString.StringPos}
191 r.Strings = append(r.Strings, mkString.Strings...)
192 r.Variables = append(r.Variables, mkString.Variables...)
193 return r
194}
195
196func isMakeControlFunc(s string) bool {
197 return s == "error" || s == "warning" || s == "info"
198}
199
Cole Faustf0632662022-04-07 13:59:24 -0700200// varAssignmentScope points to the last assignment for each variable
201// in the current block. It is used during the parsing to chain
202// the assignments to a variable together.
203type varAssignmentScope struct {
204 outer *varAssignmentScope
205 vars map[string]bool
206}
207
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800208// Starlark output generation context
209type generationContext struct {
Cole Faustf0632662022-04-07 13:59:24 -0700210 buf strings.Builder
211 starScript *StarlarkScript
212 indentLevel int
213 inAssignment bool
214 tracedCount int
215 varAssignments *varAssignmentScope
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800216}
217
218func NewGenerateContext(ss *StarlarkScript) *generationContext {
Cole Faustf0632662022-04-07 13:59:24 -0700219 return &generationContext{
220 starScript: ss,
221 varAssignments: &varAssignmentScope{
222 outer: nil,
223 vars: make(map[string]bool),
224 },
225 }
226}
227
228func (gctx *generationContext) pushVariableAssignments() {
229 va := &varAssignmentScope{
230 outer: gctx.varAssignments,
231 vars: make(map[string]bool),
232 }
233 gctx.varAssignments = va
234}
235
236func (gctx *generationContext) popVariableAssignments() {
237 gctx.varAssignments = gctx.varAssignments.outer
238}
239
240func (gctx *generationContext) hasBeenAssigned(v variable) bool {
241 for va := gctx.varAssignments; va != nil; va = va.outer {
242 if _, ok := va.vars[v.name()]; ok {
243 return true
244 }
245 }
246 return false
247}
248
249func (gctx *generationContext) setHasBeenAssigned(v variable) {
250 gctx.varAssignments.vars[v.name()] = true
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800251}
252
253// emit returns generated script
254func (gctx *generationContext) emit() string {
255 ss := gctx.starScript
256
257 // The emitted code has the following layout:
258 // <initial comments>
259 // preamble, i.e.,
260 // load statement for the runtime support
261 // load statement for each unique submodule pulled in by this one
262 // def init(g, handle):
263 // cfg = rblf.cfg(handle)
264 // <statements>
265 // <warning if conversion was not clean>
266
267 iNode := len(ss.nodes)
268 for i, node := range ss.nodes {
269 if _, ok := node.(*commentNode); !ok {
270 iNode = i
271 break
272 }
273 node.emit(gctx)
274 }
275
276 gctx.emitPreamble()
277
278 gctx.newLine()
279 // The arguments passed to the init function are the global dictionary
280 // ('g') and the product configuration dictionary ('cfg')
281 gctx.write("def init(g, handle):")
282 gctx.indentLevel++
283 if gctx.starScript.traceCalls {
284 gctx.newLine()
285 gctx.writef(`print(">%s")`, gctx.starScript.mkFile)
286 }
287 gctx.newLine()
288 gctx.writef("cfg = %s(handle)", cfnGetCfg)
289 for _, node := range ss.nodes[iNode:] {
290 node.emit(gctx)
291 }
292
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800293 if gctx.starScript.traceCalls {
294 gctx.newLine()
295 gctx.writef(`print("<%s")`, gctx.starScript.mkFile)
296 }
297 gctx.indentLevel--
298 gctx.write("\n")
299 return gctx.buf.String()
300}
301
302func (gctx *generationContext) emitPreamble() {
303 gctx.newLine()
304 gctx.writef("load(%q, %q)", baseUri, baseName)
305 // Emit exactly one load statement for each URI.
306 loadedSubConfigs := make(map[string]string)
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800307 for _, mi := range gctx.starScript.inherited {
308 uri := mi.path
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800309 if m, ok := loadedSubConfigs[uri]; ok {
310 // No need to emit load statement, but fix module name.
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800311 mi.moduleLocalName = m
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800312 continue
313 }
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800314 if mi.optional || mi.missing {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800315 uri += "|init"
316 }
317 gctx.newLine()
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800318 gctx.writef("load(%q, %s = \"init\")", uri, mi.entryName())
319 loadedSubConfigs[uri] = mi.moduleLocalName
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800320 }
321 gctx.write("\n")
322}
323
324func (gctx *generationContext) emitPass() {
325 gctx.newLine()
326 gctx.write("pass")
327}
328
329func (gctx *generationContext) write(ss ...string) {
330 for _, s := range ss {
331 gctx.buf.WriteString(s)
332 }
333}
334
335func (gctx *generationContext) writef(format string, args ...interface{}) {
336 gctx.write(fmt.Sprintf(format, args...))
337}
338
339func (gctx *generationContext) newLine() {
340 if gctx.buf.Len() == 0 {
341 return
342 }
343 gctx.write("\n")
344 gctx.writef("%*s", 2*gctx.indentLevel, "")
345}
346
Sasha Smundak422b6142021-11-11 18:31:59 -0800347func (gctx *generationContext) emitConversionError(el ErrorLocation, message string) {
348 gctx.writef(`rblf.mk2rbc_error("%s", %q)`, el, message)
349}
350
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800351func (gctx *generationContext) emitLoadCheck(im inheritedModule) {
352 if !im.needsLoadCheck() {
353 return
354 }
355 gctx.newLine()
356 gctx.writef("if not %s:", im.entryName())
357 gctx.indentLevel++
358 gctx.newLine()
359 gctx.write(`rblf.mkerror("`, gctx.starScript.mkFile, `", "Cannot find %s" % (`)
360 im.pathExpr().emit(gctx)
361 gctx.write("))")
362 gctx.indentLevel--
363}
364
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800365type knownVariable struct {
366 name string
367 class varClass
368 valueType starlarkType
369}
370
371type knownVariables map[string]knownVariable
372
373func (pcv knownVariables) NewVariable(name string, varClass varClass, valueType starlarkType) {
374 v, exists := pcv[name]
375 if !exists {
376 pcv[name] = knownVariable{name, varClass, valueType}
377 return
378 }
379 // Conflict resolution:
380 // * config class trumps everything
381 // * any type trumps unknown type
382 match := varClass == v.class
383 if !match {
384 if varClass == VarClassConfig {
385 v.class = VarClassConfig
386 match = true
387 } else if v.class == VarClassConfig {
388 match = true
389 }
390 }
391 if valueType != v.valueType {
392 if valueType != starlarkTypeUnknown {
393 if v.valueType == starlarkTypeUnknown {
394 v.valueType = valueType
395 } else {
396 match = false
397 }
398 }
399 }
400 if !match {
401 fmt.Fprintf(os.Stderr, "cannot redefine %s as %v/%v (already defined as %v/%v)\n",
402 name, varClass, valueType, v.class, v.valueType)
403 }
404}
405
406// All known product variables.
407var KnownVariables = make(knownVariables)
408
409func init() {
410 for _, kv := range []string{
411 // Kernel-related variables that we know are lists.
412 "BOARD_VENDOR_KERNEL_MODULES",
413 "BOARD_VENDOR_RAMDISK_KERNEL_MODULES",
414 "BOARD_VENDOR_RAMDISK_KERNEL_MODULES_LOAD",
415 "BOARD_RECOVERY_KERNEL_MODULES",
416 // Other variables we knwo are lists
417 "ART_APEX_JARS",
418 } {
419 KnownVariables.NewVariable(kv, VarClassSoong, starlarkTypeList)
420 }
421}
422
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800423// Information about the generated Starlark script.
424type StarlarkScript struct {
Sasha Smundak422b6142021-11-11 18:31:59 -0800425 mkFile string
426 moduleName string
427 mkPos scanner.Position
428 nodes []starlarkNode
429 inherited []*moduleInfo
430 hasErrors bool
Sasha Smundak422b6142021-11-11 18:31:59 -0800431 traceCalls bool // print enter/exit each init function
432 sourceFS fs.FS
433 makefileFinder MakefileFinder
434 nodeLocator func(pos mkparser.Pos) int
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800435}
436
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800437// parseContext holds the script we are generating and all the ephemeral data
438// needed during the parsing.
439type parseContext struct {
440 script *StarlarkScript
441 nodes []mkparser.Node // Makefile as parsed by mkparser
442 currentNodeIndex int // Node in it we are processing
443 ifNestLevel int
444 moduleNameCount map[string]int // count of imported modules with given basename
445 fatalError error
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800446 outputSuffix string
Sasha Smundak7d934b92021-11-10 12:20:01 -0800447 errorLogger ErrorLogger
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800448 tracedVariables map[string]bool // variables to be traced in the generated script
449 variables map[string]variable
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800450 outputDir string
Sasha Smundak6609ba72021-07-22 18:32:56 -0700451 dependentModules map[string]*moduleInfo
Sasha Smundak3deb9682021-07-26 18:42:25 -0700452 soongNamespaces map[string]map[string]bool
Sasha Smundak6d852dd2021-09-27 20:34:39 -0700453 includeTops []string
Cole Faustf92c9f22022-03-14 14:35:50 -0700454 typeHints map[string]starlarkType
455 atTopOfMakefile bool
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800456}
457
458func newParseContext(ss *StarlarkScript, nodes []mkparser.Node) *parseContext {
459 predefined := []struct{ name, value string }{
460 {"SRC_TARGET_DIR", filepath.Join("build", "make", "target")},
461 {"LOCAL_PATH", filepath.Dir(ss.mkFile)},
Cole Faust9b6111a2022-02-02 15:38:33 -0800462 {"TOPDIR", ""}, // TOPDIR is just set to an empty string in cleanbuild.mk and core.mk
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800463 // TODO(asmundak): maybe read it from build/make/core/envsetup.mk?
464 {"TARGET_COPY_OUT_SYSTEM", "system"},
465 {"TARGET_COPY_OUT_SYSTEM_OTHER", "system_other"},
466 {"TARGET_COPY_OUT_DATA", "data"},
467 {"TARGET_COPY_OUT_ASAN", filepath.Join("data", "asan")},
468 {"TARGET_COPY_OUT_OEM", "oem"},
469 {"TARGET_COPY_OUT_RAMDISK", "ramdisk"},
470 {"TARGET_COPY_OUT_DEBUG_RAMDISK", "debug_ramdisk"},
471 {"TARGET_COPY_OUT_VENDOR_DEBUG_RAMDISK", "vendor_debug_ramdisk"},
472 {"TARGET_COPY_OUT_TEST_HARNESS_RAMDISK", "test_harness_ramdisk"},
473 {"TARGET_COPY_OUT_ROOT", "root"},
474 {"TARGET_COPY_OUT_RECOVERY", "recovery"},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800475 {"TARGET_COPY_OUT_VENDOR_RAMDISK", "vendor_ramdisk"},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800476 // TODO(asmundak): to process internal config files, we need the following variables:
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800477 // TARGET_VENDOR
478 // target_base_product
479 //
480
481 // the following utility variables are set in build/make/common/core.mk:
482 {"empty", ""},
483 {"space", " "},
484 {"comma", ","},
485 {"newline", "\n"},
486 {"pound", "#"},
487 {"backslash", "\\"},
488 }
489 ctx := &parseContext{
490 script: ss,
491 nodes: nodes,
492 currentNodeIndex: 0,
493 ifNestLevel: 0,
494 moduleNameCount: make(map[string]int),
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800495 variables: make(map[string]variable),
Sasha Smundak6609ba72021-07-22 18:32:56 -0700496 dependentModules: make(map[string]*moduleInfo),
Sasha Smundak3deb9682021-07-26 18:42:25 -0700497 soongNamespaces: make(map[string]map[string]bool),
Cole Faust6c934f62022-01-06 15:51:12 -0800498 includeTops: []string{},
Cole Faustf92c9f22022-03-14 14:35:50 -0700499 typeHints: make(map[string]starlarkType),
500 atTopOfMakefile: true,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800501 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800502 for _, item := range predefined {
503 ctx.variables[item.name] = &predefinedVariable{
504 baseVariable: baseVariable{nam: item.name, typ: starlarkTypeString},
505 value: &stringLiteralExpr{item.value},
506 }
507 }
508
509 return ctx
510}
511
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800512func (ctx *parseContext) hasNodes() bool {
513 return ctx.currentNodeIndex < len(ctx.nodes)
514}
515
516func (ctx *parseContext) getNode() mkparser.Node {
517 if !ctx.hasNodes() {
518 return nil
519 }
520 node := ctx.nodes[ctx.currentNodeIndex]
521 ctx.currentNodeIndex++
522 return node
523}
524
525func (ctx *parseContext) backNode() {
526 if ctx.currentNodeIndex <= 0 {
527 panic("Cannot back off")
528 }
529 ctx.currentNodeIndex--
530}
531
Cole Faustdd569ae2022-01-31 15:48:29 -0800532func (ctx *parseContext) handleAssignment(a *mkparser.Assignment) []starlarkNode {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800533 // Handle only simple variables
534 if !a.Name.Const() {
Cole Faustdd569ae2022-01-31 15:48:29 -0800535 return []starlarkNode{ctx.newBadNode(a, "Only simple variables are handled")}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800536 }
537 name := a.Name.Strings[0]
Sasha Smundakea3bc3a2021-11-10 13:06:42 -0800538 // The `override` directive
539 // override FOO :=
540 // is parsed as an assignment to a variable named `override FOO`.
541 // There are very few places where `override` is used, just flag it.
542 if strings.HasPrefix(name, "override ") {
Cole Faustdd569ae2022-01-31 15:48:29 -0800543 return []starlarkNode{ctx.newBadNode(a, "cannot handle override directive")}
Sasha Smundakea3bc3a2021-11-10 13:06:42 -0800544 }
545
Cole Faustc00184e2021-11-08 12:08:57 -0800546 // Soong configuration
Sasha Smundak3deb9682021-07-26 18:42:25 -0700547 if strings.HasPrefix(name, soongNsPrefix) {
Cole Faustdd569ae2022-01-31 15:48:29 -0800548 return ctx.handleSoongNsAssignment(strings.TrimPrefix(name, soongNsPrefix), a)
Sasha Smundak3deb9682021-07-26 18:42:25 -0700549 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800550 lhs := ctx.addVariable(name)
551 if lhs == nil {
Cole Faustdd569ae2022-01-31 15:48:29 -0800552 return []starlarkNode{ctx.newBadNode(a, "unknown variable %s", name)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800553 }
Cole Faust3c4fc992022-02-28 16:05:01 -0800554 _, isTraced := ctx.tracedVariables[lhs.name()]
Sasha Smundak422b6142021-11-11 18:31:59 -0800555 asgn := &assignmentNode{lhs: lhs, mkValue: a.Value, isTraced: isTraced, location: ctx.errorLocation(a)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800556 if lhs.valueType() == starlarkTypeUnknown {
557 // Try to divine variable type from the RHS
558 asgn.value = ctx.parseMakeString(a, a.Value)
559 if xBad, ok := asgn.value.(*badExpr); ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800560 return []starlarkNode{&exprNode{xBad}}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800561 }
562 inferred_type := asgn.value.typ()
563 if inferred_type != starlarkTypeUnknown {
Sasha Smundak9d011ab2021-07-09 16:00:57 -0700564 lhs.setValueType(inferred_type)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800565 }
566 }
567 if lhs.valueType() == starlarkTypeList {
Cole Faustdd569ae2022-01-31 15:48:29 -0800568 xConcat, xBad := ctx.buildConcatExpr(a)
569 if xBad != nil {
570 return []starlarkNode{&exprNode{expr: xBad}}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800571 }
572 switch len(xConcat.items) {
573 case 0:
574 asgn.value = &listExpr{}
575 case 1:
576 asgn.value = xConcat.items[0]
577 default:
578 asgn.value = xConcat
579 }
580 } else {
581 asgn.value = ctx.parseMakeString(a, a.Value)
582 if xBad, ok := asgn.value.(*badExpr); ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800583 return []starlarkNode{&exprNode{expr: xBad}}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800584 }
585 }
586
Cole Faust421a1922022-03-16 14:35:45 -0700587 if asgn.lhs.valueType() == starlarkTypeString &&
588 asgn.value.typ() != starlarkTypeUnknown &&
589 asgn.value.typ() != starlarkTypeString {
590 asgn.value = &toStringExpr{expr: asgn.value}
591 }
592
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800593 switch a.Type {
594 case "=", ":=":
595 asgn.flavor = asgnSet
596 case "+=":
Cole Fauste2a37982022-03-09 16:00:17 -0800597 asgn.flavor = asgnAppend
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800598 case "?=":
599 asgn.flavor = asgnMaybeSet
600 default:
601 panic(fmt.Errorf("unexpected assignment type %s", a.Type))
602 }
603
Cole Faustdd569ae2022-01-31 15:48:29 -0800604 return []starlarkNode{asgn}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800605}
606
Cole Faustdd569ae2022-01-31 15:48:29 -0800607func (ctx *parseContext) handleSoongNsAssignment(name string, asgn *mkparser.Assignment) []starlarkNode {
Sasha Smundak3deb9682021-07-26 18:42:25 -0700608 val := ctx.parseMakeString(asgn, asgn.Value)
609 if xBad, ok := val.(*badExpr); ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800610 return []starlarkNode{&exprNode{expr: xBad}}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700611 }
Sasha Smundak3deb9682021-07-26 18:42:25 -0700612
613 // Unfortunately, Soong namespaces can be set up by directly setting corresponding Make
614 // variables instead of via add_soong_config_namespace + add_soong_config_var_value.
615 // Try to divine the call from the assignment as follows:
616 if name == "NAMESPACES" {
617 // Upon seeng
618 // SOONG_CONFIG_NAMESPACES += foo
619 // remember that there is a namespace `foo` and act as we saw
620 // $(call add_soong_config_namespace,foo)
621 s, ok := maybeString(val)
622 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800623 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 -0700624 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800625 result := make([]starlarkNode, 0)
Sasha Smundak3deb9682021-07-26 18:42:25 -0700626 for _, ns := range strings.Fields(s) {
627 ctx.addSoongNamespace(ns)
Cole Faustdd569ae2022-01-31 15:48:29 -0800628 result = append(result, &exprNode{&callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -0800629 name: baseName + ".soong_config_namespace",
630 args: []starlarkExpr{&globalsExpr{}, &stringLiteralExpr{ns}},
Sasha Smundak3deb9682021-07-26 18:42:25 -0700631 returnType: starlarkTypeVoid,
632 }})
633 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800634 return result
Sasha Smundak3deb9682021-07-26 18:42:25 -0700635 } else {
636 // Upon seeing
637 // SOONG_CONFIG_x_y = v
638 // find a namespace called `x` and act as if we encountered
Cole Faustc00184e2021-11-08 12:08:57 -0800639 // $(call soong_config_set,x,y,v)
Sasha Smundak3deb9682021-07-26 18:42:25 -0700640 // or check that `x_y` is a namespace, and then add the RHS of this assignment as variables in
641 // it.
642 // Emit an error in the ambiguous situation (namespaces `foo_bar` with a variable `baz`
643 // and `foo` with a variable `bar_baz`.
644 namespaceName := ""
645 if ctx.hasSoongNamespace(name) {
646 namespaceName = name
647 }
648 var varName string
649 for pos, ch := range name {
650 if !(ch == '_' && ctx.hasSoongNamespace(name[0:pos])) {
651 continue
652 }
653 if namespaceName != "" {
Cole Faustdd569ae2022-01-31 15:48:29 -0800654 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 -0700655 }
656 namespaceName = name[0:pos]
657 varName = name[pos+1:]
658 }
659 if namespaceName == "" {
Cole Faustdd569ae2022-01-31 15:48:29 -0800660 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 -0700661 }
662 if varName == "" {
663 // Remember variables in this namespace
664 s, ok := maybeString(val)
665 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800666 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 -0700667 }
668 ctx.updateSoongNamespace(asgn.Type != "+=", namespaceName, strings.Fields(s))
Cole Faustdd569ae2022-01-31 15:48:29 -0800669 return []starlarkNode{}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700670 }
671
672 // Finally, handle assignment to a namespace variable
673 if !ctx.hasNamespaceVar(namespaceName, varName) {
Cole Faustdd569ae2022-01-31 15:48:29 -0800674 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 -0700675 }
Cole Faust9ebf6e42021-12-13 14:08:34 -0800676 fname := baseName + "." + soongConfigAssign
Sasha Smundak65b547e2021-09-17 15:35:41 -0700677 if asgn.Type == "+=" {
Cole Faust9ebf6e42021-12-13 14:08:34 -0800678 fname = baseName + "." + soongConfigAppend
Sasha Smundak65b547e2021-09-17 15:35:41 -0700679 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800680 return []starlarkNode{&exprNode{&callExpr{
Sasha Smundak65b547e2021-09-17 15:35:41 -0700681 name: fname,
Cole Faust9ebf6e42021-12-13 14:08:34 -0800682 args: []starlarkExpr{&globalsExpr{}, &stringLiteralExpr{namespaceName}, &stringLiteralExpr{varName}, val},
Sasha Smundak3deb9682021-07-26 18:42:25 -0700683 returnType: starlarkTypeVoid,
Cole Faustdd569ae2022-01-31 15:48:29 -0800684 }}}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700685 }
686}
687
Cole Faustdd569ae2022-01-31 15:48:29 -0800688func (ctx *parseContext) buildConcatExpr(a *mkparser.Assignment) (*concatExpr, *badExpr) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800689 xConcat := &concatExpr{}
690 var xItemList *listExpr
691 addToItemList := func(x ...starlarkExpr) {
692 if xItemList == nil {
693 xItemList = &listExpr{[]starlarkExpr{}}
694 }
695 xItemList.items = append(xItemList.items, x...)
696 }
697 finishItemList := func() {
698 if xItemList != nil {
699 xConcat.items = append(xConcat.items, xItemList)
700 xItemList = nil
701 }
702 }
703
704 items := a.Value.Words()
705 for _, item := range items {
706 // A function call in RHS is supposed to return a list, all other item
707 // expressions return individual elements.
708 switch x := ctx.parseMakeString(a, item).(type) {
709 case *badExpr:
Cole Faustdd569ae2022-01-31 15:48:29 -0800710 return nil, x
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800711 case *stringLiteralExpr:
712 addToItemList(maybeConvertToStringList(x).(*listExpr).items...)
713 default:
714 switch x.typ() {
715 case starlarkTypeList:
716 finishItemList()
717 xConcat.items = append(xConcat.items, x)
718 case starlarkTypeString:
719 finishItemList()
720 xConcat.items = append(xConcat.items, &callExpr{
721 object: x,
722 name: "split",
723 args: nil,
724 returnType: starlarkTypeList,
725 })
726 default:
727 addToItemList(x)
728 }
729 }
730 }
731 if xItemList != nil {
732 xConcat.items = append(xConcat.items, xItemList)
733 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800734 return xConcat, nil
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800735}
736
Sasha Smundak6609ba72021-07-22 18:32:56 -0700737func (ctx *parseContext) newDependentModule(path string, optional bool) *moduleInfo {
738 modulePath := ctx.loadedModulePath(path)
739 if mi, ok := ctx.dependentModules[modulePath]; ok {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700740 mi.optional = mi.optional && optional
Sasha Smundak6609ba72021-07-22 18:32:56 -0700741 return mi
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800742 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800743 moduleName := moduleNameForFile(path)
744 moduleLocalName := "_" + moduleName
745 n, found := ctx.moduleNameCount[moduleName]
746 if found {
747 moduleLocalName += fmt.Sprintf("%d", n)
748 }
749 ctx.moduleNameCount[moduleName] = n + 1
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800750 _, err := fs.Stat(ctx.script.sourceFS, path)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700751 mi := &moduleInfo{
752 path: modulePath,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800753 originalPath: path,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800754 moduleLocalName: moduleLocalName,
Sasha Smundak6609ba72021-07-22 18:32:56 -0700755 optional: optional,
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800756 missing: err != nil,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800757 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700758 ctx.dependentModules[modulePath] = mi
759 ctx.script.inherited = append(ctx.script.inherited, mi)
760 return mi
761}
762
763func (ctx *parseContext) handleSubConfig(
Cole Faustdd569ae2022-01-31 15:48:29 -0800764 v mkparser.Node, pathExpr starlarkExpr, loadAlways bool, processModule func(inheritedModule) starlarkNode) []starlarkNode {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700765
Cole Faust62e05112022-04-05 17:56:11 -0700766 // Allow seeing $(sort $(wildcard realPathExpr)) or $(wildcard realPathExpr)
767 // because those are functionally the same as not having the sort/wildcard calls.
768 if ce, ok := pathExpr.(*callExpr); ok && ce.name == "rblf.mksort" && len(ce.args) == 1 {
769 if ce2, ok2 := ce.args[0].(*callExpr); ok2 && ce2.name == "rblf.expand_wildcard" && len(ce2.args) == 1 {
770 pathExpr = ce2.args[0]
771 }
772 } else if ce2, ok2 := pathExpr.(*callExpr); ok2 && ce2.name == "rblf.expand_wildcard" && len(ce2.args) == 1 {
773 pathExpr = ce2.args[0]
774 }
775
Sasha Smundak6609ba72021-07-22 18:32:56 -0700776 // In a simple case, the name of a module to inherit/include is known statically.
777 if path, ok := maybeString(pathExpr); ok {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700778 // Note that even if this directive loads a module unconditionally, a module may be
779 // absent without causing any harm if this directive is inside an if/else block.
780 moduleShouldExist := loadAlways && ctx.ifNestLevel == 0
Sasha Smundak6609ba72021-07-22 18:32:56 -0700781 if strings.Contains(path, "*") {
782 if paths, err := fs.Glob(ctx.script.sourceFS, path); err == nil {
Cole Faust62e05112022-04-05 17:56:11 -0700783 sort.Strings(paths)
Cole Faustdd569ae2022-01-31 15:48:29 -0800784 result := make([]starlarkNode, 0)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700785 for _, p := range paths {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700786 mi := ctx.newDependentModule(p, !moduleShouldExist)
Cole Faustdd569ae2022-01-31 15:48:29 -0800787 result = append(result, processModule(inheritedStaticModule{mi, loadAlways}))
Sasha Smundak6609ba72021-07-22 18:32:56 -0700788 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800789 return result
Sasha Smundak6609ba72021-07-22 18:32:56 -0700790 } else {
Cole Faustdd569ae2022-01-31 15:48:29 -0800791 return []starlarkNode{ctx.newBadNode(v, "cannot glob wildcard argument")}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700792 }
793 } else {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700794 mi := ctx.newDependentModule(path, !moduleShouldExist)
Cole Faustdd569ae2022-01-31 15:48:29 -0800795 return []starlarkNode{processModule(inheritedStaticModule{mi, loadAlways})}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700796 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700797 }
798
799 // If module path references variables (e.g., $(v1)/foo/$(v2)/device-config.mk), find all the paths in the
800 // source tree that may be a match and the corresponding variable values. For instance, if the source tree
801 // contains vendor1/foo/abc/dev.mk and vendor2/foo/def/dev.mk, the first one will be inherited when
802 // (v1, v2) == ('vendor1', 'abc'), and the second one when (v1, v2) == ('vendor2', 'def').
803 // We then emit the code that loads all of them, e.g.:
804 // load("//vendor1/foo/abc:dev.rbc", _dev1_init="init")
805 // load("//vendor2/foo/def/dev.rbc", _dev2_init="init")
806 // And then inherit it as follows:
807 // _e = {
808 // "vendor1/foo/abc/dev.mk": ("vendor1/foo/abc/dev", _dev1_init),
809 // "vendor2/foo/def/dev.mk": ("vendor2/foo/def/dev", _dev_init2) }.get("%s/foo/%s/dev.mk" % (v1, v2))
810 // if _e:
811 // rblf.inherit(handle, _e[0], _e[1])
812 //
813 var matchingPaths []string
Cole Faust9df1d732022-04-26 16:27:22 -0700814 var needsWarning = false
815 if interpolate, ok := pathExpr.(*interpolateExpr); ok {
816 pathPattern := []string{interpolate.chunks[0]}
817 for _, chunk := range interpolate.chunks[1:] {
818 if chunk != "" {
819 pathPattern = append(pathPattern, chunk)
820 }
821 }
822 if pathPattern[0] == "" && len(ctx.includeTops) > 0 {
823 // If pattern starts from the top. restrict it to the directories where
824 // we know inherit-product uses dynamically calculated path.
825 for _, p := range ctx.includeTops {
826 pathPattern[0] = p
827 matchingPaths = append(matchingPaths, ctx.findMatchingPaths(pathPattern)...)
828 }
829 } else {
830 matchingPaths = ctx.findMatchingPaths(pathPattern)
831 }
832 needsWarning = pathPattern[0] == "" && len(ctx.includeTops) == 0
833 } else if len(ctx.includeTops) > 0 {
834 for _, p := range ctx.includeTops {
835 matchingPaths = append(matchingPaths, ctx.findMatchingPaths([]string{p, ""})...)
836 }
837 } else {
Cole Faustdd569ae2022-01-31 15:48:29 -0800838 return []starlarkNode{ctx.newBadNode(v, "inherit-product/include argument is too complex")}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700839 }
840
Sasha Smundak6609ba72021-07-22 18:32:56 -0700841 // Safeguard against $(call inherit-product,$(PRODUCT_PATH))
Sasha Smundak90be8c52021-08-03 11:06:10 -0700842 const maxMatchingFiles = 150
Sasha Smundak6609ba72021-07-22 18:32:56 -0700843 if len(matchingPaths) > maxMatchingFiles {
Cole Faustdd569ae2022-01-31 15:48:29 -0800844 return []starlarkNode{ctx.newBadNode(v, "there are >%d files matching the pattern, please rewrite it", maxMatchingFiles)}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700845 }
Cole Faust93f8d392022-03-02 13:31:30 -0800846
Cole Faust9df1d732022-04-26 16:27:22 -0700847 res := inheritedDynamicModule{pathExpr, []*moduleInfo{}, loadAlways, ctx.errorLocation(v), needsWarning}
Cole Faust93f8d392022-03-02 13:31:30 -0800848 for _, p := range matchingPaths {
849 // A product configuration files discovered dynamically may attempt to inherit
850 // from another one which does not exist in this source tree. Prevent load errors
851 // by always loading the dynamic files as optional.
852 res.candidateModules = append(res.candidateModules, ctx.newDependentModule(p, true))
Sasha Smundak6609ba72021-07-22 18:32:56 -0700853 }
Cole Faust93f8d392022-03-02 13:31:30 -0800854 return []starlarkNode{processModule(res)}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700855}
856
857func (ctx *parseContext) findMatchingPaths(pattern []string) []string {
Cole Faust9b6111a2022-02-02 15:38:33 -0800858 files := ctx.script.makefileFinder.Find(".")
Sasha Smundak6609ba72021-07-22 18:32:56 -0700859 if len(pattern) == 0 {
860 return files
861 }
862
863 // Create regular expression from the pattern
864 s_regexp := "^" + regexp.QuoteMeta(pattern[0])
865 for _, s := range pattern[1:] {
866 s_regexp += ".*" + regexp.QuoteMeta(s)
867 }
868 s_regexp += "$"
869 rex := regexp.MustCompile(s_regexp)
870
871 // Now match
872 var res []string
873 for _, p := range files {
874 if rex.MatchString(p) {
875 res = append(res, p)
876 }
877 }
878 return res
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800879}
880
Cole Faustf035d402022-03-28 14:02:50 -0700881type inheritProductCallParser struct {
882 loadAlways bool
883}
884
885func (p *inheritProductCallParser) parse(ctx *parseContext, v mkparser.Node, args *mkparser.MakeString) []starlarkNode {
Cole Faust9ebf6e42021-12-13 14:08:34 -0800886 args.TrimLeftSpaces()
887 args.TrimRightSpaces()
888 pathExpr := ctx.parseMakeString(v, args)
889 if _, ok := pathExpr.(*badExpr); ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800890 return []starlarkNode{ctx.newBadNode(v, "Unable to parse argument to inherit")}
Cole Faust9ebf6e42021-12-13 14:08:34 -0800891 }
Cole Faustf035d402022-03-28 14:02:50 -0700892 return ctx.handleSubConfig(v, pathExpr, p.loadAlways, func(im inheritedModule) starlarkNode {
893 return &inheritNode{im, p.loadAlways}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700894 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800895}
896
Cole Faustdd569ae2022-01-31 15:48:29 -0800897func (ctx *parseContext) handleInclude(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) []starlarkNode {
898 return ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) starlarkNode {
899 return &includeNode{im, loadAlways}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700900 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800901}
902
Cole Faustdd569ae2022-01-31 15:48:29 -0800903func (ctx *parseContext) handleVariable(v *mkparser.Variable) []starlarkNode {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800904 // Handle:
905 // $(call inherit-product,...)
906 // $(call inherit-product-if-exists,...)
907 // $(info xxx)
908 // $(warning xxx)
909 // $(error xxx)
Cole Faust9ebf6e42021-12-13 14:08:34 -0800910 // $(call other-custom-functions,...)
911
Cole Faustf035d402022-03-28 14:02:50 -0700912 if name, args, ok := ctx.maybeParseFunctionCall(v, v.Name); ok {
913 if kf, ok := knownNodeFunctions[name]; ok {
914 return kf.parse(ctx, v, args)
915 }
Cole Faust9ebf6e42021-12-13 14:08:34 -0800916 }
Cole Faustf035d402022-03-28 14:02:50 -0700917
Cole Faustdd569ae2022-01-31 15:48:29 -0800918 return []starlarkNode{&exprNode{expr: ctx.parseReference(v, v.Name)}}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800919}
920
Cole Faustdd569ae2022-01-31 15:48:29 -0800921func (ctx *parseContext) maybeHandleDefine(directive *mkparser.Directive) starlarkNode {
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700922 macro_name := strings.Fields(directive.Args.Strings[0])[0]
923 // Ignore the macros that we handle
Cole Faust9ebf6e42021-12-13 14:08:34 -0800924 _, ignored := ignoredDefines[macro_name]
925 _, known := knownFunctions[macro_name]
926 if !ignored && !known {
Cole Faustdd569ae2022-01-31 15:48:29 -0800927 return ctx.newBadNode(directive, "define is not supported: %s", macro_name)
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700928 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800929 return nil
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800930}
931
Cole Faustdd569ae2022-01-31 15:48:29 -0800932func (ctx *parseContext) handleIfBlock(ifDirective *mkparser.Directive) starlarkNode {
933 ssSwitch := &switchNode{
934 ssCases: []*switchCase{ctx.processBranch(ifDirective)},
935 }
936 for ctx.hasNodes() && ctx.fatalError == nil {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800937 node := ctx.getNode()
938 switch x := node.(type) {
939 case *mkparser.Directive:
940 switch x.Name {
941 case "else", "elifdef", "elifndef", "elifeq", "elifneq":
Cole Faustdd569ae2022-01-31 15:48:29 -0800942 ssSwitch.ssCases = append(ssSwitch.ssCases, ctx.processBranch(x))
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800943 case "endif":
Cole Faustdd569ae2022-01-31 15:48:29 -0800944 return ssSwitch
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800945 default:
Cole Faustdd569ae2022-01-31 15:48:29 -0800946 return ctx.newBadNode(node, "unexpected directive %s", x.Name)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800947 }
948 default:
Cole Faustdd569ae2022-01-31 15:48:29 -0800949 return ctx.newBadNode(ifDirective, "unexpected statement")
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800950 }
951 }
952 if ctx.fatalError == nil {
953 ctx.fatalError = fmt.Errorf("no matching endif for %s", ifDirective.Dump())
954 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800955 return ctx.newBadNode(ifDirective, "no matching endif for %s", ifDirective.Dump())
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800956}
957
958// processBranch processes a single branch (if/elseif/else) until the next directive
959// on the same level.
Cole Faustdd569ae2022-01-31 15:48:29 -0800960func (ctx *parseContext) processBranch(check *mkparser.Directive) *switchCase {
961 block := &switchCase{gate: ctx.parseCondition(check)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800962 defer func() {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800963 ctx.ifNestLevel--
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800964 }()
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800965 ctx.ifNestLevel++
966
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800967 for ctx.hasNodes() {
968 node := ctx.getNode()
Cole Faust591a1fe2021-11-08 15:37:57 -0800969 if d, ok := node.(*mkparser.Directive); ok {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800970 switch d.Name {
971 case "else", "elifdef", "elifndef", "elifeq", "elifneq", "endif":
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800972 ctx.backNode()
Cole Faustdd569ae2022-01-31 15:48:29 -0800973 return block
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800974 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800975 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800976 block.nodes = append(block.nodes, ctx.handleSimpleStatement(node)...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800977 }
978 ctx.fatalError = fmt.Errorf("no matching endif for %s", check.Dump())
Cole Faustdd569ae2022-01-31 15:48:29 -0800979 return block
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800980}
981
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800982func (ctx *parseContext) parseCondition(check *mkparser.Directive) starlarkNode {
983 switch check.Name {
984 case "ifdef", "ifndef", "elifdef", "elifndef":
Cole Faust71514c02022-01-27 17:21:41 -0800985 if !check.Args.Const() {
Cole Faustdd569ae2022-01-31 15:48:29 -0800986 return ctx.newBadNode(check, "ifdef variable ref too complex: %s", check.Args.Dump())
Cole Faust71514c02022-01-27 17:21:41 -0800987 }
Cole Faustf0632662022-04-07 13:59:24 -0700988 v := NewVariableRefExpr(ctx.addVariable(check.Args.Strings[0]))
Cole Faust71514c02022-01-27 17:21:41 -0800989 if strings.HasSuffix(check.Name, "ndef") {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800990 v = &notExpr{v}
991 }
992 return &ifNode{
993 isElif: strings.HasPrefix(check.Name, "elif"),
994 expr: v,
995 }
996 case "ifeq", "ifneq", "elifeq", "elifneq":
997 return &ifNode{
998 isElif: strings.HasPrefix(check.Name, "elif"),
999 expr: ctx.parseCompare(check),
1000 }
1001 case "else":
1002 return &elseNode{}
1003 default:
1004 panic(fmt.Errorf("%s: unknown directive: %s", ctx.script.mkFile, check.Dump()))
1005 }
1006}
1007
1008func (ctx *parseContext) newBadExpr(node mkparser.Node, text string, args ...interface{}) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001009 if ctx.errorLogger != nil {
Sasha Smundak422b6142021-11-11 18:31:59 -08001010 ctx.errorLogger.NewError(ctx.errorLocation(node), node, text, args...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001011 }
1012 ctx.script.hasErrors = true
Cole Faustdd569ae2022-01-31 15:48:29 -08001013 return &badExpr{errorLocation: ctx.errorLocation(node), message: fmt.Sprintf(text, args...)}
1014}
1015
1016// records that the given node failed to be converted and includes an explanatory message
1017func (ctx *parseContext) newBadNode(failedNode mkparser.Node, message string, args ...interface{}) starlarkNode {
1018 return &exprNode{ctx.newBadExpr(failedNode, message, args...)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001019}
1020
1021func (ctx *parseContext) parseCompare(cond *mkparser.Directive) starlarkExpr {
1022 // Strip outer parentheses
1023 mkArg := cloneMakeString(cond.Args)
1024 mkArg.Strings[0] = strings.TrimLeft(mkArg.Strings[0], "( ")
1025 n := len(mkArg.Strings)
1026 mkArg.Strings[n-1] = strings.TrimRight(mkArg.Strings[n-1], ") ")
1027 args := mkArg.Split(",")
1028 // TODO(asmundak): handle the case where the arguments are in quotes and space-separated
1029 if len(args) != 2 {
1030 return ctx.newBadExpr(cond, "ifeq/ifneq len(args) != 2 %s", cond.Dump())
1031 }
1032 args[0].TrimRightSpaces()
1033 args[1].TrimLeftSpaces()
1034
1035 isEq := !strings.HasSuffix(cond.Name, "neq")
Cole Faustf8320212021-11-10 15:05:07 -08001036 xLeft := ctx.parseMakeString(cond, args[0])
1037 xRight := ctx.parseMakeString(cond, args[1])
1038 if bad, ok := xLeft.(*badExpr); ok {
1039 return bad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001040 }
Cole Faustf8320212021-11-10 15:05:07 -08001041 if bad, ok := xRight.(*badExpr); ok {
1042 return bad
1043 }
1044
1045 if expr, ok := ctx.parseCompareSpecialCases(cond, xLeft, xRight); ok {
1046 return expr
1047 }
1048
Cole Faust9ebf6e42021-12-13 14:08:34 -08001049 var stringOperand string
1050 var otherOperand starlarkExpr
1051 if s, ok := maybeString(xLeft); ok {
1052 stringOperand = s
1053 otherOperand = xRight
1054 } else if s, ok := maybeString(xRight); ok {
1055 stringOperand = s
1056 otherOperand = xLeft
1057 }
1058
Cole Faust9ebf6e42021-12-13 14:08:34 -08001059 // If we've identified one of the operands as being a string literal, check
1060 // for some special cases we can do to simplify the resulting expression.
1061 if otherOperand != nil {
1062 if stringOperand == "" {
1063 if isEq {
Cole Faustf035d402022-03-28 14:02:50 -07001064 return negateExpr(otherOperand)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001065 } else {
1066 return otherOperand
1067 }
1068 }
1069 if stringOperand == "true" && otherOperand.typ() == starlarkTypeBool {
1070 if !isEq {
Cole Faustf035d402022-03-28 14:02:50 -07001071 return negateExpr(otherOperand)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001072 } else {
1073 return otherOperand
1074 }
1075 }
Cole Faustb1103e22022-01-06 15:22:05 -08001076 if intOperand, err := strconv.Atoi(strings.TrimSpace(stringOperand)); err == nil && otherOperand.typ() == starlarkTypeInt {
1077 return &eqExpr{
1078 left: otherOperand,
1079 right: &intLiteralExpr{literal: intOperand},
1080 isEq: isEq,
1081 }
1082 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001083 }
1084
Cole Faustf8320212021-11-10 15:05:07 -08001085 return &eqExpr{left: xLeft, right: xRight, isEq: isEq}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001086}
1087
Cole Faustf8320212021-11-10 15:05:07 -08001088// Given an if statement's directive and the left/right starlarkExprs,
1089// check if the starlarkExprs are one of a few hardcoded special cases
Cole Faust9932f752022-02-08 11:56:25 -08001090// that can be converted to a simpler equality expression than simply comparing
Cole Faustf8320212021-11-10 15:05:07 -08001091// the two.
1092func (ctx *parseContext) parseCompareSpecialCases(directive *mkparser.Directive, left starlarkExpr,
1093 right starlarkExpr) (starlarkExpr, bool) {
1094 isEq := !strings.HasSuffix(directive.Name, "neq")
1095
1096 // All the special cases require a call on one side and a
1097 // string literal/variable on the other. Turn the left/right variables into
1098 // call/value variables, and return false if that's not possible.
1099 var value starlarkExpr = nil
1100 call, ok := left.(*callExpr)
1101 if ok {
1102 switch right.(type) {
1103 case *stringLiteralExpr, *variableRefExpr:
1104 value = right
1105 }
1106 } else {
1107 call, _ = right.(*callExpr)
1108 switch left.(type) {
1109 case *stringLiteralExpr, *variableRefExpr:
1110 value = left
1111 }
1112 }
1113
1114 if call == nil || value == nil {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001115 return nil, false
1116 }
Cole Faustf8320212021-11-10 15:05:07 -08001117
Cole Faustf8320212021-11-10 15:05:07 -08001118 switch call.name {
Cole Faust9932f752022-02-08 11:56:25 -08001119 case baseName + ".filter":
1120 return ctx.parseCompareFilterFuncResult(directive, call, value, isEq)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001121 case baseName + ".expand_wildcard":
Cole Faustf8320212021-11-10 15:05:07 -08001122 return ctx.parseCompareWildcardFuncResult(directive, call, value, !isEq), true
Cole Faust9ebf6e42021-12-13 14:08:34 -08001123 case baseName + ".findstring":
Cole Faustf8320212021-11-10 15:05:07 -08001124 return ctx.parseCheckFindstringFuncResult(directive, call, value, !isEq), true
Cole Faust9ebf6e42021-12-13 14:08:34 -08001125 case baseName + ".strip":
Cole Faustf8320212021-11-10 15:05:07 -08001126 return ctx.parseCompareStripFuncResult(directive, call, value, !isEq), true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001127 }
Cole Faustf8320212021-11-10 15:05:07 -08001128 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001129}
1130
1131func (ctx *parseContext) parseCompareFilterFuncResult(cond *mkparser.Directive,
Cole Faust9932f752022-02-08 11:56:25 -08001132 filterFuncCall *callExpr, xValue starlarkExpr, negate bool) (starlarkExpr, bool) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001133 // We handle:
Sasha Smundak0554d762021-07-08 18:26:12 -07001134 // * ifeq/ifneq (,$(filter v1 v2 ..., EXPR) becomes if EXPR not in/in ["v1", "v2", ...]
1135 // * ifeq/ifneq (,$(filter EXPR, v1 v2 ...) becomes if EXPR not in/in ["v1", "v2", ...]
Cole Faust9932f752022-02-08 11:56:25 -08001136 if x, ok := xValue.(*stringLiteralExpr); !ok || x.literal != "" {
1137 return nil, false
1138 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001139 xPattern := filterFuncCall.args[0]
1140 xText := filterFuncCall.args[1]
1141 var xInList *stringLiteralExpr
Sasha Smundak0554d762021-07-08 18:26:12 -07001142 var expr starlarkExpr
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001143 var ok bool
Cole Faust9932f752022-02-08 11:56:25 -08001144 if xInList, ok = xPattern.(*stringLiteralExpr); ok && !strings.ContainsRune(xInList.literal, '%') && xText.typ() == starlarkTypeList {
1145 expr = xText
1146 } else if xInList, ok = xText.(*stringLiteralExpr); ok {
1147 expr = xPattern
1148 } else {
1149 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001150 }
Cole Faust9932f752022-02-08 11:56:25 -08001151 slExpr := newStringListExpr(strings.Fields(xInList.literal))
1152 // Generate simpler code for the common cases:
1153 if expr.typ() == starlarkTypeList {
1154 if len(slExpr.items) == 1 {
1155 // Checking that a string belongs to list
1156 return &inExpr{isNot: negate, list: expr, expr: slExpr.items[0]}, true
Sasha Smundak0554d762021-07-08 18:26:12 -07001157 } else {
Cole Faust9932f752022-02-08 11:56:25 -08001158 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001159 }
Cole Faust9932f752022-02-08 11:56:25 -08001160 } else if len(slExpr.items) == 1 {
1161 return &eqExpr{left: expr, right: slExpr.items[0], isEq: !negate}, true
1162 } else {
1163 return &inExpr{isNot: negate, list: newStringListExpr(strings.Fields(xInList.literal)), expr: expr}, true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001164 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001165}
1166
1167func (ctx *parseContext) parseCompareWildcardFuncResult(directive *mkparser.Directive,
1168 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001169 if !isEmptyString(xValue) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001170 return ctx.newBadExpr(directive, "wildcard result can be compared only to empty: %s", xValue)
1171 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001172 callFunc := baseName + ".file_wildcard_exists"
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001173 if s, ok := xCall.args[0].(*stringLiteralExpr); ok && !strings.ContainsAny(s.literal, "*?{[") {
Cole Faust9ebf6e42021-12-13 14:08:34 -08001174 callFunc = baseName + ".file_exists"
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001175 }
1176 var cc starlarkExpr = &callExpr{name: callFunc, args: xCall.args, returnType: starlarkTypeBool}
1177 if !negate {
1178 cc = &notExpr{cc}
1179 }
1180 return cc
1181}
1182
1183func (ctx *parseContext) parseCheckFindstringFuncResult(directive *mkparser.Directive,
1184 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001185 if isEmptyString(xValue) {
1186 return &eqExpr{
1187 left: &callExpr{
1188 object: xCall.args[1],
1189 name: "find",
1190 args: []starlarkExpr{xCall.args[0]},
1191 returnType: starlarkTypeInt,
1192 },
1193 right: &intLiteralExpr{-1},
1194 isEq: !negate,
1195 }
Cole Faust0e9418c2021-12-13 16:33:25 -08001196 } else if s, ok := maybeString(xValue); ok {
1197 if s2, ok := maybeString(xCall.args[0]); ok && s == s2 {
1198 return &eqExpr{
1199 left: &callExpr{
1200 object: xCall.args[1],
1201 name: "find",
1202 args: []starlarkExpr{xCall.args[0]},
1203 returnType: starlarkTypeInt,
1204 },
1205 right: &intLiteralExpr{-1},
1206 isEq: negate,
1207 }
1208 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001209 }
Cole Faust0e9418c2021-12-13 16:33:25 -08001210 return ctx.newBadExpr(directive, "$(findstring) can only be compared to nothing or its first argument")
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001211}
1212
1213func (ctx *parseContext) parseCompareStripFuncResult(directive *mkparser.Directive,
1214 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
1215 if _, ok := xValue.(*stringLiteralExpr); !ok {
1216 return ctx.newBadExpr(directive, "strip result can be compared only to string: %s", xValue)
1217 }
1218 return &eqExpr{
1219 left: &callExpr{
1220 name: "strip",
1221 args: xCall.args,
1222 returnType: starlarkTypeString,
1223 },
1224 right: xValue, isEq: !negate}
1225}
1226
Cole Faustf035d402022-03-28 14:02:50 -07001227func (ctx *parseContext) maybeParseFunctionCall(node mkparser.Node, ref *mkparser.MakeString) (name string, args *mkparser.MakeString, ok bool) {
1228 ref.TrimLeftSpaces()
1229 ref.TrimRightSpaces()
1230
1231 words := ref.SplitN(" ", 2)
1232 if !words[0].Const() {
1233 return "", nil, false
1234 }
1235
1236 name = words[0].Dump()
1237 args = mkparser.SimpleMakeString("", words[0].Pos())
1238 if len(words) >= 2 {
1239 args = words[1]
1240 }
1241 args.TrimLeftSpaces()
1242 if name == "call" {
1243 words = args.SplitN(",", 2)
1244 if words[0].Empty() || !words[0].Const() {
1245 return "", nil, false
1246 }
1247 name = words[0].Dump()
1248 if len(words) < 2 {
Cole Faust6c41b8a2022-04-13 13:53:48 -07001249 args = mkparser.SimpleMakeString("", words[0].Pos())
Cole Faustf035d402022-03-28 14:02:50 -07001250 } else {
1251 args = words[1]
1252 }
1253 }
1254 ok = true
1255 return
1256}
1257
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001258// parses $(...), returning an expression
1259func (ctx *parseContext) parseReference(node mkparser.Node, ref *mkparser.MakeString) starlarkExpr {
1260 ref.TrimLeftSpaces()
1261 ref.TrimRightSpaces()
1262 refDump := ref.Dump()
1263
1264 // Handle only the case where the first (or only) word is constant
1265 words := ref.SplitN(" ", 2)
1266 if !words[0].Const() {
1267 return ctx.newBadExpr(node, "reference is too complex: %s", refDump)
1268 }
1269
1270 // If it is a single word, it can be a simple variable
1271 // reference or a function call
Cole Faustf035d402022-03-28 14:02:50 -07001272 if len(words) == 1 && !isMakeControlFunc(refDump) && refDump != "shell" && refDump != "eval" {
Sasha Smundak65b547e2021-09-17 15:35:41 -07001273 if strings.HasPrefix(refDump, soongNsPrefix) {
1274 // TODO (asmundak): if we find many, maybe handle them.
Cole Faustc00184e2021-11-08 12:08:57 -08001275 return ctx.newBadExpr(node, "SOONG_CONFIG_ variables cannot be referenced, use soong_config_get instead: %s", refDump)
Sasha Smundak65b547e2021-09-17 15:35:41 -07001276 }
Cole Faustc36c9622021-12-07 15:20:45 -08001277 // Handle substitution references: https://www.gnu.org/software/make/manual/html_node/Substitution-Refs.html
1278 if strings.Contains(refDump, ":") {
1279 parts := strings.SplitN(refDump, ":", 2)
1280 substParts := strings.SplitN(parts[1], "=", 2)
1281 if len(substParts) < 2 || strings.Count(substParts[0], "%") > 1 {
1282 return ctx.newBadExpr(node, "Invalid substitution reference")
1283 }
1284 if !strings.Contains(substParts[0], "%") {
1285 if strings.Contains(substParts[1], "%") {
1286 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.")
1287 }
1288 substParts[0] = "%" + substParts[0]
1289 substParts[1] = "%" + substParts[1]
1290 }
1291 v := ctx.addVariable(parts[0])
1292 if v == nil {
1293 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1294 }
1295 return &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001296 name: baseName + ".mkpatsubst",
1297 returnType: starlarkTypeString,
Cole Faustc36c9622021-12-07 15:20:45 -08001298 args: []starlarkExpr{
1299 &stringLiteralExpr{literal: substParts[0]},
1300 &stringLiteralExpr{literal: substParts[1]},
Cole Faustf0632662022-04-07 13:59:24 -07001301 NewVariableRefExpr(v),
Cole Faustc36c9622021-12-07 15:20:45 -08001302 },
1303 }
1304 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001305 if v := ctx.addVariable(refDump); v != nil {
Cole Faustf0632662022-04-07 13:59:24 -07001306 return NewVariableRefExpr(v)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001307 }
1308 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1309 }
1310
Cole Faustf035d402022-03-28 14:02:50 -07001311 if name, args, ok := ctx.maybeParseFunctionCall(node, ref); ok {
1312 if kf, found := knownFunctions[name]; found {
1313 return kf.parse(ctx, node, args)
Sasha Smundak6609ba72021-07-22 18:32:56 -07001314 } else {
Cole Faustf035d402022-03-28 14:02:50 -07001315 return ctx.newBadExpr(node, "cannot handle invoking %s", name)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001316 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001317 } else {
Cole Faustf035d402022-03-28 14:02:50 -07001318 return ctx.newBadExpr(node, "cannot handle %s", refDump)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001319 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001320}
1321
1322type simpleCallParser struct {
1323 name string
1324 returnType starlarkType
1325 addGlobals bool
Cole Faust1cc08852022-02-28 11:12:08 -08001326 addHandle bool
Cole Faust9ebf6e42021-12-13 14:08:34 -08001327}
1328
1329func (p *simpleCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1330 expr := &callExpr{name: p.name, returnType: p.returnType}
1331 if p.addGlobals {
1332 expr.args = append(expr.args, &globalsExpr{})
1333 }
Cole Faust1cc08852022-02-28 11:12:08 -08001334 if p.addHandle {
1335 expr.args = append(expr.args, &identifierExpr{name: "handle"})
1336 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001337 for _, arg := range args.Split(",") {
1338 arg.TrimLeftSpaces()
1339 arg.TrimRightSpaces()
1340 x := ctx.parseMakeString(node, arg)
1341 if xBad, ok := x.(*badExpr); ok {
1342 return xBad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001343 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001344 expr.args = append(expr.args, x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001345 }
1346 return expr
1347}
1348
Cole Faust9ebf6e42021-12-13 14:08:34 -08001349type makeControlFuncParser struct {
1350 name string
1351}
1352
1353func (p *makeControlFuncParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1354 // Make control functions need special treatment as everything
1355 // after the name is a single text argument
1356 x := ctx.parseMakeString(node, args)
1357 if xBad, ok := x.(*badExpr); ok {
1358 return xBad
1359 }
1360 return &callExpr{
1361 name: p.name,
1362 args: []starlarkExpr{
1363 &stringLiteralExpr{ctx.script.mkFile},
1364 x,
1365 },
1366 returnType: starlarkTypeUnknown,
1367 }
1368}
1369
1370type shellCallParser struct{}
1371
1372func (p *shellCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1373 // Shell functions need special treatment as everything
1374 // after the name is a single text argument
1375 x := ctx.parseMakeString(node, args)
1376 if xBad, ok := x.(*badExpr); ok {
1377 return xBad
1378 }
1379 return &callExpr{
1380 name: baseName + ".shell",
1381 args: []starlarkExpr{x},
1382 returnType: starlarkTypeUnknown,
1383 }
1384}
1385
1386type myDirCallParser struct{}
1387
1388func (p *myDirCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1389 if !args.Empty() {
1390 return ctx.newBadExpr(node, "my-dir function cannot have any arguments passed to it.")
1391 }
Cole Faustf5adedc2022-03-18 14:05:06 -07001392 return &stringLiteralExpr{literal: filepath.Dir(ctx.script.mkFile)}
Cole Faust9ebf6e42021-12-13 14:08:34 -08001393}
1394
Cole Faust9ebf6e42021-12-13 14:08:34 -08001395type isProductInListCallParser struct{}
1396
1397func (p *isProductInListCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1398 if args.Empty() {
1399 return ctx.newBadExpr(node, "is-product-in-list requires an argument")
1400 }
1401 return &inExpr{
Cole Faustf0632662022-04-07 13:59:24 -07001402 expr: NewVariableRefExpr(ctx.addVariable("TARGET_PRODUCT")),
Cole Faust9ebf6e42021-12-13 14:08:34 -08001403 list: maybeConvertToStringList(ctx.parseMakeString(node, args)),
1404 isNot: false,
1405 }
1406}
1407
1408type isVendorBoardPlatformCallParser struct{}
1409
1410func (p *isVendorBoardPlatformCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1411 if args.Empty() || !identifierFullMatchRegex.MatchString(args.Dump()) {
1412 return ctx.newBadExpr(node, "cannot handle non-constant argument to is-vendor-board-platform")
1413 }
1414 return &inExpr{
Cole Faustf0632662022-04-07 13:59:24 -07001415 expr: NewVariableRefExpr(ctx.addVariable("TARGET_BOARD_PLATFORM")),
1416 list: NewVariableRefExpr(ctx.addVariable(args.Dump() + "_BOARD_PLATFORMS")),
Cole Faust9ebf6e42021-12-13 14:08:34 -08001417 isNot: false,
1418 }
1419}
1420
1421type isVendorBoardQcomCallParser struct{}
1422
1423func (p *isVendorBoardQcomCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1424 if !args.Empty() {
1425 return ctx.newBadExpr(node, "is-vendor-board-qcom does not accept any arguments")
1426 }
1427 return &inExpr{
Cole Faustf0632662022-04-07 13:59:24 -07001428 expr: NewVariableRefExpr(ctx.addVariable("TARGET_BOARD_PLATFORM")),
1429 list: NewVariableRefExpr(ctx.addVariable("QCOM_BOARD_PLATFORMS")),
Cole Faust9ebf6e42021-12-13 14:08:34 -08001430 isNot: false,
1431 }
1432}
1433
1434type substCallParser struct {
1435 fname string
1436}
1437
1438func (p *substCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001439 words := args.Split(",")
1440 if len(words) != 3 {
Cole Faust9ebf6e42021-12-13 14:08:34 -08001441 return ctx.newBadExpr(node, "%s function should have 3 arguments", p.fname)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001442 }
Sasha Smundak35434ed2021-11-05 16:29:56 -07001443 from := ctx.parseMakeString(node, words[0])
1444 if xBad, ok := from.(*badExpr); ok {
1445 return xBad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001446 }
Sasha Smundak35434ed2021-11-05 16:29:56 -07001447 to := ctx.parseMakeString(node, words[1])
1448 if xBad, ok := to.(*badExpr); ok {
1449 return xBad
1450 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001451 words[2].TrimLeftSpaces()
1452 words[2].TrimRightSpaces()
1453 obj := ctx.parseMakeString(node, words[2])
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001454 typ := obj.typ()
Cole Faust9ebf6e42021-12-13 14:08:34 -08001455 if typ == starlarkTypeString && p.fname == "subst" {
Sasha Smundak94b41c72021-07-12 18:30:42 -07001456 // Optimization: if it's $(subst from, to, string), emit string.replace(from, to)
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001457 return &callExpr{
1458 object: obj,
1459 name: "replace",
Sasha Smundak35434ed2021-11-05 16:29:56 -07001460 args: []starlarkExpr{from, to},
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001461 returnType: typ,
1462 }
1463 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001464 return &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001465 name: baseName + ".mk" + p.fname,
Sasha Smundak35434ed2021-11-05 16:29:56 -07001466 args: []starlarkExpr{from, to, obj},
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001467 returnType: obj.typ(),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001468 }
1469}
1470
Cole Faust9ebf6e42021-12-13 14:08:34 -08001471type ifCallParser struct{}
1472
1473func (p *ifCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Cole Faust4eadba72021-12-07 11:54:52 -08001474 words := args.Split(",")
1475 if len(words) != 2 && len(words) != 3 {
1476 return ctx.newBadExpr(node, "if function should have 2 or 3 arguments, found "+strconv.Itoa(len(words)))
1477 }
1478 condition := ctx.parseMakeString(node, words[0])
1479 ifTrue := ctx.parseMakeString(node, words[1])
1480 var ifFalse starlarkExpr
1481 if len(words) == 3 {
1482 ifFalse = ctx.parseMakeString(node, words[2])
1483 } else {
1484 switch ifTrue.typ() {
1485 case starlarkTypeList:
1486 ifFalse = &listExpr{items: []starlarkExpr{}}
1487 case starlarkTypeInt:
1488 ifFalse = &intLiteralExpr{literal: 0}
1489 case starlarkTypeBool:
1490 ifFalse = &boolLiteralExpr{literal: false}
1491 default:
1492 ifFalse = &stringLiteralExpr{literal: ""}
1493 }
1494 }
1495 return &ifExpr{
1496 condition,
1497 ifTrue,
1498 ifFalse,
1499 }
1500}
1501
Cole Faustf035d402022-03-28 14:02:50 -07001502type ifCallNodeParser struct{}
Cole Faust9ebf6e42021-12-13 14:08:34 -08001503
Cole Faustf035d402022-03-28 14:02:50 -07001504func (p *ifCallNodeParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode {
1505 words := args.Split(",")
1506 if len(words) != 2 && len(words) != 3 {
1507 return []starlarkNode{ctx.newBadNode(node, "if function should have 2 or 3 arguments, found "+strconv.Itoa(len(words)))}
1508 }
1509
1510 ifn := &ifNode{expr: ctx.parseMakeString(node, words[0])}
1511 cases := []*switchCase{
1512 {
1513 gate: ifn,
1514 nodes: ctx.parseNodeMakeString(node, words[1]),
1515 },
1516 }
1517 if len(words) == 3 {
1518 cases = append(cases, &switchCase{
1519 gate: &elseNode{},
1520 nodes: ctx.parseNodeMakeString(node, words[2]),
1521 })
1522 }
1523 if len(cases) == 2 {
1524 if len(cases[1].nodes) == 0 {
1525 // Remove else branch if it has no contents
1526 cases = cases[:1]
1527 } else if len(cases[0].nodes) == 0 {
1528 // If the if branch has no contents but the else does,
1529 // move them to the if and negate its condition
1530 ifn.expr = negateExpr(ifn.expr)
1531 cases[0].nodes = cases[1].nodes
1532 cases = cases[:1]
1533 }
1534 }
1535
1536 return []starlarkNode{&switchNode{ssCases: cases}}
1537}
1538
1539type foreachCallParser struct{}
1540
1541func (p *foreachCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Cole Faustb0d32ab2021-12-09 14:00:59 -08001542 words := args.Split(",")
1543 if len(words) != 3 {
1544 return ctx.newBadExpr(node, "foreach function should have 3 arguments, found "+strconv.Itoa(len(words)))
1545 }
1546 if !words[0].Const() || words[0].Empty() || !identifierFullMatchRegex.MatchString(words[0].Strings[0]) {
1547 return ctx.newBadExpr(node, "first argument to foreach function must be a simple string identifier")
1548 }
1549 loopVarName := words[0].Strings[0]
1550 list := ctx.parseMakeString(node, words[1])
1551 action := ctx.parseMakeString(node, words[2]).transform(func(expr starlarkExpr) starlarkExpr {
1552 if varRefExpr, ok := expr.(*variableRefExpr); ok && varRefExpr.ref.name() == loopVarName {
1553 return &identifierExpr{loopVarName}
1554 }
1555 return nil
1556 })
1557
1558 if list.typ() != starlarkTypeList {
1559 list = &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001560 name: baseName + ".words",
1561 returnType: starlarkTypeList,
Cole Faustb0d32ab2021-12-09 14:00:59 -08001562 args: []starlarkExpr{list},
1563 }
1564 }
1565
1566 return &foreachExpr{
1567 varName: loopVarName,
1568 list: list,
1569 action: action,
1570 }
1571}
1572
Cole Faustf035d402022-03-28 14:02:50 -07001573func transformNode(node starlarkNode, transformer func(expr starlarkExpr) starlarkExpr) {
1574 switch a := node.(type) {
1575 case *ifNode:
1576 a.expr = a.expr.transform(transformer)
1577 case *switchCase:
1578 transformNode(a.gate, transformer)
1579 for _, n := range a.nodes {
1580 transformNode(n, transformer)
1581 }
1582 case *switchNode:
1583 for _, n := range a.ssCases {
1584 transformNode(n, transformer)
1585 }
1586 case *exprNode:
1587 a.expr = a.expr.transform(transformer)
1588 case *assignmentNode:
1589 a.value = a.value.transform(transformer)
1590 case *foreachNode:
1591 a.list = a.list.transform(transformer)
1592 for _, n := range a.actions {
1593 transformNode(n, transformer)
1594 }
Cole Faust9df1d732022-04-26 16:27:22 -07001595 case *inheritNode:
1596 if b, ok := a.module.(inheritedDynamicModule); ok {
1597 b.path = b.path.transform(transformer)
1598 a.module = b
1599 }
1600 case *includeNode:
1601 if b, ok := a.module.(inheritedDynamicModule); ok {
1602 b.path = b.path.transform(transformer)
1603 a.module = b
1604 }
Cole Faustf035d402022-03-28 14:02:50 -07001605 }
1606}
1607
1608type foreachCallNodeParser struct{}
1609
1610func (p *foreachCallNodeParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode {
1611 words := args.Split(",")
1612 if len(words) != 3 {
1613 return []starlarkNode{ctx.newBadNode(node, "foreach function should have 3 arguments, found "+strconv.Itoa(len(words)))}
1614 }
1615 if !words[0].Const() || words[0].Empty() || !identifierFullMatchRegex.MatchString(words[0].Strings[0]) {
1616 return []starlarkNode{ctx.newBadNode(node, "first argument to foreach function must be a simple string identifier")}
1617 }
1618
1619 loopVarName := words[0].Strings[0]
1620
1621 list := ctx.parseMakeString(node, words[1])
1622 if list.typ() != starlarkTypeList {
1623 list = &callExpr{
1624 name: baseName + ".words",
1625 returnType: starlarkTypeList,
1626 args: []starlarkExpr{list},
1627 }
1628 }
1629
1630 actions := ctx.parseNodeMakeString(node, words[2])
1631 // TODO(colefaust): Replace transforming code with something more elegant
1632 for _, action := range actions {
1633 transformNode(action, func(expr starlarkExpr) starlarkExpr {
1634 if varRefExpr, ok := expr.(*variableRefExpr); ok && varRefExpr.ref.name() == loopVarName {
1635 return &identifierExpr{loopVarName}
1636 }
1637 return nil
1638 })
1639 }
1640
1641 return []starlarkNode{&foreachNode{
1642 varName: loopVarName,
1643 list: list,
1644 actions: actions,
1645 }}
1646}
1647
Cole Faust9ebf6e42021-12-13 14:08:34 -08001648type wordCallParser struct{}
1649
1650func (p *wordCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001651 words := args.Split(",")
1652 if len(words) != 2 {
1653 return ctx.newBadExpr(node, "word function should have 2 arguments")
1654 }
1655 var index uint64 = 0
1656 if words[0].Const() {
1657 index, _ = strconv.ParseUint(strings.TrimSpace(words[0].Strings[0]), 10, 64)
1658 }
1659 if index < 1 {
1660 return ctx.newBadExpr(node, "word index should be constant positive integer")
1661 }
1662 words[1].TrimLeftSpaces()
1663 words[1].TrimRightSpaces()
1664 array := ctx.parseMakeString(node, words[1])
1665 if xBad, ok := array.(*badExpr); ok {
1666 return xBad
1667 }
1668 if array.typ() != starlarkTypeList {
1669 array = &callExpr{object: array, name: "split", returnType: starlarkTypeList}
1670 }
Cole Faustb0d32ab2021-12-09 14:00:59 -08001671 return &indexExpr{array, &intLiteralExpr{int(index - 1)}}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001672}
1673
Cole Faust9ebf6e42021-12-13 14:08:34 -08001674type firstOrLastwordCallParser struct {
1675 isLastWord bool
1676}
1677
1678func (p *firstOrLastwordCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundak16e07732021-07-23 11:38:23 -07001679 arg := ctx.parseMakeString(node, args)
1680 if bad, ok := arg.(*badExpr); ok {
1681 return bad
1682 }
1683 index := &intLiteralExpr{0}
Cole Faust9ebf6e42021-12-13 14:08:34 -08001684 if p.isLastWord {
Sasha Smundak16e07732021-07-23 11:38:23 -07001685 if v, ok := arg.(*variableRefExpr); ok && v.ref.name() == "MAKEFILE_LIST" {
1686 return &stringLiteralExpr{ctx.script.mkFile}
1687 }
1688 index.literal = -1
1689 }
1690 if arg.typ() == starlarkTypeList {
1691 return &indexExpr{arg, index}
1692 }
1693 return &indexExpr{&callExpr{object: arg, name: "split", returnType: starlarkTypeList}, index}
1694}
1695
Cole Faustb1103e22022-01-06 15:22:05 -08001696func parseIntegerArguments(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString, expectedArgs int) ([]starlarkExpr, error) {
1697 parsedArgs := make([]starlarkExpr, 0)
1698 for _, arg := range args.Split(",") {
1699 expr := ctx.parseMakeString(node, arg)
1700 if expr.typ() == starlarkTypeList {
1701 return nil, fmt.Errorf("argument to math argument has type list, which cannot be converted to int")
1702 }
1703 if s, ok := maybeString(expr); ok {
1704 intVal, err := strconv.Atoi(strings.TrimSpace(s))
1705 if err != nil {
1706 return nil, err
1707 }
1708 expr = &intLiteralExpr{literal: intVal}
1709 } else if expr.typ() != starlarkTypeInt {
1710 expr = &callExpr{
1711 name: "int",
1712 args: []starlarkExpr{expr},
1713 returnType: starlarkTypeInt,
1714 }
1715 }
1716 parsedArgs = append(parsedArgs, expr)
1717 }
1718 if len(parsedArgs) != expectedArgs {
1719 return nil, fmt.Errorf("function should have %d arguments", expectedArgs)
1720 }
1721 return parsedArgs, nil
1722}
1723
1724type mathComparisonCallParser struct {
1725 op string
1726}
1727
1728func (p *mathComparisonCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1729 parsedArgs, err := parseIntegerArguments(ctx, node, args, 2)
1730 if err != nil {
1731 return ctx.newBadExpr(node, err.Error())
1732 }
1733 return &binaryOpExpr{
1734 left: parsedArgs[0],
1735 right: parsedArgs[1],
1736 op: p.op,
1737 returnType: starlarkTypeBool,
1738 }
1739}
1740
1741type mathMaxOrMinCallParser struct {
1742 function string
1743}
1744
1745func (p *mathMaxOrMinCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1746 parsedArgs, err := parseIntegerArguments(ctx, node, args, 2)
1747 if err != nil {
1748 return ctx.newBadExpr(node, err.Error())
1749 }
1750 return &callExpr{
1751 object: nil,
1752 name: p.function,
1753 args: parsedArgs,
1754 returnType: starlarkTypeInt,
1755 }
1756}
1757
Cole Faustf035d402022-03-28 14:02:50 -07001758type evalNodeParser struct{}
1759
1760func (p *evalNodeParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode {
1761 parser := mkparser.NewParser("Eval expression", strings.NewReader(args.Dump()))
1762 nodes, errs := parser.Parse()
1763 if errs != nil {
1764 return []starlarkNode{ctx.newBadNode(node, "Unable to parse eval statement")}
1765 }
1766
1767 if len(nodes) == 0 {
1768 return []starlarkNode{}
1769 } else if len(nodes) == 1 {
1770 switch n := nodes[0].(type) {
1771 case *mkparser.Assignment:
1772 if n.Name.Const() {
1773 return ctx.handleAssignment(n)
1774 }
1775 case *mkparser.Comment:
1776 return []starlarkNode{&commentNode{strings.TrimSpace("#" + n.Comment)}}
1777 }
1778 }
1779
1780 return []starlarkNode{ctx.newBadNode(node, "Eval expression too complex; only assignments and comments are supported")}
1781}
1782
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001783func (ctx *parseContext) parseMakeString(node mkparser.Node, mk *mkparser.MakeString) starlarkExpr {
1784 if mk.Const() {
1785 return &stringLiteralExpr{mk.Dump()}
1786 }
1787 if mkRef, ok := mk.SingleVariable(); ok {
1788 return ctx.parseReference(node, mkRef)
1789 }
1790 // If we reached here, it's neither string literal nor a simple variable,
1791 // we need a full-blown interpolation node that will generate
1792 // "a%b%c" % (X, Y) for a$(X)b$(Y)c
Cole Faustfc438682021-12-14 12:46:32 -08001793 parts := make([]starlarkExpr, len(mk.Variables)+len(mk.Strings))
1794 for i := 0; i < len(parts); i++ {
1795 if i%2 == 0 {
1796 parts[i] = &stringLiteralExpr{literal: mk.Strings[i/2]}
1797 } else {
1798 parts[i] = ctx.parseReference(node, mk.Variables[i/2].Name)
1799 if x, ok := parts[i].(*badExpr); ok {
1800 return x
1801 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001802 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001803 }
Cole Faustfc438682021-12-14 12:46:32 -08001804 return NewInterpolateExpr(parts)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001805}
1806
Cole Faustf035d402022-03-28 14:02:50 -07001807func (ctx *parseContext) parseNodeMakeString(node mkparser.Node, mk *mkparser.MakeString) []starlarkNode {
1808 // Discard any constant values in the make string, as they would be top level
1809 // string literals and do nothing.
1810 result := make([]starlarkNode, 0, len(mk.Variables))
1811 for i := range mk.Variables {
1812 result = append(result, ctx.handleVariable(&mk.Variables[i])...)
1813 }
1814 return result
1815}
1816
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001817// Handles the statements whose treatment is the same in all contexts: comment,
1818// assignment, variable (which is a macro call in reality) and all constructs that
1819// do not handle in any context ('define directive and any unrecognized stuff).
Cole Faustdd569ae2022-01-31 15:48:29 -08001820func (ctx *parseContext) handleSimpleStatement(node mkparser.Node) []starlarkNode {
1821 var result []starlarkNode
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001822 switch x := node.(type) {
1823 case *mkparser.Comment:
Cole Faustdd569ae2022-01-31 15:48:29 -08001824 if n, handled := ctx.maybeHandleAnnotation(x); handled && n != nil {
1825 result = []starlarkNode{n}
1826 } else if !handled {
1827 result = []starlarkNode{&commentNode{strings.TrimSpace("#" + x.Comment)}}
Cole Faust7940c6a2022-01-31 15:54:05 -08001828 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001829 case *mkparser.Assignment:
Cole Faustdd569ae2022-01-31 15:48:29 -08001830 result = ctx.handleAssignment(x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001831 case *mkparser.Variable:
Cole Faustdd569ae2022-01-31 15:48:29 -08001832 result = ctx.handleVariable(x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001833 case *mkparser.Directive:
1834 switch x.Name {
1835 case "define":
Cole Faustdd569ae2022-01-31 15:48:29 -08001836 if res := ctx.maybeHandleDefine(x); res != nil {
1837 result = []starlarkNode{res}
1838 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001839 case "include", "-include":
Cole Faustdd569ae2022-01-31 15:48:29 -08001840 result = ctx.handleInclude(node, ctx.parseMakeString(node, x.Args), x.Name[0] != '-')
Cole Faust591a1fe2021-11-08 15:37:57 -08001841 case "ifeq", "ifneq", "ifdef", "ifndef":
Cole Faustdd569ae2022-01-31 15:48:29 -08001842 result = []starlarkNode{ctx.handleIfBlock(x)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001843 default:
Cole Faustdd569ae2022-01-31 15:48:29 -08001844 result = []starlarkNode{ctx.newBadNode(x, "unexpected directive %s", x.Name)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001845 }
1846 default:
Cole Faustdd569ae2022-01-31 15:48:29 -08001847 result = []starlarkNode{ctx.newBadNode(x, "unsupported line %s", strings.ReplaceAll(x.Dump(), "\n", "\n#"))}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001848 }
Cole Faust6c934f62022-01-06 15:51:12 -08001849
1850 // Clear the includeTops after each non-comment statement
1851 // so that include annotations placed on certain statements don't apply
1852 // globally for the rest of the makefile was well.
Cole Faustf92c9f22022-03-14 14:35:50 -07001853 if _, wasComment := node.(*mkparser.Comment); !wasComment {
1854 ctx.atTopOfMakefile = false
Cole Faust6c934f62022-01-06 15:51:12 -08001855 ctx.includeTops = []string{}
1856 }
Cole Faustdd569ae2022-01-31 15:48:29 -08001857
1858 if result == nil {
1859 result = []starlarkNode{}
1860 }
Cole Faustf035d402022-03-28 14:02:50 -07001861
Cole Faustdd569ae2022-01-31 15:48:29 -08001862 return result
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001863}
1864
Cole Faustf92c9f22022-03-14 14:35:50 -07001865// The types allowed in a type_hint
1866var typeHintMap = map[string]starlarkType{
1867 "string": starlarkTypeString,
1868 "list": starlarkTypeList,
1869}
1870
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001871// Processes annotation. An annotation is a comment that starts with #RBC# and provides
1872// a conversion hint -- say, where to look for the dynamically calculated inherit/include
Cole Faust7940c6a2022-01-31 15:54:05 -08001873// paths. Returns true if the comment was a successfully-handled annotation.
Cole Faustdd569ae2022-01-31 15:48:29 -08001874func (ctx *parseContext) maybeHandleAnnotation(cnode *mkparser.Comment) (starlarkNode, bool) {
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001875 maybeTrim := func(s, prefix string) (string, bool) {
1876 if strings.HasPrefix(s, prefix) {
1877 return strings.TrimSpace(strings.TrimPrefix(s, prefix)), true
1878 }
1879 return s, false
1880 }
1881 annotation, ok := maybeTrim(cnode.Comment, annotationCommentPrefix)
1882 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -08001883 return nil, false
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001884 }
1885 if p, ok := maybeTrim(annotation, "include_top"); ok {
Cole Faustf7ed5342021-12-21 14:15:12 -08001886 // Don't allow duplicate include tops, because then we will generate
1887 // invalid starlark code. (duplicate keys in the _entry dictionary)
1888 for _, top := range ctx.includeTops {
1889 if top == p {
Cole Faustdd569ae2022-01-31 15:48:29 -08001890 return nil, true
Cole Faustf7ed5342021-12-21 14:15:12 -08001891 }
1892 }
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001893 ctx.includeTops = append(ctx.includeTops, p)
Cole Faustdd569ae2022-01-31 15:48:29 -08001894 return nil, true
Cole Faustf92c9f22022-03-14 14:35:50 -07001895 } else if p, ok := maybeTrim(annotation, "type_hint"); ok {
1896 // Type hints must come at the beginning the file, to avoid confusion
1897 // if a type hint was specified later and thus only takes effect for half
1898 // of the file.
1899 if !ctx.atTopOfMakefile {
1900 return ctx.newBadNode(cnode, "type_hint annotations must come before the first Makefile statement"), true
1901 }
1902
1903 parts := strings.Fields(p)
1904 if len(parts) <= 1 {
1905 return ctx.newBadNode(cnode, "Invalid type_hint annotation: %s. Must be a variable type followed by a list of variables of that type", p), true
1906 }
1907
1908 var varType starlarkType
1909 if varType, ok = typeHintMap[parts[0]]; !ok {
1910 varType = starlarkTypeUnknown
1911 }
1912 if varType == starlarkTypeUnknown {
1913 return ctx.newBadNode(cnode, "Invalid type_hint annotation. Only list/string types are accepted, found %s", parts[0]), true
1914 }
1915
1916 for _, name := range parts[1:] {
1917 // Don't allow duplicate type hints
1918 if _, ok := ctx.typeHints[name]; ok {
1919 return ctx.newBadNode(cnode, "Duplicate type hint for variable %s", name), true
1920 }
1921 ctx.typeHints[name] = varType
1922 }
1923 return nil, true
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001924 }
Cole Faustdd569ae2022-01-31 15:48:29 -08001925 return ctx.newBadNode(cnode, "unsupported annotation %s", cnode.Comment), true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001926}
1927
1928func (ctx *parseContext) loadedModulePath(path string) string {
1929 // During the transition to Roboleaf some of the product configuration files
1930 // will be converted and checked in while the others will be generated on the fly
1931 // and run. The runner (rbcrun application) accommodates this by allowing three
1932 // different ways to specify the loaded file location:
1933 // 1) load(":<file>",...) loads <file> from the same directory
1934 // 2) load("//path/relative/to/source/root:<file>", ...) loads <file> source tree
1935 // 3) load("/absolute/path/to/<file> absolute path
1936 // If the file being generated and the file it wants to load are in the same directory,
1937 // generate option 1.
1938 // Otherwise, if output directory is not specified, generate 2)
1939 // Finally, if output directory has been specified and the file being generated and
1940 // the file it wants to load from are in the different directories, generate 2) or 3):
1941 // * if the file being loaded exists in the source tree, generate 2)
1942 // * otherwise, generate 3)
1943 // Finally, figure out the loaded module path and name and create a node for it
1944 loadedModuleDir := filepath.Dir(path)
1945 base := filepath.Base(path)
1946 loadedModuleName := strings.TrimSuffix(base, filepath.Ext(base)) + ctx.outputSuffix
1947 if loadedModuleDir == filepath.Dir(ctx.script.mkFile) {
1948 return ":" + loadedModuleName
1949 }
1950 if ctx.outputDir == "" {
1951 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1952 }
1953 if _, err := os.Stat(filepath.Join(loadedModuleDir, loadedModuleName)); err == nil {
1954 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1955 }
1956 return filepath.Join(ctx.outputDir, loadedModuleDir, loadedModuleName)
1957}
1958
Sasha Smundak3deb9682021-07-26 18:42:25 -07001959func (ctx *parseContext) addSoongNamespace(ns string) {
1960 if _, ok := ctx.soongNamespaces[ns]; ok {
1961 return
1962 }
1963 ctx.soongNamespaces[ns] = make(map[string]bool)
1964}
1965
1966func (ctx *parseContext) hasSoongNamespace(name string) bool {
1967 _, ok := ctx.soongNamespaces[name]
1968 return ok
1969}
1970
1971func (ctx *parseContext) updateSoongNamespace(replace bool, namespaceName string, varNames []string) {
1972 ctx.addSoongNamespace(namespaceName)
1973 vars := ctx.soongNamespaces[namespaceName]
1974 if replace {
1975 vars = make(map[string]bool)
1976 ctx.soongNamespaces[namespaceName] = vars
1977 }
1978 for _, v := range varNames {
1979 vars[v] = true
1980 }
1981}
1982
1983func (ctx *parseContext) hasNamespaceVar(namespaceName string, varName string) bool {
1984 vars, ok := ctx.soongNamespaces[namespaceName]
1985 if ok {
1986 _, ok = vars[varName]
1987 }
1988 return ok
1989}
1990
Sasha Smundak422b6142021-11-11 18:31:59 -08001991func (ctx *parseContext) errorLocation(node mkparser.Node) ErrorLocation {
1992 return ErrorLocation{ctx.script.mkFile, ctx.script.nodeLocator(node.Pos())}
1993}
1994
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001995func (ss *StarlarkScript) String() string {
1996 return NewGenerateContext(ss).emit()
1997}
1998
1999func (ss *StarlarkScript) SubConfigFiles() []string {
Sasha Smundak6609ba72021-07-22 18:32:56 -07002000
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002001 var subs []string
2002 for _, src := range ss.inherited {
2003 subs = append(subs, src.originalPath)
2004 }
2005 return subs
2006}
2007
2008func (ss *StarlarkScript) HasErrors() bool {
2009 return ss.hasErrors
2010}
2011
2012// Convert reads and parses a makefile. If successful, parsed tree
2013// is returned and then can be passed to String() to get the generated
2014// Starlark file.
2015func Convert(req Request) (*StarlarkScript, error) {
2016 reader := req.Reader
2017 if reader == nil {
2018 mkContents, err := ioutil.ReadFile(req.MkFile)
2019 if err != nil {
2020 return nil, err
2021 }
2022 reader = bytes.NewBuffer(mkContents)
2023 }
2024 parser := mkparser.NewParser(req.MkFile, reader)
2025 nodes, errs := parser.Parse()
2026 if len(errs) > 0 {
2027 for _, e := range errs {
2028 fmt.Fprintln(os.Stderr, "ERROR:", e)
2029 }
2030 return nil, fmt.Errorf("bad makefile %s", req.MkFile)
2031 }
2032 starScript := &StarlarkScript{
Sasha Smundak422b6142021-11-11 18:31:59 -08002033 moduleName: moduleNameForFile(req.MkFile),
2034 mkFile: req.MkFile,
Sasha Smundak422b6142021-11-11 18:31:59 -08002035 traceCalls: req.TraceCalls,
2036 sourceFS: req.SourceFS,
2037 makefileFinder: req.MakefileFinder,
2038 nodeLocator: func(pos mkparser.Pos) int { return parser.Unpack(pos).Line },
Cole Faustdd569ae2022-01-31 15:48:29 -08002039 nodes: make([]starlarkNode, 0),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002040 }
2041 ctx := newParseContext(starScript, nodes)
2042 ctx.outputSuffix = req.OutputSuffix
2043 ctx.outputDir = req.OutputDir
2044 ctx.errorLogger = req.ErrorLogger
2045 if len(req.TracedVariables) > 0 {
2046 ctx.tracedVariables = make(map[string]bool)
2047 for _, v := range req.TracedVariables {
2048 ctx.tracedVariables[v] = true
2049 }
2050 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002051 for ctx.hasNodes() && ctx.fatalError == nil {
Cole Faustdd569ae2022-01-31 15:48:29 -08002052 starScript.nodes = append(starScript.nodes, ctx.handleSimpleStatement(ctx.getNode())...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002053 }
2054 if ctx.fatalError != nil {
2055 return nil, ctx.fatalError
2056 }
2057 return starScript, nil
2058}
2059
Cole Faust864028a2021-12-01 13:43:17 -08002060func Launcher(mainModuleUri, inputVariablesUri, mainModuleName string) string {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002061 var buf bytes.Buffer
2062 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
Cole Faust864028a2021-12-01 13:43:17 -08002063 fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri)
Sasha Smundakd7d07ad2021-09-10 15:42:34 -07002064 fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri)
Cole Faust864028a2021-12-01 13:43:17 -08002065 fmt.Fprintf(&buf, "%s(%s(%q, init, input_variables_init))\n", cfnPrintVars, cfnMain, mainModuleName)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002066 return buf.String()
2067}
2068
Cole Faust6ed7cb42021-10-07 17:08:46 -07002069func BoardLauncher(mainModuleUri string, inputVariablesUri string) string {
2070 var buf bytes.Buffer
2071 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
2072 fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri)
2073 fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri)
Cole Fausta0604662022-02-28 11:53:58 -08002074 fmt.Fprintf(&buf, "%s(%s(init, input_variables_init))\n", cfnPrintVars, cfnBoardMain)
Cole Faust6ed7cb42021-10-07 17:08:46 -07002075 return buf.String()
2076}
2077
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002078func MakePath2ModuleName(mkPath string) string {
2079 return strings.TrimSuffix(mkPath, filepath.Ext(mkPath))
2080}