Module starlark::values

source ·
Expand description

The values module define a trait TypedValue that defines the attribute of any value in Starlark and a few macro to help implementing this trait. The Value struct defines the actual structure holding a TypedValue. It is mostly used to enable mutable and Rc behavior over a TypedValue. This modules also defines this traits for the basic immutable values: int, bool and NoneType. Sub-modules implement other common types of all Starlark dialect.

Note: we use sequence, iterable and indexable according to the definition in the Starlark specification. We also use the term container for denoting any of those type that can hold several values.

Defining a new type

Defining a new Starlark type can be done by implenting the TypedValue trait. All method of that trait are operation needed by Starlark interpreter to understand the type. The not_supported! macro let us tell which operation is not supported by the current type.

For example the NoneType trait implementation is the following:

/// Define the NoneType type
impl TypedValue for Option<()> {
    immutable!();
    any!();  // Generally you don't want to implement as_any() and as_any_mut() yourself.
    fn to_str(&self) -> String {
        "None".to_owned()
    }
    fn to_repr(&self) -> String {
        self.to_str()
    }
    not_supported!(to_int);
    fn get_type(&self) -> &'static str {
        "NoneType"
    }
    fn to_bool(&self) -> bool {
        false
    }
    // just took the result of hash(None) in macos python 2.7.10 interpreter.
    fn get_hash(&self) -> Result<u64, ValueError> {
        Ok(9223380832852120682)
    }
    fn compare(&self, other: &Value) -> Ordering { default_compare(self, other) }
    not_supported!(binop);
    not_supported!(container);
    not_supported!(function);
}

In addition to the TypedValue trait, it is recommended to implement the From trait for all type that can convert to the added type but parameterized it with the Into<Value> type. For example the unary tuple From trait is defined as followed:

impl<T: Into<Value>> From<(T,)> for Tuple {
    fn from(a: (T,)) -> Tuple {
        Tuple { content: vec![a.0.into()] }
    }
}

Modules

Module define the Starlark type Dictionary
Function as a TypedValue
Define the list type of Starlark
Define the string type for Starlark.
Define the tuple type for Starlark.

Structs

A simpler error format to return as a ValueError
A value in Starlark.

Enums

A helper enum for defining the level of mutability of an iterable.
Error that can be returned by function from the TypedValue trait,

Constants

Traits

A trait for a value with a type that all variable container will implement.

Functions

A default implementation of the compare function, this can be used if the two types of value are differents or numeric. Custom types should implement their own comparison for the last case.

Type Definitions