Documentation
¶
Overview ¶
Package starlark provides a Starlark interpreter.
Starlark values are represented by the Value interface. The following built-in Value types are known to the evaluator:
NoneType -- NoneType Bool -- bool Int -- int Float -- float String -- string *List -- list Tuple -- tuple *Dict -- dict *Set -- set *Function -- function (implemented in Starlark) *Builtin -- builtin_function_or_method (function or method implemented in Go)
Client applications may define new data types that satisfy at least the Value interface. Such types may provide additional operations by implementing any of these optional interfaces:
Callable -- value is callable like a function Comparable -- value defines its own comparison operations Iterable -- value is iterable using 'for' loops Sequence -- value is iterable sequence of known length Indexable -- value is sequence with efficient random access HasBinary -- value defines binary operations such as * and + HasAttrs -- value has readable fields or methods x.f HasSetField -- value has settable fields x.f HasSetIndex -- value supports element update using x[i]=y
Client applications may also define domain-specific functions in Go and make them available to Starlark programs. Use NewBuiltin to construct a built-in value that wraps a Go function. The implementation of the Go function may use UnpackArgs to make sense of the positional and keyword arguments provided by the caller.
Starlark's None value is not equal to Go's nil, but nil may be assigned to a Starlark Value. Be careful to avoid allowing Go nil values to leak into Starlark data structures.
The Compare operation requires two arguments of the same type, but this constraint cannot be expressed in Go's type system. (This is the classic "binary method problem".) So, each Value type's CompareSameType method is a partial function that compares a value only against others of the same type. Use the package's standalone Compare (or Equal) function to compare an arbitrary pair of values.
To parse and evaluate a Starlark source file, use ExecFile. The Eval function evaluates a single expression. All evaluator functions require a Thread parameter which defines the "thread-local storage" of a Starlark thread and may be used to plumb application state through Sklyark code and into callbacks. When evaluation fails it returns an EvalError from which the application may obtain a backtrace of active Starlark calls.
Index ¶
- Constants
- func AsFloat(x Value) (f float64, ok bool)
- func AsInt32(x Value) (int, error)
- func AsString(x Value) (string, bool)
- func Compare(op syntax.Token, x, y Value) (bool, error)
- func CompareDepth(op syntax.Token, x, y Value, depth int) (bool, error)
- func Equal(x, y Value) (bool, error)
- func EqualDepth(x, y Value, depth int) (bool, error)
- func Len(x Value) int
- func UnpackArgs(fnname string, args Tuple, kwargs []Tuple, pairs ...interface{}) error
- func UnpackPositionalArgs(fnname string, args Tuple, kwargs []Tuple, min int, vars ...interface{}) error
- type Bool
- type Builtin
- func (b *Builtin) BindReceiver(recv Value) *Builtin
- func (b *Builtin) Call(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
- type Callable
- type Comparable
- type Dict
- 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) Set(k, v Value) error
- func (d *Dict) String() string
- func (d *Dict) Truth() Bool
- func (d *Dict) Type() string
- type EvalError
- type ExecOptions
- type Float
- type Frame
- type Function
- func (fn *Function) Call(thread *Thread, args Tuple, kwargs []Tuple) (Value, error)
- func (fn *Function) Freeze()
- func (fn *Function) HasKwargs() bool
- func (fn *Function) HasVarargs() bool
- func (fn *Function) Hash() (uint32, error)
- func (fn *Function) Name() string
- func (fn *Function) NumParams() int
- func (fn *Function) Param(i int) (string, syntax.Position)
- func (fn *Function) Position() syntax.Position
- func (fn *Function) String() string
- func (fn *Function) Truth() Bool
- func (fn *Function) Type() string
- type HasAttrs
- type HasBinary
- type HasSetField
- type HasSetIndex
- type Indexable
- type Int
- func (x Int) Add(y Int) Int
- func (x Int) And(y Int) Int
- func (x Int) CompareSameType(op syntax.Token, y Value, depth int) (bool, error)
- func (x Int) Div(y Int) Int
- func (i Int) Float() Float
- func (i Int) Freeze()
- func (i Int) Hash() (uint32, error)
- func (i Int) Int64() (_ int64, ok bool)
- func (x Int) Mod(y Int) Int
- func (x Int) Mul(y Int) Int
- func (x Int) Or(y Int) 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)
- type Iterable
- type Iterator
- type List
- 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) String() string
- func (l *List) Truth() Bool
- func (l *List) Type() string
- type Mapping
- type NoneType
- type Sequence
- type Set
- 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
- type 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) Hash() (uint32, error)
- func (s String) Index(i int) Value
- func (s String) Len() int
- func (s String) String() string
- func (s String) Truth() Bool
- func (s String) Type() string
- type StringDict
- type Thread
- type Tuple
- 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) String() string
- func (t Tuple) Truth() Bool
- func (t Tuple) Type() string
- type Value
Constants ¶
const None = NoneType(0)
Variables ¶
This section is empty.
Functions ¶
func AsFloat ¶
AsFloat returns the float64 value closest to x. The f result is undefined if x is not a float or int.
func Compare ¶
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 ¶
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 EqualDepth ¶
EqualDepth reports whether two Starlark values are equal.
Recursive comparisons by implementations of Value.CompareSameType should use EqualDepth to prevent infinite recursion.
func Len ¶
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 UnpackArgs ¶
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, int, string, *List, *Dict, Callable, Iterable, or user-defined implementation of Value, UnpackArgs performs the appropriate type check. (An int uses the AsInt32 check.) If the parameter name ends with "?", it and all following parameters are optional.
If the variable implements Value, UnpackArgs may call its Type() method while constructing the error message.
Beware: an optional *List, *Dict, Callable, Iterable, or Value variable that is not assigned is not a valid Starlark Value, so the caller must explicitly handle such cases by interpreting nil as None or some computed default.
func UnpackPositionalArgs ¶
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.
Types ¶
type Builtin ¶
type Builtin struct {
// contains filtered or unexported fields
}
A Builtin is a function implemented in Go.
func NewBuiltin ¶
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 (*Builtin) BindReceiver ¶
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")
type Callable ¶
type Callable interface {
Value
Name() string
Call(thread *Thread, args Tuple, kwargs []Tuple) (Value, error)
}
A Callable value f may be the operand of a function call, f(x).
type Comparable ¶
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)
}
A Comparable is a value that defines its own equivalence relation and perhaps ordered comparisons.
type Dict ¶
type Dict struct {
// contains filtered or unexported fields
}
A *Dict represents a Starlark dictionary.
func (*Dict) CompareSameType ¶
type EvalError ¶
An EvalError is a Starlark evaluation error and its associated call stack.
type ExecOptions ¶
type ExecOptions struct {
// Thread is the state associated with the Starlark thread.
Thread *Thread
// Filename is the name of the file to execute,
// and the name that appears in error messages.
Filename string
// Source is an optional source of bytes to use
// instead of Filename. See syntax.Parse for details.
Source interface{}
// Predeclared defines the predeclared names specific to this module.
// Execution does not modify this dictionary.
Predeclared StringDict
// BeforeExec is an optional function that is called after the
// syntax tree has been resolved but before execution. If it
// returns an error, execution is not attempted.
BeforeExec func(*Thread, syntax.Node) error
}
ExecOptions specifies the arguments to Exec.
type Float ¶
type Float float64
Float is the type of a Starlark float.
func (Float) CompareSameType ¶
type Frame ¶
type Frame struct {
// contains filtered or unexported fields
}
A Frame holds the execution state of a single Starlark function call or module toplevel.
func (*Frame) ExecStmts ¶
ExecStmts executes the statements in the context of the specified frame, which must provide sufficient local slots.
Most clients do not need this function; use Exec or Eval instead.
func (*Frame) Function ¶
Function returns the frame's function, or nil for the top-level of a module.
func (*Frame) Position ¶
Position returns the source position of the current point of execution in this frame.
func (*Frame) WriteBacktrace ¶
WriteBacktrace writes a user-friendly description of the stack to buf.
type Function ¶
type Function struct {
// contains filtered or unexported fields
}
A Function is a function defined by a Starlark def statement.
func (*Function) HasVarargs ¶
type HasAttrs ¶
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 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 HasBinary ¶
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 HasSetField ¶
A HasSetField value has fields that may be written by a dot expression (x.f = y).
type HasSetIndex ¶
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 Indexable ¶
An Indexable is a sequence of known length that supports efficient random access. It is not necessarily iterable.
type Int ¶
type Int struct {
// contains filtered or unexported fields
}
Int is the type of a Starlark int.
func MakeUint64 ¶
MakeUint64 returns a Starlark int for the specified uint64.
func NumberToInt ¶
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 (Int) CompareSameType ¶
type Iterable ¶
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 Iterator ¶
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()
}
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 List ¶
type List struct {
// contains filtered or unexported fields
}
A *List represents a Starlark list value.
func NewList ¶
NewList returns a list containing the specified elements. Callers should not subsequently modify elems.
func (*List) CompareSameType ¶
type 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)
}
An Mapping is a mapping from keys to values, such as a dictionary.
type NoneType ¶
type NoneType byte
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.)
func (NoneType) CompareSameType ¶
type Set ¶
type Set struct {
// contains filtered or unexported fields
}
A Set represents a Starlark set value.
func (*Set) CompareSameType ¶
type String ¶
type String string
String is the type of a Starlark string.
A String is an immutable sequence of bytes. Strings are iterable; iteration over a string yields each of its 1-byte substrings in order.
func (String) CompareSameType ¶
type StringDict ¶
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.
var Universe StringDict
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.
func Exec ¶
func Exec(opts ExecOptions) (StringDict, error)
Exec is a variant of ExecFile that gives the client greater control over optional features.
func ExecFile ¶
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.
The filename and src parameters are as for syntax.Parse.
If ExecFile fails during evaluation, it returns an *EvalError containing a backtrace.
func (StringDict) Freeze ¶
func (d StringDict) Freeze()
func (StringDict) Has ¶
func (d StringDict) Has(key string) bool
Has reports whether the dictionary contains the specified key.
func (StringDict) String ¶
func (d StringDict) String() string
type Thread ¶
type Thread struct {
// 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)
// contains filtered or unexported fields
}
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.
func (*Thread) Caller ¶
Caller returns the frame of the innermost enclosing Starlark function. It should only be used in built-ins called from Starlark code.
func (*Thread) Pop ¶
func (thread *Thread) Pop()
Pop removes the topmost frame from the thread's stack.
Most clients do not need this low-level function; use ExecFile or Eval instead.
func (*Thread) Push ¶
func (thread *Thread) Push(predeclared StringDict, globals []Value, nlocals int) *Frame
Push pushes a new Frame on the specified thread's stack, and returns it. It must be followed by a call to Pop when the frame is no longer needed.
Most clients do not need this low-level function; use ExecFile or Eval instead.
type Tuple ¶
type Tuple []Value
A Tuple represents a Starlark tuple value.
func (Tuple) CompareSameType ¶
type Value ¶
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.
Hash() (uint32, error)
}
Value is a value in the Starlark interpreter.
func Binary ¶
Binary applies a strict binary operator (not AND or OR) to its operands. For equality tests or ordered comparisons, use Compare instead.
func Eval ¶
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.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
starlark
command
The starlark command interprets a Starlark file.
|
The starlark command interprets a Starlark file. |
|
internal
|
|
|
chunkedfile
Package chunkedfile provides utilities for testing that source code errors are reported in the appropriate places.
|
Package chunkedfile provides utilities for testing that source code errors are reported in the appropriate places. |
|
The repl package provides a read/eval/print loop for Starlark.
|
The repl package provides a read/eval/print loop for Starlark. |
|
Package resolve defines a name-resolution pass for Starlark abstract syntax trees.
|
Package resolve defines a name-resolution pass for Starlark abstract syntax trees. |
|
Package starlarkstruct defines the Starlark 'struct' type, an optional language extension.
|
Package starlarkstruct defines the Starlark 'struct' type, an optional language extension. |
|
Package starlarktest defines utilities for testing Starlark programs.
|
Package starlarktest defines utilities for testing Starlark programs. |
|
Package syntax provides a Starlark parser and abstract syntax tree.
|
Package syntax provides a Starlark parser and abstract syntax tree. |