Exploring the concept of simulating the call stack using parameters and local variables in JavaScript by utilizing a single global memory array

I've been grappling with this challenge for a few days now. Essentially, what I'm trying to figure out is how to replicate this function as if it were coded in assembly language (or even machine code, using just one memory array), but executing everything within 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
}

My attempt at solving it follows something like this:

const memory = []

function start() {
  // emulate push operation (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()
  // emulate pop operation (function epilogue)?
  memory[100] = memory[100]
}

function doX() {
  // find a way to reserve space "on the stack"
  // by only using this memory object?
  // Unsure of how to accomplish that....
  memory[10] = memory[0] + memory[1]
  memory[11] = memory[0] - memory[1]
  memory[12] = memory[10] * memory[11]
  // store result in return register?
  memory[100] = memory[12]
}

How can I correctly implement the push and pop operations utilizing solely this memory array while ensuring it looks accurate? Also, I've hardwired all the memory addresses, so how can I make them relative appropriately?

Answer №1

One must have a stack pointer, whether as a distinct global entity (similar to a CPU with separate registers and memory) or by designating a specific memory location for this purpose. As demonstrated in response to your previous inquiry by @bergi, operations such as memory[tos++] are necessary to push elements onto the stack instead of assuming that the initial value of the stack pointer is always 0 with direct assignments to memory[0].

(In various ISAs, including x86, the stack pointer typically begins at the highest address within a designated region, decrementing with each item pushed onto the stack. This results in a downward growth pattern).

The current use of memory[100] as a return-value register diverges from JavaScript's norm of returning values through its standard mechanism. Consider utilizing memory[99] as a stack pointer, enabling constructs like mem[--mem[99]] = val_to_push. For enhanced clarity, introducing a dedicated variable labeled sp, or even state.sp if incorporating it within a state object featuring both memory and scalar registers including a sp stack pointer, may be advantageous.


Conventional calling conventions prefer returns via registers opposed to memory; employing a retval register "within memory" can complicate matters unnecessarily. By allowing JS functions to adhere to the conventional method of returning values using JavaScript's built-in system and regarding it as a virtual register, similarities to CPU operations remain intact, particularly when dealing solely with basic numeric data.

Given the flexibility to delineate machine specifics, local JS variables could serve as temporary scratch registers, affording functions an unlimited number if needed.

Programs designed for this theoretical setup bear similarity to LLVM-IR, permitting usage of numerous "registers" without specifying where they reside physically. However, unlike traditional compilation processes, any surplus registers don't spill over to the stack but remain available for use as required.

To maintain the semblance of registers and prevent drifting towards pure JS implementation sans utilization of memory[], enforcing argument passing via memory (applying a stack-args calling convention) alongside treating each function call as erasing all local variable contents might prove beneficial.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show a JavaScript alert message like a toast

I know this question has probably been asked before, but I haven't found any solutions that work for my unique situation... (Just to clarify, I am a beginner when it comes to java/android programming) So here's the deal - I'm attempting to ...

The Angular Table row mysteriously vanishes once it has been edited

Utilizing ng-repeat within a table to dynamically generate content brings about the option to interact with and manage the table contents such as edit and delete. A challenge arises when editing and saving a row causes it to disappear. Attempts were made ...

Is it possible to retrieve several columns using the pluck method in Underscore.js following the input from the where method, similar to LINQ

var persons = [ {name : "Alice", location : "paris", amount : 5}, {name : "Bob", location : "tokyo", amount : 3}, {name : "Eve", location : "london", amount : 10} ]; var filteredResults=_.pluck(_.where(persons, {location : "paris"}), 'nam ...

Is there a way to prevent the variable from being trapped in the first option when using an if/else if statement?

Below is my JavaScript code snippet: let x = Math.floor(Math.random() * 6) + 1); if (x == 1){ do this } else if (x == 2){ do that } else if.... and so on. Every time I run this code in a browser, only actions related to the {do this} section seem ...

Send information using jQuery AJAX

Currently, I am attempting to use AJAX to submit data to my table. Below is the form I have created for this purpose: <form> Total <input type="text" id="total" name="total" /><br /> Bill name<input type="text" id="bill-name" ...

