Skip to content

token enum rule #34

@davemackintosh

Description

@davemackintosh

So I've got a grammar, say something like this:

pointer_semantics = { "*" | "&" }
variable_access = { pointer_semantics* ~ IDENT }

I would like to be able to create an enum using pest_ast like this, but I've tried a few different ways and I can't seem to get it to work, I.E it won't select the case based on the token/rule applied.

#[derive(Debug, FromPest, PartialEq, Eq)]
pub enum PointerSemantics {
    Pointer,
    Reference,
}

I've also tried (with the literals replaced by lexer tokens)

#[derive(Debug, FromPest, PartialEq, Eq)]
pub enum PointerSemantics {
    #[pest_ast(rule(Rule::POINTER))]
    Pointer,
    #[pest_ast(rule(Rule::REFERENCE))]
    Reference,
}

fails my tests with

thread 'ast::variable_access::tests::variable_access_with_pointer_semantics' panicked at crates/parser/src/ast/variable_access.rs:88:77:
called `Result::unwrap()` on an `Err` value: Extraneous { current_node: "Reference" }

And I've also implemented my own FromPest method

impl<'pest> FromPest<'pest> for PointerSemantics {
    type Rule = crate::Rule;
    type FatalError = Void;

    fn from_pest(
        pest: &mut Pairs<'pest, Self::Rule>,
    ) -> Result<Self, ConversionError<Self::FatalError>> {
        let symbol = pest.next().unwrap();

        match symbol.as_str() {
            "*" => Ok(PointerSemantics::Pointer),
            "&" => Ok(PointerSemantics::Reference),
            _ => Err(ConversionError::NoMatch),
        }
    }
}

But I get a NoMatch error when I try to use it in conjunction with my variable_access rule when there are no explicit pointer semantics, which makes sense if it's trying to parse an IDENT as a pointer_semantics but it is a zero-or-more rule so I'm a little stumped.

How can I do this?

I've reduced my example to a failing case but here are my full implementations for reference.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions