skylark

package module
v0.0.0-...-4956ce9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 22, 2018 License: BSD-3-Clause Imports: 16 Imported by: 0

README

Skylark in Go

This is the home of the Skylark in Go project. Skylark in Go is an interpreter for Skylark, implemented in Go.

Skylark is a dialect of Python intended for use as a configuration language. Like Python, it is an untyped dynamic language with high-level data types, first-class functions with lexical scope, and garbage collection. Unlike CPython, independent Skylark threads execute in parallel, so Skylark workloads scale well on parallel machines. Skylark is a small and simple language with a familiar and highly readable syntax. You can use it as an expressive notation for structured data, defining functions to eliminate repetition, or you can use it to add scripting capabilities to an existing application.

A Skylark interpreter is typically embedded within a larger application, and the application may define additional domain-specific functions and data types beyond those provided by the core language. For example, Skylark was originally developed for the Bazel build tool. Bazel uses Skylark as the notation both for its BUILD files (like Makefiles, these declare the executables, libraries, and tests in a directory) and for its macro language, through which Bazel is extended with custom logic to support new languages and compilers.

Documentation

Getting started

Build the code:

$ go get github.com/google/skylark/...
$ go build github.com/google/skylark/cmd/skylark

Run the interpreter:

$ cat coins.sky
coins = {
  'dime': 10,
  'nickel': 5,
  'penny': 1,
  'quarter': 25,
}
print('By name:\t' + ', '.join(sorted(coins.keys())))
print('By value:\t' + ', '.join(sorted(coins.keys(), key=coins.get)))

$ ./skylark coins.sky
By name:	dime, nickel, penny, quarter
By value:	penny, nickel, dime, quarter

Interact with the read-eval-print loop (REPL):

$ ./skylark
>>> def fibonacci(n):
...    res = list(range(n))
...    for i in res[2:]:
...        res[i] = res[i-2] + res[i-1]
...    return res
...
>>> fibonacci(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>>

When you have finished, type Ctrl-D to close the REPL's input stream.

Contributing

We welcome submissions but please let us know what you're working on if you want to change or add to the Skylark repository.

Before undertaking to write something new for the Skylark project, please file an issue or claim an existing issue. All significant changes to the language or to the interpreter's Go API must be discussed before they can be accepted. This gives all participants a chance to validate the design and to avoid duplication of effort.

Despite some differences, the Go implementation of Skylark strives to match the behavior of the Java implementation used by Bazel. For that reason, proposals to change the language itself should generally be directed to the Bazel team, not to the maintainers of this project. Only once there is consensus that a language change is desirable may its Go implementation proceed.

We use GitHub pull requests for contributions.

Please complete Google's contributor license agreement (CLA) before sending your first change to the project. If you are the copyright holder, you will need to agree to the individual contributor license agreement, which can be completed online. If your organization is the copyright holder, the organization will need to agree to the corporate contributor license agreement. If the copyright holder for your contribution has already completed the agreement in connection with another Google open source project, it does not need to be completed again.

Stability

We reserve the right to make breaking language and API changes at this stage in the project, although we will endeavor to keep them to a minimum. Once the project has its long-term name (see below) and location, and the Bazel team has finalized the version 1 language specification, we will be more rigorous with interface stability.

Credits

Skylark was designed and implemented in Java by Ulf Adams, Lukács Berki, Jon Brandvein, John Field, Laurent Le Brun, Dmitry Lomov, Damien Martin-Guillerez, Vladimir Moskva, and Florian Weikert, standing on the shoulders of the Python community. The Go implementation was written by Alan Donovan and Jay Conrod; its scanner was derived from one written by Russ Cox.

Skylark in Go is Copyright (c) 2017 The Bazel Authors. All rights reserved.

It is provided under a 3-clause BSD license: LICENSE.

The name "Skylark" is a code name of the Bazel project. We plan to rename the language before the end of 2017 to reflect its applicability to projects unrelated to Bazel.

Skylark in Go is not an official Google product.

Documentation

Overview

Package skylark provides a Skylark interpreter.

Skylark 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 Skylark)
*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 Skylark 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.

