blob: 2173e9bb3d1de5e4f94798fed66932d4de07eb17 [file] [log] [blame]
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001// Copyright 2021 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Convert makefile containing device configuration to Starlark file
16// The conversion can handle the following constructs in a makefile:
17// * comments
18// * simple variable assignments
19// * $(call init-product,<file>)
20// * $(call inherit-product-if-exists
21// * if directives
22// All other constructs are carried over to the output starlark file as comments.
23//
24package mk2rbc
25
26import (
27 "bytes"
28 "fmt"
29 "io"
Sasha Smundak6609ba72021-07-22 18:32:56 -070030 "io/fs"
Sasha Smundakb051c4e2020-11-05 20:45:07 -080031 "io/ioutil"
32 "os"
33 "path/filepath"
34 "regexp"
35 "strconv"
36 "strings"
37 "text/scanner"
38
39 mkparser "android/soong/androidmk/parser"
40)
41
42const (
43 baseUri = "//build/make/core:product_config.rbc"
44 // The name of the struct exported by the product_config.rbc
45 // that contains the functions and variables available to
46 // product configuration Starlark files.
47 baseName = "rblf"
48
49 // And here are the functions and variables:
50 cfnGetCfg = baseName + ".cfg"
51 cfnMain = baseName + ".product_configuration"
52 cfnPrintVars = baseName + ".printvars"
53 cfnWarning = baseName + ".warning"
54 cfnLocalAppend = baseName + ".local_append"
55 cfnLocalSetDefault = baseName + ".local_set_default"
56 cfnInherit = baseName + ".inherit"
57 cfnSetListDefault = baseName + ".setdefault"
58)
59
60const (
61 // Phony makefile functions, they are eventually rewritten
62 // according to knownFunctions map
63 fileExistsPhony = "$file_exists"
64 wildcardExistsPhony = "$wildcard_exists"
65)
66
67const (
68 callLoadAlways = "inherit-product"
69 callLoadIf = "inherit-product-if-exists"
70)
71
72var knownFunctions = map[string]struct {
73 // The name of the runtime function this function call in makefiles maps to.
74 // If it starts with !, then this makefile function call is rewritten to
75 // something else.
76 runtimeName string
77 returnType starlarkType
78}{
Sasha Smundak16e07732021-07-23 11:38:23 -070079 "abspath": {baseName + ".abspath", starlarkTypeString},
Sasha Smundakb051c4e2020-11-05 20:45:07 -080080 fileExistsPhony: {baseName + ".file_exists", starlarkTypeBool},
81 wildcardExistsPhony: {baseName + ".file_wildcard_exists", starlarkTypeBool},
82 "add-to-product-copy-files-if-exists": {baseName + ".copy_if_exists", starlarkTypeList},
83 "addprefix": {baseName + ".addprefix", starlarkTypeList},
84 "addsuffix": {baseName + ".addsuffix", starlarkTypeList},
Sasha Smundak16e07732021-07-23 11:38:23 -070085 "dir": {baseName + ".dir", starlarkTypeList},
Sasha Smundakb051c4e2020-11-05 20:45:07 -080086 "enforce-product-packages-exist": {baseName + ".enforce_product_packages_exist", starlarkTypeVoid},
87 "error": {baseName + ".mkerror", starlarkTypeVoid},
88 "findstring": {"!findstring", starlarkTypeInt},
89 "find-copy-subdir-files": {baseName + ".find_and_copy", starlarkTypeList},
Sasha Smundakf3e072a2021-07-14 12:50:28 -070090 "find-word-in-list": {"!find-word-in-list", starlarkTypeUnknown}, // internal macro
Sasha Smundakb051c4e2020-11-05 20:45:07 -080091 "filter": {baseName + ".filter", starlarkTypeList},
92 "filter-out": {baseName + ".filter_out", starlarkTypeList},
Sasha Smundak16e07732021-07-23 11:38:23 -070093 "firstword": {"!firstword", starlarkTypeString},
Sasha Smundakf3e072a2021-07-14 12:50:28 -070094 "get-vendor-board-platforms": {"!get-vendor-board-platforms", starlarkTypeList}, // internal macro, used by is-board-platform, etc.
Sasha Smundakb051c4e2020-11-05 20:45:07 -080095 "info": {baseName + ".mkinfo", starlarkTypeVoid},
Sasha Smundakf3e072a2021-07-14 12:50:28 -070096 "is-android-codename": {"!is-android-codename", starlarkTypeBool}, // unused by product config
97 "is-android-codename-in-list": {"!is-android-codename-in-list", starlarkTypeBool}, // unused by product config
Sasha Smundakb051c4e2020-11-05 20:45:07 -080098 "is-board-platform": {"!is-board-platform", starlarkTypeBool},
99 "is-board-platform-in-list": {"!is-board-platform-in-list", starlarkTypeBool},
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700100 "is-chipset-in-board-platform": {"!is-chipset-in-board-platform", starlarkTypeUnknown}, // unused by product config
101 "is-chipset-prefix-in-board-platform": {"!is-chipset-prefix-in-board-platform", starlarkTypeBool}, // unused by product config
102 "is-not-board-platform": {"!is-not-board-platform", starlarkTypeBool}, // defined but never used
103 "is-platform-sdk-version-at-least": {"!is-platform-sdk-version-at-least", starlarkTypeBool}, // unused by product config
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800104 "is-product-in-list": {"!is-product-in-list", starlarkTypeBool},
105 "is-vendor-board-platform": {"!is-vendor-board-platform", starlarkTypeBool},
106 callLoadAlways: {"!inherit-product", starlarkTypeVoid},
107 callLoadIf: {"!inherit-product-if-exists", starlarkTypeVoid},
Sasha Smundak16e07732021-07-23 11:38:23 -0700108 "lastword": {"!lastword", starlarkTypeString},
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700109 "match-prefix": {"!match-prefix", starlarkTypeUnknown}, // internal macro
110 "match-word": {"!match-word", starlarkTypeUnknown}, // internal macro
111 "match-word-in-list": {"!match-word-in-list", starlarkTypeUnknown}, // internal macro
Sasha Smundak16e07732021-07-23 11:38:23 -0700112 "notdir": {baseName + ".notdir", starlarkTypeString},
Sasha Smundak6609ba72021-07-22 18:32:56 -0700113 "my-dir": {"!my-dir", starlarkTypeString},
Sasha Smundak94b41c72021-07-12 18:30:42 -0700114 "patsubst": {baseName + ".mkpatsubst", starlarkTypeString},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800115 "produce_copy_files": {baseName + ".produce_copy_files", starlarkTypeList},
116 "require-artifacts-in-path": {baseName + ".require_artifacts_in_path", starlarkTypeVoid},
117 "require-artifacts-in-path-relaxed": {baseName + ".require_artifacts_in_path_relaxed", starlarkTypeVoid},
118 // TODO(asmundak): remove it once all calls are removed from configuration makefiles. see b/183161002
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700119 "shell": {baseName + ".shell", starlarkTypeString},
120 "strip": {baseName + ".mkstrip", starlarkTypeString},
121 "tb-modules": {"!tb-modules", starlarkTypeUnknown}, // defined in hardware/amlogic/tb_modules/tb_detect.mk, unused
122 "subst": {baseName + ".mksubst", starlarkTypeString},
123 "warning": {baseName + ".mkwarning", starlarkTypeVoid},
124 "word": {baseName + "!word", starlarkTypeString},
125 "wildcard": {baseName + ".expand_wildcard", starlarkTypeList},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800126}
127
128var builtinFuncRex = regexp.MustCompile(
129 "^(addprefix|addsuffix|abspath|and|basename|call|dir|error|eval" +
130 "|flavor|foreach|file|filter|filter-out|findstring|firstword|guile" +
131 "|if|info|join|lastword|notdir|or|origin|patsubst|realpath" +
132 "|shell|sort|strip|subst|suffix|value|warning|word|wordlist|words" +
133 "|wildcard)")
134
135// Conversion request parameters
136type Request struct {
137 MkFile string // file to convert
138 Reader io.Reader // if set, read input from this stream instead
139 RootDir string // root directory path used to resolve included files
140 OutputSuffix string // generated Starlark files suffix
141 OutputDir string // if set, root of the output hierarchy
142 ErrorLogger ErrorMonitorCB
143 TracedVariables []string // trace assignment to these variables
144 TraceCalls bool
145 WarnPartialSuccess bool
Sasha Smundak6609ba72021-07-22 18:32:56 -0700146 SourceFS fs.FS
147 MakefileFinder MakefileFinder
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800148}
149
150// An error sink allowing to gather error statistics.
151// NewError is called on every error encountered during processing.
152type ErrorMonitorCB interface {
153 NewError(s string, node mkparser.Node, args ...interface{})
154}
155
156// Derives module name for a given file. It is base name
157// (file name without suffix), with some characters replaced to make it a Starlark identifier
158func moduleNameForFile(mkFile string) string {
159 base := strings.TrimSuffix(filepath.Base(mkFile), filepath.Ext(mkFile))
160 // TODO(asmundak): what else can be in the product file names?
Sasha Smundak6609ba72021-07-22 18:32:56 -0700161 return strings.NewReplacer("-", "_", ".", "_").Replace(base)
162
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800163}
164
165func cloneMakeString(mkString *mkparser.MakeString) *mkparser.MakeString {
166 r := &mkparser.MakeString{StringPos: mkString.StringPos}
167 r.Strings = append(r.Strings, mkString.Strings...)
168 r.Variables = append(r.Variables, mkString.Variables...)
169 return r
170}
171
172func isMakeControlFunc(s string) bool {
173 return s == "error" || s == "warning" || s == "info"
174}
175
176// Starlark output generation context
177type generationContext struct {
178 buf strings.Builder
179 starScript *StarlarkScript
180 indentLevel int
181 inAssignment bool
182 tracedCount int
183}
184
185func NewGenerateContext(ss *StarlarkScript) *generationContext {
186 return &generationContext{starScript: ss}
187}
188
189// emit returns generated script
190func (gctx *generationContext) emit() string {
191 ss := gctx.starScript
192
193 // The emitted code has the following layout:
194 // <initial comments>
195 // preamble, i.e.,
196 // load statement for the runtime support
197 // load statement for each unique submodule pulled in by this one
198 // def init(g, handle):
199 // cfg = rblf.cfg(handle)
200 // <statements>
201 // <warning if conversion was not clean>
202
203 iNode := len(ss.nodes)
204 for i, node := range ss.nodes {
205 if _, ok := node.(*commentNode); !ok {
206 iNode = i
207 break
208 }
209 node.emit(gctx)
210 }
211
212 gctx.emitPreamble()
213
214 gctx.newLine()
215 // The arguments passed to the init function are the global dictionary
216 // ('g') and the product configuration dictionary ('cfg')
217 gctx.write("def init(g, handle):")
218 gctx.indentLevel++
219 if gctx.starScript.traceCalls {
220 gctx.newLine()
221 gctx.writef(`print(">%s")`, gctx.starScript.mkFile)
222 }
223 gctx.newLine()
224 gctx.writef("cfg = %s(handle)", cfnGetCfg)
225 for _, node := range ss.nodes[iNode:] {
226 node.emit(gctx)
227 }
228
229 if ss.hasErrors && ss.warnPartialSuccess {
230 gctx.newLine()
231 gctx.writef("%s(%q, %q)", cfnWarning, filepath.Base(ss.mkFile), "partially successful conversion")
232 }
233 if gctx.starScript.traceCalls {
234 gctx.newLine()
235 gctx.writef(`print("<%s")`, gctx.starScript.mkFile)
236 }
237 gctx.indentLevel--
238 gctx.write("\n")
239 return gctx.buf.String()
240}
241
242func (gctx *generationContext) emitPreamble() {
243 gctx.newLine()
244 gctx.writef("load(%q, %q)", baseUri, baseName)
245 // Emit exactly one load statement for each URI.
246 loadedSubConfigs := make(map[string]string)
247 for _, sc := range gctx.starScript.inherited {
248 uri := sc.path
249 if m, ok := loadedSubConfigs[uri]; ok {
250 // No need to emit load statement, but fix module name.
251 sc.moduleLocalName = m
252 continue
253 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700254 if sc.optional {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800255 uri += "|init"
256 }
257 gctx.newLine()
258 gctx.writef("load(%q, %s = \"init\")", uri, sc.entryName())
259 loadedSubConfigs[uri] = sc.moduleLocalName
260 }
261 gctx.write("\n")
262}
263
264func (gctx *generationContext) emitPass() {
265 gctx.newLine()
266 gctx.write("pass")
267}
268
269func (gctx *generationContext) write(ss ...string) {
270 for _, s := range ss {
271 gctx.buf.WriteString(s)
272 }
273}
274
275func (gctx *generationContext) writef(format string, args ...interface{}) {
276 gctx.write(fmt.Sprintf(format, args...))
277}
278
279func (gctx *generationContext) newLine() {
280 if gctx.buf.Len() == 0 {
281 return
282 }
283 gctx.write("\n")
284 gctx.writef("%*s", 2*gctx.indentLevel, "")
285}
286
287type knownVariable struct {
288 name string
289 class varClass
290 valueType starlarkType
291}
292
293type knownVariables map[string]knownVariable
294
295func (pcv knownVariables) NewVariable(name string, varClass varClass, valueType starlarkType) {
296 v, exists := pcv[name]
297 if !exists {
298 pcv[name] = knownVariable{name, varClass, valueType}
299 return
300 }
301 // Conflict resolution:
302 // * config class trumps everything
303 // * any type trumps unknown type
304 match := varClass == v.class
305 if !match {
306 if varClass == VarClassConfig {
307 v.class = VarClassConfig
308 match = true
309 } else if v.class == VarClassConfig {
310 match = true
311 }
312 }
313 if valueType != v.valueType {
314 if valueType != starlarkTypeUnknown {
315 if v.valueType == starlarkTypeUnknown {
316 v.valueType = valueType
317 } else {
318 match = false
319 }
320 }
321 }
322 if !match {
323 fmt.Fprintf(os.Stderr, "cannot redefine %s as %v/%v (already defined as %v/%v)\n",
324 name, varClass, valueType, v.class, v.valueType)
325 }
326}
327
328// All known product variables.
329var KnownVariables = make(knownVariables)
330
331func init() {
332 for _, kv := range []string{
333 // Kernel-related variables that we know are lists.
334 "BOARD_VENDOR_KERNEL_MODULES",
335 "BOARD_VENDOR_RAMDISK_KERNEL_MODULES",
336 "BOARD_VENDOR_RAMDISK_KERNEL_MODULES_LOAD",
337 "BOARD_RECOVERY_KERNEL_MODULES",
338 // Other variables we knwo are lists
339 "ART_APEX_JARS",
340 } {
341 KnownVariables.NewVariable(kv, VarClassSoong, starlarkTypeList)
342 }
343}
344
345type nodeReceiver interface {
346 newNode(node starlarkNode)
347}
348
349// Information about the generated Starlark script.
350type StarlarkScript struct {
351 mkFile string
352 moduleName string
353 mkPos scanner.Position
354 nodes []starlarkNode
Sasha Smundak6609ba72021-07-22 18:32:56 -0700355 inherited []*moduleInfo
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800356 hasErrors bool
357 topDir string
358 traceCalls bool // print enter/exit each init function
359 warnPartialSuccess bool
Sasha Smundak6609ba72021-07-22 18:32:56 -0700360 sourceFS fs.FS
361 makefileFinder MakefileFinder
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800362}
363
364func (ss *StarlarkScript) newNode(node starlarkNode) {
365 ss.nodes = append(ss.nodes, node)
366}
367
368// varAssignmentScope points to the last assignment for each variable
369// in the current block. It is used during the parsing to chain
370// the assignments to a variable together.
371type varAssignmentScope struct {
372 outer *varAssignmentScope
373 vars map[string]*assignmentNode
374}
375
376// parseContext holds the script we are generating and all the ephemeral data
377// needed during the parsing.
378type parseContext struct {
379 script *StarlarkScript
380 nodes []mkparser.Node // Makefile as parsed by mkparser
381 currentNodeIndex int // Node in it we are processing
382 ifNestLevel int
383 moduleNameCount map[string]int // count of imported modules with given basename
384 fatalError error
385 builtinMakeVars map[string]starlarkExpr
386 outputSuffix string
387 errorLogger ErrorMonitorCB
388 tracedVariables map[string]bool // variables to be traced in the generated script
389 variables map[string]variable
390 varAssignments *varAssignmentScope
391 receiver nodeReceiver // receptacle for the generated starlarkNode's
392 receiverStack []nodeReceiver
393 outputDir string
Sasha Smundak6609ba72021-07-22 18:32:56 -0700394 dependentModules map[string]*moduleInfo
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800395}
396
397func newParseContext(ss *StarlarkScript, nodes []mkparser.Node) *parseContext {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700398 topdir, _ := filepath.Split(filepath.Join(ss.topDir, "foo"))
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800399 predefined := []struct{ name, value string }{
400 {"SRC_TARGET_DIR", filepath.Join("build", "make", "target")},
401 {"LOCAL_PATH", filepath.Dir(ss.mkFile)},
Sasha Smundak6609ba72021-07-22 18:32:56 -0700402 {"TOPDIR", topdir},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800403 // TODO(asmundak): maybe read it from build/make/core/envsetup.mk?
404 {"TARGET_COPY_OUT_SYSTEM", "system"},
405 {"TARGET_COPY_OUT_SYSTEM_OTHER", "system_other"},
406 {"TARGET_COPY_OUT_DATA", "data"},
407 {"TARGET_COPY_OUT_ASAN", filepath.Join("data", "asan")},
408 {"TARGET_COPY_OUT_OEM", "oem"},
409 {"TARGET_COPY_OUT_RAMDISK", "ramdisk"},
410 {"TARGET_COPY_OUT_DEBUG_RAMDISK", "debug_ramdisk"},
411 {"TARGET_COPY_OUT_VENDOR_DEBUG_RAMDISK", "vendor_debug_ramdisk"},
412 {"TARGET_COPY_OUT_TEST_HARNESS_RAMDISK", "test_harness_ramdisk"},
413 {"TARGET_COPY_OUT_ROOT", "root"},
414 {"TARGET_COPY_OUT_RECOVERY", "recovery"},
415 {"TARGET_COPY_OUT_VENDOR", "||VENDOR-PATH-PH||"},
416 {"TARGET_COPY_OUT_VENDOR_RAMDISK", "vendor_ramdisk"},
417 {"TARGET_COPY_OUT_PRODUCT", "||PRODUCT-PATH-PH||"},
418 {"TARGET_COPY_OUT_PRODUCT_SERVICES", "||PRODUCT-PATH-PH||"},
419 {"TARGET_COPY_OUT_SYSTEM_EXT", "||SYSTEM_EXT-PATH-PH||"},
420 {"TARGET_COPY_OUT_ODM", "||ODM-PATH-PH||"},
421 {"TARGET_COPY_OUT_VENDOR_DLKM", "||VENDOR_DLKM-PATH-PH||"},
422 {"TARGET_COPY_OUT_ODM_DLKM", "||ODM_DLKM-PATH-PH||"},
423 // TODO(asmundak): to process internal config files, we need the following variables:
424 // BOARD_CONFIG_VENDOR_PATH
425 // TARGET_VENDOR
426 // target_base_product
427 //
428
429 // the following utility variables are set in build/make/common/core.mk:
430 {"empty", ""},
431 {"space", " "},
432 {"comma", ","},
433 {"newline", "\n"},
434 {"pound", "#"},
435 {"backslash", "\\"},
436 }
437 ctx := &parseContext{
438 script: ss,
439 nodes: nodes,
440 currentNodeIndex: 0,
441 ifNestLevel: 0,
442 moduleNameCount: make(map[string]int),
443 builtinMakeVars: map[string]starlarkExpr{},
444 variables: make(map[string]variable),
Sasha Smundak6609ba72021-07-22 18:32:56 -0700445 dependentModules: make(map[string]*moduleInfo),
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800446 }
447 ctx.pushVarAssignments()
448 for _, item := range predefined {
449 ctx.variables[item.name] = &predefinedVariable{
450 baseVariable: baseVariable{nam: item.name, typ: starlarkTypeString},
451 value: &stringLiteralExpr{item.value},
452 }
453 }
454
455 return ctx
456}
457
458func (ctx *parseContext) lastAssignment(name string) *assignmentNode {
459 for va := ctx.varAssignments; va != nil; va = va.outer {
460 if v, ok := va.vars[name]; ok {
461 return v
462 }
463 }
464 return nil
465}
466
467func (ctx *parseContext) setLastAssignment(name string, asgn *assignmentNode) {
468 ctx.varAssignments.vars[name] = asgn
469}
470
471func (ctx *parseContext) pushVarAssignments() {
472 va := &varAssignmentScope{
473 outer: ctx.varAssignments,
474 vars: make(map[string]*assignmentNode),
475 }
476 ctx.varAssignments = va
477}
478
479func (ctx *parseContext) popVarAssignments() {
480 ctx.varAssignments = ctx.varAssignments.outer
481}
482
483func (ctx *parseContext) pushReceiver(rcv nodeReceiver) {
484 ctx.receiverStack = append(ctx.receiverStack, ctx.receiver)
485 ctx.receiver = rcv
486}
487
488func (ctx *parseContext) popReceiver() {
489 last := len(ctx.receiverStack) - 1
490 if last < 0 {
491 panic(fmt.Errorf("popReceiver: receiver stack empty"))
492 }
493 ctx.receiver = ctx.receiverStack[last]
494 ctx.receiverStack = ctx.receiverStack[0:last]
495}
496
497func (ctx *parseContext) hasNodes() bool {
498 return ctx.currentNodeIndex < len(ctx.nodes)
499}
500
501func (ctx *parseContext) getNode() mkparser.Node {
502 if !ctx.hasNodes() {
503 return nil
504 }
505 node := ctx.nodes[ctx.currentNodeIndex]
506 ctx.currentNodeIndex++
507 return node
508}
509
510func (ctx *parseContext) backNode() {
511 if ctx.currentNodeIndex <= 0 {
512 panic("Cannot back off")
513 }
514 ctx.currentNodeIndex--
515}
516
517func (ctx *parseContext) handleAssignment(a *mkparser.Assignment) {
518 // Handle only simple variables
519 if !a.Name.Const() {
520 ctx.errorf(a, "Only simple variables are handled")
521 return
522 }
523 name := a.Name.Strings[0]
524 lhs := ctx.addVariable(name)
525 if lhs == nil {
526 ctx.errorf(a, "unknown variable %s", name)
527 return
528 }
529 _, isTraced := ctx.tracedVariables[name]
530 asgn := &assignmentNode{lhs: lhs, mkValue: a.Value, isTraced: isTraced}
531 if lhs.valueType() == starlarkTypeUnknown {
532 // Try to divine variable type from the RHS
533 asgn.value = ctx.parseMakeString(a, a.Value)
534 if xBad, ok := asgn.value.(*badExpr); ok {
535 ctx.wrapBadExpr(xBad)
536 return
537 }
538 inferred_type := asgn.value.typ()
539 if inferred_type != starlarkTypeUnknown {
Sasha Smundak9d011ab2021-07-09 16:00:57 -0700540 lhs.setValueType(inferred_type)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800541 }
542 }
543 if lhs.valueType() == starlarkTypeList {
544 xConcat := ctx.buildConcatExpr(a)
545 if xConcat == nil {
546 return
547 }
548 switch len(xConcat.items) {
549 case 0:
550 asgn.value = &listExpr{}
551 case 1:
552 asgn.value = xConcat.items[0]
553 default:
554 asgn.value = xConcat
555 }
556 } else {
557 asgn.value = ctx.parseMakeString(a, a.Value)
558 if xBad, ok := asgn.value.(*badExpr); ok {
559 ctx.wrapBadExpr(xBad)
560 return
561 }
562 }
563
564 // TODO(asmundak): move evaluation to a separate pass
565 asgn.value, _ = asgn.value.eval(ctx.builtinMakeVars)
566
567 asgn.previous = ctx.lastAssignment(name)
568 ctx.setLastAssignment(name, asgn)
569 switch a.Type {
570 case "=", ":=":
571 asgn.flavor = asgnSet
572 case "+=":
573 if asgn.previous == nil && !asgn.lhs.isPreset() {
574 asgn.flavor = asgnMaybeAppend
575 } else {
576 asgn.flavor = asgnAppend
577 }
578 case "?=":
579 asgn.flavor = asgnMaybeSet
580 default:
581 panic(fmt.Errorf("unexpected assignment type %s", a.Type))
582 }
583
584 ctx.receiver.newNode(asgn)
585}
586
587func (ctx *parseContext) buildConcatExpr(a *mkparser.Assignment) *concatExpr {
588 xConcat := &concatExpr{}
589 var xItemList *listExpr
590 addToItemList := func(x ...starlarkExpr) {
591 if xItemList == nil {
592 xItemList = &listExpr{[]starlarkExpr{}}
593 }
594 xItemList.items = append(xItemList.items, x...)
595 }
596 finishItemList := func() {
597 if xItemList != nil {
598 xConcat.items = append(xConcat.items, xItemList)
599 xItemList = nil
600 }
601 }
602
603 items := a.Value.Words()
604 for _, item := range items {
605 // A function call in RHS is supposed to return a list, all other item
606 // expressions return individual elements.
607 switch x := ctx.parseMakeString(a, item).(type) {
608 case *badExpr:
609 ctx.wrapBadExpr(x)
610 return nil
611 case *stringLiteralExpr:
612 addToItemList(maybeConvertToStringList(x).(*listExpr).items...)
613 default:
614 switch x.typ() {
615 case starlarkTypeList:
616 finishItemList()
617 xConcat.items = append(xConcat.items, x)
618 case starlarkTypeString:
619 finishItemList()
620 xConcat.items = append(xConcat.items, &callExpr{
621 object: x,
622 name: "split",
623 args: nil,
624 returnType: starlarkTypeList,
625 })
626 default:
627 addToItemList(x)
628 }
629 }
630 }
631 if xItemList != nil {
632 xConcat.items = append(xConcat.items, xItemList)
633 }
634 return xConcat
635}
636
Sasha Smundak6609ba72021-07-22 18:32:56 -0700637func (ctx *parseContext) newDependentModule(path string, optional bool) *moduleInfo {
638 modulePath := ctx.loadedModulePath(path)
639 if mi, ok := ctx.dependentModules[modulePath]; ok {
640 mi.optional = mi.optional || optional
641 return mi
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800642 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800643 moduleName := moduleNameForFile(path)
644 moduleLocalName := "_" + moduleName
645 n, found := ctx.moduleNameCount[moduleName]
646 if found {
647 moduleLocalName += fmt.Sprintf("%d", n)
648 }
649 ctx.moduleNameCount[moduleName] = n + 1
Sasha Smundak6609ba72021-07-22 18:32:56 -0700650 mi := &moduleInfo{
651 path: modulePath,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800652 originalPath: path,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800653 moduleLocalName: moduleLocalName,
Sasha Smundak6609ba72021-07-22 18:32:56 -0700654 optional: optional,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800655 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700656 ctx.dependentModules[modulePath] = mi
657 ctx.script.inherited = append(ctx.script.inherited, mi)
658 return mi
659}
660
661func (ctx *parseContext) handleSubConfig(
662 v mkparser.Node, pathExpr starlarkExpr, loadAlways bool, processModule func(inheritedModule)) {
663 pathExpr, _ = pathExpr.eval(ctx.builtinMakeVars)
664
665 // In a simple case, the name of a module to inherit/include is known statically.
666 if path, ok := maybeString(pathExpr); ok {
667 if strings.Contains(path, "*") {
668 if paths, err := fs.Glob(ctx.script.sourceFS, path); err == nil {
669 for _, p := range paths {
670 processModule(inheritedStaticModule{ctx.newDependentModule(p, !loadAlways), loadAlways})
671 }
672 } else {
673 ctx.errorf(v, "cannot glob wildcard argument")
674 }
675 } else {
676 processModule(inheritedStaticModule{ctx.newDependentModule(path, !loadAlways), loadAlways})
677 }
678 return
679 }
680
681 // If module path references variables (e.g., $(v1)/foo/$(v2)/device-config.mk), find all the paths in the
682 // source tree that may be a match and the corresponding variable values. For instance, if the source tree
683 // contains vendor1/foo/abc/dev.mk and vendor2/foo/def/dev.mk, the first one will be inherited when
684 // (v1, v2) == ('vendor1', 'abc'), and the second one when (v1, v2) == ('vendor2', 'def').
685 // We then emit the code that loads all of them, e.g.:
686 // load("//vendor1/foo/abc:dev.rbc", _dev1_init="init")
687 // load("//vendor2/foo/def/dev.rbc", _dev2_init="init")
688 // And then inherit it as follows:
689 // _e = {
690 // "vendor1/foo/abc/dev.mk": ("vendor1/foo/abc/dev", _dev1_init),
691 // "vendor2/foo/def/dev.mk": ("vendor2/foo/def/dev", _dev_init2) }.get("%s/foo/%s/dev.mk" % (v1, v2))
692 // if _e:
693 // rblf.inherit(handle, _e[0], _e[1])
694 //
695 var matchingPaths []string
696 varPath, ok := pathExpr.(*interpolateExpr)
697 if !ok {
698 ctx.errorf(v, "inherit-product/include argument is too complex")
699 return
700 }
701
702 pathPattern := []string{varPath.chunks[0]}
703 for _, chunk := range varPath.chunks[1:] {
704 if chunk != "" {
705 pathPattern = append(pathPattern, chunk)
706 }
707 }
708 if pathPattern[0] != "" {
709 matchingPaths = ctx.findMatchingPaths(pathPattern)
710 } else {
711 // Heuristics -- if pattern starts from top, restrict it to the directories where
712 // we know inherit-product uses dynamically calculated path.
713 for _, t := range []string{"vendor/qcom", "vendor/google_devices"} {
714 pathPattern[0] = t
715 matchingPaths = append(matchingPaths, ctx.findMatchingPaths(pathPattern)...)
716 }
717 }
718 // Safeguard against $(call inherit-product,$(PRODUCT_PATH))
719 const maxMatchingFiles = 100
720 if len(matchingPaths) > maxMatchingFiles {
721 ctx.errorf(v, "there are >%d files matching the pattern, please rewrite it", maxMatchingFiles)
722 return
723 }
724 res := inheritedDynamicModule{*varPath, []*moduleInfo{}, loadAlways}
725 for _, p := range matchingPaths {
726 // A product configuration files discovered dynamically may attempt to inherit
727 // from another one which does not exist in this source tree. Prevent load errors
728 // by always loading the dynamic files as optional.
729 res.candidateModules = append(res.candidateModules, ctx.newDependentModule(p, true))
730 }
731 processModule(res)
732}
733
734func (ctx *parseContext) findMatchingPaths(pattern []string) []string {
735 files := ctx.script.makefileFinder.Find(ctx.script.topDir)
736 if len(pattern) == 0 {
737 return files
738 }
739
740 // Create regular expression from the pattern
741 s_regexp := "^" + regexp.QuoteMeta(pattern[0])
742 for _, s := range pattern[1:] {
743 s_regexp += ".*" + regexp.QuoteMeta(s)
744 }
745 s_regexp += "$"
746 rex := regexp.MustCompile(s_regexp)
747
748 // Now match
749 var res []string
750 for _, p := range files {
751 if rex.MatchString(p) {
752 res = append(res, p)
753 }
754 }
755 return res
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800756}
757
758func (ctx *parseContext) handleInheritModule(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700759 ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800760 ctx.receiver.newNode(&inheritNode{im})
Sasha Smundak6609ba72021-07-22 18:32:56 -0700761 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800762}
763
764func (ctx *parseContext) handleInclude(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700765 ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) {
766 ctx.receiver.newNode(&includeNode{im})
767 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800768}
769
770func (ctx *parseContext) handleVariable(v *mkparser.Variable) {
771 // Handle:
772 // $(call inherit-product,...)
773 // $(call inherit-product-if-exists,...)
774 // $(info xxx)
775 // $(warning xxx)
776 // $(error xxx)
777 expr := ctx.parseReference(v, v.Name)
778 switch x := expr.(type) {
779 case *callExpr:
780 if x.name == callLoadAlways || x.name == callLoadIf {
781 ctx.handleInheritModule(v, x.args[0], x.name == callLoadAlways)
782 } else if isMakeControlFunc(x.name) {
783 // File name is the first argument
784 args := []starlarkExpr{
785 &stringLiteralExpr{ctx.script.mkFile},
786 x.args[0],
787 }
788 ctx.receiver.newNode(&exprNode{
789 &callExpr{name: x.name, args: args, returnType: starlarkTypeUnknown},
790 })
791 } else {
792 ctx.receiver.newNode(&exprNode{expr})
793 }
794 case *badExpr:
795 ctx.wrapBadExpr(x)
796 return
797 default:
798 ctx.errorf(v, "cannot handle %s", v.Dump())
799 return
800 }
801}
802
803func (ctx *parseContext) handleDefine(directive *mkparser.Directive) {
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700804 macro_name := strings.Fields(directive.Args.Strings[0])[0]
805 // Ignore the macros that we handle
806 if _, ok := knownFunctions[macro_name]; !ok {
807 ctx.errorf(directive, "define is not supported: %s", macro_name)
808 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800809}
810
811func (ctx *parseContext) handleIfBlock(ifDirective *mkparser.Directive) {
812 ssSwitch := &switchNode{}
813 ctx.pushReceiver(ssSwitch)
814 for ctx.processBranch(ifDirective); ctx.hasNodes() && ctx.fatalError == nil; {
815 node := ctx.getNode()
816 switch x := node.(type) {
817 case *mkparser.Directive:
818 switch x.Name {
819 case "else", "elifdef", "elifndef", "elifeq", "elifneq":
820 ctx.processBranch(x)
821 case "endif":
822 ctx.popReceiver()
823 ctx.receiver.newNode(ssSwitch)
824 return
825 default:
826 ctx.errorf(node, "unexpected directive %s", x.Name)
827 }
828 default:
829 ctx.errorf(ifDirective, "unexpected statement")
830 }
831 }
832 if ctx.fatalError == nil {
833 ctx.fatalError = fmt.Errorf("no matching endif for %s", ifDirective.Dump())
834 }
835 ctx.popReceiver()
836}
837
838// processBranch processes a single branch (if/elseif/else) until the next directive
839// on the same level.
840func (ctx *parseContext) processBranch(check *mkparser.Directive) {
841 block := switchCase{gate: ctx.parseCondition(check)}
842 defer func() {
843 ctx.popVarAssignments()
844 ctx.ifNestLevel--
845
846 }()
847 ctx.pushVarAssignments()
848 ctx.ifNestLevel++
849
850 ctx.pushReceiver(&block)
851 for ctx.hasNodes() {
852 node := ctx.getNode()
853 if ctx.handleSimpleStatement(node) {
854 continue
855 }
856 switch d := node.(type) {
857 case *mkparser.Directive:
858 switch d.Name {
859 case "else", "elifdef", "elifndef", "elifeq", "elifneq", "endif":
860 ctx.popReceiver()
861 ctx.receiver.newNode(&block)
862 ctx.backNode()
863 return
864 case "ifdef", "ifndef", "ifeq", "ifneq":
865 ctx.handleIfBlock(d)
866 default:
867 ctx.errorf(d, "unexpected directive %s", d.Name)
868 }
869 default:
870 ctx.errorf(node, "unexpected statement")
871 }
872 }
873 ctx.fatalError = fmt.Errorf("no matching endif for %s", check.Dump())
874 ctx.popReceiver()
875}
876
877func (ctx *parseContext) newIfDefinedNode(check *mkparser.Directive) (starlarkExpr, bool) {
878 if !check.Args.Const() {
879 return ctx.newBadExpr(check, "ifdef variable ref too complex: %s", check.Args.Dump()), false
880 }
881 v := ctx.addVariable(check.Args.Strings[0])
882 return &variableDefinedExpr{v}, true
883}
884
885func (ctx *parseContext) parseCondition(check *mkparser.Directive) starlarkNode {
886 switch check.Name {
887 case "ifdef", "ifndef", "elifdef", "elifndef":
888 v, ok := ctx.newIfDefinedNode(check)
889 if ok && strings.HasSuffix(check.Name, "ndef") {
890 v = &notExpr{v}
891 }
892 return &ifNode{
893 isElif: strings.HasPrefix(check.Name, "elif"),
894 expr: v,
895 }
896 case "ifeq", "ifneq", "elifeq", "elifneq":
897 return &ifNode{
898 isElif: strings.HasPrefix(check.Name, "elif"),
899 expr: ctx.parseCompare(check),
900 }
901 case "else":
902 return &elseNode{}
903 default:
904 panic(fmt.Errorf("%s: unknown directive: %s", ctx.script.mkFile, check.Dump()))
905 }
906}
907
908func (ctx *parseContext) newBadExpr(node mkparser.Node, text string, args ...interface{}) starlarkExpr {
909 message := fmt.Sprintf(text, args...)
910 if ctx.errorLogger != nil {
911 ctx.errorLogger.NewError(text, node, args)
912 }
913 ctx.script.hasErrors = true
914 return &badExpr{node, message}
915}
916
917func (ctx *parseContext) parseCompare(cond *mkparser.Directive) starlarkExpr {
918 // Strip outer parentheses
919 mkArg := cloneMakeString(cond.Args)
920 mkArg.Strings[0] = strings.TrimLeft(mkArg.Strings[0], "( ")
921 n := len(mkArg.Strings)
922 mkArg.Strings[n-1] = strings.TrimRight(mkArg.Strings[n-1], ") ")
923 args := mkArg.Split(",")
924 // TODO(asmundak): handle the case where the arguments are in quotes and space-separated
925 if len(args) != 2 {
926 return ctx.newBadExpr(cond, "ifeq/ifneq len(args) != 2 %s", cond.Dump())
927 }
928 args[0].TrimRightSpaces()
929 args[1].TrimLeftSpaces()
930
931 isEq := !strings.HasSuffix(cond.Name, "neq")
932 switch xLeft := ctx.parseMakeString(cond, args[0]).(type) {
933 case *stringLiteralExpr, *variableRefExpr:
934 switch xRight := ctx.parseMakeString(cond, args[1]).(type) {
935 case *stringLiteralExpr, *variableRefExpr:
936 return &eqExpr{left: xLeft, right: xRight, isEq: isEq}
937 case *badExpr:
938 return xRight
939 default:
940 expr, ok := ctx.parseCheckFunctionCallResult(cond, xLeft, args[1])
941 if ok {
942 return expr
943 }
944 return ctx.newBadExpr(cond, "right operand is too complex: %s", args[1].Dump())
945 }
946 case *badExpr:
947 return xLeft
948 default:
949 switch xRight := ctx.parseMakeString(cond, args[1]).(type) {
950 case *stringLiteralExpr, *variableRefExpr:
951 expr, ok := ctx.parseCheckFunctionCallResult(cond, xRight, args[0])
952 if ok {
953 return expr
954 }
955 return ctx.newBadExpr(cond, "left operand is too complex: %s", args[0].Dump())
956 case *badExpr:
957 return xRight
958 default:
959 return ctx.newBadExpr(cond, "operands are too complex: (%s,%s)", args[0].Dump(), args[1].Dump())
960 }
961 }
962}
963
964func (ctx *parseContext) parseCheckFunctionCallResult(directive *mkparser.Directive, xValue starlarkExpr,
965 varArg *mkparser.MakeString) (starlarkExpr, bool) {
966 mkSingleVar, ok := varArg.SingleVariable()
967 if !ok {
968 return nil, false
969 }
970 expr := ctx.parseReference(directive, mkSingleVar)
971 negate := strings.HasSuffix(directive.Name, "neq")
972 checkIsSomethingFunction := func(xCall *callExpr) starlarkExpr {
973 s, ok := maybeString(xValue)
974 if !ok || s != "true" {
975 return ctx.newBadExpr(directive,
976 fmt.Sprintf("the result of %s can be compared only to 'true'", xCall.name))
977 }
978 if len(xCall.args) < 1 {
979 return ctx.newBadExpr(directive, "%s requires an argument", xCall.name)
980 }
981 return nil
982 }
983 switch x := expr.(type) {
984 case *callExpr:
985 switch x.name {
986 case "filter":
987 return ctx.parseCompareFilterFuncResult(directive, x, xValue, !negate), true
988 case "filter-out":
989 return ctx.parseCompareFilterFuncResult(directive, x, xValue, negate), true
990 case "wildcard":
991 return ctx.parseCompareWildcardFuncResult(directive, x, xValue, negate), true
992 case "findstring":
993 return ctx.parseCheckFindstringFuncResult(directive, x, xValue, negate), true
994 case "strip":
995 return ctx.parseCompareStripFuncResult(directive, x, xValue, negate), true
996 case "is-board-platform":
997 if xBad := checkIsSomethingFunction(x); xBad != nil {
998 return xBad, true
999 }
1000 return &eqExpr{
1001 left: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
1002 right: x.args[0],
1003 isEq: !negate,
1004 }, true
1005 case "is-board-platform-in-list":
1006 if xBad := checkIsSomethingFunction(x); xBad != nil {
1007 return xBad, true
1008 }
1009 return &inExpr{
1010 expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
1011 list: maybeConvertToStringList(x.args[0]),
1012 isNot: negate,
1013 }, true
1014 case "is-product-in-list":
1015 if xBad := checkIsSomethingFunction(x); xBad != nil {
1016 return xBad, true
1017 }
1018 return &inExpr{
1019 expr: &variableRefExpr{ctx.addVariable("TARGET_PRODUCT"), true},
1020 list: maybeConvertToStringList(x.args[0]),
1021 isNot: negate,
1022 }, true
1023 case "is-vendor-board-platform":
1024 if xBad := checkIsSomethingFunction(x); xBad != nil {
1025 return xBad, true
1026 }
1027 s, ok := maybeString(x.args[0])
1028 if !ok {
1029 return ctx.newBadExpr(directive, "cannot handle non-constant argument to is-vendor-board-platform"), true
1030 }
1031 return &inExpr{
1032 expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
1033 list: &variableRefExpr{ctx.addVariable(s + "_BOARD_PLATFORMS"), true},
1034 isNot: negate,
1035 }, true
1036 default:
1037 return ctx.newBadExpr(directive, "Unknown function in ifeq: %s", x.name), true
1038 }
1039 case *badExpr:
1040 return x, true
1041 default:
1042 return nil, false
1043 }
1044}
1045
1046func (ctx *parseContext) parseCompareFilterFuncResult(cond *mkparser.Directive,
1047 filterFuncCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
1048 // We handle:
Sasha Smundak0554d762021-07-08 18:26:12 -07001049 // * ifeq/ifneq (,$(filter v1 v2 ..., EXPR) becomes if EXPR not in/in ["v1", "v2", ...]
1050 // * ifeq/ifneq (,$(filter EXPR, v1 v2 ...) becomes if EXPR not in/in ["v1", "v2", ...]
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001051 // * ifeq/ifneq ($(VAR),$(filter $(VAR), v1 v2 ...) becomes if VAR in/not in ["v1", "v2"]
1052 // TODO(Asmundak): check the last case works for filter-out, too.
1053 xPattern := filterFuncCall.args[0]
1054 xText := filterFuncCall.args[1]
1055 var xInList *stringLiteralExpr
Sasha Smundak0554d762021-07-08 18:26:12 -07001056 var expr starlarkExpr
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001057 var ok bool
1058 switch x := xValue.(type) {
1059 case *stringLiteralExpr:
1060 if x.literal != "" {
1061 return ctx.newBadExpr(cond, "filter comparison to non-empty value: %s", xValue)
1062 }
1063 // Either pattern or text should be const, and the
1064 // non-const one should be varRefExpr
1065 if xInList, ok = xPattern.(*stringLiteralExpr); ok {
Sasha Smundak0554d762021-07-08 18:26:12 -07001066 expr = xText
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001067 } else if xInList, ok = xText.(*stringLiteralExpr); ok {
Sasha Smundak0554d762021-07-08 18:26:12 -07001068 expr = xPattern
1069 } else {
1070 return &callExpr{
1071 object: nil,
1072 name: filterFuncCall.name,
1073 args: filterFuncCall.args,
1074 returnType: starlarkTypeBool,
1075 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001076 }
1077 case *variableRefExpr:
1078 if v, ok := xPattern.(*variableRefExpr); ok {
1079 if xInList, ok = xText.(*stringLiteralExpr); ok && v.ref.name() == x.ref.name() {
1080 // ifeq/ifneq ($(VAR),$(filter $(VAR), v1 v2 ...), flip negate,
1081 // it's the opposite to what is done when comparing to empty.
Sasha Smundak0554d762021-07-08 18:26:12 -07001082 expr = xPattern
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001083 negate = !negate
1084 }
1085 }
1086 }
Sasha Smundak0554d762021-07-08 18:26:12 -07001087 if expr != nil && xInList != nil {
1088 slExpr := newStringListExpr(strings.Fields(xInList.literal))
1089 // Generate simpler code for the common cases:
1090 if expr.typ() == starlarkTypeList {
1091 if len(slExpr.items) == 1 {
1092 // Checking that a string belongs to list
1093 return &inExpr{isNot: negate, list: expr, expr: slExpr.items[0]}
1094 } else {
1095 // TODO(asmundak):
1096 panic("TBD")
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001097 }
Sasha Smundak0554d762021-07-08 18:26:12 -07001098 } else if len(slExpr.items) == 1 {
1099 return &eqExpr{left: expr, right: slExpr.items[0], isEq: !negate}
1100 } else {
1101 return &inExpr{isNot: negate, list: newStringListExpr(strings.Fields(xInList.literal)), expr: expr}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001102 }
1103 }
1104 return ctx.newBadExpr(cond, "filter arguments are too complex: %s", cond.Dump())
1105}
1106
1107func (ctx *parseContext) parseCompareWildcardFuncResult(directive *mkparser.Directive,
1108 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001109 if !isEmptyString(xValue) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001110 return ctx.newBadExpr(directive, "wildcard result can be compared only to empty: %s", xValue)
1111 }
1112 callFunc := wildcardExistsPhony
1113 if s, ok := xCall.args[0].(*stringLiteralExpr); ok && !strings.ContainsAny(s.literal, "*?{[") {
1114 callFunc = fileExistsPhony
1115 }
1116 var cc starlarkExpr = &callExpr{name: callFunc, args: xCall.args, returnType: starlarkTypeBool}
1117 if !negate {
1118 cc = &notExpr{cc}
1119 }
1120 return cc
1121}
1122
1123func (ctx *parseContext) parseCheckFindstringFuncResult(directive *mkparser.Directive,
1124 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001125 if isEmptyString(xValue) {
1126 return &eqExpr{
1127 left: &callExpr{
1128 object: xCall.args[1],
1129 name: "find",
1130 args: []starlarkExpr{xCall.args[0]},
1131 returnType: starlarkTypeInt,
1132 },
1133 right: &intLiteralExpr{-1},
1134 isEq: !negate,
1135 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001136 }
Sasha Smundak0554d762021-07-08 18:26:12 -07001137 return ctx.newBadExpr(directive, "findstring result can be compared only to empty: %s", xValue)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001138}
1139
1140func (ctx *parseContext) parseCompareStripFuncResult(directive *mkparser.Directive,
1141 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
1142 if _, ok := xValue.(*stringLiteralExpr); !ok {
1143 return ctx.newBadExpr(directive, "strip result can be compared only to string: %s", xValue)
1144 }
1145 return &eqExpr{
1146 left: &callExpr{
1147 name: "strip",
1148 args: xCall.args,
1149 returnType: starlarkTypeString,
1150 },
1151 right: xValue, isEq: !negate}
1152}
1153
1154// parses $(...), returning an expression
1155func (ctx *parseContext) parseReference(node mkparser.Node, ref *mkparser.MakeString) starlarkExpr {
1156 ref.TrimLeftSpaces()
1157 ref.TrimRightSpaces()
1158 refDump := ref.Dump()
1159
1160 // Handle only the case where the first (or only) word is constant
1161 words := ref.SplitN(" ", 2)
1162 if !words[0].Const() {
1163 return ctx.newBadExpr(node, "reference is too complex: %s", refDump)
1164 }
1165
1166 // If it is a single word, it can be a simple variable
1167 // reference or a function call
1168 if len(words) == 1 {
1169 if isMakeControlFunc(refDump) || refDump == "shell" {
1170 return &callExpr{
1171 name: refDump,
1172 args: []starlarkExpr{&stringLiteralExpr{""}},
1173 returnType: starlarkTypeUnknown,
1174 }
1175 }
1176 if v := ctx.addVariable(refDump); v != nil {
1177 return &variableRefExpr{v, ctx.lastAssignment(v.name()) != nil}
1178 }
1179 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1180 }
1181
1182 expr := &callExpr{name: words[0].Dump(), returnType: starlarkTypeUnknown}
1183 args := words[1]
1184 args.TrimLeftSpaces()
1185 // Make control functions and shell need special treatment as everything
1186 // after the name is a single text argument
1187 if isMakeControlFunc(expr.name) || expr.name == "shell" {
1188 x := ctx.parseMakeString(node, args)
1189 if xBad, ok := x.(*badExpr); ok {
1190 return xBad
1191 }
1192 expr.args = []starlarkExpr{x}
1193 return expr
1194 }
1195 if expr.name == "call" {
1196 words = args.SplitN(",", 2)
1197 if words[0].Empty() || !words[0].Const() {
Sasha Smundakf2c9f8b2021-07-27 10:44:48 -07001198 return ctx.newBadExpr(node, "cannot handle %s", refDump)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001199 }
1200 expr.name = words[0].Dump()
1201 if len(words) < 2 {
Sasha Smundak6609ba72021-07-22 18:32:56 -07001202 args = &mkparser.MakeString{}
1203 } else {
1204 args = words[1]
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001205 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001206 }
1207 if kf, found := knownFunctions[expr.name]; found {
1208 expr.returnType = kf.returnType
1209 } else {
1210 return ctx.newBadExpr(node, "cannot handle invoking %s", expr.name)
1211 }
1212 switch expr.name {
1213 case "word":
1214 return ctx.parseWordFunc(node, args)
Sasha Smundak16e07732021-07-23 11:38:23 -07001215 case "firstword", "lastword":
1216 return ctx.parseFirstOrLastwordFunc(node, expr.name, args)
Sasha Smundak6609ba72021-07-22 18:32:56 -07001217 case "my-dir":
1218 return &variableRefExpr{ctx.addVariable("LOCAL_PATH"), true}
Sasha Smundak94b41c72021-07-12 18:30:42 -07001219 case "subst", "patsubst":
1220 return ctx.parseSubstFunc(node, expr.name, args)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001221 default:
1222 for _, arg := range args.Split(",") {
1223 arg.TrimLeftSpaces()
1224 arg.TrimRightSpaces()
1225 x := ctx.parseMakeString(node, arg)
1226 if xBad, ok := x.(*badExpr); ok {
1227 return xBad
1228 }
1229 expr.args = append(expr.args, x)
1230 }
1231 }
1232 return expr
1233}
1234
Sasha Smundak94b41c72021-07-12 18:30:42 -07001235func (ctx *parseContext) parseSubstFunc(node mkparser.Node, fname string, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001236 words := args.Split(",")
1237 if len(words) != 3 {
Sasha Smundak94b41c72021-07-12 18:30:42 -07001238 return ctx.newBadExpr(node, "%s function should have 3 arguments", fname)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001239 }
1240 if !words[0].Const() || !words[1].Const() {
Sasha Smundak94b41c72021-07-12 18:30:42 -07001241 return ctx.newBadExpr(node, "%s function's from and to arguments should be constant", fname)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001242 }
1243 from := words[0].Strings[0]
1244 to := words[1].Strings[0]
1245 words[2].TrimLeftSpaces()
1246 words[2].TrimRightSpaces()
1247 obj := ctx.parseMakeString(node, words[2])
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001248 typ := obj.typ()
Sasha Smundak94b41c72021-07-12 18:30:42 -07001249 if typ == starlarkTypeString && fname == "subst" {
1250 // Optimization: if it's $(subst from, to, string), emit string.replace(from, to)
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001251 return &callExpr{
1252 object: obj,
1253 name: "replace",
1254 args: []starlarkExpr{&stringLiteralExpr{from}, &stringLiteralExpr{to}},
1255 returnType: typ,
1256 }
1257 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001258 return &callExpr{
Sasha Smundak94b41c72021-07-12 18:30:42 -07001259 name: fname,
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001260 args: []starlarkExpr{&stringLiteralExpr{from}, &stringLiteralExpr{to}, obj},
1261 returnType: obj.typ(),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001262 }
1263}
1264
1265func (ctx *parseContext) parseWordFunc(node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1266 words := args.Split(",")
1267 if len(words) != 2 {
1268 return ctx.newBadExpr(node, "word function should have 2 arguments")
1269 }
1270 var index uint64 = 0
1271 if words[0].Const() {
1272 index, _ = strconv.ParseUint(strings.TrimSpace(words[0].Strings[0]), 10, 64)
1273 }
1274 if index < 1 {
1275 return ctx.newBadExpr(node, "word index should be constant positive integer")
1276 }
1277 words[1].TrimLeftSpaces()
1278 words[1].TrimRightSpaces()
1279 array := ctx.parseMakeString(node, words[1])
1280 if xBad, ok := array.(*badExpr); ok {
1281 return xBad
1282 }
1283 if array.typ() != starlarkTypeList {
1284 array = &callExpr{object: array, name: "split", returnType: starlarkTypeList}
1285 }
1286 return indexExpr{array, &intLiteralExpr{int(index - 1)}}
1287}
1288
Sasha Smundak16e07732021-07-23 11:38:23 -07001289func (ctx *parseContext) parseFirstOrLastwordFunc(node mkparser.Node, name string, args *mkparser.MakeString) starlarkExpr {
1290 arg := ctx.parseMakeString(node, args)
1291 if bad, ok := arg.(*badExpr); ok {
1292 return bad
1293 }
1294 index := &intLiteralExpr{0}
1295 if name == "lastword" {
1296 if v, ok := arg.(*variableRefExpr); ok && v.ref.name() == "MAKEFILE_LIST" {
1297 return &stringLiteralExpr{ctx.script.mkFile}
1298 }
1299 index.literal = -1
1300 }
1301 if arg.typ() == starlarkTypeList {
1302 return &indexExpr{arg, index}
1303 }
1304 return &indexExpr{&callExpr{object: arg, name: "split", returnType: starlarkTypeList}, index}
1305}
1306
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001307func (ctx *parseContext) parseMakeString(node mkparser.Node, mk *mkparser.MakeString) starlarkExpr {
1308 if mk.Const() {
1309 return &stringLiteralExpr{mk.Dump()}
1310 }
1311 if mkRef, ok := mk.SingleVariable(); ok {
1312 return ctx.parseReference(node, mkRef)
1313 }
1314 // If we reached here, it's neither string literal nor a simple variable,
1315 // we need a full-blown interpolation node that will generate
1316 // "a%b%c" % (X, Y) for a$(X)b$(Y)c
1317 xInterp := &interpolateExpr{args: make([]starlarkExpr, len(mk.Variables))}
1318 for i, ref := range mk.Variables {
1319 arg := ctx.parseReference(node, ref.Name)
1320 if x, ok := arg.(*badExpr); ok {
1321 return x
1322 }
1323 xInterp.args[i] = arg
1324 }
1325 xInterp.chunks = append(xInterp.chunks, mk.Strings...)
1326 return xInterp
1327}
1328
1329// Handles the statements whose treatment is the same in all contexts: comment,
1330// assignment, variable (which is a macro call in reality) and all constructs that
1331// do not handle in any context ('define directive and any unrecognized stuff).
1332// Return true if we handled it.
1333func (ctx *parseContext) handleSimpleStatement(node mkparser.Node) bool {
1334 handled := true
1335 switch x := node.(type) {
1336 case *mkparser.Comment:
1337 ctx.insertComment("#" + x.Comment)
1338 case *mkparser.Assignment:
1339 ctx.handleAssignment(x)
1340 case *mkparser.Variable:
1341 ctx.handleVariable(x)
1342 case *mkparser.Directive:
1343 switch x.Name {
1344 case "define":
1345 ctx.handleDefine(x)
1346 case "include", "-include":
1347 ctx.handleInclude(node, ctx.parseMakeString(node, x.Args), x.Name[0] != '-')
1348 default:
1349 handled = false
1350 }
1351 default:
1352 ctx.errorf(x, "unsupported line %s", x.Dump())
1353 }
1354 return handled
1355}
1356
1357func (ctx *parseContext) insertComment(s string) {
1358 ctx.receiver.newNode(&commentNode{strings.TrimSpace(s)})
1359}
1360
1361func (ctx *parseContext) carryAsComment(failedNode mkparser.Node) {
1362 for _, line := range strings.Split(failedNode.Dump(), "\n") {
1363 ctx.insertComment("# " + line)
1364 }
1365}
1366
1367// records that the given node failed to be converted and includes an explanatory message
1368func (ctx *parseContext) errorf(failedNode mkparser.Node, message string, args ...interface{}) {
1369 if ctx.errorLogger != nil {
1370 ctx.errorLogger.NewError(message, failedNode, args...)
1371 }
1372 message = fmt.Sprintf(message, args...)
1373 ctx.insertComment(fmt.Sprintf("# MK2RBC TRANSLATION ERROR: %s", message))
1374 ctx.carryAsComment(failedNode)
1375 ctx.script.hasErrors = true
1376}
1377
1378func (ctx *parseContext) wrapBadExpr(xBad *badExpr) {
1379 ctx.insertComment(fmt.Sprintf("# MK2RBC TRANSLATION ERROR: %s", xBad.message))
1380 ctx.carryAsComment(xBad.node)
1381}
1382
1383func (ctx *parseContext) loadedModulePath(path string) string {
1384 // During the transition to Roboleaf some of the product configuration files
1385 // will be converted and checked in while the others will be generated on the fly
1386 // and run. The runner (rbcrun application) accommodates this by allowing three
1387 // different ways to specify the loaded file location:
1388 // 1) load(":<file>",...) loads <file> from the same directory
1389 // 2) load("//path/relative/to/source/root:<file>", ...) loads <file> source tree
1390 // 3) load("/absolute/path/to/<file> absolute path
1391 // If the file being generated and the file it wants to load are in the same directory,
1392 // generate option 1.
1393 // Otherwise, if output directory is not specified, generate 2)
1394 // Finally, if output directory has been specified and the file being generated and
1395 // the file it wants to load from are in the different directories, generate 2) or 3):
1396 // * if the file being loaded exists in the source tree, generate 2)
1397 // * otherwise, generate 3)
1398 // Finally, figure out the loaded module path and name and create a node for it
1399 loadedModuleDir := filepath.Dir(path)
1400 base := filepath.Base(path)
1401 loadedModuleName := strings.TrimSuffix(base, filepath.Ext(base)) + ctx.outputSuffix
1402 if loadedModuleDir == filepath.Dir(ctx.script.mkFile) {
1403 return ":" + loadedModuleName
1404 }
1405 if ctx.outputDir == "" {
1406 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1407 }
1408 if _, err := os.Stat(filepath.Join(loadedModuleDir, loadedModuleName)); err == nil {
1409 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1410 }
1411 return filepath.Join(ctx.outputDir, loadedModuleDir, loadedModuleName)
1412}
1413
1414func (ss *StarlarkScript) String() string {
1415 return NewGenerateContext(ss).emit()
1416}
1417
1418func (ss *StarlarkScript) SubConfigFiles() []string {
Sasha Smundak6609ba72021-07-22 18:32:56 -07001419
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001420 var subs []string
1421 for _, src := range ss.inherited {
1422 subs = append(subs, src.originalPath)
1423 }
1424 return subs
1425}
1426
1427func (ss *StarlarkScript) HasErrors() bool {
1428 return ss.hasErrors
1429}
1430
1431// Convert reads and parses a makefile. If successful, parsed tree
1432// is returned and then can be passed to String() to get the generated
1433// Starlark file.
1434func Convert(req Request) (*StarlarkScript, error) {
1435 reader := req.Reader
1436 if reader == nil {
1437 mkContents, err := ioutil.ReadFile(req.MkFile)
1438 if err != nil {
1439 return nil, err
1440 }
1441 reader = bytes.NewBuffer(mkContents)
1442 }
1443 parser := mkparser.NewParser(req.MkFile, reader)
1444 nodes, errs := parser.Parse()
1445 if len(errs) > 0 {
1446 for _, e := range errs {
1447 fmt.Fprintln(os.Stderr, "ERROR:", e)
1448 }
1449 return nil, fmt.Errorf("bad makefile %s", req.MkFile)
1450 }
1451 starScript := &StarlarkScript{
1452 moduleName: moduleNameForFile(req.MkFile),
1453 mkFile: req.MkFile,
1454 topDir: req.RootDir,
1455 traceCalls: req.TraceCalls,
1456 warnPartialSuccess: req.WarnPartialSuccess,
Sasha Smundak6609ba72021-07-22 18:32:56 -07001457 sourceFS: req.SourceFS,
1458 makefileFinder: req.MakefileFinder,
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001459 }
1460 ctx := newParseContext(starScript, nodes)
1461 ctx.outputSuffix = req.OutputSuffix
1462 ctx.outputDir = req.OutputDir
1463 ctx.errorLogger = req.ErrorLogger
1464 if len(req.TracedVariables) > 0 {
1465 ctx.tracedVariables = make(map[string]bool)
1466 for _, v := range req.TracedVariables {
1467 ctx.tracedVariables[v] = true
1468 }
1469 }
1470 ctx.pushReceiver(starScript)
1471 for ctx.hasNodes() && ctx.fatalError == nil {
1472 node := ctx.getNode()
1473 if ctx.handleSimpleStatement(node) {
1474 continue
1475 }
1476 switch x := node.(type) {
1477 case *mkparser.Directive:
1478 switch x.Name {
1479 case "ifeq", "ifneq", "ifdef", "ifndef":
1480 ctx.handleIfBlock(x)
1481 default:
1482 ctx.errorf(x, "unexpected directive %s", x.Name)
1483 }
1484 default:
1485 ctx.errorf(x, "unsupported line")
1486 }
1487 }
1488 if ctx.fatalError != nil {
1489 return nil, ctx.fatalError
1490 }
1491 return starScript, nil
1492}
1493
1494func Launcher(path, name string) string {
1495 var buf bytes.Buffer
1496 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
1497 fmt.Fprintf(&buf, "load(%q, \"init\")\n", path)
1498 fmt.Fprintf(&buf, "g, config = %s(%q, init)\n", cfnMain, name)
1499 fmt.Fprintf(&buf, "%s(g, config)\n", cfnPrintVars)
1500 return buf.String()
1501}
1502
1503func MakePath2ModuleName(mkPath string) string {
1504 return strings.TrimSuffix(mkPath, filepath.Ext(mkPath))
1505}