Variables.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. bool vSearchStruct(Variable* v, Structs* sts, Struct* st, const char* s) {
  27. for(int i = 0; i < st->amount; i++) {
  28. if(strcmp(st->vars[i].name, s) == 0) {
  29. v->name = s;
  30. v->type = st->vars[i].type;
  31. return false;
  32. }
  33. v->address += dtGetSize(st->vars[i].type, sts);
  34. }
  35. return true;
  36. }
  37. Variable* vAdd(Variables* v, const char* s, DataType type, Structs* sts) {
  38. if(v->entries >= v->capacity) {
  39. v->capacity *= 2;
  40. v->data = realloc(v->data, sizeof(Variable) * v->capacity);
  41. }
  42. int index = v->entries++;
  43. v->data[index] = (Variable){s, type, v->address};
  44. v->address += dtGetSize(type, sts);
  45. if(v->address > v->maxAddress) {
  46. v->maxAddress = v->address;
  47. }
  48. return v->data + index;
  49. }
  50. void vReset(Variables* v) {
  51. v->entries = 0;
  52. v->address = 0;
  53. v->scope = 0;
  54. v->maxAddress = 0;
  55. }
  56. void vEnterScope(Variables* v, Scope* s) {
  57. s->address = v->address;
  58. s->entries = v->entries;
  59. s->scope = v->scope;
  60. v->scope = v->entries;
  61. }
  62. void vLeaveScope(Variables* v, Scope* s) {
  63. v->address = s->address;
  64. v->entries = s->entries;
  65. v->scope = s->scope;
  66. }