Skylark's None value is not equal to Go's nil, but nil may be assigned to a Skylark Value. Be careful to avoid allowing Go nil values to leak into Skylark 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 Skylark 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 Skylark 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 Skylark calls.

Index

Examples

Constants

View Source
const CompilerVersion = compile.Version

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.

View Source
const None = NoneType(0)

Variables

This section is empty.

Functions

func AsFloat

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.

func AsInt32

func AsInt32(x Value) (int, error)

AsInt32 returns the value of x if is representable as an int32.

func AsString

func AsString(x Value) (string, bool)

func Compare

func Compare(op syntax.Token, x, y Value) (bool, error)

Compare compares two Skylark 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

func CompareDepth(op syntax.Token, x, y Value, depth int) (bool, error)

CompareDepth compares two Skylark 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

func Equal(x, y Value) (bool, error)

Equal reports whether two Skylark values are equal.

func EqualDepth

func EqualDepth(x, y Value, depth int) (bool, error)

EqualDepth reports whether two Skylark values are equal.

Recursive comparisons by implementations of Value.CompareSameType should use EqualDepth to prevent infinite recursion.

func Len

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 UnpackArgs

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, 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 Skylark 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 Bool

type Bool bool

Bool is the type of a Skylark bool.

const (
	False Bool = false
	True  Bool = true
)

func (Bool) CompareSameType

func (x Bool) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error)

func (Bool) Freeze

func (b Bool) Freeze()

func (Bool) Hash

func (b Bool) Hash() (uint32, error)

func (Bool) String

func (b Bool) String() string

func (Bool) Truth

func (b Bool) Truth() Bool

func (Bool) Type

func (b Bool) Type() string

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

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 (*Builtin) Call

func (b *Builtin) Call(thread *Thread, args Tuple, kwargs []Tuple) (Value, error)

func (*Builtin) Freeze

func (b *Builtin) Freeze()

func (*Builtin) Hash

func (b *Builtin) Hash() (uint32, error)

func (*Builtin) Name

func (b *Builtin) Name() string

func (*Builtin) Receiver

func (b *Builtin) Receiver() Value

func (*Builtin) String

func (b *Builtin) String() string

func (*Builtin) Truth

func (b *Builtin) Truth() Bool

func (*Builtin) Type

func (b *Builtin) Type() string

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 Skylark dictionary.

func (*Dict) Attr

func (d *Dict) Attr(name string) (Value, error)

func (*Dict) AttrNames

func (d *Dict) AttrNames() []string

func (*Dict) Clear

func (d *Dict) Clear() error

func (*Dict) CompareSameType

func (x *Dict) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error)

func (*Dict) Delete

func (d *Dict) Delete(k Value) (v Value, found bool, err error)

func (*Dict) Freeze

func (d *Dict) Freeze()

func (*Dict) Get

func (d *Dict) Get(k Value) (v Value, found bool, err error)

func (*Dict) Hash

func (d *Dict) Hash() (uint32, error)

func (*Dict) Items

func (d *Dict) Items() []Tuple

func (*Dict) Iterate

func (d *Dict) Iterate() Iterator

func (*Dict) Keys

func (d *Dict) Keys() []Value

func (*Dict) Len

func (d *Dict) Len() int

func (*Dict) Set

func (d *Dict) Set(k, v Value) error

func (*Dict) String

func (d *Dict) String() string

func (*Dict) Truth

func (d *Dict) Truth() Bool

func (*Dict) Type

func (d *Dict) Type() string

type EvalError

type EvalError struct {
	Msg   string
	Frame *Frame
}

An EvalError is a Skylark evaluation error and its associated call stack.

func (*EvalError) Backtrace

func (e *EvalError) Backtrace() string

Backtrace returns a user-friendly error message describing the stack of calls that led to this error.

func (*EvalError) Error

func (e *EvalError) Error() string

func (*EvalError) Stack

func (e *EvalError) Stack() []*Frame

Stack returns the stack of frames, innermost first.

type Float

type Float float64

Float is the type of a Skylark float.

func (Float) CompareSameType

func (x Float) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error)

func (Float) Freeze

func (f Float) Freeze()

func (Float) Hash

func (f Float) Hash() (uint32, error)

func (Float) Mod

func (x Float) Mod(y Float) Float

func (Float) String

func (f Float) String() string

