0

Recently for fun I have decided to build a toy programming, compiler and vm. While starting to implement the virtual machine I got stuck. The stack which holds the variables and structs I implemented as separate arrays for each type. The problem is when I have a reference to a struct the elements are not aligned, int struct.x might be at address 2, and float struct.y might be at address 56, so accessing the struct by a reference would be impossible, because the indexes are not linear. How could I solve this?

edit:
first of all for each type I mean for each primitive, and second I know I could implement it with unions but I want to learn how it is really implemented in java, c++ or c#, that's kind of the point of making a toy language, to better understand what you are programming.

Coder3000
  • 130
  • 7
  • When you say a separate array for each type, do you mean each primitive type? That won't work for the reason you describe; you must store each class type contiguously. Why not a single array / stack? Or even add one for all non-primitive types. (Or perhaps have one array for each required alignment.) – Alan Stokes Nov 29 '15 at 18:11
  • Declare the stack as an array of *unions*. So each slot in the stack can store any kind of variable. Wasteful of memory but it is only a toy and you have plenty. – Hans Passant Nov 29 '15 at 18:31
  • Alan Stokes, I can't declare an array with different types that I can still manipulate, at least of what I am aware of in c++. – Coder3000 Nov 29 '15 at 20:48

1 Answers1

1

in this case, you have no real choice but to use a single data type like a uin32_t/uint64_t and simply have the compiler break values down into integer

int sp = 0;
uint32_t stack[MAX_STACK_SIZE];

OR

like the others have said, create a stack that is an array of unions, possibly using a tagged union. One implementation could be...

union values {
    int i;
    float f;
};
struct Type {
    int tag;
    union values val;
};
Type stack[MAX_STACK_SIZE];

It's up to you to decide on this but this is usually how it's done.

Nergal
  • 349
  • 3
  • 14