craftinginterpreters icon indicating copy to clipboard operation
craftinginterpreters copied to clipboard

parsing-expression

Open ppdog0 opened this issue 4 years ago • 1 comments

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 ")"

ppdog0 avatar Nov 22 '20 10:11 ppdog0

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).

munificent avatar Nov 26 '20 05:11 munificent