func (Float) Truth

func (f Float) Truth() Bool

func (Float) Type

func (f Float) Type() string

type Frame

type Frame struct {
	// contains filtered or unexported fields
}

A Frame records a call to a Skylark function (including module toplevel) or a built-in function or method.

func (*Frame) Callable

func (fr *Frame) Callable() Callable

Function returns the frame's function or built-in.

func (*Frame) Parent

func (fr *Frame) Parent() *Frame

Parent returns the frame of the enclosing function call, if any.

func (*Frame) Position

func (fr *Frame) Position() syntax.Position

Position returns the source position of the current point of execution in this frame.

func (*Frame) WriteBacktrace

func (fr *Frame) WriteBacktrace(out *bytes.Buffer)

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 Skylark def statement or lambda expression. The initialization behavior of a Skylark module is also represented by a Function.

func (*Function) Call

func (fn *Function) Call(thread *Thread, args Tuple, kwargs []Tuple) (Value, error)

func (*Function) Freeze

func (fn *Function) Freeze()

func (*Function) Globals

func (fn *Function) Globals() StringDict

Globals returns a new, unfrozen StringDict containing all global variables so far defined in the function's module.

func (*Function) HasKwargs

func (fn *Function) HasKwargs() bool

func (*Function) HasVarargs

func (fn *Function) HasVarargs() bool

func (*Function) Hash

func (fn *Function) Hash() (uint32, error)

func (*Function) Name

func (fn *Function) Name() string

func (*Function) NumParams

func (fn *Function) NumParams() int

func (*Function) Param

func (fn *Function) Param(i int) (string, syntax.Position)

func (*Function) Position

func (fn *Function) Position() syntax.Position

func (*Function) String

func (fn *Function) String() string

func (*Function) Truth

func (fn *Function) Truth() Bool

func (*Function) Type

func (fn *Function) Type() string

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

type HasBinary interface {
	Value
	Binary(op syntax.Token, y Value, side Side) (Value, error)
}

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

type HasSetField interface {
	HasAttrs
	SetField(name string, val Value) error
}

A HasSetField value has fields that may be written by a dot expression (x.f = y).

type HasSetIndex

type HasSetIndex interface {
	Indexable
	SetIndex(index int, v 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 Indexable

type Indexable interface {
	Value
	Index(i int) Value // requires 0 <= i < Len()
	Len() int
}

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 Skylark int.

func MakeInt

func MakeInt(x int) Int

MakeInt returns a Skylark int for the specified signed integer.

func MakeInt64

func MakeInt64(x int64) Int

MakeInt64 returns a Skylark int for the specified int64.

func MakeUint

func MakeUint(x uint) Int

MakeUint returns a Skylark int for the specified unsigned integer.

func MakeUint64

func MakeUint64(x uint64) Int

MakeUint64 returns a Skylark int for the specified uint64.

func NumberToInt

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 (Int) Add

func (x Int) Add(y Int) Int

func (Int) And

func (x Int) And(y Int) Int

func (Int) CompareSameType

func (x Int) CompareSameType(op syntax.Token, y Value, depth int) (bool, error)

func (Int) Div

func (x Int) Div(y Int) Int

Precondition: y is nonzero.

func (Int) Float

func (i Int) Float() Float

Float returns the float value nearest i.

func (Int) Freeze

func (i Int) Freeze()

func (Int) Hash

func (i Int) Hash() (uint32, error)

func (Int) Int64

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 (Int) Lsh

func (x Int) Lsh(y uint) Int

func (Int) Mod

func (x Int) Mod(y Int) Int

Precondition: y is nonzero.

func (Int) Mul

func (x Int) Mul(y Int) Int

func (Int) Not

func (x Int) Not() Int

func (Int) Or

func (x Int) Or(y Int) Int

func (Int) Rsh

func (x Int) Rsh(y uint) Int

func (Int) Sign

func (x Int) Sign() int

func (Int) String

func (i Int) String() string

func (Int) Sub

func (x Int) Sub(y Int) Int

func (Int) Truth

func (i Int) Truth() Bool

func (Int) Type

func (i Int) Type() string

func (Int) Uint64

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 (Int) Xor

func (x Int) Xor(y Int) Int

type Iterable

type Iterable interface {
	Value
	Iterate() Iterator // must be followed by call to Iterator.Done
}

An Iterable abstracts a sequence of values. An iterable value may be iterated over by a 'for' loop or used where any other Skylark 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) {
	...
}

func Iterate

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.

type List

type List struct {
	// contains filtered or unexported fields
}

A *List represents a Skylark list value.

func NewList

func NewList(elems []Value) *List

NewList returns a list containing the specified elements. Callers should not subsequently modify elems.

func (*List) Append

func (l *List) Append(v Value) error

func (*List) Attr

func (l *List) Attr(name string) (Value, error)

func (*List) AttrNames

func (l *List) AttrNames() []string

func (*List) Clear

func (l *List) Clear() error

func (*List) CompareSameType

func (x *List) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error)

