This problem is easier to see if you have some experiences with formal
languages (or if you ever constructed a compiler).

http://en.wikipedia.org/wiki/Bottom-up_parsing
http://en.wikipedia.org/wiki/Recursive_descent_parser
http://en.wikipedia.org/wiki/Operator-precedence_parser

The "proper" way to do it is to define a grammar and see the parse
tree and trace the tree.

This grammar can correctly "show" us the parse tree assumed we want to
do left-to-right for operations that have the same precedence:

<Expression> --> <Term> | <Term> +- <Expression>
<Term>       --> <Factor> | <Factor> */ <Term>
<Factor>     --> ( <Expression> ) | 0...9

The RHS expression
result := 6 / 2 * ( 1 + 2);

Is translated to:
                mov  R0, 6
                mov  R1, 2
                div R0, R1 # R0 = 6 / 2 = 3
                mov  R1, 1
                mov  R2, 2
                add R1, R2 # R1 = 1 + 2 = 3
                mul R0, R1 # R0 = 3 * 3 = 9
                mov result, R0 # result = 9

I have constructed such a compiler, so it's not pulled out of thin air
-- of course it's dumb but it works for the purpose :-)

https://docs.google.com/leaf?id=0B3fpJhdLheigYWYxZTk3ZTYtZTU5MS00NDY0LWE1NWItM2I3ZGNiZWY1NzJl&hl=en&authkey=CKDcipgK


-- 
I just want you to take it easy, man...
_______________________________________________
POST RULES : http://wiki.hanoilug.org/hanoilug:mailing_list_guidelines
_______________________________________________
HanoiLUG mailing lists: http://lists.hanoilug.org/
HanoiLUG wiki: http://wiki.hanoilug.org/
HanoiLUG blog: http://blog.hanoilug.org/

Trả lời cho