3 ms·
Assuming you are talking about using a grammar to parser tool like yacc, you probably should at some point figure out what your hangup is there, but shouldn't l
by aidenn0 7y ago
Assuming you are talking about using a grammar to parser tool like yacc, you probably should at some point figure out what your hangup is there, but shouldn't let that stop you from writing a compiler. I very rarely use such a tool for writing a compiler, and find that real-world compilers similarly rarely use a tool.
Regardless of whether you are writing a grammar or a recursive descent parser, start with a really simple language say:
Expr = "A" | "(" Expr* ")"
Which is balanced parentheses with the token that is the exact character "A" possibly appearing. All of these are valid matches:
(())
((A(A)A)A)
(((((AAA)))))
The parse tree should be such that each node is a list where each element is either an A token or another parse tree node. Once you can parse that, then you can start moving on to more complicated grammars; a possible complication is to add "B" as a valid expression, with the caveat that B cannot be the sibling of a parenthesized expression. That is:
(ABA)
is valid, but
(B(A))
is not valid.
I used single characters as the primitive here, so perhaps the next step would be to add a tokenizer. "B" has special rules, so it will be the keyword "bananas". A will be any other alphabetic token.
If all of the above is already doable, then perhaps I've misunderstood where your hangup is. Let me know, perhaps I can help.
- panda_4 7y agoShould that grammar be: Expr = "A" | "(" Expr* ")" | "" so that (()) is s a valid match? Because then Expr can be an empty string also?
- Technetium_Hat 7y ago`Expr*` means zero or more, so the empty string is implicit.
- aidenn0 7y agoTypically Star (*) means zero or more while Plus (+) means one or more.