Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't crash when freezing a struct with a circular reference #567

Merged
merged 2 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions starlark/value.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ type Value interface {
// structure through this API will fail dynamically, making the
// data structure immutable and safe for publishing to other
// Starlark interpreters running concurrently.
//
// Implementations of Freeze must be defensive against
// reference cycles; this can be achieved by first checking
// the value's frozen state, then setting it, and only then
// visiting any other values that it references.
Freeze()

// Truth returns the truth value of an object.
Expand Down
8 changes: 6 additions & 2 deletions starlarkstruct/struct.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ func FromStringDict(constructor starlark.Value, d starlark.StringDict) *Struct {
type Struct struct {
constructor starlark.Value
entries entries // sorted by name
frozen bool
}

// Default is the default constructor for structs.
Expand Down Expand Up @@ -172,8 +173,11 @@ func (s *Struct) Hash() (uint32, error) {
return x, nil
}
func (s *Struct) Freeze() {
for _, e := range s.entries {
e.value.Freeze()
if !s.frozen {
oprypin marked this conversation as resolved.
Show resolved Hide resolved
s.frozen = true
for _, e := range s.entries {
e.value.Freeze()
}
}
}

Expand Down
9 changes: 9 additions & 0 deletions starlarkstruct/testdata/struct.star
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,12 @@ assert.eq(alice + bob, person(age = 50, city = "NYC", name = "bob")) # not comm
assert.fails(lambda : alice + 1, "struct \\+ int")
assert.eq(http + http, http)
assert.fails(lambda : http + bob, "different constructors: hostport \\+ person")

# Check that a struct with a circular reference doesn't crash when it gets frozen.
def struct_with_a_circular_reference():
foo = lambda: print(self)
self = struct(foo = foo)
return self

# A top-level assigment is what causes this value to be frozen at the end of the load.
toplevel_struct_with_a_circular_reference = struct_with_a_circular_reference()
Loading