开发者

How would I implement parsing using operator precedence?

I want to implement parsing using operator precedence. I have implemented +, -, *, and /. How would开发者_Go百科 I implement rest with out using any grammar? This is a college project and yacc or bison are not allowed.


What you need is a recursive descent parser (because that's the only parser that can easily be written by hand). See Wikipedia for details, it's pretty easy.

So, to get operator precedence right you can do something like this:

term = number
unary = ('-' | '+')* term
multiplication = unary ('*' | '/' unary)*
addition = multiplication ('+' | '-' multiplication)*
expression = addition

Where 'expression' is your starting rule.


Since you're not allowed to use a parser generator, I would recommend reading about the Recursive descent parser . A very good introduction is included in the Dragon Book


If you need a quick fix:

http://www.codecodex.com/wiki/index.php?title=Recursive_descent_parsing

more extensive reading:

Basic Compiler Design

GLHF!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