We can wrap up this part of the parser with the addition of parentheses with math expressions. As you know, parentheses are a mechanism to force a desired operator precedence. So, for example, in the expression
2*(3+4)
the parentheses force the addition before the multiply. Much more importantly, though, parentheses give us a mechanism for defining expressions of any degree of complexity, as in
(1+2)/((3+4)+(5-6))
The key to incorporating parentheses into our parser is to realize that no matter how complicated an expression enclosed by parentheses may be, to the rest of the world it looks like a simple factor. That is, one of the forms for a factor is:
<factor> ::= (<expression>) |
This is where the recursion comes in. An expression can contain a factor which contains another expression which contains a factor, etc., ad infinitum.
Complicated or not, we can take care of this by adding just a few lines of Pascal to procedure Factor:
{ Parse and Translate a Math Factor }
procedure Expression; Forward;
procedure Factor;
begin
if Look = '(' then begin
Match('(');
Expression;
Match(')');
end
else
EmitLn('MOVE #' + GetNum + ',D0');
end; |
Note again how easily we can extend the parser, and how well the Pascal code matches the BNF syntax.
As usual, compile the new version and make sure that it correctly parses legal sentences, and flags illegal ones with an error message.