Skip to content

"(1 + 2)" and grammar #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
banditpig opened this issue Jan 29, 2022 · 2 comments
Closed

"(1 + 2)" and grammar #14

banditpig opened this issue Jan 29, 2022 · 2 comments
Labels
discussion and feedbacks question Further information is requested

Comments

@banditpig
Copy link

Hi, Thanks for the interesting tutorial! I'm just learning about PEG etc and wondered how to modify the grammar so that
//assert_eq!(Interpreter::source("(1 + 2)").unwrap() as i32, 3);
will work?

Thanks
Mike

@banditpig banditpig added discussion and feedbacks question Further information is requested labels Jan 29, 2022
@PrestonHager
Copy link
Contributor

Pest gives a great interactive parser at the bottom of their page. Check it out. The problem with giving the first term wrapped in parentheses is that the grammar tries to parse it as a full Binary Expression first. While this is true, it checks for least recursive first. To fix this, I changed the binary expression to include at least one operator and term. Then an expression can also be a term too (what was originally a binary term with no suffixed operator and term). The following is a fixed version of the grammar code. I also changed an Int to be defined as either negative or non-negative (getting rid of the possibility of having a preceding plus sign).

Program = _{ SOI ~ Expr ~ EOF }

Expr = { UnaryExpr | BinaryExpr | Term }

Term = _{Int | "(" ~ Expr ~ ")" }

UnaryExpr = { Operator ~ Term }

BinaryExpr = { Term ~ (Operator ~ Term)+ }

Operator = { "+" | "-" }

Int = @{ "-"? ~ ASCII_DIGIT+ }

WHITESPACE = _{ " " | "\t" }

EOF = _{ EOI | ";" }

Also check out pull request #16.

@ehsanmok
Copy link
Owner

Thanks for the fix @PrestonHager

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
discussion and feedbacks question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants