Skip to content
Open
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
11 changes: 10 additions & 1 deletion pkg/ast/attribute_bag.go
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)}
}
19 changes: 19 additions & 0 deletions pkg/ast/attribute_bag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}