Debian Codegraph @

starlark/value.go

raw
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 starlark provides a Starlark interpreter.
6 //
7 // Starlark values are represented by the Value interface.
8 // The following built-in Value types are known to the evaluator:
9 //
10 // NoneType -- NoneType
11 // Bool -- bool
12 // Bytes -- bytes
13 // Int -- int
14 // Float -- float
15 // String -- string
16 // *List -- list
17 // Tuple -- tuple
18 // *Dict -- dict
19 // *Set -- set
20 // *Function -- function (implemented in Starlark)
21 // *Builtin -- builtin_function_or_method (function or method implemented in Go)
22 //
23 // Client applications may define new data types that satisfy at least
24 // the Value interface. Such types may provide additional operations by
25 // implementing any of these optional interfaces:
26 //
27 // Callable -- value is callable like a function
28 // Comparable -- value defines its own comparison operations
29 // Container -- value supports the 'in' operator
30 // Iterable -- value is iterable using 'for' loops
31 // Sequence -- value is iterable sequence of known length
32 // Indexable -- value is sequence with efficient random access
33 // Mapping -- value maps from keys to values, like a dictionary
34 // HasBinary -- value defines binary operations such as * and +
35 // HasAttrs -- value has readable fields or methods x.f
36 // HasSetField -- value has settable fields x.f
37 // HasSetIndex -- value supports element update using x[i]=y
38 // HasSetKey -- value supports map update using x[k]=v
39 // HasUnary -- value defines unary operations such as + and -
40 //
41 // Client applications may also define domain-specific functions in Go
42 // and make them available to Starlark programs. Use NewBuiltin to
43 // construct a built-in value that wraps a Go function. The
44 // implementation of the Go function may use UnpackArgs to make sense of
45 // the positional and keyword arguments provided by the caller.
46 //
47 // Starlark's None value is not equal to Go's nil. Go's nil is not a legal
48 // Starlark value, but the compiler will not stop you from converting nil
49 // to Value. Be careful to avoid allowing Go nil values to leak into
50 // Starlark data structures.
51 //
52 // The Compare operation requires two arguments of the same
53 // type, but this constraint cannot be expressed in Go's type system.
54 // (This is the classic "binary method problem".)
55 // So, each Value type's CompareSameType method is a partial function
56 // that compares a value only against others of the same type.
57 // Use the package's standalone Compare (or Equal) function to compare
58 // an arbitrary pair of values.
59 //
60 // To parse and evaluate a Starlark source file, use ExecFile. The Eval
61 // function evaluates a single expression. All evaluator functions
62 // require a Thread parameter which defines the "thread-local storage"
63 // of a Starlark thread and may be used to plumb application state
64 // through Starlark code and into callbacks. When evaluation fails it
65 // returns an EvalError from which the application may obtain a
66 // backtrace of active Starlark calls.
67 package starlark // import "go.starlark.net/starlark"
68
69 // This file defines the data types of Starlark and their basic operations.
70
71 import (
72 "fmt"
73 "iter"
74 "math"
75 "math/big"
76 "reflect"
77 "slices"
78 "strconv"
79 "strings"
80 "unicode/utf8"
81
82 "go.starlark.net/internal/compile"
83 "go.starlark.net/syntax"
84 )
85
86 // Value is a value in the Starlark interpreter.
87 type Value interface {
88 // String returns the string representation of the value.
89 // Starlark string values are quoted as if by Python's repr.
90 String() string
91
92 // Type returns a short string describing the value's type.
93 Type() string
94
95 // Freeze causes the value, and all values transitively
96 // reachable from it through collections and closures, to be
97 // marked as frozen. All subsequent mutations to the data
98 // structure through this API will fail dynamically, making the
99 // data structure immutable and safe for publishing to other
100 // Starlark interpreters running concurrently.
101 //
102 // Implementations of Freeze must be defensive against
103 // reference cycles; this can be achieved by first checking
104 // the value's frozen state, then setting it, and only then
105 // visiting any other values that it references.
106 Freeze()
107
108 // Truth returns the truth value of an object.
109 Truth() Bool
110
111 // Hash returns a function of x such that Equals(x, y) => Hash(x) == Hash(y).
112 // Hash may fail if the value's type is not hashable, or if the value
113 // contains a non-hashable value. The hash is used only by dictionaries and
114 // is not exposed to the Starlark program.
115 Hash() (uint32, error)
116 }
117
118 // A Comparable is a value that defines its own equivalence relation and
119 // perhaps ordered comparisons.
120 type Comparable interface {
121 Value
122 // CompareSameType compares one value to another of the same Type().
123 // The comparison operation must be one of EQL, NEQ, LT, LE, GT, or GE.
124 // CompareSameType returns an error if an ordered comparison was
125 // requested for a type that does not support it.
126 //
127 // Implementations that recursively compare subcomponents of
128 // the value should use the CompareDepth function, not Compare, to
129 // avoid infinite recursion on cyclic structures.
130 //
131 // The depth parameter is used to bound comparisons of cyclic
132 // data structures. Implementations should decrement depth
133 // before calling CompareDepth and should return an error if depth
134 // < 1.
135 //
136 // Client code should not call this method. Instead, use the
137 // standalone Compare or Equals functions, which are defined for
138 // all pairs of operands.
139 CompareSameType(op syntax.Token, y Value, depth int) (bool, error)
140 }
141
142 // A TotallyOrdered is a type whose values form a total order:
143 // if x and y are of the same TotallyOrdered type, then x must be less than y,
144 // greater than y, or equal to y.
145 //
146 // It is simpler than Comparable and should be preferred in new code,
147 // but if a type implements both interfaces, Comparable takes precedence.
148 type TotallyOrdered interface {
149 Value
150 // Cmp compares two values x and y of the same totally ordered type.
151 // It returns negative if x < y, positive if x > y, and zero if the values are equal.
152 //
153 // Implementations that recursively compare subcomponents of
154 // the value should use the CompareDepth function, not Cmp, to
155 // avoid infinite recursion on cyclic structures.
156 //
157 // The depth parameter is used to bound comparisons of cyclic
158 // data structures. Implementations should decrement depth
159 // before calling CompareDepth and should return an error if depth
160 // < 1.
161 //
162 // Client code should not call this method. Instead, use the
163 // standalone Compare or Equals functions, which are defined for
164 // all pairs of operands.
165 Cmp(y Value, depth int) (int, error)
166 }
167
168 var (
169 _ TotallyOrdered = Int{}
170 _ TotallyOrdered = Float(0)
171 _ Comparable = False
172 _ Comparable = String("")
173 _ Comparable = (*Dict)(nil)
174 _ Comparable = (*List)(nil)
175 _ Comparable = Tuple(nil)
176 _ Comparable = (*Set)(nil)
177 )
178
179 // A Callable value f may be the operand of a function call, f(x).
180 //
181 // Clients should use the Call function, never the CallInternal method.
182 type Callable interface {
183 Value
184 Name() string
185 CallInternal(thread *Thread, args Tuple, kwargs []Tuple) (Value, error)
186 }
187
188 type callableWithPosition interface {
189 Callable
190 Position() syntax.Position
191 }
192
193 var (
194 _ Callable = (*Builtin)(nil)
195 _ Callable = (*Function)(nil)
196 _ callableWithPosition = (*Function)(nil)
197 )
198
199 // An Iterable abstracts a sequence of values.
200 // An iterable value may be iterated over by a 'for' loop or used where
201 // any other Starlark iterable is allowed. Unlike a Sequence, the length
202 // of an Iterable is not necessarily known in advance of iteration.
203 type Iterable interface {
204 Value
205 Iterate() Iterator // must be followed by call to Iterator.Done
206 }
207
208 // A Sequence is a sequence of values of known length.
209 type Sequence interface {
210 Iterable
211 Len() int
212 }
213
214 var (
215 _ Sequence = (*Dict)(nil)
216 _ Sequence = (*Set)(nil)
217 )
218
219 // An Indexable is a sequence of known length that supports efficient random access.
220 // It is not necessarily iterable.
221 type Indexable interface {
222 Value
223 Index(i int) Value // requires 0 <= i < Len()
224 Len() int
225 }
226
227 // A Sliceable is a sequence that can be cut into pieces with the slice operator (x[i:j:step]).
228 //
229 // All native indexable objects are sliceable.
230 // This is a separate interface for backwards-compatibility.
231 type Sliceable interface {
232 Indexable
233 // For positive strides (step > 0), 0 <= start <= end <= n.
234 // For negative strides (step < 0), -1 <= end <= start < n.
235 // The caller must ensure that the start and end indices are valid
236 // and that step is non-zero.
237 Slice(start, end, step int) Value
238 }
239
240 // A Container is a value that supports the 'in' operator.
241 type Container interface {
242 Value
243 // Has reports whether the value contains the specified element.
244 Has(y Value) (bool, error)
245 }
246
247 // A HasSetIndex is an Indexable value whose elements may be assigned (x[i] = y).
248 //
249 // The implementation should not add Len to a negative index as the
250 // evaluator does this before the call.
251 type HasSetIndex interface {
252 Indexable
253 SetIndex(index int, v Value) error
254 }
255
256 var (
257 _ HasSetIndex = (*List)(nil)
258 _ Indexable = Tuple(nil)
259 _ Indexable = String("")
260 _ Sliceable = Tuple(nil)
261 _ Sliceable = String("")
262 _ Sliceable = (*List)(nil)
263 _ Container = Tuple(nil)
264 _ Container = String("")
265 _ Container = (*List)(nil)
266 _ Container = (*Set)(nil)
267 )
268
269 // An Iterator provides a sequence of values to the caller.
270 //
271 // The caller must call Done when the iterator is no longer needed.
272 // Operations that modify a sequence will fail if it has active iterators.
273 //
274 // Example usage:
275 //
276 // var seq Iterator = ...
277 // iter := seq.Iterate()
278 // defer iter.Done()
279 // var elem Value
280 // for iter.Next(&elem) {
281 // ...
282 // }
283 //
284 // Or, using go1.23 iterators:
285 //
286 // for elem := range Elements(seq) { ... }
287 type Iterator interface {
288 // If the iterator is exhausted, Next returns false.
289 // Otherwise it sets *p to the current element of the sequence,
290 // advances the iterator, and returns true.
291 Next(p *Value) bool
292 Done()
293 }
294
295 // A Mapping is a mapping from keys to values, such as a dictionary.
296 //
297 // If a type satisfies both Mapping and Iterable, the iterator yields
298 // the keys of the mapping.
299 type Mapping interface {
300 Value
301 // Get returns the value corresponding to the specified key,
302 // or !found if the mapping does not contain the key.
303 //
304 // Get also defines the behavior of "v in mapping".
305 // The 'in' operator reports the 'found' component, ignoring errors.
306 Get(Value) (v Value, found bool, err error)
307 }
308
309 // An IterableMapping is a mapping that supports key enumeration.
310 //
311 // See [Entries] for example use.
312 type IterableMapping interface {
313 Mapping
314 Iterate() Iterator // see Iterable interface
315 Items() []Tuple // a new slice containing all key/value pairs
316 }
317
318 var _ IterableMapping = (*Dict)(nil)
319
320 // A HasSetKey supports map update using x[k]=v syntax, like a dictionary.
321 type HasSetKey interface {
322 Mapping
323 SetKey(k, v Value) error
324 }
325
326 var _ HasSetKey = (*Dict)(nil)
327
328 // A HasBinary value may be used as either operand of these binary operators:
329 // + - * / // % in not in | & ^ << >>
330 //
331 // The Side argument indicates whether the receiver is the left or right operand.
332 //
333 // An implementation may decline to handle an operation by returning (nil, nil).
334 // For this reason, clients should always call the standalone Binary(op, x, y)
335 // function rather than calling the method directly.
336 type HasBinary interface {
337 Value
338 Binary(op syntax.Token, y Value, side Side) (Value, error)
339 }
340
341 type Side bool
342
343 const (
344 Left Side = false
345 Right Side = true
346 )
347
348 // A HasUnary value may be used as the operand of these unary operators:
349 // + - ~
350 //
351 // An implementation may decline to handle an operation by returning (nil, nil).
352 // For this reason, clients should always call the standalone Unary(op, x)
353 // function rather than calling the method directly.
354 type HasUnary interface {
355 Value
356 Unary(op syntax.Token) (Value, error)
357 }
358
359 // A HasAttrs value has fields or methods that may be read by a dot expression (y = x.f).
360 // Attribute names may be listed using the built-in 'dir' function.
361 //
362 // For implementation convenience, a result of (nil, nil) from Attr is
363 // interpreted as a "no such field or method" error. Implementations are
364 // free to return a more precise error.
365 type HasAttrs interface {
366 Value
367 Attr(name string) (Value, error) // returns (nil, nil) if attribute not present
368 AttrNames() []string // callers must not modify the result.
369 }
370
371 var (
372 _ HasAttrs = String("")
373 _ HasAttrs = new(List)
374 _ HasAttrs = new(Dict)
375 _ HasAttrs = new(Set)
376 )
377
378 // A HasSetField value has fields that may be written by a dot expression (x.f = y).
379 //
380 // An implementation of SetField may return a NoSuchAttrError,
381 // in which case the runtime may augment the error message to
382 // warn of possible misspelling.
383 type HasSetField interface {
384 HasAttrs
385 SetField(name string, val Value) error
386 }
387
388 // A NoSuchAttrError may be returned by an implementation of
389 // HasAttrs.Attr or HasSetField.SetField to indicate that no such field
390 // exists. In that case the runtime may augment the error message to
391 // warn of possible misspelling.
392 type NoSuchAttrError string
393
394 func (e NoSuchAttrError) Error() string { return string(e) }
395
396 // NoneType is the type of None. Its only legal value is None.
397 // (We represent it as a number, not struct{}, so that None may be constant.)
398 type NoneType byte
399
400 const None = NoneType(0)
401
402 func (NoneType) String() string { return "None" }
403 func (NoneType) Type() string { return "NoneType" }
404 func (NoneType) Freeze() {} // immutable
405 func (NoneType) Truth() Bool { return False }
406 func (NoneType) Hash() (uint32, error) { return 0, nil }
407
408 // Bool is the type of a Starlark bool.
409 type Bool bool
410
411 const (
412 False Bool = false
413 True Bool = true
414 )
415
416 func (b Bool) String() string {
417 if b {
418 return "True"
419 } else {
420 return "False"
421 }
422 }
423 func (b Bool) Type() string { return "bool" }
424 func (b Bool) Freeze() {} // immutable
425 func (b Bool) Truth() Bool { return b }
426 func (b Bool) Hash() (uint32, error) { return uint32(b2i(bool(b))), nil }
427 func (x Bool) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) {
428 y := y_.(Bool)
429 return threeway(op, b2i(bool(x))-b2i(bool(y))), nil
430 }
431
432 // Float is the type of a Starlark float.
433 type Float float64
434
435 func (f Float) String() string {
436 var buf strings.Builder
437 f.format(&buf, 'g')
438 return buf.String()
439 }
440
441 func (f Float) format(buf *strings.Builder, conv byte) {
442 ff := float64(f)
443 if !isFinite(ff) {
444 if math.IsInf(ff, +1) {
445 buf.WriteString("+inf")
446 } else if math.IsInf(ff, -1) {
447 buf.WriteString("-inf")
448 } else {
449 buf.WriteString("nan")
450 }
451 return
452 }
453
454 // %g is the default format used by str.
455 // It uses the minimum precision to avoid ambiguity,
456 // and always includes a '.' or an 'e' so that the value
457 // is self-evidently a float, not an int.
458 if conv == 'g' || conv == 'G' {
459 s := strconv.FormatFloat(ff, conv, -1, 64)
460 buf.WriteString(s)
461 // Ensure result always has a decimal point if no exponent.
462 // "123" -> "123.0"
463 if strings.IndexByte(s, conv-'g'+'e') < 0 && strings.IndexByte(s, '.') < 0 {
464 buf.WriteString(".0")
465 }
466 return
467 }
468
469 // %[eEfF] use 6-digit precision
470 buf.WriteString(strconv.FormatFloat(ff, conv, 6, 64))
471 }
472
473 func (f Float) Type() string { return "float" }
474 func (f Float) Freeze() {} // immutable
475 func (f Float) Truth() Bool { return f != 0.0 }
476 func (f Float) Hash() (uint32, error) {
477 // Equal float and int values must yield the same hash.
478 // TODO(adonovan): opt: if f is non-integral, and thus not equal
479 // to any Int, we can avoid the Int conversion and use a cheaper hash.
480 if isFinite(float64(f)) {
481 return finiteFloatToInt(f).Hash()
482 }
483 return 1618033, nil // NaN, +/-Inf
484 }
485
486 func floor(f Float) Float { return Float(math.Floor(float64(f))) }
487
488 // isFinite reports whether f represents a finite rational value.
489 // It is equivalent to !math.IsNan(f) && !math.IsInf(f, 0).
490 func isFinite(f float64) bool {
491 return math.Abs(f) <= math.MaxFloat64
492 }
493
494 // Cmp implements comparison of two Float values.
495 // Required by the TotallyOrdered interface.
496 func (f Float) Cmp(v Value, depth int) (int, error) {
497 g := v.(Float)
498 return floatCmp(f, g), nil
499 }
500
501 // floatCmp performs a three-valued comparison on floats,
502 // which are totally ordered with NaN > +Inf.
503 func floatCmp(x, y Float) int {
504 if x > y {
505 return +1
506 } else if x < y {
507 return -1
508 } else if x == y {
509 return 0
510 }
511
512 // At least one operand is NaN.
513 if x == x {
514 return -1 // y is NaN
515 } else if y == y {
516 return +1 // x is NaN
517 }
518 return 0 // both NaN
519 }
520
521 func (f Float) rational() *big.Rat { return new(big.Rat).SetFloat64(float64(f)) }
522
523 // AsFloat returns the float64 value closest to x.
524 // The f result is undefined if x is not a float or Int.
525 // The result may be infinite if x is a very large Int.
526 func AsFloat(x Value) (f float64, ok bool) {
527 switch x := x.(type) {
528 case Float:
529 return float64(x), true
530 case Int:
531 return float64(x.Float()), true
532 }
533 return 0, false
534 }
535
536 func (x Float) Mod(y Float) Float {
537 z := Float(math.Mod(float64(x), float64(y)))
538 if (x < 0) != (y < 0) && z != 0 {
539 z += y
540 }
541 return z
542 }
543
544 // Unary implements the operations +float and -float.
545 func (f Float) Unary(op syntax.Token) (Value, error) {
546 switch op {
547 case syntax.MINUS:
548 return -f, nil
549 case syntax.PLUS:
550 return +f, nil
551 }
552 return nil, nil
553 }
554
555 // String is the type of a Starlark text string.
556 //
557 // A String encapsulates an immutable sequence of bytes,
558 // but strings are not directly iterable. Instead, iterate
559 // over the result of calling one of these four methods:
560 // codepoints, codepoint_ords, elems, elem_ords.
561 //
562 // Strings typically contain text; use Bytes for binary strings.
563 // The Starlark spec defines text strings as sequences of UTF-k
564 // codes that encode Unicode code points. In this Go implementation,
565 // k=8, whereas in a Java implementation, k=16. For portability,
566 // operations on strings should aim to avoid assumptions about
567 // the value of k.
568 //
569 // Warning: the contract of the Value interface's String method is that
570 // it returns the value printed in Starlark notation,
571 // so s.String() or fmt.Sprintf("%s", s) returns a quoted string.
572 // Use string(s) or s.GoString() or fmt.Sprintf("%#v", s) to obtain the raw contents
573 // of a Starlark string as a Go string.
574 type String string
575
576 func (s String) String() string { return syntax.Quote(string(s), false) }
577 func (s String) GoString() string { return string(s) }
578 func (s String) Type() string { return "string" }
579 func (s String) Freeze() {} // immutable
580 func (s String) Truth() Bool { return len(s) > 0 }
581 func (s String) Hash() (uint32, error) { return hashString(string(s)), nil }
582 func (s String) Len() int { return len(s) } // bytes
583 func (s String) Index(i int) Value { return s[i : i+1] }
584
585 func (s String) Slice(start, end, step int) Value {
586 if step == 1 {
587 return s[start:end]
588 }
589
590 sign := signum(step)
591 var str []byte
592 for i := start; signum(end-i) == sign; i += step {
593 str = append(str, s[i])
594 }
595 return String(str)
596 }
597
598 func (s String) Attr(name string) (Value, error) { return builtinAttr(s, name, stringMethods) }
599 func (s String) AttrNames() []string { return builtinAttrNames(stringMethods) }
600
601 func (x String) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) {
602 y := y_.(String)
603 return threeway(op, strings.Compare(string(x), string(y))), nil
604 }
605
606 func (s String) Has(y Value) (bool, error) {
607 needle, ok := y.(String)
608 if !ok {
609 return false, fmt.Errorf("'in <string>' requires string as left operand, not %s", y.Type())
610 }
611 return strings.Contains(string(s), string(needle)), nil
612 }
613
614 func AsString(x Value) (string, bool) { v, ok := x.(String); return string(v), ok }
615
616 // A stringElems is an iterable whose iterator yields a sequence of
617 // elements (bytes), either numerically or as successive substrings.
618 // It is an indexable sequence.
619 type stringElems struct {
620 s String
621 ords bool
622 }
623
624 var (
625 _ Iterable = (*stringElems)(nil)
626 _ Indexable = (*stringElems)(nil)
627 )
628
629 func (si stringElems) String() string {
630 if si.ords {
631 return si.s.String() + ".elem_ords()"
632 } else {
633 return si.s.String() + ".elems()"
634 }
635 }
636 func (si stringElems) Type() string { return "string.elems" }
637 func (si stringElems) Freeze() {} // immutable
638 func (si stringElems) Truth() Bool { return True }
639 func (si stringElems) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable: %s", si.Type()) }
640 func (si stringElems) Iterate() Iterator { return &stringElemsIterator{si, 0} }
641 func (si stringElems) Len() int { return len(si.s) }
642 func (si stringElems) Index(i int) Value {
643 if si.ords {
644 return MakeInt(int(si.s[i]))
645 } else {
646 // TODO(adonovan): opt: preallocate canonical 1-byte strings
647 // to avoid interface allocation.
648 return si.s[i : i+1]
649 }
650 }
651
652 type stringElemsIterator struct {
653 si stringElems
654 i int
655 }
656
657 func (it *stringElemsIterator) Next(p *Value) bool {
658 if it.i == len(it.si.s) {
659 return false
660 }
661 *p = it.si.Index(it.i)
662 it.i++
663 return true
664 }
665
666 func (*stringElemsIterator) Done() {}
667
668 // A stringCodepoints is an iterable whose iterator yields a sequence of
669 // Unicode code points, either numerically or as successive substrings.
670 // It is not indexable.
671 type stringCodepoints struct {
672 s String
673 ords bool
674 }
675
676 var _ Iterable = (*stringCodepoints)(nil)
677
678 func (si stringCodepoints) String() string {
679 if si.ords {
680 return si.s.String() + ".codepoint_ords()"
681 } else {
682 return si.s.String() + ".codepoints()"
683 }
684 }
685 func (si stringCodepoints) Type() string { return "string.codepoints" }
686 func (si stringCodepoints) Freeze() {} // immutable
687 func (si stringCodepoints) Truth() Bool { return True }
688 func (si stringCodepoints) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable: %s", si.Type()) }
689 func (si stringCodepoints) Iterate() Iterator { return &stringCodepointsIterator{si, 0} }
690
691 type stringCodepointsIterator struct {
692 si stringCodepoints
693 i int
694 }
695
696 func (it *stringCodepointsIterator) Next(p *Value) bool {
697 s := it.si.s[it.i:]
698 if s == "" {
699 return false
700 }
701 r, sz := utf8.DecodeRuneInString(string(s))
702 if !it.si.ords {
703 if r == utf8.RuneError {
704 *p = String(r)
705 } else {
706 *p = s[:sz]
707 }
708 } else {
709 *p = MakeInt(int(r))
710 }
711 it.i += sz
712 return true
713 }
714
715 func (*stringCodepointsIterator) Done() {}
716
717 // A Function is a function defined by a Starlark def statement or lambda expression.
718 // The initialization behavior of a Starlark module is also represented by a Function.
719 type Function struct {
720 funcode *compile.Funcode
721 module *Module
722 defaults Tuple
723 freevars Tuple
724 }
725
726 // A Module represents an evaluated Starlark module.
727 // It is the dynamic counterpart to a [Program].
728 // All functions in the same program share a Module.
729 type Module struct {
730 program *Program
731 predeclared StringDict
732 globals []Value
733 constants []Value
734 }
735
736 // Program returns the program from which this module was constructed.
737 func (m *Module) Program() *Program {
738 return m.program
739 }
740
741 // Globals returns a new StringDict containing all global
742 // variables so far defined in the module.
743 func (m *Module) Globals() StringDict {
744 r := make(StringDict, len(m.program.compiled.Globals))
745 for i, id := range m.program.compiled.Globals {
746 if v := m.globals[i]; v != nil {
747 r[id.Name] = v
748 }
749 }
750 return r
751 }
752
753 // Predeclared returns the predeclared environment used
754 // to construct this module.
755 func (m *Module) Predeclared() StringDict {
756 return m.predeclared
757 }
758
759 func (fn *Function) Name() string { return fn.funcode.Name } // "lambda" for anonymous functions
760 func (fn *Function) Doc() string { return fn.funcode.Doc }
761 func (fn *Function) Hash() (uint32, error) { return hashString(fn.funcode.Name), nil }
762 func (fn *Function) Freeze() { fn.defaults.Freeze(); fn.freevars.Freeze() }
763 func (fn *Function) String() string { return toString(fn) }
764 func (fn *Function) Type() string { return "function" }
765 func (fn *Function) Truth() Bool { return true }
766 func (fn *Function) Module() *Module { return fn.module }
767
768 // Globals returns a new StringDict containing all global
769 // variables so far defined in the function's module.
770 //
771 // fn.Globals() is equivalent to fn.Module().Globals().
772 func (fn *Function) Globals() StringDict { return fn.module.Globals() }
773
774 func (fn *Function) Position() syntax.Position { return fn.funcode.Pos }
775 func (fn *Function) NumParams() int { return fn.funcode.NumParams }
776 func (fn *Function) NumKwonlyParams() int { return fn.funcode.NumKwonlyParams }
777
778 // Param returns the name and position of the ith parameter,
779 // where 0 <= i < NumParams().
780 // The *args and **kwargs parameters are at the end
781 // even if there were optional parameters after *args.
782 func (fn *Function) Param(i int) (string, syntax.Position) {
783 if i >= fn.NumParams() {
784 panic(i)
785 }
786 id := fn.funcode.Locals[i]
787 return id.Name, id.Pos
788 }
789
790 // ParamDefault returns the default value of the specified parameter
791 // (0 <= i < NumParams()), or nil if the parameter is not optional.
792 func (fn *Function) ParamDefault(i int) Value {
793 if i < 0 || i >= fn.NumParams() {
794 panic(i)
795 }
796
797 // fn.defaults omits all required params up to the first optional param. It
798 // also does not include *args or **kwargs at the end.
799 firstOptIdx := fn.NumParams() - len(fn.defaults)
800 if fn.HasVarargs() {
801 firstOptIdx--
802 }
803 if fn.HasKwargs() {
804 firstOptIdx--
805 }
806 if i < firstOptIdx || i >= firstOptIdx+len(fn.defaults) {
807 return nil
808 }
809
810 dflt := fn.defaults[i-firstOptIdx]
811 if is[mandatory](dflt) {
812 return nil
813 }
814 return dflt
815 }
816
817 func (fn *Function) HasVarargs() bool { return fn.funcode.HasVarargs }
818 func (fn *Function) HasKwargs() bool { return fn.funcode.HasKwargs }
819
820 // NumFreeVars returns the number of free variables of this function.
821 func (fn *Function) NumFreeVars() int { return len(fn.funcode.FreeVars) }
822
823 // FreeVar returns the binding (name and binding position) and value
824 // of the i'th free variable of function fn.
825 func (fn *Function) FreeVar(i int) (Binding, Value) {
826 return Binding(fn.funcode.FreeVars[i]), fn.freevars[i].(*cell).v
827 }
828
829 // A Builtin is a function implemented in Go.
830 type Builtin struct {
831 name string
832 fn func(thread *Thread, fn *Builtin, args Tuple, kwargs []Tuple) (Value, error)
833 recv Value // for bound methods (e.g. "".startswith)
834 }
835
836 func (b *Builtin) Name() string { return b.name }
837 func (b *Builtin) Freeze() {
838 if b.recv != nil {
839 b.recv.Freeze()
840 }
841 }
842 func (b *Builtin) Hash() (uint32, error) {
843 h := hashString(b.name)
844 if b.recv != nil {
845 h ^= 5521
846 }
847 return h, nil
848 }
849 func (b *Builtin) Receiver() Value { return b.recv }
850 func (b *Builtin) String() string { return toString(b) }
851 func (b *Builtin) Type() string { return "builtin_function_or_method" }
852 func (b *Builtin) CallInternal(thread *Thread, args Tuple, kwargs []Tuple) (Value, error) {
853 return b.fn(thread, b, args, kwargs)
854 }
855 func (b *Builtin) Truth() Bool { return true }
856
857 // NewBuiltin returns a new 'builtin_function_or_method' value with the specified name
858 // and implementation. It compares unequal with all other values.
859 func NewBuiltin(name string, fn func(thread *Thread, fn *Builtin, args Tuple, kwargs []Tuple) (Value, error)) *Builtin {
860 return &Builtin{name: name, fn: fn}
861 }
862
863 // BindReceiver returns a new Builtin value representing a method
864 // closure, that is, a built-in function bound to a receiver value.
865 //
866 // In the example below, the value of f is the string.index
867 // built-in method bound to the receiver value "abc":
868 //
869 // f = "abc".index; f("a"); f("b")
870 //
871 // In the common case, the receiver is bound only during the call,
872 // but this still results in the creation of a temporary method closure:
873 //
874 // "abc".index("a")
875 func (b *Builtin) BindReceiver(recv Value) *Builtin {
876 return &Builtin{name: b.name, fn: b.fn, recv: recv}
877 }
878
879 // A *Dict represents a Starlark dictionary.
880 // The zero value of Dict is a valid empty dictionary.
881 // If you know the exact final number of entries,
882 // it is more efficient to call NewDict.
883 type Dict struct {
884 ht hashtable
885 }
886
887 // NewDict returns a set with initial space for
888 // at least size insertions before rehashing.
889 func NewDict(size int) *Dict {
890 dict := new(Dict)
891 dict.ht.init(size)
892 return dict
893 }
894
895 func (d *Dict) Clear() error { return d.ht.clear() }
896 func (d *Dict) Delete(k Value) (v Value, found bool, err error) { return d.ht.delete(k) }
897 func (d *Dict) Get(k Value) (v Value, found bool, err error) { return d.ht.lookup(k) }
898 func (d *Dict) Items() []Tuple { return d.ht.items() }
899 func (d *Dict) Keys() []Value { return d.ht.keys() }
900 func (d *Dict) Len() int { return int(d.ht.len) }
901 func (d *Dict) Iterate() Iterator { return d.ht.iterate() }
902 func (d *Dict) Entries() iter.Seq2[Value, Value] { return d.ht.entries }
903 func (d *Dict) SetKey(k, v Value) error { return d.ht.insert(k, v) }
904 func (d *Dict) String() string { return toString(d) }
905 func (d *Dict) Type() string { return "dict" }
906 func (d *Dict) Freeze() { d.ht.freeze() }
907 func (d *Dict) Truth() Bool { return d.Len() > 0 }
908 func (d *Dict) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable type: dict") }
909
910 func (x *Dict) Union(y *Dict) *Dict {
911 z := new(Dict)
912 z.ht.init(x.Len()) // a lower bound
913 z.ht.addAll(&x.ht) // can't fail
914 z.ht.addAll(&y.ht) // can't fail
915 return z
916 }
917
918 func (d *Dict) Attr(name string) (Value, error) { return builtinAttr(d, name, dictMethods) }
919 func (d *Dict) AttrNames() []string { return builtinAttrNames(dictMethods) }
920
921 func (x *Dict) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) {
922 y := y_.(*Dict)
923 switch op {
924 case syntax.EQL:
925 ok, err := dictsEqual(x, y, depth)
926 return ok, err
927 case syntax.NEQ:
928 ok, err := dictsEqual(x, y, depth)
929 return !ok, err
930 default:
931 return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type())
932 }
933 }
934
935 func dictsEqual(x, y *Dict, depth int) (bool, error) {
936 if x.Len() != y.Len() {
937 return false, nil
938 }
939 for e := x.ht.head; e != nil; e = e.next {
940 key, xval := e.key, e.value
941
942 if yval, found, _ := y.Get(key); !found {
943 return false, nil
944 } else if eq, err := EqualDepth(xval, yval, depth-1); err != nil {
945 return false, err
946 } else if !eq {
947 return false, nil
948 }
949 }
950 return true, nil
951 }
952
953 // A *List represents a Starlark list value.
954 type List struct {
955 elems []Value
956 frozen bool
957 itercount uint32 // number of active iterators (ignored if frozen)
958 }
959
960 // NewList returns a list containing the specified elements.
961 // Callers should not subsequently modify elems.
962 func NewList(elems []Value) *List { return &List{elems: elems} }
963
964 func (l *List) Freeze() {
965 if !l.frozen {
966 l.frozen = true
967 for _, elem := range l.elems {
968 elem.Freeze()
969 }
970 }
971 }
972
973 // checkMutable reports an error if the list should not be mutated.
974 // verb+" list" should describe the operation.
975 func (l *List) checkMutable(verb string) error {
976 if l.frozen {
977 return fmt.Errorf("cannot %s frozen list", verb)
978 }
979 if l.itercount > 0 {
980 return fmt.Errorf("cannot %s list during iteration", verb)
981 }
982 return nil
983 }
984
985 func (l *List) String() string { return toString(l) }
986 func (l *List) Type() string { return "list" }
987 func (l *List) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable type: list") }
988 func (l *List) Truth() Bool { return l.Len() > 0 }
989 func (l *List) Len() int { return len(l.elems) }
990 func (l *List) Index(i int) Value { return l.elems[i] }
991
992 func (l *List) Slice(start, end, step int) Value {
993 if step == 1 {
994 elems := append([]Value{}, l.elems[start:end]...)
995 return NewList(elems)
996 }
997
998 sign := signum(step)
999 var list []Value
1000 for i := start; signum(end-i) == sign; i += step {
1001 list = append(list, l.elems[i])
1002 }
1003 return NewList(list)
1004 }
1005
1006 func (l *List) Attr(name string) (Value, error) { return builtinAttr(l, name, listMethods) }
1007 func (l *List) AttrNames() []string { return builtinAttrNames(listMethods) }
1008
1009 func (l *List) Iterate() Iterator {
1010 if !l.frozen {
1011 l.itercount++
1012 }
1013 return &listIterator{l: l}
1014 }
1015
1016 // Elements returns an iterator over the sequence of elements of the list.
1017 //
1018 // Example:
1019 //
1020 // for elem := range list.Elements() { ... }
1021 func (l *List) Elements() iter.Seq[Value] {
1022 return func(yield func(Value) bool) {
1023 if !l.frozen {
1024 l.itercount++
1025 defer func() { l.itercount-- }()
1026 }
1027 for _, x := range l.elems {
1028 if !yield(x) {
1029 break
1030 }
1031 }
1032 }
1033 }
1034
1035 func (l *List) Has(y Value) (bool, error) {
1036 for _, x := range l.elems {
1037 if eq, err := Equal(x, y); err != nil {
1038 return false, err
1039 } else if eq {
1040 return true, nil
1041 }
1042 }
1043 return false, nil
1044 }
1045
1046 func (x *List) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) {
1047 y := y_.(*List)
1048 // It's tempting to check x == y as an optimization here,
1049 // but wrong because a list containing NaN is not equal to itself.
1050 return sliceCompare(op, x.elems, y.elems, depth)
1051 }
1052
1053 func sliceCompare(op syntax.Token, x, y []Value, depth int) (bool, error) {
1054 // Fast path: check length.
1055 if len(x) != len(y) && (op == syntax.EQL || op == syntax.NEQ) {
1056 return op == syntax.NEQ, nil
1057 }
1058
1059 // Find first element that is not equal in both lists.
1060 for i := 0; i < len(x) && i < len(y); i++ {
1061 if eq, err := EqualDepth(x[i], y[i], depth-1); err != nil {
1062 return false, err
1063 } else if !eq {
1064 switch op {
1065 case syntax.EQL:
1066 return false, nil
1067 case syntax.NEQ:
1068 return true, nil
1069 default:
1070 return CompareDepth(op, x[i], y[i], depth-1)
1071 }
1072 }
1073 }
1074
1075 return threeway(op, len(x)-len(y)), nil
1076 }
1077
1078 type listIterator struct {
1079 l *List
1080 i int
1081 }
1082
1083 func (it *listIterator) Next(p *Value) bool {
1084 if it.i < it.l.Len() {
1085 *p = it.l.elems[it.i]
1086 it.i++
1087 return true
1088 }
1089 return false
1090 }
1091
1092 func (it *listIterator) Done() {
1093 if !it.l.frozen {
1094 it.l.itercount--
1095 }
1096 }
1097
1098 func (l *List) SetIndex(i int, v Value) error {
1099 if err := l.checkMutable("assign to element of"); err != nil {
1100 return err
1101 }
1102 l.elems[i] = v
1103 return nil
1104 }
1105
1106 func (l *List) Append(v Value) error {
1107 if err := l.checkMutable("append to"); err != nil {
1108 return err
1109 }
1110 l.elems = append(l.elems, v)
1111 return nil
1112 }
1113
1114 func (l *List) Clear() error {
1115 if err := l.checkMutable("clear"); err != nil {
1116 return err
1117 }
1118 for i := range l.elems {
1119 l.elems[i] = nil // aid GC
1120 }
1121 l.elems = l.elems[:0]
1122 return nil
1123 }
1124
1125 // A Tuple represents a Starlark tuple value.
1126 type Tuple []Value
1127
1128 func (t Tuple) Len() int { return len(t) }
1129 func (t Tuple) Index(i int) Value { return t[i] }
1130
1131 func (t Tuple) Slice(start, end, step int) Value {
1132 if step == 1 {
1133 return t[start:end]
1134 }
1135
1136 sign := signum(step)
1137 var tuple Tuple
1138 for i := start; signum(end-i) == sign; i += step {
1139 tuple = append(tuple, t[i])
1140 }
1141 return tuple
1142 }
1143
1144 func (t Tuple) Iterate() Iterator { return &tupleIterator{elems: t} }
1145
1146 // Elements returns an iterator over the sequence of elements of the tuple.
1147 //
1148 // (A Tuple is a slice, so it is of course directly iterable. This
1149 // method exists to provide a fast path for the [Elements] standalone
1150 // function.)
1151 func (t Tuple) Elements() iter.Seq[Value] {
1152 return func(yield func(Value) bool) {
1153 for _, x := range t {
1154 if !yield(x) {
1155 break
1156 }
1157 }
1158 }
1159 }
1160
1161 func (t Tuple) Freeze() {
1162 for _, elem := range t {
1163 elem.Freeze()
1164 }
1165 }
1166 func (t Tuple) String() string { return toString(t) }
1167 func (t Tuple) Type() string { return "tuple" }
1168 func (t Tuple) Truth() Bool { return len(t) > 0 }
1169
1170 func (x Tuple) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) {
1171 y := y_.(Tuple)
1172 return sliceCompare(op, x, y, depth)
1173 }
1174
1175 func (t Tuple) Has(y Value) (bool, error) {
1176 for _, x := range t {
1177 if eq, err := Equal(x, y); err != nil {
1178 return false, err
1179 } else if eq {
1180 return true, nil
1181 }
1182 }
1183 return false, nil
1184 }
1185
1186 func (t Tuple) Hash() (uint32, error) {
1187 // Use same algorithm as Python.
1188 var x, mult uint32 = 0x345678, 1000003
1189 for _, elem := range t {
1190 y, err := elem.Hash()
1191 if err != nil {
1192 return 0, err
1193 }
1194 x = x ^ y*mult
1195 mult += 82520 + uint32(len(t)+len(t))
1196 }
1197 return x, nil
1198 }
1199
1200 type tupleIterator struct{ elems Tuple }
1201
1202 func (it *tupleIterator) Next(p *Value) bool {
1203 if len(it.elems) > 0 {
1204 *p = it.elems[0]
1205 it.elems = it.elems[1:]
1206 return true
1207 }
1208 return false
1209 }
1210
1211 func (it *tupleIterator) Done() {}
1212
1213 // A Set represents a Starlark set value.
1214 // The zero value of Set is a valid empty set.
1215 // If you know the exact final number of elements,
1216 // it is more efficient to call NewSet.
1217 type Set struct {
1218 ht hashtable // values are all None
1219 }
1220
1221 // NewSet returns a dictionary with initial space for
1222 // at least size insertions before rehashing.
1223 func NewSet(size int) *Set {
1224 set := new(Set)
1225 set.ht.init(size)
1226 return set
1227 }
1228
1229 func (s *Set) Delete(k Value) (found bool, err error) { _, found, err = s.ht.delete(k); return }
1230 func (s *Set) Clear() error { return s.ht.clear() }
1231 func (s *Set) Has(k Value) (found bool, err error) { _, found, err = s.ht.lookup(k); return }
1232 func (s *Set) Insert(k Value) error { return s.ht.insert(k, None) }
1233 func (s *Set) Len() int { return int(s.ht.len) }
1234 func (s *Set) Iterate() Iterator { return s.ht.iterate() }
1235 func (s *Set) String() string { return toString(s) }
1236 func (s *Set) Type() string { return "set" }
1237 func (s *Set) Freeze() { s.ht.freeze() }
1238 func (s *Set) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable type: set") }
1239 func (s *Set) Truth() Bool { return s.Len() > 0 }
1240
1241 func (s *Set) Elements() iter.Seq[Value] {
1242 return func(yield func(k Value) bool) {
1243 s.ht.entries(func(k, _ Value) bool { return yield(k) })
1244 }
1245 }
1246
1247 func (s *Set) Attr(name string) (Value, error) { return builtinAttr(s, name, setMethods) }
1248 func (s *Set) AttrNames() []string { return builtinAttrNames(setMethods) }
1249
1250 func (x *Set) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) {
1251 y := y_.(*Set)
1252 switch op {
1253 case syntax.EQL:
1254 ok, err := setsEqual(x, y)
1255 return ok, err
1256 case syntax.NEQ:
1257 ok, err := setsEqual(x, y)
1258 return !ok, err
1259 case syntax.GE: // superset
1260 if x.Len() < y.Len() {
1261 return false, nil
1262 }
1263 iter := y.Iterate()
1264 defer iter.Done()
1265 return x.IsSuperset(iter)
1266 case syntax.LE: // subset
1267 if x.Len() > y.Len() {
1268 return false, nil
1269 }
1270 iter := y.Iterate()
1271 defer iter.Done()
1272 return x.IsSubset(iter)
1273 case syntax.GT: // proper superset
1274 if x.Len() <= y.Len() {
1275 return false, nil
1276 }
1277 iter := y.Iterate()
1278 defer iter.Done()
1279 return x.IsSuperset(iter)
1280 case syntax.LT: // proper subset
1281 if x.Len() >= y.Len() {
1282 return false, nil
1283 }
1284 iter := y.Iterate()
1285 defer iter.Done()
1286 return x.IsSubset(iter)
1287 default:
1288 return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type())
1289 }
1290 }
1291
1292 func setsEqual(x, y *Set) (bool, error) {
1293 if x.Len() != y.Len() {
1294 return false, nil
1295 }
1296 for e := x.ht.head; e != nil; e = e.next {
1297 if found, _ := y.Has(e.key); !found {
1298 return false, nil
1299 }
1300 }
1301 return true, nil
1302 }
1303
1304 func (s *Set) clone() *Set {
1305 set := new(Set)
1306 for e := s.ht.head; e != nil; e = e.next {
1307 set.Insert(e.key) // can't fail
1308 }
1309 return set
1310 }
1311
1312 func (s *Set) Union(iter Iterator) (Value, error) {
1313 set := s.clone()
1314 var x Value
1315 for iter.Next(&x) {
1316 if err := set.Insert(x); err != nil {
1317 return nil, err
1318 }
1319 }
1320 return set, nil
1321 }
1322
1323 func (s *Set) InsertAll(iter Iterator) error {
1324 var x Value
1325 for iter.Next(&x) {
1326 if err := s.Insert(x); err != nil {
1327 return err
1328 }
1329 }
1330 return nil
1331 }
1332
1333 func (s *Set) Difference(other Iterator) (Value, error) {
1334 diff := s.clone()
1335 var x Value
1336 for other.Next(&x) {
1337 if _, err := diff.Delete(x); err != nil {
1338 return nil, err
1339 }
1340 }
1341 return diff, nil
1342 }
1343
1344 func (s *Set) IsSuperset(other Iterator) (bool, error) {
1345 var x Value
1346 for other.Next(&x) {
1347 found, err := s.Has(x)
1348 if err != nil {
1349 return false, err
1350 }
1351 if !found {
1352 return false, nil
1353 }
1354 }
1355 return true, nil
1356 }
1357
1358 func (s *Set) IsSubset(other Iterator) (bool, error) {
1359 if count, err := s.ht.count(other); err != nil {
1360 return false, err
1361 } else {
1362 return count == s.Len(), nil
1363 }
1364 }
1365
1366 func (s *Set) Intersection(other Iterator) (Value, error) {
1367 intersect := new(Set)
1368 var x Value
1369 for other.Next(&x) {
1370 found, err := s.Has(x)
1371 if err != nil {
1372 return nil, err
1373 }
1374 if found {
1375 err = intersect.Insert(x)
1376 if err != nil {
1377 return nil, err
1378 }
1379 }
1380 }
1381 return intersect, nil
1382 }
1383
1384 func (s *Set) SymmetricDifference(other Iterator) (Value, error) {
1385 diff := s.clone()
1386 var x Value
1387 for other.Next(&x) {
1388 found, err := diff.Delete(x)
1389 if err != nil {
1390 return nil, err
1391 }
1392 if !found {
1393 diff.Insert(x) // can't fail
1394 }
1395 }
1396 return diff, nil
1397 }
1398
1399 // toString returns the string form of value v.
1400 // It may be more efficient than v.String() for larger values.
1401 func toString(v Value) string {
1402 buf := new(strings.Builder)
1403 writeValue(buf, v, nil)
1404 return buf.String()
1405 }
1406
1407 // writeValue writes x to out.
1408 //
1409 // path is used to detect cycles.
1410 // It contains the list of *List and *Dict values we're currently printing.
1411 // (These are the only potentially cyclic structures.)
1412 // Callers should generally pass nil for path.
1413 // It is safe to re-use the same path slice for multiple calls.
1414 func writeValue(out *strings.Builder, x Value, path []Value) {
1415 switch x := x.(type) {
1416 case nil:
1417 out.WriteString("<nil>") // indicates a bug
1418
1419 // These four cases are duplicates of T.String(), for efficiency.
1420 case NoneType:
1421 out.WriteString("None")
1422
1423 case Int:
1424 out.WriteString(x.String())
1425
1426 case Bool:
1427 if x {
1428 out.WriteString("True")
1429 } else {
1430 out.WriteString("False")
1431 }
1432
1433 case String:
1434 out.WriteString(syntax.Quote(string(x), false))
1435
1436 case *List:
1437 out.WriteByte('[')
1438 if pathContains(path, x) {
1439 out.WriteString("...") // list contains itself
1440 } else {
1441 for i, elem := range x.elems {
1442 if i > 0 {
1443 out.WriteString(", ")
1444 }
1445 writeValue(out, elem, append(path, x))
1446 }
1447 }
1448 out.WriteByte(']')
1449
1450 case Tuple:
1451 out.WriteByte('(')
1452 for i, elem := range x {
1453 if i > 0 {
1454 out.WriteString(", ")
1455 }
1456 writeValue(out, elem, path)
1457 }
1458 if len(x) == 1 {
1459 out.WriteByte(',')
1460 }
1461 out.WriteByte(')')
1462
1463 case *Function:
1464 fmt.Fprintf(out, "<function %s>", x.Name())
1465
1466 case *Builtin:
1467 if x.recv != nil {
1468 fmt.Fprintf(out, "<built-in method %s of %s value>", x.Name(), x.recv.Type())
1469 } else {
1470 fmt.Fprintf(out, "<built-in function %s>", x.Name())
1471 }
1472
1473 case *Dict:
1474 out.WriteByte('{')
1475 if pathContains(path, x) {
1476 out.WriteString("...") // dict contains itself
1477 } else {
1478 sep := ""
1479 for e := x.ht.head; e != nil; e = e.next {
1480 k, v := e.key, e.value
1481 out.WriteString(sep)
1482 writeValue(out, k, path)
1483 out.WriteString(": ")
1484 writeValue(out, v, append(path, x)) // cycle check
1485 sep = ", "
1486 }
1487 }
1488 out.WriteByte('}')
1489
1490 case *Set:
1491 out.WriteString("set([")
1492 for e := x.ht.head; e != nil; e = e.next {
1493 if e != x.ht.head {
1494 out.WriteString(", ")
1495 }
1496 writeValue(out, e.key, path)
1497 }
1498 out.WriteString("])")
1499
1500 default:
1501 out.WriteString(x.String())
1502 }
1503 }
1504
1505 func pathContains(path []Value, x Value) bool {
1506 return slices.Contains(path, x)
1507 }
1508
1509 // CompareLimit is the depth limit on recursive comparison operations such as == and <.
1510 // Comparison of data structures deeper than this limit may fail.
1511 var CompareLimit = 10
1512
1513 // Equal reports whether two Starlark values are equal.
1514 func Equal(x, y Value) (bool, error) {
1515 if x, ok := x.(String); ok {
1516 return x == y, nil // fast path for an important special case
1517 }
1518 return EqualDepth(x, y, CompareLimit)
1519 }
1520
1521 // EqualDepth reports whether two Starlark values are equal.
1522 //
1523 // Recursive comparisons by implementations of Value.CompareSameType
1524 // should use EqualDepth to prevent infinite recursion.
1525 func EqualDepth(x, y Value, depth int) (bool, error) {
1526 return CompareDepth(syntax.EQL, x, y, depth)
1527 }
1528
1529 // Compare compares two Starlark values.
1530 // The comparison operation must be one of EQL, NEQ, LT, LE, GT, or GE.
1531 // Compare returns an error if an ordered comparison was
1532 // requested for a type that does not support it.
1533 //
1534 // Recursive comparisons by implementations of Value.CompareSameType
1535 // should use CompareDepth to prevent infinite recursion.
1536 func Compare(op syntax.Token, x, y Value) (bool, error) {
1537 return CompareDepth(op, x, y, CompareLimit)
1538 }
1539
1540 // CompareDepth compares two Starlark values.
1541 // The comparison operation must be one of EQL, NEQ, LT, LE, GT, or GE.
1542 // CompareDepth returns an error if an ordered comparison was
1543 // requested for a pair of values that do not support it.
1544 //
1545 // The depth parameter limits the maximum depth of recursion
1546 // in cyclic data structures.
1547 func CompareDepth(op syntax.Token, x, y Value, depth int) (bool, error) {
1548 if depth < 1 {
1549 return false, fmt.Errorf("comparison exceeded maximum recursion depth")
1550 }
1551 if sameType(x, y) {
1552 if xcomp, ok := x.(Comparable); ok {
1553 return xcomp.CompareSameType(op, y, depth)
1554 }
1555
1556 if xcomp, ok := x.(TotallyOrdered); ok {
1557 t, err := xcomp.Cmp(y, depth)
1558 if err != nil {
1559 return false, err
1560 }
1561 return threeway(op, t), nil
1562 }
1563
1564 // use identity comparison
1565 switch op {
1566 case syntax.EQL:
1567 return x == y, nil
1568 case syntax.NEQ:
1569 return x != y, nil
1570 }
1571 return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type())
1572 }
1573
1574 // different types
1575
1576 // int/float ordered comparisons
1577 switch x := x.(type) {
1578 case Int:
1579 if y, ok := y.(Float); ok {
1580 var cmp int
1581 if y != y {
1582 cmp = -1 // y is NaN
1583 } else if !math.IsInf(float64(y), 0) {
1584 cmp = x.rational().Cmp(y.rational()) // y is finite
1585 } else if y > 0 {
1586 cmp = -1 // y is +Inf
1587 } else {
1588 cmp = +1 // y is -Inf
1589 }
1590 return threeway(op, cmp), nil
1591 }
1592 case Float:
1593 if y, ok := y.(Int); ok {
1594 var cmp int
1595 if x != x {
1596 cmp = +1 // x is NaN
1597 } else if !math.IsInf(float64(x), 0) {
1598 cmp = x.rational().Cmp(y.rational()) // x is finite
1599 } else if x > 0 {
1600 cmp = +1 // x is +Inf
1601 } else {
1602 cmp = -1 // x is -Inf
1603 }
1604 return threeway(op, cmp), nil
1605 }
1606 }
1607
1608 // All other values of different types compare unequal.
1609 switch op {
1610 case syntax.EQL:
1611 return false, nil
1612 case syntax.NEQ:
1613 return true, nil
1614 }
1615 return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type())
1616 }
1617
1618 func sameType(x, y Value) bool {
1619 return reflect.TypeOf(x) == reflect.TypeOf(y) || x.Type() == y.Type()
1620 }
1621
1622 // threeway interprets a three-way comparison value cmp (-1, 0, +1)
1623 // as a boolean comparison (e.g. x < y).
1624 func threeway(op syntax.Token, cmp int) bool {
1625 switch op {
1626 case syntax.EQL:
1627 return cmp == 0
1628 case syntax.NEQ:
1629 return cmp != 0
1630 case syntax.LE:
1631 return cmp <= 0
1632 case syntax.LT:
1633 return cmp < 0
1634 case syntax.GE:
1635 return cmp >= 0
1636 case syntax.GT:
1637 return cmp > 0
1638 }
1639 panic(op)
1640 }
1641
1642 func b2i(b bool) int {
1643 if b {
1644 return 1
1645 } else {
1646 return 0
1647 }
1648 }
1649
1650 // Len returns the length of a string or sequence value,
1651 // and -1 for all others.
1652 //
1653 // Warning: Len(x) >= 0 does not imply Iterate(x) != nil.
1654 // A string has a known length but is not directly iterable.
1655 func Len(x Value) int {
1656 switch x := x.(type) {
1657 case String:
1658 return x.Len()
1659 case Indexable:
1660 return x.Len()
1661 case Sequence:
1662 return x.Len()
1663 }
1664 return -1
1665 }
1666
1667 // Iterate return a new iterator for the value if iterable, nil otherwise.
1668 // If the result is non-nil, the caller must call Done when finished with it.
1669 //
1670 // Warning: Iterate(x) != nil does not imply Len(x) >= 0.
1671 // Some iterables may have unknown length.
1672 func Iterate(x Value) Iterator {
1673 if x, ok := x.(Iterable); ok {
1674 return x.Iterate()
1675 }
1676 return nil
1677 }
1678
1679 // Elements returns an iterator over the sequence of elements of the iterable value.
1680 //
1681 // Example:
1682 //
1683 // for elem := range Elements(iterable) { ... }
1684 //
1685 // Push iterators are provided as a convenience for Go client code. The
1686 // core iteration behavior of Starlark for-loops is defined by the
1687 // [Iterable] interface.
1688 func Elements(iterable Iterable) iter.Seq[Value] {
1689 // Use specialized push iterator if available (*List, Tuple, *Set).
1690 type hasElements interface {
1691 Elements() iter.Seq[Value]
1692 }
1693 if iterable, ok := iterable.(hasElements); ok {
1694 return iterable.Elements()
1695 }
1696
1697 return func(yield func(Value) bool) {
1698 iter := iterable.Iterate()
1699 defer iter.Done()
1700 var x Value
1701 for iter.Next(&x) && yield(x) {
1702 }
1703 }
1704 }
1705
1706 // Entries returns an iterator over the sequence of entries (key/value pairs) of
1707 // the iterable mapping.
1708 //
1709 // Example:
1710 //
1711 // for k, v := range Entries(mapping) { ... }
1712 //
1713 // Push iterators are provided as a convenience for Go client code. The
1714 // core iteration behavior of Starlark for-loops is defined by the
1715 // [Iterable] interface.
1716 func Entries(mapping IterableMapping) iter.Seq2[Value, Value] {
1717 // If available (e.g. *Dict), use specialized push iterator,
1718 // as it gets k and v in one shot.
1719 type hasEntries interface {
1720 Entries() iter.Seq2[Value, Value]
1721 }
1722 if mapping, ok := mapping.(hasEntries); ok {
1723 return mapping.Entries()
1724 }
1725
1726 return func(yield func(k, v Value) bool) {
1727 iter := mapping.Iterate()
1728 defer iter.Done()
1729 var k Value
1730 for iter.Next(&k) {
1731 v, found, err := mapping.Get(k)
1732 if err != nil || !found {
1733 panic(fmt.Sprintf("Iterate and Get are inconsistent (mapping=%v, key=%v)",
1734 mapping.Type(), k.Type()))
1735 }
1736 if !yield(k, v) {
1737 break
1738 }
1739 }
1740 }
1741 }
1742
1743 // Bytes is the type of a Starlark binary string.
1744 //
1745 // A Bytes encapsulates an immutable sequence of bytes.
1746 // It is comparable, indexable, and sliceable, but not directly iterable;
1747 // use bytes.elems() for an iterable view.
1748 //
1749 // In this Go implementation, the elements of 'string' and 'bytes' are
1750 // both bytes, but in other implementations, notably Java, the elements
1751 // of a 'string' are UTF-16 codes (Java chars). The spec abstracts text
1752 // strings as sequences of UTF-k codes that encode Unicode code points,
1753 // and operations that convert from text to binary incur UTF-k-to-UTF-8
1754 // transcoding; conversely, conversion from binary to text incurs
1755 // UTF-8-to-UTF-k transcoding. Because k=8 for Go, these operations
1756 // are the identity function, at least for valid encodings of text.
1757 type Bytes string
1758
1759 var (
1760 _ Comparable = Bytes("")
1761 _ Sliceable = Bytes("")
1762 _ Indexable = Bytes("")
1763 _ Container = Bytes("")
1764 )
1765
1766 func (b Bytes) String() string { return syntax.Quote(string(b), true) }
1767 func (b Bytes) Type() string { return "bytes" }
1768 func (b Bytes) Freeze() {} // immutable
1769 func (b Bytes) Truth() Bool { return len(b) > 0 }
1770 func (b Bytes) Hash() (uint32, error) { return String(b).Hash() }
1771 func (b Bytes) Len() int { return len(b) }
1772 func (b Bytes) Index(i int) Value { return b[i : i+1] }
1773
1774 func (b Bytes) Attr(name string) (Value, error) { return builtinAttr(b, name, bytesMethods) }
1775 func (b Bytes) AttrNames() []string { return builtinAttrNames(bytesMethods) }
1776
1777 func (b Bytes) Slice(start, end, step int) Value {
1778 if step == 1 {
1779 return b[start:end]
1780 }
1781
1782 sign := signum(step)
1783 var str []byte
1784 for i := start; signum(end-i) == sign; i += step {
1785 str = append(str, b[i])
1786 }
1787 return Bytes(str)
1788 }
1789
1790 func (x Bytes) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) {
1791 y := y_.(Bytes)
1792 return threeway(op, strings.Compare(string(x), string(y))), nil
1793 }
1794
1795 func (b Bytes) Has(y Value) (bool, error) {
1796 switch needle := y.(type) {
1797 case Bytes:
1798 return strings.Contains(string(b), string(needle)), nil
1799 case Int:
1800 var by byte
1801 if err := AsInt(needle, &by); err != nil {
1802 return false, fmt.Errorf("int in bytes: %s", err)
1803 }
1804 return strings.IndexByte(string(b), by) >= 0, nil
1805 default:
1806 return false, fmt.Errorf("'in bytes' requires bytes or int as left operand, not %s", y.Type())
1807 }
1808 }