#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; }