Skip to main content

Expr

Struct Expr 

Source
pub struct Expr { /* private fields */ }
Expand description

Wolfram Language expression.

§Example

Construct the expression {1, 2, 3}:

use wolfram_expr::{Expr, Symbol};

let expr = Expr::normal(Symbol::new("System`List"), vec![
    Expr::from(1),
    Expr::from(2),
    Expr::from(3)
]);

§Reference counting

Internally, Expr is an atomically reference-counted ExprKind. This makes cloning an expression computationally inexpensive.

Implementations§

Source§

impl Expr

Source

pub fn try_as_normal(&self) -> Option<&Normal>

👎Deprecated:

use <&Normal>::try_from(expr) instead

If this is a Normal expression, return that. Otherwise return None.

§Migration
let normal: Option<&Normal> = <&Normal>::try_from(&expr).ok();
Source

pub fn try_as_bool(&self) -> Option<bool>

👎Deprecated:

use bool::try_from(expr) instead

If this is the True or False symbol, return that. Otherwise None.

§Migration
let is_true_or_false: Option<bool> = bool::try_from(&expr).ok();
Source

pub fn try_as_str(&self) -> Option<&str>

👎Deprecated:

use <&str>::try_from(expr) instead

If this is an ExprKind::String expression, return that. Otherwise return None.

§Migration
let s: Option<&str> = <&str>::try_from(&expr).ok();
Source

pub fn try_as_symbol(&self) -> Option<&Symbol>

👎Deprecated:

use <&Symbol>::try_from(expr) instead

If this is a Symbol expression, return that. Otherwise return None.

§Migration
let sym: Option<&Symbol> = <&Symbol>::try_from(&expr).ok();
Source

pub fn try_as_number(&self) -> Option<Number>

👎Deprecated:

use i64::try_from(expr) / f64::try_from(expr) instead

If this is a Number expression, return that. Otherwise return None.

§Migration
let int: Option<i64> = i64::try_from(&expr).ok();
let real: Option<f64> = f64::try_from(&expr).ok();
Source

pub fn try_normal(&self) -> Option<&Normal>

👎Deprecated:

use <&Normal>::try_from(expr) instead

Source

pub fn try_symbol(&self) -> Option<&Symbol>

👎Deprecated:

use <&Symbol>::try_from(expr) instead

Source

pub fn try_number(&self) -> Option<Number>

👎Deprecated:

use i64::try_from(expr) / f64::try_from(expr) instead

Source§

impl Expr

Source

pub fn new(kind: ExprKind) -> Expr

Construct a new expression from an ExprKind.

Source

pub fn to_kind(self) -> ExprKind

Consume self and return an owned ExprKind.

If the reference count of self is equal to 1 this function will not perform a clone of the stored ExprKind, making this operation very cheap in that case.

Source

pub fn kind(&self) -> &ExprKind

Get the ExprKind representing this expression.

Examples found in repository?
examples/exprs/managed.rs (line 58)
54fn set_instance_value(args: Vec<Expr>) {
55    assert!(args.len() == 2, "set_instance_value: expected 2 arguments");
56
57    let id: u32 = unwrap_id_arg(&args[0]);
58    let value: String = match args[1].kind() {
59        ExprKind::String(str) => str.clone(),
60        _ => panic!("expected 2nd argument to be a String, got: {}", args[1]),
61    };
62
63    let mut instances = INSTANCES.lock().unwrap();
64
65    let instance: &mut MyObject =
66        instances.get_mut(&id).expect("instance does not exist");
67
68    instance.value = value;
69}
70
71/// Get the fields of the `MyObject` instance for the specified instance ID.
72#[wll::export(wstp)]
73fn get_instance_data(args: Vec<Expr>) -> Expr {
74    assert!(args.len() == 1, "get_instance_data: expected 1 argument");
75
76    let id: u32 = unwrap_id_arg(&args[0]);
77
78    let MyObject { value } = {
79        let instances = INSTANCES.lock().unwrap();
80
81        instances
82            .get(&id)
83            .cloned()
84            .expect("instance does not exist")
85    };
86
87    expr!({ "Value" -> value })
88}
89
90fn unwrap_id_arg(arg: &Expr) -> u32 {
91    match arg.kind() {
92        ExprKind::Integer(int) => u32::try_from(*int).expect("id overflows u32"),
93        _ => panic!("expected Integer instance ID argument, got: {}", arg),
94    }
95}
More examples
Hide additional examples
examples/wstp.rs (line 179)
176fn expr_string_join(link: &mut Link) {
177    let expr = link.get_expr().unwrap();
178
179    let ExprKind::Normal(list) = expr.kind() else {
180        panic!("expected a List, got: {:?}", expr);
181    };
182    assert!(list.has_head(&Symbol::new("System`List")));
183
184    let mut buffer = String::new();
185    for elem in list.elements() {
186        match elem.kind() {
187            ExprKind::String(str) => buffer.push_str(str),
188            _ => panic!("expected String argument, got: {:?}", elem),
189        }
190    }
191
192    link.put_str(buffer.as_str()).unwrap()
193}
194
195//======================================
196// Using `Vec<Expr>` argument list
197//======================================
198
199//------------------
200// total()
201//------------------
202
203#[wll::export(wstp)]
204fn total(args: Vec<Expr>) -> Expr {
205    let mut total = 0.0f64;
206    for (index, arg) in args.into_iter().enumerate() {
207        total += match arg.kind() {
208            ExprKind::Integer(n) => *n as f64,
209            ExprKind::Real(f) => f64::from(*f),
210            _ => panic!(
211                "expected argument at position {} to be a number, got {}",
212                index + 1,
213                arg
214            ),
215        };
216    }
217    Expr::from(total)
218}
Source