func (*List) Freeze

func (l *List) Freeze()

func (*List) Hash

func (l *List) Hash() (uint32, error)

func (*List) Index

func (l *List) Index(i int) Value

func (*List) Iterate

func (l *List) Iterate() Iterator

func (*List) Len

func (l *List) Len() int

func (*List) SetIndex

func (l *List) SetIndex(i int, v Value) error

func (*List) Slice

func (l *List) Slice(start, end, step int) Value

func (*List) String

func (l *List) String() string

func (*List) Truth

func (l *List) Truth() Bool

func (*List) Type

func (l *List) Type() string

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

func (NoneType) CompareSameType(op syntax.Token, y Value, depth int) (bool, error)

func (NoneType) Freeze

func (NoneType) Freeze()

func (NoneType) Hash

func (NoneType) Hash() (uint32, error)

func (NoneType) String

func (NoneType) String() string

func (NoneType) Truth

func (NoneType) Truth() Bool

func (NoneType) Type

func (NoneType) Type() string

type Program

type Program struct {
	// contains filtered or unexported fields
}

A Program is a compiled Skylark 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).

func CompiledProgram

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 SourceProgram

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 Skylark 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 (*Program) Init

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 (*Program) Load

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 (*Program) NumLoads

func (prog *Program) NumLoads() int

NumLoads returns the number of load statements in the compiled program.

func (*Program) Write

func (prog *Program) Write(out io.Writer) error

WriteTo writes the compiled module to the specified output stream.

type Sequence

type Sequence interface {
	Iterable
	Len() int
}

A Sequence is a sequence of values of known length.

type Set

type Set struct {
	// contains filtered or unexported fields
}

A Set represents a Skylark set value.

func (*Set) Attr

func (s *Set) Attr(name string) (Value, error)

func (*Set) AttrNames

func (s *Set) AttrNames() []string

func (*Set) Clear

func (s *Set) Clear() error

func (*Set) CompareSameType

func (x *Set) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error)

func (*Set) Delete

func (s *Set) Delete(k Value) (found bool, err error)

func (*Set) Freeze

func (s *Set) Freeze()

func (*Set) Has

func (s *Set) Has(k Value) (found bool, err error)

func (*Set) Hash

func (s *Set) Hash() (uint32, error)

func (*Set) Insert

func (s *Set) Insert(k Value) error

func (*Set) Iterate

func (s *Set) Iterate() Iterator

func (*Set) Len

func (s *Set) Len() int

func (*Set) String

func (s *Set) String() string

func (*Set) Truth

func (s *Set) Truth() Bool

func (*Set) Type

func (s *Set) Type() string

func (*Set) Union

func (s *Set) Union(iter Iterator) (Value, error)

type Side

type Side bool
const (
	Left  Side = false
	Right Side = true
)

type Sliceable

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.
	Slice(start, end, step int) Value
}

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 String

type String string

String is the type of a Skylark 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.

func (String) Attr

func (s String) Attr(name string) (Value, error)

func (String) AttrNames

func (s String) AttrNames() []string

func (String) CompareSameType

func (x String) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error)

func (String) Freeze

func (s String) Freeze()

func (String) Hash

func (s String) Hash() (uint32, error)

func (String) Index

func (s String) Index(i int) Value

func (String) Len

func (s String) Len() int

func (String) Slice

func (s String) Slice(start, end, step int) Value

func (String) String

func (s String) String() string

