CompilerVersion is the version number of the protocol for compiled files. Applications must not run programs compiled by one version with an interpreter at another version, and should thus incorporate the compiler version into the cache key when reusing compiled code.
const CompilerVersion = compile.Version
const None = NoneType(0)
CompareLimit is the depth limit on recursive comparison operations such as == and <. Comparison of data structures deeper than this limit may fail.
var CompareLimit = 10
func AsFloat(x Value) (f float64, ok bool)
AsFloat returns the float64 value closest to x. The f result is undefined if x is not a float or Int. The result may be infinite if x is a very large Int.
func AsInt(x Value, ptr interface{}) error
AsInt sets *ptr to the value of Starlark int x, if it is exactly representable, otherwise it returns an error. The type of ptr must be one of the pointer types *int, *int8, *int16, *int32, or *int64, or one of their unsigned counterparts including *uintptr.
func AsInt32(x Value) (int, error)
AsInt32 returns the value of x if is representable as an int32.
func AsString(x Value) (string, bool)
func Compare(op syntax.Token, x, y Value) (bool, error)
Compare compares two Starlark values. The comparison operation must be one of EQL, NEQ, LT, LE, GT, or GE. Compare returns an error if an ordered comparison was requested for a type that does not support it.
Recursive comparisons by implementations of Value.CompareSameType should use CompareDepth to prevent infinite recursion.
func CompareDepth(op syntax.Token, x, y Value, depth int) (bool, error)
CompareDepth compares two Starlark values. The comparison operation must be one of EQL, NEQ, LT, LE, GT, or GE. CompareDepth returns an error if an ordered comparison was requested for a pair of values that do not support it.
The depth parameter limits the maximum depth of recursion in cyclic data structures.
func Equal(x, y Value) (bool, error)
Equal reports whether two Starlark values are equal.
func EqualDepth(x, y Value, depth int) (bool, error)
EqualDepth reports whether two Starlark values are equal.
Recursive comparisons by implementations of Value.CompareSameType should use EqualDepth to prevent infinite recursion.
func ExecREPLChunk(f *syntax.File, thread *Thread, globals StringDict) error
ExecREPLChunk compiles and executes file f in the specified thread and global environment. This is a variant of ExecFile specialized to the needs of a REPL, in which a sequence of input chunks, each syntactically a File, manipulates the same set of module globals, which are not frozen after execution.
This function is intended to support only go.starlark.net/repl. Its API stability is not guaranteed.
func Len(x Value) int
Len returns the length of a string or sequence value, and -1 for all others.
Warning: Len(x) >= 0 does not imply Iterate(x) != nil. A string has a known length but is not directly iterable.
func StartProfile(w io.Writer) error
StartProfile enables time profiling of all Starlark threads, and writes a profile in pprof format to w. It must be followed by a call to StopProfiler to stop the profiler and finalize the profile.
StartProfile returns an error if profiling was already enabled.
StartProfile must not be called concurrently with Starlark execution.
func StopProfile() error
StopProfiler stops the profiler started by a prior call to StartProfile and finalizes the profile. It returns an error if the profile could not be completed.
StopProfiler must not be called concurrently with Starlark execution.
func UnpackArgs(fnname string, args Tuple, kwargs []Tuple, pairs ...interface{}) error
UnpackArgs unpacks the positional and keyword arguments into the supplied parameter variables. pairs is an alternating list of names and pointers to variables.
If the variable is a bool, integer, string, *List, *Dict, Callable, Iterable, or user-defined implementation of Value, UnpackArgs performs the appropriate type check. Predeclared Go integer types uses the AsInt check.
If the parameter name ends with "?", it is optional.
If the parameter name ends with "??", it is optional and treats the None value as if the argument was absent.
If a parameter is marked optional, then all following parameters are implicitly optional where or not they are marked.
If the variable implements Unpacker, its Unpack argument is called with the argument value, allowing an application to define its own argument validation and conversion.
If the variable implements Value, UnpackArgs may call its Type() method while constructing the error message.
Examples:
var ( a Value b = MakeInt(42) c Value = starlark.None ) // 1. mixed parameters, like def f(a, b=42, c=None). err := UnpackArgs("f", args, kwargs, "a", &a, "b?", &b, "c?", &c) // 2. keyword parameters only, like def f(*, a, b, c=None). if len(args) > 0 { return fmt.Errorf("f: unexpected positional arguments") } err := UnpackArgs("f", args, kwargs, "a", &a, "b?", &b, "c?", &c) // 3. positional parameters only, like def f(a, b=42, c=None, /) in Python 3.8. err := UnpackPositionalArgs("f", args, kwargs, 1, &a, &b, &c)
More complex forms such as def f(a, b=42, *args, c, d=123, **kwargs) require additional logic, but their need in built-ins is exceedingly rare.
In the examples above, the declaration of b with type Int causes UnpackArgs to require that b's argument value, if provided, is also an int. To allow arguments of any type, while retaining the default value of 42, declare b as a Value:
var b Value = MakeInt(42)
The zero value of a variable of type Value, such as 'a' in the examples above, is not a valid Starlark value, so if the parameter is optional, the caller must explicitly handle the default case by interpreting nil as None or some computed default. The same is true for the zero values of variables of type *List, *Dict, Callable, or Iterable. For example:
// def myfunc(d=None, e=[], f={}) var ( d Value e *List f *Dict ) err := UnpackArgs("myfunc", args, kwargs, "d?", &d, "e?", &e, "f?", &f) if d == nil { d = None; } if e == nil { e = new(List); } if f == nil { f = new(Dict); }
func UnpackPositionalArgs(fnname string, args Tuple, kwargs []Tuple, min int, vars ...interface{}) error
UnpackPositionalArgs unpacks the positional arguments into corresponding variables. Each element of vars is a pointer; see UnpackArgs for allowed types and conversions.
UnpackPositionalArgs reports an error if the number of arguments is less than min or greater than len(vars), if kwargs is nonempty, or if any conversion fails.
See UnpackArgs for general comments.
Bool is the type of a Starlark bool.
type Bool bool
const ( False Bool = false True Bool = true )
func (x Bool) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error)
func (b Bool) Freeze()
func (b Bool) Hash() (uint32, error)
func (b Bool) String() string
func (b Bool) Truth() Bool
func (b Bool) Type() string
A Builtin is a function implemented in Go.
type Builtin struct {
// contains filtered or unexported fields
}
func NewBuiltin(name string, fn func(thread *Thread, fn *Builtin, args Tuple, kwargs []Tuple) (Value, error)) *Builtin
NewBuiltin returns a new 'builtin_function_or_method' value with the specified name and implementation. It compares unequal with all other values.
func (b *Builtin) BindReceiver(recv Value) *Builtin
BindReceiver returns a new Builtin value representing a method closure, that is, a built-in function bound to a receiver value.
In the example below, the value of f is the string.index built-in method bound to the receiver value "abc":
f = "abc".index; f("a"); f("b")
In the common case, the receiver is bound only during the call, but this still results in the creation of a temporary method closure:
"abc".index("a")
func (b *Builtin) CallInternal(thread *Thread, args Tuple, kwargs []Tuple) (Value, error)
func (b *Builtin) Freeze()
func (b *Builtin) Hash() (uint32, error)
func (b *Builtin) Name() string
func (b *Builtin) Receiver() Value
func (b *Builtin) String() string
func (b *Builtin) Truth() Bool
func (b *Builtin) Type() string
Bytes is the type of a Starlark binary string.
A Bytes encapsulates an immutable sequence of bytes. It is comparable, indexable, and sliceable, but not direcly iterable; use bytes.elems() for an iterable view.
In this Go implementation, the elements of 'string' and 'bytes' are both bytes, but in other implementations, notably Java, the elements of a 'string' are UTF-16 codes (Java chars). The spec abstracts text strings as sequences of UTF-k codes that encode Unicode code points, and operations that convert from text to binary incur UTF-k-to-UTF-8 transcoding; conversely, conversion from binary to text incurs UTF-8-to-UTF-k transcoding. Because k=8 for Go, these operations are the identity function, at least for valid encodings of text.
type Bytes string
func (b Bytes) Attr(name string) (Value, error)
func (b Bytes) AttrNames() []string
func (x Bytes) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error)
func (b Bytes) Freeze()
func (b Bytes) Hash() (uint32, error)
func (b Bytes) Index(i int) Value
func (b Bytes) Len() int
func (b Bytes) Slice(start, end, step int) Value
func (b Bytes) String() string
func (b Bytes) Truth() Bool
func (b Bytes) Type() string
A CallFrame represents the function name and current position of execution of an enclosing call frame.
type CallFrame struct { Name string Pos syntax.Position }
A CallStack is a stack of call frames, outermost first.
type CallStack []CallFrame
func (stack CallStack) At(i int) CallFrame
At returns a copy of the frame at depth i. At(0) returns the topmost frame.
func (stack *CallStack) Pop() CallFrame
Pop removes and returns the topmost frame.
func (stack CallStack) String() string
String returns a user-friendly description of the stack.
A Callable value f may be the operand of a function call, f(x).
Clients should use the Call function, never the CallInternal method.
type Callable interface { Value Name() string CallInternal(thread *Thread, args Tuple, kwargs []Tuple) (Value, error) }
A Comparable is a value that defines its own equivalence relation and perhaps ordered comparisons.
type Comparable interface { Value // CompareSameType compares one value to another of the same Type(). // The comparison operation must be one of EQL, NEQ, LT, LE, GT, or GE. // CompareSameType returns an error if an ordered comparison was // requested for a type that does not support it. // // Implementations that recursively compare subcomponents of // the value should use the CompareDepth function, not Compare, to // avoid infinite recursion on cyclic structures. // // The depth parameter is used to bound comparisons of cyclic // data structures. Implementations should decrement depth // before calling CompareDepth and should return an error if depth // < 1. // // Client code should not call this method. Instead, use the // standalone Compare or Equals functions, which are defined for // all pairs of operands. CompareSameType(op syntax.Token, y Value, depth int) (bool, error) }
DebugFrame is the debugger API for a frame of the interpreter's call stack.
Most applications have no need for this API; use CallFrame instead.
Clients must not retain a DebugFrame nor call any of its methods once the current built-in call has returned or execution has resumed after a breakpoint as this may have unpredictable effects, including but not limited to retention of object that would otherwise be garbage.
type DebugFrame interface { Callable() Callable // returns the frame's function Local(i int) Value // returns the value of the (Starlark) frame's ith local variable Position() syntax.Position // returns the current position of execution in this frame }
A *Dict represents a Starlark dictionary. The zero value of Dict is a valid empty dictionary. If you know the exact final number of entries, it is more efficient to call NewDict.
type Dict struct {
// contains filtered or unexported fields
}
func NewDict(size int) *Dict
NewDict returns a set with initial space for at least size insertions before rehashing.
func (d *Dict) Attr(name string) (Value, error)
func (d *Dict) AttrNames() []string
func (d *Dict) Clear() error
func (x *Dict) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error)
func (d *Dict) Delete(k Value) (v Value, found bool, err error)
func (d *Dict) Freeze()
func (d *Dict) Get(k Value) (v Value, found bool, err error)
func (d *Dict) Hash() (uint32, error)
func (d *Dict) Items() []Tuple
func (d *Dict) Iterate() Iterator
func (d *Dict) Keys() []Value
func (d *Dict) Len() int
func (d *Dict) SetKey(k, v Value) error
func (d *Dict) String() string
func (d *Dict) Truth() Bool
func (d *Dict) Type() string
func (x *Dict) Union(y *Dict) *Dict
An EvalError is a Starlark evaluation error and a copy of the thread's stack at the moment of the error.
type EvalError struct { Msg string CallStack CallStack // contains filtered or unexported fields }
func (e *EvalError) Backtrace() string
Backtrace returns a user-friendly error message describing the stack of calls that led to this error.
func (e *EvalError) Error() string
func (e *EvalError) Unwrap() error
Float is the type of a Starlark float.
type Float float64
func (x Float) Cmp(y_ Value, depth int) (int, error)
func (f Float) Freeze()
func (f Float) Hash() (uint32, error)
func (x Float) Mod(y Float) Float
func (f Float) String() string
func (f Float) Truth() Bool
func (f Float) Type() string
func (f Float) Unary(op syntax.Token) (Value, error)
Unary implements the operations +float and -float.
A Function is a function defined by a Starlark def statement or lambda expression. The initialization behavior of a Starlark module is also represented by a Function.
type Function struct {
// contains filtered or unexported fields
}
func ExprFunc(filename string, src interface{}, env StringDict) (*Function, error)
ExprFunc returns a no-argument function that evaluates the expression whose source is src.
func (fn *Function) CallInternal(thread *Thread, args Tuple, kwargs []Tuple) (Value, error)
func (fn *Function) Doc() string
func (fn *Function) Freeze()
func (fn *Function) Globals() StringDict
Globals returns a new, unfrozen StringDict containing all global variables so far defined in the function's module.
func (fn *Function) HasKwargs() bool
func (fn *Function) HasVarargs() bool
func (fn *Function) Hash() (uint32, error)
func (fn *Function) Name() string
func (fn *Function) NumKwonlyParams() int
func (fn *Function) NumParams() int
func (fn *Function) Param(i int) (string, syntax.Position)
Param returns the name and position of the ith parameter, where 0 <= i < NumParams(). The *args and **kwargs parameters are at the end even if there were optional parameters after *args.
func (fn *Function) ParamDefault(i int) Value
ParamDefault returns the default value of the specified parameter (0 <= i < NumParams()), or nil if the parameter is not optional.
func (fn *Function) Position() syntax.Position
func (fn *Function) String() string
func (fn *Function) Truth() Bool
func (fn *Function) Type() string
A HasAttrs value has fields or methods that may be read by a dot expression (y = x.f). Attribute names may be listed using the built-in 'dir' function.
For implementation convenience, a result of (nil, nil) from Attr is interpreted as a "no such field or method" error. Implementations are free to return a more precise error.
type HasAttrs interface { Value Attr(name string) (Value, error) // returns (nil, nil) if attribute not present AttrNames() []string // callers must not modify the result. }
A HasBinary value may be used as either operand of these binary operators: + - * / // % in not in | & ^ << >>
The Side argument indicates whether the receiver is the left or right operand.
An implementation may decline to handle an operation by returning (nil, nil). For this reason, clients should always call the standalone Binary(op, x, y) function rather than calling the method directly.
type HasBinary interface { Value Binary(op syntax.Token, y Value, side Side) (Value, error) }
A HasSetField value has fields that may be written by a dot expression (x.f = y).
An implementation of SetField may return a NoSuchAttrError, in which case the runtime may augment the error message to warn of possible misspelling.
type HasSetField interface { HasAttrs SetField(name string, val Value) error }
A HasSetIndex is an Indexable value whose elements may be assigned (x[i] = y).
The implementation should not add Len to a negative index as the evaluator does this before the call.
type HasSetIndex interface { Indexable SetIndex(index int, v Value) error }
A HasSetKey supports map update using x[k]=v syntax, like a dictionary.
type HasSetKey interface { Mapping SetKey(k, v Value) error }
A HasUnary value may be used as the operand of these unary operators: + - ~
An implementation may decline to handle an operation by returning (nil, nil). For this reason, clients should always call the standalone Unary(op, x) function rather than calling the method directly.
type HasUnary interface { Value Unary(op syntax.Token) (Value, error) }
An Indexable is a sequence of known length that supports efficient random access. It is not necessarily iterable.
type Indexable interface { Value Index(i int) Value // requires 0 <= i < Len() Len() int }
Int is the type of a Starlark int.
The zero value is not a legal value; use MakeInt(0).
type Int struct {
// contains filtered or unexported fields
}
func MakeBigInt(x *big.Int) Int
MakeBigInt returns a Starlark int for the specified big.Int. The new Int value will contain a copy of x. The caller is safe to modify x.
func MakeInt(x int) Int
MakeInt returns a Starlark int for the specified signed integer.
func MakeInt64(x int64) Int
MakeInt64 returns a Starlark int for the specified int64.
func MakeUint(x uint) Int
MakeUint returns a Starlark int for the specified unsigned integer.
func MakeUint64(x uint64) Int
MakeUint64 returns a Starlark int for the specified uint64.
func NumberToInt(x Value) (Int, error)
NumberToInt converts a number x to an integer value. An int is returned unchanged, a float is truncated towards zero. NumberToInt reports an error for all other values.
func (x Int) Add(y Int) Int
func (x Int) And(y Int) Int
func (i Int) BigInt() *big.Int
BigInt returns a new big.Int with the same value as the Int.
func (x Int) Cmp(v Value, depth int) (int, error)
Required by the TotallyOrdered interface
func (x Int) Div(y Int) Int
Precondition: y is nonzero.
func (i Int) Float() Float
Float returns the float value nearest i.
func (i Int) Format(s fmt.State, ch rune)
func (i Int) Freeze()
func (i Int) Hash() (uint32, error)
func (i Int) Int64() (_ int64, ok bool)
Int64 returns the value as an int64. If it is not exactly representable the result is undefined and ok is false.
func (x Int) Lsh(y uint) Int
func (x Int) Mod(y Int) Int
Precondition: y is nonzero.
func (x Int) Mul(y Int) Int
func (x Int) Not() Int
func (x Int) Or(y Int) Int
func (x Int) Rsh(y uint) Int
func (x Int) Sign() int
func (i Int) String() string
func (x Int) Sub(y Int) Int
func (i Int) Truth() Bool
func (i Int) Type() string
func (i Int) Uint64() (_ uint64, ok bool)
Uint64 returns the value as a uint64. If it is not exactly representable the result is undefined and ok is false.
func (i Int) Unary(op syntax.Token) (Value, error)
Unary implements the operations +int, -int, and ~int.
func (x Int) Xor(y Int) Int
An Iterable abstracts a sequence of values. An iterable value may be iterated over by a 'for' loop or used where any other Starlark iterable is allowed. Unlike a Sequence, the length of an Iterable is not necessarily known in advance of iteration.
type Iterable interface { Value Iterate() Iterator // must be followed by call to Iterator.Done }
An IterableMapping is a mapping that supports key enumeration.
type IterableMapping interface { Mapping Iterate() Iterator // see Iterable interface Items() []Tuple // a new slice containing all key/value pairs }
An Iterator provides a sequence of values to the caller.
The caller must call Done when the iterator is no longer needed. Operations that modify a sequence will fail if it has active iterators.
Example usage:
iter := iterable.Iterator() defer iter.Done() var x Value for iter.Next(&x) { ... }
type Iterator interface { // If the iterator is exhausted, Next returns false. // Otherwise it sets *p to the current element of the sequence, // advances the iterator, and returns true. Next(p *Value) bool Done() }
func Iterate(x Value) Iterator
Iterate return a new iterator for the value if iterable, nil otherwise. If the result is non-nil, the caller must call Done when finished with it.
Warning: Iterate(x) != nil does not imply Len(x) >= 0. Some iterables may have unknown length.
A *List represents a Starlark list value.
type List struct {
// contains filtered or unexported fields
}
func NewList(elems []Value) *List
NewList returns a list containing the specified elements. Callers should not subsequently modify elems.
func (l *List) Append(v Value) error
func (l *List) Attr(name string) (Value, error)
func (l *List) AttrNames() []string
func (l *List) Clear() error
func (x *List) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error)
func (l *List) Freeze()
func (l *List) Hash() (uint32, error)
func (l *List) Index(i int) Value
func (l *List) Iterate() Iterator
func (l *List) Len() int
func (l *List) SetIndex(i int, v Value) error
func (l *List) Slice(start, end, step int) Value
func (l *List) String() string
func (l *List) Truth() Bool
func (l *List) Type() string
A Mapping is a mapping from keys to values, such as a dictionary.
If a type satisfies both Mapping and Iterable, the iterator yields the keys of the mapping.
type Mapping interface { Value // Get returns the value corresponding to the specified key, // or !found if the mapping does not contain the key. // // Get also defines the behavior of "v in mapping". // The 'in' operator reports the 'found' component, ignoring errors. Get(Value) (v Value, found bool, err error) }
A NoSuchAttrError may be returned by an implementation of HasAttrs.Attr or HasSetField.SetField to indicate that no such field exists. In that case the runtime may augment the error message to warn of possible misspelling.
type NoSuchAttrError string
func (e NoSuchAttrError) Error() string
NoneType is the type of None. Its only legal value is None. (We represent it as a number, not struct{}, so that None may be constant.)
type NoneType byte
func (NoneType) Freeze()
func (NoneType) Hash() (uint32, error)
func (NoneType) String() string
func (NoneType) Truth() Bool
func (NoneType) Type() string
A Program is a compiled Starlark program.
Programs are immutable, and contain no Values. A Program may be created by parsing a source file (see SourceProgram) or by loading a previously saved compiled program (see CompiledProgram).
type Program struct {
// contains filtered or unexported fields
}
func CompiledProgram(in io.Reader) (*Program, error)
CompiledProgram produces a new program from the representation of a compiled program previously saved by Program.Write.
func FileProgram(f *syntax.File, isPredeclared func(string) bool) (*Program, error)
FileProgram produces a new program by resolving, and compiling the Starlark source file syntax tree. On success, it returns the compiled program.
Resolving a syntax tree mutates it. Do not call FileProgram more than once on the same file.
The isPredeclared predicate reports whether a name is a pre-declared identifier of the current module. Its typical value is predeclared.Has, where predeclared is a StringDict of pre-declared values.
func SourceProgram(filename string, src interface{}, isPredeclared func(string) bool) (*syntax.File, *Program, error)
SourceProgram produces a new program by parsing, resolving, and compiling a Starlark source file. On success, it returns the parsed file and the compiled program. The filename and src parameters are as for syntax.Parse.
The isPredeclared predicate reports whether a name is a pre-declared identifier of the current module. Its typical value is predeclared.Has, where predeclared is a StringDict of pre-declared values.
func (prog *Program) Filename() string
Filename returns the name of the file from which this program was loaded.
func (prog *Program) Init(thread *Thread, predeclared StringDict) (StringDict, error)
Init creates a set of global variables for the program, executes the toplevel code of the specified program, and returns a new, unfrozen dictionary of the globals.
func (prog *Program) Load(i int) (string, syntax.Position)
Load(i) returns the name and position of the i'th module directly loaded by this one, where 0 <= i < NumLoads(). The name is unresolved---exactly as it appears in the source.
func (prog *Program) NumLoads() int
NumLoads returns the number of load statements in the compiled program.
func (prog *Program) String() string
func (prog *Program) Write(out io.Writer) error
WriteTo writes the compiled module to the specified output stream.
A Sequence is a sequence of values of known length.
type Sequence interface { Iterable Len() int }
A Set represents a Starlark set value. The zero value of Set is a valid empty set. If you know the exact final number of elements, it is more efficient to call NewSet.
type Set struct {
// contains filtered or unexported fields
}
func NewSet(size int) *Set
NewSet returns a dictionary with initial space for at least size insertions before rehashing.
func (s *Set) Attr(name string) (Value, error)
func (s *Set) AttrNames() []string
func (s *Set) Clear() error
func (x *Set) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error)
func (s *Set) Delete(k Value) (found bool, err error)
func (s *Set) Freeze()
func (s *Set) Has(k Value) (found bool, err error)
func (s *Set) Hash() (uint32, error)
func (s *Set) Insert(k Value) error
func (s *Set) Iterate() Iterator
func (s *Set) Len() int
func (s *Set) String() string
func (s *Set) Truth() Bool
func (s *Set) Type() string
func (s *Set) Union(iter Iterator) (Value, error)
type Side bool
const ( Left Side = false Right Side = true )
A Sliceable is a sequence that can be cut into pieces with the slice operator (x[i:j:step]).
All native indexable objects are sliceable. This is a separate interface for backwards-compatibility.
type Sliceable interface { Indexable // For positive strides (step > 0), 0 <= start <= end <= n. // For negative strides (step < 0), -1 <= end <= start < n. // The caller must ensure that the start and end indices are valid // and that step is non-zero. Slice(start, end, step int) Value }
String is the type of a Starlark text string.
A String encapsulates an an immutable sequence of bytes, but strings are not directly iterable. Instead, iterate over the result of calling one of these four methods: codepoints, codepoint_ords, elems, elem_ords.
Strings typically contain text; use Bytes for binary strings. The Starlark spec defines text strings as sequences of UTF-k codes that encode Unicode code points. In this Go implementation, k=8, whereas in a Java implementation, k=16. For portability, operations on strings should aim to avoid assumptions about the value of k.
Warning: the contract of the Value interface's String method is that it returns the value printed in Starlark notation, so s.String() or fmt.Sprintf("%s", s) returns a quoted string. Use string(s) or s.GoString() or fmt.Sprintf("%#v", s) to obtain the raw contents of a Starlark string as a Go string.
type String string
func (s String) Attr(name string) (Value, error)
func (s String) AttrNames() []string
func (x String) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error)
func (s String) Freeze()
func (s String) GoString() string
func (s String) Hash() (uint32, error)
func (s String) Index(i int) Value
func (s String) Len() int
func (s String) Slice(start, end, step int) Value
func (s String) String() string
func (s String) Truth() Bool
func (s String) Type() string
A StringDict is a mapping from names to values, and represents an environment such as the global variables of a module. It is not a true starlark.Value.
type StringDict map[string]Value
Universe defines the set of universal built-ins, such as None, True, and len.
The Go application may add or remove items from the universe dictionary before Starlark evaluation begins. All values in the dictionary must be immutable. Starlark programs cannot modify the dictionary.
var Universe StringDict
func ExecFile(thread *Thread, filename string, src interface{}, predeclared StringDict) (StringDict, error)
ExecFile parses, resolves, and executes a Starlark file in the specified global environment, which may be modified during execution.
Thread is the state associated with the Starlark thread.
The filename and src parameters are as for syntax.Parse: filename is the name of the file to execute, and the name that appears in error messages; src is an optional source of bytes to use instead of filename.
predeclared defines the predeclared names specific to this module. Execution does not modify this dictionary, though it may mutate its values.
If ExecFile fails during evaluation, it returns an *EvalError containing a backtrace.
▹ Example
func (d StringDict) Freeze()
func (d StringDict) Has(key string) bool
Has reports whether the dictionary contains the specified key.
func (d StringDict) Keys() []string
Keys returns a new sorted slice of d's keys.
func (d StringDict) String() string
A Thread contains the state of a Starlark thread, such as its call stack and thread-local storage. The Thread is threaded throughout the evaluator.
type Thread struct { // Name is an optional name that describes the thread, for debugging. Name string // Print is the client-supplied implementation of the Starlark // 'print' function. If nil, fmt.Fprintln(os.Stderr, msg) is // used instead. Print func(thread *Thread, msg string) // Load is the client-supplied implementation of module loading. // Repeated calls with the same module name must return the same // module environment or error. // The error message need not include the module name. // // See example_test.go for some example implementations of Load. Load func(thread *Thread, module string) (StringDict, error) // OnMaxSteps is called when the thread reaches the limit set by SetMaxExecutionSteps. // The default behavior is to call thread.Cancel("too many steps"). OnMaxSteps func(thread *Thread) // Steps a count of abstract computation steps executed // by this thread. It is incremented by the interpreter. It may be used // as a measure of the approximate cost of Starlark execution, by // computing the difference in its value before and after a computation. // // The precise meaning of "step" is not specified and may change. Steps uint64 // contains filtered or unexported fields }
func (thread *Thread) CallFrame(depth int) CallFrame
CallFrame returns a copy of the specified frame of the callstack. It should only be used in built-ins called from Starlark code. Depth 0 means the frame of the built-in itself, 1 is its caller, and so on.
It is equivalent to CallStack().At(depth), but more efficient.
func (thread *Thread) CallStack() CallStack
CallStack returns a new slice containing the thread's stack of call frames.
func (thread *Thread) CallStackDepth() int
CallStackDepth returns the number of frames in the current call stack.
func (thread *Thread) Cancel(reason string)
Cancel causes execution of Starlark code in the specified thread to promptly fail with an EvalError that includes the specified reason. There may be a delay before the interpreter observes the cancellation if the thread is currently in a call to a built-in function.
Call [Uncancel] to reset the cancellation state.
Unlike most methods of Thread, it is safe to call Cancel from any goroutine, even if the thread is actively executing.
func (thread *Thread) DebugFrame(depth int) DebugFrame
DebugFrame returns the debugger interface for the specified frame of the interpreter's call stack. Frame numbering is as for Thread.CallFrame.
This function is intended for use in debugging tools. Most applications should have no need for it; use CallFrame instead.
func (thread *Thread) ExecutionSteps() uint64
ExecutionSteps returns the current value of Steps.
func (thread *Thread) Local(key string) interface{}
Local returns the thread-local value associated with the specified key.
func (thread *Thread) SetLocal(key string, value interface{})
SetLocal sets the thread-local value associated with the specified key. It must not be called after execution begins.
func (thread *Thread) SetMaxExecutionSteps(max uint64)
SetMaxExecutionSteps sets a limit on the number of Starlark computation steps that may be executed by this thread. If the thread's step counter exceeds this limit, the interpreter calls the optional OnMaxSteps function or the default behavior of calling thread.Cancel("too many steps").
func (thread *Thread) Uncancel()
Uncancel resets the cancellation state.
Unlike most methods of Thread, it is safe to call Uncancel from any goroutine, even if the thread is actively executing.
A TotallyOrdered is a type whose values form a total order: if x and y are of the same TotallyOrdered type, then x must be less than y, greater than y, or equal to y.
It is simpler than Comparable and should be preferred in new code, but if a type implements both interfaces, Comparable takes precedence.
type TotallyOrdered interface { Value // Cmp compares two values x and y of the same totally ordered type. // It returns negative if x < y, positive if x > y, and zero if the values are equal. // // Implementations that recursively compare subcomponents of // the value should use the CompareDepth function, not Cmp, to // avoid infinite recursion on cyclic structures. // // The depth parameter is used to bound comparisons of cyclic // data structures. Implementations should decrement depth // before calling CompareDepth and should return an error if depth // < 1. // // Client code should not call this method. Instead, use the // standalone Compare or Equals functions, which are defined for // all pairs of operands. Cmp(y Value, depth int) (int, error) }
A Tuple represents a Starlark tuple value.
type Tuple []Value
func (x Tuple) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error)
func (t Tuple) Freeze()
func (t Tuple) Hash() (uint32, error)
func (t Tuple) Index(i int) Value
func (t Tuple) Iterate() Iterator
func (t Tuple) Len() int
func (t Tuple) Slice(start, end, step int) Value
func (t Tuple) String() string
func (t Tuple) Truth() Bool
func (t Tuple) Type() string
An Unpacker defines custom argument unpacking behavior. See UnpackArgs.
type Unpacker interface { Unpack(v Value) error }
Value is a value in the Starlark interpreter.
type Value interface { // String returns the string representation of the value. // Starlark string values are quoted as if by Python's repr. String() string // Type returns a short string describing the value's type. Type() string // Freeze causes the value, and all values transitively // reachable from it through collections and closures, to be // marked as frozen. All subsequent mutations to the data // structure through this API will fail dynamically, making the // data structure immutable and safe for publishing to other // Starlark interpreters running concurrently. Freeze() // Truth returns the truth value of an object. Truth() Bool // Hash returns a function of x such that Equals(x, y) => Hash(x) == Hash(y). // Hash may fail if the value's type is not hashable, or if the value // contains a non-hashable value. The hash is used only by dictionaries and // is not exposed to the Starlark program. Hash() (uint32, error) }
func Binary(op syntax.Token, x, y Value) (Value, error)
Binary applies a strict binary operator (not AND or OR) to its operands. For equality tests or ordered comparisons, use Compare instead.
func Call(thread *Thread, fn Value, args Tuple, kwargs []Tuple) (Value, error)
Call calls the function fn with the specified positional and keyword arguments.
func Eval(thread *Thread, filename string, src interface{}, env StringDict) (Value, error)
Eval parses, resolves, and evaluates an expression within the specified (predeclared) environment.
Evaluation cannot mutate the environment dictionary itself, though it may modify variables reachable from the dictionary.
The filename and src parameters are as for syntax.Parse.
If Eval fails during evaluation, it returns an *EvalError containing a backtrace.
func EvalExpr(thread *Thread, expr syntax.Expr, env StringDict) (Value, error)
EvalExpr resolves and evaluates an expression within the specified (predeclared) environment. Evaluating a comma-separated list of expressions yields a tuple value.
Resolving an expression mutates it. Do not call EvalExpr more than once for the same expression.
Evaluation cannot mutate the environment dictionary itself, though it may modify variables reachable from the dictionary.
If Eval fails during evaluation, it returns an *EvalError containing a backtrace.
func Unary(op syntax.Token, x Value) (Value, error)
Unary applies a unary operator (+, -, ~, not) to its operand.