aboutsummaryrefslogtreecommitdiff
path: root/bootstrap/env.c
blob: 477c267e48d5500a45bd06191f74e1e53965c7b9 (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#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;
}

struct decl *
envput(struct env *env, const struct decl *decl) {
   struct decls *decls;
   struct env env_noparent = {
     .decls = env->decls
   };
   struct decl *d0;
   if ((d0 = envfind(&env_noparent, decl->name))) {
      for (int kind = TYstruct; kind <= TYunion; ++kind) {
         if (d0->t == Dtype && d0->ty->t == kind
          && decl->t == Dtype && decl->ty->t == kind && d0->ty->agg.fwd) {
            // modify existing forward declaration
            *(size_t *)&d0->ty->size = decl->ty->size;
            *(size_t *)&d0->ty->align = decl->ty->align;
            *(bool *)&d0->ty->agg.fwd = 0;
            memcpy((void *)&d0->ty->agg.flds, &decl->ty->agg.flds,
                  sizeof d0->ty->agg.flds);
            memcpy((void *)&d0->ty->agg.decls, &decl->ty->agg.decls,
                  sizeof d0->ty->agg.decls);
            d0->span = decl->span;
            return d0;
         }
      }
      if (!declsshadowable(d0, decl) && !declscompatible(d0, decl)) {
         return NULL;
      }
   }

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