blob: 30888c7636effc3688b391f6ab664c8888584d75 [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"},
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 {
729 mi.optional = mi.optional || optional
730 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 {
756 if strings.Contains(path, "*") {
757 if paths, err := fs.Glob(ctx.script.sourceFS, path); err == nil {
758 for _, p := range paths {
759 processModule(inheritedStaticModule{ctx.newDependentModule(p, !loadAlways), loadAlways})
760 }
761 } else {
762 ctx.errorf(v, "cannot glob wildcard argument")
763 }
764 } else {
765 processModule(inheritedStaticModule{ctx.newDependentModule(path, !loadAlways), loadAlways})
766 }
767 return
768 }
769
770 // If module path references variables (e.g., $(v1)/foo/$(v2)/device-config.mk), find all the paths in the
771 // source tree that may be a match and the corresponding variable values. For instance, if the source tree
772 // contains vendor1/foo/abc/dev.mk and vendor2/foo/def/dev.mk, the first one will be inherited when
773 // (v1, v2) == ('vendor1', 'abc'), and the second one when (v1, v2) == ('vendor2', 'def').
774 // We then emit the code that loads all of them, e.g.:
775 // load("//vendor1/foo/abc:dev.rbc", _dev1_init="init")
776 // load("//vendor2/foo/def/dev.rbc", _dev2_init="init")
777 // And then inherit it as follows:
778 // _e = {
779 // "vendor1/foo/abc/dev.mk": ("vendor1/foo/abc/dev", _dev1_init),
780 // "vendor2/foo/def/dev.mk": ("vendor2/foo/def/dev", _dev_init2) }.get("%s/foo/%s/dev.mk" % (v1, v2))
781 // if _e:
782 // rblf.inherit(handle, _e[0], _e[1])
783 //
784 var matchingPaths []string
785 varPath, ok := pathExpr.(*interpolateExpr)
786 if !ok {
787 ctx.errorf(v, "inherit-product/include argument is too complex")
788 return
789 }
790
791 pathPattern := []string{varPath.chunks[0]}
792 for _, chunk := range varPath.chunks[1:] {
793 if chunk != "" {
794 pathPattern = append(pathPattern, chunk)
795 }
796 }
797 if pathPattern[0] != "" {
798 matchingPaths = ctx.findMatchingPaths(pathPattern)
799 } else {
800 // Heuristics -- if pattern starts from top, restrict it to the directories where
Sasha Smundak90be8c52021-08-03 11:06:10 -0700801 // we know inherit-product uses dynamically calculated path. Restrict it even further
802 // for certain path which would yield too many useless matches
803 if len(varPath.chunks) == 2 && varPath.chunks[1] == "/BoardConfigVendor.mk" {
804 pathPattern[0] = "vendor/google_devices"
805 matchingPaths = ctx.findMatchingPaths(pathPattern)
806 } else {
807 for _, t := range []string{"vendor/qcom", "vendor/google_devices"} {
808 pathPattern[0] = t
809 matchingPaths = append(matchingPaths, ctx.findMatchingPaths(pathPattern)...)
810 }
Sasha Smundak6609ba72021-07-22 18:32:56 -0700811 }
812 }
813 // Safeguard against $(call inherit-product,$(PRODUCT_PATH))
Sasha Smundak90be8c52021-08-03 11:06:10 -0700814 const maxMatchingFiles = 150
Sasha Smundak6609ba72021-07-22 18:32:56 -0700815 if len(matchingPaths) > maxMatchingFiles {
816 ctx.errorf(v, "there are >%d files matching the pattern, please rewrite it", maxMatchingFiles)
817 return
818 }
819 res := inheritedDynamicModule{*varPath, []*moduleInfo{}, loadAlways}
820 for _, p := range matchingPaths {
821 // A product configuration files discovered dynamically may attempt to inherit
822 // from another one which does not exist in this source tree. Prevent load errors
823 // by always loading the dynamic files as optional.
824 res.candidateModules = append(res.candidateModules, ctx.newDependentModule(p, true))
825 }
826 processModule(res)
827}
828
829func (ctx *parseContext) findMatchingPaths(pattern []string) []string {
830 files := ctx.script.makefileFinder.Find(ctx.script.topDir)
831 if len(pattern) == 0 {
832 return files
833 }
834
835 // Create regular expression from the pattern
836 s_regexp := "^" + regexp.QuoteMeta(pattern[0])
837 for _, s := range pattern[1:] {
838 s_regexp += ".*" + regexp.QuoteMeta(s)
839 }
840 s_regexp += "$"
841 rex := regexp.MustCompile(s_regexp)
842
843 // Now match
844 var res []string
845 for _, p := range files {
846 if rex.MatchString(p) {
847 res = append(res, p)
848 }
849 }
850 return res
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800851}
852
853func (ctx *parseContext) handleInheritModule(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700854 ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800855 ctx.receiver.newNode(&inheritNode{im})
Sasha Smundak6609ba72021-07-22 18:32:56 -0700856 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800857}
858
859func (ctx *parseContext) handleInclude(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) {
Sasha Smundak6609ba72021-07-22 18:32:56 -0700860 ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) {
861 ctx.receiver.newNode(&includeNode{im})
862 })
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800863}
864
865func (ctx *parseContext) handleVariable(v *mkparser.Variable) {
866 // Handle:
867 // $(call inherit-product,...)
868 // $(call inherit-product-if-exists,...)
869 // $(info xxx)
870 // $(warning xxx)
871 // $(error xxx)
872 expr := ctx.parseReference(v, v.Name)
873 switch x := expr.(type) {
874 case *callExpr:
875 if x.name == callLoadAlways || x.name == callLoadIf {
876 ctx.handleInheritModule(v, x.args[0], x.name == callLoadAlways)
877 } else if isMakeControlFunc(x.name) {
878 // File name is the first argument
879 args := []starlarkExpr{
880 &stringLiteralExpr{ctx.script.mkFile},
881 x.args[0],
882 }
883 ctx.receiver.newNode(&exprNode{
884 &callExpr{name: x.name, args: args, returnType: starlarkTypeUnknown},
885 })
886 } else {
887 ctx.receiver.newNode(&exprNode{expr})
888 }
889 case *badExpr:
890 ctx.wrapBadExpr(x)
891 return
892 default:
893 ctx.errorf(v, "cannot handle %s", v.Dump())
894 return
895 }
896}
897
898func (ctx *parseContext) handleDefine(directive *mkparser.Directive) {
Sasha Smundakf3e072a2021-07-14 12:50:28 -0700899 macro_name := strings.Fields(directive.Args.Strings[0])[0]
900 // Ignore the macros that we handle
901 if _, ok := knownFunctions[macro_name]; !ok {
902 ctx.errorf(directive, "define is not supported: %s", macro_name)
903 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800904}
905
906func (ctx *parseContext) handleIfBlock(ifDirective *mkparser.Directive) {
907 ssSwitch := &switchNode{}
908 ctx.pushReceiver(ssSwitch)
909 for ctx.processBranch(ifDirective); ctx.hasNodes() && ctx.fatalError == nil; {
910 node := ctx.getNode()
911 switch x := node.(type) {
912 case *mkparser.Directive:
913 switch x.Name {
914 case "else", "elifdef", "elifndef", "elifeq", "elifneq":
915 ctx.processBranch(x)
916 case "endif":
917 ctx.popReceiver()
918 ctx.receiver.newNode(ssSwitch)
919 return
920 default:
921 ctx.errorf(node, "unexpected directive %s", x.Name)
922 }
923 default:
924 ctx.errorf(ifDirective, "unexpected statement")
925 }
926 }
927 if ctx.fatalError == nil {
928 ctx.fatalError = fmt.Errorf("no matching endif for %s", ifDirective.Dump())
929 }
930 ctx.popReceiver()
931}
932
933// processBranch processes a single branch (if/elseif/else) until the next directive
934// on the same level.
935func (ctx *parseContext) processBranch(check *mkparser.Directive) {
936 block := switchCase{gate: ctx.parseCondition(check)}
937 defer func() {
938 ctx.popVarAssignments()
939 ctx.ifNestLevel--
940
941 }()
942 ctx.pushVarAssignments()
943 ctx.ifNestLevel++
944
945 ctx.pushReceiver(&block)
946 for ctx.hasNodes() {
947 node := ctx.getNode()
948 if ctx.handleSimpleStatement(node) {
949 continue
950 }
951 switch d := node.(type) {
952 case *mkparser.Directive:
953 switch d.Name {
954 case "else", "elifdef", "elifndef", "elifeq", "elifneq", "endif":
955 ctx.popReceiver()
956 ctx.receiver.newNode(&block)
957 ctx.backNode()
958 return
959 case "ifdef", "ifndef", "ifeq", "ifneq":
960 ctx.handleIfBlock(d)
961 default:
962 ctx.errorf(d, "unexpected directive %s", d.Name)
963 }
964 default:
965 ctx.errorf(node, "unexpected statement")
966 }
967 }
968 ctx.fatalError = fmt.Errorf("no matching endif for %s", check.Dump())
969 ctx.popReceiver()
970}
971
972func (ctx *parseContext) newIfDefinedNode(check *mkparser.Directive) (starlarkExpr, bool) {
973 if !check.Args.Const() {
974 return ctx.newBadExpr(check, "ifdef variable ref too complex: %s", check.Args.Dump()), false
975 }
976 v := ctx.addVariable(check.Args.Strings[0])
977 return &variableDefinedExpr{v}, true
978}
979
980func (ctx *parseContext) parseCondition(check *mkparser.Directive) starlarkNode {
981 switch check.Name {
982 case "ifdef", "ifndef", "elifdef", "elifndef":
983 v, ok := ctx.newIfDefinedNode(check)
984 if ok && strings.HasSuffix(check.Name, "ndef") {
985 v = &notExpr{v}
986 }
987 return &ifNode{
988 isElif: strings.HasPrefix(check.Name, "elif"),
989 expr: v,
990 }
991 case "ifeq", "ifneq", "elifeq", "elifneq":
992 return &ifNode{
993 isElif: strings.HasPrefix(check.Name, "elif"),
994 expr: ctx.parseCompare(check),
995 }
996 case "else":
997 return &elseNode{}
998 default:
999 panic(fmt.Errorf("%s: unknown directive: %s", ctx.script.mkFile, check.Dump()))
1000 }
1001}
1002
1003func (ctx *parseContext) newBadExpr(node mkparser.Node, text string, args ...interface{}) starlarkExpr {
1004 message := fmt.Sprintf(text, args...)
1005 if ctx.errorLogger != nil {
1006 ctx.errorLogger.NewError(text, node, args)
1007 }
1008 ctx.script.hasErrors = true
1009 return &badExpr{node, message}
1010}
1011
1012func (ctx *parseContext) parseCompare(cond *mkparser.Directive) starlarkExpr {
1013 // Strip outer parentheses
1014 mkArg := cloneMakeString(cond.Args)
1015 mkArg.Strings[0] = strings.TrimLeft(mkArg.Strings[0], "( ")
1016 n := len(mkArg.Strings)
1017 mkArg.Strings[n-1] = strings.TrimRight(mkArg.Strings[n-1], ") ")
1018 args := mkArg.Split(",")
1019 // TODO(asmundak): handle the case where the arguments are in quotes and space-separated
1020 if len(args) != 2 {
1021 return ctx.newBadExpr(cond, "ifeq/ifneq len(args) != 2 %s", cond.Dump())
1022 }
1023 args[0].TrimRightSpaces()
1024 args[1].TrimLeftSpaces()
1025
1026 isEq := !strings.HasSuffix(cond.Name, "neq")
1027 switch xLeft := ctx.parseMakeString(cond, args[0]).(type) {
1028 case *stringLiteralExpr, *variableRefExpr:
1029 switch xRight := ctx.parseMakeString(cond, args[1]).(type) {
1030 case *stringLiteralExpr, *variableRefExpr:
1031 return &eqExpr{left: xLeft, right: xRight, isEq: isEq}
1032 case *badExpr:
1033 return xRight
1034 default:
1035 expr, ok := ctx.parseCheckFunctionCallResult(cond, xLeft, args[1])
1036 if ok {
1037 return expr
1038 }
1039 return ctx.newBadExpr(cond, "right operand is too complex: %s", args[1].Dump())
1040 }
1041 case *badExpr:
1042 return xLeft
1043 default:
1044 switch xRight := ctx.parseMakeString(cond, args[1]).(type) {
1045 case *stringLiteralExpr, *variableRefExpr:
1046 expr, ok := ctx.parseCheckFunctionCallResult(cond, xRight, args[0])
1047 if ok {
1048 return expr
1049 }
1050 return ctx.newBadExpr(cond, "left operand is too complex: %s", args[0].Dump())
1051 case *badExpr:
1052 return xRight
1053 default:
1054 return ctx.newBadExpr(cond, "operands are too complex: (%s,%s)", args[0].Dump(), args[1].Dump())
1055 }
1056 }
1057}
1058
1059func (ctx *parseContext) parseCheckFunctionCallResult(directive *mkparser.Directive, xValue starlarkExpr,
1060 varArg *mkparser.MakeString) (starlarkExpr, bool) {
1061 mkSingleVar, ok := varArg.SingleVariable()
1062 if !ok {
1063 return nil, false
1064 }
1065 expr := ctx.parseReference(directive, mkSingleVar)
1066 negate := strings.HasSuffix(directive.Name, "neq")
1067 checkIsSomethingFunction := func(xCall *callExpr) starlarkExpr {
1068 s, ok := maybeString(xValue)
1069 if !ok || s != "true" {
1070 return ctx.newBadExpr(directive,
1071 fmt.Sprintf("the result of %s can be compared only to 'true'", xCall.name))
1072 }
1073 if len(xCall.args) < 1 {
1074 return ctx.newBadExpr(directive, "%s requires an argument", xCall.name)
1075 }
1076 return nil
1077 }
1078 switch x := expr.(type) {
1079 case *callExpr:
1080 switch x.name {
1081 case "filter":
1082 return ctx.parseCompareFilterFuncResult(directive, x, xValue, !negate), true
1083 case "filter-out":
1084 return ctx.parseCompareFilterFuncResult(directive, x, xValue, negate), true
1085 case "wildcard":
1086 return ctx.parseCompareWildcardFuncResult(directive, x, xValue, negate), true
1087 case "findstring":
1088 return ctx.parseCheckFindstringFuncResult(directive, x, xValue, negate), true
1089 case "strip":
1090 return ctx.parseCompareStripFuncResult(directive, x, xValue, negate), true
1091 case "is-board-platform":
1092 if xBad := checkIsSomethingFunction(x); xBad != nil {
1093 return xBad, true
1094 }
1095 return &eqExpr{
1096 left: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
1097 right: x.args[0],
1098 isEq: !negate,
1099 }, true
1100 case "is-board-platform-in-list":
1101 if xBad := checkIsSomethingFunction(x); xBad != nil {
1102 return xBad, true
1103 }
1104 return &inExpr{
1105 expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
1106 list: maybeConvertToStringList(x.args[0]),
1107 isNot: negate,
1108 }, true
1109 case "is-product-in-list":
1110 if xBad := checkIsSomethingFunction(x); xBad != nil {
1111 return xBad, true
1112 }
1113 return &inExpr{
1114 expr: &variableRefExpr{ctx.addVariable("TARGET_PRODUCT"), true},
1115 list: maybeConvertToStringList(x.args[0]),
1116 isNot: negate,
1117 }, true
1118 case "is-vendor-board-platform":
1119 if xBad := checkIsSomethingFunction(x); xBad != nil {
1120 return xBad, true
1121 }
1122 s, ok := maybeString(x.args[0])
1123 if !ok {
1124 return ctx.newBadExpr(directive, "cannot handle non-constant argument to is-vendor-board-platform"), true
1125 }
1126 return &inExpr{
1127 expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
1128 list: &variableRefExpr{ctx.addVariable(s + "_BOARD_PLATFORMS"), true},
1129 isNot: negate,
1130 }, true
1131 default:
1132 return ctx.newBadExpr(directive, "Unknown function in ifeq: %s", x.name), true
1133 }
1134 case *badExpr:
1135 return x, true
1136 default:
1137 return nil, false
1138 }
1139}
1140
1141func (ctx *parseContext) parseCompareFilterFuncResult(cond *mkparser.Directive,
1142 filterFuncCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
1143 // We handle:
Sasha Smundak0554d762021-07-08 18:26:12 -07001144 // * ifeq/ifneq (,$(filter v1 v2 ..., EXPR) becomes if EXPR not in/in ["v1", "v2", ...]
1145 // * ifeq/ifneq (,$(filter EXPR, v1 v2 ...) becomes if EXPR not in/in ["v1", "v2", ...]
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001146 // * ifeq/ifneq ($(VAR),$(filter $(VAR), v1 v2 ...) becomes if VAR in/not in ["v1", "v2"]
1147 // TODO(Asmundak): check the last case works for filter-out, too.
1148 xPattern := filterFuncCall.args[0]
1149 xText := filterFuncCall.args[1]
1150 var xInList *stringLiteralExpr
Sasha Smundak0554d762021-07-08 18:26:12 -07001151 var expr starlarkExpr
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001152 var ok bool
1153 switch x := xValue.(type) {
1154 case *stringLiteralExpr:
1155 if x.literal != "" {
1156 return ctx.newBadExpr(cond, "filter comparison to non-empty value: %s", xValue)
1157 }
1158 // Either pattern or text should be const, and the
1159 // non-const one should be varRefExpr
1160 if xInList, ok = xPattern.(*stringLiteralExpr); ok {
Sasha Smundak0554d762021-07-08 18:26:12 -07001161 expr = xText
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001162 } else if xInList, ok = xText.(*stringLiteralExpr); ok {
Sasha Smundak0554d762021-07-08 18:26:12 -07001163 expr = xPattern
1164 } else {
1165 return &callExpr{
1166 object: nil,
1167 name: filterFuncCall.name,
1168 args: filterFuncCall.args,
1169 returnType: starlarkTypeBool,
1170 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001171 }
1172 case *variableRefExpr:
1173 if v, ok := xPattern.(*variableRefExpr); ok {
1174 if xInList, ok = xText.(*stringLiteralExpr); ok && v.ref.name() == x.ref.name() {
1175 // ifeq/ifneq ($(VAR),$(filter $(VAR), v1 v2 ...), flip negate,
1176 // it's the opposite to what is done when comparing to empty.
Sasha Smundak0554d762021-07-08 18:26:12 -07001177 expr = xPattern
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001178 negate = !negate
1179 }
1180 }
1181 }
Sasha Smundak0554d762021-07-08 18:26:12 -07001182 if expr != nil && xInList != nil {
1183 slExpr := newStringListExpr(strings.Fields(xInList.literal))
1184 // Generate simpler code for the common cases:
1185 if expr.typ() == starlarkTypeList {
1186 if len(slExpr.items) == 1 {
1187 // Checking that a string belongs to list
1188 return &inExpr{isNot: negate, list: expr, expr: slExpr.items[0]}
1189 } else {
1190 // TODO(asmundak):
1191 panic("TBD")
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001192 }
Sasha Smundak0554d762021-07-08 18:26:12 -07001193 } else if len(slExpr.items) == 1 {
1194 return &eqExpr{left: expr, right: slExpr.items[0], isEq: !negate}
1195 } else {
1196 return &inExpr{isNot: negate, list: newStringListExpr(strings.Fields(xInList.literal)), expr: expr}
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001197 }
1198 }
1199 return ctx.newBadExpr(cond, "filter arguments are too complex: %s", cond.Dump())
1200}
1201
1202func (ctx *parseContext) parseCompareWildcardFuncResult(directive *mkparser.Directive,
1203 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001204 if !isEmptyString(xValue) {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001205 return ctx.newBadExpr(directive, "wildcard result can be compared only to empty: %s", xValue)
1206 }
1207 callFunc := wildcardExistsPhony
1208 if s, ok := xCall.args[0].(*stringLiteralExpr); ok && !strings.ContainsAny(s.literal, "*?{[") {
1209 callFunc = fileExistsPhony
1210 }
1211 var cc starlarkExpr = &callExpr{name: callFunc, args: xCall.args, returnType: starlarkTypeBool}
1212 if !negate {
1213 cc = &notExpr{cc}
1214 }
1215 return cc
1216}
1217
1218func (ctx *parseContext) parseCheckFindstringFuncResult(directive *mkparser.Directive,
1219 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
Sasha Smundak0554d762021-07-08 18:26:12 -07001220 if isEmptyString(xValue) {
1221 return &eqExpr{
1222 left: &callExpr{
1223 object: xCall.args[1],
1224 name: "find",
1225 args: []starlarkExpr{xCall.args[0]},
1226 returnType: starlarkTypeInt,
1227 },
1228 right: &intLiteralExpr{-1},
1229 isEq: !negate,
1230 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001231 }
Sasha Smundak0554d762021-07-08 18:26:12 -07001232 return ctx.newBadExpr(directive, "findstring result can be compared only to empty: %s", xValue)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001233}
1234
1235func (ctx *parseContext) parseCompareStripFuncResult(directive *mkparser.Directive,
1236 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
1237 if _, ok := xValue.(*stringLiteralExpr); !ok {
1238 return ctx.newBadExpr(directive, "strip result can be compared only to string: %s", xValue)
1239 }
1240 return &eqExpr{
1241 left: &callExpr{
1242 name: "strip",
1243 args: xCall.args,
1244 returnType: starlarkTypeString,
1245 },
1246 right: xValue, isEq: !negate}
1247}
1248
1249// parses $(...), returning an expression
1250func (ctx *parseContext) parseReference(node mkparser.Node, ref *mkparser.MakeString) starlarkExpr {
1251 ref.TrimLeftSpaces()
1252 ref.TrimRightSpaces()
1253 refDump := ref.Dump()
1254
1255 // Handle only the case where the first (or only) word is constant
1256 words := ref.SplitN(" ", 2)
1257 if !words[0].Const() {
1258 return ctx.newBadExpr(node, "reference is too complex: %s", refDump)
1259 }
1260
1261 // If it is a single word, it can be a simple variable
1262 // reference or a function call
1263 if len(words) == 1 {
1264 if isMakeControlFunc(refDump) || refDump == "shell" {
1265 return &callExpr{
1266 name: refDump,
1267 args: []starlarkExpr{&stringLiteralExpr{""}},
1268 returnType: starlarkTypeUnknown,
1269 }
1270 }
1271 if v := ctx.addVariable(refDump); v != nil {
1272 return &variableRefExpr{v, ctx.lastAssignment(v.name()) != nil}
1273 }
1274 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1275 }
1276
1277 expr := &callExpr{name: words[0].Dump(), returnType: starlarkTypeUnknown}
1278 args := words[1]
1279 args.TrimLeftSpaces()
1280 // Make control functions and shell need special treatment as everything
1281 // after the name is a single text argument
1282 if isMakeControlFunc(expr.name) || expr.name == "shell" {
1283 x := ctx.parseMakeString(node, args)
1284 if xBad, ok := x.(*badExpr); ok {
1285 return xBad
1286 }
1287 expr.args = []starlarkExpr{x}
1288 return expr
1289 }
1290 if expr.name == "call" {
1291 words = args.SplitN(",", 2)
1292 if words[0].Empty() || !words[0].Const() {
Sasha Smundakf2c9f8b2021-07-27 10:44:48 -07001293 return ctx.newBadExpr(node, "cannot handle %s", refDump)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001294 }
1295 expr.name = words[0].Dump()
1296 if len(words) < 2 {
Sasha Smundak6609ba72021-07-22 18:32:56 -07001297 args = &mkparser.MakeString{}
1298 } else {
1299 args = words[1]
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001300 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001301 }
1302 if kf, found := knownFunctions[expr.name]; found {
1303 expr.returnType = kf.returnType
1304 } else {
1305 return ctx.newBadExpr(node, "cannot handle invoking %s", expr.name)
1306 }
1307 switch expr.name {
1308 case "word":
1309 return ctx.parseWordFunc(node, args)
Sasha Smundak16e07732021-07-23 11:38:23 -07001310 case "firstword", "lastword":
1311 return ctx.parseFirstOrLastwordFunc(node, expr.name, args)
Sasha Smundak6609ba72021-07-22 18:32:56 -07001312 case "my-dir":
1313 return &variableRefExpr{ctx.addVariable("LOCAL_PATH"), true}
Sasha Smundak94b41c72021-07-12 18:30:42 -07001314 case "subst", "patsubst":
1315 return ctx.parseSubstFunc(node, expr.name, args)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001316 default:
1317 for _, arg := range args.Split(",") {
1318 arg.TrimLeftSpaces()
1319 arg.TrimRightSpaces()
1320 x := ctx.parseMakeString(node, arg)
1321 if xBad, ok := x.(*badExpr); ok {
1322 return xBad
1323 }
1324 expr.args = append(expr.args, x)
1325 }
1326 }
1327 return expr
1328}
1329
Sasha Smundak94b41c72021-07-12 18:30:42 -07001330func (ctx *parseContext) parseSubstFunc(node mkparser.Node, fname string, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001331 words := args.Split(",")
1332 if len(words) != 3 {
Sasha Smundak94b41c72021-07-12 18:30:42 -07001333 return ctx.newBadExpr(node, "%s function should have 3 arguments", fname)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001334 }
1335 if !words[0].Const() || !words[1].Const() {
Sasha Smundak94b41c72021-07-12 18:30:42 -07001336 return ctx.newBadExpr(node, "%s function's from and to arguments should be constant", fname)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001337 }
1338 from := words[0].Strings[0]
1339 to := words[1].Strings[0]
1340 words[2].TrimLeftSpaces()
1341 words[2].TrimRightSpaces()
1342 obj := ctx.parseMakeString(node, words[2])
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001343 typ := obj.typ()
Sasha Smundak94b41c72021-07-12 18:30:42 -07001344 if typ == starlarkTypeString && fname == "subst" {
1345 // Optimization: if it's $(subst from, to, string), emit string.replace(from, to)
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001346 return &callExpr{
1347 object: obj,
1348 name: "replace",
1349 args: []starlarkExpr{&stringLiteralExpr{from}, &stringLiteralExpr{to}},
1350 returnType: typ,
1351 }
1352 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001353 return &callExpr{
Sasha Smundak94b41c72021-07-12 18:30:42 -07001354 name: fname,
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001355 args: []starlarkExpr{&stringLiteralExpr{from}, &stringLiteralExpr{to}, obj},
1356 returnType: obj.typ(),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001357 }
1358}
1359
1360func (ctx *parseContext) parseWordFunc(node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1361 words := args.Split(",")
1362 if len(words) != 2 {
1363 return ctx.newBadExpr(node, "word function should have 2 arguments")
1364 }
1365 var index uint64 = 0
1366 if words[0].Const() {
1367 index, _ = strconv.ParseUint(strings.TrimSpace(words[0].Strings[0]), 10, 64)
1368 }
1369 if index < 1 {
1370 return ctx.newBadExpr(node, "word index should be constant positive integer")
1371 }
1372 words[1].TrimLeftSpaces()
1373 words[1].TrimRightSpaces()
1374 array := ctx.parseMakeString(node, words[1])
1375 if xBad, ok := array.(*badExpr); ok {
1376 return xBad
1377 }
1378 if array.typ() != starlarkTypeList {
1379 array = &callExpr{object: array, name: "split", returnType: starlarkTypeList}
1380 }
1381 return indexExpr{array, &intLiteralExpr{int(index - 1)}}
1382}
1383
Sasha Smundak16e07732021-07-23 11:38:23 -07001384func (ctx *parseContext) parseFirstOrLastwordFunc(node mkparser.Node, name string, args *mkparser.MakeString) starlarkExpr {
1385 arg := ctx.parseMakeString(node, args)
1386 if bad, ok := arg.(*badExpr); ok {
1387 return bad
1388 }
1389 index := &intLiteralExpr{0}
1390 if name == "lastword" {
1391 if v, ok := arg.(*variableRefExpr); ok && v.ref.name() == "MAKEFILE_LIST" {
1392 return &stringLiteralExpr{ctx.script.mkFile}
1393 }
1394 index.literal = -1
1395 }
1396 if arg.typ() == starlarkTypeList {
1397 return &indexExpr{arg, index}
1398 }
1399 return &indexExpr{&callExpr{object: arg, name: "split", returnType: starlarkTypeList}, index}
1400}
1401
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001402func (ctx *parseContext) parseMakeString(node mkparser.Node, mk *mkparser.MakeString) starlarkExpr {
1403 if mk.Const() {
1404 return &stringLiteralExpr{mk.Dump()}
1405 }
1406 if mkRef, ok := mk.SingleVariable(); ok {
1407 return ctx.parseReference(node, mkRef)
1408 }
1409 // If we reached here, it's neither string literal nor a simple variable,
1410 // we need a full-blown interpolation node that will generate
1411 // "a%b%c" % (X, Y) for a$(X)b$(Y)c
1412 xInterp := &interpolateExpr{args: make([]starlarkExpr, len(mk.Variables))}
1413 for i, ref := range mk.Variables {
1414 arg := ctx.parseReference(node, ref.Name)
1415 if x, ok := arg.(*badExpr); ok {
1416 return x
1417 }
1418 xInterp.args[i] = arg
1419 }
1420 xInterp.chunks = append(xInterp.chunks, mk.Strings...)
1421 return xInterp
1422}
1423
1424// Handles the statements whose treatment is the same in all contexts: comment,
1425// assignment, variable (which is a macro call in reality) and all constructs that
1426// do not handle in any context ('define directive and any unrecognized stuff).
1427// Return true if we handled it.
1428func (ctx *parseContext) handleSimpleStatement(node mkparser.Node) bool {
1429 handled := true
1430 switch x := node.(type) {
1431 case *mkparser.Comment:
1432 ctx.insertComment("#" + x.Comment)
1433 case *mkparser.Assignment:
1434 ctx.handleAssignment(x)
1435 case *mkparser.Variable:
1436 ctx.handleVariable(x)
1437 case *mkparser.Directive:
1438 switch x.Name {
1439 case "define":
1440 ctx.handleDefine(x)
1441 case "include", "-include":
1442 ctx.handleInclude(node, ctx.parseMakeString(node, x.Args), x.Name[0] != '-')
1443 default:
1444 handled = false
1445 }
1446 default:
1447 ctx.errorf(x, "unsupported line %s", x.Dump())
1448 }
1449 return handled
1450}
1451
1452func (ctx *parseContext) insertComment(s string) {
1453 ctx.receiver.newNode(&commentNode{strings.TrimSpace(s)})
1454}
1455
1456func (ctx *parseContext) carryAsComment(failedNode mkparser.Node) {
1457 for _, line := range strings.Split(failedNode.Dump(), "\n") {
1458 ctx.insertComment("# " + line)
1459 }
1460}
1461
1462// records that the given node failed to be converted and includes an explanatory message
1463func (ctx *parseContext) errorf(failedNode mkparser.Node, message string, args ...interface{}) {
1464 if ctx.errorLogger != nil {
1465 ctx.errorLogger.NewError(message, failedNode, args...)
1466 }
1467 message = fmt.Sprintf(message, args...)
1468 ctx.insertComment(fmt.Sprintf("# MK2RBC TRANSLATION ERROR: %s", message))
1469 ctx.carryAsComment(failedNode)
1470 ctx.script.hasErrors = true
1471}
1472
1473func (ctx *parseContext) wrapBadExpr(xBad *badExpr) {
1474 ctx.insertComment(fmt.Sprintf("# MK2RBC TRANSLATION ERROR: %s", xBad.message))
1475 ctx.carryAsComment(xBad.node)
1476}
1477
1478func (ctx *parseContext) loadedModulePath(path string) string {
1479 // During the transition to Roboleaf some of the product configuration files
1480 // will be converted and checked in while the others will be generated on the fly
1481 // and run. The runner (rbcrun application) accommodates this by allowing three
1482 // different ways to specify the loaded file location:
1483 // 1) load(":<file>",...) loads <file> from the same directory
1484 // 2) load("//path/relative/to/source/root:<file>", ...) loads <file> source tree
1485 // 3) load("/absolute/path/to/<file> absolute path
1486 // If the file being generated and the file it wants to load are in the same directory,
1487 // generate option 1.
1488 // Otherwise, if output directory is not specified, generate 2)
1489 // Finally, if output directory has been specified and the file being generated and
1490 // the file it wants to load from are in the different directories, generate 2) or 3):
1491 // * if the file being loaded exists in the source tree, generate 2)
1492 // * otherwise, generate 3)
1493 // Finally, figure out the loaded module path and name and create a node for it
1494 loadedModuleDir := filepath.Dir(path)
1495 base := filepath.Base(path)
1496 loadedModuleName := strings.TrimSuffix(base, filepath.Ext(base)) + ctx.outputSuffix
1497 if loadedModuleDir == filepath.Dir(ctx.script.mkFile) {
1498 return ":" + loadedModuleName
1499 }
1500 if ctx.outputDir == "" {
1501 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1502 }
1503 if _, err := os.Stat(filepath.Join(loadedModuleDir, loadedModuleName)); err == nil {
1504 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1505 }
1506 return filepath.Join(ctx.outputDir, loadedModuleDir, loadedModuleName)
1507}
1508
Sasha Smundak3deb9682021-07-26 18:42:25 -07001509func (ctx *parseContext) addSoongNamespace(ns string) {
1510 if _, ok := ctx.soongNamespaces[ns]; ok {
1511 return
1512 }
1513 ctx.soongNamespaces[ns] = make(map[string]bool)
1514}
1515
1516func (ctx *parseContext) hasSoongNamespace(name string) bool {
1517 _, ok := ctx.soongNamespaces[name]
1518 return ok
1519}
1520
1521func (ctx *parseContext) updateSoongNamespace(replace bool, namespaceName string, varNames []string) {
1522 ctx.addSoongNamespace(namespaceName)
1523 vars := ctx.soongNamespaces[namespaceName]
1524 if replace {
1525 vars = make(map[string]bool)
1526 ctx.soongNamespaces[namespaceName] = vars
1527 }
1528 for _, v := range varNames {
1529 vars[v] = true
1530 }
1531}
1532
1533func (ctx *parseContext) hasNamespaceVar(namespaceName string, varName string) bool {
1534 vars, ok := ctx.soongNamespaces[namespaceName]
1535 if ok {
1536 _, ok = vars[varName]
1537 }
1538 return ok
1539}
1540
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001541func (ss *StarlarkScript) String() string {
1542 return NewGenerateContext(ss).emit()
1543}
1544
1545func (ss *StarlarkScript) SubConfigFiles() []string {
Sasha Smundak6609ba72021-07-22 18:32:56 -07001546
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001547 var subs []string
1548 for _, src := range ss.inherited {
1549 subs = append(subs, src.originalPath)
1550 }
1551 return subs
1552}
1553
1554func (ss *StarlarkScript) HasErrors() bool {
1555 return ss.hasErrors
1556}
1557
1558// Convert reads and parses a makefile. If successful, parsed tree
1559// is returned and then can be passed to String() to get the generated
1560// Starlark file.
1561func Convert(req Request) (*StarlarkScript, error) {
1562 reader := req.Reader
1563 if reader == nil {
1564 mkContents, err := ioutil.ReadFile(req.MkFile)
1565 if err != nil {
1566 return nil, err
1567 }
1568 reader = bytes.NewBuffer(mkContents)
1569 }
1570 parser := mkparser.NewParser(req.MkFile, reader)
1571 nodes, errs := parser.Parse()
1572 if len(errs) > 0 {
1573 for _, e := range errs {
1574 fmt.Fprintln(os.Stderr, "ERROR:", e)
1575 }
1576 return nil, fmt.Errorf("bad makefile %s", req.MkFile)
1577 }
1578 starScript := &StarlarkScript{
1579 moduleName: moduleNameForFile(req.MkFile),
1580 mkFile: req.MkFile,
1581 topDir: req.RootDir,
1582 traceCalls: req.TraceCalls,
1583 warnPartialSuccess: req.WarnPartialSuccess,
Sasha Smundak6609ba72021-07-22 18:32:56 -07001584 sourceFS: req.SourceFS,
1585 makefileFinder: req.MakefileFinder,
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001586 }
1587 ctx := newParseContext(starScript, nodes)
1588 ctx.outputSuffix = req.OutputSuffix
1589 ctx.outputDir = req.OutputDir
1590 ctx.errorLogger = req.ErrorLogger
1591 if len(req.TracedVariables) > 0 {
1592 ctx.tracedVariables = make(map[string]bool)
1593 for _, v := range req.TracedVariables {
1594 ctx.tracedVariables[v] = true
1595 }
1596 }
1597 ctx.pushReceiver(starScript)
1598 for ctx.hasNodes() && ctx.fatalError == nil {
1599 node := ctx.getNode()
1600 if ctx.handleSimpleStatement(node) {
1601 continue
1602 }
1603 switch x := node.(type) {
1604 case *mkparser.Directive:
1605 switch x.Name {
1606 case "ifeq", "ifneq", "ifdef", "ifndef":
1607 ctx.handleIfBlock(x)
1608 default:
1609 ctx.errorf(x, "unexpected directive %s", x.Name)
1610 }
1611 default:
1612 ctx.errorf(x, "unsupported line")
1613 }
1614 }
1615 if ctx.fatalError != nil {
1616 return nil, ctx.fatalError
1617 }
1618 return starScript, nil
1619}
1620
1621func Launcher(path, name string) string {
1622 var buf bytes.Buffer
1623 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
1624 fmt.Fprintf(&buf, "load(%q, \"init\")\n", path)
1625 fmt.Fprintf(&buf, "g, config = %s(%q, init)\n", cfnMain, name)
1626 fmt.Fprintf(&buf, "%s(g, config)\n", cfnPrintVars)
1627 return buf.String()
1628}
1629
1630func MakePath2ModuleName(mkPath string) string {
1631 return strings.TrimSuffix(mkPath, filepath.Ext(mkPath))
1632}