Skip to main content

Value

Enum Value 

Source
pub enum Value {
    Nothing,
    Bool(bool),
    Numb(f64),
    Text(Rc<str>),
    List(Rc<Vec<Value>>),
    Namespace(Scope),
    Func {
        params: Box<Value>,
        body: Box<Node>,
        closure: Scope,
    },
    Builtin(BuiltinFn),
    Promise(Promise),
    Undefined(Undef),
    Tuple(Rc<Vec<Value>>),
    Name(Rc<str>),
}
Expand description

Any first-class Swan value.

Cloning is cheap: heap-backed variants (Text, List, Tuple, Name) use Rc, and Scope, Promise and BuiltinFn are handles that share state when cloned.

The Swan type name of each variant (as returned by the type built-in) is the variant name, except that Builtin reports Func.

§Examples

use swan_core::value::Value;

let t = Value::tuple(vec![Value::Numb(1.0), Value::Nothing, Value::Numb(2.0)]);
assert_eq!(t.items().count(), 2);
assert!(bool::from(t));

Variants§

§

Nothing

The empty tuple (). Also the result of failed lookups such as out-of-range list indexing.

§

Bool(bool)

A boolean, TRUE or FALSE.

§

Numb(f64)

A 64-bit floating-point number.

§

Text(Rc<str>)

An immutable UTF-8 string.

§

List(Rc<Vec<Value>>)

An ordered, integer-indexed sequence — [a, b, c].

§

Namespace(Scope)

A first-class namespace — { x: 1, y: 2 }.

Backed by a Scope. Applying a namespace to a Text key performs an own-only lookup (parent scopes are not consulted) and yields Nothing if the key is absent. Equality compares bindings (and parents) by value.

§

Func

A user-defined function.

Fields

§params: Box<Value>

Parameter pattern: a Name or a tuple of names.

§body: Box<Node>

Unevaluated body expression.

§closure: Scope

Scope captured at definition time.

§

Builtin(BuiltinFn)

A native Rust function callable from Swan.

§

Promise(Promise)

A promise. It resolves at most once and never rejects; an Undefined result resolves to Nothing.

§

Undefined(Undef)

The result of an invalid operation, such as "a" - 1.

Swan expressions do not throw exceptions; they return Undefined values instead. The Undef payload describes what went wrong.

§

Tuple(Rc<Vec<Value>>)

The Swan product type — a heterogeneous sequence of items produced by the comma operator a, b, c. A Tuple of zero items is Nothing. A Tuple of exactly one item normalises to that item. Construct with Value::tuple so the result is normalized.

§

Name(Rc<str>)

An identifier in a binding position: the left side of =, : or ->, or the operand of $. It is produced only while evaluating those positions and has no meaning as a runtime result.

Implementations§

Source§

impl Value

Source

pub fn undef_unary(op: &'static str, val: Value, pos: usize) -> Value

Builds Undefined for unary operation op applied to val; pos is the source byte offset.

Source

pub fn undef_binary( op: &'static str, lhv: Value, rhv: Value, pos: usize, ) -> Value

Builds Undefined for binary operation op applied to lhv and rhv; pos is the source byte offset.

Source

pub fn list(items: Vec<Value>) -> Value

Builds a List from items.

Source

pub fn tuple(items: Vec<Value>) -> Value

Builds a normalized tuple from items.

Zero items give Nothing. One item gives that item. Nested tuples are flattened and Nothing items are dropped (see Value::normalize).

Source§

impl Value

Source

pub fn items(&self) -> ValueIter ⓘ

Returns an iterator over this value’s items, treating it as a tuple.

  • Nothing yields no items.
  • Tuple yields its items (recursively flattened, Nothing skipped).
  • Any other value yields itself as the single item.
Source

pub fn pair(&self, other: &Value) -> Pairs ⓘ

Returns an iterator yielding corresponding pairs of items between self and other, treating each value as a tuple.

If the two values have different lengths, the missing items from the shorter tuple are replaced with Value::Nothing.

Source

pub fn normalize(&self) -> Self

Returns the canonical form of this value.

For a Tuple, nested tuples are flattened and Nothing items are removed. The result is Nothing if no items remain, the sole item if one remains, and a Tuple otherwise. Non-tuple values are returned unchanged (cloned).

Source

pub fn map(&self, f: impl Fn(Value) -> Value + 'static) -> Value

Maps a function f: Value -> Value over this Value:

  • Value::Nothing -> Value::Nothing
  • Value::Tuple -> Value::Tuple containing f(v1), f(v2), ..., f(vn)
  • Any other value -> f(self) The result of mapping over a tuple is normalized, so items that map to Nothing are dropped.

Trait Implementations§

Source§

impl Clone for Value

Source§

fn clone(&self) -> Value

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Value

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<Value> for bool

Truthiness of a value.

  • Nothing and Undefined are false.
  • Bool is itself; Numb is false only for 0; Text and List are true when non-empty; Namespace is true when it has at least one binding.
  • Func and Builtin are always true.
  • A Promise is true once it is resolved (whatever its value) and false while it is pending.
  • A Name has no boolean meaning and is false.
  • A Tuple is true if at least one item is true.
Source§

fn from(val: Value) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for Value

Structural equality.

Values of different variants are never equal. Promises are equal only if they are the same promise (pointer identity). Func, Builtin and Name are never equal to anything, including themselves. Undefined values compare by operation and operands, ignoring source position.

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialOrd for Value

Partial ordering between values.

Only values of the same variant are comparable (Bool, Numb, Text, List, Tuple); lists and tuples compare lexicographically, with the shorter sequence ordering first. Nothing equals Nothing and orders before every other value. Every other pair returns None (e.g. NaN, mixed types, Func, Builtin, Namespace, Promise, Undefined).

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Value

§

impl !Send for Value

§

impl !Sync for Value

§

impl !UnwindSafe for Value

§

impl Freeze for Value

§

impl Unpin for Value

§

impl UnsafeUnpin for Value

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.