blob: 3ae8ab94c1fbd2f23357ffdf577a89c11349769d [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
Sasha Smundak3deb9682021-07-26 18:42:25 -070063 addSoongNamespace = "add_soong_config_namespace"
64 addSoongConfigVarValue = "add_soong_config_var_value"
65 fileExistsPhony = "$file_exists"
66 wildcardExistsPhony = "$wildcard_exists"
Sasha Smundakb051c4e2020-11-05 20:45:07 -080067)
68
69const (
70 callLoadAlways = "inherit-product"
71 callLoadIf = "inherit-product-if-exists"
72)
73
74var knownFunctions = map[string]struct {
75 // The name of the runtime function this function call in makefiles maps to.
76 // If it starts with !, then this makefile function call is rewritten to
77 // something else.
78 runtimeName string
79 returnType starlarkType
Sasha Smundak3deb9682021-07-26 18:42:25 -070080 hiddenArg hiddenArgType
Sasha Smundakb051c4e2020-11-05 20:45:07 -080081}{
Sasha Smundak3deb9682021-07-26 18:42:25 -070082 "abspath": {baseName + ".abspath", starlarkTypeString, hiddenArgNone},
83 fileExistsPhony: {baseName + ".file_exists", starlarkTypeBool, hiddenArgNone},
84 wildcardExistsPhony: {baseName + ".file_wildcard_exists", starlarkTypeBool, hiddenArgNone},
85 addSoongNamespace: {baseName + ".add_soong_config_namespace", starlarkTypeVoid, hiddenArgGlobal},
86 addSoongConfigVarValue: {baseName + ".add_soong_config_var_value", starlarkTypeVoid, hiddenArgGlobal},
87 "add-to-product-copy-files-if-exists": {baseName + ".copy_if_exists", starlarkTypeList, hiddenArgNone},
88 "addprefix": {baseName + ".addprefix", starlarkTypeList, hiddenArgNone},
89 "addsuffix": {baseName + ".addsuffix", starlarkTypeList, hiddenArgNone},
90 "copy-files": {baseName + ".copy_files", starlarkTypeList, hiddenArgNone},
91 "dir": {baseName + ".dir", starlarkTypeList, hiddenArgNone},
92 "enforce-product-packages-exist": {baseName + ".enforce_product_packages_exist", starlarkTypeVoid, hiddenArgNone},
93 "error": {baseName + ".mkerror", starlarkTypeVoid, hiddenArgNone},
94 "findstring": {"!findstring", starlarkTypeInt, hiddenArgNone},
95 "find-copy-subdir-files": {baseName + ".find_and_copy", starlarkTypeList, hiddenArgNone},
96 "find-word-in-list": {"!find-word-in-list", starlarkTypeUnknown, hiddenArgNone}, // internal macro
97 "filter": {baseName + ".filter", starlarkTypeList, hiddenArgNone},
98 "filter-out": {baseName + ".filter_out", starlarkTypeList, hiddenArgNone},
99 "firstword": {"!firstword", starlarkTypeString, hiddenArgNone},
100 "get-vendor-board-platforms": {"!get-vendor-board-platforms", starlarkTypeList, hiddenArgNone}, // internal macro, used by is-board-platform, etc.
101 "info": {baseName + ".mkinfo", starlarkTypeVoid, hiddenArgNone},
102 "is-android-codename": {"!is-android-codename", starlarkTypeBool, hiddenArgNone}, // unused by product config
103 "is-android-codename-in-list": {"!is-android-codename-in-list", starlarkTypeBool, hiddenArgNone}, // unused by product config
104 "is-board-platform": {"!is-board-platform", starlarkTypeBool, hiddenArgNone},
105 "is-board-platform-in-list": {"!is-board-platform-in-list", starlarkTypeBool, hiddenArgNone},
106 "is-chipset-in-board-platform": {"!is-chipset-in-board-platform", starlarkTypeUnknown, hiddenArgNone}, // unused by product config
107 "is-chipset-prefix-in-board-platform": {"!is-chipset-prefix-in-board-platform", starlarkTypeBool, hiddenArgNone}, // unused by product config
108 "is-not-board-platform": {"!is-not-board-platform", starlarkTypeBool, hiddenArgNone}, // defined but never used
109 "is-platform-sdk-version-at-least": {"!is-platform-sdk-version-at-least", starlarkTypeBool, hiddenArgNone}, // unused by product config
110 "is-product-in-list": {"!is-product-in-list", starlarkTypeBool, hiddenArgNone},
111 "is-vendor-board-platform": {"!is-vendor-board-platform", starlarkTypeBool, hiddenArgNone},
112 callLoadAlways: {"!inherit-product", starlarkTypeVoid, hiddenArgNone},
113 callLoadIf: {"!inherit-product-if-exists", starlarkTypeVoid, hiddenArgNone},
114 "lastword": {"!lastword", starlarkTypeString, hiddenArgNone},
115 "match-prefix": {"!match-prefix", starlarkTypeUnknown, hiddenArgNone}, // internal macro
116 "match-word": {"!match-word", starlarkTypeUnknown, hiddenArgNone}, // internal macro
117 "match-word-in-list": {"!match-word-in-list", starlarkTypeUnknown, hiddenArgNone}, // internal macro
118 "notdir": {baseName + ".notdir", starlarkTypeString, hiddenArgNone},
119 "my-dir": {"!my-dir", starlarkTypeString, hiddenArgNone},
120 "patsubst": {baseName + ".mkpatsubst", starlarkTypeString, hiddenArgNone},
Sasha Smundak04453082021-08-17 18:14:41 -0700121 "product-copy-files-by-pattern": {baseName + ".product_copy_files_by_pattern", starlarkTypeList, hiddenArgNone},
Sasha Smundak3deb9682021-07-26 18:42:25 -0700122 "require-artifacts-in-path": {baseName + ".require_artifacts_in_path", starlarkTypeVoid, hiddenArgNone},
123 "require-artifacts-in-path-relaxed": {baseName + ".require_artifacts_in_path_relaxed", starlarkTypeVoid, hiddenArgNone},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800124 // TODO(asmundak): remove it once all calls are removed from configuration makefiles. see b/183161002
Sasha Smundak3deb9682021-07-26 18:42:25 -0700125 "shell": {baseName + ".shell", starlarkTypeString, hiddenArgNone},
126 "strip": {baseName + ".mkstrip", starlarkTypeString, hiddenArgNone},
127 "tb-modules": {"!tb-modules", starlarkTypeUnknown, hiddenArgNone}, // defined in hardware/amlogic/tb_modules/tb_detect.mk, unused
128 "subst": {baseName + ".mksubst", starlarkTypeString, hiddenArgNone},
129 "warning": {baseName + ".mkwarning", starlarkTypeVoid, hiddenArgNone},
130 "word": {baseName + "!word", starlarkTypeString, hiddenArgNone},
131 "wildcard": {baseName + ".expand_wildcard", starlarkTypeList, hiddenArgNone},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800132}
133
134var builtinFuncRex = regexp.MustCompile(
135 "^(addprefix|addsuffix|abspath|and|basename|call|dir|error|eval" +
136 "|flavor|foreach|file|filter|filter-out|findstring|firstword|guile" +
137 "|if|info|join|lastword|notdir|or|origin|patsubst|realpath" +
138 "|shell|sort|strip|subst|suffix|value|warning|word|wordlist|words" +
139 "|wildcard)")
140
141// Conversion request parameters
142type Request struct {
143 MkFile string // file to convert
144 Reader io.Reader // if set, read input from this stream instead
145 RootDir string // root directory path used to resolve included files
146 OutputSuffix string // generated Starlark files suffix
147 OutputDir string // if set, root of the output hierarchy
148 ErrorLogger ErrorMonitorCB
149 TracedVariables []string // trace assignment to these variables
150 TraceCalls bool
151 WarnPartialSuccess bool
Sasha Smundak6609ba72021-07-22 18:32:56 -0700152 SourceFS fs.FS
153 MakefileFinder MakefileFinder
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800154}
155
156// An error sink allowing to gather error statistics.
157// NewError is called on every error encountered during processing.
158type ErrorMonitorCB interface {
159 NewError(s string, node mkparser.Node, args ...interface{})
160}
161
162// Derives module name for a given file. It is base name
163// (file name without suffix), with some characters replaced to make it a Starlark identifier
164func moduleNameForFile(mkFile string) string {
165 base := strings.TrimSuffix(filepath.Base(mkFile), filepath.Ext(mkFile))
166 // TODO(asmundak): what else can be in the product file names?
Sasha Smundak6609ba72021-07-22 18:32:56 -0700167 return strings.NewReplacer("-", "_", ".", "_").Replace(base)
168
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800169}
170
171func cloneMakeString(mkString *mkparser.MakeString) *mkparser.MakeString {
172 r := &mkparser.MakeString{StringPos: mkString.StringPos}
173 r.Strings = append(r.Strings, mkString.Strings...)
174 r.Variables = append(r.Variables, mkString.Variables...)
175 return r
176}
177
178func isMakeControlFunc(s string) bool {
179 return s == "error" || s == "warning" || s == "info"
180}
181
182// Starlark output generation context
183type generationContext struct {
184 buf strings.Builder
185 starScript *StarlarkScript
186 indentLevel int
187 inAssignment bool
188 tracedCount int
189}
190
191func NewGenerateContext(ss *StarlarkScript) *generationContext {
192 return &generationContext{starScript: ss}
193}
194
195// emit returns generated script
196func (gctx *generationContext) emit() string {
197 ss := gctx.starScript
198
199 // The emitted code has the following layout:
200 // <initial comments>
201 // preamble, i.e.,
202 // load statement for the runtime support
203 // load statement for each unique submodule pulled in by this one
204 // def init(g, handle):
205 // cfg = rblf.cfg(handle)
206 // <statements>
207 // <warning if conversion was not clean>
208
209 iNode := len(ss.nodes)
210 for i, node := range ss.nodes {
211 if _, ok := node.(*commentNode); !ok {
212 iNode = i
213 break
214 }
215 node.emit(gctx)
216 }
217
218 gctx.emitPreamble()
219
220 gctx.newLine()
221 // The arguments passed to the init function are the global dictionary
222 // ('g') and the product configuration dictionary ('cfg')
223 gctx.write("def init(g, handle):")
224 gctx.indentLevel++
225 if gctx.starScript.traceCalls {
226 gctx.newLine()
227 gctx.writef(`print(">%s")`, gctx.starScript.mkFile)
228 }
229 gctx.newLine()
230 gctx.writef("cfg = %s(handle)", cfnGetCfg)
231 for _, node := range ss.nodes[iNode:] {
232 node.emit(gctx)
233 }
234
235 if ss.hasErrors && ss.warnPartialSuccess {
236 gctx.newLine()
237 gctx.writef("%s(%q, %q)", cfnWarning, filepath.Base(ss.mkFile), "partially successful conversion")
238 }
239 if gctx.starScript.traceCalls {
240 gctx.newLine()
241 gctx.writef(`print("<%s")`, gctx.starScript.mkFile)
242 }
243 gctx.indentLevel--
244 gctx.write("\n")
245 return gctx.buf.String()
246}
247
248func (gctx *generationContext) emitPreamble() {
249 gctx.newLine()
250 gctx.writef("load(%q, %q)", baseUri, baseName)
251 // Emit exactly one load statement for each URI.
252 loadedSubConfigs := make(map[string]string)
253 for _, sc := range gctx.starScript.inherited {
254 uri := sc.path
255 if m, ok := loadedSubConfigs[uri]; ok {
256 // No need to emit load statement, but fix module name.
257 sc.moduleLocalName = m
258 continue
259 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700260 if sc.optional {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800261 uri += "|init"
262 }
263 gctx.newLine()
264 gctx.writef("load(%q, %s = \"init\")", uri, sc.entryName())
265 loadedSubConfigs[uri] = sc.moduleLocalName
266 }
267 gctx.write("\n")
268}
269
270func (gctx *generationContext) emitPass() {
271 gctx.newLine()
272 gctx.write("pass")
273}
274
275func (gctx *generationContext) write(ss ...string) {
276 for _, s := range ss {
277 gctx.buf.WriteString(s)
278 }
279}
280
281func (gctx *generationContext) writef(format string, args ...interface{}) {
282 gctx.write(fmt.Sprintf(format, args...))
283}
284
285func (gctx *generationContext) newLine() {
286 if gctx.buf.Len() == 0 {
287 return
288 }
289 gctx.write("\n")
290 gctx.writef("%*s", 2*gctx.indentLevel, "")
291}
292
293type knownVariable struct {
294 name string
295 class varClass
296 valueType starlarkType
297}
298
299type knownVariables map[string]knownVariable
300
301func (pcv knownVariables) NewVariable(name string, varClass varClass, valueType starlarkType) {
302 v, exists := pcv[name]
303 if !exists {
304 pcv[name] = knownVariable{name, varClass, valueType}
305 return
306 }
307 // Conflict resolution:
308 // * config class trumps everything
309 // * any type trumps unknown type
310 match := varClass == v.class
311 if !match {
312 if varClass == VarClassConfig {
313 v.class = VarClassConfig
314 match = true
315 } else if v.class == VarClassConfig {
316 match = true
317 }
318 }
319 if valueType != v.valueType {
320 if valueType != starlarkTypeUnknown {
321 if v.valueType == starlarkTypeUnknown {
322 v.valueType = valueType
323 } else {
324 match = false
325 }
326 }
327 }
328 if !match {
329 fmt.Fprintf(os.Stderr, "cannot redefine %s as %v/%v (already defined as %v/%v)\n",
330 name, varClass, valueType, v.class, v.valueType)
331 }
332}
333
334// All known product variables.
335var KnownVariables = make(knownVariables)
336
337func init() {
338 for _, kv := range []string{
339 // Kernel-related variables that we know are lists.
340 "BOARD_VENDOR_KERNEL_MODULES",
341 "BOARD_VENDOR_RAMDISK_KERNEL_MODULES",
342 "BOARD_VENDOR_RAMDISK_KERNEL_MODULES_LOAD",
343 "BOARD_RECOVERY_KERNEL_MODULES",
344 // Other variables we knwo are lists
345 "ART_APEX_JARS",
346 } {
347 KnownVariables.NewVariable(kv, VarClassSoong, starlarkTypeList)
348 }
349}
350
351type nodeReceiver interface {
352 newNode(node starlarkNode)
353}
354
355// Information about the generated Starlark script.
356type StarlarkScript struct {
357 mkFile string
358 moduleName string
359 mkPos scanner.Position
360 nodes []starlarkNode
Sasha Smundak6609ba72021-07-22 18:32:56 -0700361 inherited []*moduleInfo
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800362 hasErrors bool
363 topDir string
364 traceCalls bool // print enter/exit each init function
365 warnPartialSuccess bool
Sasha Smundak6609ba72021-07-22 18:32:56 -0700366 sourceFS fs.FS
367 makefileFinder MakefileFinder
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800368}
369
370func (ss *StarlarkScript) newNode(node starlarkNode) {
371 ss.nodes = append(ss.nodes, node)
372}
373
374// varAssignmentScope points to the last assignment for each variable
375// in the current block. It is used during the parsing to chain
376// the assignments to a variable together.
377type varAssignmentScope struct {
378 outer *varAssignmentScope
379 vars map[string]*assignmentNode
380}
381
382// parseContext holds the script we are generating and all the ephemeral data
383// needed during the parsing.
384type parseContext struct {
385 script *StarlarkScript
386 nodes []mkparser.Node // Makefile as parsed by mkparser
387 currentNodeIndex int // Node in it we are processing
388 ifNestLevel int
389 moduleNameCount map[string]int // count of imported modules with given basename
390 fatalError error
391 builtinMakeVars map[string]starlarkExpr
392 outputSuffix string
393 errorLogger ErrorMonitorCB
394 tracedVariables map[string]bool // variables to be traced in the generated script
395 variables map[string]variable
396 varAssignments *varAssignmentScope
397 receiver nodeReceiver // receptacle for the generated starlarkNode's
398 receiverStack []nodeReceiver
399 outputDir string
Sasha Smundak6609ba72021-07-22 18:32:56 -0700400 dependentModules map[string]*moduleInfo
Sasha Smundak3deb9682021-07-26 18:42:25 -0700401 soongNamespaces map[string]map[string]bool
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800402}
403
404func newParseContext(ss *StarlarkScript, nodes []mkparser.Node) *parseContext {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700405 topdir, _ := filepath.Split(filepath.Join(ss.topDir, "foo"))
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800406 predefined := []struct{ name, value string }{
407 {"SRC_TARGET_DIR", filepath.Join("build", "make", "target")},
408 {"LOCAL_PATH", filepath.Dir(ss.mkFile)},
Sasha Smundak6609ba72021-07-22 18:32:56 -0700409 {"TOPDIR", topdir},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800410 // TODO(asmundak): maybe read it from build/make/core/envsetup.mk?
411 {"TARGET_COPY_OUT_SYSTEM", "system"},
412 {"TARGET_COPY_OUT_SYSTEM_OTHER", "system_other"},
413 {"TARGET_COPY_OUT_DATA", "data"},
414 {"TARGET_COPY_OUT_ASAN", filepath.Join("data", "asan")},
415 {"TARGET_COPY_OUT_OEM", "oem"},
416 {"TARGET_COPY_OUT_RAMDISK", "ramdisk"},
417 {"TARGET_COPY_OUT_DEBUG_RAMDISK", "debug_ramdisk"},
418 {"TARGET_COPY_OUT_VENDOR_DEBUG_RAMDISK", "vendor_debug_ramdisk"},
419 {"TARGET_COPY_OUT_TEST_HARNESS_RAMDISK", "test_harness_ramdisk"},
420 {"TARGET_COPY_OUT_ROOT", "root"},
421 {"TARGET_COPY_OUT_RECOVERY", "recovery"},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800422 {"TARGET_COPY_OUT_VENDOR_RAMDISK", "vendor_ramdisk"},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800423 // 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 Smundak3deb9682021-07-26 18:42:25 -0700446 soongNamespaces: make(map[string]map[string]bool),
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800447 }
448 ctx.pushVarAssignments()
449 for _, item := range predefined {
450 ctx.variables[item.name] = &predefinedVariable{
451 baseVariable: baseVariable{nam: item.name, typ: starlarkTypeString},
452 value: &stringLiteralExpr{item.value},
453 }
454 }
455
456 return ctx
457}
458
459func (ctx *parseContext) lastAssignment(name string) *assignmentNode {
460 for va := ctx.varAssignments; va != nil; va = va.outer {
461 if v, ok := va.vars[name]; ok {
462 return v
463 }
464 }
465 return nil
466}
467
468func (ctx *parseContext) setLastAssignment(name string, asgn *assignmentNode) {
469 ctx.varAssignments.vars[name] = asgn
470}
471
472func (ctx *parseContext) pushVarAssignments() {
473 va := &varAssignmentScope{
474 outer: ctx.varAssignments,
475 vars: make(map[string]*assignmentNode),
476 }
477 ctx.varAssignments = va
478}
479
480func (ctx *parseContext) popVarAssignments() {
481 ctx.varAssignments = ctx.varAssignments.outer
482}
483
484func (ctx *parseContext) pushReceiver(rcv nodeReceiver) {
485 ctx.receiverStack = append(ctx.receiverStack, ctx.receiver)
486 ctx.receiver = rcv
487}
488
489func (ctx *parseContext) popReceiver() {
490 last := len(ctx.receiverStack) - 1
491 if last < 0 {
492 panic(fmt.Errorf("popReceiver: receiver stack empty"))
493 }
494 ctx.receiver = ctx.receiverStack[last]
495 ctx.receiverStack = ctx.receiverStack[0:last]
496}
497
498func (ctx *parseContext) hasNodes() bool {
499 return ctx.currentNodeIndex < len(ctx.nodes)
500}
501
502func (ctx *parseContext) getNode() mkparser.Node {
503 if !ctx.hasNodes() {
504 return nil
505 }
506 node := ctx.nodes[ctx.currentNodeIndex]
507 ctx.currentNodeIndex++
508 return node
509}
510
511func (ctx *parseContext) backNode() {
512 if ctx.currentNodeIndex <= 0 {
513 panic("Cannot back off")
514 }
515 ctx.currentNodeIndex--
516}
517
518func (ctx *parseContext) handleAssignment(a *mkparser.Assignment) {
519 // Handle only simple variables
520 if !a.Name.Const() {
521 ctx.errorf(a, "Only simple variables are handled")
522 return
523 }
524 name := a.Name.Strings[0]
Sasha Smundak3deb9682021-07-26 18:42:25 -0700525 const soongNsPrefix = "SOONG_CONFIG_"
526 // Soong confuguration
527 if strings.HasPrefix(name, soongNsPrefix) {
528 ctx.handleSoongNsAssignment(strings.TrimPrefix(name, soongNsPrefix), a)
529 return
530 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800531 lhs := ctx.addVariable(name)
532 if lhs == nil {
533 ctx.errorf(a, "unknown variable %s", name)
534 return
535 }
536 _, isTraced := ctx.tracedVariables[name]
537 asgn := &assignmentNode{lhs: lhs, mkValue: a.Value, isTraced: isTraced}
538 if lhs.valueType() == starlarkTypeUnknown {
539 // Try to divine variable type from the RHS
540 asgn.value = ctx.parseMakeString(a, a.Value)
541 if xBad, ok := asgn.value.(*badExpr); ok {
542 ctx.wrapBadExpr(xBad)
543 return
544 }
545 inferred_type := asgn.value.typ()
546 if inferred_type != starlarkTypeUnknown {
Sasha Smundak9d011ab2021-07-09 16:00:57 -0700547 lhs.setValueType(inferred_type)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800548 }
549 }
550 if lhs.valueType() == starlarkTypeList {
551 xConcat := ctx.buildConcatExpr(a)
552 if xConcat == nil {
553 return
554 }
555 switch len(xConcat.items) {
556 case 0:
557 asgn.value = &listExpr{}
558 case 1:
559 asgn.value = xConcat.items[0]
560 default:
561 asgn.value = xConcat
562 }
563 } else {
564 asgn.value = ctx.parseMakeString(a, a.Value)
565 if xBad, ok := asgn.value.(*badExpr); ok {
566 ctx.wrapBadExpr(xBad)
567 return
568 }
569 }
570
571 // TODO(asmundak): move evaluation to a separate pass
572 asgn.value, _ = asgn.value.eval(ctx.builtinMakeVars)
573
574 asgn.previous = ctx.lastAssignment(name)
575 ctx.setLastAssignment(name, asgn)
576 switch a.Type {
577 case "=", ":=":
578 asgn.flavor = asgnSet
579 case "+=":
580 if asgn.previous == nil && !asgn.lhs.isPreset() {
581 asgn.flavor = asgnMaybeAppend
582 } else {
583 asgn.flavor = asgnAppend
584 }
585 case "?=":
586 asgn.flavor = asgnMaybeSet
587 default:
588 panic(fmt.Errorf("unexpected assignment type %s", a.Type))
589 }
590
591 ctx.receiver.newNode(asgn)
592}
593
Sasha Smundak3deb9682021-07-26 18:42:25 -0700594func (ctx *parseContext) handleSoongNsAssignment(name string, asgn *mkparser.Assignment) {
595 val := ctx.parseMakeString(asgn, asgn.Value)
596 if xBad, ok := val.(*badExpr); ok {
597 ctx.wrapBadExpr(xBad)
598 return
599 }
600 val, _ = val.eval(ctx.builtinMakeVars)
601
602 // Unfortunately, Soong namespaces can be set up by directly setting corresponding Make
603 // variables instead of via add_soong_config_namespace + add_soong_config_var_value.
604 // Try to divine the call from the assignment as follows:
605 if name == "NAMESPACES" {
606 // Upon seeng
607 // SOONG_CONFIG_NAMESPACES += foo
608 // remember that there is a namespace `foo` and act as we saw
609 // $(call add_soong_config_namespace,foo)
610 s, ok := maybeString(val)
611 if !ok {
612 ctx.errorf(asgn, "cannot handle variables in SOONG_CONFIG_NAMESPACES assignment, please use add_soong_config_namespace instead")
613 return
614 }
615 for _, ns := range strings.Fields(s) {
616 ctx.addSoongNamespace(ns)
617 ctx.receiver.newNode(&exprNode{&callExpr{
618 name: addSoongNamespace,
619 args: []starlarkExpr{&stringLiteralExpr{ns}},
620 returnType: starlarkTypeVoid,
621 }})
622 }
623 } else {
624 // Upon seeing
625 // SOONG_CONFIG_x_y = v
626 // find a namespace called `x` and act as if we encountered
627 // $(call add_config_var_value(x,y,v)
628 // or check that `x_y` is a namespace, and then add the RHS of this assignment as variables in
629 // it.
630 // Emit an error in the ambiguous situation (namespaces `foo_bar` with a variable `baz`
631 // and `foo` with a variable `bar_baz`.
632 namespaceName := ""
633 if ctx.hasSoongNamespace(name) {
634 namespaceName = name
635 }
636 var varName string
637 for pos, ch := range name {
638 if !(ch == '_' && ctx.hasSoongNamespace(name[0:pos])) {
639 continue
640 }
641 if namespaceName != "" {
642 ctx.errorf(asgn, "ambiguous soong namespace (may be either `%s` or `%s`)", namespaceName, name[0:pos])
643 return
644 }
645 namespaceName = name[0:pos]
646 varName = name[pos+1:]
647 }
648 if namespaceName == "" {
649 ctx.errorf(asgn, "cannot figure out Soong namespace, please use add_soong_config_var_value macro instead")
650 return
651 }
652 if varName == "" {
653 // Remember variables in this namespace
654 s, ok := maybeString(val)
655 if !ok {
656 ctx.errorf(asgn, "cannot handle variables in SOONG_CONFIG_ assignment, please use add_soong_config_var_value instead")
657 return
658 }
659 ctx.updateSoongNamespace(asgn.Type != "+=", namespaceName, strings.Fields(s))
660 return
661 }
662
663 // Finally, handle assignment to a namespace variable
664 if !ctx.hasNamespaceVar(namespaceName, varName) {
665 ctx.errorf(asgn, "no %s variable in %s namespace, please use add_soong_config_var_value instead", varName, namespaceName)
666 return
667 }
668 ctx.receiver.newNode(&exprNode{&callExpr{
669 name: addSoongConfigVarValue,
670 args: []starlarkExpr{&stringLiteralExpr{namespaceName}, &stringLiteralExpr{varName}, val},
671 returnType: starlarkTypeVoid,
672 }})
673 }
674}
675
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800676func (ctx *parseContext) buildConcatExpr(a *mkparser.Assignment) *concatExpr {
677 xConcat := &concatExpr{}
678 var xItemList *listExpr
679 addToItemList := func(x ...starlarkExpr) {
680 if xItemList == nil {
681 xItemList = &listExpr{[]starlarkExpr{}}
682 }
683 xItemList.items = append(xItemList.items, x...)
684 }
685 finishItemList := func() {
686 if xItemList != nil {
687 xConcat.items = append(xConcat.items, xItemList)
688 xItemList = nil
689 }
690 }
691
692 items := a.Value.Words()
693 for _, item := range items {
694 // A function call in RHS is supposed to return a list, all other item
695 // expressions return individual elements.
696 switch x := ctx.parseMakeString(a, item).(type) {
697 case *badExpr:
698 ctx.wrapBadExpr(x)
699 return nil
700 case *stringLiteralExpr:
701 addToItemList(maybeConvertToStringList(x).(*listExpr).items...)
702 default:
703 switch x.typ() {
704 case starlarkTypeList:
705 finishItemList()
706 xConcat.items = append(xConcat.items, x)
707 case starlarkTypeString:
708 finishItemList()
709 xConcat.items = append(xConcat.items, &callExpr{
710 object: x,
711 name: "split",
712 args: nil,
713 returnType: starlarkTypeList,
714 })
715 default:
716 addToItemList(x)
717 }
718 }
719 }
720 if xItemList != nil {
721 xConcat.items = append(xConcat.items, xItemList)
722 }
723 return xConcat
724}
725
Sasha Smundak6609ba72021-07-22 18:32:56 -0700726func (ctx *parseContext) newDependentModule(path string, optional bool) *moduleInfo {
727 modulePath := ctx.loadedModulePath(path)
728 if mi, ok := ctx.dependentModules[modulePath]; ok {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700729 mi.optional = mi.optional && optional
Sasha Smundak6609ba72021-07-22 18:32:56 -0700730 return mi
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800731 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800732 moduleName := moduleNameForFile(path)
733 moduleLocalName := "_" + moduleName
734 n, found := ctx.moduleNameCount[moduleName]
735 if found {
736 moduleLocalName += fmt.Sprintf("%d", n)
737 }
738 ctx.moduleNameCount[moduleName] = n + 1
Sasha Smundak6609ba72021-07-22 18:32:56 -0700739 mi := &moduleInfo{
740 path: modulePath,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800741 originalPath: path,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800742 moduleLocalName: moduleLocalName,
Sasha Smundak6609ba72021-07-22 18:32:56 -0700743 optional: optional,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800744 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700745 ctx.dependentModules[modulePath] = mi
746 ctx.script.inherited = append(ctx.script.inherited, mi)
747 return mi
748}
749
750func (ctx *parseContext) handleSubConfig(
751 v mkparser.Node, pathExpr starlarkExpr, loadAlways bool, processModule func(inheritedModule)) {
752 pathExpr, _ = pathExpr.eval(ctx.builtinMakeVars)
753
754 // In a simple case, the name of a module to inherit/include is known statically.
755 if path, ok := maybeString(pathExpr); ok {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700756 // Note that even if this directive loads a module unconditionally, a module may be
757 // absent without causing any harm if this directive is inside an if/else block.
758 moduleShouldExist := loadAlways && ctx.ifNestLevel == 0
Sasha Smundak6609ba72021-07-22 18:32:56 -0700759 if strings.Contains(path, "*") {
760 if paths, err := fs.Glob(ctx.script.sourceFS, path); err == nil {
761 for _, p := range paths {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700762 mi := ctx.newDependentModule(p, !moduleShouldExist)
763 processModule(inheritedStaticModule{mi, loadAlways})
Sasha Smundak6609ba72021-07-22 18:32:56 -0700764 }
765 } else {
766 ctx.errorf(v, "cannot glob wildcard argument")
767 }
768 } else {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700769 mi := ctx.newDependentModule(path, !moduleShouldExist)
770 processModule(inheritedStaticModule{mi, loadAlways})
Sasha Smundak6609ba72021-07-22 18:32:56 -0700771 }
772 return
773 }
774
775 // If module path references variables (e.g., $(v1)/foo/$(v2)/device-config.mk), find all the paths in the
776 // source tree that may be a match and the corresponding variable values. For instance, if the source tree
777 // contains vendor1/foo/abc/dev.mk and vendor2/foo/def/dev.mk, the first one will be inherited when
778 // (v1, v2) == ('vendor1', 'abc'), and the second one when (v1, v2) == ('vendor2', 'def').
779 // We then emit the code that loads all of them, e.g.:
780 // load("//vendor1/foo/abc:dev.rbc", _dev1_init="init")
781 // load("//vendor2/foo/def/dev.rbc", _dev2_init="init")
782 // And then inherit it as follows:
783 // _e = {
784 // "vendor1/foo/abc/dev.mk": ("vendor1/foo/abc/dev", _dev1_init),
785 // "vendor2/foo/def/dev.mk": ("vendor2/foo/def/dev", _dev_init2) }.get("%s/foo/%s/dev.mk" % (v1, v2))
786 // if _e:
787 // rblf.inherit(handle, _e[0], _e[1])
788 //
789 var matchingPaths []string
790 varPath, ok := pathExpr.(*interpolateExpr)
791 if !ok {
792 ctx.errorf(v, "inherit-product/include argument is too complex")
793 return
794 }
795
796 pathPattern := []string{varPath.chunks[0]}
797 for _, chunk := range varPath.chunks[1:] {
798 if chunk != "" {
799 pathPattern = append(pathPattern, chunk)
800 }
801 }
802 if pathPattern[0] != "" {
803 matchingPaths = ctx.findMatchingPaths(pathPattern)
804 } else {
805 // Heuristics -- if pattern starts from top, restrict it to the directories where
Sasha Smundak90be8c52021-08-03 11:06:10 -0700806 // we know inherit-product uses dynamically calculated path. Restrict it even further
807 // for certain path which would yield too many useless matches
808 if len(varPath.chunks) == 2 && varPath.chunks[1] == "/BoardConfigVendor.mk" {
809 pathPattern[0] = "vendor/google_devices"
810 matchingPaths = ctx.findMatchingPaths(pathPattern)
811 } else {
812 for _, t := range []string{"vendor/qcom", "vendor/google_devices"} {
813 pathPattern[0] = t
814 matchingPaths = append(matchingPaths, ctx.findMatchingPaths(pathPattern)...)
815 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700816 }
817 }
818 // Safeguard against $(call inherit-product,$(PRODUCT_PATH))
Sasha Smundak90be8c52021-08-03 11:06:10 -0700819 const maxMatchingFiles = 150
Sasha Smundak6609ba72021-07-22 18:32:56 -0700820 if len(matchingPaths) > maxMatchingFiles {
821 ctx.errorf(v, "there are >%d files matching the pattern, please rewrite it", maxMatchingFiles)
822 return
823 }
824 res := inheritedDynamicModule{*varPath, []*moduleInfo{}, loadAlways}
825 for _, p := range matchingPaths {
826 // A product configuration files discovered dynamically may attempt to inherit
827 // from another one which does not exist in this source tree. Prevent load errors
828 // by always loading the dynamic files as optional.
829 res.candidateModules = append(res.candidateModules, ctx.newDependentModule(p, true))
830 }
831 processModule(res)
832}
833
834func (ctx *parseContext) findMatchingPaths(pattern []string) []string {
835 files := ctx.script.makefileFinder.Find(ctx.script.topDir)
836 if len(pattern) == 0 {
837 return files
838 }
839
840 // Create regular expression from the pattern
841 s_regexp := "^" + regexp.QuoteMeta(pattern[0])
842 for _, s := range pattern[1:] {
843 s_regexp += ".*" + regexp.QuoteMeta(s)
844 }
845 s_regexp += "$"
846 rex := regexp.MustCompile(s_regexp)
847
848 // Now match
849 var res []string
850 for _, p := range files {
851 if rex.MatchString(p) {
852 res = append(res, p)
853 }
854 }
855 return res
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800856}
857
858func (ctx *parseContext) handleInheritModule(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700859 ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700860 ctx.receiver.newNode(&inheritNode{im, loadAlways})
Sasha Smundak6609ba72021-07-22 18:32:56 -0700861 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800862}
863
864func (ctx *parseContext) handleInclude(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700865 ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) {
Sasha Smundak868c5e32021-09-23 16:20:58 -0700866 ctx.receiver.newNode(&includeNode{im, loadAlways})
Sasha Smundak6609ba72021-07-22 18:32:56 -0700867 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800868}
869
870func (ctx *parseContext) handleVariable(v *mkparser.Variable) {
871 // Handle:
872 // $(call inherit-product,...)
873 // $(call inherit-product-if-exists,...)
874 // $(info xxx)
875 // $(warning xxx)
876 // $(error xxx)
877 expr := ctx.parseReference(v, v.Name)
878 switch x := expr.(type) {
879 case *callExpr:
880 if x.name == callLoadAlways || x.name == callLoadIf {
881 ctx.handleInheritModule(v, x.args[0], x.name == callLoadAlways)
882 } else if isMakeControlFunc(x.name) {
883 // File name is the first argument
884 args := []starlarkExpr{
885 &stringLiteralExpr{ctx.script.mkFile},
886 x.args[0],
887 }
888 ctx.receiver.newNode(&exprNode{
889 &callExpr{name: x.name, args: args, returnType: starlarkTypeUnknown},
890 })
891 } else {
892 ctx.receiver.newNode(&exprNode{expr})
893 }
894 case *badExpr:
895 ctx.wrapBadExpr(x)
896 return
897 default:
898 ctx.errorf(v, "cannot handle %s", v.Dump())
899 return
900 }
901}
902
903func (ctx *parseContext) handleDefine(directive *mkparser.Directive) {
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700904 macro_name := strings.Fields(directive.Args.Strings[0])[0]
905 // Ignore the macros that we handle
906 if _, ok := knownFunctions[macro_name]; !ok {
907 ctx.errorf(directive, "define is not supported: %s", macro_name)
908 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800909}
910
911func (ctx *parseContext) handleIfBlock(ifDirective *mkparser.Directive) {
912 ssSwitch := &switchNode{}
913 ctx.pushReceiver(ssSwitch)
914 for ctx.processBranch(ifDirective); ctx.hasNodes() && ctx.fatalError == nil; {
915 node := ctx.getNode()
916 switch x := node.(type) {
917 case *mkparser.Directive:
918 switch x.Name {
919 case "else", "elifdef", "elifndef", "elifeq", "elifneq":
920 ctx.processBranch(x)
921 case "endif":
922 ctx.popReceiver()
923 ctx.receiver.newNode(ssSwitch)
924 return
925 default:
926 ctx.errorf(node, "unexpected directive %s", x.Name)
927 }
928 default:
929 ctx.errorf(ifDirective, "unexpected statement")
930 }
931 }
932 if ctx.fatalError == nil {
933 ctx.fatalError = fmt.Errorf("no matching endif for %s", ifDirective.Dump())
934 }
935 ctx.popReceiver()
936}
937
938// processBranch processes a single branch (if/elseif/else) until the next directive
939// on the same level.
940func (ctx *parseContext) processBranch(check *mkparser.Directive) {
941 block := switchCase{gate: ctx.parseCondition(check)}
942 defer func() {
943 ctx.popVarAssignments()
944 ctx.ifNestLevel--
945
946 }()
947 ctx.pushVarAssignments()
948 ctx.ifNestLevel++
949
950 ctx.pushReceiver(&block)
951 for ctx.hasNodes() {
952 node := ctx.getNode()
953 if ctx.handleSimpleStatement(node) {
954 continue
955 }
956 switch d := node.(type) {
957 case *mkparser.Directive:
958 switch d.Name {
959 case "else", "elifdef", "elifndef", "elifeq", "elifneq", "endif":
960 ctx.popReceiver()
961 ctx.receiver.newNode(&block)
962 ctx.backNode()
963 return
964 case "ifdef", "ifndef", "ifeq", "ifneq":
965 ctx.handleIfBlock(d)
966 default:
967 ctx.errorf(d, "unexpected directive %s", d.Name)
968 }
969 default:
970 ctx.errorf(node, "unexpected statement")
971 }
972 }
973 ctx.fatalError = fmt.Errorf("no matching endif for %s", check.Dump())
974 ctx.popReceiver()
975}
976
977func (ctx *parseContext) newIfDefinedNode(check *mkparser.Directive) (starlarkExpr, bool) {
978 if !check.Args.Const() {
979 return ctx.newBadExpr(check, "ifdef variable ref too complex: %s", check.Args.Dump()), false
980 }
981 v := ctx.addVariable(check.Args.Strings[0])
982 return &variableDefinedExpr{v}, true
983}
984
985func (ctx *parseContext) parseCondition(check *mkparser.Directive) starlarkNode {
986 switch check.Name {
987 case "ifdef", "ifndef", "elifdef", "elifndef":
988 v, ok := ctx.newIfDefinedNode(check)
989 if ok && strings.HasSuffix(check.Name, "ndef") {
990 v = &notExpr{v}
991 }
992 return &ifNode{
993 isElif: strings.HasPrefix(check.Name, "elif"),
994 expr: v,
995 }
996 case "ifeq", "ifneq", "elifeq", "elifneq":
997 return &ifNode{
998 isElif: strings.HasPrefix(check.Name, "elif"),
999 expr: ctx.parseCompare(check),
1000 }
1001 case "else":
1002 return &elseNode{}
1003 default:
1004 panic(fmt.Errorf("%s: unknown directive: %s", ctx.script.mkFile, check.Dump()))
1005 }
1006}
1007
1008func (ctx *parseContext) newBadExpr(node mkparser.Node, text string, args ...interface{}) starlarkExpr {
1009 message := fmt.Sprintf(text, args...)
1010 if ctx.errorLogger != nil {
1011 ctx.errorLogger.NewError(text, node, args)
1012 }
1013 ctx.script.hasErrors = true
1014 return &badExpr{node, message}
1015}
1016
1017func (ctx *parseContext) parseCompare(cond *mkparser.Directive) starlarkExpr {
1018 // Strip outer parentheses
1019 mkArg := cloneMakeString(cond.Args)
1020 mkArg.Strings[0] = strings.TrimLeft(mkArg.Strings[0], "( ")
1021 n := len(mkArg.Strings)
1022 mkArg.Strings[n-1] = strings.TrimRight(mkArg.Strings[n-1], ") ")
1023 args := mkArg.Split(",")
1024 // TODO(asmundak): handle the case where the arguments are in quotes and space-separated
1025 if len(args) != 2 {
1026 return ctx.newBadExpr(cond, "ifeq/ifneq len(args) != 2 %s", cond.Dump())
1027 }
1028 args[0].TrimRightSpaces()
1029 args[1].TrimLeftSpaces()
1030
1031 isEq := !strings.HasSuffix(cond.Name, "neq")
1032 switch xLeft := ctx.parseMakeString(cond, args[0]).(type) {
1033 case *stringLiteralExpr, *variableRefExpr:
1034 switch xRight := ctx.parseMakeString(cond, args[1]).(type) {
1035 case *stringLiteralExpr, *variableRefExpr:
1036 return &eqExpr{left: xLeft, right: xRight, isEq: isEq}
1037 case *badExpr:
1038 return xRight
1039 default:
1040 expr, ok := ctx.parseCheckFunctionCallResult(cond, xLeft, args[1])
1041 if ok {
1042 return expr
1043 }
1044 return ctx.newBadExpr(cond, "right operand is too complex: %s", args[1].Dump())
1045 }
1046 case *badExpr:
1047 return xLeft
1048 default:
1049 switch xRight := ctx.parseMakeString(cond, args[1]).(type) {
1050 case *stringLiteralExpr, *variableRefExpr:
1051 expr, ok := ctx.parseCheckFunctionCallResult(cond, xRight, args[0])
1052 if ok {
1053 return expr
1054 }
1055 return ctx.newBadExpr(cond, "left operand is too complex: %s", args[0].Dump())
1056 case *badExpr:
1057 return xRight
1058 default:
1059 return ctx.newBadExpr(cond, "operands are too complex: (%s,%s)", args[0].Dump(), args[1].Dump())
1060 }
1061 }
1062}
1063
1064func (ctx *parseContext) parseCheckFunctionCallResult(directive *mkparser.Directive, xValue starlarkExpr,
1065 varArg *mkparser.MakeString) (starlarkExpr, bool) {
1066 mkSingleVar, ok := varArg.SingleVariable()
1067 if !ok {
1068 return nil, false
1069 }
1070 expr := ctx.parseReference(directive, mkSingleVar)
1071 negate := strings.HasSuffix(directive.Name, "neq")
1072 checkIsSomethingFunction := func(xCall *callExpr) starlarkExpr {
1073 s, ok := maybeString(xValue)
1074 if !ok || s != "true" {
1075 return ctx.newBadExpr(directive,
1076 fmt.Sprintf("the result of %s can be compared only to 'true'", xCall.name))
1077 }
1078 if len(xCall.args) < 1 {
1079 return ctx.newBadExpr(directive, "%s requires an argument", xCall.name)
1080 }
1081 return nil
1082 }
1083 switch x := expr.(type) {
1084 case *callExpr:
1085 switch x.name {
1086 case "filter":
1087 return ctx.parseCompareFilterFuncResult(directive, x, xValue, !negate), true
1088 case "filter-out":
1089 return ctx.parseCompareFilterFuncResult(directive, x, xValue, negate), true
1090 case "wildcard":
1091 return ctx.parseCompareWildcardFuncResult(directive, x, xValue, negate), true
1092 case "findstring":
1093 return ctx.parseCheckFindstringFuncResult(directive, x, xValue, negate), true
1094 case "strip":
1095 return ctx.parseCompareStripFuncResult(directive, x, xValue, negate), true
1096 case "is-board-platform":
1097 if xBad := checkIsSomethingFunction(x); xBad != nil {
1098 return xBad, true
1099 }
1100 return &eqExpr{
1101 left: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
1102 right: x.args[0],
1103 isEq: !negate,
1104 }, true
1105 case "is-board-platform-in-list":
1106 if xBad := checkIsSomethingFunction(x); xBad != nil {
1107 return xBad, true
1108 }
1109 return &inExpr{
1110 expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
1111 list: maybeConvertToStringList(x.args[0]),
1112 isNot: negate,
1113 }, true
1114 case "is-product-in-list":
1115 if xBad := checkIsSomethingFunction(x); xBad != nil {
1116 return xBad, true
1117 }
1118 return &inExpr{
1119 expr: &variableRefExpr{ctx.addVariable("TARGET_PRODUCT"), true},
1120 list: maybeConvertToStringList(x.args[0]),
1121 isNot: negate,
1122 }, true
1123 case "is-vendor-board-platform":
1124 if xBad := checkIsSomethingFunction(x); xBad != nil {
1125 return xBad, true
1126 }
1127 s, ok := maybeString(x.args[0])
1128 if !ok {
1129 return ctx.newBadExpr(directive, "cannot handle non-constant argument to is-vendor-board-platform"), true
1130 }
1131 return &inExpr{
1132 expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
1133 list: &variableRefExpr{ctx.addVariable(s + "_BOARD_PLATFORMS"), true},
1134 isNot: negate,
1135 }, true
1136 default:
1137 return ctx.newBadExpr(directive, "Unknown function in ifeq: %s", x.name), true
1138 }
1139 case *badExpr:
1140 return x, true
1141 default:
1142 return nil, false
1143 }
1144}
1145
1146func (ctx *parseContext) parseCompareFilterFuncResult(cond *mkparser.Directive,
1147 filterFuncCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
1148 // We handle:
Sasha Smundak0554d762021-07-08 18:26:12 -07001149 // * ifeq/ifneq (,$(filter v1 v2 ..., EXPR) becomes if EXPR not in/in ["v1", "v2", ...]
1150 // * ifeq/ifneq (,$(filter EXPR, v1 v2 ...) becomes if EXPR not in/in ["v1", "v2", ...]
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001151 // * ifeq/ifneq ($(VAR),$(filter $(VAR), v1 v2 ...) becomes if VAR in/not in ["v1", "v2"]
1152 // TODO(Asmundak): check the last case works for filter-out, too.
1153 xPattern := filterFuncCall.args[0]
1154 xText := filterFuncCall.args[1]
1155 var xInList *stringLiteralExpr
Sasha Smundak0554d762021-07-08 18:26:12 -07001156 var expr starlarkExpr
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001157 var ok bool
1158 switch x := xValue.(type) {
1159 case *stringLiteralExpr:
1160 if x.literal != "" {
1161 return ctx.newBadExpr(cond, "filter comparison to non-empty value: %s", xValue)
1162 }
1163 // Either pattern or text should be const, and the
1164 // non-const one should be varRefExpr
1165 if xInList, ok = xPattern.(*stringLiteralExpr); ok {
Sasha Smundak0554d762021-07-08 18:26:12 -07001166 expr = xText
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001167 } else if xInList, ok = xText.(*stringLiteralExpr); ok {
Sasha Smundak0554d762021-07-08 18:26:12 -07001168 expr = xPattern
1169 } else {
1170 return &callExpr{
1171 object: nil,
1172 name: filterFuncCall.name,
1173 args: filterFuncCall.args,
1174 returnType: starlarkTypeBool,
1175 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001176 }
1177 case *variableRefExpr:
1178 if v, ok := xPattern.(*variableRefExpr); ok {
1179 if xInList, ok = xText.(*stringLiteralExpr); ok && v.ref.name() == x.ref.name() {
1180 // ifeq/ifneq ($(VAR),$(filter $(VAR), v1 v2 ...), flip negate,
1181 // it's the opposite to what is done when comparing to empty.
Sasha Smundak0554d762021-07-08 18:26:12 -07001182 expr = xPattern
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001183 negate = !negate
1184 }
1185 }
1186 }
Sasha Smundak0554d762021-07-08 18:26:12 -07001187 if expr != nil && xInList != nil {
1188 slExpr := newStringListExpr(strings.Fields(xInList.literal))
1189 // Generate simpler code for the common cases:
1190 if expr.typ() == starlarkTypeList {
1191 if len(slExpr.items) == 1 {
1192 // Checking that a string belongs to list
1193 return &inExpr{isNot: negate, list: expr, expr: slExpr.items[0]}
1194 } else {
1195 // TODO(asmundak):
1196 panic("TBD")
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001197 }
Sasha Smundak0554d762021-07-08 18:26:12 -07001198 } else if len(slExpr.items) == 1 {
1199 return &eqExpr{left: expr, right: slExpr.items[0], isEq: !negate}
1200 } else {
1201 return &inExpr{isNot: negate, list: newStringListExpr(strings.Fields(xInList.literal)), expr: expr}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001202 }
1203 }
1204 return ctx.newBadExpr(cond, "filter arguments are too complex: %s", cond.Dump())
1205}
1206
1207func (ctx *parseContext) parseCompareWildcardFuncResult(directive *mkparser.Directive,
1208 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001209 if !isEmptyString(xValue) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001210 return ctx.newBadExpr(directive, "wildcard result can be compared only to empty: %s", xValue)
1211 }
1212 callFunc := wildcardExistsPhony
1213 if s, ok := xCall.args[0].(*stringLiteralExpr); ok && !strings.ContainsAny(s.literal, "*?{[") {
1214 callFunc = fileExistsPhony
1215 }
1216 var cc starlarkExpr = &callExpr{name: callFunc, args: xCall.args, returnType: starlarkTypeBool}
1217 if !negate {
1218 cc = &notExpr{cc}
1219 }
1220 return cc
1221}
1222
1223func (ctx *parseContext) parseCheckFindstringFuncResult(directive *mkparser.Directive,
1224 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001225 if isEmptyString(xValue) {
1226 return &eqExpr{
1227 left: &callExpr{
1228 object: xCall.args[1],
1229 name: "find",
1230 args: []starlarkExpr{xCall.args[0]},
1231 returnType: starlarkTypeInt,
1232 },
1233 right: &intLiteralExpr{-1},
1234 isEq: !negate,
1235 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001236 }
Sasha Smundak0554d762021-07-08 18:26:12 -07001237 return ctx.newBadExpr(directive, "findstring result can be compared only to empty: %s", xValue)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001238}
1239
1240func (ctx *parseContext) parseCompareStripFuncResult(directive *mkparser.Directive,
1241 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
1242 if _, ok := xValue.(*stringLiteralExpr); !ok {
1243 return ctx.newBadExpr(directive, "strip result can be compared only to string: %s", xValue)
1244 }
1245 return &eqExpr{
1246 left: &callExpr{
1247 name: "strip",
1248 args: xCall.args,
1249 returnType: starlarkTypeString,
1250 },
1251 right: xValue, isEq: !negate}
1252}
1253
1254// parses $(...), returning an expression
1255func (ctx *parseContext) parseReference(node mkparser.Node, ref *mkparser.MakeString) starlarkExpr {
1256 ref.TrimLeftSpaces()
1257 ref.TrimRightSpaces()
1258 refDump := ref.Dump()
1259
1260 // Handle only the case where the first (or only) word is constant
1261 words := ref.SplitN(" ", 2)
1262 if !words[0].Const() {
1263 return ctx.newBadExpr(node, "reference is too complex: %s", refDump)
1264 }
1265
1266 // If it is a single word, it can be a simple variable
1267 // reference or a function call
1268 if len(words) == 1 {
1269 if isMakeControlFunc(refDump) || refDump == "shell" {
1270 return &callExpr{
1271 name: refDump,
1272 args: []starlarkExpr{&stringLiteralExpr{""}},
1273 returnType: starlarkTypeUnknown,
1274 }
1275 }
1276 if v := ctx.addVariable(refDump); v != nil {
1277 return &variableRefExpr{v, ctx.lastAssignment(v.name()) != nil}
1278 }
1279 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1280 }
1281
1282 expr := &callExpr{name: words[0].Dump(), returnType: starlarkTypeUnknown}
1283 args := words[1]
1284 args.TrimLeftSpaces()
1285 // Make control functions and shell need special treatment as everything
1286 // after the name is a single text argument
1287 if isMakeControlFunc(expr.name) || expr.name == "shell" {
1288 x := ctx.parseMakeString(node, args)
1289 if xBad, ok := x.(*badExpr); ok {
1290 return xBad
1291 }
1292 expr.args = []starlarkExpr{x}
1293 return expr
1294 }
1295 if expr.name == "call" {
1296 words = args.SplitN(",", 2)
1297 if words[0].Empty() || !words[0].Const() {
Sasha Smundakf2c9f8b2021-07-27 10:44:48 -07001298 return ctx.newBadExpr(node, "cannot handle %s", refDump)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001299 }
1300 expr.name = words[0].Dump()
1301 if len(words) < 2 {
Sasha Smundak6609ba72021-07-22 18:32:56 -07001302 args = &mkparser.MakeString{}
1303 } else {
1304 args = words[1]
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001305 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001306 }
1307 if kf, found := knownFunctions[expr.name]; found {
1308 expr.returnType = kf.returnType
1309 } else {
1310 return ctx.newBadExpr(node, "cannot handle invoking %s", expr.name)
1311 }
1312 switch expr.name {
1313 case "word":
1314 return ctx.parseWordFunc(node, args)
Sasha Smundak16e07732021-07-23 11:38:23 -07001315 case "firstword", "lastword":
1316 return ctx.parseFirstOrLastwordFunc(node, expr.name, args)
Sasha Smundak6609ba72021-07-22 18:32:56 -07001317 case "my-dir":
1318 return &variableRefExpr{ctx.addVariable("LOCAL_PATH"), true}
Sasha Smundak94b41c72021-07-12 18:30:42 -07001319 case "subst", "patsubst":
1320 return ctx.parseSubstFunc(node, expr.name, args)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001321 default:
1322 for _, arg := range args.Split(",") {
1323 arg.TrimLeftSpaces()
1324 arg.TrimRightSpaces()
1325 x := ctx.parseMakeString(node, arg)
1326 if xBad, ok := x.(*badExpr); ok {
1327 return xBad
1328 }
1329 expr.args = append(expr.args, x)
1330 }
1331 }
1332 return expr
1333}
1334
Sasha Smundak94b41c72021-07-12 18:30:42 -07001335func (ctx *parseContext) parseSubstFunc(node mkparser.Node, fname string, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001336 words := args.Split(",")
1337 if len(words) != 3 {
Sasha Smundak94b41c72021-07-12 18:30:42 -07001338 return ctx.newBadExpr(node, "%s function should have 3 arguments", fname)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001339 }
1340 if !words[0].Const() || !words[1].Const() {
Sasha Smundak94b41c72021-07-12 18:30:42 -07001341 return ctx.newBadExpr(node, "%s function's from and to arguments should be constant", fname)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001342 }
1343 from := words[0].Strings[0]
1344 to := words[1].Strings[0]
1345 words[2].TrimLeftSpaces()
1346 words[2].TrimRightSpaces()
1347 obj := ctx.parseMakeString(node, words[2])
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001348 typ := obj.typ()
Sasha Smundak94b41c72021-07-12 18:30:42 -07001349 if typ == starlarkTypeString && fname == "subst" {
1350 // Optimization: if it's $(subst from, to, string), emit string.replace(from, to)
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001351 return &callExpr{
1352 object: obj,
1353 name: "replace",
1354 args: []starlarkExpr{&stringLiteralExpr{from}, &stringLiteralExpr{to}},
1355 returnType: typ,
1356 }
1357 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001358 return &callExpr{
Sasha Smundak94b41c72021-07-12 18:30:42 -07001359 name: fname,
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001360 args: []starlarkExpr{&stringLiteralExpr{from}, &stringLiteralExpr{to}, obj},
1361 returnType: obj.typ(),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001362 }
1363}
1364
1365func (ctx *parseContext) parseWordFunc(node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1366 words := args.Split(",")
1367 if len(words) != 2 {
1368 return ctx.newBadExpr(node, "word function should have 2 arguments")
1369 }
1370 var index uint64 = 0
1371 if words[0].Const() {
1372 index, _ = strconv.ParseUint(strings.TrimSpace(words[0].Strings[0]), 10, 64)
1373 }
1374 if index < 1 {
1375 return ctx.newBadExpr(node, "word index should be constant positive integer")
1376 }
1377 words[1].TrimLeftSpaces()
1378 words[1].TrimRightSpaces()
1379 array := ctx.parseMakeString(node, words[1])
1380 if xBad, ok := array.(*badExpr); ok {
1381 return xBad
1382 }
1383 if array.typ() != starlarkTypeList {
1384 array = &callExpr{object: array, name: "split", returnType: starlarkTypeList}
1385 }
1386 return indexExpr{array, &intLiteralExpr{int(index - 1)}}
1387}
1388
Sasha Smundak16e07732021-07-23 11:38:23 -07001389func (ctx *parseContext) parseFirstOrLastwordFunc(node mkparser.Node, name string, args *mkparser.MakeString) starlarkExpr {
1390 arg := ctx.parseMakeString(node, args)
1391 if bad, ok := arg.(*badExpr); ok {
1392 return bad
1393 }
1394 index := &intLiteralExpr{0}
1395 if name == "lastword" {
1396 if v, ok := arg.(*variableRefExpr); ok && v.ref.name() == "MAKEFILE_LIST" {
1397 return &stringLiteralExpr{ctx.script.mkFile}
1398 }
1399 index.literal = -1
1400 }
1401 if arg.typ() == starlarkTypeList {
1402 return &indexExpr{arg, index}
1403 }
1404 return &indexExpr{&callExpr{object: arg, name: "split", returnType: starlarkTypeList}, index}
1405}
1406
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001407func (ctx *parseContext) parseMakeString(node mkparser.Node, mk *mkparser.MakeString) starlarkExpr {
1408 if mk.Const() {
1409 return &stringLiteralExpr{mk.Dump()}
1410 }
1411 if mkRef, ok := mk.SingleVariable(); ok {
1412 return ctx.parseReference(node, mkRef)
1413 }
1414 // If we reached here, it's neither string literal nor a simple variable,
1415 // we need a full-blown interpolation node that will generate
1416 // "a%b%c" % (X, Y) for a$(X)b$(Y)c
1417 xInterp := &interpolateExpr{args: make([]starlarkExpr, len(mk.Variables))}
1418 for i, ref := range mk.Variables {
1419 arg := ctx.parseReference(node, ref.Name)
1420 if x, ok := arg.(*badExpr); ok {
1421 return x
1422 }
1423 xInterp.args[i] = arg
1424 }
1425 xInterp.chunks = append(xInterp.chunks, mk.Strings...)
1426 return xInterp
1427}
1428
1429// Handles the statements whose treatment is the same in all contexts: comment,
1430// assignment, variable (which is a macro call in reality) and all constructs that
1431// do not handle in any context ('define directive and any unrecognized stuff).
1432// Return true if we handled it.
1433func (ctx *parseContext) handleSimpleStatement(node mkparser.Node) bool {
1434 handled := true
1435 switch x := node.(type) {
1436 case *mkparser.Comment:
1437 ctx.insertComment("#" + x.Comment)
1438 case *mkparser.Assignment:
1439 ctx.handleAssignment(x)
1440 case *mkparser.Variable:
1441 ctx.handleVariable(x)
1442 case *mkparser.Directive:
1443 switch x.Name {
1444 case "define":
1445 ctx.handleDefine(x)
1446 case "include", "-include":
1447 ctx.handleInclude(node, ctx.parseMakeString(node, x.Args), x.Name[0] != '-')
1448 default:
1449 handled = false
1450 }
1451 default:
1452 ctx.errorf(x, "unsupported line %s", x.Dump())
1453 }
1454 return handled
1455}
1456
1457func (ctx *parseContext) insertComment(s string) {
1458 ctx.receiver.newNode(&commentNode{strings.TrimSpace(s)})
1459}
1460
1461func (ctx *parseContext) carryAsComment(failedNode mkparser.Node) {
1462 for _, line := range strings.Split(failedNode.Dump(), "\n") {
1463 ctx.insertComment("# " + line)
1464 }
1465}
1466
1467// records that the given node failed to be converted and includes an explanatory message
1468func (ctx *parseContext) errorf(failedNode mkparser.Node, message string, args ...interface{}) {
1469 if ctx.errorLogger != nil {
1470 ctx.errorLogger.NewError(message, failedNode, args...)
1471 }
1472 message = fmt.Sprintf(message, args...)
1473 ctx.insertComment(fmt.Sprintf("# MK2RBC TRANSLATION ERROR: %s", message))
1474 ctx.carryAsComment(failedNode)
1475 ctx.script.hasErrors = true
1476}
1477
1478func (ctx *parseContext) wrapBadExpr(xBad *badExpr) {
1479 ctx.insertComment(fmt.Sprintf("# MK2RBC TRANSLATION ERROR: %s", xBad.message))
1480 ctx.carryAsComment(xBad.node)
1481}
1482
1483func (ctx *parseContext) loadedModulePath(path string) string {
1484 // During the transition to Roboleaf some of the product configuration files
1485 // will be converted and checked in while the others will be generated on the fly
1486 // and run. The runner (rbcrun application) accommodates this by allowing three
1487 // different ways to specify the loaded file location:
1488 // 1) load(":<file>",...) loads <file> from the same directory
1489 // 2) load("//path/relative/to/source/root:<file>", ...) loads <file> source tree
1490 // 3) load("/absolute/path/to/<file> absolute path
1491 // If the file being generated and the file it wants to load are in the same directory,
1492 // generate option 1.
1493 // Otherwise, if output directory is not specified, generate 2)
1494 // Finally, if output directory has been specified and the file being generated and
1495 // the file it wants to load from are in the different directories, generate 2) or 3):
1496 // * if the file being loaded exists in the source tree, generate 2)
1497 // * otherwise, generate 3)
1498 // Finally, figure out the loaded module path and name and create a node for it
1499 loadedModuleDir := filepath.Dir(path)
1500 base := filepath.Base(path)
1501 loadedModuleName := strings.TrimSuffix(base, filepath.Ext(base)) + ctx.outputSuffix
1502 if loadedModuleDir == filepath.Dir(ctx.script.mkFile) {
1503 return ":" + loadedModuleName
1504 }
1505 if ctx.outputDir == "" {
1506 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1507 }
1508 if _, err := os.Stat(filepath.Join(loadedModuleDir, loadedModuleName)); err == nil {
1509 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1510 }
1511 return filepath.Join(ctx.outputDir, loadedModuleDir, loadedModuleName)
1512}
1513
Sasha Smundak3deb9682021-07-26 18:42:25 -07001514func (ctx *parseContext) addSoongNamespace(ns string) {
1515 if _, ok := ctx.soongNamespaces[ns]; ok {
1516 return
1517 }
1518 ctx.soongNamespaces[ns] = make(map[string]bool)
1519}
1520
1521func (ctx *parseContext) hasSoongNamespace(name string) bool {
1522 _, ok := ctx.soongNamespaces[name]
1523 return ok
1524}
1525
1526func (ctx *parseContext) updateSoongNamespace(replace bool, namespaceName string, varNames []string) {
1527 ctx.addSoongNamespace(namespaceName)
1528 vars := ctx.soongNamespaces[namespaceName]
1529 if replace {
1530 vars = make(map[string]bool)
1531 ctx.soongNamespaces[namespaceName] = vars
1532 }
1533 for _, v := range varNames {
1534 vars[v] = true
1535 }
1536}
1537
1538func (ctx *parseContext) hasNamespaceVar(namespaceName string, varName string) bool {
1539 vars, ok := ctx.soongNamespaces[namespaceName]
1540 if ok {
1541 _, ok = vars[varName]
1542 }
1543 return ok
1544}
1545
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001546func (ss *StarlarkScript) String() string {
1547 return NewGenerateContext(ss).emit()
1548}
1549
1550func (ss *StarlarkScript) SubConfigFiles() []string {
Sasha Smundak6609ba72021-07-22 18:32:56 -07001551
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001552 var subs []string
1553 for _, src := range ss.inherited {
1554 subs = append(subs, src.originalPath)
1555 }
1556 return subs
1557}
1558
1559func (ss *StarlarkScript) HasErrors() bool {
1560 return ss.hasErrors
1561}
1562
1563// Convert reads and parses a makefile. If successful, parsed tree
1564// is returned and then can be passed to String() to get the generated
1565// Starlark file.
1566func Convert(req Request) (*StarlarkScript, error) {
1567 reader := req.Reader
1568 if reader == nil {
1569 mkContents, err := ioutil.ReadFile(req.MkFile)
1570 if err != nil {
1571 return nil, err
1572 }
1573 reader = bytes.NewBuffer(mkContents)
1574 }
1575 parser := mkparser.NewParser(req.MkFile, reader)
1576 nodes, errs := parser.Parse()
1577 if len(errs) > 0 {
1578 for _, e := range errs {
1579 fmt.Fprintln(os.Stderr, "ERROR:", e)
1580 }
1581 return nil, fmt.Errorf("bad makefile %s", req.MkFile)
1582 }
1583 starScript := &StarlarkScript{
1584 moduleName: moduleNameForFile(req.MkFile),
1585 mkFile: req.MkFile,
1586 topDir: req.RootDir,
1587 traceCalls: req.TraceCalls,
1588 warnPartialSuccess: req.WarnPartialSuccess,
Sasha Smundak6609ba72021-07-22 18:32:56 -07001589 sourceFS: req.SourceFS,
1590 makefileFinder: req.MakefileFinder,
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001591 }
1592 ctx := newParseContext(starScript, nodes)
1593 ctx.outputSuffix = req.OutputSuffix
1594 ctx.outputDir = req.OutputDir
1595 ctx.errorLogger = req.ErrorLogger
1596 if len(req.TracedVariables) > 0 {
1597 ctx.tracedVariables = make(map[string]bool)
1598 for _, v := range req.TracedVariables {
1599 ctx.tracedVariables[v] = true
1600 }
1601 }
1602 ctx.pushReceiver(starScript)
1603 for ctx.hasNodes() && ctx.fatalError == nil {
1604 node := ctx.getNode()
1605 if ctx.handleSimpleStatement(node) {
1606 continue
1607 }
1608 switch x := node.(type) {
1609 case *mkparser.Directive:
1610 switch x.Name {
1611 case "ifeq", "ifneq", "ifdef", "ifndef":
1612 ctx.handleIfBlock(x)
1613 default:
1614 ctx.errorf(x, "unexpected directive %s", x.Name)
1615 }
1616 default:
1617 ctx.errorf(x, "unsupported line")
1618 }
1619 }
1620 if ctx.fatalError != nil {
1621 return nil, ctx.fatalError
1622 }
1623 return starScript, nil
1624}
1625
Sasha Smundakd7d07ad2021-09-10 15:42:34 -07001626func Launcher(mainModuleUri, versionDefaultsUri, mainModuleName string) string {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001627 var buf bytes.Buffer
1628 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
Sasha Smundakd7d07ad2021-09-10 15:42:34 -07001629 fmt.Fprintf(&buf, "load(%q, \"version_defaults\")\n", versionDefaultsUri)
1630 fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri)
1631 fmt.Fprintf(&buf, "%s(%s(%q, init, version_defaults))\n", cfnPrintVars, cfnMain, mainModuleName)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001632 return buf.String()
1633}
1634
1635func MakePath2ModuleName(mkPath string) string {
1636 return strings.TrimSuffix(mkPath, filepath.Ext(mkPath))
1637}