Variables.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 = (Variable*)malloc(sizeof(Variable) * (size_t)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 =
  45. (Variable*)realloc(v->data, sizeof(Variable) * (size_t)v->capacity);
  46. }
  47. int index = v->entries++;
  48. v->data[index] = (Variable){s, type, v->address};
  49. v->address += dtGetSize(type, sts);
  50. if(v->address > v->maxAddress) {
  51. v->maxAddress = v->address;
  52. }
  53. return v->data + index;
  54. }
  55. void vsReset(Variables* v) {
  56. v->entries = 0;
  57. v->address = 0;
  58. v->scope = 0;
  59. v->maxAddress = 0;
  60. }
  61. void vsEnterScope(Variables* v, Scope* s) {
  62. s->address = v->address;
  63. s->entries = v->entries;
  64. s->scope = v->scope;
  65. v->scope = v->entries;
  66. }
  67. void vsLeaveScope(Variables* v, Scope* s) {
  68. v->address = s->address;
  69. v->entries = s->entries;
  70. v->scope = s->scope;
  71. }