diff --git a/pkg/ast/attribute_bag.go b/pkg/ast/attribute_bag.go index eb1b311..fd7694b 100644 --- a/pkg/ast/attribute_bag.go +++ b/pkg/ast/attribute_bag.go @@ -1,6 +1,9 @@ package ast -import "reflect" +import ( + "maps" + "reflect" +) // AttributeBag is embedded in every AST node to carry metadata assigned after // parsing, such as a resolved type. Attributes are keyed by string and allocated @@ -28,3 +31,9 @@ func (bag *AttributeBag) GetAttribute(key string) (any, bool) { value, ok := bag.attributes[key] return value, ok } + +// Clone returns a bag with its own copy of the attributes, for a copied +// node whose attributes must not change the original's. +func (bag AttributeBag) Clone() AttributeBag { + return AttributeBag{attributes: maps.Clone(bag.attributes)} +} diff --git a/pkg/ast/attribute_bag_test.go b/pkg/ast/attribute_bag_test.go index c2ec03b..94780e3 100644 --- a/pkg/ast/attribute_bag_test.go +++ b/pkg/ast/attribute_bag_test.go @@ -48,3 +48,22 @@ func TestNodeCarriesAttributes(test *testing.T) { test.Fatalf("node attribute not stored: got %v, %v", value, ok) } } + +func TestAttributeBagClone(test *testing.T) { + var bag AttributeBag + bag.SetAttribute("type", "User") + + clone := bag.Clone() + clone.SetAttribute("type", "Admin") + if value, _ := bag.GetAttribute("type"); value != "User" { + test.Fatalf("setting the clone changed the original: got %v", value) + } + if value, _ := clone.GetAttribute("type"); value != "Admin" { + test.Fatalf("got %v; want Admin", value) + } + + var empty AttributeBag + if clone := empty.Clone(); !clone.Equal(empty) { + test.Fatal("the clone of an empty bag should equal it") + } +}