| 1 |
// Copyright 2017 The Bazel Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
// Package starlarkstruct defines the Starlark types 'struct' and |
| 6 |
// 'module', both optional language extensions. |
| 7 |
package starlarkstruct // import "go.starlark.net/starlarkstruct" |
| 8 |
|
| 9 |
// It is tempting to introduce a variant of Struct that is a wrapper |
| 10 |
// around a Go struct value, for stronger typing guarantees and more |
| 11 |
// efficient and convenient field lookup. However: |
| 12 |
// 1) all fields of Starlark structs are optional, so we cannot represent |
| 13 |
// them using more specific types such as String, Int, *Depset, and |
| 14 |
// *File, as such types give no way to represent missing fields. |
| 15 |
// 2) the efficiency gain of direct struct field access is rather |
| 16 |
// marginal: finding the index of a field by binary searching on the |
| 17 |
// sorted list of field names is quite fast compared to the other |
| 18 |
// overheads. |
| 19 |
// 3) the gains in compactness and spatial locality are also rather |
| 20 |
// marginal: the array behind the []entry slice is (due to field name |
| 21 |
// strings) only a factor of 2 larger than the corresponding Go struct |
| 22 |
// would be, and, like the Go struct, requires only a single allocation. |
| 23 |
|
| 24 |
import ( |
| 25 |
"fmt" |
| 26 |
"iter" |
| 27 |
"sort" |
| 28 |
"strings" |
| 29 |
|
| 30 |
"go.starlark.net/starlark" |
| 31 |
"go.starlark.net/syntax" |
| 32 |
) |
| 33 |
|
| 34 |
// Make is the implementation of a built-in function that instantiates |
| 35 |
// an immutable struct from the specified keyword arguments. |
| 36 |
// |
| 37 |
// An application can add 'struct' to the Starlark environment like so: |
| 38 |
// |
| 39 |
// globals := starlark.StringDict{ |
| 40 |
// "struct": starlark.NewBuiltin("struct", starlarkstruct.Make), |
| 41 |
// } |
| 42 |
func Make(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { |
| 43 |
if len(args) > 0 { |
| 44 |
return nil, fmt.Errorf("struct: unexpected positional arguments") |
| 45 |
} |
| 46 |
return FromKeywords(Default, kwargs), nil |
| 47 |
} |
| 48 |
|
| 49 |
// FromKeywords returns a new struct instance whose fields are specified by the |
| 50 |
// key/value pairs in kwargs. (Each kwargs[i][0] must be a starlark.String.) |
| 51 |
func FromKeywords(constructor starlark.Value, kwargs []starlark.Tuple) *Struct { |
| 52 |
if constructor == nil { |
| 53 |
panic("nil constructor") |
| 54 |
} |
| 55 |
s := &Struct{ |
| 56 |
constructor: constructor, |
| 57 |
entries: make(entries, 0, len(kwargs)), |
| 58 |
} |
| 59 |
for _, kwarg := range kwargs { |
| 60 |
k := string(kwarg[0].(starlark.String)) |
| 61 |
v := kwarg[1] |
| 62 |
s.entries = append(s.entries, entry{k, v}) |
| 63 |
} |
| 64 |
sort.Sort(s.entries) |
| 65 |
return s |
| 66 |
} |
| 67 |
|
| 68 |
// FromStringDict returns a new struct instance whose elements are those of d. |
| 69 |
// The constructor parameter specifies the constructor; use Default for an ordinary struct. |
| 70 |
func FromStringDict(constructor starlark.Value, d starlark.StringDict) *Struct { |
| 71 |
if constructor == nil { |
| 72 |
panic("nil constructor") |
| 73 |
} |
| 74 |
s := &Struct{ |
| 75 |
constructor: constructor, |
| 76 |
entries: make(entries, 0, len(d)), |
| 77 |
} |
| 78 |
for k, v := range d { |
| 79 |
s.entries = append(s.entries, entry{k, v}) |
| 80 |
} |
| 81 |
sort.Sort(s.entries) |
| 82 |
return s |
| 83 |
} |
| 84 |
|
| 85 |
// Struct is an immutable Starlark type that maps field names to values. |
| 86 |
// It is not iterable and does not support len. |
| 87 |
// |
| 88 |
// A struct has a constructor, a distinct value that identifies a class |
| 89 |
// of structs, and which appears in the struct's string representation. |
| 90 |
// |
| 91 |
// Operations such as x+y fail if the constructors of the two operands |
| 92 |
// are not equal. |
| 93 |
// |
| 94 |
// The default constructor, Default, is the string "struct", but |
| 95 |
// clients may wish to 'brand' structs for their own purposes. |
| 96 |
// The constructor value appears in the printed form of the value, |
| 97 |
// and is accessible using the Constructor method. |
| 98 |
// |
| 99 |
// Use Attr to access its fields and AttrNames to enumerate them. |
| 100 |
type Struct struct { |
| 101 |
constructor starlark.Value |
| 102 |
entries entries // sorted by name |
| 103 |
frozen bool |
| 104 |
} |
| 105 |
|
| 106 |
// Default is the default constructor for structs. |
| 107 |
// It is merely the string "struct". |
| 108 |
const Default = starlark.String("struct") |
| 109 |
|
| 110 |
type entries []entry |
| 111 |
|
| 112 |
func (a entries) Len() int { return len(a) } |
| 113 |
func (a entries) Less(i, j int) bool { return a[i].name < a[j].name } |
| 114 |
func (a entries) Swap(i, j int) { a[i], a[j] = a[j], a[i] } |
| 115 |
|
| 116 |
type entry struct { |
| 117 |
name string |
| 118 |
value starlark.Value |
| 119 |
} |
| 120 |
|
| 121 |
var ( |
| 122 |
_ starlark.HasAttrs = (*Struct)(nil) |
| 123 |
_ starlark.HasBinary = (*Struct)(nil) |
| 124 |
) |
| 125 |
|
| 126 |
// ToStringDict adds a name/value entry to d for each field of the struct. |
| 127 |
func (s *Struct) ToStringDict(d starlark.StringDict) { |
| 128 |
for _, e := range s.entries { |
| 129 |
d[e.name] = e.value |
| 130 |
} |
| 131 |
} |
| 132 |
|
| 133 |
func (s *Struct) String() string { |
| 134 |
buf := new(strings.Builder) |
| 135 |
switch constructor := s.constructor.(type) { |
| 136 |
case starlark.String: |
| 137 |
// NB: The Java implementation always prints struct |
| 138 |
// even for Bazel provider instances. |
| 139 |
buf.WriteString(constructor.GoString()) // avoid String()'s quotation |
| 140 |
default: |
| 141 |
buf.WriteString(s.constructor.String()) |
| 142 |
} |
| 143 |
buf.WriteByte('(') |
| 144 |
for i, e := range s.entries { |
| 145 |
if i > 0 { |
| 146 |
buf.WriteString(", ") |
| 147 |
} |
| 148 |
buf.WriteString(e.name) |
| 149 |
buf.WriteString(" = ") |
| 150 |
buf.WriteString(e.value.String()) |
| 151 |
} |
| 152 |
buf.WriteByte(')') |
| 153 |
return buf.String() |
| 154 |
} |
| 155 |
|
| 156 |
// Constructor returns the constructor used to create this struct. |
| 157 |
func (s *Struct) Constructor() starlark.Value { return s.constructor } |
| 158 |
|
| 159 |
func (s *Struct) Type() string { return "struct" } |
| 160 |
func (s *Struct) Truth() starlark.Bool { return true } // even when empty |
| 161 |
func (s *Struct) Hash() (uint32, error) { |
| 162 |
// Same algorithm as Tuple.hash, but with different primes. |
| 163 |
var x, m uint32 = 8731, 9839 |
| 164 |
for _, e := range s.entries { |
| 165 |
namehash, _ := starlark.String(e.name).Hash() |
| 166 |
x = x ^ 3*namehash |
| 167 |
y, err := e.value.Hash() |
| 168 |
if err != nil { |
| 169 |
return 0, err |
| 170 |
} |
| 171 |
x = x ^ y*m |
| 172 |
m += 7349 |
| 173 |
} |
| 174 |
return x, nil |
| 175 |
} |
| 176 |
func (s *Struct) Freeze() { |
| 177 |
if !s.frozen { |
| 178 |
s.frozen = true |
| 179 |
for _, e := range s.entries { |
| 180 |
e.value.Freeze() |
| 181 |
} |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
func (x *Struct) Binary(op syntax.Token, y starlark.Value, side starlark.Side) (starlark.Value, error) { |
| 186 |
if y, ok := y.(*Struct); ok && op == syntax.PLUS { |
| 187 |
if side == starlark.Right { |
| 188 |
x, y = y, x |
| 189 |
} |
| 190 |
|
| 191 |
if eq, err := starlark.Equal(x.constructor, y.constructor); err != nil { |
| 192 |
return nil, fmt.Errorf("in %s + %s: error comparing constructors: %v", |
| 193 |
x.constructor, y.constructor, err) |
| 194 |
} else if !eq { |
| 195 |
return nil, fmt.Errorf("cannot add structs of different constructors: %s + %s", |
| 196 |
x.constructor, y.constructor) |
| 197 |
} |
| 198 |
|
| 199 |
z := make(starlark.StringDict, x.Len()+y.Len()) |
| 200 |
for _, e := range x.entries { |
| 201 |
z[e.name] = e.value |
| 202 |
} |
| 203 |
for _, e := range y.entries { |
| 204 |
z[e.name] = e.value |
| 205 |
} |
| 206 |
|
| 207 |
return FromStringDict(x.constructor, z), nil |
| 208 |
} |
| 209 |
return nil, nil // unhandled |
| 210 |
} |
| 211 |
|
| 212 |
// Attr returns the value of the specified field. |
| 213 |
func (s *Struct) Attr(name string) (starlark.Value, error) { |
| 214 |
// Binary search the entries. |
| 215 |
// This implementation is a specialization of |
| 216 |
// sort.Search that avoids dynamic dispatch. |
| 217 |
n := len(s.entries) |
| 218 |
i, j := 0, n |
| 219 |
for i < j { |
| 220 |
h := int(uint(i+j) >> 1) |
| 221 |
if s.entries[h].name < name { |
| 222 |
i = h + 1 |
| 223 |
} else { |
| 224 |
j = h |
| 225 |
} |
| 226 |
} |
| 227 |
if i < n && s.entries[i].name == name { |
| 228 |
return s.entries[i].value, nil |
| 229 |
} |
| 230 |
|
| 231 |
var ctor string |
| 232 |
if s.constructor != Default { |
| 233 |
ctor = s.constructor.String() + " " |
| 234 |
} |
| 235 |
return nil, starlark.NoSuchAttrError( |
| 236 |
fmt.Sprintf("%sstruct has no .%s attribute", ctor, name)) |
| 237 |
} |
| 238 |
|
| 239 |
func (s *Struct) Len() int { return len(s.entries) } |
| 240 |
|
| 241 |
// AttrNames returns a new sorted list of the struct fields. |
| 242 |
func (s *Struct) AttrNames() []string { |
| 243 |
names := make([]string, len(s.entries)) |
| 244 |
for i, e := range s.entries { |
| 245 |
names[i] = e.name |
| 246 |
} |
| 247 |
return names |
| 248 |
} |
| 249 |
|
| 250 |
// AttrAt returns the value of the field at the specified index. |
| 251 |
func (s *Struct) AttrAt(i int) (string, starlark.Value) { |
| 252 |
e := s.entries[i] |
| 253 |
return e.name, e.value |
| 254 |
} |
| 255 |
|
| 256 |
// Entries returns an iterator over the sequence of fields of a struct. For |
| 257 |
// example: |
| 258 |
// |
| 259 |
// for name, val := range struct1.Entries() { ... } |
| 260 |
func (s *Struct) Entries() iter.Seq2[string, starlark.Value] { |
| 261 |
return func(yield func(string, starlark.Value) bool) { |
| 262 |
for _, e := range s.entries { |
| 263 |
if !yield(e.name, e.value) { |
| 264 |
return |
| 265 |
} |
| 266 |
} |
| 267 |
} |
| 268 |
} |
| 269 |
|
| 270 |
func (x *Struct) CompareSameType(op syntax.Token, y_ starlark.Value, depth int) (bool, error) { |
| 271 |
y := y_.(*Struct) |
| 272 |
switch op { |
| 273 |
case syntax.EQL: |
| 274 |
return structsEqual(x, y, depth) |
| 275 |
case syntax.NEQ: |
| 276 |
eq, err := structsEqual(x, y, depth) |
| 277 |
return !eq, err |
| 278 |
default: |
| 279 |
return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type()) |
| 280 |
} |
| 281 |
} |
| 282 |
|
| 283 |
func structsEqual(x, y *Struct, depth int) (bool, error) { |
| 284 |
if x.Len() != y.Len() { |
| 285 |
return false, nil |
| 286 |
} |
| 287 |
|
| 288 |
if eq, err := starlark.Equal(x.constructor, y.constructor); err != nil { |
| 289 |
return false, fmt.Errorf("error comparing struct constructors %v and %v: %v", |
| 290 |
x.constructor, y.constructor, err) |
| 291 |
} else if !eq { |
| 292 |
return false, nil |
| 293 |
} |
| 294 |
|
| 295 |
for i := range x.Len() { |
| 296 |
if x.entries[i].name != y.entries[i].name { |
| 297 |
return false, nil |
| 298 |
} else if eq, err := starlark.EqualDepth(x.entries[i].value, y.entries[i].value, depth-1); err != nil { |
| 299 |
return false, err |
| 300 |
} else if !eq { |
| 301 |
return false, nil |
| 302 |
} |
| 303 |
} |
| 304 |
return true, nil |
| 305 |
} |