I have been stuck on this for a few days. Basically I can sum it up into asking, how do you simulate this function like it were written in assembly (or machine code even, something using only 1 memory array), but doing everything in JavaScript?
function start() {
let x = doX(1, 2)
let y = doX(3, 4)
let z = doX(x, y)
return z
}
function doX(a, b) {
let x = a + b
let y = a - b
let z = x * y
return z
}
So my attempt at it is something along these lines:
const memory = []
function start() {
// capture push (function prologue)?
memory[0] = 1
memory[1] = 2
doX()
memory[2] = memory[100]
memory[0] = 3
memory[1] = 4
doX()
memory[0] = memory[2]
memory[1] = memory[100]
doX()
// capture pop (function epilogue)?
memory[100] = memory[100]
}
function doX() {
// somehow allocate space "on the stack"
// using only this memory object?
// don't know how to do that....
memory[10] = memory[0] + memory[1]
memory[11] = memory[0] - memory[1]
memory[12] = memory[10] * memory[11]
// put it on the return register?
memory[100] = memory[12]
}
How do I properly add the push and pop operations using only this memory array and make this look right? Also, I hardcoded all the memory addresses, how do I properly make them relative?