Matching a name and keywords in pest

I'm trying to parse a line like this

MyTupleComponent str, str

with grammar

cname = _{ (ASCII_ALPHANUMERIC | "_")+ }

ints = { "i8" | "i16" | "i32" | "i64" | "i128" | "isize" }
uints = { "u8" | "u16" | "u32" | "u64" | "u128" | "usize" }
strings = { "str" | "String" }
types = { strings | ints | uints }

tuple_component = { cname ~ (types ~ ("," ~ types)?)+ }

But end up with

Err(Error { variant: ParsingError { positives: [types], negatives: [ ] }, location: Pos(20), line_col: Pos((1, 21)), path: None, line: "MyTupleComponent str, str", continued_line: None })

Anyone know why the rule don't matches correctly?

Never used pest but it doesn’t like like you’re accounting for spaces in the grammar. Maybe something like this?

tuple_component = { cname ~ " "+ ~ (types ~ ("," ~ " "+ ~ types)*) }

Also I changed the ? to * and removed the + since I’m guessing that that wasn’t doing what you intended without actually knowing what you’re parsing

It's implicit as I've understood it. With this,

WHITESPACE =  _{ " " | "\t" | "\r" | "\n" }
cname = { (ASCII_ALPHANUMERIC | "_")+ }

ints = _{ "i8" | "i16" | "i32" | "i64" | "i128" | "isize" }
uints = _{ "u8" | "u16" | "u32" | "u64" | "u128" | "usize" }
strings = _{ "str" | "String" }
types = { strings | ints | uints }

single_component = { cname ~ NEWLINE }
tuple_component = { cname ~ types ~ ("," ~ types)* }

components = _{ single_component | tuple_component }

On pest. The Elegant Parser

it complains for some god-forsaken reason about "expecting type" where the comma is

Ah, seeing that now on the site. The issue is your cname definition.

The following matches WHITESPACE automatically between each character similar to how ~ is working for your other definitions, so the entire string up to the , are matching to cname

cname = { (ASCII_ALPHANUMERIC | "_")+ }

You need to change it to the following (Note the @ which causes the definition to skip the automatic WHITESPACE matching)

cname = @{ (ASCII_ALPHANUMERIC | "_")+ }
1 Like

That did the trick, ty!