Variables.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. for(int i = 0; i < v->entries; i++) {
  11. free(v->data[i].name);
  12. }
  13. free(v->data);
  14. }
  15. static Variable* vSearchUntil(Variables* v, const char* s, int index) {
  16. for(int i = v->entries - 1; i >= index; i--) {
  17. if(strcmp(s, v->data[i].name) == 0) {
  18. return v->data + i;
  19. }
  20. }
  21. return NULL;
  22. }
  23. Variable* vSearch(Variables* v, const char* s) {
  24. return vSearchUntil(v, s, 0);
  25. }
  26. Variable* vSearchScope(Variables* v, const char* s) {
  27. return vSearchUntil(v, s, v->scope);
  28. }
  29. Variable* vAdd(Variables* v, const char* s, DataType type) {
  30. if(v->entries >= v->capacity) {
  31. v->capacity *= 2;
  32. v->data = realloc(v->data, sizeof(Variable) * v->capacity);
  33. }
  34. int index = v->entries++;
  35. v->data[index] = (Variable){strdup(s), type, v->address};
  36. v->address += dtGetSize(type);
  37. if(v->address > v->maxAddress) {
  38. v->maxAddress = v->address;
  39. }
  40. return v->data + index;
  41. }
  42. void vReset(Variables* v) {
  43. v->entries = 0;
  44. v->address = 0;
  45. v->scope = 0;
  46. v->maxAddress = 0;
  47. }
  48. void vEnterScope(Variables* v, Scope* s) {
  49. s->address = v->address;
  50. s->entries = v->entries;
  51. s->scope = v->scope;
  52. v->scope = v->entries;
  53. }
  54. void vLeaveScope(Variables* v, Scope* s) {
  55. v->address = s->address;
  56. v->entries = s->entries;
  57. v->scope = s->scope;
  58. }