83 lines
2.0 KiB
C
Executable File
83 lines
2.0 KiB
C
Executable File
//
|
|
// Created by Nils on 29.10.2023.
|
|
//
|
|
#ifndef STACK
|
|
#define STACK
|
|
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include "stackslot.c"
|
|
|
|
|
|
|
|
|
|
struct stack {
|
|
int* size;
|
|
int* current;
|
|
StackSlot *stack;
|
|
};
|
|
|
|
typedef struct {
|
|
unsigned int size;
|
|
ObjRef *refs;
|
|
}ObjRefContainer;
|
|
|
|
void printStack(struct stack stack, int fp) {
|
|
printf("Stack\nSize:\t\t%i\nCurrent:\t%i\n", *stack.size, *stack.current);
|
|
for (int i = *stack.current -1; i >= 0; --i) {
|
|
printf("%i\t",i);
|
|
if(stack.stack[i].isObjRef){
|
|
printf("|%p|", (void *)stack.stack[i].u.objRef);
|
|
if(stack.stack[i].u.objRef->size == sizeof(int))
|
|
printf("(%i)",*(int *)stack.stack[i].u.objRef->data);
|
|
}else {
|
|
printf("|%i|", getIntValfromStackSlot(stack.stack[i]));
|
|
}
|
|
if(fp == i) printf("<-\tFP\n");
|
|
else if(*stack.current == i) printf("<-\tSP\n");
|
|
else printf("\n");
|
|
}
|
|
}
|
|
|
|
ObjRefContainer getRefs(struct stack stack){
|
|
ObjRefContainer continer;
|
|
int counter = 0;
|
|
for (int i = 0; i <= *stack.current; i++) {
|
|
if(stack.stack[i].isObjRef == true) counter++;
|
|
}
|
|
continer.size = counter;
|
|
ObjRef *list = (ObjRef *)malloc(counter * sizeof(ObjRef));
|
|
for (int i = 0; i<= *stack.current; i++)
|
|
if(stack.stack[i].isObjRef == true)
|
|
list[counter--] = stack.stack[i].u.objRef;
|
|
continer.refs = list;
|
|
return continer;
|
|
}
|
|
|
|
void push(struct stack s, StackSlot value) {
|
|
if (*s.current >= *s.size) {
|
|
printf("Stack Overflow\n");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
s.stack[*s.current] = value;
|
|
*s.current=*s.current + 1;
|
|
}
|
|
|
|
StackSlot pop(struct stack s) {
|
|
if (*s.current == 0) {
|
|
printf("Stack Underflow\n");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
*s.current = *s.current -1;
|
|
return s.stack[*s.current];
|
|
}
|
|
|
|
int peek(struct stack s, int steps) {
|
|
if (*s.current - steps < 0) {
|
|
printf("Stack Underflow\n");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
return getIntValfromStackSlot(s.stack[*s.current - steps]);
|
|
}
|
|
#endif
|