Browse Source

Set the callee value in recursive RunProgram calls. Fixes #477

Dmitry Panov 2 years ago
parent
commit
9577c35d40
2 changed files with 20 additions and 1 deletions
  1. 3 1
      runtime.go
  2. 17 0
      runtime_test.go

+ 3 - 1
runtime.go

@@ -1444,6 +1444,7 @@ func (r *Runtime) RunProgram(p *Program) (result Value, err error) {
 	recursive := len(vm.callStack) > 0
 	recursive := len(vm.callStack) > 0
 	defer func() {
 	defer func() {
 		if recursive {
 		if recursive {
+			vm.sp--
 			vm.popCtx()
 			vm.popCtx()
 		} else {
 		} else {
 			vm.callStack = vm.callStack[:len(vm.callStack)-1]
 			vm.callStack = vm.callStack[:len(vm.callStack)-1]
@@ -1462,7 +1463,8 @@ func (r *Runtime) RunProgram(p *Program) (result Value, err error) {
 	if recursive {
 	if recursive {
 		vm.pushCtx()
 		vm.pushCtx()
 		vm.stash = &r.global.stash
 		vm.stash = &r.global.stash
-		vm.sb = vm.sp - 1
+		vm.push(_undefined) // make sure the 'callee' value (stack[sb-1]) is set
+		vm.sb = vm.sp
 	} else {
 	} else {
 		vm.callStack = append(vm.callStack, context{})
 		vm.callStack = append(vm.callStack, context{})
 	}
 	}

+ 17 - 0
runtime_test.go

@@ -239,6 +239,23 @@ func TestRecursiveRun(t *testing.T) {
 	}
 	}
 }
 }
 
 
+func TestRecursiveRunCallee(t *testing.T) {
+	// Make sure that a recursive call to Run*() correctly sets the callee (i.e. stack[sb-1])
+	vm := New()
+	vm.Set("f", func() (Value, error) {
+		return vm.RunString("this; (() => 1)()")
+	})
+	res, err := vm.RunString(`
+		f(123, 123);
+	`)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if !res.SameAs(valueInt(1)) {
+		t.Fatal(res)
+	}
+}
+
 func TestObjectGetSet(t *testing.T) {
 func TestObjectGetSet(t *testing.T) {
 	const SCRIPT = `
 	const SCRIPT = `
 		input.test++;
 		input.test++;