func (String) Truth

func (s String) Truth() Bool

func (String) Type

func (s String) Type() string

type StringDict

type StringDict map[string]Value

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 skylark.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 Skylark evaluation begins. All values in the dictionary must be immutable. Skylark programs cannot modify the dictionary.

func ExecFile

func ExecFile(thread *Thread, filename string, src interface{}, predeclared StringDict) (StringDict, error)

ExecFile parses, resolves, and executes a Skylark file in the specified global environment, which may be modified during execution.

Thread is the state associated with the Skylark 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

ExampleExecFile demonstrates a simple embedding of the Skylark interpreter into a Go program.

package main

import (
	"fmt"
	"log"
	"sort"

	"github.com/google/skylark"
)

func main() {
	const data = `
print(greeting + ", world")

squares = [x*x for x in range(10)]
`

	thread := &skylark.Thread{
		Print: func(_ *skylark.Thread, msg string) { fmt.Println(msg) },
	}
	predeclared := skylark.StringDict{
		"greeting": skylark.String("hello"),
	}
	globals, err := skylark.ExecFile(thread, "apparent/filename.sky", data, predeclared)
	if err != nil {
		if evalErr, ok := err.(*skylark.EvalError); ok {
			log.Fatal(evalErr.Backtrace())
		}
		log.Fatal(err)
	}

	// Print the global environment.
	var names []string
	for name := range globals {
		names = append(names, name)
	}
	sort.Strings(names)
	fmt.Println("\nGlobals:")
	for _, name := range names {
		v := globals[name]
		fmt.Printf("%s (%s) = %s\n", name, v.Type(), v.String())
	}

}
Output:

hello, world

Globals:
squares (list) = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

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 Skylark
	// '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 Skylark thread, such as its call stack and thread-local storage. The Thread is threaded throughout the evaluator.

func (*Thread) Caller

func (thread *Thread) Caller() *Frame

Caller returns the frame of the caller of the current function. It should only be used in built-ins called from Skylark code.

func (*Thread) Local

func (thread *Thread) Local(key string) interface{}

Local returns the thread-local value associated with the specified key.

func (*Thread) SetLocal

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) TopFrame

func (thread *Thread) TopFrame() *Frame

TopFrame returns the topmost stack frame.

type Tuple

type Tuple []Value

A Tuple represents a Skylark tuple value.

func (Tuple) CompareSameType

func (x Tuple) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error)

func (Tuple) Freeze

func (t Tuple) Freeze()

func (Tuple) Hash

func (t Tuple) Hash() (uint32, error)

func (Tuple) Index

func (t Tuple) Index(i int) Value

func (Tuple) Iterate

func (t Tuple) Iterate() Iterator

func (Tuple) Len

func (t Tuple) Len() int

func (Tuple) Slice

func (t Tuple) Slice(start, end, step int) Value

func (Tuple) String

func (t Tuple) String() string

func (Tuple) Truth

func (t Tuple) Truth() Bool

func (Tuple) Type

func (t Tuple) Type() string

type Value

type Value interface {
	// String returns the string representation of the value.
	// Skylark 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
	// Skylark 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 Skylark interpreter.

func Binary

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

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

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 Unary

func Unary(op syntax.Token, x Value) (Value, error)

Unary applies a unary operator (+, -, ~, not) to its operand.

Directories

Path Synopsis
cmd
skylark
The skylark command interprets a Skylark file.
The skylark command interprets a Skylark 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.
compile
The compile package defines the Skylark bytecode compiler.
The compile package defines the Skylark bytecode compiler.
The repl package provides a read/eval/print loop for Skylark.
The repl package provides a read/eval/print loop for Skylark.
Package resolve defines a name-resolution pass for Skylark abstract syntax trees.
Package resolve defines a name-resolution pass for Skylark abstract syntax trees.
Package skylarkstruct defines the Skylark 'struct' type, an optional language extension.
Package skylarkstruct defines the Skylark 'struct' type, an optional language extension.
Package skylarktest defines utilities for testing Skylark programs.
Package skylarktest defines utilities for testing Skylark programs.
Package syntax provides a Skylark parser and abstract syntax tree.
Package syntax provides a Skylark parser and abstract syntax tree.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL