From 334db21fd64e25bc6e6f5bbd11458b1a9a5506e5 Mon Sep 17 00:00:00 2001 From: mappu Date: Wed, 8 Apr 2020 19:58:09 +1200 Subject: [PATCH] node: support die() --- node.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/node.go b/node.go index 6f6001e..32581a5 100644 --- a/node.go +++ b/node.go @@ -850,6 +850,33 @@ func (this *conversionState) convertNoFreeFloating(n_ node.Node) (string, error) return this.convert(expr.NewFunctionCall(transparentNameNode, n.ArgumentList)) + case *expr.Exit: + // die(0) - set process exit code and exit + // die("message") - print to stdout and exit 0 + // die - exit 0 + + this.importPackages["os"] = struct{}{} + + if n.Expr == nil { + return "os.Exit(0)", nil + } + + child, err := this.convert(n.Expr) + if err != nil { + return "", parseErr{n, err} + } + + // Although it might have been a more complex string expression - we + // don't currently know that + // TODO type inference + switch n.Expr.(type) { + case *scalar.String: + this.importPackages["fmt"] = struct{}{} + return "fmt.Print(" + child + ")\nos.Exit(0)", nil // hopefully die() was standalone, and not "or die" + default: + return "os.Exit(" + child + ")", nil + } + case *expr.PreInc: // """In Go, i++ is a statement, not an expression. So you can't use its value in another expression such as a function call.""" v, err := this.convert(n.Variable)