Recursive Functions and the Power of Stacking

Just hoping this isn't a duplicate inquiry, as I've searched extensively but couldn't find the solution. I'm currently experimenting with recursive functions (I'm relatively new to this), attempting to multiply each number in an a ...

Is there a way to retrieve a JSON list containing objects in Dart programming language?

I received a list from the server and I'm having trouble creating an object model for it. Can you provide assistance? [ { "id": 1, "reason": "Could Not Reach Buyer Due to Address Issue" ...

What is the reason behind my Canvas loading only after I save the new code?

I'm currently facing an issue with loading an image into my canvas. The strange thing is, when I load the page, the image doesn't appear, even though the image src is logging correctly in the console. However, if I save my code and trigger a refr ...

Feeling lost when it comes to tackling the Data Access Object/Layer in an Express/MongoDB setup?

I currently have an Express application that is integrated with MongoDB. My goal is to decouple my database access from the server layer. However, in trying to achieve this, I've encountered two main approaches: Passing Res as an argument //server.j ...

Aligning event with angular (similar to the 'join()' function in threads)

I am searching for a straightforward equivalent to join() for threads in Angular. In my Controller: vehiclesService.getVehicles().then(function(sth){ $scope.vehicles = sth.data; $scope.isend();//this call is not ideal }); vehiclesService.getFitme ...

Enable users to choose multiple rows at once or alternatively choose by checking the checkboxes

When using Tabulator with the setting table.selectable = true, any cell click selects the row. However, I specifically want rows to be selected only via checkboxes, so I set selectable = false. The issue now is that the checkboxes behave like a radio butt ...

Style of active link fades after reloading the page

In my MVC application, I am facing an issue with the left menu. I want the active link's CSS to remain styled even after a page reload. Within my CSS file, I have defined the following styles: .navleft li a:hover { background: url('../Conte ...

Encountering a JavaScript glitch with Bootstrap 3 jQuery offset

I am facing an issue with a function that throws an error in the console of my browser when the page is loading: function getRight() { return ($(window).width() - ($('[data-toggle="popover"]').offset().left + $('[data-toggle="popover"]& ...

Adjusting the line-height in CSS dynamically based on the length of characters using jQuery

I am facing an issue with the Twitter widget on my website where our company's latest tweet sometimes gets cut off if it exceeds a certain length. I want to dynamically adjust the line-height CSS property of the element based on the tweet's chara ...

What are the best techniques for maintaining state in Xstate state machines within a React application?

I'm currently using a functioning cart state machine in reactjs to add items to the cart. However, I've noticed that when refreshing the page, the context is not persisted. As someone new to state machines, I would appreciate any assistance in fi ...

Choosing items while using the Orthographic camera in Three Js

Currently, I am working on an isometric level and facing issues while trying to select objects within the level. I have tried various solutions from Stackoverflow, such as this one Orthographic camera and selecting objects with raycast. However, none of t ...

A PHP array containing various values assigned to specific indexes

I am looking to create an array or function in PHP that works as follows: - For indexes between 1-20, the output should be "type 1" - For indexes between 20-25, the output should be "type 2" - For indexes between 25-35, the output should be "type 1" ...

Fade the background image to 50% opacity as you scroll down

Currently, I am utilizing the Backstretch jQuery plugin and aiming to darken the background while scrolling down. This is my progress so far: Setting the body background color to dark Adjusting the opacity of the background image to 0.4 when scrolling dow ...

What are some ways to change the sorting dynamically?

I am currently working with a jqgrid and have a SortNo field that handles sorting. I am looking for a way to dynamically adjust the sorting when adding the same number in SortNo, automatically adjusting the numbers by sequence. You can refer to my sample a ...

Utilize a form with a table layout to send all data to an IEnumerable Controller method

I'm experiencing an issue with a form containing data presented in a table structure @model IEnumerable<myType> @Html.AntiForgeryToken() @using (Ajax.BeginForm("Save", "NOC", null, ajaxopts, new { @encType = "multipart/form-data", @id = "myform ...