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