Variables.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include "utils/Variables.h"
  4. void vsInit(Variables* v) {
  5. v->capacity = 16;
  6. vsReset(v);
  7. v->data = malloc(sizeof(Variable) * v->capacity);
  8. }
  9. void vsDelete(Variables* v) {
  10. free(v->data);
  11. }
  12. bool vsSearch(const Variables* vs, Variable* v, const char* s) {
  13. for(int i = vs->entries - 1; i >= 0; i--) {
  14. if(strcmp(s, vs->data[i].name) == 0) {
  15. *v = vs->data[i];
  16. return false;
  17. }
  18. }
  19. return true;
  20. }
  21. bool vsInScope(const Variables* vs, const char* s) {
  22. for(int i = vs->entries - 1; i >= vs->scope; i--) {
  23. if(strcmp(s, vs->data[i].name) == 0) {
  24. return true;
  25. }
  26. }
  27. return false;
  28. }
  29. bool vSearchStruct(Variable* v, Structs* sts, Struct* st, const char* s) {
  30. v->address = 0;
  31. for(int i = 0; i < st->amount; i++) {
  32. if(strcmp(st->vars[i].name, s) == 0) {
  33. v->name = s;
  34. v->type = st->vars[i].type;
  35. return false;
  36. }
  37. v->address += dtGetSize(st->vars[i].type, sts);
  38. }
  39. return true;
  40. }
  41. Variable* vsAdd(Variables* v, const char* s, DataType type, Structs* sts) {
  42. if(v->entries >= v->capacity) {
  43. v->capacity *= 2;
  44. v->data = realloc(v->data, sizeof(Variable) * v->capacity);
  45. }
  46. int index = v->entries++;
  47. v->data[index] = (Variable){s, type, v->address};
  48. v->address += dtGetSize(type, sts);
  49. if(v->address > v->maxAddress) {
  50. v->maxAddress = v->address;
  51. }
  52. return v->data + index;
  53. }
  54. void vsReset(Variables* v) {
  55. v->entries = 0;
  56. v->address = 0;
  57. v->scope = 0;
  58. v->maxAddress = 0;
  59. }
  60. void vsEnterScope(Variables* v, Scope* s) {
  61. s->address = v->address;
  62. s->entries = v->entries;
  63. s->scope = v->scope;
  64. v->scope = v->entries;
  65. }
  66. void vsLeaveScope(Variables* v, Scope* s) {
  67. v->address = s->address;
  68. v->entries = s->entries;
  69. v->scope = s->scope;
  70. }