pub fn kind_mut(&mut self) -> &mut ExprKind

Get mutable access to the ExprKind that represents this expression.

If the reference count of the underlying shared pointer is not equal to 1, this will clone the ExprKind to make it unique.

Source

pub fn ref_count(&self) -> usize

Retrieve the reference count of this expression.

Source

pub fn normal<H>(head: H, contents: Vec<Expr>) -> Expr
where H: Into<Expr>,

Construct a new normal expression from the head and elements.

Source

pub fn symbol<S>(s: S) -> Expr
where S: Into<Symbol>,

Construct a new expression from a Symbol.

Source

pub fn number(num: Number) -> Expr

👎Deprecated since 0.6.0-alpha.3:

use Expr::from(i64) or Expr::from(f64) instead

Construct a new expression from a Number.

§Migration
// Expr::number(Number::Integer(42))
let _int = Expr::from(42_i64);

// Expr::number(Number::real(3.14))
let _real = Expr::from(3.14_f64);  // or Expr::real(3.14)

// Expr::number(Number::Real(f))  — when you already have an F64
let f = F64::new(3.14).unwrap();
let _real = Expr::new(ExprKind::Real(f));
Source

pub fn string<S>(s: S) -> Expr
where S: Into<String>,

Construct a new expression from a String.

Examples found in repository?
examples/exprs/basic_expressions.rs (line 25)
17pub fn echo_arguments(args: Vec<Expr>) -> Expr {
18    let arg_count = args.len();
19
20    for arg in args {
21        // Echo[<arg>]
22        wll::evaluate(&expr!(System::Echo[arg]));
23    }
24
25    Expr::string(format!("finished echoing {} argument(s)", arg_count))
26}
More examples
Hide additional examples
examples/raw/raw_wstp_function.rs (line 125)
81pub extern "C" fn demo_wstp_function_callback(
82    lib: WolframLibraryData,
83    mut link: WSLINK,
84) -> c_uint {
85    // Create a safe Link wrapper around the raw `WSLINK`. This is a borrowed rather than
86    // owned Link because the caller (the Kernel) owns the link.
87    let link: &mut Link = unsafe { Link::unchecked_ref_cast_mut(&mut link) };
88
89    // Skip reading the argument list packet.
90    if link.raw_get_next().and_then(|_| link.new_packet()).is_err() {
91        return LIBRARY_FUNCTION_ERROR;
92    }
93
94    let callback_link = unsafe { (*lib).getWSLINK.unwrap()(lib) };
95    let mut callback_link = callback_link as wstp::sys::WSLINK;
96
97    {
98        let safe_callback_link =
99            unsafe { Link::unchecked_ref_cast_mut(&mut callback_link) };
100
101        safe_callback_link
102            // EvaluatePacket[Print["Hello, World! --- WSTP"]]
103            .put_expr(&expr!(
104                System::EvaluatePacket[System::Print["Hello, World! --- WSTP"]]
105            ))
106            .unwrap();
107
108        unsafe {
109            (*lib).processWSLINK.unwrap()(
110                safe_callback_link.raw_link() as wll_sys::WSLINK
111            );
112        }
113
114        // Skip the return value packet. This is necessary, otherwise the link has
115        // unread data and the return value of this function cannot be processed properly.
116        if safe_callback_link
117            .raw_get_next()
118            .and_then(|_| safe_callback_link.new_packet())
119            .is_err()
120        {
121            return LIBRARY_FUNCTION_ERROR;
122        }
123    }
124
125    link.put_expr(&Expr::string("returned normally")).unwrap();
126
127    return LIBRARY_NO_ERROR;
128}
129
130/// This example makes use of the [`wstp`][wstp] crate to provide a safe wrapper around
131/// around the WSTP link object, which can be used to read the argument expression and
132/// write out the return expression.
133///
134/// ```wolfram
135/// function = LibraryFunctionLoad[
136///     "raw_wstp_function",
137///     "wstp_expr_function",
138///     LinkObject,
139///     LinkObject
140/// ];
141/// ```
142#[no_mangle]
143pub extern "C" fn wstp_expr_function(
144    _lib: WolframLibraryData,
145    mut unsafe_link: WSLINK,
146) -> c_uint {
147    let link: &mut Link = unsafe { Link::unchecked_ref_cast_mut(&mut unsafe_link) };
148
149    let expr = match link.get_expr() {
150        Ok(expr) => expr,
151        Err(err) => {
152            // Skip reading the argument list packet.
153            if link.raw_get_next().and_then(|_| link.new_packet()).is_err() {
154                return LIBRARY_FUNCTION_ERROR;
155            }
156
157            let msg = err.to_string();
158            let err = wolfram_library_link::expr::expr!(
159                System::Failure["WSTP Error", {"Message" -> msg}]
160            );
161            match link.put_expr(&err) {
162                Ok(()) => return LIBRARY_NO_ERROR,
163                Err(_) => return LIBRARY_FUNCTION_ERROR,
164            }
165        },
166    };
167
168    let expr_string = format!("Input: {}", expr.to_string());
169
170    match link.put_expr(&Expr::string(expr_string)) {
171        Ok(()) => LIBRARY_NO_ERROR,
172        Err(_) => LIBRARY_FUNCTION_ERROR,
173    }
174}
Source

