Variables.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. VariableError vSearchStruct(Variable* v, const Structs* sts, const Struct* st,
  30. const char* s) {
  31. v->address = 0;
  32. for(int i = 0; i < st->amount; i++) {
  33. if(strcmp(st->vars[i].name, s) == 0) {
  34. v->name = s;
  35. v->type = st->vars[i].type;
  36. return VE_OK;
  37. }
  38. int add;
  39. if(dtGetSize(st->vars[i].type, sts, &add)) {
  40. return VE_SIZE_ERROR;
  41. }
  42. v->address += add;
  43. }
  44. return VE_CANNOT_FIND;
  45. }
  46. VariableError vsAdd(Variables* vs, const char* s, DataType type,
  47. const Structs* sts, Variable** v) {
  48. if(vs->entries >= vs->capacity) {
  49. vs->capacity *= 2;
  50. vs->data = (Variable*)realloc(vs->data,
  51. sizeof(Variable) * (size_t)vs->capacity);
  52. }
  53. int size;
  54. if(dtGetSize(type, sts, &size)) {
  55. return VE_SIZE_ERROR;
  56. }
  57. int index = vs->entries++;
  58. vs->data[index] = (Variable){s, type, vs->address};
  59. vs->address += size;
  60. if(vs->address > vs->maxAddress) {
  61. vs->maxAddress = vs->address;
  62. }
  63. *v = vs->data + index;
  64. return VE_OK;
  65. }
  66. void vsReset(Variables* v) {
  67. v->entries = 0;
  68. v->address = 0;
  69. v->scope = 0;
  70. v->maxAddress = 0;
  71. }
  72. void vsEnterScope(Variables* v, Scope* s) {
  73. s->address = v->address;
  74. s->entries = v->entries;
  75. s->scope = v->scope;
  76. v->scope = v->entries;
  77. }
  78. void vsLeaveScope(Variables* v, const Scope* s) {
  79. v->address = s->address;
  80. v->entries = s->entries;
  81. v->scope = s->scope;
  82. }