Mathematical Expression Parser Via Recursive Descent in C

preview_player
Показать описание
This is a recursive descent parser written in the C programming language. Just as a precaution, this is a terrible method of evaluating expressions. I wrote this as a demonstration for how you can convert any given grammar into a tree format, be it AST or expression tree.

Here is the BNF grammar for the recursive descent parser:

expr ::= term ( + | - ) expr | term
term ::= power ( * | / ) term | power
power ::= unary ^ power | unary
unary ::= - unary | factor
factor ::= ( expr ) | integer
integer ::= digit integer | digit
digit ::= [0-9]

If you want to play around with it, I put it on a GitHub gist:

Be a good person and evaluate expressions via precedence climbing, not recursive descent. If we were to parse a programming language syntax then a more optimized and streamlined recursive descent parser would be applicable.

Рекомендации по теме