blob: 2707f0c5e73f655c41ef988888f04d3c8a957067 [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},
Cole Faust5a13aaf2022-04-27 17:49:35 -070089 "firstword": &simpleCallParser{name: baseName + ".first_word", returnType: starlarkTypeString},
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{},
Cole Faust5a13aaf2022-04-27 17:49:35 -0700100 "lastword": &simpleCallParser{name: baseName + ".last_word", returnType: starlarkTypeString},
Cole Faust1cc08852022-02-28 11:12:08 -0800101 "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 Faust94c4a9a2022-04-22 17:43:52 -0700119 "words": &wordsCallParser{},
Cole Faust1cc08852022-02-28 11:12:08 -0800120 "wildcard": &simpleCallParser{name: baseName + ".expand_wildcard", returnType: starlarkTypeList},
Cole Faust9ebf6e42021-12-13 14:08:34 -0800121}
122
Cole Faustf035d402022-03-28 14:02:50 -0700123// The same as knownFunctions, but returns a []starlarkNode instead of a starlarkExpr
124var knownNodeFunctions = map[string]interface {
125 parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode
126}{
127 "eval": &evalNodeParser{},
128 "if": &ifCallNodeParser{},
129 "inherit-product": &inheritProductCallParser{loadAlways: true},
130 "inherit-product-if-exists": &inheritProductCallParser{loadAlways: false},
131 "foreach": &foreachCallNodeParser{},
132}
133
Cole Faust1e275862022-04-26 14:28:04 -0700134// These look like variables, but are actually functions, and would give
135// undefined variable errors if we converted them as variables. Instead,
136// emit an error instead of converting them.
137var unsupportedFunctions = map[string]bool{
138 "local-generated-sources-dir": true,
139 "local-intermediates-dir": true,
140}
141
Cole Faust9ebf6e42021-12-13 14:08:34 -0800142// These are functions that we don't implement conversions for, but
143// we allow seeing their definitions in the product config files.
144var ignoredDefines = map[string]bool{
145 "find-word-in-list": true, // internal macro
146 "get-vendor-board-platforms": true, // internal macro, used by is-board-platform, etc.
147 "is-android-codename": true, // unused by product config
148 "is-android-codename-in-list": true, // unused by product config
149 "is-chipset-in-board-platform": true, // unused by product config
150 "is-chipset-prefix-in-board-platform": true, // unused by product config
151 "is-not-board-platform": true, // defined but never used
152 "is-platform-sdk-version-at-least": true, // unused by product config
153 "match-prefix": true, // internal macro
154 "match-word": true, // internal macro
155 "match-word-in-list": true, // internal macro
156 "tb-modules": true, // defined in hardware/amlogic/tb_modules/tb_detect.mk, unused
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800157}
158
Cole Faustb0d32ab2021-12-09 14:00:59 -0800159var identifierFullMatchRegex = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$")
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800160
161// Conversion request parameters
162type Request struct {
Sasha Smundak422b6142021-11-11 18:31:59 -0800163 MkFile string // file to convert
164 Reader io.Reader // if set, read input from this stream instead
Sasha Smundak422b6142021-11-11 18:31:59 -0800165 OutputSuffix string // generated Starlark files suffix
166 OutputDir string // if set, root of the output hierarchy
167 ErrorLogger ErrorLogger
168 TracedVariables []string // trace assignment to these variables
169 TraceCalls bool
170 SourceFS fs.FS
171 MakefileFinder MakefileFinder
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800172}
173
Sasha Smundak7d934b92021-11-10 12:20:01 -0800174// ErrorLogger prints errors and gathers error statistics.
175// Its NewError function is called on every error encountered during the conversion.
176type ErrorLogger interface {
Sasha Smundak422b6142021-11-11 18:31:59 -0800177 NewError(el ErrorLocation, node mkparser.Node, text string, args ...interface{})
178}
179
180type ErrorLocation struct {
181 MkFile string
182 MkLine int
183}
184
185func (el ErrorLocation) String() string {
186 return fmt.Sprintf("%s:%d", el.MkFile, el.MkLine)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800187}
188
189// Derives module name for a given file. It is base name
190// (file name without suffix), with some characters replaced to make it a Starlark identifier
191func moduleNameForFile(mkFile string) string {
192 base := strings.TrimSuffix(filepath.Base(mkFile), filepath.Ext(mkFile))
193 // TODO(asmundak): what else can be in the product file names?
Sasha Smundak6609ba72021-07-22 18:32:56 -0700194 return strings.NewReplacer("-", "_", ".", "_").Replace(base)
195
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800196}
197
198func cloneMakeString(mkString *mkparser.MakeString) *mkparser.MakeString {
199 r := &mkparser.MakeString{StringPos: mkString.StringPos}
200 r.Strings = append(r.Strings, mkString.Strings...)
201 r.Variables = append(r.Variables, mkString.Variables...)
202 return r
203}
204
205func isMakeControlFunc(s string) bool {
206 return s == "error" || s == "warning" || s == "info"
207}
208
Cole Faustf0632662022-04-07 13:59:24 -0700209// varAssignmentScope points to the last assignment for each variable
210// in the current block. It is used during the parsing to chain
211// the assignments to a variable together.
212type varAssignmentScope struct {
213 outer *varAssignmentScope
214 vars map[string]bool
215}
216
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800217// Starlark output generation context
218type generationContext struct {
Cole Faustf0632662022-04-07 13:59:24 -0700219 buf strings.Builder
220 starScript *StarlarkScript
221 indentLevel int
222 inAssignment bool
223 tracedCount int
224 varAssignments *varAssignmentScope
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800225}
226
227func NewGenerateContext(ss *StarlarkScript) *generationContext {
Cole Faustf0632662022-04-07 13:59:24 -0700228 return &generationContext{
229 starScript: ss,
230 varAssignments: &varAssignmentScope{
231 outer: nil,
232 vars: make(map[string]bool),
233 },
234 }
235}
236
237func (gctx *generationContext) pushVariableAssignments() {
238 va := &varAssignmentScope{
239 outer: gctx.varAssignments,
240 vars: make(map[string]bool),
241 }
242 gctx.varAssignments = va
243}
244
245func (gctx *generationContext) popVariableAssignments() {
246 gctx.varAssignments = gctx.varAssignments.outer
247}
248
249func (gctx *generationContext) hasBeenAssigned(v variable) bool {
250 for va := gctx.varAssignments; va != nil; va = va.outer {
251 if _, ok := va.vars[v.name()]; ok {
252 return true
253 }
254 }
255 return false
256}
257
258func (gctx *generationContext) setHasBeenAssigned(v variable) {
259 gctx.varAssignments.vars[v.name()] = true
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800260}
261
262// emit returns generated script
263func (gctx *generationContext) emit() string {
264 ss := gctx.starScript
265
266 // The emitted code has the following layout:
267 // <initial comments>
268 // preamble, i.e.,
269 // load statement for the runtime support
270 // load statement for each unique submodule pulled in by this one
271 // def init(g, handle):
272 // cfg = rblf.cfg(handle)
273 // <statements>
274 // <warning if conversion was not clean>
275
276 iNode := len(ss.nodes)
277 for i, node := range ss.nodes {
278 if _, ok := node.(*commentNode); !ok {
279 iNode = i
280 break
281 }
282 node.emit(gctx)
283 }
284
285 gctx.emitPreamble()
286
287 gctx.newLine()
288 // The arguments passed to the init function are the global dictionary
289 // ('g') and the product configuration dictionary ('cfg')
290 gctx.write("def init(g, handle):")
291 gctx.indentLevel++
292 if gctx.starScript.traceCalls {
293 gctx.newLine()
294 gctx.writef(`print(">%s")`, gctx.starScript.mkFile)
295 }
296 gctx.newLine()
297 gctx.writef("cfg = %s(handle)", cfnGetCfg)
298 for _, node := range ss.nodes[iNode:] {
299 node.emit(gctx)
300 }
301
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800302 if gctx.starScript.traceCalls {
303 gctx.newLine()
304 gctx.writef(`print("<%s")`, gctx.starScript.mkFile)
305 }
306 gctx.indentLevel--
307 gctx.write("\n")
308 return gctx.buf.String()
309}
310
311func (gctx *generationContext) emitPreamble() {
312 gctx.newLine()
313 gctx.writef("load(%q, %q)", baseUri, baseName)
314 // Emit exactly one load statement for each URI.
315 loadedSubConfigs := make(map[string]string)
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800316 for _, mi := range gctx.starScript.inherited {
317 uri := mi.path
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800318 if m, ok := loadedSubConfigs[uri]; ok {
319 // No need to emit load statement, but fix module name.
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800320 mi.moduleLocalName = m
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800321 continue
322 }
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800323 if mi.optional || mi.missing {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800324 uri += "|init"
325 }
326 gctx.newLine()
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800327 gctx.writef("load(%q, %s = \"init\")", uri, mi.entryName())
328 loadedSubConfigs[uri] = mi.moduleLocalName
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800329 }
330 gctx.write("\n")
331}
332
333func (gctx *generationContext) emitPass() {
334 gctx.newLine()
335 gctx.write("pass")
336}
337
338func (gctx *generationContext) write(ss ...string) {
339 for _, s := range ss {
340 gctx.buf.WriteString(s)
341 }
342}
343
344func (gctx *generationContext) writef(format string, args ...interface{}) {
345 gctx.write(fmt.Sprintf(format, args...))
346}
347
348func (gctx *generationContext) newLine() {
349 if gctx.buf.Len() == 0 {
350 return
351 }
352 gctx.write("\n")
353 gctx.writef("%*s", 2*gctx.indentLevel, "")
354}
355
Sasha Smundak422b6142021-11-11 18:31:59 -0800356func (gctx *generationContext) emitConversionError(el ErrorLocation, message string) {
357 gctx.writef(`rblf.mk2rbc_error("%s", %q)`, el, message)
358}
359
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800360func (gctx *generationContext) emitLoadCheck(im inheritedModule) {
361 if !im.needsLoadCheck() {
362 return
363 }
364 gctx.newLine()
365 gctx.writef("if not %s:", im.entryName())
366 gctx.indentLevel++
367 gctx.newLine()
368 gctx.write(`rblf.mkerror("`, gctx.starScript.mkFile, `", "Cannot find %s" % (`)
369 im.pathExpr().emit(gctx)
370 gctx.write("))")
371 gctx.indentLevel--
372}
373
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800374type knownVariable struct {
375 name string
376 class varClass
377 valueType starlarkType
378}
379
380type knownVariables map[string]knownVariable
381
382func (pcv knownVariables) NewVariable(name string, varClass varClass, valueType starlarkType) {
383 v, exists := pcv[name]
384 if !exists {
385 pcv[name] = knownVariable{name, varClass, valueType}
386 return
387 }
388 // Conflict resolution:
389 // * config class trumps everything
390 // * any type trumps unknown type
391 match := varClass == v.class
392 if !match {
393 if varClass == VarClassConfig {
394 v.class = VarClassConfig
395 match = true
396 } else if v.class == VarClassConfig {
397 match = true
398 }
399 }
400 if valueType != v.valueType {
401 if valueType != starlarkTypeUnknown {
402 if v.valueType == starlarkTypeUnknown {
403 v.valueType = valueType
404 } else {
405 match = false
406 }
407 }
408 }
409 if !match {
410 fmt.Fprintf(os.Stderr, "cannot redefine %s as %v/%v (already defined as %v/%v)\n",
411 name, varClass, valueType, v.class, v.valueType)
412 }
413}
414
415// All known product variables.
416var KnownVariables = make(knownVariables)
417
418func init() {
419 for _, kv := range []string{
420 // Kernel-related variables that we know are lists.
421 "BOARD_VENDOR_KERNEL_MODULES",
422 "BOARD_VENDOR_RAMDISK_KERNEL_MODULES",
423 "BOARD_VENDOR_RAMDISK_KERNEL_MODULES_LOAD",
424 "BOARD_RECOVERY_KERNEL_MODULES",
425 // Other variables we knwo are lists
426 "ART_APEX_JARS",
427 } {
428 KnownVariables.NewVariable(kv, VarClassSoong, starlarkTypeList)
429 }
430}
431
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800432// Information about the generated Starlark script.
433type StarlarkScript struct {
Sasha Smundak422b6142021-11-11 18:31:59 -0800434 mkFile string
435 moduleName string
436 mkPos scanner.Position
437 nodes []starlarkNode
438 inherited []*moduleInfo
439 hasErrors bool
Sasha Smundak422b6142021-11-11 18:31:59 -0800440 traceCalls bool // print enter/exit each init function
441 sourceFS fs.FS
442 makefileFinder MakefileFinder
443 nodeLocator func(pos mkparser.Pos) int
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800444}
445
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800446// parseContext holds the script we are generating and all the ephemeral data
447// needed during the parsing.
448type parseContext struct {
449 script *StarlarkScript
450 nodes []mkparser.Node // Makefile as parsed by mkparser
451 currentNodeIndex int // Node in it we are processing
452 ifNestLevel int
453 moduleNameCount map[string]int // count of imported modules with given basename
454 fatalError error
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800455 outputSuffix string
Sasha Smundak7d934b92021-11-10 12:20:01 -0800456 errorLogger ErrorLogger
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800457 tracedVariables map[string]bool // variables to be traced in the generated script
458 variables map[string]variable
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800459 outputDir string
Sasha Smundak6609ba72021-07-22 18:32:56 -0700460 dependentModules map[string]*moduleInfo
Sasha Smundak3deb9682021-07-26 18:42:25 -0700461 soongNamespaces map[string]map[string]bool
Sasha Smundak6d852dd2021-09-27 20:34:39 -0700462 includeTops []string
Cole Faustf92c9f22022-03-14 14:35:50 -0700463 typeHints map[string]starlarkType
464 atTopOfMakefile bool
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800465}
466
467func newParseContext(ss *StarlarkScript, nodes []mkparser.Node) *parseContext {
468 predefined := []struct{ name, value string }{
469 {"SRC_TARGET_DIR", filepath.Join("build", "make", "target")},
470 {"LOCAL_PATH", filepath.Dir(ss.mkFile)},
Cole Faust5a13aaf2022-04-27 17:49:35 -0700471 {"MAKEFILE_LIST", ss.mkFile},
Cole Faust9b6111a2022-02-02 15:38:33 -0800472 {"TOPDIR", ""}, // TOPDIR is just set to an empty string in cleanbuild.mk and core.mk
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800473 // TODO(asmundak): maybe read it from build/make/core/envsetup.mk?
474 {"TARGET_COPY_OUT_SYSTEM", "system"},
475 {"TARGET_COPY_OUT_SYSTEM_OTHER", "system_other"},
476 {"TARGET_COPY_OUT_DATA", "data"},
477 {"TARGET_COPY_OUT_ASAN", filepath.Join("data", "asan")},
478 {"TARGET_COPY_OUT_OEM", "oem"},
479 {"TARGET_COPY_OUT_RAMDISK", "ramdisk"},
480 {"TARGET_COPY_OUT_DEBUG_RAMDISK", "debug_ramdisk"},
481 {"TARGET_COPY_OUT_VENDOR_DEBUG_RAMDISK", "vendor_debug_ramdisk"},
482 {"TARGET_COPY_OUT_TEST_HARNESS_RAMDISK", "test_harness_ramdisk"},
483 {"TARGET_COPY_OUT_ROOT", "root"},
484 {"TARGET_COPY_OUT_RECOVERY", "recovery"},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800485 {"TARGET_COPY_OUT_VENDOR_RAMDISK", "vendor_ramdisk"},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800486 // TODO(asmundak): to process internal config files, we need the following variables:
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800487 // TARGET_VENDOR
488 // target_base_product
489 //
490
491 // the following utility variables are set in build/make/common/core.mk:
492 {"empty", ""},
493 {"space", " "},
494 {"comma", ","},
495 {"newline", "\n"},
496 {"pound", "#"},
497 {"backslash", "\\"},
498 }
499 ctx := &parseContext{
500 script: ss,
501 nodes: nodes,
502 currentNodeIndex: 0,
503 ifNestLevel: 0,
504 moduleNameCount: make(map[string]int),
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800505 variables: make(map[string]variable),
Sasha Smundak6609ba72021-07-22 18:32:56 -0700506 dependentModules: make(map[string]*moduleInfo),
Sasha Smundak3deb9682021-07-26 18:42:25 -0700507 soongNamespaces: make(map[string]map[string]bool),
Cole Faust6c934f62022-01-06 15:51:12 -0800508 includeTops: []string{},
Cole Faustf92c9f22022-03-14 14:35:50 -0700509 typeHints: make(map[string]starlarkType),
510 atTopOfMakefile: true,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800511 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800512 for _, item := range predefined {
513 ctx.variables[item.name] = &predefinedVariable{
514 baseVariable: baseVariable{nam: item.name, typ: starlarkTypeString},
515 value: &stringLiteralExpr{item.value},
516 }
517 }
518
519 return ctx
520}
521
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800522func (ctx *parseContext) hasNodes() bool {
523 return ctx.currentNodeIndex < len(ctx.nodes)
524}
525
526func (ctx *parseContext) getNode() mkparser.Node {
527 if !ctx.hasNodes() {
528 return nil
529 }
530 node := ctx.nodes[ctx.currentNodeIndex]
531 ctx.currentNodeIndex++
532 return node
533}
534
535func (ctx *parseContext) backNode() {
536 if ctx.currentNodeIndex <= 0 {
537 panic("Cannot back off")
538 }
539 ctx.currentNodeIndex--
540}
541
Cole Faustdd569ae2022-01-31 15:48:29 -0800542func (ctx *parseContext) handleAssignment(a *mkparser.Assignment) []starlarkNode {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800543 // Handle only simple variables
Cole Faust00afd4f2022-04-26 14:01:56 -0700544 if !a.Name.Const() || a.Target != nil {
Cole Faustdd569ae2022-01-31 15:48:29 -0800545 return []starlarkNode{ctx.newBadNode(a, "Only simple variables are handled")}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800546 }
547 name := a.Name.Strings[0]
Sasha Smundakea3bc3a2021-11-10 13:06:42 -0800548 // The `override` directive
549 // override FOO :=
550 // is parsed as an assignment to a variable named `override FOO`.
551 // There are very few places where `override` is used, just flag it.
552 if strings.HasPrefix(name, "override ") {
Cole Faustdd569ae2022-01-31 15:48:29 -0800553 return []starlarkNode{ctx.newBadNode(a, "cannot handle override directive")}
Sasha Smundakea3bc3a2021-11-10 13:06:42 -0800554 }
Cole Faust5d5fcc32022-04-26 18:02:05 -0700555 if name == ".KATI_READONLY" {
556 // Skip assignments to .KATI_READONLY. If it was in the output file, it
557 // would be an error because it would be sorted before the definition of
558 // the variable it's trying to make readonly.
559 return []starlarkNode{}
560 }
Sasha Smundakea3bc3a2021-11-10 13:06:42 -0800561
Cole Faustc00184e2021-11-08 12:08:57 -0800562 // Soong configuration
Sasha Smundak3deb9682021-07-26 18:42:25 -0700563 if strings.HasPrefix(name, soongNsPrefix) {
Cole Faustdd569ae2022-01-31 15:48:29 -0800564 return ctx.handleSoongNsAssignment(strings.TrimPrefix(name, soongNsPrefix), a)
Sasha Smundak3deb9682021-07-26 18:42:25 -0700565 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800566 lhs := ctx.addVariable(name)
567 if lhs == nil {
Cole Faustdd569ae2022-01-31 15:48:29 -0800568 return []starlarkNode{ctx.newBadNode(a, "unknown variable %s", name)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800569 }
Cole Faust3c4fc992022-02-28 16:05:01 -0800570 _, isTraced := ctx.tracedVariables[lhs.name()]
Sasha Smundak422b6142021-11-11 18:31:59 -0800571 asgn := &assignmentNode{lhs: lhs, mkValue: a.Value, isTraced: isTraced, location: ctx.errorLocation(a)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800572 if lhs.valueType() == starlarkTypeUnknown {
573 // Try to divine variable type from the RHS
574 asgn.value = ctx.parseMakeString(a, a.Value)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800575 inferred_type := asgn.value.typ()
576 if inferred_type != starlarkTypeUnknown {
Sasha Smundak9d011ab2021-07-09 16:00:57 -0700577 lhs.setValueType(inferred_type)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800578 }
579 }
580 if lhs.valueType() == starlarkTypeList {
Cole Faustdd569ae2022-01-31 15:48:29 -0800581 xConcat, xBad := ctx.buildConcatExpr(a)
582 if xBad != nil {
Cole Faust1e275862022-04-26 14:28:04 -0700583 asgn.value = xBad
584 } else {
585 switch len(xConcat.items) {
586 case 0:
587 asgn.value = &listExpr{}
588 case 1:
589 asgn.value = xConcat.items[0]
590 default:
591 asgn.value = xConcat
592 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800593 }
594 } else {
595 asgn.value = ctx.parseMakeString(a, a.Value)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800596 }
597
Cole Faust421a1922022-03-16 14:35:45 -0700598 if asgn.lhs.valueType() == starlarkTypeString &&
599 asgn.value.typ() != starlarkTypeUnknown &&
600 asgn.value.typ() != starlarkTypeString {
601 asgn.value = &toStringExpr{expr: asgn.value}
602 }
603
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800604 switch a.Type {
605 case "=", ":=":
606 asgn.flavor = asgnSet
607 case "+=":
Cole Fauste2a37982022-03-09 16:00:17 -0800608 asgn.flavor = asgnAppend
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800609 case "?=":
610 asgn.flavor = asgnMaybeSet
611 default:
612 panic(fmt.Errorf("unexpected assignment type %s", a.Type))
613 }
614
Cole Faustdd569ae2022-01-31 15:48:29 -0800615 return []starlarkNode{asgn}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800616}
617
Cole Faustdd569ae2022-01-31 15:48:29 -0800618func (ctx *parseContext) handleSoongNsAssignment(name string, asgn *mkparser.Assignment) []starlarkNode {
Sasha Smundak3deb9682021-07-26 18:42:25 -0700619 val := ctx.parseMakeString(asgn, asgn.Value)
620 if xBad, ok := val.(*badExpr); ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800621 return []starlarkNode{&exprNode{expr: xBad}}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700622 }
Sasha Smundak3deb9682021-07-26 18:42:25 -0700623
624 // Unfortunately, Soong namespaces can be set up by directly setting corresponding Make
625 // variables instead of via add_soong_config_namespace + add_soong_config_var_value.
626 // Try to divine the call from the assignment as follows:
627 if name == "NAMESPACES" {
628 // Upon seeng
629 // SOONG_CONFIG_NAMESPACES += foo
630 // remember that there is a namespace `foo` and act as we saw
631 // $(call add_soong_config_namespace,foo)
632 s, ok := maybeString(val)
633 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800634 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 -0700635 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800636 result := make([]starlarkNode, 0)
Sasha Smundak3deb9682021-07-26 18:42:25 -0700637 for _, ns := range strings.Fields(s) {
638 ctx.addSoongNamespace(ns)
Cole Faustdd569ae2022-01-31 15:48:29 -0800639 result = append(result, &exprNode{&callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -0800640 name: baseName + ".soong_config_namespace",
641 args: []starlarkExpr{&globalsExpr{}, &stringLiteralExpr{ns}},
Sasha Smundak3deb9682021-07-26 18:42:25 -0700642 returnType: starlarkTypeVoid,
643 }})
644 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800645 return result
Sasha Smundak3deb9682021-07-26 18:42:25 -0700646 } else {
647 // Upon seeing
648 // SOONG_CONFIG_x_y = v
649 // find a namespace called `x` and act as if we encountered
Cole Faustc00184e2021-11-08 12:08:57 -0800650 // $(call soong_config_set,x,y,v)
Sasha Smundak3deb9682021-07-26 18:42:25 -0700651 // or check that `x_y` is a namespace, and then add the RHS of this assignment as variables in
652 // it.
653 // Emit an error in the ambiguous situation (namespaces `foo_bar` with a variable `baz`
654 // and `foo` with a variable `bar_baz`.
655 namespaceName := ""
656 if ctx.hasSoongNamespace(name) {
657 namespaceName = name
658 }
659 var varName string
660 for pos, ch := range name {
661 if !(ch == '_' && ctx.hasSoongNamespace(name[0:pos])) {
662 continue
663 }
664 if namespaceName != "" {
Cole Faustdd569ae2022-01-31 15:48:29 -0800665 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 -0700666 }
667 namespaceName = name[0:pos]
668 varName = name[pos+1:]
669 }
670 if namespaceName == "" {
Cole Faustdd569ae2022-01-31 15:48:29 -0800671 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 -0700672 }
673 if varName == "" {
674 // Remember variables in this namespace
675 s, ok := maybeString(val)
676 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800677 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 -0700678 }
679 ctx.updateSoongNamespace(asgn.Type != "+=", namespaceName, strings.Fields(s))
Cole Faustdd569ae2022-01-31 15:48:29 -0800680 return []starlarkNode{}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700681 }
682
683 // Finally, handle assignment to a namespace variable
684 if !ctx.hasNamespaceVar(namespaceName, varName) {
Cole Faustdd569ae2022-01-31 15:48:29 -0800685 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 -0700686 }
Cole Faust9ebf6e42021-12-13 14:08:34 -0800687 fname := baseName + "." + soongConfigAssign
Sasha Smundak65b547e2021-09-17 15:35:41 -0700688 if asgn.Type == "+=" {
Cole Faust9ebf6e42021-12-13 14:08:34 -0800689 fname = baseName + "." + soongConfigAppend
Sasha Smundak65b547e2021-09-17 15:35:41 -0700690 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800691 return []starlarkNode{&exprNode{&callExpr{
Sasha Smundak65b547e2021-09-17 15:35:41 -0700692 name: fname,
Cole Faust9ebf6e42021-12-13 14:08:34 -0800693 args: []starlarkExpr{&globalsExpr{}, &stringLiteralExpr{namespaceName}, &stringLiteralExpr{varName}, val},
Sasha Smundak3deb9682021-07-26 18:42:25 -0700694 returnType: starlarkTypeVoid,
Cole Faustdd569ae2022-01-31 15:48:29 -0800695 }}}
Sasha Smundak3deb9682021-07-26 18:42:25 -0700696 }
697}
698
Cole Faustdd569ae2022-01-31 15:48:29 -0800699func (ctx *parseContext) buildConcatExpr(a *mkparser.Assignment) (*concatExpr, *badExpr) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800700 xConcat := &concatExpr{}
701 var xItemList *listExpr
702 addToItemList := func(x ...starlarkExpr) {
703 if xItemList == nil {
704 xItemList = &listExpr{[]starlarkExpr{}}
705 }
706 xItemList.items = append(xItemList.items, x...)
707 }
708 finishItemList := func() {
709 if xItemList != nil {
710 xConcat.items = append(xConcat.items, xItemList)
711 xItemList = nil
712 }
713 }
714
715 items := a.Value.Words()
716 for _, item := range items {
717 // A function call in RHS is supposed to return a list, all other item
718 // expressions return individual elements.
719 switch x := ctx.parseMakeString(a, item).(type) {
720 case *badExpr:
Cole Faustdd569ae2022-01-31 15:48:29 -0800721 return nil, x
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800722 case *stringLiteralExpr:
723 addToItemList(maybeConvertToStringList(x).(*listExpr).items...)
724 default:
725 switch x.typ() {
726 case starlarkTypeList:
727 finishItemList()
728 xConcat.items = append(xConcat.items, x)
729 case starlarkTypeString:
730 finishItemList()
731 xConcat.items = append(xConcat.items, &callExpr{
732 object: x,
733 name: "split",
734 args: nil,
735 returnType: starlarkTypeList,
736 })
737 default:
738 addToItemList(x)
739 }
740 }
741 }
742 if xItemList != nil {
743 xConcat.items = append(xConcat.items, xItemList)
744 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800745 return xConcat, nil
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800746}
747
Sasha Smundak6609ba72021-07-22 18:32:56 -0700748func (ctx *parseContext) newDependentModule(path string, optional bool) *moduleInfo {
749 modulePath := ctx.loadedModulePath(path)
750 if mi, ok := ctx.dependentModules[modulePath]; ok {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700751 mi.optional = mi.optional && optional
Sasha Smundak6609ba72021-07-22 18:32:56 -0700752 return mi
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800753 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800754 moduleName := moduleNameForFile(path)
755 moduleLocalName := "_" + moduleName
756 n, found := ctx.moduleNameCount[moduleName]
757 if found {
758 moduleLocalName += fmt.Sprintf("%d", n)
759 }
760 ctx.moduleNameCount[moduleName] = n + 1
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800761 _, err := fs.Stat(ctx.script.sourceFS, path)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700762 mi := &moduleInfo{
763 path: modulePath,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800764 originalPath: path,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800765 moduleLocalName: moduleLocalName,
Sasha Smundak6609ba72021-07-22 18:32:56 -0700766 optional: optional,
Sasha Smundak6bc132a2022-01-10 17:02:16 -0800767 missing: err != nil,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800768 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700769 ctx.dependentModules[modulePath] = mi
770 ctx.script.inherited = append(ctx.script.inherited, mi)
771 return mi
772}
773
774func (ctx *parseContext) handleSubConfig(
Cole Faustdd569ae2022-01-31 15:48:29 -0800775 v mkparser.Node, pathExpr starlarkExpr, loadAlways bool, processModule func(inheritedModule) starlarkNode) []starlarkNode {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700776
Cole Faust62e05112022-04-05 17:56:11 -0700777 // Allow seeing $(sort $(wildcard realPathExpr)) or $(wildcard realPathExpr)
778 // because those are functionally the same as not having the sort/wildcard calls.
779 if ce, ok := pathExpr.(*callExpr); ok && ce.name == "rblf.mksort" && len(ce.args) == 1 {
780 if ce2, ok2 := ce.args[0].(*callExpr); ok2 && ce2.name == "rblf.expand_wildcard" && len(ce2.args) == 1 {
781 pathExpr = ce2.args[0]
782 }
783 } else if ce2, ok2 := pathExpr.(*callExpr); ok2 && ce2.name == "rblf.expand_wildcard" && len(ce2.args) == 1 {
784 pathExpr = ce2.args[0]
785 }
786
Sasha Smundak6609ba72021-07-22 18:32:56 -0700787 // In a simple case, the name of a module to inherit/include is known statically.
788 if path, ok := maybeString(pathExpr); ok {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700789 // Note that even if this directive loads a module unconditionally, a module may be
790 // absent without causing any harm if this directive is inside an if/else block.
791 moduleShouldExist := loadAlways && ctx.ifNestLevel == 0
Sasha Smundak6609ba72021-07-22 18:32:56 -0700792 if strings.Contains(path, "*") {
793 if paths, err := fs.Glob(ctx.script.sourceFS, path); err == nil {
Cole Faust62e05112022-04-05 17:56:11 -0700794 sort.Strings(paths)
Cole Faustdd569ae2022-01-31 15:48:29 -0800795 result := make([]starlarkNode, 0)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700796 for _, p := range paths {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700797 mi := ctx.newDependentModule(p, !moduleShouldExist)
Cole Faustdd569ae2022-01-31 15:48:29 -0800798 result = append(result, processModule(inheritedStaticModule{mi, loadAlways}))
Sasha Smundak6609ba72021-07-22 18:32:56 -0700799 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800800 return result
Sasha Smundak6609ba72021-07-22 18:32:56 -0700801 } else {
Cole Faustdd569ae2022-01-31 15:48:29 -0800802 return []starlarkNode{ctx.newBadNode(v, "cannot glob wildcard argument")}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700803 }
804 } else {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700805 mi := ctx.newDependentModule(path, !moduleShouldExist)
Cole Faustdd569ae2022-01-31 15:48:29 -0800806 return []starlarkNode{processModule(inheritedStaticModule{mi, loadAlways})}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700807 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700808 }
809
810 // If module path references variables (e.g., $(v1)/foo/$(v2)/device-config.mk), find all the paths in the
811 // source tree that may be a match and the corresponding variable values. For instance, if the source tree
812 // contains vendor1/foo/abc/dev.mk and vendor2/foo/def/dev.mk, the first one will be inherited when
813 // (v1, v2) == ('vendor1', 'abc'), and the second one when (v1, v2) == ('vendor2', 'def').
814 // We then emit the code that loads all of them, e.g.:
815 // load("//vendor1/foo/abc:dev.rbc", _dev1_init="init")
816 // load("//vendor2/foo/def/dev.rbc", _dev2_init="init")
817 // And then inherit it as follows:
818 // _e = {
819 // "vendor1/foo/abc/dev.mk": ("vendor1/foo/abc/dev", _dev1_init),
820 // "vendor2/foo/def/dev.mk": ("vendor2/foo/def/dev", _dev_init2) }.get("%s/foo/%s/dev.mk" % (v1, v2))
821 // if _e:
822 // rblf.inherit(handle, _e[0], _e[1])
823 //
824 var matchingPaths []string
Cole Faust9df1d732022-04-26 16:27:22 -0700825 var needsWarning = false
826 if interpolate, ok := pathExpr.(*interpolateExpr); ok {
827 pathPattern := []string{interpolate.chunks[0]}
828 for _, chunk := range interpolate.chunks[1:] {
829 if chunk != "" {
830 pathPattern = append(pathPattern, chunk)
831 }
832 }
Cole Faust74ac0272022-06-14 12:45:26 -0700833 if len(pathPattern) == 1 {
834 pathPattern = append(pathPattern, "")
Cole Faust9df1d732022-04-26 16:27:22 -0700835 }
Cole Faust74ac0272022-06-14 12:45:26 -0700836 matchingPaths = ctx.findMatchingPaths(pathPattern)
Cole Faust9df1d732022-04-26 16:27:22 -0700837 needsWarning = pathPattern[0] == "" && len(ctx.includeTops) == 0
838 } else if len(ctx.includeTops) > 0 {
Cole Faust74ac0272022-06-14 12:45:26 -0700839 matchingPaths = append(matchingPaths, ctx.findMatchingPaths([]string{"", ""})...)
Cole Faust9df1d732022-04-26 16:27:22 -0700840 } else {
Cole Faustdd569ae2022-01-31 15:48:29 -0800841 return []starlarkNode{ctx.newBadNode(v, "inherit-product/include argument is too complex")}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700842 }
843
Sasha Smundak6609ba72021-07-22 18:32:56 -0700844 // Safeguard against $(call inherit-product,$(PRODUCT_PATH))
Sasha Smundak90be8c52021-08-03 11:06:10 -0700845 const maxMatchingFiles = 150
Sasha Smundak6609ba72021-07-22 18:32:56 -0700846 if len(matchingPaths) > maxMatchingFiles {
Cole Faustdd569ae2022-01-31 15:48:29 -0800847 return []starlarkNode{ctx.newBadNode(v, "there are >%d files matching the pattern, please rewrite it", maxMatchingFiles)}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700848 }
Cole Faust93f8d392022-03-02 13:31:30 -0800849
Cole Faust9df1d732022-04-26 16:27:22 -0700850 res := inheritedDynamicModule{pathExpr, []*moduleInfo{}, loadAlways, ctx.errorLocation(v), needsWarning}
Cole Faust93f8d392022-03-02 13:31:30 -0800851 for _, p := range matchingPaths {
852 // A product configuration files discovered dynamically may attempt to inherit
853 // from another one which does not exist in this source tree. Prevent load errors
854 // by always loading the dynamic files as optional.
855 res.candidateModules = append(res.candidateModules, ctx.newDependentModule(p, true))
Sasha Smundak6609ba72021-07-22 18:32:56 -0700856 }
Cole Faust93f8d392022-03-02 13:31:30 -0800857 return []starlarkNode{processModule(res)}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700858}
859
860func (ctx *parseContext) findMatchingPaths(pattern []string) []string {
Cole Faust9b6111a2022-02-02 15:38:33 -0800861 files := ctx.script.makefileFinder.Find(".")
Sasha Smundak6609ba72021-07-22 18:32:56 -0700862 if len(pattern) == 0 {
863 return files
864 }
865
866 // Create regular expression from the pattern
Cole Faust74ac0272022-06-14 12:45:26 -0700867 regexString := "^" + regexp.QuoteMeta(pattern[0])
Sasha Smundak6609ba72021-07-22 18:32:56 -0700868 for _, s := range pattern[1:] {
Cole Faust74ac0272022-06-14 12:45:26 -0700869 regexString += ".*" + regexp.QuoteMeta(s)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700870 }
Cole Faust74ac0272022-06-14 12:45:26 -0700871 regexString += "$"
872 rex := regexp.MustCompile(regexString)
873
874 includeTopRegexString := ""
875 if len(ctx.includeTops) > 0 {
876 for i, top := range ctx.includeTops {
877 if i > 0 {
878 includeTopRegexString += "|"
879 }
880 includeTopRegexString += "^" + regexp.QuoteMeta(top)
881 }
882 } else {
883 includeTopRegexString = ".*"
884 }
885
886 includeTopRegex := regexp.MustCompile(includeTopRegexString)
Sasha Smundak6609ba72021-07-22 18:32:56 -0700887
888 // Now match
889 var res []string
890 for _, p := range files {
Cole Faust74ac0272022-06-14 12:45:26 -0700891 if rex.MatchString(p) && includeTopRegex.MatchString(p) {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700892 res = append(res, p)
893 }
894 }
895 return res
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800896}
897
Cole Faustf035d402022-03-28 14:02:50 -0700898type inheritProductCallParser struct {
899 loadAlways bool
900}
901
902func (p *inheritProductCallParser) parse(ctx *parseContext, v mkparser.Node, args *mkparser.MakeString) []starlarkNode {
Cole Faust9ebf6e42021-12-13 14:08:34 -0800903 args.TrimLeftSpaces()
904 args.TrimRightSpaces()
905 pathExpr := ctx.parseMakeString(v, args)
906 if _, ok := pathExpr.(*badExpr); ok {
Cole Faustdd569ae2022-01-31 15:48:29 -0800907 return []starlarkNode{ctx.newBadNode(v, "Unable to parse argument to inherit")}
Cole Faust9ebf6e42021-12-13 14:08:34 -0800908 }
Cole Faustf035d402022-03-28 14:02:50 -0700909 return ctx.handleSubConfig(v, pathExpr, p.loadAlways, func(im inheritedModule) starlarkNode {
910 return &inheritNode{im, p.loadAlways}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700911 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800912}
913
Cole Faust20052982022-04-22 14:43:55 -0700914func (ctx *parseContext) handleInclude(v *mkparser.Directive) []starlarkNode {
915 loadAlways := v.Name[0] != '-'
916 return ctx.handleSubConfig(v, ctx.parseMakeString(v, v.Args), loadAlways, func(im inheritedModule) starlarkNode {
Cole Faustdd569ae2022-01-31 15:48:29 -0800917 return &includeNode{im, loadAlways}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700918 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800919}
920
Cole Faustdd569ae2022-01-31 15:48:29 -0800921func (ctx *parseContext) handleVariable(v *mkparser.Variable) []starlarkNode {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800922 // Handle:
923 // $(call inherit-product,...)
924 // $(call inherit-product-if-exists,...)
925 // $(info xxx)
926 // $(warning xxx)
927 // $(error xxx)
Cole Faust9ebf6e42021-12-13 14:08:34 -0800928 // $(call other-custom-functions,...)
929
Cole Faustf035d402022-03-28 14:02:50 -0700930 if name, args, ok := ctx.maybeParseFunctionCall(v, v.Name); ok {
931 if kf, ok := knownNodeFunctions[name]; ok {
932 return kf.parse(ctx, v, args)
933 }
Cole Faust9ebf6e42021-12-13 14:08:34 -0800934 }
Cole Faustf035d402022-03-28 14:02:50 -0700935
Cole Faustdd569ae2022-01-31 15:48:29 -0800936 return []starlarkNode{&exprNode{expr: ctx.parseReference(v, v.Name)}}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800937}
938
Cole Faustdd569ae2022-01-31 15:48:29 -0800939func (ctx *parseContext) maybeHandleDefine(directive *mkparser.Directive) starlarkNode {
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700940 macro_name := strings.Fields(directive.Args.Strings[0])[0]
941 // Ignore the macros that we handle
Cole Faust9ebf6e42021-12-13 14:08:34 -0800942 _, ignored := ignoredDefines[macro_name]
943 _, known := knownFunctions[macro_name]
944 if !ignored && !known {
Cole Faustdd569ae2022-01-31 15:48:29 -0800945 return ctx.newBadNode(directive, "define is not supported: %s", macro_name)
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700946 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800947 return nil
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800948}
949
Cole Faustdd569ae2022-01-31 15:48:29 -0800950func (ctx *parseContext) handleIfBlock(ifDirective *mkparser.Directive) starlarkNode {
951 ssSwitch := &switchNode{
952 ssCases: []*switchCase{ctx.processBranch(ifDirective)},
953 }
954 for ctx.hasNodes() && ctx.fatalError == nil {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800955 node := ctx.getNode()
956 switch x := node.(type) {
957 case *mkparser.Directive:
958 switch x.Name {
959 case "else", "elifdef", "elifndef", "elifeq", "elifneq":
Cole Faustdd569ae2022-01-31 15:48:29 -0800960 ssSwitch.ssCases = append(ssSwitch.ssCases, ctx.processBranch(x))
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800961 case "endif":
Cole Faustdd569ae2022-01-31 15:48:29 -0800962 return ssSwitch
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800963 default:
Cole Faustdd569ae2022-01-31 15:48:29 -0800964 return ctx.newBadNode(node, "unexpected directive %s", x.Name)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800965 }
966 default:
Cole Faustdd569ae2022-01-31 15:48:29 -0800967 return ctx.newBadNode(ifDirective, "unexpected statement")
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800968 }
969 }
970 if ctx.fatalError == nil {
971 ctx.fatalError = fmt.Errorf("no matching endif for %s", ifDirective.Dump())
972 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800973 return ctx.newBadNode(ifDirective, "no matching endif for %s", ifDirective.Dump())
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800974}
975
976// processBranch processes a single branch (if/elseif/else) until the next directive
977// on the same level.
Cole Faustdd569ae2022-01-31 15:48:29 -0800978func (ctx *parseContext) processBranch(check *mkparser.Directive) *switchCase {
979 block := &switchCase{gate: ctx.parseCondition(check)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800980 defer func() {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800981 ctx.ifNestLevel--
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800982 }()
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800983 ctx.ifNestLevel++
984
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800985 for ctx.hasNodes() {
986 node := ctx.getNode()
Cole Faust591a1fe2021-11-08 15:37:57 -0800987 if d, ok := node.(*mkparser.Directive); ok {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800988 switch d.Name {
989 case "else", "elifdef", "elifndef", "elifeq", "elifneq", "endif":
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800990 ctx.backNode()
Cole Faustdd569ae2022-01-31 15:48:29 -0800991 return block
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800992 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800993 }
Cole Faustdd569ae2022-01-31 15:48:29 -0800994 block.nodes = append(block.nodes, ctx.handleSimpleStatement(node)...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800995 }
996 ctx.fatalError = fmt.Errorf("no matching endif for %s", check.Dump())
Cole Faustdd569ae2022-01-31 15:48:29 -0800997 return block
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800998}
999
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001000func (ctx *parseContext) parseCondition(check *mkparser.Directive) starlarkNode {
1001 switch check.Name {
1002 case "ifdef", "ifndef", "elifdef", "elifndef":
Cole Faust71514c02022-01-27 17:21:41 -08001003 if !check.Args.Const() {
Cole Faustdd569ae2022-01-31 15:48:29 -08001004 return ctx.newBadNode(check, "ifdef variable ref too complex: %s", check.Args.Dump())
Cole Faust71514c02022-01-27 17:21:41 -08001005 }
Cole Faustf0632662022-04-07 13:59:24 -07001006 v := NewVariableRefExpr(ctx.addVariable(check.Args.Strings[0]))
Cole Faust71514c02022-01-27 17:21:41 -08001007 if strings.HasSuffix(check.Name, "ndef") {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001008 v = &notExpr{v}
1009 }
1010 return &ifNode{
1011 isElif: strings.HasPrefix(check.Name, "elif"),
1012 expr: v,
1013 }
1014 case "ifeq", "ifneq", "elifeq", "elifneq":
1015 return &ifNode{
1016 isElif: strings.HasPrefix(check.Name, "elif"),
1017 expr: ctx.parseCompare(check),
1018 }
1019 case "else":
1020 return &elseNode{}
1021 default:
1022 panic(fmt.Errorf("%s: unknown directive: %s", ctx.script.mkFile, check.Dump()))
1023 }
1024}
1025
1026func (ctx *parseContext) newBadExpr(node mkparser.Node, text string, args ...interface{}) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001027 if ctx.errorLogger != nil {
Sasha Smundak422b6142021-11-11 18:31:59 -08001028 ctx.errorLogger.NewError(ctx.errorLocation(node), node, text, args...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001029 }
1030 ctx.script.hasErrors = true
Cole Faustdd569ae2022-01-31 15:48:29 -08001031 return &badExpr{errorLocation: ctx.errorLocation(node), message: fmt.Sprintf(text, args...)}
1032}
1033
1034// records that the given node failed to be converted and includes an explanatory message
1035func (ctx *parseContext) newBadNode(failedNode mkparser.Node, message string, args ...interface{}) starlarkNode {
1036 return &exprNode{ctx.newBadExpr(failedNode, message, args...)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001037}
1038
1039func (ctx *parseContext) parseCompare(cond *mkparser.Directive) starlarkExpr {
1040 // Strip outer parentheses
1041 mkArg := cloneMakeString(cond.Args)
1042 mkArg.Strings[0] = strings.TrimLeft(mkArg.Strings[0], "( ")
1043 n := len(mkArg.Strings)
1044 mkArg.Strings[n-1] = strings.TrimRight(mkArg.Strings[n-1], ") ")
1045 args := mkArg.Split(",")
1046 // TODO(asmundak): handle the case where the arguments are in quotes and space-separated
1047 if len(args) != 2 {
1048 return ctx.newBadExpr(cond, "ifeq/ifneq len(args) != 2 %s", cond.Dump())
1049 }
1050 args[0].TrimRightSpaces()
1051 args[1].TrimLeftSpaces()
1052
1053 isEq := !strings.HasSuffix(cond.Name, "neq")
Cole Faustf8320212021-11-10 15:05:07 -08001054 xLeft := ctx.parseMakeString(cond, args[0])
1055 xRight := ctx.parseMakeString(cond, args[1])
1056 if bad, ok := xLeft.(*badExpr); ok {
1057 return bad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001058 }
Cole Faustf8320212021-11-10 15:05:07 -08001059 if bad, ok := xRight.(*badExpr); ok {
1060 return bad
1061 }
1062
1063 if expr, ok := ctx.parseCompareSpecialCases(cond, xLeft, xRight); ok {
1064 return expr
1065 }
1066
Cole Faust9ebf6e42021-12-13 14:08:34 -08001067 var stringOperand string
1068 var otherOperand starlarkExpr
1069 if s, ok := maybeString(xLeft); ok {
1070 stringOperand = s
1071 otherOperand = xRight
1072 } else if s, ok := maybeString(xRight); ok {
1073 stringOperand = s
1074 otherOperand = xLeft
1075 }
1076
Cole Faust9ebf6e42021-12-13 14:08:34 -08001077 // If we've identified one of the operands as being a string literal, check
1078 // for some special cases we can do to simplify the resulting expression.
1079 if otherOperand != nil {
1080 if stringOperand == "" {
1081 if isEq {
Cole Faustf035d402022-03-28 14:02:50 -07001082 return negateExpr(otherOperand)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001083 } else {
1084 return otherOperand
1085 }
1086 }
1087 if stringOperand == "true" && otherOperand.typ() == starlarkTypeBool {
1088 if !isEq {
Cole Faustf035d402022-03-28 14:02:50 -07001089 return negateExpr(otherOperand)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001090 } else {
1091 return otherOperand
1092 }
1093 }
Cole Fausta99afdf2022-04-26 12:06:49 -07001094 if otherOperand.typ() == starlarkTypeList {
1095 fields := strings.Fields(stringOperand)
1096 elements := make([]starlarkExpr, len(fields))
1097 for i, s := range fields {
1098 elements[i] = &stringLiteralExpr{literal: s}
1099 }
1100 return &eqExpr{
1101 left: otherOperand,
1102 right: &listExpr{elements},
1103 isEq: isEq,
1104 }
1105 }
Cole Faustb1103e22022-01-06 15:22:05 -08001106 if intOperand, err := strconv.Atoi(strings.TrimSpace(stringOperand)); err == nil && otherOperand.typ() == starlarkTypeInt {
1107 return &eqExpr{
1108 left: otherOperand,
1109 right: &intLiteralExpr{literal: intOperand},
1110 isEq: isEq,
1111 }
1112 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001113 }
1114
Cole Faustf8320212021-11-10 15:05:07 -08001115 return &eqExpr{left: xLeft, right: xRight, isEq: isEq}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001116}
1117
Cole Faustf8320212021-11-10 15:05:07 -08001118// Given an if statement's directive and the left/right starlarkExprs,
1119// check if the starlarkExprs are one of a few hardcoded special cases
Cole Faust9932f752022-02-08 11:56:25 -08001120// that can be converted to a simpler equality expression than simply comparing
Cole Faustf8320212021-11-10 15:05:07 -08001121// the two.
1122func (ctx *parseContext) parseCompareSpecialCases(directive *mkparser.Directive, left starlarkExpr,
1123 right starlarkExpr) (starlarkExpr, bool) {
1124 isEq := !strings.HasSuffix(directive.Name, "neq")
1125
1126 // All the special cases require a call on one side and a
1127 // string literal/variable on the other. Turn the left/right variables into
1128 // call/value variables, and return false if that's not possible.
1129 var value starlarkExpr = nil
1130 call, ok := left.(*callExpr)
1131 if ok {
1132 switch right.(type) {
1133 case *stringLiteralExpr, *variableRefExpr:
1134 value = right
1135 }
1136 } else {
1137 call, _ = right.(*callExpr)
1138 switch left.(type) {
1139 case *stringLiteralExpr, *variableRefExpr:
1140 value = left
1141 }
1142 }
1143
1144 if call == nil || value == nil {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001145 return nil, false
1146 }
Cole Faustf8320212021-11-10 15:05:07 -08001147
Cole Faustf8320212021-11-10 15:05:07 -08001148 switch call.name {
Cole Faust9932f752022-02-08 11:56:25 -08001149 case baseName + ".filter":
1150 return ctx.parseCompareFilterFuncResult(directive, call, value, isEq)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001151 case baseName + ".findstring":
Cole Faustf8320212021-11-10 15:05:07 -08001152 return ctx.parseCheckFindstringFuncResult(directive, call, value, !isEq), true
Cole Faust9ebf6e42021-12-13 14:08:34 -08001153 case baseName + ".strip":
Cole Faustf8320212021-11-10 15:05:07 -08001154 return ctx.parseCompareStripFuncResult(directive, call, value, !isEq), true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001155 }
Cole Faustf8320212021-11-10 15:05:07 -08001156 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001157}
1158
1159func (ctx *parseContext) parseCompareFilterFuncResult(cond *mkparser.Directive,
Cole Faust9932f752022-02-08 11:56:25 -08001160 filterFuncCall *callExpr, xValue starlarkExpr, negate bool) (starlarkExpr, bool) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001161 // We handle:
Sasha Smundak0554d762021-07-08 18:26:12 -07001162 // * ifeq/ifneq (,$(filter v1 v2 ..., EXPR) becomes if EXPR not in/in ["v1", "v2", ...]
1163 // * ifeq/ifneq (,$(filter EXPR, v1 v2 ...) becomes if EXPR not in/in ["v1", "v2", ...]
Cole Faust9932f752022-02-08 11:56:25 -08001164 if x, ok := xValue.(*stringLiteralExpr); !ok || x.literal != "" {
1165 return nil, false
1166 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001167 xPattern := filterFuncCall.args[0]
1168 xText := filterFuncCall.args[1]
1169 var xInList *stringLiteralExpr
Sasha Smundak0554d762021-07-08 18:26:12 -07001170 var expr starlarkExpr
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001171 var ok bool
Cole Faust9932f752022-02-08 11:56:25 -08001172 if xInList, ok = xPattern.(*stringLiteralExpr); ok && !strings.ContainsRune(xInList.literal, '%') && xText.typ() == starlarkTypeList {
1173 expr = xText
1174 } else if xInList, ok = xText.(*stringLiteralExpr); ok {
1175 expr = xPattern
1176 } else {
1177 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001178 }
Cole Faust9932f752022-02-08 11:56:25 -08001179 slExpr := newStringListExpr(strings.Fields(xInList.literal))
1180 // Generate simpler code for the common cases:
1181 if expr.typ() == starlarkTypeList {
1182 if len(slExpr.items) == 1 {
1183 // Checking that a string belongs to list
1184 return &inExpr{isNot: negate, list: expr, expr: slExpr.items[0]}, true
Sasha Smundak0554d762021-07-08 18:26:12 -07001185 } else {
Cole Faust9932f752022-02-08 11:56:25 -08001186 return nil, false
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001187 }
Cole Faust9932f752022-02-08 11:56:25 -08001188 } else if len(slExpr.items) == 1 {
1189 return &eqExpr{left: expr, right: slExpr.items[0], isEq: !negate}, true
1190 } else {
1191 return &inExpr{isNot: negate, list: newStringListExpr(strings.Fields(xInList.literal)), expr: expr}, true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001192 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001193}
1194
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001195func (ctx *parseContext) parseCheckFindstringFuncResult(directive *mkparser.Directive,
1196 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001197 if isEmptyString(xValue) {
1198 return &eqExpr{
1199 left: &callExpr{
1200 object: xCall.args[1],
1201 name: "find",
1202 args: []starlarkExpr{xCall.args[0]},
1203 returnType: starlarkTypeInt,
1204 },
1205 right: &intLiteralExpr{-1},
1206 isEq: !negate,
1207 }
Cole Faust0e9418c2021-12-13 16:33:25 -08001208 } else if s, ok := maybeString(xValue); ok {
1209 if s2, ok := maybeString(xCall.args[0]); ok && s == s2 {
1210 return &eqExpr{
1211 left: &callExpr{
1212 object: xCall.args[1],
1213 name: "find",
1214 args: []starlarkExpr{xCall.args[0]},
1215 returnType: starlarkTypeInt,
1216 },
1217 right: &intLiteralExpr{-1},
1218 isEq: negate,
1219 }
1220 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001221 }
Cole Faust0e9418c2021-12-13 16:33:25 -08001222 return ctx.newBadExpr(directive, "$(findstring) can only be compared to nothing or its first argument")
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001223}
1224
1225func (ctx *parseContext) parseCompareStripFuncResult(directive *mkparser.Directive,
1226 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
1227 if _, ok := xValue.(*stringLiteralExpr); !ok {
1228 return ctx.newBadExpr(directive, "strip result can be compared only to string: %s", xValue)
1229 }
1230 return &eqExpr{
1231 left: &callExpr{
1232 name: "strip",
1233 args: xCall.args,
1234 returnType: starlarkTypeString,
1235 },
1236 right: xValue, isEq: !negate}
1237}
1238
Cole Faustf035d402022-03-28 14:02:50 -07001239func (ctx *parseContext) maybeParseFunctionCall(node mkparser.Node, ref *mkparser.MakeString) (name string, args *mkparser.MakeString, ok bool) {
1240 ref.TrimLeftSpaces()
1241 ref.TrimRightSpaces()
1242
1243 words := ref.SplitN(" ", 2)
1244 if !words[0].Const() {
1245 return "", nil, false
1246 }
1247
1248 name = words[0].Dump()
1249 args = mkparser.SimpleMakeString("", words[0].Pos())
1250 if len(words) >= 2 {
1251 args = words[1]
1252 }
1253 args.TrimLeftSpaces()
1254 if name == "call" {
1255 words = args.SplitN(",", 2)
1256 if words[0].Empty() || !words[0].Const() {
1257 return "", nil, false
1258 }
1259 name = words[0].Dump()
1260 if len(words) < 2 {
Cole Faust6c41b8a2022-04-13 13:53:48 -07001261 args = mkparser.SimpleMakeString("", words[0].Pos())
Cole Faustf035d402022-03-28 14:02:50 -07001262 } else {
1263 args = words[1]
1264 }
1265 }
1266 ok = true
1267 return
1268}
1269
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001270// parses $(...), returning an expression
1271func (ctx *parseContext) parseReference(node mkparser.Node, ref *mkparser.MakeString) starlarkExpr {
1272 ref.TrimLeftSpaces()
1273 ref.TrimRightSpaces()
1274 refDump := ref.Dump()
1275
1276 // Handle only the case where the first (or only) word is constant
1277 words := ref.SplitN(" ", 2)
1278 if !words[0].Const() {
Cole Faust13238772022-04-28 14:29:57 -07001279 if len(words) == 1 {
1280 expr := ctx.parseMakeString(node, ref)
1281 return &callExpr{
1282 object: &identifierExpr{"cfg"},
1283 name: "get",
1284 args: []starlarkExpr{
1285 expr,
1286 &callExpr{
1287 object: &identifierExpr{"g"},
1288 name: "get",
1289 args: []starlarkExpr{
1290 expr,
1291 &stringLiteralExpr{literal: ""},
1292 },
1293 returnType: starlarkTypeUnknown,
1294 },
1295 },
1296 returnType: starlarkTypeUnknown,
1297 }
1298 } else {
1299 return ctx.newBadExpr(node, "reference is too complex: %s", refDump)
1300 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001301 }
1302
Cole Faust1e275862022-04-26 14:28:04 -07001303 if name, _, ok := ctx.maybeParseFunctionCall(node, ref); ok {
1304 if _, unsupported := unsupportedFunctions[name]; unsupported {
1305 return ctx.newBadExpr(node, "%s is not supported", refDump)
1306 }
1307 }
1308
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001309 // If it is a single word, it can be a simple variable
1310 // reference or a function call
Cole Faustf035d402022-03-28 14:02:50 -07001311 if len(words) == 1 && !isMakeControlFunc(refDump) && refDump != "shell" && refDump != "eval" {
Sasha Smundak65b547e2021-09-17 15:35:41 -07001312 if strings.HasPrefix(refDump, soongNsPrefix) {
1313 // TODO (asmundak): if we find many, maybe handle them.
Cole Faustc00184e2021-11-08 12:08:57 -08001314 return ctx.newBadExpr(node, "SOONG_CONFIG_ variables cannot be referenced, use soong_config_get instead: %s", refDump)
Sasha Smundak65b547e2021-09-17 15:35:41 -07001315 }
Cole Faustc36c9622021-12-07 15:20:45 -08001316 // Handle substitution references: https://www.gnu.org/software/make/manual/html_node/Substitution-Refs.html
1317 if strings.Contains(refDump, ":") {
1318 parts := strings.SplitN(refDump, ":", 2)
1319 substParts := strings.SplitN(parts[1], "=", 2)
1320 if len(substParts) < 2 || strings.Count(substParts[0], "%") > 1 {
1321 return ctx.newBadExpr(node, "Invalid substitution reference")
1322 }
1323 if !strings.Contains(substParts[0], "%") {
1324 if strings.Contains(substParts[1], "%") {
1325 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.")
1326 }
1327 substParts[0] = "%" + substParts[0]
1328 substParts[1] = "%" + substParts[1]
1329 }
1330 v := ctx.addVariable(parts[0])
1331 if v == nil {
1332 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1333 }
1334 return &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001335 name: baseName + ".mkpatsubst",
1336 returnType: starlarkTypeString,
Cole Faustc36c9622021-12-07 15:20:45 -08001337 args: []starlarkExpr{
1338 &stringLiteralExpr{literal: substParts[0]},
1339 &stringLiteralExpr{literal: substParts[1]},
Cole Faustf0632662022-04-07 13:59:24 -07001340 NewVariableRefExpr(v),
Cole Faustc36c9622021-12-07 15:20:45 -08001341 },
1342 }
1343 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001344 if v := ctx.addVariable(refDump); v != nil {
Cole Faustf0632662022-04-07 13:59:24 -07001345 return NewVariableRefExpr(v)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001346 }
1347 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1348 }
1349
Cole Faustf035d402022-03-28 14:02:50 -07001350 if name, args, ok := ctx.maybeParseFunctionCall(node, ref); ok {
1351 if kf, found := knownFunctions[name]; found {
1352 return kf.parse(ctx, node, args)
Sasha Smundak6609ba72021-07-22 18:32:56 -07001353 } else {
Cole Faustf035d402022-03-28 14:02:50 -07001354 return ctx.newBadExpr(node, "cannot handle invoking %s", name)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001355 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001356 }
Cole Faust1e275862022-04-26 14:28:04 -07001357 return ctx.newBadExpr(node, "cannot handle %s", refDump)
Cole Faust9ebf6e42021-12-13 14:08:34 -08001358}
1359
1360type simpleCallParser struct {
1361 name string
1362 returnType starlarkType
1363 addGlobals bool
Cole Faust1cc08852022-02-28 11:12:08 -08001364 addHandle bool
Cole Faust9ebf6e42021-12-13 14:08:34 -08001365}
1366
1367func (p *simpleCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1368 expr := &callExpr{name: p.name, returnType: p.returnType}
1369 if p.addGlobals {
1370 expr.args = append(expr.args, &globalsExpr{})
1371 }
Cole Faust1cc08852022-02-28 11:12:08 -08001372 if p.addHandle {
1373 expr.args = append(expr.args, &identifierExpr{name: "handle"})
1374 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001375 for _, arg := range args.Split(",") {
1376 arg.TrimLeftSpaces()
1377 arg.TrimRightSpaces()
1378 x := ctx.parseMakeString(node, arg)
1379 if xBad, ok := x.(*badExpr); ok {
1380 return xBad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001381 }
Cole Faust9ebf6e42021-12-13 14:08:34 -08001382 expr.args = append(expr.args, x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001383 }
1384 return expr
1385}
1386
Cole Faust9ebf6e42021-12-13 14:08:34 -08001387type makeControlFuncParser struct {
1388 name string
1389}
1390
1391func (p *makeControlFuncParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1392 // Make control functions need special treatment as everything
1393 // after the name is a single text argument
1394 x := ctx.parseMakeString(node, args)
1395 if xBad, ok := x.(*badExpr); ok {
1396 return xBad
1397 }
1398 return &callExpr{
1399 name: p.name,
1400 args: []starlarkExpr{
1401 &stringLiteralExpr{ctx.script.mkFile},
1402 x,
1403 },
1404 returnType: starlarkTypeUnknown,
1405 }
1406}
1407
1408type shellCallParser struct{}
1409
1410func (p *shellCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1411 // Shell functions need special treatment as everything
1412 // after the name is a single text argument
1413 x := ctx.parseMakeString(node, args)
1414 if xBad, ok := x.(*badExpr); ok {
1415 return xBad
1416 }
1417 return &callExpr{
1418 name: baseName + ".shell",
1419 args: []starlarkExpr{x},
1420 returnType: starlarkTypeUnknown,
1421 }
1422}
1423
1424type myDirCallParser struct{}
1425
1426func (p *myDirCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1427 if !args.Empty() {
1428 return ctx.newBadExpr(node, "my-dir function cannot have any arguments passed to it.")
1429 }
Cole Faustf5adedc2022-03-18 14:05:06 -07001430 return &stringLiteralExpr{literal: filepath.Dir(ctx.script.mkFile)}
Cole Faust9ebf6e42021-12-13 14:08:34 -08001431}
1432
Cole Faust9ebf6e42021-12-13 14:08:34 -08001433type isProductInListCallParser struct{}
1434
1435func (p *isProductInListCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1436 if args.Empty() {
1437 return ctx.newBadExpr(node, "is-product-in-list requires an argument")
1438 }
1439 return &inExpr{
Cole Faustf0632662022-04-07 13:59:24 -07001440 expr: NewVariableRefExpr(ctx.addVariable("TARGET_PRODUCT")),
Cole Faust9ebf6e42021-12-13 14:08:34 -08001441 list: maybeConvertToStringList(ctx.parseMakeString(node, args)),
1442 isNot: false,
1443 }
1444}
1445
1446type isVendorBoardPlatformCallParser struct{}
1447
1448func (p *isVendorBoardPlatformCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1449 if args.Empty() || !identifierFullMatchRegex.MatchString(args.Dump()) {
1450 return ctx.newBadExpr(node, "cannot handle non-constant argument to is-vendor-board-platform")
1451 }
1452 return &inExpr{
Cole Faustf0632662022-04-07 13:59:24 -07001453 expr: NewVariableRefExpr(ctx.addVariable("TARGET_BOARD_PLATFORM")),
1454 list: NewVariableRefExpr(ctx.addVariable(args.Dump() + "_BOARD_PLATFORMS")),
Cole Faust9ebf6e42021-12-13 14:08:34 -08001455 isNot: false,
1456 }
1457}
1458
1459type isVendorBoardQcomCallParser struct{}
1460
1461func (p *isVendorBoardQcomCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1462 if !args.Empty() {
1463 return ctx.newBadExpr(node, "is-vendor-board-qcom does not accept any arguments")
1464 }
1465 return &inExpr{
Cole Faustf0632662022-04-07 13:59:24 -07001466 expr: NewVariableRefExpr(ctx.addVariable("TARGET_BOARD_PLATFORM")),
1467 list: NewVariableRefExpr(ctx.addVariable("QCOM_BOARD_PLATFORMS")),
Cole Faust9ebf6e42021-12-13 14:08:34 -08001468 isNot: false,
1469 }
1470}
1471
1472type substCallParser struct {
1473 fname string
1474}
1475
1476func (p *substCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001477 words := args.Split(",")
1478 if len(words) != 3 {
Cole Faust9ebf6e42021-12-13 14:08:34 -08001479 return ctx.newBadExpr(node, "%s function should have 3 arguments", p.fname)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001480 }
Sasha Smundak35434ed2021-11-05 16:29:56 -07001481 from := ctx.parseMakeString(node, words[0])
1482 if xBad, ok := from.(*badExpr); ok {
1483 return xBad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001484 }
Sasha Smundak35434ed2021-11-05 16:29:56 -07001485 to := ctx.parseMakeString(node, words[1])
1486 if xBad, ok := to.(*badExpr); ok {
1487 return xBad
1488 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001489 words[2].TrimLeftSpaces()
1490 words[2].TrimRightSpaces()
1491 obj := ctx.parseMakeString(node, words[2])
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001492 typ := obj.typ()
Cole Faust9ebf6e42021-12-13 14:08:34 -08001493 if typ == starlarkTypeString && p.fname == "subst" {
Sasha Smundak94b41c72021-07-12 18:30:42 -07001494 // Optimization: if it's $(subst from, to, string), emit string.replace(from, to)
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001495 return &callExpr{
1496 object: obj,
1497 name: "replace",
Sasha Smundak35434ed2021-11-05 16:29:56 -07001498 args: []starlarkExpr{from, to},
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001499 returnType: typ,
1500 }
1501 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001502 return &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001503 name: baseName + ".mk" + p.fname,
Sasha Smundak35434ed2021-11-05 16:29:56 -07001504 args: []starlarkExpr{from, to, obj},
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001505 returnType: obj.typ(),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001506 }
1507}
1508
Cole Faust9ebf6e42021-12-13 14:08:34 -08001509type ifCallParser struct{}
1510
1511func (p *ifCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Cole Faust4eadba72021-12-07 11:54:52 -08001512 words := args.Split(",")
1513 if len(words) != 2 && len(words) != 3 {
1514 return ctx.newBadExpr(node, "if function should have 2 or 3 arguments, found "+strconv.Itoa(len(words)))
1515 }
1516 condition := ctx.parseMakeString(node, words[0])
1517 ifTrue := ctx.parseMakeString(node, words[1])
1518 var ifFalse starlarkExpr
1519 if len(words) == 3 {
1520 ifFalse = ctx.parseMakeString(node, words[2])
1521 } else {
1522 switch ifTrue.typ() {
1523 case starlarkTypeList:
1524 ifFalse = &listExpr{items: []starlarkExpr{}}
1525 case starlarkTypeInt:
1526 ifFalse = &intLiteralExpr{literal: 0}
1527 case starlarkTypeBool:
1528 ifFalse = &boolLiteralExpr{literal: false}
1529 default:
1530 ifFalse = &stringLiteralExpr{literal: ""}
1531 }
1532 }
1533 return &ifExpr{
1534 condition,
1535 ifTrue,
1536 ifFalse,
1537 }
1538}
1539
Cole Faustf035d402022-03-28 14:02:50 -07001540type ifCallNodeParser struct{}
Cole Faust9ebf6e42021-12-13 14:08:34 -08001541
Cole Faustf035d402022-03-28 14:02:50 -07001542func (p *ifCallNodeParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode {
1543 words := args.Split(",")
1544 if len(words) != 2 && len(words) != 3 {
1545 return []starlarkNode{ctx.newBadNode(node, "if function should have 2 or 3 arguments, found "+strconv.Itoa(len(words)))}
1546 }
1547
1548 ifn := &ifNode{expr: ctx.parseMakeString(node, words[0])}
1549 cases := []*switchCase{
1550 {
1551 gate: ifn,
1552 nodes: ctx.parseNodeMakeString(node, words[1]),
1553 },
1554 }
1555 if len(words) == 3 {
1556 cases = append(cases, &switchCase{
1557 gate: &elseNode{},
1558 nodes: ctx.parseNodeMakeString(node, words[2]),
1559 })
1560 }
1561 if len(cases) == 2 {
1562 if len(cases[1].nodes) == 0 {
1563 // Remove else branch if it has no contents
1564 cases = cases[:1]
1565 } else if len(cases[0].nodes) == 0 {
1566 // If the if branch has no contents but the else does,
1567 // move them to the if and negate its condition
1568 ifn.expr = negateExpr(ifn.expr)
1569 cases[0].nodes = cases[1].nodes
1570 cases = cases[:1]
1571 }
1572 }
1573
1574 return []starlarkNode{&switchNode{ssCases: cases}}
1575}
1576
1577type foreachCallParser struct{}
1578
1579func (p *foreachCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Cole Faustb0d32ab2021-12-09 14:00:59 -08001580 words := args.Split(",")
1581 if len(words) != 3 {
1582 return ctx.newBadExpr(node, "foreach function should have 3 arguments, found "+strconv.Itoa(len(words)))
1583 }
1584 if !words[0].Const() || words[0].Empty() || !identifierFullMatchRegex.MatchString(words[0].Strings[0]) {
1585 return ctx.newBadExpr(node, "first argument to foreach function must be a simple string identifier")
1586 }
1587 loopVarName := words[0].Strings[0]
1588 list := ctx.parseMakeString(node, words[1])
1589 action := ctx.parseMakeString(node, words[2]).transform(func(expr starlarkExpr) starlarkExpr {
1590 if varRefExpr, ok := expr.(*variableRefExpr); ok && varRefExpr.ref.name() == loopVarName {
1591 return &identifierExpr{loopVarName}
1592 }
1593 return nil
1594 })
1595
1596 if list.typ() != starlarkTypeList {
1597 list = &callExpr{
Cole Faust9ebf6e42021-12-13 14:08:34 -08001598 name: baseName + ".words",
1599 returnType: starlarkTypeList,
Cole Faustb0d32ab2021-12-09 14:00:59 -08001600 args: []starlarkExpr{list},
1601 }
1602 }
1603
Cole Faust72374fc2022-05-05 11:45:04 -07001604 var result starlarkExpr = &foreachExpr{
Cole Faustb0d32ab2021-12-09 14:00:59 -08001605 varName: loopVarName,
1606 list: list,
1607 action: action,
1608 }
Cole Faust72374fc2022-05-05 11:45:04 -07001609
1610 if action.typ() == starlarkTypeList {
1611 result = &callExpr{
1612 name: baseName + ".flatten_2d_list",
1613 args: []starlarkExpr{result},
1614 returnType: starlarkTypeList,
1615 }
1616 }
1617
1618 return result
Cole Faustb0d32ab2021-12-09 14:00:59 -08001619}
1620
Cole Faustf035d402022-03-28 14:02:50 -07001621func transformNode(node starlarkNode, transformer func(expr starlarkExpr) starlarkExpr) {
1622 switch a := node.(type) {
1623 case *ifNode:
1624 a.expr = a.expr.transform(transformer)
1625 case *switchCase:
1626 transformNode(a.gate, transformer)
1627 for _, n := range a.nodes {
1628 transformNode(n, transformer)
1629 }
1630 case *switchNode:
1631 for _, n := range a.ssCases {
1632 transformNode(n, transformer)
1633 }
1634 case *exprNode:
1635 a.expr = a.expr.transform(transformer)
1636 case *assignmentNode:
1637 a.value = a.value.transform(transformer)
1638 case *foreachNode:
1639 a.list = a.list.transform(transformer)
1640 for _, n := range a.actions {
1641 transformNode(n, transformer)
1642 }
Cole Faust9df1d732022-04-26 16:27:22 -07001643 case *inheritNode:
1644 if b, ok := a.module.(inheritedDynamicModule); ok {
1645 b.path = b.path.transform(transformer)
1646 a.module = b
1647 }
1648 case *includeNode:
1649 if b, ok := a.module.(inheritedDynamicModule); ok {
1650 b.path = b.path.transform(transformer)
1651 a.module = b
1652 }
Cole Faustf035d402022-03-28 14:02:50 -07001653 }
1654}
1655
1656type foreachCallNodeParser struct{}
1657
1658func (p *foreachCallNodeParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode {
1659 words := args.Split(",")
1660 if len(words) != 3 {
1661 return []starlarkNode{ctx.newBadNode(node, "foreach function should have 3 arguments, found "+strconv.Itoa(len(words)))}
1662 }
1663 if !words[0].Const() || words[0].Empty() || !identifierFullMatchRegex.MatchString(words[0].Strings[0]) {
1664 return []starlarkNode{ctx.newBadNode(node, "first argument to foreach function must be a simple string identifier")}
1665 }
1666
1667 loopVarName := words[0].Strings[0]
1668
1669 list := ctx.parseMakeString(node, words[1])
1670 if list.typ() != starlarkTypeList {
1671 list = &callExpr{
1672 name: baseName + ".words",
1673 returnType: starlarkTypeList,
1674 args: []starlarkExpr{list},
1675 }
1676 }
1677
1678 actions := ctx.parseNodeMakeString(node, words[2])
1679 // TODO(colefaust): Replace transforming code with something more elegant
1680 for _, action := range actions {
1681 transformNode(action, func(expr starlarkExpr) starlarkExpr {
1682 if varRefExpr, ok := expr.(*variableRefExpr); ok && varRefExpr.ref.name() == loopVarName {
1683 return &identifierExpr{loopVarName}
1684 }
1685 return nil
1686 })
1687 }
1688
1689 return []starlarkNode{&foreachNode{
1690 varName: loopVarName,
1691 list: list,
1692 actions: actions,
1693 }}
1694}
1695
Cole Faust9ebf6e42021-12-13 14:08:34 -08001696type wordCallParser struct{}
1697
1698func (p *wordCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001699 words := args.Split(",")
1700 if len(words) != 2 {
1701 return ctx.newBadExpr(node, "word function should have 2 arguments")
1702 }
Cole Faust94c4a9a2022-04-22 17:43:52 -07001703 var index = 0
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001704 if words[0].Const() {
Cole Faust94c4a9a2022-04-22 17:43:52 -07001705 if i, err := strconv.Atoi(strings.TrimSpace(words[0].Strings[0])); err == nil {
1706 index = i
1707 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001708 }
1709 if index < 1 {
1710 return ctx.newBadExpr(node, "word index should be constant positive integer")
1711 }
1712 words[1].TrimLeftSpaces()
1713 words[1].TrimRightSpaces()
1714 array := ctx.parseMakeString(node, words[1])
Cole Faust94c4a9a2022-04-22 17:43:52 -07001715 if bad, ok := array.(*badExpr); ok {
1716 return bad
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001717 }
1718 if array.typ() != starlarkTypeList {
Cole Faust94c4a9a2022-04-22 17:43:52 -07001719 array = &callExpr{
1720 name: baseName + ".words",
1721 args: []starlarkExpr{array},
1722 returnType: starlarkTypeList,
1723 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001724 }
Cole Faust94c4a9a2022-04-22 17:43:52 -07001725 return &indexExpr{array, &intLiteralExpr{index - 1}}
1726}
1727
1728type wordsCallParser struct{}
1729
1730func (p *wordsCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1731 args.TrimLeftSpaces()
1732 args.TrimRightSpaces()
1733 array := ctx.parseMakeString(node, args)
1734 if bad, ok := array.(*badExpr); ok {
1735 return bad
1736 }
1737 if array.typ() != starlarkTypeList {
1738 array = &callExpr{
1739 name: baseName + ".words",
1740 args: []starlarkExpr{array},
1741 returnType: starlarkTypeList,
1742 }
1743 }
1744 return &callExpr{
1745 name: "len",
1746 args: []starlarkExpr{array},
1747 returnType: starlarkTypeInt,
1748 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001749}
1750
Cole Faustb1103e22022-01-06 15:22:05 -08001751func parseIntegerArguments(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString, expectedArgs int) ([]starlarkExpr, error) {
1752 parsedArgs := make([]starlarkExpr, 0)
1753 for _, arg := range args.Split(",") {
1754 expr := ctx.parseMakeString(node, arg)
1755 if expr.typ() == starlarkTypeList {
1756 return nil, fmt.Errorf("argument to math argument has type list, which cannot be converted to int")
1757 }
1758 if s, ok := maybeString(expr); ok {
1759 intVal, err := strconv.Atoi(strings.TrimSpace(s))
1760 if err != nil {
1761 return nil, err
1762 }
1763 expr = &intLiteralExpr{literal: intVal}
1764 } else if expr.typ() != starlarkTypeInt {
1765 expr = &callExpr{
1766 name: "int",
1767 args: []starlarkExpr{expr},
1768 returnType: starlarkTypeInt,
1769 }
1770 }
1771 parsedArgs = append(parsedArgs, expr)
1772 }
1773 if len(parsedArgs) != expectedArgs {
1774 return nil, fmt.Errorf("function should have %d arguments", expectedArgs)
1775 }
1776 return parsedArgs, nil
1777}
1778
1779type mathComparisonCallParser struct {
1780 op string
1781}
1782
1783func (p *mathComparisonCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1784 parsedArgs, err := parseIntegerArguments(ctx, node, args, 2)
1785 if err != nil {
1786 return ctx.newBadExpr(node, err.Error())
1787 }
1788 return &binaryOpExpr{
1789 left: parsedArgs[0],
1790 right: parsedArgs[1],
1791 op: p.op,
1792 returnType: starlarkTypeBool,
1793 }
1794}
1795
1796type mathMaxOrMinCallParser struct {
1797 function string
1798}
1799
1800func (p *mathMaxOrMinCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1801 parsedArgs, err := parseIntegerArguments(ctx, node, args, 2)
1802 if err != nil {
1803 return ctx.newBadExpr(node, err.Error())
1804 }
1805 return &callExpr{
1806 object: nil,
1807 name: p.function,
1808 args: parsedArgs,
1809 returnType: starlarkTypeInt,
1810 }
1811}
1812
Cole Faustf035d402022-03-28 14:02:50 -07001813type evalNodeParser struct{}
1814
1815func (p *evalNodeParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) []starlarkNode {
1816 parser := mkparser.NewParser("Eval expression", strings.NewReader(args.Dump()))
1817 nodes, errs := parser.Parse()
1818 if errs != nil {
1819 return []starlarkNode{ctx.newBadNode(node, "Unable to parse eval statement")}
1820 }
1821
1822 if len(nodes) == 0 {
1823 return []starlarkNode{}
1824 } else if len(nodes) == 1 {
1825 switch n := nodes[0].(type) {
1826 case *mkparser.Assignment:
1827 if n.Name.Const() {
1828 return ctx.handleAssignment(n)
1829 }
1830 case *mkparser.Comment:
1831 return []starlarkNode{&commentNode{strings.TrimSpace("#" + n.Comment)}}
Cole Faust20052982022-04-22 14:43:55 -07001832 case *mkparser.Directive:
1833 if n.Name == "include" || n.Name == "-include" {
1834 return ctx.handleInclude(n)
1835 }
1836 case *mkparser.Variable:
1837 // Technically inherit-product(-if-exists) don't need to be put inside
1838 // an eval, but some makefiles do it, presumably because they copy+pasted
1839 // from a $(eval include ...)
1840 if name, _, ok := ctx.maybeParseFunctionCall(n, n.Name); ok {
1841 if name == "inherit-product" || name == "inherit-product-if-exists" {
1842 return ctx.handleVariable(n)
1843 }
1844 }
Cole Faustf035d402022-03-28 14:02:50 -07001845 }
1846 }
1847
Cole Faust20052982022-04-22 14:43:55 -07001848 return []starlarkNode{ctx.newBadNode(node, "Eval expression too complex; only assignments, comments, includes, and inherit-products are supported")}
Cole Faustf035d402022-03-28 14:02:50 -07001849}
1850
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001851func (ctx *parseContext) parseMakeString(node mkparser.Node, mk *mkparser.MakeString) starlarkExpr {
1852 if mk.Const() {
1853 return &stringLiteralExpr{mk.Dump()}
1854 }
1855 if mkRef, ok := mk.SingleVariable(); ok {
1856 return ctx.parseReference(node, mkRef)
1857 }
1858 // If we reached here, it's neither string literal nor a simple variable,
1859 // we need a full-blown interpolation node that will generate
1860 // "a%b%c" % (X, Y) for a$(X)b$(Y)c
Cole Faustfc438682021-12-14 12:46:32 -08001861 parts := make([]starlarkExpr, len(mk.Variables)+len(mk.Strings))
1862 for i := 0; i < len(parts); i++ {
1863 if i%2 == 0 {
1864 parts[i] = &stringLiteralExpr{literal: mk.Strings[i/2]}
1865 } else {
1866 parts[i] = ctx.parseReference(node, mk.Variables[i/2].Name)
1867 if x, ok := parts[i].(*badExpr); ok {
1868 return x
1869 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001870 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001871 }
Cole Faustfc438682021-12-14 12:46:32 -08001872 return NewInterpolateExpr(parts)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001873}
1874
Cole Faustf035d402022-03-28 14:02:50 -07001875func (ctx *parseContext) parseNodeMakeString(node mkparser.Node, mk *mkparser.MakeString) []starlarkNode {
1876 // Discard any constant values in the make string, as they would be top level
1877 // string literals and do nothing.
1878 result := make([]starlarkNode, 0, len(mk.Variables))
1879 for i := range mk.Variables {
1880 result = append(result, ctx.handleVariable(&mk.Variables[i])...)
1881 }
1882 return result
1883}
1884
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001885// Handles the statements whose treatment is the same in all contexts: comment,
1886// assignment, variable (which is a macro call in reality) and all constructs that
1887// do not handle in any context ('define directive and any unrecognized stuff).
Cole Faustdd569ae2022-01-31 15:48:29 -08001888func (ctx *parseContext) handleSimpleStatement(node mkparser.Node) []starlarkNode {
1889 var result []starlarkNode
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001890 switch x := node.(type) {
1891 case *mkparser.Comment:
Cole Faustdd569ae2022-01-31 15:48:29 -08001892 if n, handled := ctx.maybeHandleAnnotation(x); handled && n != nil {
1893 result = []starlarkNode{n}
1894 } else if !handled {
1895 result = []starlarkNode{&commentNode{strings.TrimSpace("#" + x.Comment)}}
Cole Faust7940c6a2022-01-31 15:54:05 -08001896 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001897 case *mkparser.Assignment:
Cole Faustdd569ae2022-01-31 15:48:29 -08001898 result = ctx.handleAssignment(x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001899 case *mkparser.Variable:
Cole Faustdd569ae2022-01-31 15:48:29 -08001900 result = ctx.handleVariable(x)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001901 case *mkparser.Directive:
1902 switch x.Name {
1903 case "define":
Cole Faustdd569ae2022-01-31 15:48:29 -08001904 if res := ctx.maybeHandleDefine(x); res != nil {
1905 result = []starlarkNode{res}
1906 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001907 case "include", "-include":
Cole Faust20052982022-04-22 14:43:55 -07001908 result = ctx.handleInclude(x)
Cole Faust591a1fe2021-11-08 15:37:57 -08001909 case "ifeq", "ifneq", "ifdef", "ifndef":
Cole Faustdd569ae2022-01-31 15:48:29 -08001910 result = []starlarkNode{ctx.handleIfBlock(x)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001911 default:
Cole Faustdd569ae2022-01-31 15:48:29 -08001912 result = []starlarkNode{ctx.newBadNode(x, "unexpected directive %s", x.Name)}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001913 }
1914 default:
Cole Faustdd569ae2022-01-31 15:48:29 -08001915 result = []starlarkNode{ctx.newBadNode(x, "unsupported line %s", strings.ReplaceAll(x.Dump(), "\n", "\n#"))}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001916 }
Cole Faust6c934f62022-01-06 15:51:12 -08001917
1918 // Clear the includeTops after each non-comment statement
1919 // so that include annotations placed on certain statements don't apply
1920 // globally for the rest of the makefile was well.
Cole Faustf92c9f22022-03-14 14:35:50 -07001921 if _, wasComment := node.(*mkparser.Comment); !wasComment {
1922 ctx.atTopOfMakefile = false
Cole Faust6c934f62022-01-06 15:51:12 -08001923 ctx.includeTops = []string{}
1924 }
Cole Faustdd569ae2022-01-31 15:48:29 -08001925
1926 if result == nil {
1927 result = []starlarkNode{}
1928 }
Cole Faustf035d402022-03-28 14:02:50 -07001929
Cole Faustdd569ae2022-01-31 15:48:29 -08001930 return result
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001931}
1932
Cole Faustf92c9f22022-03-14 14:35:50 -07001933// The types allowed in a type_hint
1934var typeHintMap = map[string]starlarkType{
1935 "string": starlarkTypeString,
1936 "list": starlarkTypeList,
1937}
1938
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001939// Processes annotation. An annotation is a comment that starts with #RBC# and provides
1940// a conversion hint -- say, where to look for the dynamically calculated inherit/include
Cole Faust7940c6a2022-01-31 15:54:05 -08001941// paths. Returns true if the comment was a successfully-handled annotation.
Cole Faustdd569ae2022-01-31 15:48:29 -08001942func (ctx *parseContext) maybeHandleAnnotation(cnode *mkparser.Comment) (starlarkNode, bool) {
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001943 maybeTrim := func(s, prefix string) (string, bool) {
1944 if strings.HasPrefix(s, prefix) {
1945 return strings.TrimSpace(strings.TrimPrefix(s, prefix)), true
1946 }
1947 return s, false
1948 }
1949 annotation, ok := maybeTrim(cnode.Comment, annotationCommentPrefix)
1950 if !ok {
Cole Faustdd569ae2022-01-31 15:48:29 -08001951 return nil, false
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001952 }
1953 if p, ok := maybeTrim(annotation, "include_top"); ok {
Cole Faustf7ed5342021-12-21 14:15:12 -08001954 // Don't allow duplicate include tops, because then we will generate
1955 // invalid starlark code. (duplicate keys in the _entry dictionary)
1956 for _, top := range ctx.includeTops {
1957 if top == p {
Cole Faustdd569ae2022-01-31 15:48:29 -08001958 return nil, true
Cole Faustf7ed5342021-12-21 14:15:12 -08001959 }
1960 }
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001961 ctx.includeTops = append(ctx.includeTops, p)
Cole Faustdd569ae2022-01-31 15:48:29 -08001962 return nil, true
Cole Faustf92c9f22022-03-14 14:35:50 -07001963 } else if p, ok := maybeTrim(annotation, "type_hint"); ok {
1964 // Type hints must come at the beginning the file, to avoid confusion
1965 // if a type hint was specified later and thus only takes effect for half
1966 // of the file.
1967 if !ctx.atTopOfMakefile {
1968 return ctx.newBadNode(cnode, "type_hint annotations must come before the first Makefile statement"), true
1969 }
1970
1971 parts := strings.Fields(p)
1972 if len(parts) <= 1 {
1973 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
1974 }
1975
1976 var varType starlarkType
1977 if varType, ok = typeHintMap[parts[0]]; !ok {
1978 varType = starlarkTypeUnknown
1979 }
1980 if varType == starlarkTypeUnknown {
1981 return ctx.newBadNode(cnode, "Invalid type_hint annotation. Only list/string types are accepted, found %s", parts[0]), true
1982 }
1983
1984 for _, name := range parts[1:] {
1985 // Don't allow duplicate type hints
1986 if _, ok := ctx.typeHints[name]; ok {
1987 return ctx.newBadNode(cnode, "Duplicate type hint for variable %s", name), true
1988 }
1989 ctx.typeHints[name] = varType
1990 }
1991 return nil, true
Sasha Smundak6d852dd2021-09-27 20:34:39 -07001992 }
Cole Faustdd569ae2022-01-31 15:48:29 -08001993 return ctx.newBadNode(cnode, "unsupported annotation %s", cnode.Comment), true
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001994}
1995
1996func (ctx *parseContext) loadedModulePath(path string) string {
1997 // During the transition to Roboleaf some of the product configuration files
1998 // will be converted and checked in while the others will be generated on the fly
1999 // and run. The runner (rbcrun application) accommodates this by allowing three
2000 // different ways to specify the loaded file location:
2001 // 1) load(":<file>",...) loads <file> from the same directory
2002 // 2) load("//path/relative/to/source/root:<file>", ...) loads <file> source tree
2003 // 3) load("/absolute/path/to/<file> absolute path
2004 // If the file being generated and the file it wants to load are in the same directory,
2005 // generate option 1.
2006 // Otherwise, if output directory is not specified, generate 2)
2007 // Finally, if output directory has been specified and the file being generated and
2008 // the file it wants to load from are in the different directories, generate 2) or 3):
2009 // * if the file being loaded exists in the source tree, generate 2)
2010 // * otherwise, generate 3)
2011 // Finally, figure out the loaded module path and name and create a node for it
2012 loadedModuleDir := filepath.Dir(path)
2013 base := filepath.Base(path)
2014 loadedModuleName := strings.TrimSuffix(base, filepath.Ext(base)) + ctx.outputSuffix
2015 if loadedModuleDir == filepath.Dir(ctx.script.mkFile) {
2016 return ":" + loadedModuleName
2017 }
2018 if ctx.outputDir == "" {
2019 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
2020 }
2021 if _, err := os.Stat(filepath.Join(loadedModuleDir, loadedModuleName)); err == nil {
2022 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
2023 }
2024 return filepath.Join(ctx.outputDir, loadedModuleDir, loadedModuleName)
2025}
2026
Sasha Smundak3deb9682021-07-26 18:42:25 -07002027func (ctx *parseContext) addSoongNamespace(ns string) {
2028 if _, ok := ctx.soongNamespaces[ns]; ok {
2029 return
2030 }
2031 ctx.soongNamespaces[ns] = make(map[string]bool)
2032}
2033
2034func (ctx *parseContext) hasSoongNamespace(name string) bool {
2035 _, ok := ctx.soongNamespaces[name]
2036 return ok
2037}
2038
2039func (ctx *parseContext) updateSoongNamespace(replace bool, namespaceName string, varNames []string) {
2040 ctx.addSoongNamespace(namespaceName)
2041 vars := ctx.soongNamespaces[namespaceName]
2042 if replace {
2043 vars = make(map[string]bool)
2044 ctx.soongNamespaces[namespaceName] = vars
2045 }
2046 for _, v := range varNames {
2047 vars[v] = true
2048 }
2049}
2050
2051func (ctx *parseContext) hasNamespaceVar(namespaceName string, varName string) bool {
2052 vars, ok := ctx.soongNamespaces[namespaceName]
2053 if ok {
2054 _, ok = vars[varName]
2055 }
2056 return ok
2057}
2058
Sasha Smundak422b6142021-11-11 18:31:59 -08002059func (ctx *parseContext) errorLocation(node mkparser.Node) ErrorLocation {
2060 return ErrorLocation{ctx.script.mkFile, ctx.script.nodeLocator(node.Pos())}
2061}
2062
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002063func (ss *StarlarkScript) String() string {
2064 return NewGenerateContext(ss).emit()
2065}
2066
2067func (ss *StarlarkScript) SubConfigFiles() []string {
Sasha Smundak6609ba72021-07-22 18:32:56 -07002068
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002069 var subs []string
2070 for _, src := range ss.inherited {
2071 subs = append(subs, src.originalPath)
2072 }
2073 return subs
2074}
2075
2076func (ss *StarlarkScript) HasErrors() bool {
2077 return ss.hasErrors
2078}
2079
2080// Convert reads and parses a makefile. If successful, parsed tree
2081// is returned and then can be passed to String() to get the generated
2082// Starlark file.
2083func Convert(req Request) (*StarlarkScript, error) {
2084 reader := req.Reader
2085 if reader == nil {
2086 mkContents, err := ioutil.ReadFile(req.MkFile)
2087 if err != nil {
2088 return nil, err
2089 }
2090 reader = bytes.NewBuffer(mkContents)
2091 }
2092 parser := mkparser.NewParser(req.MkFile, reader)
2093 nodes, errs := parser.Parse()
2094 if len(errs) > 0 {
2095 for _, e := range errs {
2096 fmt.Fprintln(os.Stderr, "ERROR:", e)
2097 }
2098 return nil, fmt.Errorf("bad makefile %s", req.MkFile)
2099 }
2100 starScript := &StarlarkScript{
Sasha Smundak422b6142021-11-11 18:31:59 -08002101 moduleName: moduleNameForFile(req.MkFile),
2102 mkFile: req.MkFile,
Sasha Smundak422b6142021-11-11 18:31:59 -08002103 traceCalls: req.TraceCalls,
2104 sourceFS: req.SourceFS,
2105 makefileFinder: req.MakefileFinder,
2106 nodeLocator: func(pos mkparser.Pos) int { return parser.Unpack(pos).Line },
Cole Faustdd569ae2022-01-31 15:48:29 -08002107 nodes: make([]starlarkNode, 0),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002108 }
2109 ctx := newParseContext(starScript, nodes)
2110 ctx.outputSuffix = req.OutputSuffix
2111 ctx.outputDir = req.OutputDir
2112 ctx.errorLogger = req.ErrorLogger
2113 if len(req.TracedVariables) > 0 {
2114 ctx.tracedVariables = make(map[string]bool)
2115 for _, v := range req.TracedVariables {
2116 ctx.tracedVariables[v] = true
2117 }
2118 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002119 for ctx.hasNodes() && ctx.fatalError == nil {
Cole Faustdd569ae2022-01-31 15:48:29 -08002120 starScript.nodes = append(starScript.nodes, ctx.handleSimpleStatement(ctx.getNode())...)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002121 }
2122 if ctx.fatalError != nil {
2123 return nil, ctx.fatalError
2124 }
2125 return starScript, nil
2126}
2127
Cole Faust864028a2021-12-01 13:43:17 -08002128func Launcher(mainModuleUri, inputVariablesUri, mainModuleName string) string {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002129 var buf bytes.Buffer
2130 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
Cole Faust864028a2021-12-01 13:43:17 -08002131 fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri)
Sasha Smundakd7d07ad2021-09-10 15:42:34 -07002132 fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri)
Cole Faust864028a2021-12-01 13:43:17 -08002133 fmt.Fprintf(&buf, "%s(%s(%q, init, input_variables_init))\n", cfnPrintVars, cfnMain, mainModuleName)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002134 return buf.String()
2135}
2136
Cole Faust6ed7cb42021-10-07 17:08:46 -07002137func BoardLauncher(mainModuleUri string, inputVariablesUri string) string {
2138 var buf bytes.Buffer
2139 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
2140 fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri)
2141 fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri)
Cole Fausta0604662022-02-28 11:53:58 -08002142 fmt.Fprintf(&buf, "%s(%s(init, input_variables_init))\n", cfnPrintVars, cfnBoardMain)
Cole Faust6ed7cb42021-10-07 17:08:46 -07002143 return buf.String()
2144}
2145
Sasha Smundakb051c4e2020-11-05 20:45:07 -08002146func MakePath2ModuleName(mkPath string) string {
2147 return strings.TrimSuffix(mkPath, filepath.Ext(mkPath))
2148}