blob: 62724c7d084d8b395e9353da0c732d4f7228c3cf [file] [log] [blame]
Alan Donovan312d1a52017-10-02 10:10:28 -04001// 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 skylark provides a Skylark interpreter.
6//
7// Skylark 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// Int -- int
13// Float -- float
14// String -- string
15// *List -- list
16// Tuple -- tuple
17// *Dict -- dict
18// *Set -- set
19// *Function -- function (implemented in Skylark)
20// *Builtin -- builtin (function or method implemented in Go)
21//
22// Client applications may define new data types that satisfy at least
23// the Value interface. Such types may provide additional operations by
24// implementing any of these optional interfaces:
25//
26// Callable -- value is callable like a function
27// Comparable -- value defines its own comparison operations
28// Iterable -- value is iterable using 'for' loops
29// Sequence -- value is iterable sequence of known length
30// Indexable -- value is sequence with efficient random access
31// HasBinary -- value defines binary operations such as * and +
32// HasAttrs -- value has readable fields or methods x.f
33// HasSetField -- value has settable fields x.f
34// HasSetIndex -- value supports element update using x[i]=y
35//
36// Client applications may also define domain-specific functions in Go
37// and make them available to Skylark programs. Use NewBuiltin to
38// construct a built-in value that wraps a Go function. The
39// implementation of the Go function may use UnpackArgs to make sense of
40// the positional and keyword arguments provided by the caller.
41//
42// Skylark's None value is not equal to Go's nil, but nil may be
43// assigned to a Skylark Value. Be careful to avoid allowing Go nil
44// values to leak into Skylark data structures.
45//
46// The Compare operation requires two arguments of the same
47// type, but this constraint cannot be expressed in Go's type system.
48// (This is the classic "binary method problem".)
49// So, each Value type's CompareSameType method is a partial function
50// that compares a value only against others of the same type.
51// Use the package's standalone Compare (or Equal) function to compare
52// an arbitrary pair of values.
53//
54// To parse and evaluate a Skylark source file, use ExecFile. The Eval
55// function evaluates a single expression. All evaluator functions
56// require a Thread parameter which defines the "thread-local storage"
57// of a Skylark thread and may be used to plumb application state
58// through Sklyark code and into callbacks. When evaluation fails it
59// returns an EvalError from which the application may obtain a
60// backtrace of active Skylark calls.
61//
62package skylark
63
64// This file defines the data types of Skylark and their basic operations.
65
66import (
67 "bytes"
68 "fmt"
69 "math"
70 "math/big"
71 "reflect"
72 "strconv"
73 "strings"
74 "unicode/utf8"
75
76 "github.com/google/skylark/syntax"
77)
78
79// Value is a value in the Skylark interpreter.
80type Value interface {
81 // String returns the string representation of the value.
82 // Skylark string values are quoted as if by Python's repr.
83 String() string
84
85 // Type returns a short string describing the value's type.
86 Type() string
87
88 // Freeze causes the value, and all values transitively
89 // reachable from it through collections and closures, to be
90 // marked as frozen. All subsequent mutations to the data
91 // structure through this API will fail dynamically, making the
92 // data structure immutable and safe for publishing to other
93 // Skylark interpreters running concurrently.
94 Freeze()
95
96 // Truth returns the truth value of an object, according to Python rules.
97 // http://docs.python.org/2/library/stdtypes.html#truth-value-testing
98 Truth() Bool
99
100 // Hash returns a function of x such that Equals(x, y) => Hash(x) == Hash(y).
101 // Hash may fail if the value's type is not hashable, or if the value
102 // contains a non-hashable value.
103 Hash() (uint32, error)
104}
105
106// A Comparable is a value that defines its own equivalence relation and
107// perhaps ordered comparisons.
108type Comparable interface {
109 Value
110 // CompareSameType compares one value to another of the same Type().
111 // The comparison operation must be one of EQL, NEQ, LT, LE, GT, or GE.
112 // CompareSameType returns an error if an ordered comparison was
113 // requested for a type that does not support it.
114 //
115 // Implementations that recursively compare subcomponents of
116 // the value should use the CompareDepth function, not Compare, to
117 // avoid infinite recursion on cyclic structures.
118 //
119 // The depth parameter is used to bound comparisons of cyclic
120 // data structures. Implementations should decrement depth
121 // before calling CompareDepth and should return an error if depth
122 // < 1.
123 //
124 // Client code should not call this method. Instead, use the
125 // standalone Compare or Equals functions, which are defined for
126 // all pairs of operands.
127 CompareSameType(op syntax.Token, y Value, depth int) (bool, error)
128}
129
130var (
131 _ Comparable = None
132 _ Comparable = Int{}
133 _ Comparable = False
134 _ Comparable = Float(0)
135 _ Comparable = String("")
136 _ Comparable = (*Dict)(nil)
137 _ Comparable = (*List)(nil)
138 _ Comparable = Tuple(nil)
139 _ Comparable = (*Set)(nil)
140)
141
142// A Callable value f may be the operand of a function call, f(x).
143type Callable interface {
144 Value
145 Name() string
146 Call(thread *Thread, args Tuple, kwargs []Tuple) (Value, error)
147}
148
149var (
150 _ Callable = (*Builtin)(nil)
151 _ Callable = (*Function)(nil)
152)
153
154// An Iterable abstracts a sequence of values.
155// An iterable value may be iterated over by a 'for' loop or used where
156// any other Skylark iterable is allowed. Unlike a Sequence, the length
157// of an Iterable is not necessarily known in advance of iteration.
158type Iterable interface {
159 Value
160 Iterate() Iterator // must be followed by call to Iterator.Done
161}
162
163// A Sequence is a sequence of values of known length.
164type Sequence interface {
165 Iterable
166 Len() int
167}
168
169var (
170 _ Sequence = (*Dict)(nil)
171 _ Sequence = (*Set)(nil)
172)
173
174// An Indexable is a sequence of known length that supports efficient random access.
175// It is not necessarily iterable.
176type Indexable interface {
177 Value
178 Index(i int) Value // requires 0 <= i < Len()
179 Len() int
180}
181
182// A HasSetIndex is an Indexable value whose elements may be assigned (x[i] = y).
183//
184// The implementation should not add Len to a negative index as the
185// evaluator does this before the call.
186type HasSetIndex interface {
187 Indexable
188 SetIndex(index int, v Value) error
189}
190
191var (
192 _ HasSetIndex = (*List)(nil)
193 _ Indexable = Tuple(nil)
194 _ Indexable = String("")
195)
196
197// An Iterator provides a sequence of values to the caller.
198//
199// The caller must call Done when the iterator is no longer needed.
200// Operations that modify a sequence will fail if it has active iterators.
201//
202// Example usage:
203//
204// iter := iterable.Iterator()
205// defer iter.Done()
206// var x Value
207// for iter.Next(&x) {
208// ...
209// }
210//
211type Iterator interface {
212 // If the iterator is exhausted, Next returns false.
213 // Otherwise it sets *p to the current element of the sequence,
214 // advances the iterator, and returns true.
215 Next(p *Value) bool
216 Done()
217}
218
219// An Mapping is a mapping from keys to values, such as a dictionary.
220type Mapping interface {
221 Value
222 // Get returns the value corresponding to the specified key,
223 // or !found if the mapping does not contain the key.
224 Get(Value) (v Value, found bool, err error)
225}
226
227var _ Mapping = (*Dict)(nil)
228
229// A HasBinary value may be used as either operand of these binary operators:
230// + - * / % in not in | &
231// The Side argument indicates whether the receiver is the left or right operand.
232//
233// An implementation may decline to handle an operation by returning (nil, nil).
234// For this reason, clients should always call the standalone Binary(op, x, y)
235// function rather than calling the method directly.
236type HasBinary interface {
237 Value
238 Binary(op syntax.Token, y Value, side Side) (Value, error)
239}
240
241type Side bool
242
243const (
244 Left Side = false
245 Right Side = true
246)
247
248// A HasAttrs value has fields or methods that may be read by a dot expression (y = x.f).
249// Attribute names may be listed using the built-in 'dir' function.
250//
251// For implementation convenience, a result of (nil, nil) from Attr is
252// interpreted as a "no such field or method" error. Implementations are
253// free to return a more precise error.
254type HasAttrs interface {
255 Value
256 Attr(name string) (Value, error) // returns (nil, nil) if attribute not present
257 AttrNames() []string // callers must not modify the result.
258}
259
260var (
261 _ HasAttrs = String("")
262 _ HasAttrs = new(List)
263 _ HasAttrs = new(Dict)
264 _ HasAttrs = new(Set)
265)
266
267// A HasSetField value has fields that may be written by a dot expression (x.f = y).
268type HasSetField interface {
269 HasAttrs
270 SetField(name string, val Value) error
271}
272
273// NoneType is the type of None. Its only legal value is None.
274// (We represent it as a number, not struct{}, so that None may be constant.)
275type NoneType byte
276
277const None = NoneType(0)
278
279func (NoneType) String() string { return "None" }
280func (NoneType) Type() string { return "NoneType" }
281func (NoneType) Freeze() {} // immutable
282func (NoneType) Truth() Bool { return False }
283func (NoneType) Hash() (uint32, error) { return 0, nil }
284func (NoneType) CompareSameType(op syntax.Token, y Value, depth int) (bool, error) {
285 return threeway(op, 0), nil
286}
287
288// Bool is the type of a Skylark bool.
289type Bool bool
290
291const (
292 False Bool = false
293 True Bool = true
294)
295
296func (b Bool) String() string {
297 if b {
298 return "True"
299 } else {
300 return "False"
301 }
302}
303func (b Bool) Type() string { return "bool" }
304func (b Bool) Freeze() {} // immutable
305func (b Bool) Truth() Bool { return b }
306func (b Bool) Hash() (uint32, error) { return uint32(b2i(bool(b))), nil }
307func (x Bool) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) {
308 y := y_.(Bool)
309 return threeway(op, b2i(bool(x))-b2i(bool(y))), nil
310}
311
312// Float is the type of a Skylark float.
313type Float float64
314
315func (f Float) String() string { return strconv.FormatFloat(float64(f), 'g', 6, 64) }
316func (f Float) Type() string { return "float" }
317func (f Float) Freeze() {} // immutable
318func (f Float) Truth() Bool { return f != 0.0 }
319func (f Float) Hash() (uint32, error) {
320 // Equal float and int values must yield the same hash.
321 // TODO(adonovan): opt: if f is non-integral, and thus not equal
322 // to any Int, we can avoid the Int conversion and use a cheaper hash.
323 if isFinite(float64(f)) {
324 return finiteFloatToInt(f).Hash()
325 }
326 return 1618033, nil // NaN, +/-Inf
327}
328
329func floor(f Float) Float { return Float(math.Floor(float64(f))) }
330
331// isFinite reports whether f represents a finite rational value.
332// It is equivalent to !math.IsNan(f) && !math.IsInf(f, 0).
333func isFinite(f float64) bool {
334 return math.Abs(f) <= math.MaxFloat64
335}
336
337func (x Float) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) {
338 y := y_.(Float)
339 switch op {
340 case syntax.EQL:
341 return x == y, nil
342 case syntax.NEQ:
343 return x != y, nil
344 case syntax.LE:
345 return x <= y, nil
346 case syntax.LT:
347 return x < y, nil
348 case syntax.GE:
349 return x >= y, nil
350 case syntax.GT:
351 return x > y, nil
352 }
353 panic(op)
354}
355
356func (f Float) rational() *big.Rat { return new(big.Rat).SetFloat64(float64(f)) }
357
358// AsFloat returns the float64 value closest to x.
359// The f result is undefined if x is not a float or int.
360func AsFloat(x Value) (f float64, ok bool) {
361 switch x := x.(type) {
362 case Float:
363 return float64(x), true
364 case Int:
365 return float64(x.Float()), true
366 }
367 return 0, false
368}
369
370func (x Float) Mod(y Float) Float { return Float(math.Mod(float64(x), float64(y))) }
371
372// String is the type of a Skylark string.
373//
374// A String is an immutable sequence of bytes. Strings are iterable;
375// iteration over a string yields each of its 1-byte substrings in order.
376type String string
377
378func (s String) String() string { return strconv.Quote(string(s)) }
379func (s String) Type() string { return "string" }
380func (s String) Freeze() {} // immutable
381func (s String) Truth() Bool { return len(s) > 0 }
382func (s String) Hash() (uint32, error) { return hashString(string(s)), nil }
383func (s String) Len() int { return len(s) } // bytes
384func (s String) Index(i int) Value { return s[i : i+1] }
385
386func (s String) Attr(name string) (Value, error) { return builtinAttr(s, name, stringMethods) }
387func (s String) AttrNames() []string { return builtinAttrNames(stringMethods) }
388
389func (x String) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) {
390 y := y_.(String)
391 return threeway(op, strings.Compare(string(x), string(y))), nil
392}
393
394func AsString(x Value) (string, bool) { v, ok := x.(String); return string(v), ok }
395
396// A stringIterable is an iterable whose iterator yields a sequence of
397// either Unicode code points or bytes,
398// either numerically or as successive substrings.
399type stringIterable struct {
400 s String
401 split bool
402 codepoints bool
403}
404
405var _ Iterable = (*stringIterable)(nil)
406
407func (si stringIterable) String() string {
408 if si.split {
409 return si.s.String() + ".split_" + si.Type() + "()"
410 } else {
411 return si.s.String() + "." + si.Type() + "()"
412 }
413}
414func (si stringIterable) Type() string {
415 if si.codepoints {
416 return "codepoints"
417 } else {
418 return "bytes"
419 }
420}
421func (si stringIterable) Freeze() {} // immutable
422func (si stringIterable) Truth() Bool { return True }
423func (si stringIterable) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable: %s", si.Type()) }
424func (si stringIterable) Iterate() Iterator { return &stringIterator{si, 0} }
425
426type stringIterator struct {
427 si stringIterable
428 i int
429}
430
431func (it *stringIterator) Next(p *Value) bool {
432 s := it.si.s[it.i:]
433 if s == "" {
434 return false
435 }
436 if it.si.codepoints {
437 r, sz := utf8.DecodeRuneInString(string(s))
438 if it.si.split {
439 *p = s[:sz]
440 } else {
441 *p = MakeInt(int(r))
442 }
443 it.i += sz
444 } else {
445 b := int(s[0])
446 if it.si.split {
447 *p = s[:1]
448 } else {
449 *p = MakeInt(b)
450 }
451 it.i += 1
452 }
453 return true
454}
455
456func (*stringIterator) Done() {}
457
458// A Function is a function defined by a Skylark def statement.
459type Function struct {
460 name string // "lambda" for anonymous functions
461 position syntax.Position // position of def or lambda token
462 syntax *syntax.Function
463 globals StringDict
464 defaults Tuple
465 freevars Tuple
466}
467
468func (fn *Function) Name() string { return fn.name }
469func (fn *Function) Hash() (uint32, error) { return hashString(fn.name), nil }
470func (fn *Function) Freeze() { fn.defaults.Freeze(); fn.freevars.Freeze() }
471func (fn *Function) String() string { return toString(fn) }
472func (fn *Function) Type() string { return "function" }
473func (fn *Function) Truth() Bool { return true }
474
475func (fn *Function) Syntax() *syntax.Function { return fn.syntax }
476
477// A Builtin is a function implemented in Go.
478type Builtin struct {
479 name string
480 fn func(thread *Thread, fn *Builtin, args Tuple, kwargs []Tuple) (Value, error)
481 recv Value // for bound methods (e.g. "".startswith)
482}
483
484func (b *Builtin) Name() string { return b.name }
485func (b *Builtin) Freeze() {
486 if b.recv != nil {
487 b.recv.Freeze()
488 }
489}
490func (b *Builtin) Hash() (uint32, error) {
491 h := hashString(b.name)
492 if b.recv != nil {
493 h ^= 5521
494 }
495 return h, nil
496}
497func (b *Builtin) Receiver() Value { return b.recv }
498func (b *Builtin) String() string { return toString(b) }
499func (b *Builtin) Type() string { return "builtin" }
500func (b *Builtin) Call(thread *Thread, args Tuple, kwargs []Tuple) (Value, error) {
501 return b.fn(thread, b, args, kwargs)
502}
503func (b *Builtin) Truth() Bool { return true }
504
505// NewBuiltin returns a new 'builtin' value with the specified name
506// and implementation. It compares unequal with all other values.
507func NewBuiltin(name string, fn func(thread *Thread, fn *Builtin, args Tuple, kwargs []Tuple) (Value, error)) *Builtin {
508 return &Builtin{name: name, fn: fn}
509}
510
511// BindReceiver returns a new Builtin value representing a method
512// closure, that is, a built-in function bound to a receiver value.
513//
514// In the example below, the value of f is the string.index builtin bound to
515// the receiver value "abc":
516//
517// f = "abc".index; f("a"); f("b")
518//
519// In the common case, the receiver is bound only during the call,
520// but this still results in the creation of a temporary method closure:
521//
522// "abc".index("a")
523//
524func (b *Builtin) BindReceiver(recv Value) *Builtin {
525 return &Builtin{name: b.name, fn: b.fn, recv: recv}
526}
527
528// A *Dict represents a Skylark dictionary.
529type Dict struct {
530 ht hashtable
531}
532
533func (d *Dict) Clear() error { return d.ht.clear() }
534func (d *Dict) Delete(k Value) (v Value, found bool, err error) { return d.ht.delete(k) }
535func (d *Dict) Get(k Value) (v Value, found bool, err error) { return d.ht.lookup(k) }
536func (d *Dict) Items() []Tuple { return d.ht.items() }
537func (d *Dict) Keys() []Value { return d.ht.keys() }
538func (d *Dict) Len() int { return int(d.ht.len) }
539func (d *Dict) Iterate() Iterator { return d.ht.iterate() }
540func (d *Dict) Set(k, v Value) error { return d.ht.insert(k, v) }
541func (d *Dict) String() string { return toString(d) }
542func (d *Dict) Type() string { return "dict" }
543func (d *Dict) Freeze() { d.ht.freeze() }
544func (d *Dict) Truth() Bool { return d.Len() > 0 }
545func (d *Dict) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable type: dict") }
546
547func (d *Dict) Attr(name string) (Value, error) { return builtinAttr(d, name, dictMethods) }
548func (d *Dict) AttrNames() []string { return builtinAttrNames(dictMethods) }
549
550func (x *Dict) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) {
551 y := y_.(*Dict)
552 switch op {
553 case syntax.EQL:
554 ok, err := dictsEqual(x, y, depth)
555 return ok, err
556 case syntax.NEQ:
557 ok, err := dictsEqual(x, y, depth)
558 return !ok, err
559 default:
560 return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type())
561 }
562}
563
564func dictsEqual(x, y *Dict, depth int) (bool, error) {
565 if x.Len() != y.Len() {
566 return false, nil
567 }
568 for _, xitem := range x.Items() {
569 key, xval := xitem[0], xitem[1]
570
571 if yval, found, _ := y.Get(key); !found {
572 return false, nil
573 } else if eq, err := EqualDepth(xval, yval, depth-1); err != nil {
574 return false, err
575 } else if !eq {
576 return false, nil
577 }
578 }
579 return true, nil
580}
581
582// A *List represents a Skylark list value.
583type List struct {
584 elems []Value
585 frozen bool
586 itercount uint32 // number of active iterators (ignored if frozen)
587}
588
589// NewList returns a list containing the specified elements.
590// Callers should not subsequently modify elems.
591func NewList(elems []Value) *List { return &List{elems: elems} }
592
593func (l *List) Freeze() {
594 if !l.frozen {
595 l.frozen = true
596 for _, elem := range l.elems {
597 elem.Freeze()
598 }
599 }
600}
601
602// checkMutable reports an error if the list should not be mutated.
603// verb+" list" should describe the operation.
604// Structural mutations are not permitted during iteration.
605func (l *List) checkMutable(verb string, structural bool) error {
606 if l.frozen {
607 return fmt.Errorf("cannot %s frozen list", verb)
608 }
609 if structural && l.itercount > 0 {
610 return fmt.Errorf("cannot %s list during iteration", verb)
611 }
612 return nil
613}
614
615func (l *List) String() string { return toString(l) }
616func (l *List) Type() string { return "list" }
617func (l *List) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable type: list") }
618func (l *List) Truth() Bool { return l.Len() > 0 }
619func (l *List) Len() int { return len(l.elems) }
620func (l *List) Index(i int) Value { return l.elems[i] }
621
622func (l *List) Attr(name string) (Value, error) { return builtinAttr(l, name, listMethods) }
623func (l *List) AttrNames() []string { return builtinAttrNames(listMethods) }
624
625func (l *List) Iterate() Iterator {
626 if !l.frozen {
627 l.itercount++
628 }
629 return &listIterator{l: l}
630}
631
632func (x *List) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) {
633 y := y_.(*List)
634 // It's tempting to check x == y as an optimization here,
635 // but wrong because a list containing NaN is not equal to itself.
636 return sliceCompare(op, x.elems, y.elems, depth)
637}
638
639func sliceCompare(op syntax.Token, x, y []Value, depth int) (bool, error) {
640 // Fast path: check length.
641 if len(x) != len(y) && (op == syntax.EQL || op == syntax.NEQ) {
642 return op == syntax.NEQ, nil
643 }
644
645 // Find first element that is not equal in both lists.
646 for i := 0; i < len(x) && i < len(y); i++ {
647 if eq, err := EqualDepth(x[i], y[i], depth-1); err != nil {
648 return false, err
649 } else if !eq {
650 switch op {
651 case syntax.EQL:
652 return false, nil
653 case syntax.NEQ:
654 return true, nil
655 default:
656 return CompareDepth(op, x[i], y[i], depth-1)
657 }
658 }
659 }
660
661 return threeway(op, len(x)-len(y)), nil
662}
663
664type listIterator struct {
665 l *List
666 i int
667}
668
669func (it *listIterator) Next(p *Value) bool {
670 if it.i < it.l.Len() {
671 *p = it.l.elems[it.i]
672 it.i++
673 return true
674 }
675 return false
676}
677
678func (it *listIterator) Done() {
679 if !it.l.frozen {
680 it.l.itercount--
681 }
682}
683
684func (l *List) SetIndex(i int, v Value) error {
685 if err := l.checkMutable("assign to element of", false); err != nil {
686 return err
687 }
688 l.elems[i] = v
689 return nil
690}
691
692func (l *List) Append(v Value) error {
693 if err := l.checkMutable("append to", true); err != nil {
694 return err
695 }
696 l.elems = append(l.elems, v)
697 return nil
698}
699
700func (l *List) Clear() error {
701 if err := l.checkMutable("clear", true); err != nil {
702 return err
703 }
704 for i := range l.elems {
705 l.elems[i] = nil // aid GC
706 }
707 l.elems = l.elems[:0]
708 return nil
709}
710
711// A Tuple represents a Skylark tuple value.
712type Tuple []Value
713
714func (t Tuple) Len() int { return len(t) }
715func (t Tuple) Index(i int) Value { return t[i] }
716func (t Tuple) Iterate() Iterator { return &tupleIterator{elems: t} }
717func (t Tuple) Freeze() {
718 for _, elem := range t {
719 elem.Freeze()
720 }
721}
722func (t Tuple) String() string { return toString(t) }
723func (t Tuple) Type() string { return "tuple" }
724func (t Tuple) Truth() Bool { return len(t) > 0 }
725
726func (x Tuple) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) {
727 y := y_.(Tuple)
728 return sliceCompare(op, x, y, depth)
729}
730
731func (t Tuple) Hash() (uint32, error) {
732 // Use same algorithm as Python.
733 var x, mult uint32 = 0x345678, 1000003
734 for _, elem := range t {
735 y, err := elem.Hash()
736 if err != nil {
737 return 0, err
738 }
739 x = x ^ y*mult
740 mult += 82520 + uint32(len(t)+len(t))
741 }
742 return x, nil
743}
744
745type tupleIterator struct{ elems Tuple }
746
747func (it *tupleIterator) Next(p *Value) bool {
748 if len(it.elems) > 0 {
749 *p = it.elems[0]
750 it.elems = it.elems[1:]
751 return true
752 }
753 return false
754}
755
756func (it *tupleIterator) Done() {}
757
758// A Set represents a Skylark set value.
759type Set struct {
760 ht hashtable // values are all None
761}
762
763func (s *Set) Delete(k Value) (found bool, err error) { _, found, err = s.ht.delete(k); return }
764func (s *Set) Clear() error { return s.ht.clear() }
765func (s *Set) Has(k Value) (found bool, err error) { _, found, err = s.ht.lookup(k); return }
766func (s *Set) Insert(k Value) error { return s.ht.insert(k, None) }
767func (s *Set) Len() int { return int(s.ht.len) }
768func (s *Set) Iterate() Iterator { return s.ht.iterate() }
769func (s *Set) String() string { return toString(s) }
770func (s *Set) Type() string { return "set" }
771func (s *Set) elems() []Value { return s.ht.keys() }
772func (s *Set) Freeze() { s.ht.freeze() }
773func (s *Set) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable type: set") }
774func (s *Set) Truth() Bool { return s.Len() > 0 }
775
776func (s *Set) Attr(name string) (Value, error) { return builtinAttr(s, name, setMethods) }
777func (s *Set) AttrNames() []string { return builtinAttrNames(setMethods) }
778
779func (x *Set) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) {
780 y := y_.(*Set)
781 switch op {
782 case syntax.EQL:
783 ok, err := setsEqual(x, y, depth)
784 return ok, err
785 case syntax.NEQ:
786 ok, err := setsEqual(x, y, depth)
787 return !ok, err
788 default:
789 return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type())
790 }
791}
792
793func setsEqual(x, y *Set, depth int) (bool, error) {
794 if x.Len() != y.Len() {
795 return false, nil
796 }
797 for _, elem := range x.elems() {
798 if found, _ := y.Has(elem); !found {
799 return false, nil
800 }
801 }
802 return true, nil
803}
804
805func (s *Set) Union(iter Iterator) (Value, error) {
806 set := new(Set)
807 for _, elem := range s.elems() {
808 set.Insert(elem) // can't fail
809 }
810 var x Value
811 for iter.Next(&x) {
812 if err := set.Insert(x); err != nil {
813 return nil, err
814 }
815 }
816 return set, nil
817}
818
819// toString returns the string form of value v.
820// It may be more efficient than v.String() for larger values.
821func toString(v Value) string {
822 var buf bytes.Buffer
823 path := make([]Value, 0, 4)
824 writeValue(&buf, v, path)
825 return buf.String()
826}
827
828// path is the list of *List and *Dict values we're currently printing.
829// (These are the only potentially cyclic structures.)
830func writeValue(out *bytes.Buffer, x Value, path []Value) {
831 switch x := x.(type) {
832 case NoneType:
833 out.WriteString("None")
834
835 case Int:
836 out.WriteString(x.String())
837
838 case Bool:
839 if x {
840 out.WriteString("True")
841 } else {
842 out.WriteString("False")
843 }
844
845 case String:
846 fmt.Fprintf(out, "%q", string(x))
847
848 case *List:
849 out.WriteByte('[')
850 if pathContains(path, x) {
851 out.WriteString("...") // list contains itself
852 } else {
853 for i, elem := range x.elems {
854 if i > 0 {
855 out.WriteString(", ")
856 }
857 writeValue(out, elem, append(path, x))
858 }
859 }
860 out.WriteByte(']')
861
862 case Tuple:
863 out.WriteByte('(')
864 for i, elem := range x {
865 if i > 0 {
866 out.WriteString(", ")
867 }
868 writeValue(out, elem, path)
869 }
870 if len(x) == 1 {
871 out.WriteByte(',')
872 }
873 out.WriteByte(')')
874
875 case *Function:
876 fmt.Fprintf(out, "<function %s>", x.Name())
877
878 case *Builtin:
879 if x.recv != nil {
880 fmt.Fprintf(out, "<built-in method %s of %s value>", x.Name(), x.recv.Type())
881 } else {
882 fmt.Fprintf(out, "<built-in function %s>", x.Name())
883 }
884
885 case *Dict:
886 out.WriteByte('{')
887 if pathContains(path, x) {
888 out.WriteString("...") // dict contains itself
889 } else {
890 sep := ""
891 for _, item := range x.Items() {
892 k, v := item[0], item[1]
893 out.WriteString(sep)
894 writeValue(out, k, path)
895 out.WriteString(": ")
896 writeValue(out, v, append(path, x)) // cycle check
897 sep = ", "
898 }
899 }
900 out.WriteByte('}')
901
902 case *Set:
903 out.WriteString("set([")
904 for i, elem := range x.elems() {
905 if i > 0 {
906 out.WriteString(", ")
907 }
908 writeValue(out, elem, path)
909 }
910 out.WriteString("])")
911
912 default:
913 out.WriteString(x.String())
914 }
915}
916
917func pathContains(path []Value, x Value) bool {
918 for _, y := range path {
919 if x == y {
920 return true
921 }
922 }
923 return false
924}
925
926const maxdepth = 10
927
928// Equal reports whether two Skylark values are equal.
929func Equal(x, y Value) (bool, error) {
930 return EqualDepth(x, y, maxdepth)
931}
932
933// EqualDepth reports whether two Skylark values are equal.
934//
935// Recursive comparisons by implementations of Value.CompareSameType
936// should use EqualDepth to prevent infinite recursion.
937func EqualDepth(x, y Value, depth int) (bool, error) {
938 return CompareDepth(syntax.EQL, x, y, depth)
939}
940
941// Compare compares two Skylark values.
942// The comparison operation must be one of EQL, NEQ, LT, LE, GT, or GE.
943// Compare returns an error if an ordered comparison was
944// requested for a type that does not support it.
945//
946// Recursive comparisons by implementations of Value.CompareSameType
947// should use CompareDepth to prevent infinite recursion.
948func Compare(op syntax.Token, x, y Value) (bool, error) {
949 return CompareDepth(op, x, y, maxdepth)
950}
951
952// CompareDepth compares two Skylark values.
953// The comparison operation must be one of EQL, NEQ, LT, LE, GT, or GE.
954// CompareDepth returns an error if an ordered comparison was
955// requested for a pair of values that do not support it.
956//
957// The depth parameter limits the maximum depth of recursion
958// in cyclic data structures.
959func CompareDepth(op syntax.Token, x, y Value, depth int) (bool, error) {
960 if depth < 1 {
961 return false, fmt.Errorf("comparison exceeded maximum recursion depth")
962 }
963 if sameType(x, y) {
964 if xcomp, ok := x.(Comparable); ok {
965 return xcomp.CompareSameType(op, y, depth)
966 }
967
968 // use identity comparison
969 switch op {
970 case syntax.EQL:
971 return x == y, nil
972 case syntax.NEQ:
973 return x != y, nil
974 }
975 return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type())
976 }
977
978 // different types
979
980 // int/float ordered comparisons
981 switch x := x.(type) {
982 case Int:
983 if y, ok := y.(Float); ok {
984 if y != y {
985 return false, nil // y is NaN
986 }
987 var cmp int
988 if !math.IsInf(float64(y), 0) {
989 cmp = x.rational().Cmp(y.rational()) // y is finite
990 } else if y > 0 {
991 cmp = -1 // y is +Inf
992 } else {
993 cmp = +1 // y is -Inf
994 }
995 return threeway(op, cmp), nil
996 }
997 case Float:
998 if y, ok := y.(Int); ok {
999 if x != x {
1000 return false, nil // x is NaN
1001 }
1002 var cmp int
1003 if !math.IsInf(float64(x), 0) {
1004 cmp = x.rational().Cmp(y.rational()) // x is finite
1005 } else if x > 0 {
1006 cmp = -1 // x is +Inf
1007 } else {
1008 cmp = +1 // x is -Inf
1009 }
1010 return threeway(op, cmp), nil
1011 }
1012 }
1013
1014 // All other values of different types compare unequal.
1015 switch op {
1016 case syntax.EQL:
1017 return false, nil
1018 case syntax.NEQ:
1019 return true, nil
1020 }
1021 return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type())
1022}
1023
1024func sameType(x, y Value) bool {
1025 return reflect.TypeOf(x) == reflect.TypeOf(y) || x.Type() == y.Type()
1026}
1027
1028// threeway interprets a three-way comparison value cmp (-1, 0, +1)
1029// as a boolean comparison (e.g. x < y).
1030func threeway(op syntax.Token, cmp int) bool {
1031 switch op {
1032 case syntax.EQL:
1033 return cmp == 0
1034 case syntax.NEQ:
1035 return cmp != 0
1036 case syntax.LE:
1037 return cmp <= 0
1038 case syntax.LT:
1039 return cmp < 0
1040 case syntax.GE:
1041 return cmp >= 0
1042 case syntax.GT:
1043 return cmp > 0
1044 }
1045 panic(op)
1046}
1047
1048func b2i(b bool) int {
1049 if b {
1050 return 1
1051 } else {
1052 return 0
1053 }
1054}
1055
1056// Len returns the length of a string or sequence value,
1057// and -1 for all others.
1058//
1059// Warning: Len(x) >= 0 does not imply Iterate(x) != nil.
1060// A string has a known length but is not directly iterable.
1061func Len(x Value) int {
1062 switch x := x.(type) {
1063 case String:
1064 return x.Len()
1065 case Sequence:
1066 return x.Len()
1067 }
1068 return -1
1069}
1070
1071// Iterate return a new iterator for the value if iterable, nil otherwise.
1072// If the result is non-nil, the caller must call Done when finished with it.
1073//
1074// Warning: Iterate(x) != nil does not imply Len(x) >= 0.
1075// Some iterables may have unknown length.
1076func Iterate(x Value) Iterator {
1077 if x, ok := x.(Iterable); ok {
1078 return x.Iterate()
1079 }
1080 return nil
1081}