cproc

Unnamed repository; edit this file 'description' to name the repository.
git clone git://git.nihaljere.xyz/cproc
Log | Files | Refs | Submodules | README | LICENSE

decl.c (27287B)


      1 #include <assert.h>
      2 #include <inttypes.h>
      3 #include <stdbool.h>
      4 #include <stddef.h>
      5 #include <stdint.h>
      6 #include <stdio.h>
      7 #include <stdlib.h>
      8 #include <string.h>
      9 #include "util.h"
     10 #include "cc.h"
     11 
     12 static struct list tentativedefns = {&tentativedefns, &tentativedefns};
     13 
     14 struct qualtype {
     15 	struct type *type;
     16 	enum typequal qual;
     17 };
     18 
     19 enum storageclass {
     20 	SCNONE,
     21 
     22 	SCTYPEDEF     = 1<<1,
     23 	SCEXTERN      = 1<<2,
     24 	SCSTATIC      = 1<<3,
     25 	SCAUTO        = 1<<4,
     26 	SCREGISTER    = 1<<5,
     27 	SCTHREADLOCAL = 1<<6,
     28 };
     29 
     30 enum typespec {
     31 	SPECNONE,
     32 
     33 	SPECVOID     = 1<<1,
     34 	SPECCHAR     = 1<<2,
     35 	SPECBOOL     = 1<<3,
     36 	SPECINT      = 1<<4,
     37 	SPECFLOAT    = 1<<5,
     38 	SPECDOUBLE   = 1<<6,
     39 	SPECSHORT    = 1<<7,
     40 	SPECLONG     = 1<<8,
     41 	SPECLONG2    = 1<<9,
     42 	SPECSIGNED   = 1<<10,
     43 	SPECUNSIGNED = 1<<11,
     44 	SPECCOMPLEX  = 1<<12,
     45 
     46 	SPECLONGLONG = SPECLONG|SPECLONG2,
     47 };
     48 
     49 enum funcspec {
     50 	FUNCNONE,
     51 
     52 	FUNCINLINE   = 1<<1,
     53 	FUNCNORETURN = 1<<2,
     54 };
     55 
     56 struct structbuilder {
     57 	struct type *type;
     58 	struct member **last;
     59 	unsigned bits;  /* number of bits remaining in the last byte */
     60 };
     61 
     62 struct decl *
     63 mkdecl(enum declkind k, struct type *t, enum typequal tq, enum linkage linkage)
     64 {
     65 	struct decl *d;
     66 
     67 	d = xmalloc(sizeof(*d));
     68 	memset(d, 0, sizeof(*d));
     69 	d->kind = k;
     70 	d->linkage = linkage;
     71 	d->type = t;
     72 	d->qual = tq;
     73 
     74 	return d;
     75 }
     76 
     77 /* 6.7.1 Storage-class specifiers */
     78 static int
     79 storageclass(enum storageclass *sc)
     80 {
     81 	enum storageclass allowed, new;
     82 
     83 	switch (tok.kind) {
     84 	case TTYPEDEF:       new = SCTYPEDEF;     break;
     85 	case TEXTERN:        new = SCEXTERN;      break;
     86 	case TSTATIC:        new = SCSTATIC;      break;
     87 	case T_THREAD_LOCAL: new = SCTHREADLOCAL; break;
     88 	case TAUTO:          new = SCAUTO;        break;
     89 	case TREGISTER:      new = SCREGISTER;    break;
     90 	default: return 0;
     91 	}
     92 	if (!sc)
     93 		error(&tok.loc, "storage class not allowed in this declaration");
     94 	switch (*sc) {
     95 	case SCNONE:        allowed = ~SCNONE;           break;
     96 	case SCTHREADLOCAL: allowed = SCSTATIC|SCEXTERN; break;
     97 	case SCSTATIC:
     98 	case SCEXTERN:      allowed = SCTHREADLOCAL;     break;
     99 	default:            allowed = SCNONE;            break;
    100 	}
    101 	if (new & ~allowed)
    102 		error(&tok.loc, "invalid combination of storage class specifiers");
    103 	*sc |= new;
    104 	next();
    105 
    106 	return 1;
    107 }
    108 
    109 /* 6.7.3 Type qualifiers */
    110 static int
    111 typequal(enum typequal *tq)
    112 {
    113 	switch (tok.kind) {
    114 	case TCONST:    *tq |= QUALCONST;    break;
    115 	case TVOLATILE: *tq |= QUALVOLATILE; break;
    116 	case TRESTRICT: *tq |= QUALRESTRICT; break;
    117 	case T_ATOMIC: error(&tok.loc, "_Atomic type qualifier is not yet supported");
    118 	default: return 0;
    119 	}
    120 	next();
    121 
    122 	return 1;
    123 }
    124 
    125 /* 6.7.4 Function specifiers */
    126 static int
    127 funcspec(enum funcspec *fs)
    128 {
    129 	enum funcspec new;
    130 
    131 	switch (tok.kind) {
    132 	case TINLINE:    new = FUNCINLINE;   break;
    133 	case T_NORETURN: new = FUNCNORETURN; break;
    134 	default: return 0;
    135 	}
    136 	if (!fs)
    137 		error(&tok.loc, "function specifier not allowed in this declaration");
    138 	*fs |= new;
    139 	next();
    140 
    141 	return 1;
    142 }
    143 
    144 static void structdecl(struct scope *, struct structbuilder *);
    145 
    146 static struct type *
    147 tagspec(struct scope *s)
    148 {
    149 	struct type *t;
    150 	char *tag, *name;
    151 	enum typekind kind;
    152 	struct decl *d;
    153 	struct expr *e;
    154 	struct structbuilder b;
    155 	uint64_t i;
    156 	bool large;
    157 
    158 	switch (tok.kind) {
    159 	case TSTRUCT: kind = TYPESTRUCT; break;
    160 	case TUNION:  kind = TYPEUNION;  break;
    161 	case TENUM:   kind = TYPEENUM;   break;
    162 	default: fatal("internal error: unknown tag kind");
    163 	}
    164 	next();
    165 	if (tok.kind == TLBRACE) {
    166 		tag = NULL;
    167 		t = NULL;
    168 	} else {
    169 		tag = expect(TIDENT, "or '{' after struct/union");
    170 		t = scopegettag(s, tag, false);
    171 		if (s->parent && !t && tok.kind != TLBRACE && (kind == TYPEENUM || tok.kind != TSEMICOLON))
    172 			t = scopegettag(s->parent, tag, true);
    173 	}
    174 	if (t) {
    175 		if (t->kind != kind)
    176 			error(&tok.loc, "redeclaration of tag '%s' with different kind", tag);
    177 	} else {
    178 		if (kind == TYPEENUM) {
    179 			t = xmalloc(sizeof(*t));
    180 			*t = typeuint;
    181 			t->kind = kind;
    182 		} else {
    183 			t = mktype(kind, PROPOBJECT);
    184 			if (kind == TYPESTRUCT)
    185 				t->prop |= PROPAGGR;
    186 			t->repr = &i64; // XXX
    187 			t->size = 0;
    188 			t->align = 0;
    189 			t->structunion.tag = tag;
    190 			t->structunion.members = NULL;
    191 		}
    192 		t->incomplete = true;
    193 		if (tag)
    194 			scopeputtag(s, tag, t);
    195 	}
    196 	if (tok.kind != TLBRACE)
    197 		return t;
    198 	if (!t->incomplete)
    199 		error(&tok.loc, "redefinition of tag '%s'", tag);
    200 	next();
    201 	switch (t->kind) {
    202 	case TYPESTRUCT:
    203 	case TYPEUNION:
    204 		b.type = t;
    205 		b.last = &t->structunion.members;
    206 		b.bits = 0;
    207 		do structdecl(s, &b);
    208 		while (tok.kind != TRBRACE);
    209 		next();
    210 		t->size = ALIGNUP(t->size, t->align);
    211 		t->incomplete = false;
    212 		break;
    213 	case TYPEENUM:
    214 		large = false;
    215 		for (i = 0; tok.kind == TIDENT; ++i) {
    216 			name = tok.lit;
    217 			next();
    218 			if (consume(TASSIGN)) {
    219 				e = constexpr(s);
    220 				if (e->kind != EXPRCONST || !(e->type->prop & PROPINT))
    221 					error(&tok.loc, "expected integer constant expression");
    222 				i = e->constant.i;
    223 				if (e->type->basic.issigned && i >= 1ull << 63) {
    224 					if (i < -1ull << 31)
    225 						goto invalid;
    226 					t->basic.issigned = true;
    227 				} else if (i >= 1ull << 32) {
    228 					goto invalid;
    229 				}
    230 			} else if (i == 1ull << 32) {
    231 			invalid:
    232 				error(&tok.loc, "enumerator '%s' value cannot be represented as 'int' or 'unsigned int'", name);
    233 			}
    234 			d = mkdecl(DECLCONST, &typeint, QUALNONE, LINKNONE);
    235 			d->value = mkintconst(t->repr, i);
    236 			if (i >= 1ull << 31 && i < 1ull << 63) {
    237 				large = true;
    238 				d->type = &typeuint;
    239 			}
    240 			if (large && t->basic.issigned)
    241 				error(&tok.loc, "neither 'int' nor 'unsigned' can represent all enumerator values");
    242 			scopeputdecl(s, name, d);
    243 			if (!consume(TCOMMA))
    244 				break;
    245 		}
    246 		expect(TRBRACE, "to close enum specifier");
    247 		t->incomplete = false;
    248 	}
    249 
    250 	return t;
    251 }
    252 
    253 /* 6.7 Declarations */
    254 static struct qualtype
    255 declspecs(struct scope *s, enum storageclass *sc, enum funcspec *fs, int *align)
    256 {
    257 	struct type *t, *other;
    258 	struct decl *d;
    259 	struct expr *e;
    260 	enum typespec ts = SPECNONE;
    261 	enum typequal tq = QUALNONE;
    262 	int ntypes = 0;
    263 	uint64_t i;
    264 
    265 	t = NULL;
    266 	if (sc)
    267 		*sc = SCNONE;
    268 	if (fs)
    269 		*fs = FUNCNONE;
    270 	if (align)
    271 		*align = 0;
    272 	for (;;) {
    273 		if (typequal(&tq) || storageclass(sc) || funcspec(fs))
    274 			continue;
    275 		switch (tok.kind) {
    276 		/* 6.7.2 Type specifiers */
    277 		case TVOID:
    278 			t = &typevoid;
    279 			++ntypes;
    280 			next();
    281 			break;
    282 		case TCHAR:
    283 			ts |= SPECCHAR;
    284 			++ntypes;
    285 			next();
    286 			break;
    287 		case TSHORT:
    288 			if (ts & SPECSHORT)
    289 				error(&tok.loc, "duplicate 'short'");
    290 			ts |= SPECSHORT;
    291 			next();
    292 			break;
    293 		case TINT:
    294 			ts |= SPECINT;
    295 			++ntypes;
    296 			next();
    297 			break;
    298 		case TLONG:
    299 			if (ts & SPECLONG2)
    300 				error(&tok.loc, "too many 'long'");
    301 			if (ts & SPECLONG)
    302 				ts |= SPECLONG2;
    303 			ts |= SPECLONG;
    304 			next();
    305 			break;
    306 		case TFLOAT:
    307 			ts |= SPECFLOAT;
    308 			++ntypes;
    309 			next();
    310 			break;
    311 		case TDOUBLE:
    312 			ts |= SPECDOUBLE;
    313 			++ntypes;
    314 			next();
    315 			break;
    316 		case TSIGNED:
    317 			if (ts & SPECSIGNED)
    318 				error(&tok.loc, "duplicate 'signed'");
    319 			ts |= SPECSIGNED;
    320 			next();
    321 			break;
    322 		case TUNSIGNED:
    323 			if (ts & SPECUNSIGNED)
    324 				error(&tok.loc, "duplicate 'unsigned'");
    325 			ts |= SPECUNSIGNED;
    326 			next();
    327 			break;
    328 		case T_BOOL:
    329 			t = &typebool;
    330 			++ntypes;
    331 			next();
    332 			break;
    333 		case T_COMPLEX:
    334 			fatal("_Complex is not yet supported");
    335 			break;
    336 		case T_ATOMIC:
    337 			fatal("_Atomic is not yet supported");
    338 			break;
    339 		case TSTRUCT:
    340 		case TUNION:
    341 		case TENUM:
    342 			t = tagspec(s);
    343 			++ntypes;
    344 			break;
    345 		case TIDENT:
    346 			if (t || ts)
    347 				goto done;
    348 			d = scopegetdecl(s, tok.lit, 1);
    349 			if (!d || d->kind != DECLTYPE)
    350 				goto done;
    351 			t = d->type;
    352 			++ntypes;
    353 			next();
    354 			break;
    355 		case T__TYPEOF__:
    356 			next();
    357 			expect(TLPAREN, "after '__typeof__'");
    358 			t = typename(s, &tq);
    359 			if (!t) {
    360 				e = expr(s);
    361 				if (e->decayed)
    362 					e = e->base;
    363 				t = e->type;
    364 				tq |= e->qual;
    365 				delexpr(e);
    366 			}
    367 			++ntypes;
    368 			expect(TRPAREN, "to close '__typeof__'");
    369 			break;
    370 
    371 		/* 6.7.5 Alignment specifier */
    372 		case T_ALIGNAS:
    373 			if (!align)
    374 				error(&tok.loc, "alignment specifier not allowed in this declaration");
    375 			next();
    376 			expect(TLPAREN, "after '_Alignas'");
    377 			other = typename(s, NULL);
    378 			if (other) {
    379 				*align = other->align;
    380 			} else {
    381 				i = intconstexpr(s, false);
    382 				if (!i || i & (i - 1) || i > 16)
    383 					error(&tok.loc, "invalid alignment: %d", i);
    384 				*align = (int)i;
    385 			}
    386 			expect(TRPAREN, "to close '_Alignas' specifier");
    387 			break;
    388 
    389 		default:
    390 			goto done;
    391 		}
    392 		if (ntypes > 1 || (t && ts))
    393 			error(&tok.loc, "multiple types in declaration specifiers");
    394 	}
    395 done:
    396 	switch ((int)ts) {
    397 	case SPECNONE:                                            break;
    398 	case SPECCHAR:                          t = &typechar;    break;
    399 	case SPECSIGNED|SPECCHAR:               t = &typeschar;   break;
    400 	case SPECUNSIGNED|SPECCHAR:             t = &typeuchar;   break;
    401 	case SPECSHORT:
    402 	case SPECSHORT|SPECINT:
    403 	case SPECSIGNED|SPECSHORT:
    404 	case SPECSIGNED|SPECSHORT|SPECINT:      t = &typeshort;   break;
    405 	case SPECUNSIGNED|SPECSHORT:
    406 	case SPECUNSIGNED|SPECSHORT|SPECINT:    t = &typeushort;  break;
    407 	case SPECINT:
    408 	case SPECSIGNED:
    409 	case SPECSIGNED|SPECINT:                t = &typeint;     break;
    410 	case SPECUNSIGNED:
    411 	case SPECUNSIGNED|SPECINT:              t = &typeuint;    break;
    412 	case SPECLONG:
    413 	case SPECLONG|SPECINT:
    414 	case SPECSIGNED|SPECLONG:
    415 	case SPECSIGNED|SPECLONG|SPECINT:       t = &typelong;    break;
    416 	case SPECUNSIGNED|SPECLONG:
    417 	case SPECUNSIGNED|SPECLONG|SPECINT:     t = &typeulong;   break;
    418 	case SPECLONGLONG:
    419 	case SPECLONGLONG|SPECINT:
    420 	case SPECSIGNED|SPECLONGLONG:
    421 	case SPECSIGNED|SPECLONGLONG|SPECINT:   t = &typellong;   break;
    422 	case SPECUNSIGNED|SPECLONGLONG:
    423 	case SPECUNSIGNED|SPECLONGLONG|SPECINT: t = &typeullong;  break;
    424 	case SPECFLOAT:                         t = &typefloat;   break;
    425 	case SPECDOUBLE:                        t = &typedouble;  break;
    426 	case SPECLONG|SPECDOUBLE:               t = &typeldouble; break;
    427 	default:
    428 		error(&tok.loc, "invalid combination of type specifiers");
    429 	}
    430 	if (!t && (tq || sc && *sc || fs && *fs))
    431 		error(&tok.loc, "declaration has no type specifier");
    432 	if (t && tq && t->kind == TYPEARRAY) {
    433 		t = mkarraytype(t->base, t->qual | tq, t->array.length);
    434 		tq = QUALNONE;
    435 	}
    436 
    437 	return (struct qualtype){t, tq};
    438 }
    439 
    440 /* 6.7.6 Declarators */
    441 static struct param *parameter(struct scope *);
    442 
    443 static bool
    444 istypename(struct scope *s, const char *name)
    445 {
    446 	struct decl *d;
    447 
    448 	d = scopegetdecl(s, name, 1);
    449 	return d && d->kind == DECLTYPE;
    450 }
    451 
    452 /*
    453 When parsing a declarator, qualifiers for derived types are temporarily
    454 stored in the `qual` field of the type itself (elsewhere this field
    455 is used for the qualifiers of the base type). This is corrected in
    456 declarator().
    457 */
    458 static void
    459 declaratortypes(struct scope *s, struct list *result, char **name, bool allowabstract)
    460 {
    461 	struct list *ptr;
    462 	struct type *t;
    463 	struct param **p;
    464 	struct expr *e;
    465 	uint64_t i;
    466 	enum typequal tq;
    467 
    468 	while (consume(TMUL)) {
    469 		tq = QUALNONE;
    470 		while (typequal(&tq))
    471 			;
    472 		t = mkpointertype(NULL, tq);
    473 		listinsert(result, &t->link);
    474 	}
    475 	if (name)
    476 		*name = NULL;
    477 	ptr = result->next;
    478 	switch (tok.kind) {
    479 	case TLPAREN:
    480 		next();
    481 		switch (tok.kind) {
    482 		case TMUL:
    483 		case TLPAREN:
    484 			break;
    485 		case TIDENT:
    486 			if (!allowabstract || !istypename(s, tok.lit))
    487 				break;
    488 			/* fallthrough */
    489 		default:
    490 			goto func;
    491 		}
    492 		declaratortypes(s, result, name, allowabstract);
    493 		expect(TRPAREN, "after parenthesized declarator");
    494 		break;
    495 	case TIDENT:
    496 		if (!name)
    497 			error(&tok.loc, "identifier not allowed in abstract declarator");
    498 		*name = tok.lit;
    499 		next();
    500 		break;
    501 	default:
    502 		if (!allowabstract)
    503 			error(&tok.loc, "expected '(' or identifier");
    504 	}
    505 	for (;;) {
    506 		switch (tok.kind) {
    507 		case TLPAREN:  /* function declarator */
    508 			next();
    509 		func:
    510 			t = mktype(TYPEFUNC, PROPDERIVED);
    511 			t->qual = QUALNONE;
    512 			t->func.isprototype = false;
    513 			t->func.isvararg = false;
    514 			t->func.isnoreturn = false;
    515 			t->func.params = NULL;
    516 			p = &t->func.params;
    517 			switch (tok.kind) {
    518 			case TIDENT:
    519 				if (!istypename(s, tok.lit)) {
    520 					/* identifier-list (K&R declaration) */
    521 					do {
    522 						*p = mkparam(tok.lit, NULL, QUALNONE);
    523 						p = &(*p)->next;
    524 						next();
    525 					} while (consume(TCOMMA) && tok.kind == TIDENT);
    526 					break;
    527 				}
    528 				/* fallthrough */
    529 			default:
    530 				t->func.isprototype = true;
    531 				for (;;) {
    532 					*p = parameter(s);
    533 					p = &(*p)->next;
    534 					if (!consume(TCOMMA))
    535 						break;
    536 					if (consume(TELLIPSIS)) {
    537 						t->func.isvararg = true;
    538 						break;
    539 					}
    540 				}
    541 				if (t->func.params->type->kind == TYPEVOID && !t->func.params->next)
    542 					t->func.params = NULL;
    543 				break;
    544 			case TRPAREN:
    545 				break;
    546 			}
    547 			expect(TRPAREN, "to close function declarator");
    548 			t->func.paraminfo = t->func.isprototype || t->func.params || tok.kind == TLBRACE;
    549 			listinsert(ptr->prev, &t->link);
    550 			break;
    551 		case TLBRACK:  /* array declarator */
    552 			next();
    553 			tq = QUALNONE;
    554 			while (consume(TSTATIC) || typequal(&tq))
    555 				;
    556 			if (tok.kind == TMUL)
    557 				error(&tok.loc, "VLAs are not yet supported");
    558 			if (tok.kind == TRBRACK) {
    559 				i = 0;
    560 				next();
    561 			} else {
    562 				e = eval(assignexpr(s), EVALARITH);
    563 				if (e->kind != EXPRCONST || !(e->type->prop & PROPINT))
    564 					error(&tok.loc, "VLAs are not yet supported");
    565 				i = e->constant.i;
    566 				if (e->type->basic.issigned && i > INT64_MAX)
    567 					error(&tok.loc, "array length must be non-negative");
    568 				delexpr(e);
    569 				expect(TRBRACK, "after array length");
    570 			}
    571 			t = mkarraytype(NULL, tq, i);
    572 			listinsert(ptr->prev, &t->link);
    573 			break;
    574 		default:
    575 			return;
    576 		}
    577 	}
    578 }
    579 
    580 static struct qualtype
    581 declarator(struct scope *s, struct qualtype base, char **name, bool allowabstract)
    582 {
    583 	struct type *t;
    584 	enum typequal tq;
    585 	struct list result = {&result, &result}, *l, *prev;
    586 
    587 	declaratortypes(s, &result, name, allowabstract);
    588 	for (l = result.prev; l != &result; l = prev) {
    589 		prev = l->prev;
    590 		t = listelement(l, struct type, link);
    591 		tq = t->qual;
    592 		t->base = base.type;
    593 		t->qual = base.qual;
    594 		switch (t->kind) {
    595 		case TYPEFUNC:
    596 			if (base.type->kind == TYPEFUNC)
    597 				error(&tok.loc, "function declarator specifies function return type");
    598 			if (base.type->kind == TYPEARRAY)
    599 				error(&tok.loc, "function declarator specifies array return type");
    600 			break;
    601 		case TYPEARRAY:
    602 			if (base.type->incomplete)
    603 				error(&tok.loc, "array element has incomplete type");
    604 			if (base.type->kind == TYPEFUNC)
    605 				error(&tok.loc, "array element has function type");
    606 			t->align = base.type->align;
    607 			t->size = base.type->size * t->array.length;  // XXX: overflow?
    608 			break;
    609 		}
    610 		base.type = t;
    611 		base.qual = tq;
    612 	}
    613 
    614 	return base;
    615 }
    616 
    617 static struct type *
    618 adjust(struct type *t)
    619 {
    620 	switch (t->kind) {
    621 	case TYPEARRAY:
    622 		t = mkpointertype(t->base, t->qual);
    623 		break;
    624 	case TYPEFUNC:
    625 		t = mkpointertype(t, QUALNONE);
    626 		break;
    627 	}
    628 
    629 	return t;
    630 }
    631 
    632 static struct param *
    633 parameter(struct scope *s)
    634 {
    635 	char *name;
    636 	struct qualtype t;
    637 	enum storageclass sc;
    638 
    639 	t = declspecs(s, &sc, NULL, NULL);
    640 	if (!t.type)
    641 		error(&tok.loc, "no type in parameter declaration");
    642 	if (sc && sc != SCREGISTER)
    643 		error(&tok.loc, "parameter declaration has invalid storage-class specifier");
    644 	t = declarator(s, t, &name, true);
    645 
    646 	return mkparam(name, adjust(t.type), t.qual);
    647 }
    648 
    649 static bool
    650 paramdecl(struct scope *s, struct param *params)
    651 {
    652 	struct param *p;
    653 	struct qualtype t, base;
    654 	enum storageclass sc;
    655 	char *name;
    656 
    657 	base = declspecs(s, &sc, NULL, NULL);
    658 	if (!base.type)
    659 		return false;
    660 	if (sc && sc != SCREGISTER)
    661 		error(&tok.loc, "parameter declaration has invalid storage-class specifier");
    662 	for (;;) {
    663 		t = declarator(s, base, &name, false);
    664 		for (p = params; p && strcmp(name, p->name) != 0; p = p->next)
    665 			;
    666 		if (!p)
    667 			error(&tok.loc, "old-style function declarator has no parameter named '%s'", name);
    668 		p->type = adjust(t.type);
    669 		p->qual = t.qual;
    670 		if (tok.kind == TSEMICOLON)
    671 			break;
    672 		expect(TCOMMA, "or ';' after parameter declarator");
    673 	}
    674 	next();
    675 	return true;
    676 }
    677 
    678 static void
    679 addmember(struct structbuilder *b, struct qualtype mt, char *name, int align, uint64_t width)
    680 {
    681 	struct type *t = b->type;
    682 	struct member *m;
    683 	size_t end;
    684 
    685 	// XXX: check incomplete type, except for flexible array member
    686 	if (mt.type->kind == TYPEFUNC)
    687 		error(&tok.loc, "struct member '%s' has function type", name);
    688 	assert(mt.type->align > 0);
    689 	if (name || width == -1) {
    690 		m = xmalloc(sizeof(*m));
    691 		m->type = mt.type;
    692 		m->qual = mt.qual;
    693 		m->name = name;
    694 		m->next = NULL;
    695 		*b->last = m;
    696 		b->last = &m->next;
    697 	} else {
    698 		m = NULL;
    699 	}
    700 	if (width == -1) {
    701 		m->bits.before = 0;
    702 		m->bits.after = 0;
    703 		if (align < mt.type->align)
    704 			align = mt.type->align;
    705 		t->size = ALIGNUP(t->size, align);
    706 		if (t->kind == TYPESTRUCT) {
    707 			m->offset = t->size;
    708 			t->size += mt.type->size;
    709 		} else {
    710 			m->offset = 0;
    711 			if (t->size < mt.type->size)
    712 				t->size = mt.type->size;
    713 		}
    714 		b->bits = 0;
    715 	} else {  /* bit-field */
    716 		if (!(mt.type->prop & PROPINT))
    717 			error(&tok.loc, "bit-field has invalid type");
    718 		if (align)
    719 			error(&tok.loc, "alignment specified for bit-field");
    720 		if (!width && name)
    721 			error(&tok.loc, "bit-field with zero width must not have declarator");
    722 		if (width > mt.type->size * 8)
    723 			error(&tok.loc, "bit-field exceeds width of underlying type");
    724 		align = mt.type->align;
    725 		if (t->kind == TYPESTRUCT) {
    726 			/* calculate end of the storage-unit for this bit-field */
    727 			end = ALIGNUP(t->size, mt.type->size);
    728 			if (!width || width > (end - t->size) * 8 + b->bits) {
    729 				/* no room, allocate a new storage-unit */
    730 				t->size = end;
    731 				b->bits = 0;
    732 			}
    733 			if (m) {
    734 				m->offset = ALIGNDOWN(t->size - !!b->bits, mt.type->size);
    735 				m->bits.before = (t->size - m->offset) * 8 - b->bits;
    736 				m->bits.after = mt.type->size * 8 - width - m->bits.before;
    737 			}
    738 			t->size += (width - b->bits + 7) / 8;
    739 			b->bits = (b->bits - width) % 8;
    740 		} else if (m) {
    741 			m->offset = 0;
    742 			m->bits.before = 0;
    743 			m->bits.after = mt.type->size * 8 - width;
    744 			if (t->size < mt.type->size)
    745 				t->size = mt.type->size;
    746 		}
    747 	}
    748 	if (m && t->align < align)
    749 		t->align = align;
    750 }
    751 
    752 static void
    753 structdecl(struct scope *s, struct structbuilder *b)
    754 {
    755 	struct qualtype base, mt;
    756 	char *name;
    757 	uint64_t width;
    758 	int align;
    759 
    760 	base = declspecs(s, NULL, NULL, &align);
    761 	if (!base.type)
    762 		error(&tok.loc, "no type in struct member declaration");
    763 	if (tok.kind == TSEMICOLON) {
    764 		if ((base.type->kind != TYPESTRUCT && base.type->kind != TYPEUNION) || base.type->structunion.tag)
    765 			error(&tok.loc, "struct declaration must declare at least one member");
    766 		next();
    767 		addmember(b, base, NULL, align, -1);
    768 		return;
    769 	}
    770 	for (;;) {
    771 		if (consume(TCOLON)) {
    772 			width = intconstexpr(s, false);
    773 			addmember(b, base, NULL, 0, width);
    774 		} else {
    775 			mt = declarator(s, base, &name, false);
    776 			width = consume(TCOLON) ? intconstexpr(s, false) : -1;
    777 			addmember(b, mt, name, align, width);
    778 		}
    779 		if (tok.kind == TSEMICOLON)
    780 			break;
    781 		expect(TCOMMA, "or ';' after declarator");
    782 	}
    783 	next();
    784 }
    785 
    786 /* 6.7.7 Type names */
    787 struct type *
    788 typename(struct scope *s, enum typequal *tq)
    789 {
    790 	struct qualtype t;
    791 
    792 	t = declspecs(s, NULL, NULL, NULL);
    793 	if (t.type) {
    794 		t = declarator(s, t, NULL, true);
    795 		if (tq)
    796 			*tq |= t.qual;
    797 	}
    798 	return t.type;
    799 }
    800 
    801 static enum linkage
    802 getlinkage(enum declkind kind, enum storageclass sc, struct decl *prior, bool filescope)
    803 {
    804 	if (sc & SCSTATIC)
    805 		return filescope ? LINKINTERN : LINKNONE;
    806 	if (sc & SCEXTERN || kind == DECLFUNC)
    807 		return prior ? prior->linkage : LINKEXTERN;
    808 	return filescope ? LINKEXTERN : LINKNONE;
    809 }
    810 
    811 static struct decl *
    812 declcommon(struct scope *s, enum declkind kind, char *name, char *asmname, struct type *t, enum typequal tq, enum storageclass sc, struct decl *prior)
    813 {
    814 	struct decl *d;
    815 	enum linkage linkage;
    816 	const char *kindstr = kind == DECLFUNC ? "function" : "object";
    817 	char *priorname;
    818 
    819 	if (prior) {
    820 		if (prior->linkage == LINKNONE)
    821 			error(&tok.loc, "%s '%s' with no linkage redeclared", kindstr, name);
    822 		linkage = getlinkage(kind, sc, prior, s == &filescope);
    823 		if (prior->linkage != linkage)
    824 			error(&tok.loc, "%s '%s' redeclared with different linkage", kindstr, name);
    825 		if (!typecompatible(t, prior->type) || tq != prior->qual)
    826 			error(&tok.loc, "%s '%s' redeclared with incompatible type", kindstr, name);
    827 		if (asmname && strcmp(globalname(prior->value), asmname) != 0)
    828 			error(&tok.loc, "%s '%s' redeclared with different assembler name", kindstr, name);
    829 		prior->type = typecomposite(t, prior->type);
    830 		return prior;
    831 	}
    832 	if (s->parent)
    833 		prior = scopegetdecl(s->parent, name, true);
    834 	linkage = getlinkage(kind, sc, prior, s == &filescope);
    835 	if (linkage != LINKNONE && s->parent) {
    836 		/* XXX: should maintain map of identifiers with linkage to their declaration, and use that */
    837 		if (s->parent != &filescope)
    838 			prior = scopegetdecl(&filescope, name, false);
    839 		if (prior && prior->linkage != LINKNONE) {
    840 			if (prior->kind != kind)
    841 				error(&tok.loc, "'%s' redeclared with different kind", name);
    842 			if (prior->linkage != linkage)
    843 				error(&tok.loc, "%s '%s' redeclared with different linkage", kindstr, name);
    844 			if (!typecompatible(t, prior->type) || tq != prior->qual)
    845 				error(&tok.loc, "%s '%s' redeclared with incompatible type", kindstr, name);
    846 			priorname = globalname(prior->value);
    847 			if (!asmname)
    848 				asmname = priorname;
    849 			else if (strcmp(priorname, asmname) != 0)
    850 				error(&tok.loc, "%s '%s' redeclared with different assembler name", kindstr, name);
    851 			t = typecomposite(t, prior->type);
    852 		}
    853 	}
    854 	d = mkdecl(kind, t, tq, linkage);
    855 	scopeputdecl(s, name, d);
    856 	if (kind == DECLFUNC || linkage != LINKNONE || sc & SCSTATIC)
    857 		d->value = mkglobal(asmname ? asmname : name, linkage == LINKNONE && !asmname);
    858 	return d;
    859 }
    860 
    861 static bool
    862 staticassert(struct scope *s)
    863 {
    864 	struct expr *e;
    865 	uint64_t c;
    866 
    867 	if (!consume(T_STATIC_ASSERT))
    868 		return false;
    869 	expect(TLPAREN, "after _Static_assert");
    870 	c = intconstexpr(s, true);
    871 	if (consume(TCOMMA)) {
    872 		e = assignexpr(s);
    873 		if (!e->decayed || e->base->kind != EXPRSTRING)
    874 			error(&tok.loc, "expected string literal after static assertion expression");
    875 		if (!c)
    876 			error(&tok.loc, "static assertion failed: %.*s", (int)e->base->string.size, e->base->string.data);
    877 	} else if (!c) {
    878 		error(&tok.loc, "static assertion failed");
    879 	}
    880 	expect(TRPAREN, "after static assertion");
    881 	expect(TSEMICOLON, "after static assertion");
    882 	return true;
    883 }
    884 
    885 bool
    886 decl(struct scope *s, struct func *f)
    887 {
    888 	struct qualtype base, qt;
    889 	struct type *t;
    890 	enum typequal tq;
    891 	enum storageclass sc;
    892 	enum funcspec fs;
    893 	struct init *init;
    894 	struct param *p;
    895 	char *name, *asmname;
    896 	int allowfunc = !f;
    897 	struct decl *d, *prior;
    898 	enum declkind kind;
    899 	int align;
    900 
    901 	if (staticassert(s))
    902 		return true;
    903 	base = declspecs(s, &sc, &fs, &align);
    904 	if (!base.type)
    905 		return false;
    906 	if (f) {
    907 		if (sc == SCTHREADLOCAL)
    908 			error(&tok.loc, "block scope declaration containing '_Thread_local' must contain 'static' or 'extern'");
    909 	} else {
    910 		/* 6.9p2 */
    911 		if (sc & SCAUTO)
    912 			error(&tok.loc, "external declaration must not contain 'auto'");
    913 		if (sc & SCREGISTER)
    914 			error(&tok.loc, "external declaration must not contain 'register'");
    915 	}
    916 	if (sc & SCTHREADLOCAL)
    917 		error(&tok.loc, "'_Thread_local' is not yet supported");
    918 	if (consume(TSEMICOLON)) {
    919 		/* XXX 6.7p2 error unless in function parameter/struct/union, or tag/enum members are declared */
    920 		return true;
    921 	}
    922 	for (;;) {
    923 		qt = declarator(s, base, &name, false);
    924 		t = qt.type;
    925 		tq = qt.qual;
    926 		if (consume(T__ASM__)) {
    927 			expect(TLPAREN, "after __asm__");
    928 			asmname = expect(TSTRINGLIT, "for assembler name");
    929 			expect(TRPAREN, "after assembler name");
    930 			allowfunc = 0;
    931 		} else {
    932 			asmname = NULL;
    933 		}
    934 		kind = sc & SCTYPEDEF ? DECLTYPE : t->kind == TYPEFUNC ? DECLFUNC : DECLOBJECT;
    935 		prior = scopegetdecl(s, name, false);
    936 		if (prior && prior->kind != kind)
    937 			error(&tok.loc, "'%s' redeclared with different kind", name);
    938 		switch (kind) {
    939 		case DECLTYPE:
    940 			if (align)
    941 				error(&tok.loc, "typedef '%s' declared with alignment specifier", name);
    942 			if (asmname)
    943 				error(&tok.loc, "typedef '%s' declared with assembler label", name);
    944 			if (!prior)
    945 				scopeputdecl(s, name, mkdecl(DECLTYPE, t, tq, LINKNONE));
    946 			else if (!typesame(prior->type, t) || prior->qual != tq)
    947 				error(&tok.loc, "typedef '%s' redefined with different type", name);
    948 			break;
    949 		case DECLOBJECT:
    950 			d = declcommon(s, kind, name, asmname, t, tq, sc, prior);
    951 			if (d->align < align)
    952 				d->align = align;
    953 			if (consume(TASSIGN)) {
    954 				if (f && d->linkage != LINKNONE)
    955 					error(&tok.loc, "object '%s' with block scope and %s linkage cannot have initializer", name, d->linkage == LINKEXTERN ? "external" : "internal");
    956 				if (d->defined)
    957 					error(&tok.loc, "object '%s' redefined", name);
    958 				init = parseinit(s, d->type);
    959 			} else {
    960 				init = NULL;
    961 			}
    962 			if (init || d->linkage == LINKNONE) {
    963 				if (d->linkage != LINKNONE || sc & SCSTATIC)
    964 					emitdata(d, init);
    965 				else
    966 					funcinit(f, d, init);
    967 				d->defined = true;
    968 				if (d->tentative.next)
    969 					listremove(&d->tentative);
    970 			} else if (!(sc & SCEXTERN) && !d->defined && !d->tentative.next) {
    971 				listinsert(tentativedefns.prev, &d->tentative);
    972 			}
    973 			break;
    974 		case DECLFUNC:
    975 			if (align)
    976 				error(&tok.loc, "function '%s' declared with alignment specifier", name);
    977 			t->func.isnoreturn |= fs & FUNCNORETURN;
    978 			if (f && sc && sc != SCEXTERN)  /* 6.7.1p7 */
    979 				error(&tok.loc, "function '%s' with block scope may only have storage class 'extern'", name);
    980 			if (!t->func.isprototype && t->func.params) {
    981 				if (!allowfunc)
    982 					error(&tok.loc, "function definition not allowed");
    983 				/* collect type information for parameters before we check compatibility */
    984 				while (paramdecl(s, t->func.params))
    985 					;
    986 				if (tok.kind != TLBRACE)
    987 					error(&tok.loc, "function declaration with identifier list is not part of definition");
    988 				for (p = t->func.params; p; p = p->next) {
    989 					if (!p->type)
    990 						error(&tok.loc, "old-style function definition does not declare '%s'", p->name);
    991 				}
    992 			}
    993 			d = declcommon(s, kind, name, asmname, t, tq, sc, prior);
    994 			d->inlinedefn = d->linkage == LINKEXTERN && fs & FUNCINLINE && !(sc & SCEXTERN) && (!prior || prior->inlinedefn);
    995 			if (tok.kind == TLBRACE) {
    996 				if (!allowfunc)
    997 					error(&tok.loc, "function definition not allowed");
    998 				if (d->defined)
    999 					error(&tok.loc, "function '%s' redefined", name);
   1000 				s = mkscope(&filescope);
   1001 				f = mkfunc(d, name, t, s);
   1002 				stmt(f, s);
   1003 				/* XXX: need to keep track of function in case a later declaration specifies extern */
   1004 				if (!d->inlinedefn)
   1005 					emitfunc(f, d->linkage == LINKEXTERN);
   1006 				s = delscope(s);
   1007 				delfunc(f);
   1008 				d->defined = true;
   1009 				return true;
   1010 			}
   1011 			break;
   1012 		}
   1013 		if (consume(TSEMICOLON))
   1014 			return true;
   1015 		expect(TCOMMA, "or ';' after declarator");
   1016 		allowfunc = 0;
   1017 	}
   1018 }
   1019 
   1020 struct decl *stringdecl(struct expr *expr)
   1021 {
   1022 	static struct map *strings;
   1023 	struct mapkey key;
   1024 	void **entry;
   1025 	struct decl *d;
   1026 
   1027 	if (!strings)
   1028 		strings = mkmap(64);
   1029 	assert(expr->kind == EXPRSTRING);
   1030 	mapkey(&key, expr->string.data, expr->string.size);
   1031 	entry = mapput(strings, &key);
   1032 	d = *entry;
   1033 	if (!d) {
   1034 		d = mkdecl(DECLOBJECT, expr->type, QUALNONE, LINKNONE);
   1035 		d->value = mkglobal("string", true);
   1036 		emitdata(d, mkinit(0, expr->type->size, (struct bitfield){0}, expr));
   1037 		*entry = d;
   1038 	}
   1039 	return d;
   1040 }
   1041 
   1042 void
   1043 emittentativedefns(void)
   1044 {
   1045 	struct list *l;
   1046 
   1047 	for (l = tentativedefns.next; l != &tentativedefns; l = l->next)
   1048 		emitdata(listelement(l, struct decl, tentative), NULL);
   1049 }