My VMTranslator has bug that couldn't be caught by StackTest (gt, lt)

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

My VMTranslator has bug that couldn't be caught by StackTest (gt, lt)

bupjae
VM code:

push constant 32767
push constant 32766
neg
gt

Pseudocode: if (32767 > -32766) then push -1 else push 0

Expected result: TOS is -1
Actual result of my VMTranslator: TOS is 0

My VMTranslator implementation with this flaw has passed Coursera grader system.

I thought check result of A-B is enough to comparing A and B.
However, 32767 - (-32766) provokes overflow and I got wrong result.
I believe that many VMTranslator implementations, including which is used to create Pong.asm for Project 6, might have similar issue.
Reply | Threaded
Open this post in threaded view
|

Re: My VMTranslator has bug that couldn't be caught by StackTest (gt, lt)

dolomiti7
You are right, the nand2tetris course ignores the potential signed overflow in comparisons. The topic has been discussed in a couple of posts in the past. In a nutshell, it seems that this was considered to be beyond the scope of the course.

However, depending on the actual program, it might be required to handle this correctly in the VM translator to ensure a correct execution. For Pong it is not relevant, the range of values will not trigger any overflows.

For some other programs published here, it is required, i.e. Chess, and the various raycasters. In my own translator I added a flag to switch on/off the overflow detection for comparisons. Additionally the translator will handle comparisons with 0 with a special translation (cannot overflow and also can be optimized).

The issue arises when the subtraction of two values to be compared will overflow. In this case 16400 can falsely be lower than -16400...

The VM Emulator is based on Java comparisons and works correctly.
Reply | Threaded
Open this post in threaded view
|

Re: My VMTranslator has bug that couldn't be caught by StackTest (gt, lt)

bupjae
This answer seems that "We'll put this issue aside. You can tackle it for Project 13."

Thanks for answer.


Related post I just found: Greater or less than when comparing numbers with different signs?