I’m currently working on an interpreter I created that uses a pseudo c++ syntax. I am looking for the best way of storing variables created by the interpreter.
Currently I am using dynamic arrays that store pointers to those variables, but surely there’s a better way? Maybe some sort of inline assembler code to control a memory block?
I’m not too concerned about portability as I am willing to rewrite those pieces of code for every major OS. I am simply looking for a way to create a memory block without it being locked to a single type. For my current testing I am using the MingW compiler on Windows.
Any ideas will be greately appreciated.
I’d say it very much depends on how your language works what you can do in an interpreter. Provided that this is a true interpreter and you don’t have any precompile step you’d typically have two sorts of allocations – stack and heap allocations. If you support allocating things on the stack, you should implement this as a stack in your interpreter.
Use a
vector<char>as a stack buffer. Keep track of each scope being entered, place a marker on the stack. When you encounter a stack allocated variable, grow the stack to accommodate the new local variable. Use placementnewto initialize the object if that is required.Add it to some sort of dictionary to match the variable name to the memory space so that your code knows where to find the name given the context. Like a symbol table really, only kept at run-time.
Once you encounter a scope end you will pop the stack of all the locally allocated symbols and call destructors if necessary. Also remove all the entries from the symbol table, since they are no longer in scope. This way you’re avoiding the heap allocation entirely for objects that aren’t used on the heap.