aboutsummaryrefslogtreecommitdiff
path: root/bootstrap/env.c
blob: 0c0021be22370180b0bcb03fc0fd2a7ff6df2a55 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include "all.h"


struct decl *
envfind(const struct env *env, const char *name) {
   if (!env)
      return NULL;
   for (struct decls *decls = env->decls; decls; decls = decls->next) {
      if (!strcmp(decls->decl.name, name))
         return &decls->decl;
   }
   return envfind(env->parent, name);
}

static bool
declsshadowable(const struct decl *a, const struct decl *b) {
   return b->t == Dlet;
}

static bool
declscompatible(const struct decl *a, const struct decl *b) {
   if (a->t != b->t)
      return 0;
   if (a->t == Dfn && a->externp == b->externp && a->fn.selfty == b->fn.selfty && !a->fn.body)
      return 1;
   if (a->t == Dstatic && a->externp == b->externp && a->var.ty == b->var.ty && !a->var.ini)
      return 1;
   if (a->t == Dtype && a->ty == b->ty)
      return 1;
   return 0;
}

bool
envput(struct env *env, const struct decl *decl) {
   struct decls *decls;
   struct env env_noparent = {
     .decls = env->decls
   };
   struct decl *decl0;
   if ((decl0 = envfind(&env_noparent, decl->name))) {
      if (!declsshadowable(decl0, decl) && !declscompatible(decl0, decl))
         return 0;
   }

   decls = xcalloc(1, sizeof *decls);
   decls->next = env->decls;
   decls->decl = *decl;
   env->decls = decls;
   return 1;
}