# Obtain an expression tree from a math expression

Hi,

I'm trying parse 'arithmetic' with a macro :

``````/// the usize is the ID
struct Variable(usize);
let x = Variable(12);
let y = Variable(3);
// dont want to use parse("x + y = 20") because that relies on populating the variables by // name
// Exemples :
let constraint = parse!(x + y == 20);
let constraint2 = parse!(x + 2 <= 20);
// for later maybe do
// contraint.evaluate(valuesxy)
``````

So I'm trying to use the actual type system to compile the AST and get an Expression Tree, instead on relying on evaluation of a string on runtime. To get the expression tree easily there is a trick or crate or I have to parse the AST by hand ?

1 Like

There are several parser libraries available for Rust. If you are satisfied with your expression trees needing to be syntactically valid Rust, then you are looking for Syn. Otherwise, if you want to parse an arbitrary language, you might be interested in trying out Pest.

You can then write a function-like procedural macro that uses these libraries to parse the passed-in token streams, and transform them into a data structure that e.g. holds references to (or copies of) the referenced variables.

1 Like