So for the above lines, my compiler returns:
That makes sense to me because you need one "not" for the ~(position > 16) and another one as part of the if-statement algorithm. The code generated from the supplied compiler only has one. Why is that?
The other problem I am having is with the order of if and goto statements. The vm code you get with the Jack Compiler looks something like this:
(Code from compiled statement)
But according to the given algorithm, shouldn't it be something more like:
(code from compiled statements)
Based on how I think the stack works and previous assignments, the code that the Jack compiler puts out makes sense. However, it doesn't look like it's following the algorithm. Can someone offer some help on where I'm getting the logic wrong?
In some_code_1, we need to make sure that the THEN part only will be executed if the COND is evaluated to true. So if COND is true, we can just continue. If it's false we should jump to the ELSE part. The VM only has if-goto, which jumps if the top of the stack is true. That's why we need to NOT it first. The code now looks like this:
The some_code_2 part is reached only after the THEN expression is executed. It needs to make sure that ELSE isn't executed in this case. It's as easy as a unconditional jump:
That is, we switch the places of THEN and ELSE expressions. Why? Well, we can skip one NOT instruction in this case, because we don't need to invert the COND result. I'll leave it to you to finish this, if you want to.
In general, compilation can involve several passes, including various analysis and optimization ones. One easy and common optimization technique is called peep-hole optimization. In it, the compiler identifies sequences of instructions, which can be replaced by other, more effective sequences. For example the sequence:
can be eliminated altogether (or replaced with an empty sequence), because the effect is exactly the same. My guess is, that the official compiler produced 3 NOTs and then removed two of them and so you see just one.
You don't need to do any optimizations in the compiler to finish the course. After that you can dive in this very interesting problem. There are some very interesting results and resources in this forum.