munificent / craftinginterpreters

Repository for the book "Crafting Interpreters"
http://www.craftinginterpreters.com/
Other
8.75k stars 1.03k forks source link

parsing-expression #857

Open ppdog0 opened 3 years ago

ppdog0 commented 3 years ago

Before I would like express my thanks to you since we have compiler principles this semester. Our compiler project is totally based on your work and we change the code by ourselves so it can scan C-style code. When we finish it , I would like to share it there.
Now I am working on grammar analysis. In the parsing-expression part, the book says:

unary  → ( "!" | "-" ) unary | primary ;

which is different from other grammar. For example, for term we have

term  → factor ( ( "-" | "+" ) factor )* ;

In this grammar, we use '*' to make it iteration-style. However, we can see that Unary is like recursion-style.


So, I would like to write this:

unary  → ( "!" | "-" )* primary ;

to make it recursive, we write

unary  → ( "!" | "-" ) unary | primary ;


that's all, and I would like to share my recursion-style grammar there:

 Expression -> Condition
 Conditition -> Logior ? Logior : Condition | Logior
 Logior -> (Logiand || Logior) | Logiand
 Logiand -> (Or && Logiand) | Or 
 Or -> (Xor | Or) | Xor
 Xor -> (And ^ Xor) | And
 And -> (Equality & And) | Equality
 Equality -> (Comparison [==,!=] Eqality) | Cmparison
 Comparison -> (Term [>,>=,<,<=] Comparison) | Term
 Term -> (Factor [-,+] Term) | Factor
 Factor -> (Unary [/,*,%] Factor) | Unary
 Unary -> ([~,&,*,!,-,+,++,--,sizeof,(Primary)] Unary) | Get
 Get -> (Primary [(),[],->,.] Get) | Primary
 Primary -> NUMBER | TRING | true | false | NULL | "(" Expression ")"
munificent commented 3 years ago

So, I would like to write this:

unary  → ( "!" | "-" )* primary ;

Yes, that works fine too. I used a recursive grammar rule in the book because that mirrors the recursive code we write to parse it, but an iterative grammar rule is also fine (and you can parse it iteratively too if you want).