njvm/stackslot.c

58 lines
1.2 KiB
C

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#ifndef STACKSLOT
#define STACKSLOT
typedef int Object;
typedef struct {
unsigned int size;
unsigned char data[1];
} *ObjRef;
typedef struct{
bool isObjRef;
union {
ObjRef objRef;
int number;
} u;
} StackSlot;
ObjRef getIntObj(int val){
ObjRef intObject;
unsigned int objSize = sizeof(unsigned int) + sizeof(int);
if ((intObject = malloc(objSize)) == NULL) {
perror("malloc");
}
*(int *)intObject->data=val;
intObject->size=sizeof(int);
return intObject;
}
int getValFromIntObj(ObjRef iref){
return *(int *)iref->data;
}
int getIntValfromStackSlot(StackSlot s){
if(s.isObjRef){
return *(int *)s.u.objRef->data;
}
return s.u.number;
}
void setValIntObj(ObjRef iref, int val){
iref->size=sizeof(int);
*(int *)iref->data=val;
}
StackSlot stackSlotWithObjRef(ObjRef val){
StackSlot *stackSlot;
stackSlot=malloc(sizeof(StackSlot));
stackSlot->isObjRef=true;
stackSlot->u.objRef=val;
return *stackSlot;
}
StackSlot stackSlotWitchNumber(int val){
StackSlot *stackSlot;
stackSlot= malloc(sizeof(StackSlot));
stackSlot->isObjRef=false;
stackSlot->u.number=val;
return *stackSlot;
}
#endif