At this point I'm going to violate my rule that we don't introduce any complexity until it's absolutely necessary, long enough to point out a problem with the code we're generating. As things stand now, the parser uses D0 for the “primary” register, and D1 as a place to store the partial sum. That works fine for now, because as long as we deal with only the “addops” + and -, any new term can be added in as soon as it is found. But in general that isn't true. Consider, for example, the expression
If we put the '1' in D1, where do we put the '2'? Since a general expression can have any degree of complexity, we're going to run out of registers fast!
Fortunately, there's a simple solution. Like every modern microprocessor, the 68000 has a stack, which is the perfect place to save a variable number of items. So instead of moving the term in D0 to D1, let's just push it onto the stack. For the benefit of those unfamiliar with 68000 assembler language, a push is written -(SP) and a pop, (SP)+.
So let's change the EmitLn in Expression to read:
and the two lines in Add and Subtract to
respectively. Now try the parser again and make sure we haven't broken it.
Once again, the generated code is less efficient than before, but it's a necessary step, as you'll see.