blob: 073c2ed8f9742b76d0fdc411533f9483a6cf7868 [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 Faust1e275862022-04-26 14:28:04 -0700133// These look like variables, but are actually functions, and would give
134// undefined variable errors if we converted them as variables. Instead,
135// emit an error instead of converting them.
136var unsupportedFunctions = map[string]bool{
137 "local-generated-sources-dir": true,
138 "local-intermediates-dir": true,
139}
140
Cole Faust9ebf6e42021-12-13 14:08:34 -0800141// These are functions that we don't implement conversions for, but
142// we allow seeing their definitions in the product config files.
143var ignoredDefines = map[string]bool{
144 "find-word-in-list": true, // internal macro
145 "get-vendor-board-platforms": true, // internal macro, used by is-board-platform, etc.
146 "is-android-codename": true, // unused by product config
147 "is-android-codename-in-list": true, // unused by product config
148 "is-chipset-in-board-platform": true, // unused by product config
149 "is-chipset-prefix-in-board-platform": true, // unused by product config
150 "is-not-board-platform": true, // defined but never used
151 "is-platform-sdk-version-at-least": true, // unused by product config
152 "match-prefix": true, // internal macro
153 "match-word": true, // internal macro
154 "match-word-in-list": true, // internal macro
155 "tb-modules": true, // defined in hardware/amlogic/tb_modules/tb_detect.mk, unused
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800156}
157
Cole Faustb0d32ab2021-12-09 14:00:59 -0800158var identifierFullMatchRegex = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$")
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800159
160// Conversion request parameters
161type Request struct {
Sasha Smundak422b6142021-11-11 18:31:59 -0800162 MkFile string // file to convert
163 Reader io.Reader // if set, read input from this stream instead
Sasha Smundak422b6142021-11-11 18:31:59 -0800164 OutputSuffix string // generated Starlark files suffix
165 OutputDir string // if set, root of the output hierarchy
166 ErrorLogger ErrorLogger
167 TracedVariables []string // trace assignment to these variables
168 TraceCalls bool
169 SourceFS fs.FS
170 MakefileFinder MakefileFinder
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800171}
172
Sasha Smundak7d934b92021-11-10 12:20:01 -0800173// ErrorLogger prints errors and gathers error statistics.
174// Its NewError function is called on every error encountered during the conversion.
175type ErrorLogger interface {
Sasha Smundak422b6142021-11-11 18:31:59 -0800176 NewError(el ErrorLocation, node mkparser.Node, text string, args ...interface{})
177}
178
179type ErrorLocation struct {
180 MkFile string
181 MkLine int
182}
183
184func (el ErrorLocation) String() string {
185 return fmt.Sprintf("%s:%d", el.MkFile, el.MkLine)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800186}
187
188// Derives module name for a given file. It is base name
189// (file name without suffix), with some characters replaced to make it a Starlark identifier
190func moduleNameForFile(mkFile string) string {
191 base := strings.TrimSuffix(filepath.Base(mkFile), filepath.Ext(mkFile))
192 // TODO(asmundak): what else can be in the product file names?
Sasha Smundak6609ba72021-07-22 18:32:56 -0700193 return strings.NewReplacer("-", "_", ".", "_").Replace(base)
194
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800195}
196
197func cloneMakeString(mkString *mkparser.MakeString) *mkparser.MakeString {
198 r := &mkparser.MakeString{StringPos: mkString.StringPos}
199 r.Strings = append(r.Strings, mkString.Strings...)
200 r.Variables = append(r.Variables, mkString.Variables...)
201 return r
202}
203
204func isMakeControlFunc(s string) bool {
205 return s == "error" || s == "warning" || s == "info"
206}
207
Cole Faustf0632662022-04-07 13:59:24 -0700208// varAssignmentScope points to the last assignment for each variable
209// in the current block. It is used during the parsing to chain
210// the assignments to a variable together.
211type varAssignmentScope struct {
212 outer *varAssignmentScope
213 vars map[string]bool
214}
215
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800216// Starlark output generation context
217type generationContext struct {
Cole Faustf0632662022-04-07 13:59:24 -0700218 buf strings.Builder
219 starScript *StarlarkScript
220 indentLevel int
221 inAssignment bool
222 tracedCount int
223 varAssignments *varAssignmentScope
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800224}
225
226func NewGenerateContext(ss *StarlarkScript) *generationContext {
Cole Faustf0632662022-04-07 13:59:24 -0700227 return &generationContext{
228 starScript: ss,
229 varAssignments: &varAssignmentScope{
230 outer: nil,
231 vars: make(map[string]bool),
232 },
233 }
234}
235
236func (gctx *generationContext) pushVariableAssignments() {
237 va := &varAssignmentScope{
238 outer: gctx.varAssignments,
239 vars: make(map[string]bool),
240 }
241 gctx.varAssignments = va
242}
243
244func (gctx *generationContext) popVariableAssignments() {
245 gctx.varAssignments = gctx.varAssignments.outer
246}
247
248func (gctx *generationContext) hasBeenAssigned(v variable) bool {
249 for va := gctx.varAssignments; va != nil; va = va.outer {
250 if _, ok := va.vars[v.name()]; ok {
251 return true
252 }
253 }
254 return false
255}
256
257func (gctx *generationContext) setHasBeenAssigned(v variable) {
258 gctx.varAssignments.vars[v.name()] = true
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800259}
260
261// emit returns generated script
262func (gctx *generationContext) emit() string {
263 ss := gctx.starScript
264
265 // The emitted code has the following layout:
266 // <initial comments>
267 // preamble, i.e.,
268 // load statement for the runtime support
269 // load statement for each unique submodule pulled in by this one
270 // def init(g, handle):
271 // cfg = rblf.cfg(handle)
272 // <statements>
273 // <warning if conversion was not clean>
274
275 iNode := len(ss.nodes)
276 for i, node := range ss.nodes {
277 if _, ok := node.(*commentNode); !ok {
278 iNode = i
279 break
280 }
281 node.emit(gctx)
282 }
283
284 gctx.emitPreamble()
285
286 gctx.newLine()
287 // The arguments passed to the init function are the global dictionary
288 // ('g') and the product configuration dictionary ('cfg')
289 gctx.write("def init(g, handle):")
290 gctx.indentLevel++
291 if gctx.starScript.traceCalls {
292 gctx.newLine()
293 gctx.writef(`print(">%s")`, gctx.starScript.mkFile)
294 }
295 gctx.newLine()
296 gctx.writef("cfg = %s(handle)", cfnGetCfg)
297 for _, node := range ss.nodes[iNode:] {
298 node.emit(gctx)
299 }
300
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800301 if gctx.starScript.traceCalls {
302 gctx.newLine()
303 gctx.writef(`print("<%s")`, gctx.starScript.mkFile)
304 }
305 gctx.indentLevel--
306 gctx.write("\n")
307 return gctx.buf.String()
308}
309
310func (gctx *generationContext) emitPreamble() {
311 gctx.newLine()
312 gctx.writef("load(%q, %q)", baseUri, baseName)
313 // Emit exactly one load statement for each URI.
314 loadedSubConfigs := make(map[string]string)
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800315 for _, mi := range gctx.starScript.inherited {
316 uri := mi.path
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800317 if m, ok := loadedSubConfigs[uri]; ok {
318 // No need to emit load statement, but fix module name.
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800319 mi.moduleLocalName = m
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800320 continue
321 }
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800322 if mi.optional || mi.missing {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800323 uri += "|init"
324 }
325 gctx.newLine()
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800326 gctx.writef("load(%q, %s = \"init\")", uri, mi.entryName())
327 loadedSubConfigs[uri] = mi.moduleLocalName
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800328 }
329 gctx.write("\n")
330}
331
332func (gctx *generationContext) emitPass() {
333 gctx.newLine()
334 gctx.write("pass")
335}
336
337func (gctx *generationContext) write(ss ...string) {
338 for _, s := range ss {
339 gctx.buf.WriteString(s)
340 }
341}
342
343func (gctx *generationContext) writef(format string, args ...interface{}) {
344 gctx.write(fmt.Sprintf(format, args...))
345}
346
347func (gctx *generationContext) newLine() {
348 if gctx.buf.Len() == 0 {
349 return
350 }
351 gctx.write("\n")
352 gctx.writef("%*s", 2*gctx.indentLevel, "")
353}
354
Sasha Smundak422b6142021-11-11 18:31:59 -0800355func (gctx *generationContext) emitConversionError(el ErrorLocation, message string) {
356 gctx.writef(`rblf.mk2rbc_error("%s", %q)`, el, message)
357}
358
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800359func (gctx *generationContext) emitLoadCheck(im inheritedModule) {
360 if !im.needsLoadCheck() {
361 return
362 }
363 gctx.newLine()
364 gctx.writef("if not %s:", im.entryName())
365 gctx.indentLevel++
366 gctx.newLine()
367 gctx.write(`rblf.mkerror("`, gctx.starScript.mkFile, `", "Cannot find %s" % (`)
368 im.pathExpr().emit(gctx)
369 gctx.write("))")
370 gctx.indentLevel--
371}
372
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800373type knownVariable struct {
374 name string
375 class varClass
376 valueType starlarkType
377}
378
379type knownVariables map[string]knownVariable
380
381func (pcv knownVariables) NewVariable(name string, varClass varClass, valueType starlarkType) {
382 v, exists := pcv[name]
383 if !exists {
384 pcv[name] = knownVariable{name, varClass, valueType}
385 return
386 }
387 // Conflict resolution:
388 // * config class trumps everything
389 // * any type trumps unknown type
390 match := varClass == v.class
391 if !match {
392 if varClass == VarClassConfig {
393 v.class = VarClassConfig
394 match = true
395 } else if v.class == VarClassConfig {
396 match = true
397 }
398 }
399 if valueType != v.valueType {
400 if valueType != starlarkTypeUnknown {
401 if v.valueType == starlarkTypeUnknown {
402 v.valueType = valueType
403 } else {
404 match = false
405 }
406 }
407 }
408 if !match {
409 fmt.Fprintf(os.Stderr, "cannot redefine %s as %v/%v (already defined as %v/%v)\n",
410 name, varClass, valueType, v.class, v.valueType)
411 }
412}
413
414// All known product variables.
415var KnownVariables = make(knownVariables)
416
417func init() {
418 for _, kv := range []string{
419 // Kernel-related variables that we know are lists.
420 "BOARD_VENDOR_KERNEL_MODULES",
421 "BOARD_VENDOR_RAMDISK_KERNEL_MODULES",
422 "BOARD_VENDOR_RAMDISK_KERNEL_MODULES_LOAD",
423 "BOARD_RECOVERY_KERNEL_MODULES",
424 // Other variables we knwo are lists
425 "ART_APEX_JARS",
426 } {
427 KnownVariables.NewVariable(kv, VarClassSoong, starlarkTypeList)
428 }
429}
430
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800431// Information about the generated Starlark script.
432type StarlarkScript struct {
Sasha Smundak422b6142021-11-11 18:31:59 -0800433 mkFile string
434 moduleName string
435 mkPos scanner.Position
436 nodes []starlarkNode
437 inherited []*moduleInfo
438 hasErrors bool
Sasha Smundak422b6142021-11-11 18:31:59 -0800439 traceCalls bool // print enter/exit each init function
440 sourceFS fs.FS
441 makefileFinder MakefileFinder
442 nodeLocator func(pos mkparser.Pos) int
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800443}
444
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800445// parseContext holds the script we are generating and all the ephemeral data
446// needed during the parsing.
447type parseContext struct {
448 script *StarlarkScript
449 nodes []mkparser.Node // Makefile as parsed by mkparser
450 currentNodeIndex int // Node in it we are processing
451 ifNestLevel int
452 moduleNameCount map[string]int // count of imported modules with given basename
453 fatalError error
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800454 outputSuffix string
Sasha Smundak7d934b92021-11-10 12:20:01 -0800455 errorLogger ErrorLogger
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800456 tracedVariables map[string]bool // variables to be traced in the generated script
457 variables map[string]variable
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800458 outputDir string
Sasha Smundak6609ba72021-07-22 18:32:56 -0700459 dependentModules map[string]*moduleInfo
Sasha Smundak3deb9682021-07-26 18:42:25 -0700460 soongNamespaces map[string]map[string]bool
Sasha Smundak6d852dd2021-09-27 20:34:39 -0700461 includeTops []string
Cole Faustf92c9f22022-03-14 14:35:50 -0700462 typeHints map[string]starlarkType
463 atTopOfMakefile bool
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800464}
465
466func newParseContext(ss *StarlarkScript, nodes []mkparser.Node) *parseContext {
467 predefined := []struct{ name, value string }{
468 {"SRC_TARGET_DIR", filepath.Join("build", "make", "target")},
469 {"LOCAL_PATH", filepath.Dir(ss.mkFile)},
Cole Faust9b6111a2022-02-02 15:38:33 -0800470 {"TOPDIR", ""}, // TOPDIR is just set to an empty string in cleanbuild.mk and core.mk
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800471 // TODO(asmundak): maybe read it from build/make/core/envsetup.mk?
472 {"TARGET_COPY_OUT_SYSTEM", "system"},
473 {"TARGET_COPY_OUT_SYSTEM_OTHER", "system_other"},
474 {"TARGET_COPY_OUT_DATA", "data"},
475 {"TARGET_COPY_OUT_ASAN", filepath.Join("data", "asan")},
476 {"TARGET_COPY_OUT_OEM", "oem"},
477 {"TARGET_COPY_OUT_RAMDISK", "ramdisk"},
478 {"TARGET_COPY_OUT_DEBUG_RAMDISK", "debug_ramdisk"},
479 {"TARGET_COPY_OUT_VENDOR_DEBUG_RAMDISK", "vendor_debug_ramdisk"},
480 {"TARGET_COPY_OUT_TEST_HARNESS_RAMDISK", "test_harness_ramdisk"},
481 {"TARGET_COPY_OUT_ROOT", "root"},
482 {"TARGET_COPY_OUT_RECOVERY", "recovery"},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800483 {"TARGET_COPY_OUT_VENDOR_RAMDISK", "vendor_ramdisk"},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800484 // TODO(asmundak): to process internal config files, we need the following variables:
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800485 // TARGET_VENDOR
486 // target_base_product
487 //
488
489 // the following utility variables are set in build/make/common/core.mk:
490 {"empty", ""},
491 {"space", " "},
492 {"comma", ","},
493 {"newline", "\n"},
494 {"pound", "#"},
495 {"backslash", "\\"},
496 }
497 ctx := &parseContext{
498 script: ss,
499 nodes: nodes,
500 currentNodeIndex: 0,
501 ifNestLevel: 0,
502 moduleNameCount: make(map[string]int),
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800503 variables: make(map[string]variable),
Sasha Smundak6609ba72021-07-22 18:32:56 -0700504 dependentModules: make(map[string]*moduleInfo),
Sasha Smundak3deb9682021-07-26 18:42:25 -0700505 soongNamespaces: make(map[string]map[string]bool),
Cole Faust6c934f62022-01-06 15:51:12 -0800506 includeTops: []string{},
Cole Faustf92c9f22022-03-14 14:35:50 -0700507 typeHints: make(map[string]starlarkType),
508 atTopOfMakefile: true,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800509 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800510 for _, item := range predefined {
511 ctx.variables[item.name] = &predefinedVariable{
512 baseVariable: baseVariable{nam: item.name, typ: starlarkTypeString},
513 value: &stringLiteralExpr{item.value},
514 }
515 }
516
517 return ctx
518}
519
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800520func (ctx *parseContext) hasNodes() bool {
521 return ctx.currentNodeIndex < len(ctx.nodes)
522}
523
524func (ctx *parseContext) getNode() mkparser.Node {
525 if !ctx.hasNodes() {
526 return nil
527 }
528 node := ctx.nodes[ctx.currentNodeIndex]
529 ctx.currentNodeIndex++
530 return node
531}
532
533func (ctx *parseContext) backNode() {
534 if ctx.currentNodeIndex <= 0 {
535 panic("Cannot back off")
536 }
537 ctx.currentNodeIndex--
538}
539
Cole Faustdd569ae2022-01-31 15:48:29 -0800540func (ctx *parseContext) handleAssignment(a *mkparser.Assignment) []starlarkNode {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800541 // Handle only simple variables
542 if !a.Name.Const() {
Cole Faustdd569ae2022-01-31 15:48:29 -0800543 return []starlarkNode{ctx.newBadNode(a, "Only simple variables are handled")}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800544 }
545 name := a.Name.Strings[0]
Sasha Smundakea3bc3a2021-11-10 13:06:42 -0800546 // The `override` directive
547 // override FOO :=
548 // is parsed as an assignment to a variable named `override FOO`.
549 // There are very few places where `override` is used, just flag it.
550 if strings.HasPrefix(name, "override ") {
Cole Faustdd569ae2022-01-31 15:48:29 -0800551 return []starlarkNode{ctx.newBadNode(a, "cannot handle override directive")}
Sasha Smundakea3bc3a2021-11-10 13:06:42 -0800552 }
553
Cole Faustc00184e2021-11-08 12:08:57 -0800554 // Soong configuration
Sasha Smundak3deb9682021-07-26 18:42:25 -0700555 if strings.HasPrefix(name, soongNsPrefix) {
Cole Faustdd569ae2022-01-31 15:48:29 -0800556 return ctx.handleSoongNsAssignment(strings.TrimPrefix(name, soongNsPrefix), a)
Sasha Smundak3deb9682021-07-26 18:42:25 -0700557 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800558 lhs := ctx.addVariable(name)
559 if lhs == nil {
Cole Faustdd569ae2022-01-31 15:48:29 -0800560 return []starlarkNode{ctx.newBadNode(a, "unknown variable %s", name)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800561 }
Cole Faust3c4fc992022-02-28 16:05:01 -0800562 _, isTraced := ctx.tracedVariables[lhs.name()]
Sasha Smundak422b6142021-11-11 18:31:59 -0800563 asgn := &assignmentNode{lhs: lhs, mkValue: a.Value, isTraced: isTraced, location: ctx.errorLocation(a)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800564 if lhs.valueType() == starlarkTypeUnknown {
565 // Try to divine variable type from the RHS
566 asgn.value = ctx.parseMakeString(a, a.Value)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800567 inferred_type := asgn.value.typ()
568 if inferred_type != starlarkTypeUnknown {
Sasha Smundak9d011ab2021-07-09 16:00:57 -0700569 lhs.setValueType(inferred_type)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800570 }
571 }
572 if lhs.valueType() == starlarkTypeList {
Cole Faustdd569ae2022-01-31 15:48:29 -0800573 xConcat, xBad := ctx.buildConcatExpr(a)
574 if xBad != nil {
Cole Faust1e275862022-04-26 14:28:04 -0700575 asgn.value = xBad
576 } else {
577 switch len(xConcat.items) {
578 case 0:
579 asgn.value = &listExpr{}
580 case 1:
581 asgn.value = xConcat.items[0]
582 default:
583 asgn.value = xConcat
584 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800585 }
586 } else {
587 asgn.value = ctx.parseMakeString(a, a.Value)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800588 }
589
Cole Faust421a1922022-03-16 14:35:45 -0700590 if asgn.lhs.valueType() == starlarkTypeString &&
591 asgn.value.typ() != starlarkTypeUnknown &&
592 asgn.value.typ() != starlarkTypeString {
593 asgn.value = &toStringExpr{expr: asgn.value}
594 }
595
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800596 switch a.Type {
597 case "=", ":=":
598 asgn.flavor = asgnSet
599 case "+=":
Cole Fauste2a37982022-03-09 16:00:17 -0800600 asgn.flavor = asgnAppend
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800601 case "?=":
602 asgn.flavor = asgnMaybeSet
603 default:
604 panic(fmt.Errorf("unexpected assignment type %s", a.Type))
605 }
606
Cole Faustdd569ae2022-01-31 15:48:29 -0800607 return []starlarkNode{asgn}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800608}
609
Cole Faustdd569ae2022-01-31 15:48:29 -0800610func (ctx *parseContext) handleSoongNsAssignment(name string, asgn *mkparser.Assignment) []starlarkNode {
Sasha Smundak3deb9682021-07-26 18:42:25 -0700611 val := ctx.parseMakeString(asgn, asgn.Value)
612 if xBad, ok := val.(*badExpr); ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800613 return []starlarkNode{&exprNode{expr: xBad}}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700614 }
Sasha Smundak3deb9682021-07-26 18:42:25 -0700615
616 // Unfortunately, Soong namespaces can be set up by directly setting corresponding Make
617 // variables instead of via add_soong_config_namespace + add_soong_config_var_value.
618 // Try to divine the call from the assignment as follows:
619 if name == "NAMESPACES" {
620 // Upon seeng
621 // SOONG_CONFIG_NAMESPACES += foo
622 // remember that there is a namespace `foo` and act as we saw
623 // $(call add_soong_config_namespace,foo)
624 s, ok := maybeString(val)
625 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800626 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 -0700627 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800628 result := make([]starlarkNode, 0)
Sasha Smundak3deb9682021-07-26 18:42:25 -0700629 for _, ns := range strings.Fields(s) {
630 ctx.addSoongNamespace(ns)
Cole Faustdd569ae2022-01-31 15:48:29 -0800631 result = append(result, &exprNode{&callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -0800632 name: baseName + ".soong_config_namespace",
633 args: []starlarkExpr{&globalsExpr{}, &stringLiteralExpr{ns}},
Sasha Smundak3deb9682021-07-26 18:42:25 -0700634 returnType: starlarkTypeVoid,
635 }})
636 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800637 return result
Sasha Smundak3deb9682021-07-26 18:42:25 -0700638 } else {
639 // Upon seeing
640 // SOONG_CONFIG_x_y = v
641 // find a namespace called `x` and act as if we encountered
Cole Faustc00184e2021-11-08 12:08:57 -0800642 // $(call soong_config_set,x,y,v)
Sasha Smundak3deb9682021-07-26 18:42:25 -0700643 // or check that `x_y` is a namespace, and then add the RHS of this assignment as variables in
644 // it.
645 // Emit an error in the ambiguous situation (namespaces `foo_bar` with a variable `baz`
646 // and `foo` with a variable `bar_baz`.
647 namespaceName := ""
648 if ctx.hasSoongNamespace(name) {
649 namespaceName = name
650 }
651 var varName string
652 for pos, ch := range name {
653 if !(ch == '_' && ctx.hasSoongNamespace(name[0:pos])) {
654 continue
655 }
656 if namespaceName != "" {
Cole Faustdd569ae2022-01-31 15:48:29 -0800657 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 -0700658 }
659 namespaceName = name[0:pos]
660 varName = name[pos+1:]
661 }
662 if namespaceName == "" {
Cole Faustdd569ae2022-01-31 15:48:29 -0800663 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 -0700664 }
665 if varName == "" {
666 // Remember variables in this namespace
667 s, ok := maybeString(val)
668 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800669 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 -0700670 }
671 ctx.updateSoongNamespace(asgn.Type != "+=", namespaceName, strings.Fields(s))
Cole Faustdd569ae2022-01-31 15:48:29 -0800672 return []starlarkNode{}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700673 }
674
675 // Finally, handle assignment to a namespace variable
676 if !ctx.hasNamespaceVar(namespaceName, varName) {
Cole Faustdd569ae2022-01-31 15:48:29 -0800677 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 -0700678 }
Cole Faust9ebf6e42021-12-13 14:08:34 -0800679 fname := baseName + "." + soongConfigAssign
Sasha Smundak65b547e2021-09-17 15:35:41 -0700680 if asgn.Type == "+=" {
Cole Faust9ebf6e42021-12-13 14:08:34 -0800681 fname = baseName + "." + soongConfigAppend
Sasha Smundak65b547e2021-09-17 15:35:41 -0700682 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800683 return []starlarkNode{&exprNode{&callExpr{
Sasha Smundak65b547e2021-09-17 15:35:41 -0700684 name: fname,
Cole Faust9ebf6e42021-12-13 14:08:34 -0800685 args: []starlarkExpr{&globalsExpr{}, &stringLiteralExpr{namespaceName}, &stringLiteralExpr{varName}, val},
Sasha Smundak3deb9682021-07-26 18:42:25 -0700686 returnType: starlarkTypeVoid,
Cole Faustdd569ae2022-01-31 15:48:29 -0800687 }}}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700688 }
689}
690
Cole Faustdd569ae2022-01-31 15:48:29 -0800691func (ctx *parseContext) buildConcatExpr(a *mkparser.Assignment) (*concatExpr, *badExpr) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800692 xConcat := &concatExpr{}
693 var xItemList *listExpr
694 addToItemList := func(x ...starlarkExpr) {
695 if xItemList == nil {
696 xItemList = &listExpr{[]starlarkExpr{}}
697 }
698 xItemList.items = append(xItemList.items, x...)
699 }
700 finishItemList := func() {
701 if xItemList != nil {
702 xConcat.items = append(xConcat.items, xItemList)
703 xItemList = nil
704 }
705 }
706
707 items := a.Value.Words()
708 for _, item := range items {
709 // A function call in RHS is supposed to return a list, all other item
710 // expressions return individual elements.
711 switch x := ctx.parseMakeString(a, item).(type) {
712 case *badExpr:
Cole Faustdd569ae2022-01-31 15:48:29 -0800713 return nil, x
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800714 case *stringLiteralExpr:
715 addToItemList(maybeConvertToStringList(x).(*listExpr).items...)
716 default:
717 switch x.typ() {
718 case starlarkTypeList:
719 finishItemList()
720 xConcat.items = append(xConcat.items, x)
721 case starlarkTypeString:
722 finishItemList()
723 xConcat.items = append(xConcat.items, &callExpr{
724 object: x,
725 name: "split",
726 args: nil,
727 returnType: starlarkTypeList,
728 })
729 default:
730 addToItemList(x)
731 }
732 }
733 }
734 if xItemList != nil {
735 xConcat.items = append(xConcat.items, xItemList)
736 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800737 return xConcat, nil
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800738}
739
Sasha Smundak6609ba72021-07-22 18:32:56 -0700740func (ctx *parseContext) newDependentModule(path string, optional bool) *moduleInfo {
741 modulePath := ctx.loadedModulePath(path)
742 if mi, ok := ctx.dependentModules[modulePath]; ok {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700743 mi.optional = mi.optional && optional
Sasha Smundak6609ba72021-07-22 18:32:56 -0700744 return mi
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800745 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800746 moduleName := moduleNameForFile(path)
747 moduleLocalName := "_" + moduleName
748 n, found := ctx.moduleNameCount[moduleName]
749 if found {
750 moduleLocalName += fmt.Sprintf("%d", n)
751 }
752 ctx.moduleNameCount[moduleName] = n + 1
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800753 _, err := fs.Stat(ctx.script.sourceFS, path)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700754 mi := &moduleInfo{
755 path: modulePath,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800756 originalPath: path,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800757 moduleLocalName: moduleLocalName,
Sasha Smundak6609ba72021-07-22 18:32:56 -0700758 optional: optional,
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800759 missing: err != nil,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800760 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700761 ctx.dependentModules[modulePath] = mi
762 ctx.script.inherited = append(ctx.script.inherited, mi)
763 return mi
764}
765
766func (ctx *parseContext) handleSubConfig(
Cole Faustdd569ae2022-01-31 15:48:29 -0800767 v mkparser.Node, pathExpr starlarkExpr, loadAlways bool, processModule func(inheritedModule) starlarkNode) []starlarkNode {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700768
Cole Faust62e05112022-04-05 17:56:11 -0700769 // Allow seeing $(sort $(wildcard realPathExpr)) or $(wildcard realPathExpr)
770 // because those are functionally the same as not having the sort/wildcard calls.
771 if ce, ok := pathExpr.(*callExpr); ok && ce.name == "rblf.mksort" && len(ce.args) == 1 {
772 if ce2, ok2 := ce.args[0].(*callExpr); ok2 && ce2.name == "rblf.expand_wildcard" && len(ce2.args) == 1 {
773 pathExpr = ce2.args[0]
774 }
775 } else if ce2, ok2 := pathExpr.(*callExpr); ok2 && ce2.name == "rblf.expand_wildcard" && len(ce2.args) == 1 {
776 pathExpr = ce2.args[0]
777 }
778
Sasha Smundak6609ba72021-07-22 18:32:56 -0700779 // In a simple case, the name of a module to inherit/include is known statically.
780 if path, ok := maybeString(pathExpr); ok {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700781 // Note that even if this directive loads a module unconditionally, a module may be
782 // absent without causing any harm if this directive is inside an if/else block.
783 moduleShouldExist := loadAlways && ctx.ifNestLevel == 0
Sasha Smundak6609ba72021-07-22 18:32:56 -0700784 if strings.Contains(path, "*") {
785 if paths, err := fs.Glob(ctx.script.sourceFS, path); err == nil {
Cole Faust62e05112022-04-05 17:56:11 -0700786 sort.Strings(paths)
Cole Faustdd569ae2022-01-31 15:48:29 -0800787 result := make([]starlarkNode, 0)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700788 for _, p := range paths {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700789 mi := ctx.newDependentModule(p, !moduleShouldExist)
Cole Faustdd569ae2022-01-31 15:48:29 -0800790 result = append(result, processModule(inheritedStaticModule{mi, loadAlways}))
Sasha Smundak6609ba72021-07-22 18:32:56 -0700791 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800792 return result
Sasha Smundak6609ba72021-07-22 18:32:56 -0700793 } else {
Cole Faustdd569ae2022-01-31 15:48:29 -0800794 return []starlarkNode{ctx.newBadNode(v, "cannot glob wildcard argument")}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700795 }
796 } else {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700797 mi := ctx.newDependentModule(path, !moduleShouldExist)
Cole Faustdd569ae2022-01-31 15:48:29 -0800798 return []starlarkNode{processModule(inheritedStaticModule{mi, loadAlways})}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700799 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700800 }
801
802 // If module path references variables (e.g., $(v1)/foo/$(v2)/device-config.mk), find all the paths in the
803 // source tree that may be a match and the corresponding variable values. For instance, if the source tree
804 // contains vendor1/foo/abc/dev.mk and vendor2/foo/def/dev.mk, the first one will be inherited when
805 // (v1, v2) == ('vendor1', 'abc'), and the second one when (v1, v2) == ('vendor2', 'def').
806 // We then emit the code that loads all of them, e.g.:
807 // load("//vendor1/foo/abc:dev.rbc", _dev1_init="init")
808 // load("//vendor2/foo/def/dev.rbc", _dev2_init="init")
809 // And then inherit it as follows:
810 // _e = {
811 // "vendor1/foo/abc/dev.mk": ("vendor1/foo/abc/dev", _dev1_init),
812 // "vendor2/foo/def/dev.mk": ("vendor2/foo/def/dev", _dev_init2) }.get("%s/foo/%s/dev.mk" % (v1, v2))
813 // if _e:
814 // rblf.inherit(handle, _e[0], _e[1])
815 //
816 var matchingPaths []string
817 varPath, ok := pathExpr.(*interpolateExpr)
818 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800819 return []starlarkNode{ctx.newBadNode(v, "inherit-product/include argument is too complex")}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700820 }
821
822 pathPattern := []string{varPath.chunks[0]}
823 for _, chunk := range varPath.chunks[1:] {
824 if chunk != "" {
825 pathPattern = append(pathPattern, chunk)
826 }
827 }
Cole Faust069aba62022-01-26 17:47:33 -0800828 if pathPattern[0] == "" && len(ctx.includeTops) > 0 {
Sasha Smundak6d852dd2021-09-27 20:34:39 -0700829 // If pattern starts from the top. restrict it to the directories where
830 // we know inherit-product uses dynamically calculated path.
831 for _, p := range ctx.includeTops {
832 pathPattern[0] = p
833 matchingPaths = append(matchingPaths, ctx.findMatchingPaths(pathPattern)...)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700834 }
Sasha Smundak6d852dd2021-09-27 20:34:39 -0700835 } else {
836 matchingPaths = ctx.findMatchingPaths(pathPattern)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700837 }
838 // Safeguard against $(call inherit-product,$(PRODUCT_PATH))
Sasha Smundak90be8c52021-08-03 11:06:10 -0700839 const maxMatchingFiles = 150
Sasha Smundak6609ba72021-07-22 18:32:56 -0700840 if len(matchingPaths) > maxMatchingFiles {
Cole Faustdd569ae2022-01-31 15:48:29 -0800841 return []starlarkNode{ctx.newBadNode(v, "there are >%d files matching the pattern, please rewrite it", maxMatchingFiles)}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700842 }
Cole Faust93f8d392022-03-02 13:31:30 -0800843
844 needsWarning := pathPattern[0] == "" && len(ctx.includeTops) == 0
845 res := inheritedDynamicModule{*varPath, []*moduleInfo{}, loadAlways, ctx.errorLocation(v), needsWarning}
846 for _, p := range matchingPaths {
847 // A product configuration files discovered dynamically may attempt to inherit
848 // from another one which does not exist in this source tree. Prevent load errors
849 // by always loading the dynamic files as optional.
850 res.candidateModules = append(res.candidateModules, ctx.newDependentModule(p, true))
Sasha Smundak6609ba72021-07-22 18:32:56 -0700851 }
Cole Faust93f8d392022-03-02 13:31:30 -0800852 return []starlarkNode{processModule(res)}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700853}
854
855func (ctx *parseContext) findMatchingPaths(pattern []string) []string {
Cole Faust9b6111a2022-02-02 15:38:33 -0800856 files := ctx.script.makefileFinder.Find(".")
Sasha Smundak6609ba72021-07-22 18:32:56 -0700857 if len(pattern) == 0 {
858 return files
859 }
860
861 // Create regular expression from the pattern
862 s_regexp := "^" + regexp.QuoteMeta(pattern[0])
863 for _, s := range pattern[1:] {
864 s_regexp += ".*" + regexp.QuoteMeta(s)
865 }
866 s_regexp += "$"
867 rex := regexp.MustCompile(s_regexp)
868
869 // Now match
870 var res []string
871 for _, p := range files {
872 if rex.MatchString(p) {
873 res = append(res, p)
874 }
875 }
876 return res
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800877}
878
Cole Faustf035d402022-03-28 14:02:50 -0700879type inheritProductCallParser struct {
880 loadAlways bool
881}
882
883func (p *inheritProductCallParser) parse(ctx *parseContext, v mkparser.Node, args *mkparser.MakeString) []starlarkNode {
Cole Faust9ebf6e42021-12-13 14:08:34 -0800884 args.TrimLeftSpaces()
885 args.TrimRightSpaces()
886 pathExpr := ctx.parseMakeString(v, args)
887 if _, ok := pathExpr.(*badExpr); ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800888 return []starlarkNode{ctx.newBadNode(v, "Unable to parse argument to inherit")}
Cole Faust9ebf6e42021-12-13 14:08:34 -0800889 }
Cole Faustf035d402022-03-28 14:02:50 -0700890 return ctx.handleSubConfig(v, pathExpr, p.loadAlways, func(im inheritedModule) starlarkNode {
891 return &inheritNode{im, p.loadAlways}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700892 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800893}
894
Cole Faustdd569ae2022-01-31 15:48:29 -0800895func (ctx *parseContext) handleInclude(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) []starlarkNode {
896 return ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) starlarkNode {
897 return &includeNode{im, loadAlways}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700898 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800899}
900
Cole Faustdd569ae2022-01-31 15:48:29 -0800901func (ctx *parseContext) handleVariable(v *mkparser.Variable) []starlarkNode {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800902 // Handle:
903 // $(call inherit-product,...)
904 // $(call inherit-product-if-exists,...)
905 // $(info xxx)
906 // $(warning xxx)
907 // $(error xxx)
Cole Faust9ebf6e42021-12-13 14:08:34 -0800908 // $(call other-custom-functions,...)
909
Cole Faustf035d402022-03-28 14:02:50 -0700910 if name, args, ok := ctx.maybeParseFunctionCall(v, v.Name); ok {
911 if kf, ok := knownNodeFunctions[name]; ok {
912 return kf.parse(ctx, v, args)
913 }
Cole Faust9ebf6e42021-12-13 14:08:34 -0800914 }
Cole Faustf035d402022-03-28 14:02:50 -0700915
Cole Faustdd569ae2022-01-31 15:48:29 -0800916 return []starlarkNode{&exprNode{expr: ctx.parseReference(v, v.Name)}}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800917}
918
Cole Faustdd569ae2022-01-31 15:48:29 -0800919func (ctx *parseContext) maybeHandleDefine(directive *mkparser.Directive) starlarkNode {
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700920 macro_name := strings.Fields(directive.Args.Strings[0])[0]
921 // Ignore the macros that we handle
Cole Faust9ebf6e42021-12-13 14:08:34 -0800922 _, ignored := ignoredDefines[macro_name]
923 _, known := knownFunctions[macro_name]
924 if !ignored && !known {
Cole Faustdd569ae2022-01-31 15:48:29 -0800925 return ctx.newBadNode(directive, "define is not supported: %s", macro_name)
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700926 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800927 return nil
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800928}
929
Cole Faustdd569ae2022-01-31 15:48:29 -0800930func (ctx *parseContext) handleIfBlock(ifDirective *mkparser.Directive) starlarkNode {
931 ssSwitch := &switchNode{
932 ssCases: []*switchCase{ctx.processBranch(ifDirective)},
933 }
934 for ctx.hasNodes() && ctx.fatalError == nil {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800935 node := ctx.getNode()
936 switch x := node.(type) {
937 case *mkparser.Directive:
938 switch x.Name {
939 case "else", "elifdef", "elifndef", "elifeq", "elifneq":
Cole Faustdd569ae2022-01-31 15:48:29 -0800940 ssSwitch.ssCases = append(ssSwitch.ssCases, ctx.processBranch(x))
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800941 case "endif":
Cole Faustdd569ae2022-01-31 15:48:29 -0800942 return ssSwitch
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800943 default:
Cole Faustdd569ae2022-01-31 15:48:29 -0800944 return ctx.newBadNode(node, "unexpected directive %s", x.Name)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800945 }
946 default:
Cole Faustdd569ae2022-01-31 15:48:29 -0800947 return ctx.newBadNode(ifDirective, "unexpected statement")
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800948 }
949 }
950 if ctx.fatalError == nil {
951 ctx.fatalError = fmt.Errorf("no matching endif for %s", ifDirective.Dump())
952 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800953 return ctx.newBadNode(ifDirective, "no matching endif for %s", ifDirective.Dump())
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800954}
955
956// processBranch processes a single branch (if/elseif/else) until the next directive
957// on the same level.
Cole Faustdd569ae2022-01-31 15:48:29 -0800958func (ctx *parseContext) processBranch(check *mkparser.Directive) *switchCase {
959 block := &switchCase{gate: ctx.parseCondition(check)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800960 defer func() {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800961 ctx.ifNestLevel--
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800962 }()
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800963 ctx.ifNestLevel++
964
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800965 for ctx.hasNodes() {
966 node := ctx.getNode()
Cole Faust591a1fe2021-11-08 15:37:57 -0800967 if d, ok := node.(*mkparser.Directive); ok {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800968 switch d.Name {
969 case "else", "elifdef", "elifndef", "elifeq", "elifneq", "endif":
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800970 ctx.backNode()
Cole Faustdd569ae2022-01-31 15:48:29 -0800971 return block
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800972 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800973 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800974 block.nodes = append(block.nodes, ctx.handleSimpleStatement(node)...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800975 }
976 ctx.fatalError = fmt.Errorf("no matching endif for %s", check.Dump())
Cole Faustdd569ae2022-01-31 15:48:29 -0800977 return block
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800978}
979
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800980func (ctx *parseContext) parseCondition(check *mkparser.Directive) starlarkNode {
981 switch check.Name {
982 case "ifdef", "ifndef", "elifdef", "elifndef":
Cole Faust71514c02022-01-27 17:21:41 -0800983 if !check.Args.Const() {
Cole Faustdd569ae2022-01-31 15:48:29 -0800984 return ctx.newBadNode(check, "ifdef variable ref too complex: %s", check.Args.Dump())
Cole Faust71514c02022-01-27 17:21:41 -0800985 }
Cole Faustf0632662022-04-07 13:59:24 -0700986 v := NewVariableRefExpr(ctx.addVariable(check.Args.Strings[0]))
Cole Faust71514c02022-01-27 17:21:41 -0800987 if strings.HasSuffix(check.Name, "ndef") {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800988 v = &notExpr{v}
989 }
990 return &ifNode{
991 isElif: strings.HasPrefix(check.Name, "elif"),
992 expr: v,
993 }
994 case "ifeq", "ifneq", "elifeq", "elifneq":
995 return &ifNode{
996 isElif: strings.HasPrefix(check.Name, "elif"),
997 expr: ctx.parseCompare(check),
998 }
999 case "else":
1000 return &elseNode{}
1001 default:
1002 panic(fmt.Errorf("%s: unknown directive: %s", ctx.script.mkFile, check.Dump()))
1003 }
1004}
1005
1006func (ctx *parseContext) newBadExpr(node mkparser.Node, text string, args ...interface{}) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001007 if ctx.errorLogger != nil {
Sasha Smundak422b6142021-11-11 18:31:59 -08001008 ctx.errorLogger.NewError(ctx.errorLocation(node), node, text, args...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001009 }
1010 ctx.script.hasErrors = true
Cole Faustdd569ae2022-01-31 15:48:29 -08001011 return &badExpr{errorLocation: ctx.errorLocation(node), message: fmt.Sprintf(text, args...)}
1012}
1013
1014// records that the given node failed to be converted and includes an explanatory message
1015func (ctx *parseContext) newBadNode(failedNode mkparser.Node, message string, args ...interface{}) starlarkNode {
1016 return &exprNode{ctx.newBadExpr(failedNode, message, args...)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001017}
1018
1019func (ctx *parseContext) parseCompare(cond *mkparser.Directive) starlarkExpr {
1020 // Strip outer parentheses
1021 mkArg := cloneMakeString(cond.Args)
1022 mkArg.Strings[0] = strings.TrimLeft(mkArg.Strings[0], "( ")
1023 n := len(mkArg.Strings)
1024 mkArg.Strings[n-1] = strings.TrimRight(mkArg.Strings[n-1], ") ")
1025 args := mkArg.Split(",")
1026 // TODO(asmundak): handle the case where the arguments are in quotes and space-separated
1027 if len(args) != 2 {
1028 return ctx.newBadExpr(cond, "ifeq/ifneq len(args) != 2 %s", cond.Dump())
1029 }
1030 args[0].TrimRightSpaces()
1031 args[1].TrimLeftSpaces()
1032
1033 isEq := !strings.HasSuffix(cond.Name, "neq")
Cole Faustf8320212021-11-10 15:05:07 -08001034 xLeft := ctx.parseMakeString(cond, args[0])
1035 xRight := ctx.parseMakeString(cond, args[1])
1036 if bad, ok := xLeft.(*badExpr); ok {
1037 return bad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001038 }
Cole Faustf8320212021-11-10 15:05:07 -08001039 if bad, ok := xRight.(*badExpr); ok {
1040 return bad
1041 }
1042
1043 if expr, ok := ctx.parseCompareSpecialCases(cond, xLeft, xRight); ok {
1044 return expr
1045 }
1046
Cole Faust9ebf6e42021-12-13 14:08:34 -08001047 var stringOperand string
1048 var otherOperand starlarkExpr
1049 if s, ok := maybeString(xLeft); ok {
1050 stringOperand = s
1051 otherOperand = xRight
1052 } else if s, ok := maybeString(xRight); ok {
1053 stringOperand = s
1054 otherOperand = xLeft
1055 }
1056
Cole Faust9ebf6e42021-12-13 14:08:34 -08001057 // If we've identified one of the operands as being a string literal, check
1058 // for some special cases we can do to simplify the resulting expression.
1059 if otherOperand != nil {
1060 if stringOperand == "" {
1061 if isEq {
Cole Faustf035d402022-03-28 14:02:50 -07001062 return negateExpr(otherOperand)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001063 } else {
1064 return otherOperand
1065 }
1066 }
1067 if stringOperand == "true" && otherOperand.typ() == starlarkTypeBool {
1068 if !isEq {
Cole Faustf035d402022-03-28 14:02:50 -07001069 return negateExpr(otherOperand)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001070 } else {
1071 return otherOperand
1072 }
1073 }
Cole Faustb1103e22022-01-06 15:22:05 -08001074 if intOperand, err := strconv.Atoi(strings.TrimSpace(stringOperand)); err == nil && otherOperand.typ() == starlarkTypeInt {
1075 return &eqExpr{
1076 left: otherOperand,
1077 right: &intLiteralExpr{literal: intOperand},
1078 isEq: isEq,
1079 }
1080 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001081 }
1082
Cole Faustf8320212021-11-10 15:05:07 -08001083 return &eqExpr{left: xLeft, right: xRight, isEq: isEq}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001084}
1085
Cole Faustf8320212021-11-10 15:05:07 -08001086// Given an if statement's directive and the left/right starlarkExprs,
1087// check if the starlarkExprs are one of a few hardcoded special cases
Cole Faust9932f752022-02-08 11:56:25 -08001088// that can be converted to a simpler equality expression than simply comparing
Cole Faustf8320212021-11-10 15:05:07 -08001089// the two.
1090func (ctx *parseContext) parseCompareSpecialCases(directive *mkparser.Directive, left starlarkExpr,
1091 right starlarkExpr) (starlarkExpr, bool) {
1092 isEq := !strings.HasSuffix(directive.Name, "neq")
1093
1094 // All the special cases require a call on one side and a
1095 // string literal/variable on the other. Turn the left/right variables into
1096 // call/value variables, and return false if that's not possible.
1097 var value starlarkExpr = nil
1098 call, ok := left.(*callExpr)
1099 if ok {
1100 switch right.(type) {
1101 case *stringLiteralExpr, *variableRefExpr:
1102 value = right
1103 }
1104 } else {
1105 call, _ = right.(*callExpr)
1106 switch left.(type) {
1107 case *stringLiteralExpr, *variableRefExpr:
1108 value = left
1109 }
1110 }
1111
1112 if call == nil || value == nil {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001113 return nil, false
1114 }
Cole Faustf8320212021-11-10 15:05:07 -08001115
Cole Faustf8320212021-11-10 15:05:07 -08001116 switch call.name {
Cole Faust9932f752022-02-08 11:56:25 -08001117 case baseName + ".filter":
1118 return ctx.parseCompareFilterFuncResult(directive, call, value, isEq)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001119 case baseName + ".expand_wildcard":
Cole Faustf8320212021-11-10 15:05:07 -08001120 return ctx.parseCompareWildcardFuncResult(directive, call, value, !isEq), true
Cole Faust9ebf6e42021-12-13 14:08:34 -08001121 case baseName + ".findstring":
Cole Faustf8320212021-11-10 15:05:07 -08001122 return ctx.parseCheckFindstringFuncResult(directive, call, value, !isEq), true
Cole Faust9ebf6e42021-12-13 14:08:34 -08001123 case baseName + ".strip":
Cole Faustf8320212021-11-10 15:05:07 -08001124 return ctx.parseCompareStripFuncResult(directive, call, value, !isEq), true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001125 }
Cole Faustf8320212021-11-10 15:05:07 -08001126 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001127}
1128
1129func (ctx *parseContext) parseCompareFilterFuncResult(cond *mkparser.Directive,
Cole Faust9932f752022-02-08 11:56:25 -08001130 filterFuncCall *callExpr, xValue starlarkExpr, negate bool) (starlarkExpr, bool) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001131 // We handle:
Sasha Smundak0554d762021-07-08 18:26:12 -07001132 // * ifeq/ifneq (,$(filter v1 v2 ..., EXPR) becomes if EXPR not in/in ["v1", "v2", ...]
1133 // * ifeq/ifneq (,$(filter EXPR, v1 v2 ...) becomes if EXPR not in/in ["v1", "v2", ...]
Cole Faust9932f752022-02-08 11:56:25 -08001134 if x, ok := xValue.(*stringLiteralExpr); !ok || x.literal != "" {
1135 return nil, false
1136 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001137 xPattern := filterFuncCall.args[0]
1138 xText := filterFuncCall.args[1]
1139 var xInList *stringLiteralExpr
Sasha Smundak0554d762021-07-08 18:26:12 -07001140 var expr starlarkExpr
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001141 var ok bool
Cole Faust9932f752022-02-08 11:56:25 -08001142 if xInList, ok = xPattern.(*stringLiteralExpr); ok && !strings.ContainsRune(xInList.literal, '%') && xText.typ() == starlarkTypeList {
1143 expr = xText
1144 } else if xInList, ok = xText.(*stringLiteralExpr); ok {
1145 expr = xPattern
1146 } else {
1147 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001148 }
Cole Faust9932f752022-02-08 11:56:25 -08001149 slExpr := newStringListExpr(strings.Fields(xInList.literal))
1150 // Generate simpler code for the common cases:
1151 if expr.typ() == starlarkTypeList {
1152 if len(slExpr.items) == 1 {
1153 // Checking that a string belongs to list
1154 return &inExpr{isNot: negate, list: expr, expr: slExpr.items[0]}, true
Sasha Smundak0554d762021-07-08 18:26:12 -07001155 } else {
Cole Faust9932f752022-02-08 11:56:25 -08001156 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001157 }
Cole Faust9932f752022-02-08 11:56:25 -08001158 } else if len(slExpr.items) == 1 {
1159 return &eqExpr{left: expr, right: slExpr.items[0], isEq: !negate}, true
1160 } else {
1161 return &inExpr{isNot: negate, list: newStringListExpr(strings.Fields(xInList.literal)), expr: expr}, true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001162 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001163}
1164
1165func (ctx *parseContext) parseCompareWildcardFuncResult(directive *mkparser.Directive,
1166 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001167 if !isEmptyString(xValue) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001168 return ctx.newBadExpr(directive, "wildcard result can be compared only to empty: %s", xValue)
1169 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001170 callFunc := baseName + ".file_wildcard_exists"
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001171 if s, ok := xCall.args[0].(*stringLiteralExpr); ok && !strings.ContainsAny(s.literal, "*?{[") {
Cole Faust9ebf6e42021-12-13 14:08:34 -08001172 callFunc = baseName + ".file_exists"
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001173 }
1174 var cc starlarkExpr = &callExpr{name: callFunc, args: xCall.args, returnType: starlarkTypeBool}
1175 if !negate {
1176 cc = &notExpr{cc}
1177 }
1178 return cc
1179}
1180
1181func (ctx *parseContext) parseCheckFindstringFuncResult(directive *mkparser.Directive,
1182 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001183 if isEmptyString(xValue) {
1184 return &eqExpr{
1185 left: &callExpr{
1186 object: xCall.args[1],
1187 name: "find",
1188 args: []starlarkExpr{xCall.args[0]},
1189 returnType: starlarkTypeInt,
1190 },
1191 right: &intLiteralExpr{-1},
1192 isEq: !negate,
1193 }
Cole Faust0e9418c2021-12-13 16:33:25 -08001194 } else if s, ok := maybeString(xValue); ok {
1195 if s2, ok := maybeString(xCall.args[0]); ok && s == s2 {
1196 return &eqExpr{
1197 left: &callExpr{
1198 object: xCall.args[1],
1199 name: "find",
1200 args: []starlarkExpr{xCall.args[0]},
1201 returnType: starlarkTypeInt,
1202 },
1203 right: &intLiteralExpr{-1},
1204 isEq: negate,
1205 }
1206 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001207 }
Cole Faust0e9418c2021-12-13 16:33:25 -08001208 return ctx.newBadExpr(directive, "$(findstring) can only be compared to nothing or its first argument")
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001209}
1210
1211func (ctx *parseContext) parseCompareStripFuncResult(directive *mkparser.Directive,
1212 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
1213 if _, ok := xValue.(*stringLiteralExpr); !ok {
1214 return ctx.newBadExpr(directive, "strip result can be compared only to string: %s", xValue)
1215 }
1216 return &eqExpr{
1217 left: &callExpr{
1218 name: "strip",
1219 args: xCall.args,
1220 returnType: starlarkTypeString,
1221 },
1222 right: xValue, isEq: !negate}
1223}
1224
Cole Faustf035d402022-03-28 14:02:50 -07001225func (ctx *parseContext) maybeParseFunctionCall(node mkparser.Node, ref *mkparser.MakeString) (name string, args *mkparser.MakeString, ok bool) {
1226 ref.TrimLeftSpaces()
1227 ref.TrimRightSpaces()
1228
1229 words := ref.SplitN(" ", 2)
1230 if !words[0].Const() {
1231 return "", nil, false
1232 }
1233
1234 name = words[0].Dump()
1235 args = mkparser.SimpleMakeString("", words[0].Pos())
1236 if len(words) >= 2 {
1237 args = words[1]
1238 }
1239 args.TrimLeftSpaces()
1240 if name == "call" {
1241 words = args.SplitN(",", 2)
1242 if words[0].Empty() || !words[0].Const() {
1243 return "", nil, false
1244 }
1245 name = words[0].Dump()
1246 if len(words) < 2 {
Cole Faust6c41b8a2022-04-13 13:53:48 -07001247 args = mkparser.SimpleMakeString("", words[0].Pos())
Cole Faustf035d402022-03-28 14:02:50 -07001248 } else {
1249 args = words[1]
1250 }
1251 }
1252 ok = true
1253 return
1254}
1255
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001256// parses $(...), returning an expression
1257func (ctx *parseContext) parseReference(node mkparser.Node, ref *mkparser.MakeString) starlarkExpr {
1258 ref.TrimLeftSpaces()
1259 ref.TrimRightSpaces()
1260 refDump := ref.Dump()
1261
1262 // Handle only the case where the first (or only) word is constant
1263 words := ref.SplitN(" ", 2)
1264 if !words[0].Const() {
1265 return ctx.newBadExpr(node, "reference is too complex: %s", refDump)
1266 }
1267
Cole Faust1e275862022-04-26 14:28:04 -07001268 if name, _, ok := ctx.maybeParseFunctionCall(node, ref); ok {
1269 if _, unsupported := unsupportedFunctions[name]; unsupported {
1270 return ctx.newBadExpr(node, "%s is not supported", refDump)
1271 }
1272 }
1273
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001274 // If it is a single word, it can be a simple variable
1275 // reference or a function call
Cole Faustf035d402022-03-28 14:02:50 -07001276 if len(words) == 1 && !isMakeControlFunc(refDump) && refDump != "shell" && refDump != "eval" {
Sasha Smundak65b547e2021-09-17 15:35:41 -07001277 if strings.HasPrefix(refDump, soongNsPrefix) {
1278 // TODO (asmundak): if we find many, maybe handle them.
Cole Faustc00184e2021-11-08 12:08:57 -08001279 return ctx.newBadExpr(node, "SOONG_CONFIG_ variables cannot be referenced, use soong_config_get instead: %s", refDump)
Sasha Smundak65b547e2021-09-17 15:35:41 -07001280 }
Cole Faustc36c9622021-12-07 15:20:45 -08001281 // Handle substitution references: https://www.gnu.org/software/make/manual/html_node/Substitution-Refs.html
1282 if strings.Contains(refDump, ":") {
1283 parts := strings.SplitN(refDump, ":", 2)
1284 substParts := strings.SplitN(parts[1], "=", 2)
1285 if len(substParts) < 2 || strings.Count(substParts[0], "%") > 1 {
1286 return ctx.newBadExpr(node, "Invalid substitution reference")
1287 }
1288 if !strings.Contains(substParts[0], "%") {
1289 if strings.Contains(substParts[1], "%") {
1290 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.")
1291 }
1292 substParts[0] = "%" + substParts[0]
1293 substParts[1] = "%" + substParts[1]
1294 }
1295 v := ctx.addVariable(parts[0])
1296 if v == nil {
1297 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1298 }
1299 return &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001300 name: baseName + ".mkpatsubst",
1301 returnType: starlarkTypeString,
Cole Faustc36c9622021-12-07 15:20:45 -08001302 args: []starlarkExpr{
1303 &stringLiteralExpr{literal: substParts[0]},
1304 &stringLiteralExpr{literal: substParts[1]},
Cole Faustf0632662022-04-07 13:59:24 -07001305 NewVariableRefExpr(v),
Cole Faustc36c9622021-12-07 15:20:45 -08001306 },
1307 }
1308 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001309 if v := ctx.addVariable(refDump); v != nil {
Cole Faustf0632662022-04-07 13:59:24 -07001310 return NewVariableRefExpr(v)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001311 }
1312 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1313 }
1314
Cole Faustf035d402022-03-28 14:02:50 -07001315 if name, args, ok := ctx.maybeParseFunctionCall(node, ref); ok {
1316 if kf, found := knownFunctions[name]; found {
1317 return kf.parse(ctx, node, args)
Sasha Smundak6609ba72021-07-22 18:32:56 -07001318 } else {
Cole Faustf035d402022-03-28 14:02:50 -07001319 return ctx.newBadExpr(node, "cannot handle invoking %s", name)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001320 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001321 }
Cole Faust1e275862022-04-26 14:28:04 -07001322 return ctx.newBadExpr(node, "cannot handle %s", refDump)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001323}
1324
1325type simpleCallParser struct {
1326 name string
1327 returnType starlarkType
1328 addGlobals bool
Cole Faust1cc08852022-02-28 11:12:08 -08001329 addHandle bool
Cole Faust9ebf6e42021-12-13 14:08:34 -08001330}
1331
1332func (p *simpleCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1333 expr := &callExpr{name: p.name, returnType: p.returnType}
1334 if p.addGlobals {
1335 expr.args = append(expr.args, &globalsExpr{})
1336 }
Cole Faust1cc08852022-02-28 11:12:08 -08001337 if p.addHandle {
1338 expr.args = append(expr.args, &identifierExpr{name: "handle"})
1339 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001340 for _, arg := range args.Split(",") {
1341 arg.TrimLeftSpaces()
1342 arg.TrimRightSpaces()
1343 x := ctx.parseMakeString(node, arg)
1344 if xBad, ok := x.(*badExpr); ok {
1345 return xBad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001346 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001347 expr.args = append(expr.args, x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001348 }
1349 return expr
1350}
1351
Cole Faust9ebf6e42021-12-13 14:08:34 -08001352type makeControlFuncParser struct {
1353 name string
1354}
1355
1356func (p *makeControlFuncParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1357 // Make control functions need special treatment as everything
1358 // after the name is a single text argument
1359 x := ctx.parseMakeString(node, args)
1360 if xBad, ok := x.(*badExpr); ok {
1361 return xBad
1362 }
1363 return &callExpr{
1364 name: p.name,
1365 args: []starlarkExpr{
1366 &stringLiteralExpr{ctx.script.mkFile},
1367 x,
1368 },
1369 returnType: starlarkTypeUnknown,
1370 }
1371}
1372
1373type shellCallParser struct{}
1374
1375func (p *shellCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1376 // Shell functions need special treatment as everything
1377 // after the name is a single text argument
1378 x := ctx.parseMakeString(node, args)
1379 if xBad, ok := x.(*badExpr); ok {
1380 return xBad
1381 }
1382 return &callExpr{
1383 name: baseName + ".shell",
1384 args: []starlarkExpr{x},
1385 returnType: starlarkTypeUnknown,
1386 }
1387}
1388
1389type myDirCallParser struct{}
1390
1391func (p *myDirCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1392 if !args.Empty() {
1393 return ctx.newBadExpr(node, "my-dir function cannot have any arguments passed to it.")
1394 }
Cole Faustf5adedc2022-03-18 14:05:06 -07001395 return &stringLiteralExpr{literal: filepath.Dir(ctx.script.mkFile)}
Cole Faust9ebf6e42021-12-13 14:08:34 -08001396}
1397
Cole Faust9ebf6e42021-12-13 14:08:34 -08001398type isProductInListCallParser struct{}
1399
1400func (p *isProductInListCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1401 if args.Empty() {
1402 return ctx.newBadExpr(node, "is-product-in-list requires an argument")
1403 }
1404 return &inExpr{
Cole Faustf0632662022-04-07 13:59:24 -07001405 expr: NewVariableRefExpr(ctx.addVariable("TARGET_PRODUCT")),
Cole Faust9ebf6e42021-12-13 14:08:34 -08001406 list: maybeConvertToStringList(ctx.parseMakeString(node, args)),
1407 isNot: false,
1408 }
1409}
1410
1411type isVendorBoardPlatformCallParser struct{}
1412
1413func (p *isVendorBoardPlatformCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1414 if args.Empty() || !identifierFullMatchRegex.MatchString(args.Dump()) {
1415 return ctx.newBadExpr(node, "cannot handle non-constant argument to is-vendor-board-platform")
1416 }
1417 return &inExpr{
Cole Faustf0632662022-04-07 13:59:24 -07001418 expr: NewVariableRefExpr(ctx.addVariable("TARGET_BOARD_PLATFORM")),
1419 list: NewVariableRefExpr(ctx.addVariable(args.Dump() + "_BOARD_PLATFORMS")),
Cole Faust9ebf6e42021-12-13 14:08:34 -08001420 isNot: false,
1421 }
1422}
1423
1424type isVendorBoardQcomCallParser struct{}
1425
1426func (p *isVendorBoardQcomCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1427 if !args.Empty() {
1428 return ctx.newBadExpr(node, "is-vendor-board-qcom does not accept any arguments")
1429 }
1430 return &inExpr{
Cole Faustf0632662022-04-07 13:59:24 -07001431 expr: NewVariableRefExpr(ctx.addVariable("TARGET_BOARD_PLATFORM")),
1432 list: NewVariableRefExpr(ctx.addVariable("QCOM_BOARD_PLATFORMS")),
Cole Faust9ebf6e42021-12-13 14:08:34 -08001433 isNot: false,
1434 }
1435}
1436
1437type substCallParser struct {
1438 fname string
1439}
1440
1441func (p *substCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001442 words := args.Split(",")
1443 if len(words) != 3 {
Cole Faust9ebf6e42021-12-13 14:08:34 -08001444 return ctx.newBadExpr(node, "%s function should have 3 arguments", p.fname)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001445 }
Sasha Smundak35434ed2021-11-05 16:29:56 -07001446 from := ctx.parseMakeString(node, words[0])
1447 if xBad, ok := from.(*badExpr); ok {
1448 return xBad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001449 }
Sasha Smundak35434ed2021-11-05 16:29:56 -07001450 to := ctx.parseMakeString(node, words[1])
1451 if xBad, ok := to.(*badExpr); ok {
1452 return xBad
1453 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001454 words[2].TrimLeftSpaces()
1455 words[2].TrimRightSpaces()
1456 obj := ctx.parseMakeString(node, words[2])
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001457 typ := obj.typ()
Cole Faust9ebf6e42021-12-13 14:08:34 -08001458 if typ == starlarkTypeString && p.fname == "subst" {
Sasha Smundak94b41c72021-07-12 18:30:42 -07001459 // Optimization: if it's $(subst from, to, string), emit string.replace(from, to)
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001460 return &callExpr{
1461 object: obj,
1462 name: "replace",
Sasha Smundak35434ed2021-11-05 16:29:56 -07001463 args: []starlarkExpr{from, to},
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001464 returnType: typ,
1465 }
1466 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001467 return &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001468 name: baseName + ".mk" + p.fname,
Sasha Smundak35434ed2021-11-05 16:29:56 -07001469 args: []starlarkExpr{from, to, obj},
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001470 returnType: obj.typ(),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001471 }
1472}
1473
Cole Faust9ebf6e42021-12-13 14:08:34 -08001474type ifCallParser struct{}
1475
1476func (p *ifCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Cole Faust4eadba72021-12-07 11:54:52 -08001477 words := args.Split(",")
1478 if len(words) != 2 && len(words) != 3 {
1479 return ctx.newBadExpr(node, "if function should have 2 or 3 arguments, found "+strconv.Itoa(len(words)))
1480 }
1481 condition := ctx.parseMakeString(node, words[0])
1482 ifTrue := ctx.parseMakeString(node, words[1])
1483 var ifFalse starlarkExpr
1484 if len(words) == 3 {
1485 ifFalse = ctx.parseMakeString(node, words[2])
1486 } else {
1487 switch ifTrue.typ() {
1488 case starlarkTypeList:
1489 ifFalse = &listExpr{items: []starlarkExpr{}}
1490 case starlarkTypeInt:
1491 ifFalse = &intLiteralExpr{literal: 0}
1492 case starlarkTypeBool:
1493 ifFalse = &boolLiteralExpr{literal: false}
1494 default:
1495 ifFalse = &stringLiteralExpr{literal: ""}
1496 }
1497 }
1498 return &ifExpr{
1499 condition,
1500 ifTrue,
1501 ifFalse,
1502 }
1503}
1504
Cole Faustf035d402022-03-28 14:02:50 -07001505type ifCallNodeParser struct{}
Cole Faust9ebf6e42021-12-13 14:08:34 -08001506
Cole Faustf035d402022-03-28 14:02:50 -07001507func (p *ifCallNodeParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode {
1508 words := args.Split(",")
1509 if len(words) != 2 && len(words) != 3 {
1510 return []starlarkNode{ctx.newBadNode(node, "if function should have 2 or 3 arguments, found "+strconv.Itoa(len(words)))}
1511 }
1512
1513 ifn := &ifNode{expr: ctx.parseMakeString(node, words[0])}
1514 cases := []*switchCase{
1515 {
1516 gate: ifn,
1517 nodes: ctx.parseNodeMakeString(node, words[1]),
1518 },
1519 }
1520 if len(words) == 3 {
1521 cases = append(cases, &switchCase{
1522 gate: &elseNode{},
1523 nodes: ctx.parseNodeMakeString(node, words[2]),
1524 })
1525 }
1526 if len(cases) == 2 {
1527 if len(cases[1].nodes) == 0 {
1528 // Remove else branch if it has no contents
1529 cases = cases[:1]
1530 } else if len(cases[0].nodes) == 0 {
1531 // If the if branch has no contents but the else does,
1532 // move them to the if and negate its condition
1533 ifn.expr = negateExpr(ifn.expr)
1534 cases[0].nodes = cases[1].nodes
1535 cases = cases[:1]
1536 }
1537 }
1538
1539 return []starlarkNode{&switchNode{ssCases: cases}}
1540}
1541
1542type foreachCallParser struct{}
1543
1544func (p *foreachCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Cole Faustb0d32ab2021-12-09 14:00:59 -08001545 words := args.Split(",")
1546 if len(words) != 3 {
1547 return ctx.newBadExpr(node, "foreach function should have 3 arguments, found "+strconv.Itoa(len(words)))
1548 }
1549 if !words[0].Const() || words[0].Empty() || !identifierFullMatchRegex.MatchString(words[0].Strings[0]) {
1550 return ctx.newBadExpr(node, "first argument to foreach function must be a simple string identifier")
1551 }
1552 loopVarName := words[0].Strings[0]
1553 list := ctx.parseMakeString(node, words[1])
1554 action := ctx.parseMakeString(node, words[2]).transform(func(expr starlarkExpr) starlarkExpr {
1555 if varRefExpr, ok := expr.(*variableRefExpr); ok && varRefExpr.ref.name() == loopVarName {
1556 return &identifierExpr{loopVarName}
1557 }
1558 return nil
1559 })
1560
1561 if list.typ() != starlarkTypeList {
1562 list = &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001563 name: baseName + ".words",
1564 returnType: starlarkTypeList,
Cole Faustb0d32ab2021-12-09 14:00:59 -08001565 args: []starlarkExpr{list},
1566 }
1567 }
1568
1569 return &foreachExpr{
1570 varName: loopVarName,
1571 list: list,
1572 action: action,
1573 }
1574}
1575
Cole Faustf035d402022-03-28 14:02:50 -07001576func transformNode(node starlarkNode, transformer func(expr starlarkExpr) starlarkExpr) {
1577 switch a := node.(type) {
1578 case *ifNode:
1579 a.expr = a.expr.transform(transformer)
1580 case *switchCase:
1581 transformNode(a.gate, transformer)
1582 for _, n := range a.nodes {
1583 transformNode(n, transformer)
1584 }
1585 case *switchNode:
1586 for _, n := range a.ssCases {
1587 transformNode(n, transformer)
1588 }
1589 case *exprNode:
1590 a.expr = a.expr.transform(transformer)
1591 case *assignmentNode:
1592 a.value = a.value.transform(transformer)
1593 case *foreachNode:
1594 a.list = a.list.transform(transformer)
1595 for _, n := range a.actions {
1596 transformNode(n, transformer)
1597 }
1598 }
1599}
1600
1601type foreachCallNodeParser struct{}
1602
1603func (p *foreachCallNodeParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode {
1604 words := args.Split(",")
1605 if len(words) != 3 {
1606 return []starlarkNode{ctx.newBadNode(node, "foreach function should have 3 arguments, found "+strconv.Itoa(len(words)))}
1607 }
1608 if !words[0].Const() || words[0].Empty() || !identifierFullMatchRegex.MatchString(words[0].Strings[0]) {
1609 return []starlarkNode{ctx.newBadNode(node, "first argument to foreach function must be a simple string identifier")}
1610 }
1611
1612 loopVarName := words[0].Strings[0]
1613
1614 list := ctx.parseMakeString(node, words[1])
1615 if list.typ() != starlarkTypeList {
1616 list = &callExpr{
1617 name: baseName + ".words",
1618 returnType: starlarkTypeList,
1619 args: []starlarkExpr{list},
1620 }
1621 }
1622
1623 actions := ctx.parseNodeMakeString(node, words[2])
1624 // TODO(colefaust): Replace transforming code with something more elegant
1625 for _, action := range actions {
1626 transformNode(action, func(expr starlarkExpr) starlarkExpr {
1627 if varRefExpr, ok := expr.(*variableRefExpr); ok && varRefExpr.ref.name() == loopVarName {
1628 return &identifierExpr{loopVarName}
1629 }
1630 return nil
1631 })
1632 }
1633
1634 return []starlarkNode{&foreachNode{
1635 varName: loopVarName,
1636 list: list,
1637 actions: actions,
1638 }}
1639}
1640
Cole Faust9ebf6e42021-12-13 14:08:34 -08001641type wordCallParser struct{}
1642
1643func (p *wordCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001644 words := args.Split(",")
1645 if len(words) != 2 {
1646 return ctx.newBadExpr(node, "word function should have 2 arguments")
1647 }
1648 var index uint64 = 0
1649 if words[0].Const() {
1650 index, _ = strconv.ParseUint(strings.TrimSpace(words[0].Strings[0]), 10, 64)
1651 }
1652 if index < 1 {
1653 return ctx.newBadExpr(node, "word index should be constant positive integer")
1654 }
1655 words[1].TrimLeftSpaces()
1656 words[1].TrimRightSpaces()
1657 array := ctx.parseMakeString(node, words[1])
1658 if xBad, ok := array.(*badExpr); ok {
1659 return xBad
1660 }
1661 if array.typ() != starlarkTypeList {
1662 array = &callExpr{object: array, name: "split", returnType: starlarkTypeList}
1663 }
Cole Faustb0d32ab2021-12-09 14:00:59 -08001664 return &indexExpr{array, &intLiteralExpr{int(index - 1)}}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001665}
1666
Cole Faust9ebf6e42021-12-13 14:08:34 -08001667type firstOrLastwordCallParser struct {
1668 isLastWord bool
1669}
1670
1671func (p *firstOrLastwordCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundak16e07732021-07-23 11:38:23 -07001672 arg := ctx.parseMakeString(node, args)
1673 if bad, ok := arg.(*badExpr); ok {
1674 return bad
1675 }
1676 index := &intLiteralExpr{0}
Cole Faust9ebf6e42021-12-13 14:08:34 -08001677 if p.isLastWord {
Sasha Smundak16e07732021-07-23 11:38:23 -07001678 if v, ok := arg.(*variableRefExpr); ok && v.ref.name() == "MAKEFILE_LIST" {
1679 return &stringLiteralExpr{ctx.script.mkFile}
1680 }
1681 index.literal = -1
1682 }
1683 if arg.typ() == starlarkTypeList {
1684 return &indexExpr{arg, index}
1685 }
1686 return &indexExpr{&callExpr{object: arg, name: "split", returnType: starlarkTypeList}, index}
1687}
1688
Cole Faustb1103e22022-01-06 15:22:05 -08001689func parseIntegerArguments(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString, expectedArgs int) ([]starlarkExpr, error) {
1690 parsedArgs := make([]starlarkExpr, 0)
1691 for _, arg := range args.Split(",") {
1692 expr := ctx.parseMakeString(node, arg)
1693 if expr.typ() == starlarkTypeList {
1694 return nil, fmt.Errorf("argument to math argument has type list, which cannot be converted to int")
1695 }
1696 if s, ok := maybeString(expr); ok {
1697 intVal, err := strconv.Atoi(strings.TrimSpace(s))
1698 if err != nil {
1699 return nil, err
1700 }
1701 expr = &intLiteralExpr{literal: intVal}
1702 } else if expr.typ() != starlarkTypeInt {
1703 expr = &callExpr{
1704 name: "int",
1705 args: []starlarkExpr{expr},
1706 returnType: starlarkTypeInt,
1707 }
1708 }
1709 parsedArgs = append(parsedArgs, expr)
1710 }
1711 if len(parsedArgs) != expectedArgs {
1712 return nil, fmt.Errorf("function should have %d arguments", expectedArgs)
1713 }
1714 return parsedArgs, nil
1715}
1716
1717type mathComparisonCallParser struct {
1718 op string
1719}
1720
1721func (p *mathComparisonCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1722 parsedArgs, err := parseIntegerArguments(ctx, node, args, 2)
1723 if err != nil {
1724 return ctx.newBadExpr(node, err.Error())
1725 }
1726 return &binaryOpExpr{
1727 left: parsedArgs[0],
1728 right: parsedArgs[1],
1729 op: p.op,
1730 returnType: starlarkTypeBool,
1731 }
1732}
1733
1734type mathMaxOrMinCallParser struct {
1735 function string
1736}
1737
1738func (p *mathMaxOrMinCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1739 parsedArgs, err := parseIntegerArguments(ctx, node, args, 2)
1740 if err != nil {
1741 return ctx.newBadExpr(node, err.Error())
1742 }
1743 return &callExpr{
1744 object: nil,
1745 name: p.function,
1746 args: parsedArgs,
1747 returnType: starlarkTypeInt,
1748 }
1749}
1750
Cole Faustf035d402022-03-28 14:02:50 -07001751type evalNodeParser struct{}
1752
1753func (p *evalNodeParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode {
1754 parser := mkparser.NewParser("Eval expression", strings.NewReader(args.Dump()))
1755 nodes, errs := parser.Parse()
1756 if errs != nil {
1757 return []starlarkNode{ctx.newBadNode(node, "Unable to parse eval statement")}
1758 }
1759
1760 if len(nodes) == 0 {
1761 return []starlarkNode{}
1762 } else if len(nodes) == 1 {
1763 switch n := nodes[0].(type) {
1764 case *mkparser.Assignment:
1765 if n.Name.Const() {
1766 return ctx.handleAssignment(n)
1767 }
1768 case *mkparser.Comment:
1769 return []starlarkNode{&commentNode{strings.TrimSpace("#" + n.Comment)}}
1770 }
1771 }
1772
1773 return []starlarkNode{ctx.newBadNode(node, "Eval expression too complex; only assignments and comments are supported")}
1774}
1775
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001776func (ctx *parseContext) parseMakeString(node mkparser.Node, mk *mkparser.MakeString) starlarkExpr {
1777 if mk.Const() {
1778 return &stringLiteralExpr{mk.Dump()}
1779 }
1780 if mkRef, ok := mk.SingleVariable(); ok {
1781 return ctx.parseReference(node, mkRef)
1782 }
1783 // If we reached here, it's neither string literal nor a simple variable,
1784 // we need a full-blown interpolation node that will generate
1785 // "a%b%c" % (X, Y) for a$(X)b$(Y)c
Cole Faustfc438682021-12-14 12:46:32 -08001786 parts := make([]starlarkExpr, len(mk.Variables)+len(mk.Strings))
1787 for i := 0; i < len(parts); i++ {
1788 if i%2 == 0 {
1789 parts[i] = &stringLiteralExpr{literal: mk.Strings[i/2]}
1790 } else {
1791 parts[i] = ctx.parseReference(node, mk.Variables[i/2].Name)
1792 if x, ok := parts[i].(*badExpr); ok {
1793 return x
1794 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001795 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001796 }
Cole Faustfc438682021-12-14 12:46:32 -08001797 return NewInterpolateExpr(parts)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001798}
1799
Cole Faustf035d402022-03-28 14:02:50 -07001800func (ctx *parseContext) parseNodeMakeString(node mkparser.Node, mk *mkparser.MakeString) []starlarkNode {
1801 // Discard any constant values in the make string, as they would be top level
1802 // string literals and do nothing.
1803 result := make([]starlarkNode, 0, len(mk.Variables))
1804 for i := range mk.Variables {
1805 result = append(result, ctx.handleVariable(&mk.Variables[i])...)
1806 }
1807 return result
1808}
1809
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001810// Handles the statements whose treatment is the same in all contexts: comment,
1811// assignment, variable (which is a macro call in reality) and all constructs that
1812// do not handle in any context ('define directive and any unrecognized stuff).
Cole Faustdd569ae2022-01-31 15:48:29 -08001813func (ctx *parseContext) handleSimpleStatement(node mkparser.Node) []starlarkNode {
1814 var result []starlarkNode
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001815 switch x := node.(type) {
1816 case *mkparser.Comment:
Cole Faustdd569ae2022-01-31 15:48:29 -08001817 if n, handled := ctx.maybeHandleAnnotation(x); handled && n != nil {
1818 result = []starlarkNode{n}
1819 } else if !handled {
1820 result = []starlarkNode{&commentNode{strings.TrimSpace("#" + x.Comment)}}
Cole Faust7940c6a2022-01-31 15:54:05 -08001821 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001822 case *mkparser.Assignment:
Cole Faustdd569ae2022-01-31 15:48:29 -08001823 result = ctx.handleAssignment(x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001824 case *mkparser.Variable:
Cole Faustdd569ae2022-01-31 15:48:29 -08001825 result = ctx.handleVariable(x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001826 case *mkparser.Directive:
1827 switch x.Name {
1828 case "define":
Cole Faustdd569ae2022-01-31 15:48:29 -08001829 if res := ctx.maybeHandleDefine(x); res != nil {
1830 result = []starlarkNode{res}
1831 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001832 case "include", "-include":
Cole Faustdd569ae2022-01-31 15:48:29 -08001833 result = ctx.handleInclude(node, ctx.parseMakeString(node, x.Args), x.Name[0] != '-')
Cole Faust591a1fe2021-11-08 15:37:57 -08001834 case "ifeq", "ifneq", "ifdef", "ifndef":
Cole Faustdd569ae2022-01-31 15:48:29 -08001835 result = []starlarkNode{ctx.handleIfBlock(x)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001836 default:
Cole Faustdd569ae2022-01-31 15:48:29 -08001837 result = []starlarkNode{ctx.newBadNode(x, "unexpected directive %s", x.Name)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001838 }
1839 default:
Cole Faustdd569ae2022-01-31 15:48:29 -08001840 result = []starlarkNode{ctx.newBadNode(x, "unsupported line %s", strings.ReplaceAll(x.Dump(), "\n", "\n#"))}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001841 }
Cole Faust6c934f62022-01-06 15:51:12 -08001842
1843 // Clear the includeTops after each non-comment statement
1844 // so that include annotations placed on certain statements don't apply
1845 // globally for the rest of the makefile was well.
Cole Faustf92c9f22022-03-14 14:35:50 -07001846 if _, wasComment := node.(*mkparser.Comment); !wasComment {
1847 ctx.atTopOfMakefile = false
Cole Faust6c934f62022-01-06 15:51:12 -08001848 ctx.includeTops = []string{}
1849 }
Cole Faustdd569ae2022-01-31 15:48:29 -08001850
1851 if result == nil {
1852 result = []starlarkNode{}
1853 }
Cole Faustf035d402022-03-28 14:02:50 -07001854
Cole Faustdd569ae2022-01-31 15:48:29 -08001855 return result
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001856}
1857
Cole Faustf92c9f22022-03-14 14:35:50 -07001858// The types allowed in a type_hint
1859var typeHintMap = map[string]starlarkType{
1860 "string": starlarkTypeString,
1861 "list": starlarkTypeList,
1862}
1863
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001864// Processes annotation. An annotation is a comment that starts with #RBC# and provides
1865// a conversion hint -- say, where to look for the dynamically calculated inherit/include
Cole Faust7940c6a2022-01-31 15:54:05 -08001866// paths. Returns true if the comment was a successfully-handled annotation.
Cole Faustdd569ae2022-01-31 15:48:29 -08001867func (ctx *parseContext) maybeHandleAnnotation(cnode *mkparser.Comment) (starlarkNode, bool) {
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001868 maybeTrim := func(s, prefix string) (string, bool) {
1869 if strings.HasPrefix(s, prefix) {
1870 return strings.TrimSpace(strings.TrimPrefix(s, prefix)), true
1871 }
1872 return s, false
1873 }
1874 annotation, ok := maybeTrim(cnode.Comment, annotationCommentPrefix)
1875 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -08001876 return nil, false
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001877 }
1878 if p, ok := maybeTrim(annotation, "include_top"); ok {
Cole Faustf7ed5342021-12-21 14:15:12 -08001879 // Don't allow duplicate include tops, because then we will generate
1880 // invalid starlark code. (duplicate keys in the _entry dictionary)
1881 for _, top := range ctx.includeTops {
1882 if top == p {
Cole Faustdd569ae2022-01-31 15:48:29 -08001883 return nil, true
Cole Faustf7ed5342021-12-21 14:15:12 -08001884 }
1885 }
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001886 ctx.includeTops = append(ctx.includeTops, p)
Cole Faustdd569ae2022-01-31 15:48:29 -08001887 return nil, true
Cole Faustf92c9f22022-03-14 14:35:50 -07001888 } else if p, ok := maybeTrim(annotation, "type_hint"); ok {
1889 // Type hints must come at the beginning the file, to avoid confusion
1890 // if a type hint was specified later and thus only takes effect for half
1891 // of the file.
1892 if !ctx.atTopOfMakefile {
1893 return ctx.newBadNode(cnode, "type_hint annotations must come before the first Makefile statement"), true
1894 }
1895
1896 parts := strings.Fields(p)
1897 if len(parts) <= 1 {
1898 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
1899 }
1900
1901 var varType starlarkType
1902 if varType, ok = typeHintMap[parts[0]]; !ok {
1903 varType = starlarkTypeUnknown
1904 }
1905 if varType == starlarkTypeUnknown {
1906 return ctx.newBadNode(cnode, "Invalid type_hint annotation. Only list/string types are accepted, found %s", parts[0]), true
1907 }
1908
1909 for _, name := range parts[1:] {
1910 // Don't allow duplicate type hints
1911 if _, ok := ctx.typeHints[name]; ok {
1912 return ctx.newBadNode(cnode, "Duplicate type hint for variable %s", name), true
1913 }
1914 ctx.typeHints[name] = varType
1915 }
1916 return nil, true
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001917 }
Cole Faustdd569ae2022-01-31 15:48:29 -08001918 return ctx.newBadNode(cnode, "unsupported annotation %s", cnode.Comment), true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001919}
1920
1921func (ctx *parseContext) loadedModulePath(path string) string {
1922 // During the transition to Roboleaf some of the product configuration files
1923 // will be converted and checked in while the others will be generated on the fly
1924 // and run. The runner (rbcrun application) accommodates this by allowing three
1925 // different ways to specify the loaded file location:
1926 // 1) load(":<file>",...) loads <file> from the same directory
1927 // 2) load("//path/relative/to/source/root:<file>", ...) loads <file> source tree
1928 // 3) load("/absolute/path/to/<file> absolute path
1929 // If the file being generated and the file it wants to load are in the same directory,
1930 // generate option 1.
1931 // Otherwise, if output directory is not specified, generate 2)
1932 // Finally, if output directory has been specified and the file being generated and
1933 // the file it wants to load from are in the different directories, generate 2) or 3):
1934 // * if the file being loaded exists in the source tree, generate 2)
1935 // * otherwise, generate 3)
1936 // Finally, figure out the loaded module path and name and create a node for it
1937 loadedModuleDir := filepath.Dir(path)
1938 base := filepath.Base(path)
1939 loadedModuleName := strings.TrimSuffix(base, filepath.Ext(base)) + ctx.outputSuffix
1940 if loadedModuleDir == filepath.Dir(ctx.script.mkFile) {
1941 return ":" + loadedModuleName
1942 }
1943 if ctx.outputDir == "" {
1944 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1945 }
1946 if _, err := os.Stat(filepath.Join(loadedModuleDir, loadedModuleName)); err == nil {
1947 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1948 }
1949 return filepath.Join(ctx.outputDir, loadedModuleDir, loadedModuleName)
1950}
1951
Sasha Smundak3deb9682021-07-26 18:42:25 -07001952func (ctx *parseContext) addSoongNamespace(ns string) {
1953 if _, ok := ctx.soongNamespaces[ns]; ok {
1954 return
1955 }
1956 ctx.soongNamespaces[ns] = make(map[string]bool)
1957}
1958
1959func (ctx *parseContext) hasSoongNamespace(name string) bool {
1960 _, ok := ctx.soongNamespaces[name]
1961 return ok
1962}
1963
1964func (ctx *parseContext) updateSoongNamespace(replace bool, namespaceName string, varNames []string) {
1965 ctx.addSoongNamespace(namespaceName)
1966 vars := ctx.soongNamespaces[namespaceName]
1967 if replace {
1968 vars = make(map[string]bool)
1969 ctx.soongNamespaces[namespaceName] = vars
1970 }
1971 for _, v := range varNames {
1972 vars[v] = true
1973 }
1974}
1975
1976func (ctx *parseContext) hasNamespaceVar(namespaceName string, varName string) bool {
1977 vars, ok := ctx.soongNamespaces[namespaceName]
1978 if ok {
1979 _, ok = vars[varName]
1980 }
1981 return ok
1982}
1983
Sasha Smundak422b6142021-11-11 18:31:59 -08001984func (ctx *parseContext) errorLocation(node mkparser.Node) ErrorLocation {
1985 return ErrorLocation{ctx.script.mkFile, ctx.script.nodeLocator(node.Pos())}
1986}
1987
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001988func (ss *StarlarkScript) String() string {
1989 return NewGenerateContext(ss).emit()
1990}
1991
1992func (ss *StarlarkScript) SubConfigFiles() []string {
Sasha Smundak6609ba72021-07-22 18:32:56 -07001993
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001994 var subs []string
1995 for _, src := range ss.inherited {
1996 subs = append(subs, src.originalPath)
1997 }
1998 return subs
1999}
2000
2001func (ss *StarlarkScript) HasErrors() bool {
2002 return ss.hasErrors
2003}
2004
2005// Convert reads and parses a makefile. If successful, parsed tree
2006// is returned and then can be passed to String() to get the generated
2007// Starlark file.
2008func Convert(req Request) (*StarlarkScript, error) {
2009 reader := req.Reader
2010 if reader == nil {
2011 mkContents, err := ioutil.ReadFile(req.MkFile)
2012 if err != nil {
2013 return nil, err
2014 }
2015 reader = bytes.NewBuffer(mkContents)
2016 }
2017 parser := mkparser.NewParser(req.MkFile, reader)
2018 nodes, errs := parser.Parse()
2019 if len(errs) > 0 {
2020 for _, e := range errs {
2021 fmt.Fprintln(os.Stderr, "ERROR:", e)
2022 }
2023 return nil, fmt.Errorf("bad makefile %s", req.MkFile)
2024 }
2025 starScript := &StarlarkScript{
Sasha Smundak422b6142021-11-11 18:31:59 -08002026 moduleName: moduleNameForFile(req.MkFile),
2027 mkFile: req.MkFile,
Sasha Smundak422b6142021-11-11 18:31:59 -08002028 traceCalls: req.TraceCalls,
2029 sourceFS: req.SourceFS,
2030 makefileFinder: req.MakefileFinder,
2031 nodeLocator: func(pos mkparser.Pos) int { return parser.Unpack(pos).Line },
Cole Faustdd569ae2022-01-31 15:48:29 -08002032 nodes: make([]starlarkNode, 0),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002033 }
2034 ctx := newParseContext(starScript, nodes)
2035 ctx.outputSuffix = req.OutputSuffix
2036 ctx.outputDir = req.OutputDir
2037 ctx.errorLogger = req.ErrorLogger
2038 if len(req.TracedVariables) > 0 {
2039 ctx.tracedVariables = make(map[string]bool)
2040 for _, v := range req.TracedVariables {
2041 ctx.tracedVariables[v] = true
2042 }
2043 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002044 for ctx.hasNodes() && ctx.fatalError == nil {
Cole Faustdd569ae2022-01-31 15:48:29 -08002045 starScript.nodes = append(starScript.nodes, ctx.handleSimpleStatement(ctx.getNode())...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002046 }
2047 if ctx.fatalError != nil {
2048 return nil, ctx.fatalError
2049 }
2050 return starScript, nil
2051}
2052
Cole Faust864028a2021-12-01 13:43:17 -08002053func Launcher(mainModuleUri, inputVariablesUri, mainModuleName string) string {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002054 var buf bytes.Buffer
2055 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
Cole Faust864028a2021-12-01 13:43:17 -08002056 fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri)
Sasha Smundakd7d07ad2021-09-10 15:42:34 -07002057 fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri)
Cole Faust864028a2021-12-01 13:43:17 -08002058 fmt.Fprintf(&buf, "%s(%s(%q, init, input_variables_init))\n", cfnPrintVars, cfnMain, mainModuleName)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002059 return buf.String()
2060}
2061
Cole Faust6ed7cb42021-10-07 17:08:46 -07002062func BoardLauncher(mainModuleUri string, inputVariablesUri string) string {
2063 var buf bytes.Buffer
2064 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
2065 fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri)
2066 fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri)
Cole Fausta0604662022-02-28 11:53:58 -08002067 fmt.Fprintf(&buf, "%s(%s(init, input_variables_init))\n", cfnPrintVars, cfnBoardMain)
Cole Faust6ed7cb42021-10-07 17:08:46 -07002068 return buf.String()
2069}
2070
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002071func MakePath2ModuleName(mkPath string) string {
2072 return strings.TrimSuffix(mkPath, filepath.Ext(mkPath))
2073}