Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

66 строки
2.0 KiB

  1. struct Environment {
  2. struct Environment* parent;
  3. int capacity;
  4. int next_index;
  5. // TODO(Felix): Use a hashmap here.
  6. char** keys;
  7. Ast_Node** values;
  8. };
  9. typedef struct Environment Environment;
  10. Environment* create_child_environment(Environment* parent) {
  11. Environment* env = new(Environment);
  12. int start_capacity = 16;
  13. env->parent = parent;
  14. env->capacity = start_capacity;
  15. env->next_index = 0;
  16. env->keys = (char**)malloc(start_capacity * sizeof(char*));
  17. env->values = (Ast_Node**)malloc(start_capacity * sizeof(Ast_Node*));
  18. return env;
  19. }
  20. Environment* create_empty_environment() {
  21. return create_child_environment(nullptr);
  22. }
  23. void define_symbol(Ast_Node* symbol, Ast_Node* value, Environment* env) {
  24. // NOTE(Felix): right now we are simply adding the symol at the
  25. // back of the list without checking if it already exists but are
  26. // also searching for thesymbol from the back, so we will find the
  27. // latest defined one first, but a bit messy. Later we should use
  28. // a hashmap here. @refactor
  29. if (env->next_index == env->capacity) {
  30. env->capacity *= 2;
  31. env->keys = (char**)realloc(env->keys, env->capacity * sizeof(char*));
  32. env->values = (Ast_Node**)realloc(env->values, env->capacity * sizeof(Ast_Node*));
  33. }
  34. env->keys [env->next_index] = symbol->value.symbol->identifier;
  35. env->values[env->next_index] = value;
  36. ++env->next_index;
  37. }
  38. Ast_Node* lookup_symbol(Symbol* sym, Environment* env) {
  39. for (int i = env->next_index - 1; i >= 0; --i)
  40. if (string_equal(env->keys[i], sym->identifier))
  41. return env->values[i];
  42. if (env->parent)
  43. return lookup_symbol(sym, env->parent);
  44. Ast_Node* built_in = create_ast_node_built_in_function(sym->identifier);
  45. if (built_in)
  46. return built_in;
  47. create_error(Error_Type_Symbol_Not_Defined, create_ast_node_nil());
  48. printf("%s\n", sym->identifier);
  49. return nullptr;
  50. }