blob: 0e9e6fe325bf9f26c8d8d156cb72e049c97f64d9 [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"
30 "io/ioutil"
31 "os"
32 "path/filepath"
33 "regexp"
34 "strconv"
35 "strings"
36 "text/scanner"
37
38 mkparser "android/soong/androidmk/parser"
39)
40
41const (
42 baseUri = "//build/make/core:product_config.rbc"
43 // The name of the struct exported by the product_config.rbc
44 // that contains the functions and variables available to
45 // product configuration Starlark files.
46 baseName = "rblf"
47
48 // And here are the functions and variables:
49 cfnGetCfg = baseName + ".cfg"
50 cfnMain = baseName + ".product_configuration"
51 cfnPrintVars = baseName + ".printvars"
52 cfnWarning = baseName + ".warning"
53 cfnLocalAppend = baseName + ".local_append"
54 cfnLocalSetDefault = baseName + ".local_set_default"
55 cfnInherit = baseName + ".inherit"
56 cfnSetListDefault = baseName + ".setdefault"
57)
58
59const (
60 // Phony makefile functions, they are eventually rewritten
61 // according to knownFunctions map
62 fileExistsPhony = "$file_exists"
63 wildcardExistsPhony = "$wildcard_exists"
64)
65
66const (
67 callLoadAlways = "inherit-product"
68 callLoadIf = "inherit-product-if-exists"
69)
70
71var knownFunctions = map[string]struct {
72 // The name of the runtime function this function call in makefiles maps to.
73 // If it starts with !, then this makefile function call is rewritten to
74 // something else.
75 runtimeName string
76 returnType starlarkType
77}{
78 fileExistsPhony: {baseName + ".file_exists", starlarkTypeBool},
79 wildcardExistsPhony: {baseName + ".file_wildcard_exists", starlarkTypeBool},
80 "add-to-product-copy-files-if-exists": {baseName + ".copy_if_exists", starlarkTypeList},
81 "addprefix": {baseName + ".addprefix", starlarkTypeList},
82 "addsuffix": {baseName + ".addsuffix", starlarkTypeList},
83 "enforce-product-packages-exist": {baseName + ".enforce_product_packages_exist", starlarkTypeVoid},
84 "error": {baseName + ".mkerror", starlarkTypeVoid},
85 "findstring": {"!findstring", starlarkTypeInt},
86 "find-copy-subdir-files": {baseName + ".find_and_copy", starlarkTypeList},
87 "filter": {baseName + ".filter", starlarkTypeList},
88 "filter-out": {baseName + ".filter_out", starlarkTypeList},
89 "info": {baseName + ".mkinfo", starlarkTypeVoid},
90 "is-board-platform": {"!is-board-platform", starlarkTypeBool},
91 "is-board-platform-in-list": {"!is-board-platform-in-list", starlarkTypeBool},
92 "is-product-in-list": {"!is-product-in-list", starlarkTypeBool},
93 "is-vendor-board-platform": {"!is-vendor-board-platform", starlarkTypeBool},
94 callLoadAlways: {"!inherit-product", starlarkTypeVoid},
95 callLoadIf: {"!inherit-product-if-exists", starlarkTypeVoid},
Sasha Smundak94b41c72021-07-12 18:30:42 -070096 "patsubst": {baseName + ".mkpatsubst", starlarkTypeString},
Sasha Smundakb051c4e2020-11-05 20:45:07 -080097 "produce_copy_files": {baseName + ".produce_copy_files", starlarkTypeList},
98 "require-artifacts-in-path": {baseName + ".require_artifacts_in_path", starlarkTypeVoid},
99 "require-artifacts-in-path-relaxed": {baseName + ".require_artifacts_in_path_relaxed", starlarkTypeVoid},
100 // TODO(asmundak): remove it once all calls are removed from configuration makefiles. see b/183161002
101 "shell": {baseName + ".shell", starlarkTypeString},
102 "strip": {baseName + ".mkstrip", starlarkTypeString},
Sasha Smundak9d011ab2021-07-09 16:00:57 -0700103 "subst": {baseName + ".mksubst", starlarkTypeString},
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800104 "warning": {baseName + ".mkwarning", starlarkTypeVoid},
105 "word": {baseName + "!word", starlarkTypeString},
106 "wildcard": {baseName + ".expand_wildcard", starlarkTypeList},
107}
108
109var builtinFuncRex = regexp.MustCompile(
110 "^(addprefix|addsuffix|abspath|and|basename|call|dir|error|eval" +
111 "|flavor|foreach|file|filter|filter-out|findstring|firstword|guile" +
112 "|if|info|join|lastword|notdir|or|origin|patsubst|realpath" +
113 "|shell|sort|strip|subst|suffix|value|warning|word|wordlist|words" +
114 "|wildcard)")
115
116// Conversion request parameters
117type Request struct {
118 MkFile string // file to convert
119 Reader io.Reader // if set, read input from this stream instead
120 RootDir string // root directory path used to resolve included files
121 OutputSuffix string // generated Starlark files suffix
122 OutputDir string // if set, root of the output hierarchy
123 ErrorLogger ErrorMonitorCB
124 TracedVariables []string // trace assignment to these variables
125 TraceCalls bool
126 WarnPartialSuccess bool
127}
128
129// An error sink allowing to gather error statistics.
130// NewError is called on every error encountered during processing.
131type ErrorMonitorCB interface {
132 NewError(s string, node mkparser.Node, args ...interface{})
133}
134
135// Derives module name for a given file. It is base name
136// (file name without suffix), with some characters replaced to make it a Starlark identifier
137func moduleNameForFile(mkFile string) string {
138 base := strings.TrimSuffix(filepath.Base(mkFile), filepath.Ext(mkFile))
139 // TODO(asmundak): what else can be in the product file names?
140 return strings.ReplaceAll(base, "-", "_")
141}
142
143func cloneMakeString(mkString *mkparser.MakeString) *mkparser.MakeString {
144 r := &mkparser.MakeString{StringPos: mkString.StringPos}
145 r.Strings = append(r.Strings, mkString.Strings...)
146 r.Variables = append(r.Variables, mkString.Variables...)
147 return r
148}
149
150func isMakeControlFunc(s string) bool {
151 return s == "error" || s == "warning" || s == "info"
152}
153
154// Starlark output generation context
155type generationContext struct {
156 buf strings.Builder
157 starScript *StarlarkScript
158 indentLevel int
159 inAssignment bool
160 tracedCount int
161}
162
163func NewGenerateContext(ss *StarlarkScript) *generationContext {
164 return &generationContext{starScript: ss}
165}
166
167// emit returns generated script
168func (gctx *generationContext) emit() string {
169 ss := gctx.starScript
170
171 // The emitted code has the following layout:
172 // <initial comments>
173 // preamble, i.e.,
174 // load statement for the runtime support
175 // load statement for each unique submodule pulled in by this one
176 // def init(g, handle):
177 // cfg = rblf.cfg(handle)
178 // <statements>
179 // <warning if conversion was not clean>
180
181 iNode := len(ss.nodes)
182 for i, node := range ss.nodes {
183 if _, ok := node.(*commentNode); !ok {
184 iNode = i
185 break
186 }
187 node.emit(gctx)
188 }
189
190 gctx.emitPreamble()
191
192 gctx.newLine()
193 // The arguments passed to the init function are the global dictionary
194 // ('g') and the product configuration dictionary ('cfg')
195 gctx.write("def init(g, handle):")
196 gctx.indentLevel++
197 if gctx.starScript.traceCalls {
198 gctx.newLine()
199 gctx.writef(`print(">%s")`, gctx.starScript.mkFile)
200 }
201 gctx.newLine()
202 gctx.writef("cfg = %s(handle)", cfnGetCfg)
203 for _, node := range ss.nodes[iNode:] {
204 node.emit(gctx)
205 }
206
207 if ss.hasErrors && ss.warnPartialSuccess {
208 gctx.newLine()
209 gctx.writef("%s(%q, %q)", cfnWarning, filepath.Base(ss.mkFile), "partially successful conversion")
210 }
211 if gctx.starScript.traceCalls {
212 gctx.newLine()
213 gctx.writef(`print("<%s")`, gctx.starScript.mkFile)
214 }
215 gctx.indentLevel--
216 gctx.write("\n")
217 return gctx.buf.String()
218}
219
220func (gctx *generationContext) emitPreamble() {
221 gctx.newLine()
222 gctx.writef("load(%q, %q)", baseUri, baseName)
223 // Emit exactly one load statement for each URI.
224 loadedSubConfigs := make(map[string]string)
225 for _, sc := range gctx.starScript.inherited {
226 uri := sc.path
227 if m, ok := loadedSubConfigs[uri]; ok {
228 // No need to emit load statement, but fix module name.
229 sc.moduleLocalName = m
230 continue
231 }
232 if !sc.loadAlways {
233 uri += "|init"
234 }
235 gctx.newLine()
236 gctx.writef("load(%q, %s = \"init\")", uri, sc.entryName())
237 loadedSubConfigs[uri] = sc.moduleLocalName
238 }
239 gctx.write("\n")
240}
241
242func (gctx *generationContext) emitPass() {
243 gctx.newLine()
244 gctx.write("pass")
245}
246
247func (gctx *generationContext) write(ss ...string) {
248 for _, s := range ss {
249 gctx.buf.WriteString(s)
250 }
251}
252
253func (gctx *generationContext) writef(format string, args ...interface{}) {
254 gctx.write(fmt.Sprintf(format, args...))
255}
256
257func (gctx *generationContext) newLine() {
258 if gctx.buf.Len() == 0 {
259 return
260 }
261 gctx.write("\n")
262 gctx.writef("%*s", 2*gctx.indentLevel, "")
263}
264
265type knownVariable struct {
266 name string
267 class varClass
268 valueType starlarkType
269}
270
271type knownVariables map[string]knownVariable
272
273func (pcv knownVariables) NewVariable(name string, varClass varClass, valueType starlarkType) {
274 v, exists := pcv[name]
275 if !exists {
276 pcv[name] = knownVariable{name, varClass, valueType}
277 return
278 }
279 // Conflict resolution:
280 // * config class trumps everything
281 // * any type trumps unknown type
282 match := varClass == v.class
283 if !match {
284 if varClass == VarClassConfig {
285 v.class = VarClassConfig
286 match = true
287 } else if v.class == VarClassConfig {
288 match = true
289 }
290 }
291 if valueType != v.valueType {
292 if valueType != starlarkTypeUnknown {
293 if v.valueType == starlarkTypeUnknown {
294 v.valueType = valueType
295 } else {
296 match = false
297 }
298 }
299 }
300 if !match {
301 fmt.Fprintf(os.Stderr, "cannot redefine %s as %v/%v (already defined as %v/%v)\n",
302 name, varClass, valueType, v.class, v.valueType)
303 }
304}
305
306// All known product variables.
307var KnownVariables = make(knownVariables)
308
309func init() {
310 for _, kv := range []string{
311 // Kernel-related variables that we know are lists.
312 "BOARD_VENDOR_KERNEL_MODULES",
313 "BOARD_VENDOR_RAMDISK_KERNEL_MODULES",
314 "BOARD_VENDOR_RAMDISK_KERNEL_MODULES_LOAD",
315 "BOARD_RECOVERY_KERNEL_MODULES",
316 // Other variables we knwo are lists
317 "ART_APEX_JARS",
318 } {
319 KnownVariables.NewVariable(kv, VarClassSoong, starlarkTypeList)
320 }
321}
322
323type nodeReceiver interface {
324 newNode(node starlarkNode)
325}
326
327// Information about the generated Starlark script.
328type StarlarkScript struct {
329 mkFile string
330 moduleName string
331 mkPos scanner.Position
332 nodes []starlarkNode
333 inherited []*inheritedModule
334 hasErrors bool
335 topDir string
336 traceCalls bool // print enter/exit each init function
337 warnPartialSuccess bool
338}
339
340func (ss *StarlarkScript) newNode(node starlarkNode) {
341 ss.nodes = append(ss.nodes, node)
342}
343
344// varAssignmentScope points to the last assignment for each variable
345// in the current block. It is used during the parsing to chain
346// the assignments to a variable together.
347type varAssignmentScope struct {
348 outer *varAssignmentScope
349 vars map[string]*assignmentNode
350}
351
352// parseContext holds the script we are generating and all the ephemeral data
353// needed during the parsing.
354type parseContext struct {
355 script *StarlarkScript
356 nodes []mkparser.Node // Makefile as parsed by mkparser
357 currentNodeIndex int // Node in it we are processing
358 ifNestLevel int
359 moduleNameCount map[string]int // count of imported modules with given basename
360 fatalError error
361 builtinMakeVars map[string]starlarkExpr
362 outputSuffix string
363 errorLogger ErrorMonitorCB
364 tracedVariables map[string]bool // variables to be traced in the generated script
365 variables map[string]variable
366 varAssignments *varAssignmentScope
367 receiver nodeReceiver // receptacle for the generated starlarkNode's
368 receiverStack []nodeReceiver
369 outputDir string
370}
371
372func newParseContext(ss *StarlarkScript, nodes []mkparser.Node) *parseContext {
373 predefined := []struct{ name, value string }{
374 {"SRC_TARGET_DIR", filepath.Join("build", "make", "target")},
375 {"LOCAL_PATH", filepath.Dir(ss.mkFile)},
376 {"TOPDIR", ss.topDir},
377 // TODO(asmundak): maybe read it from build/make/core/envsetup.mk?
378 {"TARGET_COPY_OUT_SYSTEM", "system"},
379 {"TARGET_COPY_OUT_SYSTEM_OTHER", "system_other"},
380 {"TARGET_COPY_OUT_DATA", "data"},
381 {"TARGET_COPY_OUT_ASAN", filepath.Join("data", "asan")},
382 {"TARGET_COPY_OUT_OEM", "oem"},
383 {"TARGET_COPY_OUT_RAMDISK", "ramdisk"},
384 {"TARGET_COPY_OUT_DEBUG_RAMDISK", "debug_ramdisk"},
385 {"TARGET_COPY_OUT_VENDOR_DEBUG_RAMDISK", "vendor_debug_ramdisk"},
386 {"TARGET_COPY_OUT_TEST_HARNESS_RAMDISK", "test_harness_ramdisk"},
387 {"TARGET_COPY_OUT_ROOT", "root"},
388 {"TARGET_COPY_OUT_RECOVERY", "recovery"},
389 {"TARGET_COPY_OUT_VENDOR", "||VENDOR-PATH-PH||"},
390 {"TARGET_COPY_OUT_VENDOR_RAMDISK", "vendor_ramdisk"},
391 {"TARGET_COPY_OUT_PRODUCT", "||PRODUCT-PATH-PH||"},
392 {"TARGET_COPY_OUT_PRODUCT_SERVICES", "||PRODUCT-PATH-PH||"},
393 {"TARGET_COPY_OUT_SYSTEM_EXT", "||SYSTEM_EXT-PATH-PH||"},
394 {"TARGET_COPY_OUT_ODM", "||ODM-PATH-PH||"},
395 {"TARGET_COPY_OUT_VENDOR_DLKM", "||VENDOR_DLKM-PATH-PH||"},
396 {"TARGET_COPY_OUT_ODM_DLKM", "||ODM_DLKM-PATH-PH||"},
397 // TODO(asmundak): to process internal config files, we need the following variables:
398 // BOARD_CONFIG_VENDOR_PATH
399 // TARGET_VENDOR
400 // target_base_product
401 //
402
403 // the following utility variables are set in build/make/common/core.mk:
404 {"empty", ""},
405 {"space", " "},
406 {"comma", ","},
407 {"newline", "\n"},
408 {"pound", "#"},
409 {"backslash", "\\"},
410 }
411 ctx := &parseContext{
412 script: ss,
413 nodes: nodes,
414 currentNodeIndex: 0,
415 ifNestLevel: 0,
416 moduleNameCount: make(map[string]int),
417 builtinMakeVars: map[string]starlarkExpr{},
418 variables: make(map[string]variable),
419 }
420 ctx.pushVarAssignments()
421 for _, item := range predefined {
422 ctx.variables[item.name] = &predefinedVariable{
423 baseVariable: baseVariable{nam: item.name, typ: starlarkTypeString},
424 value: &stringLiteralExpr{item.value},
425 }
426 }
427
428 return ctx
429}
430
431func (ctx *parseContext) lastAssignment(name string) *assignmentNode {
432 for va := ctx.varAssignments; va != nil; va = va.outer {
433 if v, ok := va.vars[name]; ok {
434 return v
435 }
436 }
437 return nil
438}
439
440func (ctx *parseContext) setLastAssignment(name string, asgn *assignmentNode) {
441 ctx.varAssignments.vars[name] = asgn
442}
443
444func (ctx *parseContext) pushVarAssignments() {
445 va := &varAssignmentScope{
446 outer: ctx.varAssignments,
447 vars: make(map[string]*assignmentNode),
448 }
449 ctx.varAssignments = va
450}
451
452func (ctx *parseContext) popVarAssignments() {
453 ctx.varAssignments = ctx.varAssignments.outer
454}
455
456func (ctx *parseContext) pushReceiver(rcv nodeReceiver) {
457 ctx.receiverStack = append(ctx.receiverStack, ctx.receiver)
458 ctx.receiver = rcv
459}
460
461func (ctx *parseContext) popReceiver() {
462 last := len(ctx.receiverStack) - 1
463 if last < 0 {
464 panic(fmt.Errorf("popReceiver: receiver stack empty"))
465 }
466 ctx.receiver = ctx.receiverStack[last]
467 ctx.receiverStack = ctx.receiverStack[0:last]
468}
469
470func (ctx *parseContext) hasNodes() bool {
471 return ctx.currentNodeIndex < len(ctx.nodes)
472}
473
474func (ctx *parseContext) getNode() mkparser.Node {
475 if !ctx.hasNodes() {
476 return nil
477 }
478 node := ctx.nodes[ctx.currentNodeIndex]
479 ctx.currentNodeIndex++
480 return node
481}
482
483func (ctx *parseContext) backNode() {
484 if ctx.currentNodeIndex <= 0 {
485 panic("Cannot back off")
486 }
487 ctx.currentNodeIndex--
488}
489
490func (ctx *parseContext) handleAssignment(a *mkparser.Assignment) {
491 // Handle only simple variables
492 if !a.Name.Const() {
493 ctx.errorf(a, "Only simple variables are handled")
494 return
495 }
496 name := a.Name.Strings[0]
497 lhs := ctx.addVariable(name)
498 if lhs == nil {
499 ctx.errorf(a, "unknown variable %s", name)
500 return
501 }
502 _, isTraced := ctx.tracedVariables[name]
503 asgn := &assignmentNode{lhs: lhs, mkValue: a.Value, isTraced: isTraced}
504 if lhs.valueType() == starlarkTypeUnknown {
505 // Try to divine variable type from the RHS
506 asgn.value = ctx.parseMakeString(a, a.Value)
507 if xBad, ok := asgn.value.(*badExpr); ok {
508 ctx.wrapBadExpr(xBad)
509 return
510 }
511 inferred_type := asgn.value.typ()
512 if inferred_type != starlarkTypeUnknown {
Sasha Smundak9d011ab2021-07-09 16:00:57 -0700513 lhs.setValueType(inferred_type)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800514 }
515 }
516 if lhs.valueType() == starlarkTypeList {
517 xConcat := ctx.buildConcatExpr(a)
518 if xConcat == nil {
519 return
520 }
521 switch len(xConcat.items) {
522 case 0:
523 asgn.value = &listExpr{}
524 case 1:
525 asgn.value = xConcat.items[0]
526 default:
527 asgn.value = xConcat
528 }
529 } else {
530 asgn.value = ctx.parseMakeString(a, a.Value)
531 if xBad, ok := asgn.value.(*badExpr); ok {
532 ctx.wrapBadExpr(xBad)
533 return
534 }
535 }
536
537 // TODO(asmundak): move evaluation to a separate pass
538 asgn.value, _ = asgn.value.eval(ctx.builtinMakeVars)
539
540 asgn.previous = ctx.lastAssignment(name)
541 ctx.setLastAssignment(name, asgn)
542 switch a.Type {
543 case "=", ":=":
544 asgn.flavor = asgnSet
545 case "+=":
546 if asgn.previous == nil && !asgn.lhs.isPreset() {
547 asgn.flavor = asgnMaybeAppend
548 } else {
549 asgn.flavor = asgnAppend
550 }
551 case "?=":
552 asgn.flavor = asgnMaybeSet
553 default:
554 panic(fmt.Errorf("unexpected assignment type %s", a.Type))
555 }
556
557 ctx.receiver.newNode(asgn)
558}
559
560func (ctx *parseContext) buildConcatExpr(a *mkparser.Assignment) *concatExpr {
561 xConcat := &concatExpr{}
562 var xItemList *listExpr
563 addToItemList := func(x ...starlarkExpr) {
564 if xItemList == nil {
565 xItemList = &listExpr{[]starlarkExpr{}}
566 }
567 xItemList.items = append(xItemList.items, x...)
568 }
569 finishItemList := func() {
570 if xItemList != nil {
571 xConcat.items = append(xConcat.items, xItemList)
572 xItemList = nil
573 }
574 }
575
576 items := a.Value.Words()
577 for _, item := range items {
578 // A function call in RHS is supposed to return a list, all other item
579 // expressions return individual elements.
580 switch x := ctx.parseMakeString(a, item).(type) {
581 case *badExpr:
582 ctx.wrapBadExpr(x)
583 return nil
584 case *stringLiteralExpr:
585 addToItemList(maybeConvertToStringList(x).(*listExpr).items...)
586 default:
587 switch x.typ() {
588 case starlarkTypeList:
589 finishItemList()
590 xConcat.items = append(xConcat.items, x)
591 case starlarkTypeString:
592 finishItemList()
593 xConcat.items = append(xConcat.items, &callExpr{
594 object: x,
595 name: "split",
596 args: nil,
597 returnType: starlarkTypeList,
598 })
599 default:
600 addToItemList(x)
601 }
602 }
603 }
604 if xItemList != nil {
605 xConcat.items = append(xConcat.items, xItemList)
606 }
607 return xConcat
608}
609
610func (ctx *parseContext) newInheritedModule(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) *inheritedModule {
611 var path string
612 x, _ := pathExpr.eval(ctx.builtinMakeVars)
613 s, ok := x.(*stringLiteralExpr)
614 if !ok {
615 ctx.errorf(v, "inherit-product/include argument is too complex")
616 return nil
617 }
618
619 path = s.literal
620 moduleName := moduleNameForFile(path)
621 moduleLocalName := "_" + moduleName
622 n, found := ctx.moduleNameCount[moduleName]
623 if found {
624 moduleLocalName += fmt.Sprintf("%d", n)
625 }
626 ctx.moduleNameCount[moduleName] = n + 1
627 ln := &inheritedModule{
628 path: ctx.loadedModulePath(path),
629 originalPath: path,
630 moduleName: moduleName,
631 moduleLocalName: moduleLocalName,
632 loadAlways: loadAlways,
633 }
634 ctx.script.inherited = append(ctx.script.inherited, ln)
635 return ln
636}
637
638func (ctx *parseContext) handleInheritModule(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) {
639 if im := ctx.newInheritedModule(v, pathExpr, loadAlways); im != nil {
640 ctx.receiver.newNode(&inheritNode{im})
641 }
642}
643
644func (ctx *parseContext) handleInclude(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) {
645 if ln := ctx.newInheritedModule(v, pathExpr, loadAlways); ln != nil {
646 ctx.receiver.newNode(&includeNode{ln})
647 }
648}
649
650func (ctx *parseContext) handleVariable(v *mkparser.Variable) {
651 // Handle:
652 // $(call inherit-product,...)
653 // $(call inherit-product-if-exists,...)
654 // $(info xxx)
655 // $(warning xxx)
656 // $(error xxx)
657 expr := ctx.parseReference(v, v.Name)
658 switch x := expr.(type) {
659 case *callExpr:
660 if x.name == callLoadAlways || x.name == callLoadIf {
661 ctx.handleInheritModule(v, x.args[0], x.name == callLoadAlways)
662 } else if isMakeControlFunc(x.name) {
663 // File name is the first argument
664 args := []starlarkExpr{
665 &stringLiteralExpr{ctx.script.mkFile},
666 x.args[0],
667 }
668 ctx.receiver.newNode(&exprNode{
669 &callExpr{name: x.name, args: args, returnType: starlarkTypeUnknown},
670 })
671 } else {
672 ctx.receiver.newNode(&exprNode{expr})
673 }
674 case *badExpr:
675 ctx.wrapBadExpr(x)
676 return
677 default:
678 ctx.errorf(v, "cannot handle %s", v.Dump())
679 return
680 }
681}
682
683func (ctx *parseContext) handleDefine(directive *mkparser.Directive) {
684 tokens := strings.Fields(directive.Args.Strings[0])
685 ctx.errorf(directive, "define is not supported: %s", tokens[0])
686}
687
688func (ctx *parseContext) handleIfBlock(ifDirective *mkparser.Directive) {
689 ssSwitch := &switchNode{}
690 ctx.pushReceiver(ssSwitch)
691 for ctx.processBranch(ifDirective); ctx.hasNodes() && ctx.fatalError == nil; {
692 node := ctx.getNode()
693 switch x := node.(type) {
694 case *mkparser.Directive:
695 switch x.Name {
696 case "else", "elifdef", "elifndef", "elifeq", "elifneq":
697 ctx.processBranch(x)
698 case "endif":
699 ctx.popReceiver()
700 ctx.receiver.newNode(ssSwitch)
701 return
702 default:
703 ctx.errorf(node, "unexpected directive %s", x.Name)
704 }
705 default:
706 ctx.errorf(ifDirective, "unexpected statement")
707 }
708 }
709 if ctx.fatalError == nil {
710 ctx.fatalError = fmt.Errorf("no matching endif for %s", ifDirective.Dump())
711 }
712 ctx.popReceiver()
713}
714
715// processBranch processes a single branch (if/elseif/else) until the next directive
716// on the same level.
717func (ctx *parseContext) processBranch(check *mkparser.Directive) {
718 block := switchCase{gate: ctx.parseCondition(check)}
719 defer func() {
720 ctx.popVarAssignments()
721 ctx.ifNestLevel--
722
723 }()
724 ctx.pushVarAssignments()
725 ctx.ifNestLevel++
726
727 ctx.pushReceiver(&block)
728 for ctx.hasNodes() {
729 node := ctx.getNode()
730 if ctx.handleSimpleStatement(node) {
731 continue
732 }
733 switch d := node.(type) {
734 case *mkparser.Directive:
735 switch d.Name {
736 case "else", "elifdef", "elifndef", "elifeq", "elifneq", "endif":
737 ctx.popReceiver()
738 ctx.receiver.newNode(&block)
739 ctx.backNode()
740 return
741 case "ifdef", "ifndef", "ifeq", "ifneq":
742 ctx.handleIfBlock(d)
743 default:
744 ctx.errorf(d, "unexpected directive %s", d.Name)
745 }
746 default:
747 ctx.errorf(node, "unexpected statement")
748 }
749 }
750 ctx.fatalError = fmt.Errorf("no matching endif for %s", check.Dump())
751 ctx.popReceiver()
752}
753
754func (ctx *parseContext) newIfDefinedNode(check *mkparser.Directive) (starlarkExpr, bool) {
755 if !check.Args.Const() {
756 return ctx.newBadExpr(check, "ifdef variable ref too complex: %s", check.Args.Dump()), false
757 }
758 v := ctx.addVariable(check.Args.Strings[0])
759 return &variableDefinedExpr{v}, true
760}
761
762func (ctx *parseContext) parseCondition(check *mkparser.Directive) starlarkNode {
763 switch check.Name {
764 case "ifdef", "ifndef", "elifdef", "elifndef":
765 v, ok := ctx.newIfDefinedNode(check)
766 if ok && strings.HasSuffix(check.Name, "ndef") {
767 v = &notExpr{v}
768 }
769 return &ifNode{
770 isElif: strings.HasPrefix(check.Name, "elif"),
771 expr: v,
772 }
773 case "ifeq", "ifneq", "elifeq", "elifneq":
774 return &ifNode{
775 isElif: strings.HasPrefix(check.Name, "elif"),
776 expr: ctx.parseCompare(check),
777 }
778 case "else":
779 return &elseNode{}
780 default:
781 panic(fmt.Errorf("%s: unknown directive: %s", ctx.script.mkFile, check.Dump()))
782 }
783}
784
785func (ctx *parseContext) newBadExpr(node mkparser.Node, text string, args ...interface{}) starlarkExpr {
786 message := fmt.Sprintf(text, args...)
787 if ctx.errorLogger != nil {
788 ctx.errorLogger.NewError(text, node, args)
789 }
790 ctx.script.hasErrors = true
791 return &badExpr{node, message}
792}
793
794func (ctx *parseContext) parseCompare(cond *mkparser.Directive) starlarkExpr {
795 // Strip outer parentheses
796 mkArg := cloneMakeString(cond.Args)
797 mkArg.Strings[0] = strings.TrimLeft(mkArg.Strings[0], "( ")
798 n := len(mkArg.Strings)
799 mkArg.Strings[n-1] = strings.TrimRight(mkArg.Strings[n-1], ") ")
800 args := mkArg.Split(",")
801 // TODO(asmundak): handle the case where the arguments are in quotes and space-separated
802 if len(args) != 2 {
803 return ctx.newBadExpr(cond, "ifeq/ifneq len(args) != 2 %s", cond.Dump())
804 }
805 args[0].TrimRightSpaces()
806 args[1].TrimLeftSpaces()
807
808 isEq := !strings.HasSuffix(cond.Name, "neq")
809 switch xLeft := ctx.parseMakeString(cond, args[0]).(type) {
810 case *stringLiteralExpr, *variableRefExpr:
811 switch xRight := ctx.parseMakeString(cond, args[1]).(type) {
812 case *stringLiteralExpr, *variableRefExpr:
813 return &eqExpr{left: xLeft, right: xRight, isEq: isEq}
814 case *badExpr:
815 return xRight
816 default:
817 expr, ok := ctx.parseCheckFunctionCallResult(cond, xLeft, args[1])
818 if ok {
819 return expr
820 }
821 return ctx.newBadExpr(cond, "right operand is too complex: %s", args[1].Dump())
822 }
823 case *badExpr:
824 return xLeft
825 default:
826 switch xRight := ctx.parseMakeString(cond, args[1]).(type) {
827 case *stringLiteralExpr, *variableRefExpr:
828 expr, ok := ctx.parseCheckFunctionCallResult(cond, xRight, args[0])
829 if ok {
830 return expr
831 }
832 return ctx.newBadExpr(cond, "left operand is too complex: %s", args[0].Dump())
833 case *badExpr:
834 return xRight
835 default:
836 return ctx.newBadExpr(cond, "operands are too complex: (%s,%s)", args[0].Dump(), args[1].Dump())
837 }
838 }
839}
840
841func (ctx *parseContext) parseCheckFunctionCallResult(directive *mkparser.Directive, xValue starlarkExpr,
842 varArg *mkparser.MakeString) (starlarkExpr, bool) {
843 mkSingleVar, ok := varArg.SingleVariable()
844 if !ok {
845 return nil, false
846 }
847 expr := ctx.parseReference(directive, mkSingleVar)
848 negate := strings.HasSuffix(directive.Name, "neq")
849 checkIsSomethingFunction := func(xCall *callExpr) starlarkExpr {
850 s, ok := maybeString(xValue)
851 if !ok || s != "true" {
852 return ctx.newBadExpr(directive,
853 fmt.Sprintf("the result of %s can be compared only to 'true'", xCall.name))
854 }
855 if len(xCall.args) < 1 {
856 return ctx.newBadExpr(directive, "%s requires an argument", xCall.name)
857 }
858 return nil
859 }
860 switch x := expr.(type) {
861 case *callExpr:
862 switch x.name {
863 case "filter":
864 return ctx.parseCompareFilterFuncResult(directive, x, xValue, !negate), true
865 case "filter-out":
866 return ctx.parseCompareFilterFuncResult(directive, x, xValue, negate), true
867 case "wildcard":
868 return ctx.parseCompareWildcardFuncResult(directive, x, xValue, negate), true
869 case "findstring":
870 return ctx.parseCheckFindstringFuncResult(directive, x, xValue, negate), true
871 case "strip":
872 return ctx.parseCompareStripFuncResult(directive, x, xValue, negate), true
873 case "is-board-platform":
874 if xBad := checkIsSomethingFunction(x); xBad != nil {
875 return xBad, true
876 }
877 return &eqExpr{
878 left: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
879 right: x.args[0],
880 isEq: !negate,
881 }, true
882 case "is-board-platform-in-list":
883 if xBad := checkIsSomethingFunction(x); xBad != nil {
884 return xBad, true
885 }
886 return &inExpr{
887 expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
888 list: maybeConvertToStringList(x.args[0]),
889 isNot: negate,
890 }, true
891 case "is-product-in-list":
892 if xBad := checkIsSomethingFunction(x); xBad != nil {
893 return xBad, true
894 }
895 return &inExpr{
896 expr: &variableRefExpr{ctx.addVariable("TARGET_PRODUCT"), true},
897 list: maybeConvertToStringList(x.args[0]),
898 isNot: negate,
899 }, true
900 case "is-vendor-board-platform":
901 if xBad := checkIsSomethingFunction(x); xBad != nil {
902 return xBad, true
903 }
904 s, ok := maybeString(x.args[0])
905 if !ok {
906 return ctx.newBadExpr(directive, "cannot handle non-constant argument to is-vendor-board-platform"), true
907 }
908 return &inExpr{
909 expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false},
910 list: &variableRefExpr{ctx.addVariable(s + "_BOARD_PLATFORMS"), true},
911 isNot: negate,
912 }, true
913 default:
914 return ctx.newBadExpr(directive, "Unknown function in ifeq: %s", x.name), true
915 }
916 case *badExpr:
917 return x, true
918 default:
919 return nil, false
920 }
921}
922
923func (ctx *parseContext) parseCompareFilterFuncResult(cond *mkparser.Directive,
924 filterFuncCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
925 // We handle:
926 // * ifeq/ifneq (,$(filter v1 v2 ..., $(VAR)) becomes if VAR not in/in ["v1", "v2", ...]
927 // * ifeq/ifneq (,$(filter $(VAR), v1 v2 ...) becomes if VAR not in/in ["v1", "v2", ...]
928 // * ifeq/ifneq ($(VAR),$(filter $(VAR), v1 v2 ...) becomes if VAR in/not in ["v1", "v2"]
929 // TODO(Asmundak): check the last case works for filter-out, too.
930 xPattern := filterFuncCall.args[0]
931 xText := filterFuncCall.args[1]
932 var xInList *stringLiteralExpr
933 var xVar starlarkExpr
934 var ok bool
935 switch x := xValue.(type) {
936 case *stringLiteralExpr:
937 if x.literal != "" {
938 return ctx.newBadExpr(cond, "filter comparison to non-empty value: %s", xValue)
939 }
940 // Either pattern or text should be const, and the
941 // non-const one should be varRefExpr
942 if xInList, ok = xPattern.(*stringLiteralExpr); ok {
943 xVar = xText
944 } else if xInList, ok = xText.(*stringLiteralExpr); ok {
945 xVar = xPattern
946 }
947 case *variableRefExpr:
948 if v, ok := xPattern.(*variableRefExpr); ok {
949 if xInList, ok = xText.(*stringLiteralExpr); ok && v.ref.name() == x.ref.name() {
950 // ifeq/ifneq ($(VAR),$(filter $(VAR), v1 v2 ...), flip negate,
951 // it's the opposite to what is done when comparing to empty.
952 xVar = xPattern
953 negate = !negate
954 }
955 }
956 }
957 if xVar != nil && xInList != nil {
958 if _, ok := xVar.(*variableRefExpr); ok {
959 slExpr := newStringListExpr(strings.Fields(xInList.literal))
960 // Generate simpler code for the common cases:
961 if xVar.typ() == starlarkTypeList {
962 if len(slExpr.items) == 1 {
963 // Checking that a string belongs to list
964 return &inExpr{isNot: negate, list: xVar, expr: slExpr.items[0]}
965 } else {
966 // TODO(asmundak):
967 panic("TBD")
968 }
969 }
970 return &inExpr{isNot: negate, list: newStringListExpr(strings.Fields(xInList.literal)), expr: xVar}
971 }
972 }
973 return ctx.newBadExpr(cond, "filter arguments are too complex: %s", cond.Dump())
974}
975
976func (ctx *parseContext) parseCompareWildcardFuncResult(directive *mkparser.Directive,
977 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
978 if x, ok := xValue.(*stringLiteralExpr); !ok || x.literal != "" {
979 return ctx.newBadExpr(directive, "wildcard result can be compared only to empty: %s", xValue)
980 }
981 callFunc := wildcardExistsPhony
982 if s, ok := xCall.args[0].(*stringLiteralExpr); ok && !strings.ContainsAny(s.literal, "*?{[") {
983 callFunc = fileExistsPhony
984 }
985 var cc starlarkExpr = &callExpr{name: callFunc, args: xCall.args, returnType: starlarkTypeBool}
986 if !negate {
987 cc = &notExpr{cc}
988 }
989 return cc
990}
991
992func (ctx *parseContext) parseCheckFindstringFuncResult(directive *mkparser.Directive,
993 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
994 if x, ok := xValue.(*stringLiteralExpr); !ok || x.literal != "" {
995 return ctx.newBadExpr(directive, "findstring result can be compared only to empty: %s", xValue)
996 }
997 return &eqExpr{
998 left: &callExpr{
999 object: xCall.args[1],
1000 name: "find",
1001 args: []starlarkExpr{xCall.args[0]},
1002 returnType: starlarkTypeInt,
1003 },
1004 right: &intLiteralExpr{-1},
1005 isEq: !negate,
1006 }
1007}
1008
1009func (ctx *parseContext) parseCompareStripFuncResult(directive *mkparser.Directive,
1010 xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr {
1011 if _, ok := xValue.(*stringLiteralExpr); !ok {
1012 return ctx.newBadExpr(directive, "strip result can be compared only to string: %s", xValue)
1013 }
1014 return &eqExpr{
1015 left: &callExpr{
1016 name: "strip",
1017 args: xCall.args,
1018 returnType: starlarkTypeString,
1019 },
1020 right: xValue, isEq: !negate}
1021}
1022
1023// parses $(...), returning an expression
1024func (ctx *parseContext) parseReference(node mkparser.Node, ref *mkparser.MakeString) starlarkExpr {
1025 ref.TrimLeftSpaces()
1026 ref.TrimRightSpaces()
1027 refDump := ref.Dump()
1028
1029 // Handle only the case where the first (or only) word is constant
1030 words := ref.SplitN(" ", 2)
1031 if !words[0].Const() {
1032 return ctx.newBadExpr(node, "reference is too complex: %s", refDump)
1033 }
1034
1035 // If it is a single word, it can be a simple variable
1036 // reference or a function call
1037 if len(words) == 1 {
1038 if isMakeControlFunc(refDump) || refDump == "shell" {
1039 return &callExpr{
1040 name: refDump,
1041 args: []starlarkExpr{&stringLiteralExpr{""}},
1042 returnType: starlarkTypeUnknown,
1043 }
1044 }
1045 if v := ctx.addVariable(refDump); v != nil {
1046 return &variableRefExpr{v, ctx.lastAssignment(v.name()) != nil}
1047 }
1048 return ctx.newBadExpr(node, "unknown variable %s", refDump)
1049 }
1050
1051 expr := &callExpr{name: words[0].Dump(), returnType: starlarkTypeUnknown}
1052 args := words[1]
1053 args.TrimLeftSpaces()
1054 // Make control functions and shell need special treatment as everything
1055 // after the name is a single text argument
1056 if isMakeControlFunc(expr.name) || expr.name == "shell" {
1057 x := ctx.parseMakeString(node, args)
1058 if xBad, ok := x.(*badExpr); ok {
1059 return xBad
1060 }
1061 expr.args = []starlarkExpr{x}
1062 return expr
1063 }
1064 if expr.name == "call" {
1065 words = args.SplitN(",", 2)
1066 if words[0].Empty() || !words[0].Const() {
1067 return ctx.newBadExpr(nil, "cannot handle %s", refDump)
1068 }
1069 expr.name = words[0].Dump()
1070 if len(words) < 2 {
1071 return expr
1072 }
1073 args = words[1]
1074 }
1075 if kf, found := knownFunctions[expr.name]; found {
1076 expr.returnType = kf.returnType
1077 } else {
1078 return ctx.newBadExpr(node, "cannot handle invoking %s", expr.name)
1079 }
1080 switch expr.name {
1081 case "word":
1082 return ctx.parseWordFunc(node, args)
Sasha Smundak94b41c72021-07-12 18:30:42 -07001083 case "subst", "patsubst":
1084 return ctx.parseSubstFunc(node, expr.name, args)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001085 default:
1086 for _, arg := range args.Split(",") {
1087 arg.TrimLeftSpaces()
1088 arg.TrimRightSpaces()
1089 x := ctx.parseMakeString(node, arg)
1090 if xBad, ok := x.(*badExpr); ok {
1091 return xBad
1092 }
1093 expr.args = append(expr.args, x)
1094 }
1095 }
1096 return expr
1097}
1098
Sasha Smundak94b41c72021-07-12 18:30:42 -07001099func (ctx *parseContext) parseSubstFunc(node mkparser.Node, fname string, args *mkparser.MakeString) starlarkExpr {
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001100 words := args.Split(",")
1101 if len(words) != 3 {
Sasha Smundak94b41c72021-07-12 18:30:42 -07001102 return ctx.newBadExpr(node, "%s function should have 3 arguments", fname)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001103 }
1104 if !words[0].Const() || !words[1].Const() {
Sasha Smundak94b41c72021-07-12 18:30:42 -07001105 return ctx.newBadExpr(node, "%s function's from and to arguments should be constant", fname)
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001106 }
1107 from := words[0].Strings[0]
1108 to := words[1].Strings[0]
1109 words[2].TrimLeftSpaces()
1110 words[2].TrimRightSpaces()
1111 obj := ctx.parseMakeString(node, words[2])
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001112 typ := obj.typ()
Sasha Smundak94b41c72021-07-12 18:30:42 -07001113 if typ == starlarkTypeString && fname == "subst" {
1114 // Optimization: if it's $(subst from, to, string), emit string.replace(from, to)
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001115 return &callExpr{
1116 object: obj,
1117 name: "replace",
1118 args: []starlarkExpr{&stringLiteralExpr{from}, &stringLiteralExpr{to}},
1119 returnType: typ,
1120 }
1121 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001122 return &callExpr{
Sasha Smundak94b41c72021-07-12 18:30:42 -07001123 name: fname,
Sasha Smundak9d011ab2021-07-09 16:00:57 -07001124 args: []starlarkExpr{&stringLiteralExpr{from}, &stringLiteralExpr{to}, obj},
1125 returnType: obj.typ(),
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001126 }
1127}
1128
1129func (ctx *parseContext) parseWordFunc(node mkparser.Node, args *mkparser.MakeString) starlarkExpr {
1130 words := args.Split(",")
1131 if len(words) != 2 {
1132 return ctx.newBadExpr(node, "word function should have 2 arguments")
1133 }
1134 var index uint64 = 0
1135 if words[0].Const() {
1136 index, _ = strconv.ParseUint(strings.TrimSpace(words[0].Strings[0]), 10, 64)
1137 }
1138 if index < 1 {
1139 return ctx.newBadExpr(node, "word index should be constant positive integer")
1140 }
1141 words[1].TrimLeftSpaces()
1142 words[1].TrimRightSpaces()
1143 array := ctx.parseMakeString(node, words[1])
1144 if xBad, ok := array.(*badExpr); ok {
1145 return xBad
1146 }
1147 if array.typ() != starlarkTypeList {
1148 array = &callExpr{object: array, name: "split", returnType: starlarkTypeList}
1149 }
1150 return indexExpr{array, &intLiteralExpr{int(index - 1)}}
1151}
1152
1153func (ctx *parseContext) parseMakeString(node mkparser.Node, mk *mkparser.MakeString) starlarkExpr {
1154 if mk.Const() {
1155 return &stringLiteralExpr{mk.Dump()}
1156 }
1157 if mkRef, ok := mk.SingleVariable(); ok {
1158 return ctx.parseReference(node, mkRef)
1159 }
1160 // If we reached here, it's neither string literal nor a simple variable,
1161 // we need a full-blown interpolation node that will generate
1162 // "a%b%c" % (X, Y) for a$(X)b$(Y)c
1163 xInterp := &interpolateExpr{args: make([]starlarkExpr, len(mk.Variables))}
1164 for i, ref := range mk.Variables {
1165 arg := ctx.parseReference(node, ref.Name)
1166 if x, ok := arg.(*badExpr); ok {
1167 return x
1168 }
1169 xInterp.args[i] = arg
1170 }
1171 xInterp.chunks = append(xInterp.chunks, mk.Strings...)
1172 return xInterp
1173}
1174
1175// Handles the statements whose treatment is the same in all contexts: comment,
1176// assignment, variable (which is a macro call in reality) and all constructs that
1177// do not handle in any context ('define directive and any unrecognized stuff).
1178// Return true if we handled it.
1179func (ctx *parseContext) handleSimpleStatement(node mkparser.Node) bool {
1180 handled := true
1181 switch x := node.(type) {
1182 case *mkparser.Comment:
1183 ctx.insertComment("#" + x.Comment)
1184 case *mkparser.Assignment:
1185 ctx.handleAssignment(x)
1186 case *mkparser.Variable:
1187 ctx.handleVariable(x)
1188 case *mkparser.Directive:
1189 switch x.Name {
1190 case "define":
1191 ctx.handleDefine(x)
1192 case "include", "-include":
1193 ctx.handleInclude(node, ctx.parseMakeString(node, x.Args), x.Name[0] != '-')
1194 default:
1195 handled = false
1196 }
1197 default:
1198 ctx.errorf(x, "unsupported line %s", x.Dump())
1199 }
1200 return handled
1201}
1202
1203func (ctx *parseContext) insertComment(s string) {
1204 ctx.receiver.newNode(&commentNode{strings.TrimSpace(s)})
1205}
1206
1207func (ctx *parseContext) carryAsComment(failedNode mkparser.Node) {
1208 for _, line := range strings.Split(failedNode.Dump(), "\n") {
1209 ctx.insertComment("# " + line)
1210 }
1211}
1212
1213// records that the given node failed to be converted and includes an explanatory message
1214func (ctx *parseContext) errorf(failedNode mkparser.Node, message string, args ...interface{}) {
1215 if ctx.errorLogger != nil {
1216 ctx.errorLogger.NewError(message, failedNode, args...)
1217 }
1218 message = fmt.Sprintf(message, args...)
1219 ctx.insertComment(fmt.Sprintf("# MK2RBC TRANSLATION ERROR: %s", message))
1220 ctx.carryAsComment(failedNode)
1221 ctx.script.hasErrors = true
1222}
1223
1224func (ctx *parseContext) wrapBadExpr(xBad *badExpr) {
1225 ctx.insertComment(fmt.Sprintf("# MK2RBC TRANSLATION ERROR: %s", xBad.message))
1226 ctx.carryAsComment(xBad.node)
1227}
1228
1229func (ctx *parseContext) loadedModulePath(path string) string {
1230 // During the transition to Roboleaf some of the product configuration files
1231 // will be converted and checked in while the others will be generated on the fly
1232 // and run. The runner (rbcrun application) accommodates this by allowing three
1233 // different ways to specify the loaded file location:
1234 // 1) load(":<file>",...) loads <file> from the same directory
1235 // 2) load("//path/relative/to/source/root:<file>", ...) loads <file> source tree
1236 // 3) load("/absolute/path/to/<file> absolute path
1237 // If the file being generated and the file it wants to load are in the same directory,
1238 // generate option 1.
1239 // Otherwise, if output directory is not specified, generate 2)
1240 // Finally, if output directory has been specified and the file being generated and
1241 // the file it wants to load from are in the different directories, generate 2) or 3):
1242 // * if the file being loaded exists in the source tree, generate 2)
1243 // * otherwise, generate 3)
1244 // Finally, figure out the loaded module path and name and create a node for it
1245 loadedModuleDir := filepath.Dir(path)
1246 base := filepath.Base(path)
1247 loadedModuleName := strings.TrimSuffix(base, filepath.Ext(base)) + ctx.outputSuffix
1248 if loadedModuleDir == filepath.Dir(ctx.script.mkFile) {
1249 return ":" + loadedModuleName
1250 }
1251 if ctx.outputDir == "" {
1252 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1253 }
1254 if _, err := os.Stat(filepath.Join(loadedModuleDir, loadedModuleName)); err == nil {
1255 return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName)
1256 }
1257 return filepath.Join(ctx.outputDir, loadedModuleDir, loadedModuleName)
1258}
1259
1260func (ss *StarlarkScript) String() string {
1261 return NewGenerateContext(ss).emit()
1262}
1263
1264func (ss *StarlarkScript) SubConfigFiles() []string {
1265 var subs []string
1266 for _, src := range ss.inherited {
1267 subs = append(subs, src.originalPath)
1268 }
1269 return subs
1270}
1271
1272func (ss *StarlarkScript) HasErrors() bool {
1273 return ss.hasErrors
1274}
1275
1276// Convert reads and parses a makefile. If successful, parsed tree
1277// is returned and then can be passed to String() to get the generated
1278// Starlark file.
1279func Convert(req Request) (*StarlarkScript, error) {
1280 reader := req.Reader
1281 if reader == nil {
1282 mkContents, err := ioutil.ReadFile(req.MkFile)
1283 if err != nil {
1284 return nil, err
1285 }
1286 reader = bytes.NewBuffer(mkContents)
1287 }
1288 parser := mkparser.NewParser(req.MkFile, reader)
1289 nodes, errs := parser.Parse()
1290 if len(errs) > 0 {
1291 for _, e := range errs {
1292 fmt.Fprintln(os.Stderr, "ERROR:", e)
1293 }
1294 return nil, fmt.Errorf("bad makefile %s", req.MkFile)
1295 }
1296 starScript := &StarlarkScript{
1297 moduleName: moduleNameForFile(req.MkFile),
1298 mkFile: req.MkFile,
1299 topDir: req.RootDir,
1300 traceCalls: req.TraceCalls,
1301 warnPartialSuccess: req.WarnPartialSuccess,
1302 }
1303 ctx := newParseContext(starScript, nodes)
1304 ctx.outputSuffix = req.OutputSuffix
1305 ctx.outputDir = req.OutputDir
1306 ctx.errorLogger = req.ErrorLogger
1307 if len(req.TracedVariables) > 0 {
1308 ctx.tracedVariables = make(map[string]bool)
1309 for _, v := range req.TracedVariables {
1310 ctx.tracedVariables[v] = true
1311 }
1312 }
1313 ctx.pushReceiver(starScript)
1314 for ctx.hasNodes() && ctx.fatalError == nil {
1315 node := ctx.getNode()
1316 if ctx.handleSimpleStatement(node) {
1317 continue
1318 }
1319 switch x := node.(type) {
1320 case *mkparser.Directive:
1321 switch x.Name {
1322 case "ifeq", "ifneq", "ifdef", "ifndef":
1323 ctx.handleIfBlock(x)
1324 default:
1325 ctx.errorf(x, "unexpected directive %s", x.Name)
1326 }
1327 default:
1328 ctx.errorf(x, "unsupported line")
1329 }
1330 }
1331 if ctx.fatalError != nil {
1332 return nil, ctx.fatalError
1333 }
1334 return starScript, nil
1335}
1336
1337func Launcher(path, name string) string {
1338 var buf bytes.Buffer
1339 fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName)
1340 fmt.Fprintf(&buf, "load(%q, \"init\")\n", path)
1341 fmt.Fprintf(&buf, "g, config = %s(%q, init)\n", cfnMain, name)
1342 fmt.Fprintf(&buf, "%s(g, config)\n", cfnPrintVars)
1343 return buf.String()
1344}
1345
1346func MakePath2ModuleName(mkPath string) string {
1347 return strings.TrimSuffix(mkPath, filepath.Ext(mkPath))
1348}