Logical Operators Implementation Question

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

Logical Operators Implementation Question

andybendy
Hello, I'm currently building out the logical operators eq, lt, gt, (as well as neg and or, but those are a bit different, so I'll handle them later).

From what I understand, they should update the stack to contain TRUE or FALSE

e.g.

push constant 17
push constant 17
eq

the stack goes from having 17 and 17 and then the pointer on top, to having true and then the pointer on top, which follows the same pattern as add or subtract etc... but I have no clue how to represent TRUE or FALSE in assembly? I read that -1 is equivalent to true, and 0 is equivalent to false.

Am I supposed to store those values in the correct point in the stack? And then I pick which value to store based on some jump sequencing in assembly?
Reply | Threaded
Open this post in threaded view
|

Re: Logical Operators Implementation Question

WBahn
Administrator
Don't make it harder than it is.

Imagine:

push constant 17
push constant 17
add

Let's say that the stack originally looked like the following:


71
86
41 <- SP
35
19

So, before the code runs, the stack pointer is pointing at the memory location containing 41, which is not on the stack. Instead, the top value on the stack is 35 (the memory is drawn with lower addresses at the bottom).

Now you execute the first VM command:

push constant 17

The stack should become:

71
86 <- SP
17
35
19

Now you execute the second VM command:

push constant 17

The stack should become:

71 <- SP
17
17
35
19

Now you execute the third VM command:
Now you execute the first VM command:

add

The stack should become:

71
17 <- SP
34
35
19

Whether the values 17 or 71 remain intact is irrelevant -- they are not on the stack, so we don't care.

The important thing is that the net effect of the add command is to reduce the size of the stack by one and place the result of adding the top two values on the stack with their sum. How your code makes this happen is totally up to you.

So what is the ONLY difference between the 'add' command in the 'eq' command?

It simply the value of the result. If the top two values are equal, then the result is -1. Otherwise, the result is 0. So, instead of making 34 end up on top of the stack for 'add', you make -1 end up there for 'eq'.

push constant 17
push constant 17
eq

Takes

71
86
41 <- SP
35
19

to

71
17 <- SP
-1
35
19

How you make this happen is entirely up to you.