Repository: d5/tengo (go)

Issue:
Runtime panic on self assignment 
The following Tengo script panics at run time:

a := a.foo

This likely because the compiler wrongly considers a to be defined after the := . A should only be considered defined in the next statement.

Pull request description:
fix runtime panics on self assignment
fixes #386 

I'm not sure this is the best solution to the problem, but it's fairly minimal. I can't really think of anything other than functions that might need this recursive definition.

@d5 thoughts?

Patch:
diff --git a/compiler.go b/compiler.go
index 6591603..0d46a4d 100644
--- a/compiler.go
+++ b/compiler.go
@@ -692,12 +692,15 @@ func (c *Compiler) compileAssign(
 		return c.errorf(node, "operator ':=' not allowed with selector")
 	}
 
+	_, isFunc := rhs[0].(*parser.FuncLit)
 	symbol, depth, exists := c.symbolTable.Resolve(ident, false)
 	if op == token.Define {
 		if depth == 0 && exists {
 			return c.errorf(node, "'%s' redeclared in this block", ident)
 		}
-		symbol = c.symbolTable.Define(ident)
+		if isFunc {
+			symbol = c.symbolTable.Define(ident)
+		}
 	} else {
 		if !exists {
 			return c.errorf(node, "unresolved reference '%s'", ident)
@@ -718,6 +721,10 @@ func (c *Compiler) compileAssign(
 		}
 	}
 
+	if op == token.Define && !isFunc {
+		symbol = c.symbolTable.Define(ident)
+	}
+
 	switch op {
 	case token.AddAssign:
 		c.emit(node, parser.OpBinaryOp, int(token.Add))


Test patch:
diff --git a/compiler_test.go b/compiler_test.go
index fd1d422..d525b47 100644
--- a/compiler_test.go
+++ b/compiler_test.go
@@ -1023,6 +1023,8 @@ func TestCompilerErrorReport(t *testing.T) {
 
 	expectCompileError(t, `a = 1`,
 		"Compile Error: unresolved reference 'a'\n\tat test:1:1")
+	expectCompileError(t, `a := a`,
+		"Compile Error: unresolved reference 'a'\n\tat test:1:6")
 	expectCompileError(t, `a, b := 1, 2`,
 		"Compile Error: tuple assignment not allowed\n\tat test:1:1")
 	expectCompileError(t, `a.b := 1`,