pub fn real(real: f64) -> Expr

Construct an expression from a floating-point number.

let expr = Expr::real(3.14159);
§Panics

This function will panic if real is NaN.

Source

pub fn tag(&self) -> Option<Symbol>

Returns the outer-most symbol “tag” used in this expression.

To illustrate:

ExpressionTag
5None
"hello"None
foofoo
f[1, 2, 3]f
g[x][y]g
Source

pub fn normal_head(&self) -> Option<Expr>

If this represents a Normal expression, return its head. Otherwise, return None.

Source

pub fn normal_part(&self, index_0: usize) -> Option<&Expr>

Attempt to get the element at index of a Normal expression.

Return None if this is not a Normal expression, or the given index is out of bounds.

index is 0-based. The 0th index is the first element, not the head.

This function does not panic.

Source

pub fn has_normal_head(&self, sym: &Symbol) -> bool

Returns true if self is a Normal expr with the head sym.

Source

pub fn null() -> Expr

Null WL.

Source

pub fn rule<LHS>(lhs: LHS, rhs: Expr) -> Expr
where LHS: Into<Expr>,

Construct a new Rule[_, _] expression from the left-hand side and right-hand side.

§Example

Construct the expression FontSize -> 16:

use wolfram_expr::{Expr, Symbol};

let option = Expr::rule(Symbol::new("System`FontSize"), Expr::from(16));
Source

pub fn rule_delayed<LHS>(lhs: LHS, rhs: Expr) -> Expr
where LHS: Into<Expr>,

Construct a new RuleDelayed[_, _] expression from the left-hand side and right-hand side.

§Example

Construct the expression x :> RandomReal[]:

use wolfram_expr::{Expr, Symbol};

let delayed = Expr::rule_delayed(
    Symbol::new("Global`x"),
    Expr::normal(Symbol::new("System`RandomReal"), vec![])
);
Source

pub fn list(elements: Vec<Expr>) -> Expr

Construct a new List[...]({...}) expression from it’s elements.

§Example

Construct the expression {1, 2, 3}:

use wolfram_expr::Expr;

let list = Expr::list(vec![Expr::from(1), Expr::from(2), Expr::from(3)]);

Trait Implementations§

Source§

impl Clone for Expr

Source§

fn clone(&self) -> Expr

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 Expr

Source§

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

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

impl Display for Expr

Source§

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

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

impl Eq for Expr

Source§

impl From<&LibraryError> for Expr

Source§

fn from(__value: &LibraryError) -> Expr

Converts to this type from the input type.
Source§

impl From<&String> for Expr

Source§

fn from(s: &String) -> Expr

Converts to this type from the input type.
Source§

impl From<&Symbol> for Expr

Source§

fn from(sym: &Symbol) -> Expr

Converts to this type from the input type.
Source§

impl From<&str> for Expr

Source§

fn from(s: &str) -> Expr

Converts to this type from the input type.
Source§

impl From<ArrayBuf<NumericArrayEnum>> for Expr

Source§

fn from(a: ArrayBuf<NumericArrayEnum>) -> Expr

Converts to this type from the input type.
Source§

impl From<ArrayBuf<PackedArrayEnum>> for Expr

Source§

fn from(a: ArrayBuf<PackedArrayEnum>) -> Expr

Converts to this type from the input type.
Source§

