Browse Source

Correctly detect circular references in JSON.stringify for wrapped Go objects. Fixes #543.

Dmitry Panov 1 year ago
parent
commit
594410467b
2 changed files with 18 additions and 1 deletions
  1. 1 1
      builtin_json.go
  2. 17 0
      builtin_json_test.go

+ 1 - 1
builtin_json.go

@@ -359,7 +359,7 @@ func (ctx *_builtinJSON_stringifyContext) str(key Value, holder *Object) bool {
 		ctx.buf.WriteString("null")
 		ctx.buf.WriteString("null")
 	case *Object:
 	case *Object:
 		for _, object := range ctx.stack {
 		for _, object := range ctx.stack {
-			if value1 == object {
+			if value1.SameAs(object) {
 				ctx.r.typeErrorResult(true, "Converting circular structure to JSON")
 				ctx.r.typeErrorResult(true, "Converting circular structure to JSON")
 			}
 			}
 		}
 		}

+ 17 - 0
builtin_json_test.go

@@ -48,6 +48,23 @@ func TestJSONMarshalObjectCircular(t *testing.T) {
 	}
 	}
 }
 }
 
 
+func TestJSONStringifyCircularWrappedGo(t *testing.T) {
+	type CircularType struct {
+		Self *CircularType
+	}
+	vm := New()
+	v := CircularType{}
+	v.Self = &v
+	vm.Set("v", &v)
+	_, err := vm.RunString("JSON.stringify(v)")
+	if err == nil {
+		t.Fatal("Expected error")
+	}
+	if !strings.HasPrefix(err.Error(), "TypeError: Converting circular structure to JSON") {
+		t.Fatalf("Unexpected error: %v", err)
+	}
+}
+
 func TestJSONParseReviver(t *testing.T) {
 func TestJSONParseReviver(t *testing.T) {
 	// example from
 	// example from
 	// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
 	// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse