blob: 7ceac41b5df511435d25d530fbd6e5e28170d5a7 [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},
121 "produce_copy_files": {baseName + ".produce_copy_files", starlarkTypeList, hiddenArgNone},
122 "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"},
422 {"TARGET_COPY_OUT_VENDOR", "||VENDOR-PATH-PH||"},
423 {"TARGET_COPY_OUT_VENDOR_RAMDISK", "vendor_ramdisk"},
424 {"TARGET_COPY_OUT_PRODUCT", "||PRODUCT-PATH-PH||"},
425 {"TARGET_COPY_OUT_PRODUCT_SERVICES", "||PRODUCT-PATH-PH||"},
426 {"TARGET_COPY_OUT_SYSTEM_EXT", "||SYSTEM_EXT-PATH-PH||"},
427 {"TARGET_COPY_OUT_ODM", "||ODM-PATH-PH||"},
428 {"TARGET_COPY_OUT_VENDOR_DLKM", "||VENDOR_DLKM-PATH-PH||"},
429 {"TARGET_COPY_OUT_ODM_DLKM", "||ODM_DLKM-PATH-PH||"},
430 // TODO(asmundak): to process internal config files, we need the following variables:
431 // BOARD_CONFIG_VENDOR_PATH
432 // TARGET_VENDOR
433 // target_base_product
434 //
435
436 // the following utility variables are set in build/make/common/core.mk:
437 {"empty", ""},
438 {"space", " "},
439 {"comma", ","},
440 {"newline", "\n"},
441 {"pound", "#"},
442 {"backslash", "\\"},
443 }
444 ctx := &parseContext{
445 script: ss,
446 nodes: nodes,
447 currentNodeIndex: 0,
448 ifNestLevel: 0,
449 moduleNameCount: make(map[string]int),
450 builtinMakeVars: map[string]starlarkExpr{},
451 variables: make(map[string]variable),
Sasha Smundak6609ba72021-07-22 18:32:56 -0700452 dependentModules: make(map[string]*moduleInfo),
Sasha Smundak3deb9682021-07-26 18:42:25 -0700453 soongNamespaces: make(map[string]map[string]bool),
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800454 }
455 ctx.pushVarAssignments()
456 for _, item := range predefined {
457 ctx.variables[item.name] = &predefinedVariable{
458 baseVariable: baseVariable{nam: item.name, typ: starlarkTypeString},
459 value: &stringLiteralExpr{item.value},
460 }
461 }
462
463 return ctx
464}
465
466func (ctx *parseContext) lastAssignment(name string) *assignmentNode {
467 for va := ctx.varAssignments; va != nil; va = va.outer {
468 if v, ok := va.vars[name]; ok {
469 return v
470 }
471 }
472 return nil
473}
474
475func (ctx *parseContext) setLastAssignment(name string, asgn *assignmentNode) {
476 ctx.varAssignments.vars[name] = asgn
477}
478
479func (ctx *parseContext) pushVarAssignments() {
480 va := &varAssignmentScope{
481 outer: ctx.varAssignments,
482 vars: make(map[string]*assignmentNode),
483 }
484 ctx.varAssignments = va
485}
486
487func (ctx *parseContext) popVarAssignments() {
488 ctx.varAssignments = ctx.varAssignments.outer
489}
490
491func (ctx *parseContext) pushReceiver(rcv nodeReceiver) {
492 ctx.receiverStack = append(ctx.receiverStack, ctx.receiver)
493 ctx.receiver = rcv
494}
495
496func (ctx *parseContext) popReceiver() {
497 last := len(ctx.receiverStack) - 1
498 if last < 0 {
499 panic(fmt.Errorf("popReceiver: receiver stack empty"))
500 }
501 ctx.receiver = ctx.receiverStack[last]
502 ctx.receiverStack = ctx.receiverStack[0:last]
503}
504
505func (ctx *parseContext) hasNodes() bool {
506 return ctx.currentNodeIndex < len(ctx.nodes)
507}
508
509func (ctx *parseContext) getNode() mkparser.Node {
510 if !ctx.hasNodes() {
511 return nil
512 }
513 node := ctx.nodes[ctx.currentNodeIndex]
514 ctx.currentNodeIndex++
515 return node
516}
517
518func (ctx *parseContext) backNode() {
519 if ctx.currentNodeIndex <= 0 {
520 panic("Cannot back off")
521 }
522 ctx.currentNodeIndex--
523}
524
525func (ctx *parseContext) handleAssignment(a *mkparser.Assignment) {
526 // Handle only simple variables
527 if !a.Name.Const() {
528 ctx.errorf(a, "Only simple variables are handled")
529 return
530 }
531 name := a.Name.Strings[0]
Sasha Smundak3deb9682021-07-26 18:42:25 -0700532 const soongNsPrefix = "SOONG_CONFIG_"
533 // Soong confuguration
534 if strings.HasPrefix(name, soongNsPrefix) {
535 ctx.handleSoongNsAssignment(strings.TrimPrefix(name, soongNsPrefix), a)
536 return
537 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800538 lhs := ctx.addVariable(name)
539 if lhs == nil {
540 ctx.errorf(a, "unknown variable %s", name)
541 return
542 }
543 _, isTraced := ctx.tracedVariables[name]
544 asgn := &assignmentNode{lhs: lhs, mkValue: a.Value, isTraced: isTraced}
545 if lhs.valueType() == starlarkTypeUnknown {
546 // Try to divine variable type from the RHS
547 asgn.value = ctx.parseMakeString(a, a.Value)
548 if xBad, ok := asgn.value.(*badExpr); ok {
549 ctx.wrapBadExpr(xBad)
550 return
551 }
552 inferred_type := asgn.value.typ()
553 if inferred_type != starlarkTypeUnknown {
Sasha Smundak9d011ab2021-07-09 16:00:57 -0700554 lhs.setValueType(inferred_type)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800555 }
556 }
557 if lhs.valueType() == starlarkTypeList {
558 xConcat := ctx.buildConcatExpr(a)
559 if xConcat == nil {
560 return
561 }
562 switch len(xConcat.items) {
563 case 0:
564 asgn.value = &listExpr{}
565 case 1:
566 asgn.value = xConcat.items[0]
567 default:
568 asgn.value = xConcat
569 }
570 } else {
571 asgn.value = ctx.parseMakeString(a, a.Value)
572 if xBad, ok := asgn.value.(*badExpr); ok {
573 ctx.wrapBadExpr(xBad)
574 return
575 }
576 }
577
578 // TODO(asmundak): move evaluation to a separate pass
579 asgn.value, _ = asgn.value.eval(ctx.builtinMakeVars)
580
581 asgn.previous = ctx.lastAssignment(name)
582 ctx.setLastAssignment(name, asgn)
583 switch a.Type {
584 case "=", ":=":
585 asgn.flavor = asgnSet
586 case "+=":
587 if asgn.previous == nil && !asgn.lhs.isPreset() {
588 asgn.flavor = asgnMaybeAppend
589 } else {
590 asgn.flavor = asgnAppend
591 }
592 case "?=":
593 asgn.flavor = asgnMaybeSet
594 default:
595 panic(fmt.Errorf("unexpected assignment type %s", a.Type))
596 }
597
598 ctx.receiver.newNode(asgn)
599}
600
Sasha Smundak3deb9682021-07-26 18:42:25 -0700601func (ctx *parseContext) handleSoongNsAssignment(name string, asgn *mkparser.Assignment) {
602 val := ctx.parseMakeString(asgn, asgn.Value)
603 if xBad, ok := val.(*badExpr); ok {
604 ctx.wrapBadExpr(xBad)
605 return
606 }
607 val, _ = val.eval(ctx.builtinMakeVars)
608
609 // Unfortunately, Soong namespaces can be set up by directly setting corresponding Make
610 // variables instead of via add_soong_config_namespace + add_soong_config_var_value.
611 // Try to divine the call from the assignment as follows:
612 if name == "NAMESPACES" {
613 // Upon seeng
614 // SOONG_CONFIG_NAMESPACES += foo
615 // remember that there is a namespace `foo` and act as we saw
616 // $(call add_soong_config_namespace,foo)
617 s, ok := maybeString(val)
618 if !ok {
619 ctx.errorf(asgn, "cannot handle variables in SOONG_CONFIG_NAMESPACES assignment, please use add_soong_config_namespace instead")
620 return
621 }
622 for _, ns := range strings.Fields(s) {
623 ctx.addSoongNamespace(ns)
624 ctx.receiver.newNode(&exprNode{&callExpr{
625 name: addSoongNamespace,
626 args: []starlarkExpr{&stringLiteralExpr{ns}},
627 returnType: starlarkTypeVoid,
628 }})
629 }
630 } else {
631 // Upon seeing
632 // SOONG_CONFIG_x_y = v
633 // find a namespace called `x` and act as if we encountered
634 // $(call add_config_var_value(x,y,v)
635 // or check that `x_y` is a namespace, and then add the RHS of this assignment as variables in
636 // it.
637 // Emit an error in the ambiguous situation (namespaces `foo_bar` with a variable `baz`
638 // and `foo` with a variable `bar_baz`.
639 namespaceName := ""
640 if ctx.hasSoongNamespace(name) {
641 namespaceName = name
642 }
643 var varName string
644 for pos, ch := range name {
645 if !(ch == '_' && ctx.hasSoongNamespace(name[0:pos])) {
646 continue
647 }
648 if namespaceName != "" {
649 ctx.errorf(asgn, "ambiguous soong namespace (may be either `%s` or `%s`)", namespaceName, name[0:pos])
650 return
651 }
652 namespaceName = name[0:pos]
653 varName = name[pos+1:]
654 }
655 if namespaceName == "" {
656 ctx.errorf(asgn, "cannot figure out Soong namespace, please use add_soong_config_var_value macro instead")
657 return
658 }
659 if varName == "" {
660 // Remember variables in this namespace
661 s, ok := maybeString(val)
662 if !ok {
663 ctx.errorf(asgn, "cannot handle variables in SOONG_CONFIG_ assignment, please use add_soong_config_var_value instead")
664 return
665 }
666 ctx.updateSoongNamespace(asgn.Type != "+=", namespaceName, strings.Fields(s))
667 return
668 }
669
670 // Finally, handle assignment to a namespace variable
671 if !ctx.hasNamespaceVar(namespaceName, varName) {
672 ctx.errorf(asgn, "no %s variable in %s namespace, please use add_soong_config_var_value instead", varName, namespaceName)
673 return
674 }
675 ctx.receiver.newNode(&exprNode{&callExpr{
676 name: addSoongConfigVarValue,
677 args: []starlarkExpr{&stringLiteralExpr{namespaceName}, &stringLiteralExpr{varName}, val},
678 returnType: starlarkTypeVoid,
679 }})
680 }
681}
682
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800683func (ctx *parseContext) buildConcatExpr(a *mkparser.Assignment) *concatExpr {
684 xConcat := &concatExpr{}
685 var xItemList *listExpr
686 addToItemList := func(x ...starlarkExpr) {
687 if xItemList == nil {
688 xItemList = &listExpr{[]starlarkExpr{}}
689 }
690 xItemList.items = append(xItemList.items, x...)
691 }
692 finishItemList := func() {
693 if xItemList != nil {
694 xConcat.items = append(xConcat.items, xItemList)
695 xItemList = nil
696 }
697 }
698
699 items := a.Value.Words()
700 for _, item := range items {
701 // A function call in RHS is supposed to return a list, all other item
702 // expressions return individual elements.
703 switch x := ctx.parseMakeString(a, item).(type) {
704 case *badExpr:
705 ctx.wrapBadExpr(x)
706 return nil
707 case *stringLiteralExpr:
708 addToItemList(maybeConvertToStringList(x).(*listExpr).items...)
709 default:
710 switch x.typ() {
711 case starlarkTypeList:
712 finishItemList()
713 xConcat.items = append(xConcat.items, x)
714 case starlarkTypeString:
715 finishItemList()
716 xConcat.items = append(xConcat.items, &callExpr{
717 object: x,
718 name: "split",
719 args: nil,
720 returnType: starlarkTypeList,
721 })
722 default:
723 addToItemList(x)
724 }
725 }
726 }
727 if xItemList != nil {
728 xConcat.items = append(xConcat.items, xItemList)
729 }
730 return xConcat
731}
732
Sasha Smundak6609ba72021-07-22 18:32:56 -0700733func (ctx *parseContext) newDependentModule(path string, optional bool) *moduleInfo {
734 modulePath := ctx.loadedModulePath(path)
735 if mi, ok := ctx.dependentModules[modulePath]; ok {
736 mi.optional = mi.optional || optional
737 return mi
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800738 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800739 moduleName := moduleNameForFile(path)
740 moduleLocalName := "_" + moduleName
741 n, found := ctx.moduleNameCount[moduleName]
742 if found {
743 moduleLocalName += fmt.Sprintf("%d", n)
744 }
745 ctx.moduleNameCount[moduleName] = n + 1
Sasha Smundak6609ba72021-07-22 18:32:56 -0700746 mi := &moduleInfo{
747 path: modulePath,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800748 originalPath: path,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800749 moduleLocalName: moduleLocalName,
Sasha Smundak6609ba72021-07-22 18:32:56 -0700750 optional: optional,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800751 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700752 ctx.dependentModules[modulePath] = mi
753 ctx.script.inherited = append(ctx.script.inherited, mi)
754 return mi
755}
756
757func (ctx *parseContext) handleSubConfig(
758 v mkparser.Node, pathExpr starlarkExpr, loadAlways bool, processModule func(inheritedModule)) {
759 pathExpr, _ = pathExpr.eval(ctx.builtinMakeVars)
760
761 // In a simple case, the name of a module to inherit/include is known statically.
762 if path, ok := maybeString(pathExpr); ok {
763 if strings.Contains(path, "*") {
764 if paths, err := fs.Glob(ctx.script.sourceFS, path); err == nil {
765 for _, p := range paths {
766 processModule(inheritedStaticModule{ctx.newDependentModule(p, !loadAlways), loadAlways})
767 }
768 } else {
769 ctx.errorf(v, "cannot glob wildcard argument")
770 }
771 } else {
772 processModule(inheritedStaticModule{ctx.newDependentModule(path, !loadAlways), loadAlways})
773 }
774 return
775 }
776
777 // If module path references variables (e.g., $(v1)/foo/$(v2)/device-config.mk), find all the paths in the
778 // source tree that may be a match and the corresponding variable values. For instance, if the source tree
779 // contains vendor1/foo/abc/dev.mk and vendor2/foo/def/dev.mk, the first one will be inherited when
780 // (v1, v2) == ('vendor1', 'abc'), and the second one when (v1, v2) == ('vendor2', 'def').
781 // We then emit the code that loads all of them, e.g.:
782 // load("//vendor1/foo/abc:dev.rbc", _dev1_init="init")
783 // load("//vendor2/foo/def/dev.rbc", _dev2_init="init")
784 // And then inherit it as follows:
785 // _e = {
786 // "vendor1/foo/abc/dev.mk": ("vendor1/foo/abc/dev", _dev1_init),
787 // "vendor2/foo/def/dev.mk": ("vendor2/foo/def/dev", _dev_init2) }.get("%s/foo/%s/dev.mk" % (v1, v2))
788 // if _e:
789 // rblf.inherit(handle, _e[0], _e[1])
790 //
791 var matchingPaths []string
792 varPath, ok := pathExpr.(*interpolateExpr)
793 if !ok {
794 ctx.errorf(v, "inherit-product/include argument is too complex")
795 return
796 }
797
798 pathPattern := []string{varPath.chunks[0]}
799 for _, chunk := range varPath.chunks[1:] {
800 if chunk != "" {
801 pathPattern = append(pathPattern, chunk)
802 }
803 }
804 if pathPattern[0] != "" {
805 matchingPaths = ctx.findMatchingPaths(pathPattern)
806 } else {
807 // Heuristics -- if pattern starts from top, restrict it to the directories where
Sasha Smundak90be8c52021-08-03 11:06:10 -0700808 // we know inherit-product uses dynamically calculated path. Restrict it even further
809 // for certain path which would yield too many useless matches
810 if len(varPath.chunks) == 2 && varPath.chunks[1] == "/BoardConfigVendor.mk" {
811 pathPattern[0] = "vendor/google_devices"
812 matchingPaths = ctx.findMatchingPaths(pathPattern)
813 } else {
814 for _, t := range []string{"vendor/qcom", "vendor/google_devices"} {
815 pathPattern[0] = t
816 matchingPaths = append(matchingPaths, ctx.findMatchingPaths(pathPattern)...)
817 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700818 }
819 }
820 // Safeguard against $(call inherit-product,$(PRODUCT_PATH))
Sasha Smundak90be8c52021-08-03 11:06:10 -0700821 const maxMatchingFiles = 150
Sasha Smundak6609ba72021-07-22 18:32:56 -0700822 if len(matchingPaths) > maxMatchingFiles {
823 ctx.errorf(v, "there are >%d files matching the pattern, please rewrite it", maxMatchingFiles)
824 return
825 }
826 res := inheritedDynamicModule{*varPath, []*moduleInfo{}, loadAlways}
827 for _, p := range matchingPaths {
828 // A product configuration files discovered dynamically may attempt to inherit
829 // from another one which does not exist in this source tree. Prevent load errors
830 // by always loading the dynamic files as optional.
831 res.candidateModules = append(res.candidateModules, ctx.newDependentModule(p, true))
832 }
833 processModule(res)
834}
835
836func (ctx *parseContext) findMatchingPaths(pattern []string) []string {
837 files := ctx.script.makefileFinder.Find(ctx.script.topDir)
838 if len(pattern) == 0 {
839 return files
840 }
841
842 // Create regular expression from the pattern
843 s_regexp := "^" + regexp.QuoteMeta(pattern[0])
844 for _, s := range pattern[1:] {
845 s_regexp += ".*" + regexp.QuoteMeta(s)
846 }
847 s_regexp += "$"
848 rex := regexp.MustCompile(s_regexp)
849
850 // Now match
851 var res []string
852 for _, p := range files {
853 if rex.MatchString(p) {
854 res = append(res, p)
855 }
856 }
857 return res
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800858}
859
860func (ctx *parseContext) handleInheritModule(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700861 ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800862 ctx.receiver.newNode(&inheritNode{im})
Sasha Smundak6609ba72021-07-22 18:32:56 -0700863 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800864}
865
866func (ctx *parseContext) handleInclude(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700867 ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) {
868 ctx.receiver.newNode(&includeNode{im})
869 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800870}
871
872func (ctx *parseContext) handleVariable(v *mkparser.Variable) {
873 // Handle:
874 // $(call inherit-product,...)
875 // $(call inherit-product-if-exists,...)
876 // $(info xxx)
877 // $(warning xxx)
878 // $(error xxx)
879 expr := ctx.parseReference(v, v.Name)
880 switch x := expr.(type) {
881 case *callExpr:
882 if x.name == callLoadAlways || x.name == callLoadIf {
883 ctx.handleInheritModule(v, x.args[0], x.name == callLoadAlways)
884 } else if isMakeControlFunc(x.name) {
885 // File name is the first argument
886 args := []starlarkExpr{
887 &stringLiteralExpr{ctx.script.mkFile},
888 x.args[0],
889 }
890 ctx.receiver.newNode(&exprNode{
891 &callExpr{name: x.name, args: args, returnType: starlarkTypeUnknown},
892 })
893 } else {
894 ctx.receiver.newNode(&exprNode{expr})
895 }
896 case *badExpr:
897 ctx.wrapBadExpr(x)
898 return
899 default:
900 ctx.errorf(v, "cannot handle %s", v.Dump())
901 return
902 }
903}
904
905func (ctx *parseContext) handleDefine(directive *mkparser.Directive) {
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700906 macro_name := strings.Fields(directive.Args.Strings[0])[0]
907 // Ignore the macros that we handle
908 if _, ok := knownFunctions[macro_name]; !ok {
909 ctx.errorf(directive, "define is not supported: %s", macro_name)
910 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800911}
912
913func (ctx *parseContext) handleIfBlock(ifDirective *mkparser.Directive) {
914 ssSwitch := &switchNode{}
915 ctx.pushReceiver(ssSwitch)
916 for ctx.processBranch(ifDirective); ctx.hasNodes() && ctx.fatalError == nil; {
917 node := ctx.getNode()
918 switch x := node.(type) {
919 case *mkparser.Directive:
920 switch x.Name {
921 case "else", "elifdef", "elifndef", "elifeq", "elifneq":
922 ctx.processBranch(x)
923 case "endif":
924 ctx.popReceiver()
925 ctx.receiver.newNode(ssSwitch)
926 return
927 default:
928 ctx.errorf(node, "unexpected directive %s", x.Name)
929 }
930 default:
931 ctx.errorf(ifDirective, "unexpected statement")
932 }
933 }
934 if ctx.fatalError == nil {
935 ctx.fatalError = fmt.Errorf("no matching endif for %s", ifDirective.Dump())
936 }
937 ctx.popReceiver()
938}
939
940// processBranch processes a single branch (if/elseif/else) until the next directive
941// on the same level.
942func (ctx *parseContext) processBranch(check *mkparser.Directive) {
943 block := switchCase{gate: ctx.parseCondition(check)}
944 defer func() {
945 ctx.popVarAssignments()
946 ctx.ifNestLevel--
947
948 }()
949 ctx.pushVarAssignments()
950 ctx.ifNestLevel++
951
952 ctx.pushReceiver(&block)
953 for ctx.hasNodes() {
954 node := ctx.getNode()
955 if ctx.handleSimpleStatement(node) {
956 continue
957 }
958 switch d := node.(type) {
959 case *mkparser.Directive:
960 switch d.Name {
961 case "else", "elifdef", "elifndef", "elifeq", "elifneq", "endif":
962 ctx.popReceiver()
963 ctx.receiver.newNode(&block)
964 ctx.backNode()
965 return
966 case "ifdef", "ifndef", "ifeq", "ifneq":
967 ctx.handleIfBlock(d)
968 default:
969 ctx.errorf(d, "unexpected directive %s", d.Name)
970 }
971 default:
972 ctx.errorf(node, "unexpected statement")
973 }
974 }
975 ctx.fatalError = fmt.Errorf("no matching endif for %s", check.Dump())
976 ctx.popReceiver()
977}
978
979func (ctx *parseContext) newIfDefinedNode(check *mkparser.Directive) (starlarkExpr, bool) {
980 if !check.Args.Const() {
981 return ctx.newBadExpr(check, "ifdef variable ref too complex: %s", check.Args.Dump()), false
982 }
983 v := ctx.addVariable(check.Args.Strings[0])
984 return &variableDefinedExpr{v}, true
985}
986
987func (ctx *parseContext) parseCondition(check *mkparser.Directive) starlarkNode {
988 switch check.Name {
989 case "ifdef", "ifndef", "elifdef", "elifndef":
990 v, ok := ctx.newIfDefinedNode(check)
991 if ok && strings.HasSuffix(check.Name, "ndef") {
992 v = &notExpr{v}
993 }
994 return &ifNode{
995 isElif: strings.HasPrefix(check.Name, "elif"),
996 expr: v,
997 }
998 case "ifeq", "ifneq", "elifeq", "elifneq":
999 return &ifNode{
1000 isElif: strings.HasPrefix(check.Name, "elif"),
1001 expr: ctx.parseCompare(check),
1002 }
1003 case "else":
1004 return &elseNode{}
1005 default:
1006 panic(fmt.Errorf("%s: unknown directive: %s", ctx.script.mkFile, check.Dump()))
1007 }
1008}
1009
1010func (ctx *parseContext) newBadExpr(node mkparser.Node, text string, args ...interface{}) starlarkExpr {
1011 message := fmt.Sprintf(text, args...)
1012 if ctx.errorLogger != nil {
1013 ctx.errorLogger.NewError(text, node, args)
1014 }
1015 ctx.script.hasErrors = true
1016 return &badExpr{node, message}
1017}
1018
1019func (ctx *parseContext) parseCompare(cond *mkparser.Directive) starlarkExpr {
1020 // Strip outer parentheses
1021 mkArg := cloneMakeString(cond.Args)
1022 mkArg.Strings[0] = strings.TrimLeft(mkArg.Strings[0], "( ")
1023 n := len(mkArg.Strings)
1024 mkArg.Strings[n-1] = strings.TrimRight(mkArg.Strings[n-1], ") ")
1025 args := mkArg.Split(",")
1026 // TODO(asmundak): handle the case where the arguments are in quotes and space-separated
1027 if len(args) != 2 {
1028 return ctx.newBadExpr(cond, "ifeq/ifneq len(args) != 2 %s", cond.Dump())
1029 }
1030 args[0].TrimRightSpaces()
1031 args[1].TrimLeftSpaces()
1032
1033 isEq := !strings.HasSuffix(cond.Name, "neq")
1034 switch xLeft := ctx.parseMakeString(cond, args[0]).(type) {
1035 case *stringLiteralExpr, *variableRefExpr:
1036 switch xRight := ctx.parseMakeString(cond, args[1]).(type) {
1037 case *stringLiteralExpr, *variableRefExpr:
1038 return &eqExpr{left: xLeft, right: xRight, isEq: isEq}
1039 case *badExpr:
1040 return xRight
1041 default:
1042 expr, ok := ctx.parseCheckFunctionCallResult(cond, xLeft, args[1])
1043 if ok {
1044 return expr
1045 }
1046 return ctx.newBadExpr(cond, "right operand is too complex: %s", args[1].Dump())
1047 }
1048 case *badExpr:
1049 return xLeft
1050 default:
1051 switch xRight := ctx.parseMakeString(cond, args[1]).(type) {
1052 case *stringLiteralExpr, *variableRefExpr:
1053 expr, ok := ctx.parseCheckFunctionCallResult(cond, xRight, args[0])
1054 if ok {
1055 return expr
1056 }
1057 return ctx.newBadExpr(cond, "left operand is too complex: %s", args[0].Dump())
1058 case *badExpr:
1059 return xRight
1060 default:
1061 return ctx.newBadExpr(cond, "operands are too complex: (%s,%s)", args[0].Dump(), args[1].Dump())
1062 }
1063 }
1064}
1065
1066func (ctx *parseContext) parseCheckFunctionCallResult(directive *mkparser.Directive, xValue starlarkExpr,
1067 varArg *mkparser.MakeString) (starlarkExpr, bool) {
1068 mkSingleVar, ok := varArg.SingleVariable()
1069 if !ok {
1070 return nil, false
1071 }
1072 expr := ctx.parseReference(directive, mkSingleVar)
1073 negate := strings.HasSuffix(directive.Name, "neq")
1074 checkIsSomethingFunction := func(xCall *callExpr) starlarkExpr {
1075 s, ok := maybeString(xValue)
1076 if !ok || s != "true" {
1077 return ctx.newBadExpr(directive,
1078 fmt.Sprintf("the result of %s can be compared only to 'true'", xCall.name))
1079 }
1080 if len(xCall.args) < 1 {
1081 return ctx.newBadExpr(directive, "%s requires an argument", xCall.name)
1082 }
1083 return nil
1084 }
1085 switch x := expr.(type) {
1086 case *callExpr:
1087 switch x.name {
1088 case "filter":
1089 return ctx.parseCompareFilterFuncResult(directive, x, xValue, !negate), true
1090 case "filter-out":
1091 return ctx.parseCompareFilterFuncResult(directive, x, xValue, negate), true
1092 case "wildcard":
1093 return ctx.parseCompareWildcardFuncResult(directive, x, xValue, negate), true
1094 case "findstring":
1095 return ctx.parseCheckFindstringFuncResult(directive, x, xValue, negate), true
1096 case "strip":
1097 return ctx.parseCompareStripFuncResult(directive, x, xValue, negate), true
1098 case "is-board-platform":
1099 if xBad := checkIsSomethingFunction(x); xBad != nil {
1100 return xBad, true
1101 }
1102 return &eqExpr{
1103 left: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
1104 right: x.args[0],
1105 isEq: !negate,
1106 }, true
1107 case "is-board-platform-in-list":
1108 if xBad := checkIsSomethingFunction(x); xBad != nil {
1109 return xBad, true
1110 }
1111 return &inExpr{
1112 expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
1113 list: maybeConvertToStringList(x.args[0]),
1114 isNot: negate,
1115 }, true
1116 case "is-product-in-list":
1117 if xBad := checkIsSomethingFunction(x); xBad != nil {
1118 return xBad, true
1119 }
1120 return &inExpr{
1121 expr: &variableRefExpr{ctx.addVariable("TARGET_PRODUCT"), true},
1122 list: maybeConvertToStringList(x.args[0]),
1123 isNot: negate,
1124 }, true
1125 case "is-vendor-board-platform":
1126 if xBad := checkIsSomethingFunction(x); xBad != nil {
1127 return xBad, true
1128 }
1129 s, ok := maybeString(x.args[0])
1130 if !ok {
1131 return ctx.newBadExpr(directive, "cannot handle non-constant argument to is-vendor-board-platform"), true
1132 }
1133 return &inExpr{
1134 expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
1135 list: &variableRefExpr{ctx.addVariable(s + "_BOARD_PLATFORMS"), true},
1136 isNot: negate,
1137 }, true
1138 default:
1139 return ctx.newBadExpr(directive, "Unknown function in ifeq: %s", x.name), true
1140 }
1141 case *badExpr:
1142 return x, true
1143 default:
1144 return nil, false
1145 }
1146}
1147
1148func (ctx *parseContext) parseCompareFilterFuncResult(cond *mkparser.Directive,
1149 filterFuncCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
1150 // We handle:
Sasha Smundak0554d762021-07-08 18:26:12 -07001151 // * ifeq/ifneq (,$(filter v1 v2 ..., EXPR) becomes if EXPR not in/in ["v1", "v2", ...]
1152 // * ifeq/ifneq (,$(filter EXPR, v1 v2 ...) becomes if EXPR not in/in ["v1", "v2", ...]
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001153 // * ifeq/ifneq ($(VAR),$(filter $(VAR), v1 v2 ...) becomes if VAR in/not in ["v1", "v2"]
1154 // TODO(Asmundak): check the last case works for filter-out, too.
1155 xPattern := filterFuncCall.args[0]
1156 xText := filterFuncCall.args[1]
1157 var xInList *stringLiteralExpr
Sasha Smundak0554d762021-07-08 18:26:12 -07001158 var expr starlarkExpr
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001159 var ok bool
1160 switch x := xValue.(type) {
1161 case *stringLiteralExpr:
1162 if x.literal != "" {
1163 return ctx.newBadExpr(cond, "filter comparison to non-empty value: %s", xValue)
1164 }
1165 // Either pattern or text should be const, and the
1166 // non-const one should be varRefExpr
1167 if xInList, ok = xPattern.(*stringLiteralExpr); ok {
Sasha Smundak0554d762021-07-08 18:26:12 -07001168 expr = xText
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001169 } else if xInList, ok = xText.(*stringLiteralExpr); ok {
Sasha Smundak0554d762021-07-08 18:26:12 -07001170 expr = xPattern
1171 } else {
1172 return &callExpr{
1173 object: nil,
1174 name: filterFuncCall.name,
1175 args: filterFuncCall.args,
1176 returnType: starlarkTypeBool,
1177 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001178 }
1179 case *variableRefExpr:
1180 if v, ok := xPattern.(*variableRefExpr); ok {
1181 if xInList, ok = xText.(*stringLiteralExpr); ok && v.ref.name() == x.ref.name() {
1182 // ifeq/ifneq ($(VAR),$(filter $(VAR), v1 v2 ...), flip negate,
1183 // it's the opposite to what is done when comparing to empty.
Sasha Smundak0554d762021-07-08 18:26:12 -07001184 expr = xPattern
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001185 negate = !negate
1186 }
1187 }
1188 }
Sasha Smundak0554d762021-07-08 18:26:12 -07001189 if expr != nil && xInList != nil {
1190 slExpr := newStringListExpr(strings.Fields(xInList.literal))
1191 // Generate simpler code for the common cases:
1192 if expr.typ() == starlarkTypeList {
1193 if len(slExpr.items) == 1 {
1194 // Checking that a string belongs to list
1195 return &inExpr{isNot: negate, list: expr, expr: slExpr.items[0]}
1196 } else {
1197 // TODO(asmundak):
1198 panic("TBD")
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001199 }
Sasha Smundak0554d762021-07-08 18:26:12 -07001200 } else if len(slExpr.items) == 1 {
1201 return &eqExpr{left: expr, right: slExpr.items[0], isEq: !negate}
1202 } else {
1203 return &inExpr{isNot: negate, list: newStringListExpr(strings.Fields(xInList.literal)), expr: expr}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001204 }
1205 }
1206 return ctx.newBadExpr(cond, "filter arguments are too complex: %s", cond.Dump())
1207}
1208
1209func (ctx *parseContext) parseCompareWildcardFuncResult(directive *mkparser.Directive,
1210 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001211 if !isEmptyString(xValue) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001212 return ctx.newBadExpr(directive, "wildcard result can be compared only to empty: %s", xValue)
1213 }
1214 callFunc := wildcardExistsPhony
1215 if s, ok := xCall.args[0].(*stringLiteralExpr); ok && !strings.ContainsAny(s.literal, "*?{[") {
1216 callFunc = fileExistsPhony
1217 }
1218 var cc starlarkExpr = &callExpr{name: callFunc, args: xCall.args, returnType: starlarkTypeBool}
1219 if !negate {
1220 cc = &notExpr{cc}
1221 }
1222 return cc
1223}
1224
1225func (ctx *parseContext) parseCheckFindstringFuncResult(directive *mkparser.Directive,
1226 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001227 if isEmptyString(xValue) {
1228 return &eqExpr{
1229 left: &callExpr{
1230 object: xCall.args[1],
1231 name: "find",
1232 args: []starlarkExpr{xCall.args[0]},
1233 returnType: starlarkTypeInt,
1234 },
1235 right: &intLiteralExpr{-1},
1236 isEq: !negate,
1237 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001238 }
Sasha Smundak0554d762021-07-08 18:26:12 -07001239 return ctx.newBadExpr(directive, "findstring result can be compared only to empty: %s", xValue)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001240}
1241
1242func (ctx *parseContext) parseCompareStripFuncResult(directive *mkparser.Directive,
1243 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
1244 if _, ok := xValue.(*stringLiteralExpr); !ok {
1245 return ctx.newBadExpr(directive, "strip result can be compared only to string: %s", xValue)
1246 }
1247 return &eqExpr{
1248 left: &callExpr{
1249 name: "strip",
1250 args: xCall.args,
1251 returnType: starlarkTypeString,
1252 },
1253 right: xValue, isEq: !negate}
1254}
1255
1256// parses $(...), returning an expression
1257func (ctx *parseContext) parseReference(node mkparser.Node, ref *mkparser.MakeString) starlarkExpr {
1258 ref.TrimLeftSpaces()
1259 ref.TrimRightSpaces()
1260 refDump := ref.Dump()
1261
1262 // Handle only the case where the first (or only) word is constant
1263 words := ref.SplitN(" ", 2)
1264 if !words[0].Const() {
1265 return ctx.newBadExpr(node, "reference is too complex: %s", refDump)
1266 }
1267
1268 // If it is a single word, it can be a simple variable
1269 // reference or a function call
1270 if len(words) == 1 {
1271 if isMakeControlFunc(refDump) || refDump == "shell" {
1272 return &callExpr{
1273 name: refDump,
1274 args: []starlarkExpr{&stringLiteralExpr{""}},
1275 returnType: starlarkTypeUnknown,
1276 }
1277 }
1278 if v := ctx.addVariable(refDump); v != nil {
1279 return &variableRefExpr{v, ctx.lastAssignment(v.name()) != nil}
1280 }
1281 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1282 }
1283
1284 expr := &callExpr{name: words[0].Dump(), returnType: starlarkTypeUnknown}
1285 args := words[1]
1286 args.TrimLeftSpaces()
1287 // Make control functions and shell need special treatment as everything
1288 // after the name is a single text argument
1289 if isMakeControlFunc(expr.name) || expr.name == "shell" {
1290 x := ctx.parseMakeString(node, args)
1291 if xBad, ok := x.(*badExpr); ok {
1292 return xBad
1293 }
1294 expr.args = []starlarkExpr{x}
1295 return expr
1296 }
1297 if expr.name == "call" {
1298 words = args.SplitN(",", 2)
1299 if words[0].Empty() || !words[0].Const() {
Sasha Smundakf2c9f8b2021-07-27 10:44:48 -07001300 return ctx.newBadExpr(node, "cannot handle %s", refDump)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001301 }
1302 expr.name = words[0].Dump()
1303 if len(words) < 2 {
Sasha Smundak6609ba72021-07-22 18:32:56 -07001304 args = &mkparser.MakeString{}
1305 } else {
1306 args = words[1]
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001307 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001308 }
1309 if kf, found := knownFunctions[expr.name]; found {
1310 expr.returnType = kf.returnType
1311 } else {
1312 return ctx.newBadExpr(node, "cannot handle invoking %s", expr.name)
1313 }
1314 switch expr.name {
1315 case "word":
1316 return ctx.parseWordFunc(node, args)
Sasha Smundak16e07732021-07-23 11:38:23 -07001317 case "firstword", "lastword":
1318 return ctx.parseFirstOrLastwordFunc(node, expr.name, args)
Sasha Smundak6609ba72021-07-22 18:32:56 -07001319 case "my-dir":
1320 return &variableRefExpr{ctx.addVariable("LOCAL_PATH"), true}
Sasha Smundak94b41c72021-07-12 18:30:42 -07001321 case "subst", "patsubst":
1322 return ctx.parseSubstFunc(node, expr.name, args)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001323 default:
1324 for _, arg := range args.Split(",") {
1325 arg.TrimLeftSpaces()
1326 arg.TrimRightSpaces()
1327 x := ctx.parseMakeString(node, arg)
1328 if xBad, ok := x.(*badExpr); ok {
1329 return xBad
1330 }
1331 expr.args = append(expr.args, x)
1332 }
1333 }
1334 return expr
1335}
1336
Sasha Smundak94b41c72021-07-12 18:30:42 -07001337func (ctx *parseContext) parseSubstFunc(node mkparser.Node, fname string, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001338 words := args.Split(",")
1339 if len(words) != 3 {
Sasha Smundak94b41c72021-07-12 18:30:42 -07001340 return ctx.newBadExpr(node, "%s function should have 3 arguments", fname)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001341 }
1342 if !words[0].Const() || !words[1].Const() {
Sasha Smundak94b41c72021-07-12 18:30:42 -07001343 return ctx.newBadExpr(node, "%s function's from and to arguments should be constant", fname)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001344 }
1345 from := words[0].Strings[0]
1346 to := words[1].Strings[0]
1347 words[2].TrimLeftSpaces()
1348 words[2].TrimRightSpaces()
1349 obj := ctx.parseMakeString(node, words[2])
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001350 typ := obj.typ()
Sasha Smundak94b41c72021-07-12 18:30:42 -07001351 if typ == starlarkTypeString && fname == "subst" {
1352 // Optimization: if it's $(subst from, to, string), emit string.replace(from, to)
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001353 return &callExpr{
1354 object: obj,
1355 name: "replace",
1356 args: []starlarkExpr{&stringLiteralExpr{from}, &stringLiteralExpr{to}},
1357 returnType: typ,
1358 }
1359 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001360 return &callExpr{
Sasha Smundak94b41c72021-07-12 18:30:42 -07001361 name: fname,
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001362 args: []starlarkExpr{&stringLiteralExpr{from}, &stringLiteralExpr{to}, obj},
1363 returnType: obj.typ(),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001364 }
1365}
1366
1367func (ctx *parseContext) parseWordFunc(node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1368 words := args.Split(",")
1369 if len(words) != 2 {
1370 return ctx.newBadExpr(node, "word function should have 2 arguments")
1371 }
1372 var index uint64 = 0
1373 if words[0].Const() {
1374 index, _ = strconv.ParseUint(strings.TrimSpace(words[0].Strings[0]), 10, 64)
1375 }
1376 if index < 1 {
1377 return ctx.newBadExpr(node, "word index should be constant positive integer")
1378 }
1379 words[1].TrimLeftSpaces()
1380 words[1].TrimRightSpaces()
1381 array := ctx.parseMakeString(node, words[1])
1382 if xBad, ok := array.(*badExpr); ok {
1383 return xBad
1384 }
1385 if array.typ() != starlarkTypeList {
1386 array = &callExpr{object: array, name: "split", returnType: starlarkTypeList}
1387 }
1388 return indexExpr{array, &intLiteralExpr{int(index - 1)}}
1389}
1390
Sasha Smundak16e07732021-07-23 11:38:23 -07001391func (ctx *parseContext) parseFirstOrLastwordFunc(node mkparser.Node, name string, args *mkparser.MakeString) starlarkExpr {
1392 arg := ctx.parseMakeString(node, args)
1393 if bad, ok := arg.(*badExpr); ok {
1394 return bad
1395 }
1396 index := &intLiteralExpr{0}
1397 if name == "lastword" {
1398 if v, ok := arg.(*variableRefExpr); ok && v.ref.name() == "MAKEFILE_LIST" {
1399 return &stringLiteralExpr{ctx.script.mkFile}
1400 }
1401 index.literal = -1
1402 }
1403 if arg.typ() == starlarkTypeList {
1404 return &indexExpr{arg, index}
1405 }
1406 return &indexExpr{&callExpr{object: arg, name: "split", returnType: starlarkTypeList}, index}
1407}
1408
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001409func (ctx *parseContext) parseMakeString(node mkparser.Node, mk *mkparser.MakeString) starlarkExpr {
1410 if mk.Const() {
1411 return &stringLiteralExpr{mk.Dump()}
1412 }
1413 if mkRef, ok := mk.SingleVariable(); ok {
1414 return ctx.parseReference(node, mkRef)
1415 }
1416 // If we reached here, it's neither string literal nor a simple variable,
1417 // we need a full-blown interpolation node that will generate
1418 // "a%b%c" % (X, Y) for a$(X)b$(Y)c
1419 xInterp := &interpolateExpr{args: make([]starlarkExpr, len(mk.Variables))}
1420 for i, ref := range mk.Variables {
1421 arg := ctx.parseReference(node, ref.Name)
1422 if x, ok := arg.(*badExpr); ok {
1423 return x
1424 }
1425 xInterp.args[i] = arg
1426 }
1427 xInterp.chunks = append(xInterp.chunks, mk.Strings...)
1428 return xInterp
1429}
1430
1431// Handles the statements whose treatment is the same in all contexts: comment,
1432// assignment, variable (which is a macro call in reality) and all constructs that
1433// do not handle in any context ('define directive and any unrecognized stuff).
1434// Return true if we handled it.
1435func (ctx *parseContext) handleSimpleStatement(node mkparser.Node) bool {
1436 handled := true
1437 switch x := node.(type) {
1438 case *mkparser.Comment:
1439 ctx.insertComment("#" + x.Comment)
1440 case *mkparser.Assignment:
1441 ctx.handleAssignment(x)
1442 case *mkparser.Variable:
1443 ctx.handleVariable(x)
1444 case *mkparser.Directive:
1445 switch x.Name {
1446 case "define":
1447 ctx.handleDefine(x)
1448 case "include", "-include":
1449 ctx.handleInclude(node, ctx.parseMakeString(node, x.Args), x.Name[0] != '-')
1450 default:
1451 handled = false
1452 }
1453 default:
1454 ctx.errorf(x, "unsupported line %s", x.Dump())
1455 }
1456 return handled
1457}
1458
1459func (ctx *parseContext) insertComment(s string) {
1460 ctx.receiver.newNode(&commentNode{strings.TrimSpace(s)})
1461}
1462
1463func (ctx *parseContext) carryAsComment(failedNode mkparser.Node) {
1464 for _, line := range strings.Split(failedNode.Dump(), "\n") {
1465 ctx.insertComment("# " + line)
1466 }
1467}
1468
1469// records that the given node failed to be converted and includes an explanatory message
1470func (ctx *parseContext) errorf(failedNode mkparser.Node, message string, args ...interface{}) {
1471 if ctx.errorLogger != nil {
1472 ctx.errorLogger.NewError(message, failedNode, args...)
1473 }
1474 message = fmt.Sprintf(message, args...)
1475 ctx.insertComment(fmt.Sprintf("# MK2RBC TRANSLATION ERROR: %s", message))
1476 ctx.carryAsComment(failedNode)
1477 ctx.script.hasErrors = true
1478}
1479
1480func (ctx *parseContext) wrapBadExpr(xBad *badExpr) {
1481 ctx.insertComment(fmt.Sprintf("# MK2RBC TRANSLATION ERROR: %s", xBad.message))
1482 ctx.carryAsComment(xBad.node)
1483}
1484
1485func (ctx *parseContext) loadedModulePath(path string) string {
1486 // During the transition to Roboleaf some of the product configuration files
1487 // will be converted and checked in while the others will be generated on the fly
1488 // and run. The runner (rbcrun application) accommodates this by allowing three
1489 // different ways to specify the loaded file location:
1490 // 1) load(":<file>",...) loads <file> from the same directory
1491 // 2) load("//path/relative/to/source/root:<file>", ...) loads <file> source tree
1492 // 3) load("/absolute/path/to/<file> absolute path
1493 // If the file being generated and the file it wants to load are in the same directory,
1494 // generate option 1.
1495 // Otherwise, if output directory is not specified, generate 2)
1496 // Finally, if output directory has been specified and the file being generated and
1497 // the file it wants to load from are in the different directories, generate 2) or 3):
1498 // * if the file being loaded exists in the source tree, generate 2)
1499 // * otherwise, generate 3)
1500 // Finally, figure out the loaded module path and name and create a node for it
1501 loadedModuleDir := filepath.Dir(path)
1502 base := filepath.Base(path)
1503 loadedModuleName := strings.TrimSuffix(base, filepath.Ext(base)) + ctx.outputSuffix
1504 if loadedModuleDir == filepath.Dir(ctx.script.mkFile) {
1505 return ":" + loadedModuleName
1506 }
1507 if ctx.outputDir == "" {
1508 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1509 }
1510 if _, err := os.Stat(filepath.Join(loadedModuleDir, loadedModuleName)); err == nil {
1511 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1512 }
1513 return filepath.Join(ctx.outputDir, loadedModuleDir, loadedModuleName)
1514}
1515
Sasha Smundak3deb9682021-07-26 18:42:25 -07001516func (ctx *parseContext) addSoongNamespace(ns string) {
1517 if _, ok := ctx.soongNamespaces[ns]; ok {
1518 return
1519 }
1520 ctx.soongNamespaces[ns] = make(map[string]bool)
1521}
1522
1523func (ctx *parseContext) hasSoongNamespace(name string) bool {
1524 _, ok := ctx.soongNamespaces[name]
1525 return ok
1526}
1527
1528func (ctx *parseContext) updateSoongNamespace(replace bool, namespaceName string, varNames []string) {
1529 ctx.addSoongNamespace(namespaceName)
1530 vars := ctx.soongNamespaces[namespaceName]
1531 if replace {
1532 vars = make(map[string]bool)
1533 ctx.soongNamespaces[namespaceName] = vars
1534 }
1535 for _, v := range varNames {
1536 vars[v] = true
1537 }
1538}
1539
1540func (ctx *parseContext) hasNamespaceVar(namespaceName string, varName string) bool {
1541 vars, ok := ctx.soongNamespaces[namespaceName]
1542 if ok {
1543 _, ok = vars[varName]
1544 }
1545 return ok
1546}
1547
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001548func (ss *StarlarkScript) String() string {
1549 return NewGenerateContext(ss).emit()
1550}
1551
1552func (ss *StarlarkScript) SubConfigFiles() []string {
Sasha Smundak6609ba72021-07-22 18:32:56 -07001553
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001554 var subs []string
1555 for _, src := range ss.inherited {
1556 subs = append(subs, src.originalPath)
1557 }
1558 return subs
1559}
1560
1561func (ss *StarlarkScript) HasErrors() bool {
1562 return ss.hasErrors
1563}
1564
1565// Convert reads and parses a makefile. If successful, parsed tree
1566// is returned and then can be passed to String() to get the generated
1567// Starlark file.
1568func Convert(req Request) (*StarlarkScript, error) {
1569 reader := req.Reader
1570 if reader == nil {
1571 mkContents, err := ioutil.ReadFile(req.MkFile)
1572 if err != nil {
1573 return nil, err
1574 }
1575 reader = bytes.NewBuffer(mkContents)
1576 }
1577 parser := mkparser.NewParser(req.MkFile, reader)
1578 nodes, errs := parser.Parse()
1579 if len(errs) > 0 {
1580 for _, e := range errs {
1581 fmt.Fprintln(os.Stderr, "ERROR:", e)
1582 }
1583 return nil, fmt.Errorf("bad makefile %s", req.MkFile)
1584 }
1585 starScript := &StarlarkScript{
1586 moduleName: moduleNameForFile(req.MkFile),
1587 mkFile: req.MkFile,
1588 topDir: req.RootDir,
1589 traceCalls: req.TraceCalls,
1590 warnPartialSuccess: req.WarnPartialSuccess,
Sasha Smundak6609ba72021-07-22 18:32:56 -07001591 sourceFS: req.SourceFS,
1592 makefileFinder: req.MakefileFinder,
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001593 }
1594 ctx := newParseContext(starScript, nodes)
1595 ctx.outputSuffix = req.OutputSuffix
1596 ctx.outputDir = req.OutputDir
1597 ctx.errorLogger = req.ErrorLogger
1598 if len(req.TracedVariables) > 0 {
1599 ctx.tracedVariables = make(map[string]bool)
1600 for _, v := range req.TracedVariables {
1601 ctx.tracedVariables[v] = true
1602 }
1603 }
1604 ctx.pushReceiver(starScript)
1605 for ctx.hasNodes() && ctx.fatalError == nil {
1606 node := ctx.getNode()
1607 if ctx.handleSimpleStatement(node) {
1608 continue
1609 }
1610 switch x := node.(type) {
1611 case *mkparser.Directive:
1612 switch x.Name {
1613 case "ifeq", "ifneq", "ifdef", "ifndef":
1614 ctx.handleIfBlock(x)
1615 default:
1616 ctx.errorf(x, "unexpected directive %s", x.Name)
1617 }
1618 default:
1619 ctx.errorf(x, "unsupported line")
1620 }
1621 }
1622 if ctx.fatalError != nil {
1623 return nil, ctx.fatalError
1624 }
1625 return starScript, nil
1626}
1627
1628func Launcher(path, name string) string {
1629 var buf bytes.Buffer
1630 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
1631 fmt.Fprintf(&buf, "load(%q, \"init\")\n", path)
1632 fmt.Fprintf(&buf, "g, config = %s(%q, init)\n", cfnMain, name)
1633 fmt.Fprintf(&buf, "%s(g, config)\n", cfnPrintVars)
1634 return buf.String()
1635}
1636
1637func MakePath2ModuleName(mkPath string) string {
1638 return strings.TrimSuffix(mkPath, filepath.Ext(mkPath))
1639}