impl From<BigInteger> for Expr

Source§

fn from(n: BigInteger) -> Expr

Converts to this type from the input type.
Source§

impl From<BigReal> for Expr

Source§

fn from(r: BigReal) -> Expr

Converts to this type from the input type.
Source§

impl From<LibraryError> for Expr

Source§

fn from(__value: LibraryError) -> Expr

Converts to this type from the input type.
Source§

impl From<Normal> for Expr

Source§

fn from(normal: Normal) -> Expr

Converts to this type from the input type.
Source§

impl From<String> for Expr

Source§

fn from(s: String) -> Expr

Converts to this type from the input type.
Source§

impl From<Symbol> for Expr

Source§

fn from(sym: Symbol) -> Expr

Converts to this type from the input type.
Source§

impl From<Vec<Expr>> for Expr

Source§

fn from(v: Vec<Expr>) -> Expr

Converts to this type from the input type.
Source§

impl From<Vec<RuleEntry>> for Expr

Source§

fn from(a: Vec<RuleEntry>) -> Expr

Converts to this type from the input type.
Source§

impl From<Vec<u8>> for Expr

Source§

fn from(b: Vec<u8>) -> Expr

Converts to this type from the input type.
Source§

impl From<bool> for Expr

Source§

fn from(value: bool) -> Expr

Converts to this type from the input type.
Source§

impl From<f64> for Expr

Source§

fn from(f: f64) -> Expr

Converts to this type from the input type.
Source§

impl From<i8> for Expr

Source§

fn from(int: i8) -> Expr

Converts to this type from the input type.
Source§

impl From<i16> for Expr

Source§

fn from(int: i16) -> Expr

Converts to this type from the input type.
Source§

impl From<i32> for Expr

Source§

fn from(int: i32) -> Expr

Converts to this type from the input type.
Source§

impl From<i64> for Expr

Source§

fn from(int: i64) -> Expr

Converts to this type from the input type.
Source§

impl From<u8> for Expr

Source§

fn from(int: u8) -> Expr

Converts to this type from the input type.
Source§

impl From<u16> for Expr

Source§

fn from(int: u16) -> Expr

Converts to this type from the input type.
Source§

impl From<u32> for Expr

Source§

fn from(int: u32) -> Expr

Converts to this type from the input type.
Source§

impl<'de> FromWXF<'de> for Expr

Source§

fn from_wxf<R>(r: &mut WxfReader<R>) -> Result<Self, Error>
where R: Reader<'de>,

Read a complete value: its expression token, then its body.
Source§

impl Hash for Expr

Source§

fn hash<__H>(&self, state: &mut __H)
where __H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for Expr

Source§

fn cmp(&self, other: &Expr) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for Expr

Source§

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

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

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

Inequality operator !=. Read more
Source§

impl PartialEq<Symbol> for Expr

Source§

fn eq(&self, other: &Symbol) -> 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 Expr

Source§

fn partial_cmp(&self, other: &Expr) -> 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
Source§

impl StructuralPartialEq for Expr

Source§

impl ToWXF for Expr

Source§

fn to_wxf<W>(&self, w: &mut WxfWriter<W>) -> Result<(), Error>
where W: Writer,

Write self to w as a complete WXF value (tag + payload).
Source§

impl<'e> TryFrom<&'e Expr> for &'e str

Source§

fn try_from(expr: &'e Expr) -> Result<&'e str, &'e Expr>

If this is an ExprKind::String expression, return that.

let expr = expr!("hello");
let s = <&str>::try_from(&expr).unwrap();
assert_eq!(s, "hello");
Source§

type Error = &'e Expr

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

impl<'e> TryFrom<&'e Expr> for &'e Symbol

Source§

fn try_from(expr: &'e Expr) -> Result<&'e Symbol, &'e Expr>

If this is a Symbol expression, return that.

let expr = expr!(System::Pi);
let sym = <&Symbol>::try_from(&expr).unwrap();
assert_eq!(sym.as_str(), "System`Pi");
Source§

type Error = &'e Expr

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

impl<'e> TryFrom<&'e Expr> for &'e Normal

Source§

fn try_from(expr: &'e Expr) -> Result<&'e Normal, &'e Expr>

If this is a Normal expression, return that.

let expr = expr!(System::List[1, 2, 3]);
let normal = <&Normal>::try_from(&expr).unwrap();
assert_eq!(normal.elements().len(), 3);
Source§

type Error = &'e Expr

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

impl WxfStruct for Expr

Auto Trait Implementations§

§

impl Freeze for Expr

§

impl RefUnwindSafe for Expr

§

impl Send for Expr

§

impl Sync for Expr

§

impl Unpin for Expr

§

impl UnsafeUnpin for Expr

§

impl UnwindSafe for Expr

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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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.