Variables.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include "utils/Variables.h"
  4. void vInit(Variables* v) {
  5. v->capacity = 16;
  6. vReset(v);
  7. v->data = malloc(sizeof(Variable) * v->capacity);
  8. }
  9. void vDelete(Variables* v) {
  10. free(v->data);
  11. }
  12. static Variable* vSearchUntil(Variables* v, const char* s, int index) {
  13. for(int i = v->entries - 1; i >= index; i--) {
  14. if(strcmp(s, v->data[i].name) == 0) {
  15. return v->data + i;
  16. }
  17. }
  18. return NULL;
  19. }
  20. Variable* vSearch(Variables* v, const char* s) {
  21. return vSearchUntil(v, s, 0);
  22. }
  23. Variable* vSearchScope(Variables* v, const char* s) {
  24. return vSearchUntil(v, s, v->scope);
  25. }
  26. Variable* vAdd(Variables* v, const char* s, DataType type) {
  27. if(v->entries >= v->capacity) {
  28. v->capacity *= 2;
  29. v->data = realloc(v->data, sizeof(Variable) * v->capacity);
  30. }
  31. int index = v->entries++;
  32. v->data[index] = (Variable){s, type, v->address};
  33. v->address += dtGetSize(type);
  34. if(v->address > v->maxAddress) {
  35. v->maxAddress = v->address;
  36. }
  37. return v->data + index;
  38. }
  39. void vReset(Variables* v) {
  40. v->entries = 0;
  41. v->address = 0;
  42. v->scope = 0;
  43. v->maxAddress = 0;
  44. }
  45. void vEnterScope(Variables* v, Scope* s) {
  46. s->address = v->address;
  47. s->entries = v->entries;
  48. s->scope = v->scope;
  49. v->scope = v->entries;
  50. }
  51. void vLeaveScope(Variables* v, Scope* s) {
  52. v->address = s->address;
  53. v->entries = s->entries;
  54. v->scope = s->scope;
  55. }