I need a hint on how to begin with the parser Booleans & Nil #sc2 (rust)

I’m a bit stuck on defining the parsing rules into code.

expression     → equality ;
equality       → comparison ( ( "!=" | "==" ) comparison )* ;
comparison     → term ( ( ">" | ">=" | "<" | "<=" ) term )* ;
term           → factor ( ( "-" | "+" ) factor )* ;
factor         → unary ( ( "/" | "*" ) unary )* ;
unary          → ( "!" | "-" ) unary
               | primary ;
primary        → NUMBER | STRING | "true" | "false" | "nil"
               | "(" expression ")" ;

Would you create a struct for each of these? Something like this

struct equality {
    left: comparison
}

Or am I on the wrong track?

I had created a single enum called Expr to represent the result of all these branches, and kept its variants on the basis of the number of operators and operands they take.

Something like this:

#[derive(Debug)]
pub enum Expr {
    Unary(Token, Box<Expr>),
    Binary(Box<Expr>, Token, Box<Expr>),
    Grouping(Box<Expr>),
    Literal(Token),
}

Here, the Token is the operator that is associated with both the operands (which themselves are Expr). Not sure if it’s the most idiomatic way to do the same, but worked well for me.

2 Likes

Thanks for your suggestion.
When I think at enums I only think of them as

class Expr(enum.Enum):
    Unary = "Unary"

I will read a little bit more about them in rust.

1 Like

Can’t blame you for that. Coming from other languages like Typescript and even CPP, enums have a reputation of being glorified constants. But in Rust, they are one of the most powerful concepts because of ability of store different shapes of data and pattern matching expressiveness!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.