harec

[hare] Hare compiler, written in C11 for POSIX OSs
Log | Files | Refs | README | LICENSE

check.c (121336B)


      1 #include <assert.h>
      2 #include <errno.h>
      3 #include <stdarg.h>
      4 #include <stdint.h>
      5 #include <stdio.h>
      6 #include <stdlib.h>
      7 #include <string.h>
      8 #include "ast.h"
      9 #include "check.h"
     10 #include "eval.h"
     11 #include "expr.h"
     12 #include "mod.h"
     13 #include "scope.h"
     14 #include "type_store.h"
     15 #include "typedef.h"
     16 #include "types.h"
     17 #include "util.h"
     18 
     19 void
     20 mkident(struct context *ctx, struct identifier *out, const struct identifier *in,
     21 		const char *symbol)
     22 {
     23 	if (symbol) {
     24 		out->name = xstrdup(symbol);
     25 		return;
     26 	}
     27 	identifier_dup(out, in);
     28 	if (ctx->ns && !in->ns) {
     29 		out->ns = xcalloc(1, sizeof(struct identifier));
     30 		identifier_dup(out->ns, ctx->ns);
     31 	}
     32 }
     33 
     34 static char *
     35 gen_typename(const struct type *type)
     36 {
     37 	size_t sz = 0;
     38 	char *ptr = NULL;
     39 	FILE *f = open_memstream(&ptr, &sz);
     40 	if (f == NULL) {
     41 		fprintf(stderr, "Unable to open memstream: %s\n",
     42 			strerror(errno));
     43 		exit(EXIT_FAILURE);
     44 	}
     45 	emit_type(type, f);
     46 	fclose(f);
     47 	return ptr;
     48 }
     49 
     50 static void
     51 handle_errors(struct errors *errors)
     52 {
     53 	struct errors *error = errors;
     54 	bool first = true;
     55 	while (error) {
     56 		fprintf(stderr, "Error %s:%d:%d: %s\n", sources[error->loc.file],
     57 			error->loc.lineno, error->loc.colno, error->msg);
     58 		if (first) {
     59 			errline(sources[error->loc.file], error->loc.lineno, error->loc.colno);
     60 			first = false;
     61 		}
     62 		struct errors *next = error->next;
     63 		free(error);
     64 		error = next;
     65 	}
     66 	if (errors) {
     67 		exit(EXIT_FAILURE);
     68 	}
     69 }
     70 
     71 static void
     72 verror(struct context *ctx, const struct location loc, struct expression *expr,
     73 		char *fmt, va_list ap)
     74 {
     75 	if (expr) {
     76 		expr->type = EXPR_CONSTANT;
     77 		expr->result = &builtin_type_error;
     78 		expr->constant.uval = 0; // XXX: ival?
     79 		expr->terminates = false;
     80 		expr->loc = loc;
     81 	}
     82 
     83 	va_list copy;
     84 	va_copy(copy, ap);
     85 	size_t sz = vsnprintf(NULL, 0, fmt, copy);
     86 	va_end(copy);
     87 
     88 	char *msg = xcalloc(1, sz + 1);
     89 	vsnprintf(msg, sz + 1, fmt, ap);
     90 
     91 	struct errors *next = *ctx->next = xcalloc(1, sizeof(struct errors));
     92 	next->loc = loc;
     93 	next->msg = msg;
     94 	ctx->next = &next->next;
     95 }
     96 
     97 static void
     98 error(struct context *ctx, const struct location loc, struct expression *expr,
     99 		char *fmt, ...)
    100 {
    101 	va_list ap;
    102 	va_start(ap, fmt);
    103 	verror(ctx, loc, expr, fmt, ap);
    104 	va_end(ap);
    105 }
    106 
    107 static void
    108 expect(struct context *ctx, const struct location *loc, bool constraint,
    109 	char *fmt, ...)
    110 {
    111 	if (!constraint) {
    112 		va_list ap;
    113 		va_start(ap, fmt);
    114 		verror(ctx, *loc, NULL, fmt, ap);
    115 		va_end(ap);
    116 
    117 		handle_errors(ctx->errors);
    118 	}
    119 }
    120 
    121 static struct expression *
    122 lower_implicit_cast(const struct type *to, struct expression *expr)
    123 {
    124 	if (to == expr->result || expr->terminates) {
    125 		return expr;
    126 	}
    127 	
    128 	if (type_dealias(to)->storage == STORAGE_SLICE &&
    129 		expr->result->storage == STORAGE_ARRAY &&
    130 		expr->result->array.expandable) {
    131 		return expr;
    132 	}
    133 
    134 	if (type_dealias(to)->storage == STORAGE_TAGGED) {
    135 		const struct type *interim =
    136 			tagged_select_subtype(to, expr->result, true);
    137 		if (interim) {
    138 			expr = lower_implicit_cast(interim, expr);
    139 		}
    140 	}
    141 
    142 	struct expression *cast = xcalloc(1, sizeof(struct expression));
    143 	cast->type = EXPR_CAST;
    144 	cast->result = cast->cast.secondary = to;
    145 	cast->terminates = false;
    146 	cast->cast.kind = C_CAST;
    147 	cast->cast.value = expr;
    148 	cast->cast.lowered = true;
    149 	return cast;
    150 }
    151 
    152 static void
    153 check_expr_access(struct context *ctx,
    154 	const struct ast_expression *aexpr,
    155 	struct expression *expr,
    156 	const struct type *hint)
    157 {
    158 	expr->type = EXPR_ACCESS;
    159 	expr->access.type = aexpr->access.type;
    160 
    161 	const struct scope_object *obj = NULL;
    162 	switch (expr->access.type) {
    163 	case ACCESS_IDENTIFIER:
    164 		obj = scope_lookup(ctx->scope, &aexpr->access.ident);
    165 		if (!obj) {
    166 			char buf[1024];
    167 			identifier_unparse_static(&aexpr->access.ident,
    168 				buf, sizeof(buf));
    169 			error(ctx, aexpr->loc, expr,
    170 				"Unknown object '%s'", buf);
    171 			return;
    172 		}
    173 		wrap_resolver(ctx, obj, resolve_decl);
    174 
    175 		switch (obj->otype) {
    176 		case O_CONST:
    177 			// Lower constants
    178 			*expr = *obj->value;
    179 			break;
    180 		case O_BIND:
    181 		case O_DECL:
    182 			expr->result = obj->type;
    183 			expr->access.object = obj;
    184 			break;
    185 		case O_TYPE:
    186 			if (type_dealias(obj->type)->storage != STORAGE_VOID) {
    187 				error(ctx, aexpr->loc, expr,
    188 					"Cannot use non-void type alias '%s' as constant",
    189 					identifier_unparse(&obj->type->alias.ident));
    190 				return;
    191 			}
    192 			expr->type = EXPR_CONSTANT;
    193 			expr->result = obj->type;
    194 			break;
    195 		case O_SCAN:
    196 			assert(0); // handled above
    197 		}
    198 		break;
    199 	case ACCESS_INDEX:
    200 		expr->access.array = xcalloc(1, sizeof(struct expression));
    201 		expr->access.index = xcalloc(1, sizeof(struct expression));
    202 		check_expression(ctx, aexpr->access.array, expr->access.array, NULL);
    203 		check_expression(ctx, aexpr->access.index, expr->access.index, &builtin_type_size);
    204 		const struct type *atype =
    205 			type_dereference(expr->access.array->result);
    206 		if (!atype) {
    207 			error(ctx, aexpr->access.array->loc, expr,
    208 				"Cannot dereference nullable pointer for indexing");
    209 			return;
    210 		}
    211 		atype = type_dealias(atype);
    212 		const struct type *itype =
    213 			type_dealias(expr->access.index->result);
    214 		if (atype->storage != STORAGE_ARRAY
    215 				&& atype->storage != STORAGE_SLICE) {
    216 			error(ctx, aexpr->access.array->loc, expr,
    217 				"Can only index into array or slice object, but got %s",
    218 				type_storage_unparse(atype->storage));
    219 			return;
    220 		}
    221 		if (atype->storage == STORAGE_SLICE
    222 				&& atype->array.members->storage == STORAGE_VOID) {
    223 			error(ctx, aexpr->access.array->loc, expr,
    224 				"Cannot use index into slice of void");
    225 			return;
    226 		}
    227 		if (!type_is_integer(itype)) {
    228 			error(ctx, aexpr->access.index->loc, expr,
    229 				"Cannot use non-integer %s type as slice/array index",
    230 				type_storage_unparse(itype->storage));
    231 			return;
    232 		}
    233 		expr->access.index = lower_implicit_cast(
    234 			&builtin_type_size, expr->access.index);
    235 		expr->result = type_store_lookup_with_flags(ctx->store,
    236 			atype->array.members, atype->flags | atype->array.members->flags);
    237 
    238 		// Compile-time bounds check
    239 		if (atype->storage == STORAGE_ARRAY
    240 				&& atype->array.length != SIZE_UNDEFINED) {
    241 			struct expression *evaled = xcalloc(1, sizeof(struct expression));
    242 			enum eval_result r = eval_expr(ctx, expr->access.index, evaled);
    243 			if (r == EVAL_OK) {
    244 				if (evaled->constant.uval >= atype->array.length) {
    245 					error(ctx, aexpr->loc, expr,
    246 						"Index must not be greater than array length");
    247 					free(evaled);
    248 					return;
    249 				}
    250 				expr->access.bounds_checked = true;
    251 			}
    252 			free(evaled);
    253 		}
    254 
    255 		break;
    256 	case ACCESS_FIELD:
    257 		expr->access._struct = xcalloc(1, sizeof(struct expression));
    258 		check_expression(ctx, aexpr->access._struct, expr->access._struct, NULL);
    259 		const struct type *stype =
    260 			type_dereference(expr->access._struct->result);
    261 		if (!stype) {
    262 			error(ctx, aexpr->access._struct->loc, expr,
    263 				"Cannot dereference nullable pointer for field selection");
    264 			return;
    265 		}
    266 		stype = type_dealias(stype);
    267 		if (stype->storage != STORAGE_STRUCT
    268 				&& stype->storage != STORAGE_UNION) {
    269 			error(ctx, aexpr->access._struct->loc, expr,
    270 				"Cannot select field from non-struct, non-union object");
    271 			return;
    272 		}
    273 		expr->access.field = type_get_field(stype, aexpr->access.field);
    274 		if (!expr->access.field) {
    275 			error(ctx, aexpr->access._struct->loc, expr,
    276 				"No such struct field '%s'", aexpr->access.field);
    277 			return;
    278 		}
    279 		expr->result = expr->access.field->type;
    280 		break;
    281 	case ACCESS_TUPLE:
    282 		expr->access.tuple = xcalloc(1, sizeof(struct expression));
    283 		struct expression *value = xcalloc(1, sizeof(struct expression));
    284 		check_expression(ctx, aexpr->access.tuple, expr->access.tuple, NULL);
    285 		check_expression(ctx, aexpr->access.value, value, NULL);
    286 		assert(value->type == EXPR_CONSTANT);
    287 
    288 		const struct type *ttype =
    289 			type_dereference(expr->access.tuple->result);
    290 		if (!ttype) {
    291 			error(ctx, aexpr->access.tuple->loc, expr,
    292 				"Cannot dereference nullable pointer for value selection");
    293 			return;
    294 		}
    295 		ttype = type_dealias(ttype);
    296 		if (ttype->storage != STORAGE_TUPLE) {
    297 			error(ctx, aexpr->access.tuple->loc, expr,
    298 				"Cannot select value from non-tuple object");
    299 			return;
    300 		}
    301 		if (!type_is_integer(value->result)) {
    302 			error(ctx, aexpr->access.tuple->loc, expr,
    303 				"Cannot use non-integer constant to select tuple value");
    304 			return;
    305 		}
    306 
    307 		expr->access.tvalue = type_get_value(ttype,
    308 			aexpr->access.value->constant.uval);
    309 		if (!expr->access.tvalue) {
    310 			error(ctx, aexpr->access.tuple->loc, expr,
    311 				"No such tuple value '%zu'",
    312 				aexpr->access.value->constant.uval);
    313 			return;
    314 		}
    315 		expr->access.tindex = aexpr->access.value->constant.uval;
    316 
    317 		expr->result = expr->access.tvalue->type;
    318 		break;
    319 	}
    320 }
    321 
    322 static void
    323 check_expr_alloc_init(struct context *ctx,
    324 	const struct ast_expression *aexpr,
    325 	struct expression *expr,
    326 	const struct type *hint)
    327 {
    328 	// alloc(initializer) case
    329 	int ptrflags = 0;
    330 	const struct type *inithint = NULL;
    331 	if (hint) {
    332 		const struct type *htype = type_dealias(hint);
    333 		switch (htype->storage) {
    334 		case STORAGE_POINTER:
    335 			inithint = htype->pointer.referent;
    336 			// TODO: Describe the use of pointer flags in the spec
    337 			ptrflags = htype->pointer.flags;
    338 			break;
    339 		case STORAGE_SLICE:
    340 			inithint = hint;
    341 			break;
    342 		case STORAGE_TAGGED:
    343 			// TODO
    344 			break;
    345 		default:
    346 			// The user's code is wrong here, but we'll let it fail
    347 			// later.
    348 			break;
    349 		}
    350 	}
    351 
    352 	check_expression(ctx, aexpr->alloc.init, expr->alloc.init, inithint);
    353 
    354 	const struct type *objtype = expr->alloc.init->result;
    355 	if (type_dealias(objtype)->storage == STORAGE_ARRAY
    356 			&& type_dealias(objtype)->array.expandable) {
    357 		const struct type *atype = type_dealias(objtype);
    358 		if (!inithint) {
    359 			error(ctx, aexpr->loc, expr,
    360 				"Cannot infer expandable array length without type hint");
    361 			return;
    362 		}
    363 		const struct type *htype = type_dealias(inithint);
    364 		if (htype->storage != STORAGE_ARRAY) {
    365 			error(ctx, aexpr->loc, expr,
    366 				"Cannot assign expandable array from non-array type");
    367 			return;
    368 		}
    369 		assert(htype->array.members == atype->array.members);
    370 		objtype = htype;
    371 	}
    372 	expr->result = type_store_lookup_pointer(ctx->store, aexpr->loc,
    373 			objtype, ptrflags);
    374 	if (expr->alloc.init->result->size == 0) {
    375 		error(ctx, aexpr->loc, expr,
    376 			"Cannot allocate object with size 0");
    377 		return;
    378 	}
    379 	if (expr->alloc.init->result->size == SIZE_UNDEFINED) {
    380 		error(ctx, aexpr->loc, expr,
    381 			"Cannot allocate object of undefined size");
    382 		return;
    383 	}
    384 }
    385 
    386 static void
    387 check_expr_alloc_slice(struct context *ctx,
    388 	const struct ast_expression *aexpr,
    389 	struct expression *expr,
    390 	const struct type *hint)
    391 {
    392 	// alloc(init, capacity) case
    393 	check_expression(ctx, aexpr->alloc.init, expr->alloc.init, hint);
    394 
    395 	const struct type *objtype = expr->alloc.init->result;
    396 	if (type_dealias(objtype)->storage == STORAGE_ARRAY) {
    397 		if (type_dealias(objtype)->array.length == SIZE_UNDEFINED) {
    398 			error(ctx, aexpr->alloc.init->loc, expr,
    399 				"Slice initializer must have defined length");
    400 			return;
    401 		}
    402 	} else if (type_dealias(objtype)->storage != STORAGE_SLICE) {
    403 		error(ctx, aexpr->alloc.init->loc, expr,
    404 			"Slice initializer must be of slice or array type, not %s",
    405 			type_storage_unparse(type_dealias(objtype)->storage));
    406 		return;
    407 	}
    408 
    409 	const struct type *caphint = &builtin_type_size;
    410 	expr->alloc.cap = xcalloc(1, sizeof(struct expression));
    411 	check_expression(ctx, aexpr->alloc.cap, expr->alloc.cap, caphint);
    412 
    413 	const struct type *captype = expr->alloc.cap->result;
    414 	if (!type_is_assignable(&builtin_type_size, captype)) {
    415 		error(ctx, aexpr->alloc.cap->loc, expr,
    416 			"Slice capacity must be assignable to size");
    417 		return;
    418 	}
    419 	expr->alloc.cap = lower_implicit_cast(&builtin_type_size, expr->alloc.cap);
    420 
    421 	struct expression cap = {0};
    422 	if (expr->alloc.init->type == EXPR_CONSTANT
    423 			&& expr->alloc.cap->type == EXPR_CONSTANT
    424 			&& eval_expr(ctx, expr->alloc.cap, &cap) == EVAL_OK) {
    425 		uintmax_t len = 0;
    426 		for (struct array_constant *c = expr->alloc.init->constant.array;
    427 				c != NULL; c = c->next) {
    428 			len++;
    429 		}
    430 		if (cap.constant.uval < len) {
    431 			error(ctx, aexpr->alloc.cap->loc, expr,
    432 				"Slice capacity cannot be smaller than length of initializer");
    433 			return;
    434 		}
    435 	}
    436 
    437 	const struct type *membtype = type_dealias(objtype)->array.members;
    438 	expr->result = type_store_lookup_slice(ctx->store,
    439 		aexpr->alloc.init->loc, membtype);
    440 
    441 	if (objtype->storage == STORAGE_ARRAY
    442 			&& objtype->array.expandable) {
    443 		expr->alloc.kind = ALLOC_WITH_LEN;
    444 	}
    445 }
    446 
    447 static void
    448 check_expr_alloc_copy(struct context *ctx,
    449 	const struct ast_expression *aexpr,
    450 	struct expression *expr,
    451 	const struct type *hint)
    452 {
    453 	// alloc(init...) case
    454 	check_expression(ctx, aexpr->alloc.init, expr->alloc.init, hint);
    455 
    456 	const struct type *result = type_dealias(expr->alloc.init->result);
    457 	if (result->storage != STORAGE_ARRAY
    458 			&& result->storage != STORAGE_SLICE) {
    459 		error(ctx, aexpr->alloc.init->loc, expr,
    460 			"Slice initializer must be of slice or array type, not %s",
    461 			type_storage_unparse(result->storage));
    462 		return;
    463 	}
    464 	if (hint) {
    465 		const struct type *htype = type_dealias(hint);
    466 		if (htype->storage != STORAGE_SLICE
    467 				&& htype->storage != STORAGE_TAGGED) {
    468 			error(ctx, aexpr->alloc.init->loc, expr,
    469 				"Hint must be a slice type, not %s",
    470 				type_storage_unparse(htype->storage));
    471 			return;
    472 		}
    473 	}
    474 
    475 	check_expression(ctx, aexpr->alloc.init, expr->alloc.init, hint);
    476 	result = type_dealias(expr->alloc.init->result);
    477 	expr->result = type_store_lookup_slice(ctx->store,
    478 			aexpr->alloc.init->loc, result->array.members);
    479 }
    480 
    481 static void
    482 check_expr_alloc(struct context *ctx,
    483 	const struct ast_expression *aexpr,
    484 	struct expression *expr,
    485 	const struct type *hint)
    486 {
    487 	assert(aexpr->type == EXPR_ALLOC);
    488 	expr->type = EXPR_ALLOC;
    489 	expr->alloc.init = xcalloc(1, sizeof(struct expression));
    490 	expr->alloc.kind = aexpr->alloc.kind;
    491 	switch (aexpr->alloc.kind) {
    492 	case ALLOC_OBJECT:
    493 		check_expr_alloc_init(ctx, aexpr, expr, hint);
    494 		break;
    495 	case ALLOC_WITH_CAP:
    496 		check_expr_alloc_slice(ctx, aexpr, expr, hint);
    497 		break;
    498 	case ALLOC_COPY:
    499 		check_expr_alloc_copy(ctx, aexpr, expr, hint);
    500 		break;
    501 	case ALLOC_WITH_LEN:
    502 		abort(); // Not determined by parse
    503 	}
    504 }
    505 
    506 static void
    507 check_expr_append_insert(struct context *ctx,
    508 	const struct ast_expression *aexpr,
    509 	struct expression *expr,
    510 	const struct type *hint)
    511 {
    512 	assert(aexpr->type == EXPR_APPEND || aexpr->type == EXPR_INSERT);
    513 	expr->loc = aexpr->loc;
    514 	expr->type = aexpr->type;
    515 	expr->result = &builtin_type_void;
    516 	expr->append.is_static = aexpr->append.is_static;
    517 	expr->append.is_multi = aexpr->append.is_multi;
    518 	expr->append.object = xcalloc(sizeof(struct expression), 1);
    519 	check_expression(ctx, aexpr->append.object, expr->append.object, NULL);
    520 	if (expr->append.object->type != EXPR_ACCESS) {
    521 		error(ctx, aexpr->append.object->loc, expr,
    522 			"Expression must operate on an object");
    523 		return;
    524 	};
    525 
    526 	const struct type *sltype;
    527 	const struct type *sltypename;
    528 	const char *exprtype_name;
    529 	switch (expr->type) {
    530 	case EXPR_APPEND:
    531 		sltypename = expr->append.object->result;
    532 		exprtype_name = "append";
    533 		break;
    534 	case EXPR_INSERT:
    535 		assert(expr->append.object->access.type == ACCESS_INDEX);
    536 		sltypename = expr->append.object->access.array->result;
    537 		exprtype_name = "insert";
    538 		break;
    539 	default:
    540 		abort(); // Invariant
    541 	}
    542 	sltype = type_dereference(sltypename);
    543 	if (!sltype) {
    544 		error(ctx, aexpr->access.tuple->loc, expr,
    545 			"Cannot dereference nullable pointer for %s expression",
    546 			exprtype_name);
    547 		return;
    548 	}
    549 	sltype = type_dealias(sltype);
    550 
    551 	if (sltype->storage != STORAGE_SLICE) {
    552 		char *typename = gen_typename(sltypename);
    553 		error(ctx, aexpr->append.object->loc, expr,
    554 			"%s expression must operate on a slice, but got %s",
    555 			exprtype_name, typename);
    556 		free(typename);
    557 		return;
    558 	}
    559 	if (sltype->flags & TYPE_CONST) {
    560 		error(ctx, aexpr->append.object->loc, expr,
    561 			"expression must operate on a mutable slice");
    562 		return;
    563 	}
    564 
    565 	expr->append.value = xcalloc(sizeof(struct expression), 1);
    566 
    567 	if (!expr->append.is_multi && !aexpr->append.length) {
    568 		check_expression(ctx, aexpr->append.value, expr->append.value,
    569 				sltype->array.members);
    570 		if (!type_is_assignable(sltype->array.members,
    571 				expr->append.value->result)) {
    572 			error(ctx, aexpr->append.value->loc, expr,
    573 				"Value type must be assignable to object member type");
    574 			return;
    575 		}
    576 		expr->append.value = lower_implicit_cast(
    577 			sltype->array.members, expr->append.value);
    578 		return;
    579 	}
    580 
    581 	check_expression(ctx, aexpr->append.value, expr->append.value, sltype);
    582 	const struct type *valtype = type_dereference(expr->append.value->result);
    583 	if (!valtype) {
    584 		error(ctx, aexpr->loc, expr,
    585 			"Cannot dereference nullable pointer for %s expression",
    586 			exprtype_name);
    587 		return;
    588 	}
    589 	valtype = type_dealias(valtype);
    590 	if (aexpr->append.length) {
    591 		if (valtype->storage != STORAGE_ARRAY
    592 				|| !valtype->array.expandable) {
    593 			error(ctx, aexpr->append.value->loc, expr,
    594 				"Value must be an expandable array in append with length");
    595 			return;
    596 		}
    597 		struct expression *len = xcalloc(sizeof(struct expression), 1);
    598 		check_expression(ctx, aexpr->append.length, len, &builtin_type_size);
    599 		if (!type_is_assignable(&builtin_type_size, len->result)) {
    600 			error(ctx, aexpr->append.length->loc, expr,
    601 				"Length parameter must be assignable to size");
    602 			return;
    603 		}
    604 		len = lower_implicit_cast(&builtin_type_size, len);
    605 		expr->append.length = len;
    606 	} else {
    607 		if (valtype->storage != STORAGE_SLICE
    608 				&& valtype->storage != STORAGE_ARRAY) {
    609 			error(ctx, aexpr->append.value->loc, expr,
    610 				"Value must be an array or a slice in multi-valued %s",
    611 				exprtype_name);
    612 			return;
    613 		}
    614 	}
    615 	if (sltype->array.members != valtype->array.members) {
    616 		error(ctx, aexpr->loc, expr,
    617 			"Value member type must match object member type");
    618 		return;
    619 	}
    620 }
    621 
    622 static void
    623 check_expr_assert(struct context *ctx,
    624 	const struct ast_expression *aexpr,
    625 	struct expression *expr,
    626 	const struct type *hint)
    627 {
    628 	expr->type = EXPR_ASSERT;
    629 	expr->result = &builtin_type_void;
    630 	expr->assert.is_static = aexpr->assert.is_static;
    631 
    632 	if (aexpr->assert.cond != NULL) {
    633 		expr->assert.cond = xcalloc(1, sizeof(struct expression));
    634 		check_expression(ctx, aexpr->assert.cond, expr->assert.cond, &builtin_type_bool);
    635 		if (type_dealias(expr->assert.cond->result)->storage != STORAGE_BOOL) {
    636 			error(ctx, aexpr->assert.cond->loc, expr,
    637 				"Assertion condition must be boolean");
    638 			return;
    639 		}
    640 	} else {
    641 		expr->terminates = true;
    642 	}
    643 
    644 	expr->assert.message = xcalloc(1, sizeof(struct expression));
    645 	if (aexpr->assert.message != NULL) {
    646 		check_expression(ctx, aexpr->assert.message, expr->assert.message, &builtin_type_str);
    647 		if (expr->assert.message->result->storage != STORAGE_STRING) {
    648 			error(ctx, aexpr->assert.message->loc, expr,
    649 				"Assertion message must be string");
    650 			return;
    651 		}
    652 
    653 		assert(expr->assert.message->type == EXPR_CONSTANT);
    654 		size_t n = snprintf(NULL, 0, "%s:%d:%d: ",
    655 			sources[aexpr->loc.file],
    656 			aexpr->loc.lineno, aexpr->loc.colno);
    657 		size_t s_len = expr->assert.message->constant.string.len;
    658 		char *s = xcalloc(1, n + s_len + 1);
    659 		snprintf(s, n + 1, "%s:%d:%d: ", sources[aexpr->loc.file],
    660 			aexpr->loc.lineno, aexpr->loc.colno);
    661 		memcpy(s+n, expr->assert.message->constant.string.value, s_len);
    662 		s[n + s_len] = '\0';
    663 
    664 		expr->assert.message->constant.string.value = s;
    665 		expr->assert.message->constant.string.len = n + s_len;
    666 	} else {
    667 		int n = snprintf(NULL, 0, "Assertion failed: %s:%d:%d",
    668 			sources[aexpr->loc.file],
    669 			aexpr->loc.lineno, aexpr->loc.colno);
    670 		char *s = xcalloc(1, n + 1);
    671 		snprintf(s, n, "Assertion failed: %s:%d:%d",
    672 			sources[aexpr->loc.file],
    673 			aexpr->loc.lineno, aexpr->loc.colno);
    674 
    675 		expr->assert.message->type = EXPR_CONSTANT;
    676 		expr->assert.message->result = &builtin_type_const_str;
    677 		expr->assert.message->constant.string.value = s;
    678 		expr->assert.message->constant.string.len = n - 1;
    679 	}
    680 
    681 	if (expr->assert.is_static) {
    682 		bool cond;
    683 		if (expr->assert.cond != NULL) {
    684 			struct expression out = {0};
    685 			enum eval_result r =
    686 				eval_expr(ctx, expr->assert.cond, &out);
    687 			if (r != EVAL_OK) {
    688 				error(ctx, aexpr->assert.cond->loc, expr,
    689 					"Unable to evaluate static assertion at compile time");
    690 				return;
    691 			}
    692 			assert(out.result->storage == STORAGE_BOOL);
    693 			cond = out.constant.bval;
    694 		} else {
    695 			cond = false;
    696 		}
    697 		// XXX: Should these abort immediately?
    698 		if (!cond) {
    699 			if (aexpr->assert.message != NULL) {
    700 				char format[40];
    701 				snprintf(format, 40, "Static assertion failed %%%zds",
    702 					expr->assert.message->constant.string.len);
    703 				if (aexpr->assert.cond == NULL) {
    704 					error(ctx, aexpr->loc, expr, format,
    705 						expr->assert.message->constant.string.value);
    706 					return;
    707 				} else {
    708 					error(ctx, aexpr->assert.cond->loc,
    709 						expr, format,
    710 						expr->assert.message->constant.string.value);
    711 					return;
    712 				};
    713 			} else {
    714 				error(ctx, aexpr->loc, expr,
    715 					"Static assertion failed");
    716 				return;
    717 			}
    718 		}
    719 	}
    720 }
    721 
    722 static void
    723 check_expr_assign(struct context *ctx,
    724 	const struct ast_expression *aexpr,
    725 	struct expression *expr,
    726 	const struct type *hint)
    727 {
    728 	expr->type = EXPR_ASSIGN;
    729 	expr->result = &builtin_type_void;
    730 	struct expression *object = xcalloc(1, sizeof(struct expression));
    731 	struct expression *value = xcalloc(1, sizeof(struct expression));
    732 
    733 	check_expression(ctx, aexpr->assign.object, object, NULL);
    734 
    735 	expr->assign.op = aexpr->assign.op;
    736 
    737 	check_expression(ctx, aexpr->assign.value, value, object->result);
    738 	if (object->type == EXPR_CONSTANT
    739 			&& object->result != &builtin_type_error) {
    740 		error(ctx, aexpr->assign.object->loc, expr,
    741 			"Cannot assign to constant");
    742 		return;
    743 	}
    744 
    745 	if (object->type == EXPR_SLICE) {
    746 		if (expr->assign.op != BIN_LEQUAL) {
    747 			error(ctx, aexpr->assign.object->loc, expr,
    748 				"Slice assignments may not have a binop");
    749 			return;
    750 		}
    751 	}
    752 	if (!type_is_assignable(object->result, value->result)) {
    753 		char *valtypename = gen_typename(value->result);
    754 		char *objtypename = gen_typename(object->result);
    755 		error(ctx, aexpr->loc, expr,
    756 			"rvalue type (%s) is not assignable to lvalue (%s)",
    757 			valtypename, objtypename);
    758 		free(valtypename);
    759 		free(objtypename);
    760 		return;
    761 	}
    762 	value = lower_implicit_cast(object->result, value);
    763 
    764 	expr->assign.object = object;
    765 	expr->assign.value = value;
    766 }
    767 
    768 static const struct type *
    769 type_promote(struct type_store *store,
    770 	const struct type *a,
    771 	const struct type *b)
    772 {
    773 	// Note: we must return either a, b, or NULL
    774 	// TODO: There are likely some improperly handled edge cases around type
    775 	// flags, both here and in the spec
    776 	const struct type *da = type_store_lookup_with_flags(store, a, 0);
    777 	const struct type *db = type_store_lookup_with_flags(store, b, 0);
    778 
    779 	if (da == db) {
    780 		const struct type *base = type_store_lookup_with_flags(store, a,
    781 			a->flags | b->flags);
    782 		assert(base == a || base == b);
    783 		return base;
    784 	}
    785 
    786 	if (a->storage == STORAGE_ALIAS && b->storage == STORAGE_ALIAS) {
    787 		return NULL;
    788 	}
    789 
    790 	da = type_dealias(da);
    791 	db = type_dealias(db);
    792 
    793 	if (da == db) {
    794 		return a->storage == STORAGE_ALIAS ? a : b;
    795 	}
    796 
    797 	if (type_is_constant(da) || type_is_constant(db)) {
    798 		return promote_const(a, b);
    799 	}
    800 
    801 	if (db->storage == STORAGE_ENUM && da->storage == db->alias.type->storage) {
    802 		return b;
    803 	}
    804 	switch (da->storage) {
    805 	case STORAGE_ARRAY:
    806 		if (da->array.length == SIZE_UNDEFINED && da->array.members) {
    807 			return b;
    808 		}
    809 		if (db->array.length == SIZE_UNDEFINED && db->array.members) {
    810 			return a;
    811 		}
    812 		return NULL;
    813 	case STORAGE_ENUM:
    814 		if (da->alias.type->storage == db->storage) {
    815 			return a;
    816 		}
    817 		return NULL;
    818 	case STORAGE_I8:
    819 	case STORAGE_I16:
    820 	case STORAGE_I32:
    821 	case STORAGE_I64:
    822 	case STORAGE_INT:
    823 		if (!type_is_integer(db) || !type_is_signed(db)
    824 				|| db->size == da->size) {
    825 			return NULL;
    826 		}
    827 		return da->size > db->size ? a : b;
    828 	case STORAGE_U32:
    829 	case STORAGE_U16:
    830 	case STORAGE_U64:
    831 	case STORAGE_UINT:
    832 	case STORAGE_SIZE:
    833 	case STORAGE_U8:
    834 	case STORAGE_CHAR:
    835 		if (!type_is_integer(db) || type_is_signed(db)
    836 				|| db->size == da->size) {
    837 			return NULL;
    838 		}
    839 		return da->size > db->size ? a : b;
    840 	case STORAGE_F32:
    841 	case STORAGE_F64:
    842 		if (!type_is_float(db) || db->size == da->size) {
    843 			return NULL;
    844 		}
    845 		return da->size > db->size ? a : b;
    846 	case STORAGE_POINTER:
    847 		if (db->storage == STORAGE_NULL) {
    848 			return a;
    849 		}
    850 		if (db->storage != STORAGE_POINTER) {
    851 			return NULL;
    852 		}
    853 		if (da->pointer.referent->storage == STORAGE_VOID ||
    854 				db->pointer.referent->storage == STORAGE_VOID) {
    855 			return a;
    856 		}
    857 		const struct type *r = type_promote(store,
    858 			da->pointer.referent, db->pointer.referent);
    859 		if (r == da->pointer.referent) {
    860 			return a;
    861 		}
    862 		if (r == db->pointer.referent) {
    863 			return b;
    864 		}
    865 		assert(r == NULL);
    866 		return NULL;
    867 	case STORAGE_NULL:
    868 		assert(db->storage != STORAGE_NULL);
    869 		if (db->storage == STORAGE_POINTER) {
    870 			return b;
    871 		}
    872 		return NULL;
    873 	case STORAGE_ERROR:
    874 		return b;
    875 	// Cannot be promoted
    876 	case STORAGE_BOOL:
    877 	case STORAGE_FUNCTION:
    878 	case STORAGE_RUNE:
    879 	case STORAGE_SLICE:
    880 	case STORAGE_STRING:
    881 	case STORAGE_STRUCT:
    882 	case STORAGE_TAGGED:
    883 	case STORAGE_TUPLE:
    884 	case STORAGE_UINTPTR:
    885 	case STORAGE_UNION:
    886 	case STORAGE_VALIST:
    887 	case STORAGE_VOID:
    888 		return NULL;
    889 	// Handled above
    890 	case STORAGE_ALIAS:
    891 	case STORAGE_FCONST:
    892 	case STORAGE_ICONST:
    893 	case STORAGE_RCONST:
    894 		assert(0);
    895 	}
    896 	assert(0);
    897 }
    898 
    899 static void
    900 check_expr_binarithm(struct context *ctx,
    901 	const struct ast_expression *aexpr,
    902 	struct expression *expr,
    903 	const struct type *hint)
    904 {
    905 	expr->type = EXPR_BINARITHM;
    906 	expr->binarithm.op = aexpr->binarithm.op;
    907 
    908 	enum {
    909 		BT_INVALID = -1,
    910 		BT_NUMERIC,
    911 		BT_INTEGER,
    912 		BT_LOGICAL,
    913 		BT_COMPARISON,
    914 		BT_EQUALITY,
    915 	} btype;
    916 
    917 	btype = BT_INVALID;
    918 
    919 	switch (expr->binarithm.op) {
    920 	// Numeric arithmetic
    921 	case BIN_DIV:
    922 	case BIN_MINUS:
    923 	case BIN_PLUS:
    924 	case BIN_TIMES:
    925 		btype = BT_NUMERIC;
    926 		break;
    927 	// Integer artithmetic
    928 	case BIN_BAND:
    929 	case BIN_BOR:
    930 	case BIN_LSHIFT:
    931 	case BIN_MODULO:
    932 	case BIN_RSHIFT:
    933 	case BIN_BXOR:
    934 		btype = BT_INTEGER;
    935 		break;
    936 	// Logical arithmetic
    937 	case BIN_LAND:
    938 	case BIN_LOR:
    939 	case BIN_LXOR:
    940 		btype = BT_LOGICAL;
    941 		hint = NULL;
    942 		break;
    943 	case BIN_GREATER:
    944 	case BIN_GREATEREQ:
    945 	case BIN_LESS:
    946 	case BIN_LESSEQ:
    947 		btype = BT_COMPARISON;
    948 		hint = NULL;
    949 		break;
    950 	case BIN_LEQUAL:
    951 	case BIN_NEQUAL:
    952 		btype = BT_EQUALITY;
    953 		hint = NULL;
    954 		break;
    955 	}
    956 
    957 	struct expression *lvalue = xcalloc(1, sizeof(struct expression)),
    958 		*rvalue = xcalloc(1, sizeof(struct expression));
    959 	struct ast_expression *alvalue = aexpr->binarithm.lvalue,
    960 		*arvalue = aexpr->binarithm.rvalue;
    961 	// XXX: Should hints be passed down?
    962 	(void)hint;
    963 	check_expression(ctx, alvalue, lvalue, NULL);
    964 	check_expression(ctx, arvalue, rvalue, NULL);
    965 
    966 	const struct type *p =
    967 		type_promote(ctx->store, lvalue->result, rvalue->result);
    968 	if (p == NULL) {
    969 		char *ltypename = gen_typename(lvalue->result);
    970 		char *rtypename = gen_typename(rvalue->result);
    971 		error(ctx, aexpr->loc, expr,
    972 			"Cannot promote lvalue %s and rvalue %s",
    973 			ltypename, rtypename);
    974 		free(ltypename);
    975 		free(rtypename);
    976 		return;
    977 	}
    978 	expr->result = &builtin_type_bool;
    979 	switch (btype) {
    980 	case BT_NUMERIC:
    981 		if (!type_is_numeric(p)) {
    982 			error(ctx, aexpr->loc, expr,
    983 				"Cannot perform arithmetic on non-numeric %s type",
    984 				type_storage_unparse(type_dealias(p)->storage));
    985 			return;
    986 		}
    987 		expr->result = p;
    988 		break;
    989 	case BT_INTEGER:
    990 		if (!type_is_integer(p)) {
    991 			error(ctx, aexpr->loc, expr,
    992 				"Cannot perform operation on non-integer %s type",
    993 				type_storage_unparse(type_dealias(p)->storage));
    994 			return;
    995 		}
    996 		expr->result = p;
    997 		break;
    998 	case BT_LOGICAL:
    999 		if (type_dealias(p)->storage != STORAGE_BOOL) {
   1000 			error(ctx, aexpr->loc, expr,
   1001 				"Cannot perform logical arithmetic on non-bool %s type",
   1002 				type_storage_unparse(type_dealias(p)->storage));
   1003 			return;
   1004 		}
   1005 		break;
   1006 	case BT_COMPARISON:
   1007 		if (!type_is_numeric(p)) {
   1008 			error(ctx, aexpr->loc, expr,
   1009 				"Cannot perform comparison on non-numeric %s type",
   1010 				type_storage_unparse(type_dealias(p)->storage));
   1011 			return;
   1012 		}
   1013 		break;
   1014 	case BT_EQUALITY:
   1015 		if (!type_is_numeric(p) && type_dealias(p)->storage != STORAGE_POINTER
   1016 				&& type_dealias(p)->storage != STORAGE_STRING
   1017 				&& type_dealias(p)->storage != STORAGE_BOOL
   1018 				&& type_dealias(p)->storage != STORAGE_RCONST
   1019 				&& type_dealias(p)->storage != STORAGE_RUNE) {
   1020 			error(ctx, aexpr->loc, expr,
   1021 				"Cannot perform equality test on %s type",
   1022 				type_storage_unparse(type_dealias(p)->storage));
   1023 			return;
   1024 		}
   1025 		break;
   1026 	case BT_INVALID:
   1027 		abort();
   1028 		break;
   1029 	}
   1030 	lvalue = lower_implicit_cast(p, lvalue);
   1031 	rvalue = lower_implicit_cast(p, rvalue);
   1032 
   1033 	expr->binarithm.lvalue = lvalue;
   1034 	expr->binarithm.rvalue = rvalue;
   1035 }
   1036 
   1037 static void
   1038 check_binding_unpack(struct context *ctx,
   1039 	const struct type *type,
   1040 	const struct ast_expression_binding *abinding,
   1041 	struct expression_binding *binding,
   1042 	const struct ast_expression *aexpr,
   1043 	struct expression *expr)
   1044 {
   1045 	assert(abinding->unpack);
   1046 	const struct ast_binding_unpack *cur = abinding->unpack;
   1047 	binding->unpack = xcalloc(1, sizeof(struct binding_unpack));
   1048 	struct binding_unpack *unpack = binding->unpack;
   1049 
   1050 	struct expression *initializer = xcalloc(1, sizeof(struct expression));
   1051 	check_expression(ctx, abinding->initializer, initializer, type);
   1052 	if (type_dealias(initializer->result)->storage != STORAGE_TUPLE) {
   1053 		error(ctx, aexpr->loc, expr, "Could not unpack non-tuple type");
   1054 		return;
   1055 	}
   1056 
   1057 	if (!type) {
   1058 		type = type_store_lookup_with_flags(
   1059 			ctx->store, initializer->result, abinding->flags);
   1060 	}
   1061 	type = type_dealias(type);
   1062 
   1063 	binding->initializer = lower_implicit_cast(type, initializer);
   1064 
   1065 	if (abinding->is_static) {
   1066 		struct expression *value = xcalloc(1, sizeof(struct expression));
   1067 		enum eval_result r = eval_expr(ctx, binding->initializer, value);
   1068 		if (r != EVAL_OK) {
   1069 			error(ctx, abinding->initializer->loc,
   1070 				expr,
   1071 				"Unable to evaluate static initializer at compile time");
   1072 			return;
   1073 		}
   1074 		// TODO: Free initializer
   1075 		binding->initializer = value;
   1076 		assert(binding->initializer->type == EXPR_CONSTANT);
   1077 	}
   1078 
   1079 	if (type->storage != STORAGE_TUPLE) {
   1080 		error(ctx, abinding->initializer->loc, expr,
   1081 			"Unable to unpack tuple with non-tuple type specifier");
   1082 		return;
   1083 	}
   1084 	const struct type_tuple *type_tuple = &type->tuple;
   1085 	bool found_binding = false;
   1086 	while (cur && type_tuple) {
   1087 		if (type_tuple->type->storage == STORAGE_NULL) {
   1088 			error(ctx, aexpr->loc, expr,
   1089 				"Null is not a valid type for a binding");
   1090 			return;
   1091 		}
   1092 
   1093 		if (cur->name) {
   1094 			struct identifier ident = {
   1095 				.name = cur->name,
   1096 			};
   1097 
   1098 			if (abinding->is_static) {
   1099 				struct identifier gen = {0};
   1100 
   1101 				// Generate a static declaration identifier
   1102 				gen.name = gen_name(&ctx->id, "static.%d");
   1103 
   1104 				unpack->object = scope_insert(
   1105 					ctx->scope, O_DECL, &gen, &ident,
   1106 					type_tuple->type, NULL);
   1107 			} else {
   1108 				unpack->object = scope_insert(
   1109 					ctx->scope, O_BIND, &ident, &ident,
   1110 					type_tuple->type, NULL);
   1111 			}
   1112 
   1113 			unpack->offset = type_tuple->offset;
   1114 
   1115 			found_binding = true;
   1116 		}
   1117 
   1118 		cur = cur->next;
   1119 		type_tuple = type_tuple->next;
   1120 
   1121 		if (cur && found_binding && cur->name) {
   1122 			unpack->next = xcalloc(1, sizeof(struct binding_unpack));
   1123 			unpack = unpack->next;
   1124 		}
   1125 	}
   1126 
   1127 	if (!found_binding) {
   1128 		error(ctx, aexpr->loc, expr,
   1129 			"Must have at least one non-underscore value when unpacking tuples");
   1130 		return;
   1131 	}
   1132 
   1133 	if (type_tuple) {
   1134 		error(ctx, aexpr->loc, expr,
   1135 			"Fewer bindings than tuple elements were provided when unpacking");
   1136 		return;
   1137 	}
   1138 	if (cur) {
   1139 		error(ctx, aexpr->loc, expr,
   1140 			"More bindings than tuple elements were provided when unpacking");
   1141 		return;
   1142 	}
   1143 }
   1144 
   1145 static void
   1146 check_expr_binding(struct context *ctx,
   1147 	const struct ast_expression *aexpr,
   1148 	struct expression *expr,
   1149 	const struct type *hint)
   1150 {
   1151 	expr->type = EXPR_BINDING;
   1152 	expr->result = &builtin_type_void;
   1153 
   1154 	struct expression_binding *binding = &expr->binding;
   1155 	struct expression_binding **next = &expr->binding.next;
   1156 
   1157 	const struct ast_expression_binding *abinding = &aexpr->binding;
   1158 	while (abinding) {
   1159 		const struct type *type = NULL;
   1160 		if (abinding->type) {
   1161 			type = type_store_lookup_atype(
   1162 				ctx->store, abinding->type);
   1163 			type = type_store_lookup_with_flags(ctx->store,
   1164 				type, type->flags | abinding->flags);
   1165 		}
   1166 
   1167 		if (abinding->unpack) {
   1168 			check_binding_unpack(ctx, type, abinding, binding,
   1169 				aexpr, expr);
   1170 			goto done;
   1171 		}
   1172 
   1173 		struct expression *initializer =
   1174 			xcalloc(1, sizeof(struct expression));
   1175 		check_expression(ctx, abinding->initializer, initializer, type);
   1176 
   1177 		if (abinding->type
   1178 				&& abinding->type->storage == STORAGE_ARRAY
   1179 				&& abinding->type->array.contextual) {
   1180 			if (initializer->result->storage != STORAGE_ARRAY) {
   1181 				error(ctx, aexpr->loc, expr,
   1182 					"Cannot infer array length from non-array type");
   1183 				return;
   1184 			}
   1185 			if (initializer->result->array.members
   1186 					!= type->array.members) {
   1187 				error(ctx, aexpr->loc, expr,
   1188 					"Initializer is not assignable to binding type");
   1189 				return;
   1190 			}
   1191 			type = initializer->result;
   1192 		}
   1193 
   1194 		if (!type) {
   1195 			type = type_store_lookup_with_flags(ctx->store,
   1196 				initializer->result, abinding->flags);
   1197 		}
   1198 
   1199 		struct identifier ident = {
   1200 			.name = abinding->name,
   1201 		};
   1202 		if (abinding->is_static) {
   1203 			// Generate a static declaration identifier
   1204 			struct identifier gen = {0};
   1205 			gen.name = gen_name(&ctx->id, "static.%d");
   1206 			binding->object = scope_insert(ctx->scope,
   1207 				O_DECL, &gen, &ident, type, NULL);
   1208 		} else {
   1209 			binding->object = scope_insert(ctx->scope,
   1210 				O_BIND, &ident, &ident, type, NULL);
   1211 		}
   1212 
   1213 		if (type->storage == STORAGE_NULL) {
   1214 			error(ctx, aexpr->loc, expr,
   1215 				"Null is not a valid type for a binding");
   1216 			return;
   1217 		}
   1218 		if (!type_is_assignable(type, initializer->result)) {
   1219 			error(ctx, aexpr->loc, expr,
   1220 				"Initializer is not assignable to binding type");
   1221 			return;
   1222 		}
   1223 		// XXX: Can we avoid this?
   1224 		type = lower_const(type, NULL);
   1225 		if (type->size == 0 || type->size == SIZE_UNDEFINED) {
   1226 			error(ctx, aexpr->loc, expr,
   1227 				"Cannot create binding for type of zero or undefined size");
   1228 			return;
   1229 		}
   1230 		binding->initializer = lower_implicit_cast(type, initializer);
   1231 
   1232 		if (abinding->is_static) {
   1233 			struct expression *value =
   1234 				xcalloc(1, sizeof(struct expression));
   1235 			enum eval_result r = eval_expr(
   1236 				ctx, binding->initializer, value);
   1237 			if (r != EVAL_OK) {
   1238 				error(ctx, abinding->initializer->loc, expr,
   1239 					"Unable to evaluate static initializer at compile time");
   1240 				return;
   1241 			}
   1242 			// TODO: Free initializer
   1243 			binding->initializer = value;
   1244 		}
   1245 
   1246 done:
   1247 		if (abinding->next) {
   1248 			binding = *next =
   1249 				xcalloc(1, sizeof(struct expression_binding));
   1250 			next = &binding->next;
   1251 		}
   1252 
   1253 		abinding = abinding->next;
   1254 	}
   1255 }
   1256 
   1257 // Lower Hare-style variadic arguments into an array literal
   1258 static void
   1259 lower_vaargs(struct context *ctx,
   1260 	const struct ast_call_argument *aarg,
   1261 	struct expression *vaargs,
   1262 	const struct type *type)
   1263 {
   1264 	struct ast_expression val = {
   1265 		.type = EXPR_CONSTANT,
   1266 		.constant = {
   1267 			.storage = STORAGE_ARRAY,
   1268 		},
   1269 	};
   1270 	// TODO: Provide location some other way
   1271 	if (aarg) {
   1272 		val.loc = aarg->value->loc;
   1273 	}
   1274 	struct ast_array_constant **next = &val.constant.array;
   1275 	while (aarg) {
   1276 		struct ast_array_constant *item = *next =
   1277 			xcalloc(1, sizeof(struct ast_array_constant));
   1278 		item->value = aarg->value;
   1279 		aarg = aarg->next;
   1280 		next = &item->next;
   1281 	}
   1282 
   1283 	// XXX: This error handling is minimum-effort and bad
   1284 	const struct type *hint = type_store_lookup_array(ctx->store,
   1285 			val.loc, type, SIZE_UNDEFINED, false);
   1286 	check_expression(ctx, &val, vaargs, hint);
   1287 	if (vaargs->result->storage != STORAGE_ARRAY
   1288 			|| vaargs->result->array.members != type) {
   1289 		error(ctx, val.loc, vaargs,
   1290 			"Argument is not assignable to variadic parameter type");
   1291 		return;
   1292 	}
   1293 
   1294 	struct ast_array_constant *item = val.constant.array;
   1295 	while (item) {
   1296 		struct ast_array_constant *next = item->next;
   1297 		free(item);
   1298 		item = next;
   1299 	}
   1300 }
   1301 
   1302 static void
   1303 check_expr_call(struct context *ctx,
   1304 	const struct ast_expression *aexpr,
   1305 	struct expression *expr,
   1306 	const struct type *hint)
   1307 {
   1308 	expr->type = EXPR_CALL;
   1309 
   1310 	struct expression *lvalue = xcalloc(1, sizeof(struct expression));
   1311 	check_expression(ctx, aexpr->call.lvalue, lvalue, NULL);
   1312 	expr->call.lvalue = lvalue;
   1313 
   1314 	const struct type *fntype = type_dereference(lvalue->result);
   1315 	if (!fntype) {
   1316 		error(ctx, aexpr->loc, expr,
   1317 			"Cannot dereference nullable pointer type for function call");
   1318 		return;
   1319 	}
   1320 	fntype = type_dealias(fntype);
   1321 	if (fntype->storage != STORAGE_FUNCTION) {
   1322 		error(ctx, aexpr->loc, expr,
   1323 			"Cannot call non-function type");
   1324 		return;
   1325 	}
   1326 	expr->result = fntype->func.result;
   1327 	if (fntype->func.flags & FN_NORETURN) {
   1328 		expr->terminates = true;
   1329 	}
   1330 
   1331 	struct call_argument *arg, **next = &expr->call.args;
   1332 	struct ast_call_argument *aarg = aexpr->call.args;
   1333 	struct type_func_param *param = fntype->func.params;
   1334 	while ((param || fntype->func.variadism == VARIADISM_C) && aarg) {
   1335 		arg = *next = xcalloc(1, sizeof(struct call_argument));
   1336 		arg->value = xcalloc(1, sizeof(struct expression));
   1337 
   1338 		if (param && !param->next
   1339 				&& fntype->func.variadism == VARIADISM_HARE
   1340 				&& !aarg->variadic) {
   1341 			lower_vaargs(ctx, aarg, arg->value,
   1342 				param->type->array.members);
   1343 			arg->value = lower_implicit_cast(param->type, arg->value);
   1344 			param = NULL;
   1345 			aarg = NULL;
   1346 			break;
   1347 		}
   1348 
   1349 		const struct type *ptype = NULL;
   1350 		if (param) {
   1351 			ptype = param->type;
   1352 		}
   1353 		check_expression(ctx, aarg->value, arg->value, ptype);
   1354 
   1355 		if (param) {
   1356 			if (!type_is_assignable(ptype, arg->value->result)) {
   1357 				char *argtypename = gen_typename(arg->value->result);
   1358 				char *paramtypename = gen_typename(param->type);
   1359 				error(ctx, aarg->value->loc, expr,
   1360 					"Argument type %s is not assignable to parameter type %s",
   1361 					argtypename, paramtypename);
   1362 				free(argtypename);
   1363 				free(paramtypename);
   1364 				return;
   1365 			}
   1366 			arg->value = lower_implicit_cast(ptype, arg->value);
   1367 		}
   1368 
   1369 		aarg = aarg->next;
   1370 		next = &arg->next;
   1371 		if (param) {
   1372 			param = param->next;
   1373 		}
   1374 	}
   1375 
   1376 	if (param && !param->next && fntype->func.variadism == VARIADISM_HARE) {
   1377 		// No variadic arguments, lower to empty slice
   1378 		arg = *next = xcalloc(1, sizeof(struct call_argument));
   1379 		arg->value = xcalloc(1, sizeof(struct expression));
   1380 		lower_vaargs(ctx, NULL, arg->value,
   1381 			param->type->array.members);
   1382 		arg->value = lower_implicit_cast(param->type, arg->value);
   1383 		param = param->next;
   1384 	}
   1385 
   1386 	if (aarg && fntype->func.variadism != VARIADISM_C) {
   1387 		error(ctx, aexpr->loc, expr,
   1388 			"Too many parameters for function call");
   1389 		return;
   1390 	}
   1391 	if (param) {
   1392 		error(ctx, aexpr->loc, expr,
   1393 			"Not enough parameters for function call");
   1394 		return;
   1395 	}
   1396 
   1397 }
   1398 
   1399 static void
   1400 check_expr_cast(struct context *ctx,
   1401 	const struct ast_expression *aexpr,
   1402 	struct expression *expr,
   1403 	const struct type *hint)
   1404 {
   1405 	expr->type = EXPR_CAST;
   1406 	expr->cast.kind = aexpr->cast.kind;
   1407 	struct expression *value = expr->cast.value =
   1408 		xcalloc(1, sizeof(struct expression));
   1409 	const struct type *secondary = expr->cast.secondary =
   1410 		type_store_lookup_atype(ctx->store, aexpr->cast.type);
   1411 	// TODO: Instead of allowing errors on casts to void, we should use a
   1412 	// different nonterminal
   1413 	check_expression(ctx, aexpr->cast.value, value,
   1414 			secondary == &builtin_type_void ? NULL : secondary);
   1415 	if (value->terminates) {
   1416 		error(ctx, aexpr->cast.value->loc, expr,
   1417 			"Cast must not operate on terminating expression");
   1418 		return;
   1419 	}
   1420 
   1421 	const struct type *primary = type_dealias(expr->cast.value->result);
   1422 	switch (aexpr->cast.kind) {
   1423 	case C_ASSERTION:
   1424 	case C_TEST:
   1425 		if (primary->storage == STORAGE_POINTER) {
   1426 			if (!(primary->pointer.flags & PTR_NULLABLE)) {
   1427 				error(ctx, aexpr->cast.value->loc, expr,
   1428 					"Expected a tagged union type or "
   1429 					"a nullable pointer");
   1430 				return;
   1431 			}
   1432 			if (secondary->storage != STORAGE_NULL
   1433 					&& (secondary->storage != STORAGE_POINTER
   1434 					|| primary->pointer.referent
   1435 						!= secondary->pointer.referent
   1436 					|| (secondary->pointer.flags & PTR_NULLABLE))) {
   1437 				error(ctx, aexpr->cast.type->loc, expr,
   1438 					"Can only type assert nullable pointer into non-nullable pointer of the same type or null");
   1439 				return;
   1440 			}
   1441 			break;
   1442 		}
   1443 		if (primary->storage != STORAGE_TAGGED) {
   1444 			error(ctx, aexpr->cast.value->loc, expr,
   1445 				"Expected a tagged union type or "
   1446 				"a nullable pointer");
   1447 			return;
   1448 		}
   1449 		// secondary type must be a strict subset or a
   1450 		// member of the primary type
   1451 		if (!((tagged_subset_compat(primary, secondary)
   1452 				|| tagged_select_subtype(primary, secondary, true))
   1453 				&& !tagged_subset_compat(secondary, primary))) {
   1454 			error(ctx, aexpr->cast.type->loc, expr,
   1455 				"Type is not a valid member of "
   1456 				"the tagged union type");
   1457 			return;
   1458 		}
   1459 		break;
   1460 	case C_CAST:;
   1461 		const struct type *intermediary =
   1462 			type_is_castable(secondary, value->result);
   1463 		if (intermediary == NULL) {
   1464 			char *primarytypename = gen_typename(value->result);
   1465 			char *secondarytypename = gen_typename(secondary);
   1466 			error(ctx, aexpr->cast.type->loc, expr,
   1467 				"Invalid cast from %s to %s",
   1468 				primarytypename, secondarytypename);
   1469 			free(primarytypename);
   1470 			free(secondarytypename);
   1471 			return;
   1472 		}
   1473 		// intermediary type is required when casting to tagged union
   1474 		// whose member is an alias of primary type, since gen.c asserts
   1475 		// that the primary type is a direct member of the tagged union.
   1476 		// The value is first cast to an intermediary type which is a
   1477 		// direct member of the tagged union, before being cast to the
   1478 		// tagged union itself.
   1479 		expr->cast.value = xcalloc(1, sizeof(struct expression));
   1480 		expr->cast.value->type = EXPR_CAST;
   1481 		expr->cast.value->result = intermediary;
   1482 		expr->cast.value->cast.kind = C_CAST;
   1483 		expr->cast.value->cast.value = value;
   1484 		expr->cast.value->cast.secondary = intermediary;
   1485 		if (value->result->storage == STORAGE_RCONST) {
   1486 			uint32_t max = 0;
   1487 			switch (secondary->storage) {
   1488 			case STORAGE_RUNE:
   1489 			case STORAGE_U64:
   1490 			case STORAGE_I64:
   1491 			case STORAGE_U32:
   1492 			case STORAGE_UINT:
   1493 			case STORAGE_SIZE:
   1494 			case STORAGE_UINTPTR:
   1495 				break;
   1496 			case STORAGE_I32:
   1497 				max = INT32_MAX;
   1498 				break;
   1499 			case STORAGE_U16:
   1500 				max = UINT16_MAX;
   1501 				break;
   1502 			case STORAGE_I16:
   1503 				max = INT16_MAX;
   1504 				break;
   1505 			case STORAGE_U8:
   1506 				max = UINT8_MAX;
   1507 				break;
   1508 			case STORAGE_I8:
   1509 				max = INT8_MAX;
   1510 				break;
   1511 			default:
   1512 				assert(0); // Invariant
   1513 			}
   1514 
   1515 			if (max != 0 && value->constant.rune > max) {
   1516 				char *typename = gen_typename(secondary);
   1517 				error(ctx, aexpr->cast.type->loc, expr,
   1518 					"Rune does not fit in %s",
   1519 					typename);
   1520 				free(typename);
   1521 				return;
   1522 			}
   1523 		}
   1524 		break;
   1525 	}
   1526 	expr->result = aexpr->cast.kind == C_TEST? &builtin_type_bool : secondary;
   1527 }
   1528 
   1529 static void
   1530 check_expr_array(struct context *ctx,
   1531 	const struct ast_expression *aexpr,
   1532 	struct expression *expr,
   1533 	const struct type *hint)
   1534 {
   1535 	size_t len = 0;
   1536 	bool expand = false;
   1537 	struct ast_array_constant *item = aexpr->constant.array;
   1538 	struct array_constant *cur, **next = &expr->constant.array;
   1539 	const struct type *type = NULL;
   1540 	if (hint) {
   1541 		hint = type_dealias(hint);
   1542 
   1543 		size_t narray = 0;
   1544 		switch (hint->storage) {
   1545 		case STORAGE_ARRAY:
   1546 		case STORAGE_SLICE:
   1547 			type = hint->array.members;
   1548 			break;
   1549 		case STORAGE_TAGGED:
   1550 			for (const struct type_tagged_union *tu = &hint->tagged;
   1551 					tu; tu = tu->next) {
   1552 				const struct type *t = type_dealias(tu->type);
   1553 				if (t->storage == STORAGE_ARRAY
   1554 						|| t->storage == STORAGE_SLICE) {
   1555 					hint = t;
   1556 					type = hint->array.members;
   1557 					++narray;
   1558 				}
   1559 			}
   1560 			if (narray != 1) {
   1561 				type = hint = NULL;
   1562 			}
   1563 			break;
   1564 		default:
   1565 			hint = NULL;
   1566 			break;
   1567 		}
   1568 	}
   1569 
   1570 	while (item) {
   1571 		struct expression *value = xcalloc(1, sizeof(struct expression));
   1572 		check_expression(ctx, item->value, value, type);
   1573 		cur = *next = xcalloc(1, sizeof(struct array_constant));
   1574 		cur->value = value;
   1575 
   1576 		if (!type) {
   1577 			type = value->result;
   1578 		} else {
   1579 			if (!hint) {
   1580 				// The promote_const in
   1581 				// check_expression_constant might've caused the
   1582 				// type to change out from under our feet
   1583 				type = expr->constant.array->value->result;
   1584 			}
   1585 			if (!type_is_assignable(type, value->result)) {
   1586 				char *typename1 = gen_typename(type);
   1587 				char *typename2 = gen_typename(value->result);
   1588 				error(ctx, item->value->loc, expr,
   1589 					"Array members must be of a uniform type, previously seen %s, but now see %s",
   1590 					typename1, typename2);
   1591 				free(typename1);
   1592 				free(typename2);
   1593 				return;
   1594 			}
   1595 			if (!hint) {
   1596 				// Ditto
   1597 				type = expr->constant.array->value->result;
   1598 			}
   1599 			cur->value = lower_implicit_cast(type, cur->value);
   1600 		}
   1601 
   1602 		if (item->expand) {
   1603 			expand = true;
   1604 			assert(!item->next);
   1605 		}
   1606 
   1607 		item = item->next;
   1608 		next = &cur->next;
   1609 		++len;
   1610 	}
   1611 
   1612 	if (type == NULL) {
   1613 		error(ctx, aexpr->loc, expr, "Cannot infer array type from context, try casting it to the desired type");
   1614 		return;
   1615 	}
   1616 	expr->result = type_store_lookup_array(ctx->store, aexpr->loc,
   1617 			type, len, expand);
   1618 }
   1619 
   1620 static void
   1621 check_expr_compound(struct context *ctx,
   1622 	const struct ast_expression *aexpr,
   1623 	struct expression *expr,
   1624 	const struct type *hint)
   1625 {
   1626 	expr->type = EXPR_COMPOUND;
   1627 
   1628 	struct scope *scope = scope_push(&ctx->scope, SCOPE_COMPOUND);
   1629 	scope->hint = hint;
   1630 	expr->compound.scope = scope;
   1631 
   1632 	if (aexpr->compound.label) {
   1633 		expr->compound.label = xstrdup(aexpr->compound.label);
   1634 		scope->label = xstrdup(aexpr->compound.label);
   1635 	}
   1636 
   1637 	struct expressions *list = &expr->compound.exprs;
   1638 	struct expressions **next = &list->next;
   1639 
   1640 	const struct ast_expression_list *alist = &aexpr->compound.list;
   1641 	struct expression *lexpr = NULL;
   1642 	while (alist) {
   1643 		lexpr = xcalloc(1, sizeof(struct expression));
   1644 		check_expression(ctx, alist->expr, lexpr, &builtin_type_void);
   1645 		list->expr = lexpr;
   1646 
   1647 		alist = alist->next;
   1648 		if (alist) {
   1649 			*next = xcalloc(1, sizeof(struct expressions));
   1650 			list = *next;
   1651 			next = &list->next;
   1652 		}
   1653 		if (alist && lexpr->terminates) {
   1654 			error(ctx, alist->expr->loc, expr,
   1655 				"A terminating expression may not be followed by additional expressions");
   1656 		}
   1657 	}
   1658 
   1659 	expr->terminates = false;
   1660 	if (lexpr->terminates && scope->yields == NULL) {
   1661 		expr->terminates = true;
   1662 		if (lexpr->type == EXPR_YIELD) {
   1663 			const char *llabel = lexpr->control.label;
   1664 			if (!llabel || (scope->label
   1665 					&& strcmp(llabel, scope->label) == 0)) {
   1666 				expr->terminates = false;
   1667 			}
   1668 		}
   1669 	}
   1670 	expr->result = type_store_reduce_result(ctx->store, aexpr->loc,
   1671 			scope->results);
   1672 
   1673 	for (struct yield *yield = scope->yields; yield;) {
   1674 		struct expression *lowered = lower_implicit_cast(
   1675 				expr->result, *yield->expression);
   1676 		if (*yield->expression != lowered) {
   1677 			*yield->expression = lowered;
   1678 		}
   1679 
   1680 		struct yield *next = yield->next;
   1681 		free(yield);
   1682 		yield = next;
   1683 	}
   1684 
   1685 	assert(expr->result);
   1686 	scope_pop(&ctx->scope);
   1687 }
   1688 
   1689 static void
   1690 check_expr_constant(struct context *ctx,
   1691 	const struct ast_expression *aexpr,
   1692 	struct expression *expr,
   1693 	const struct type *hint)
   1694 {
   1695 	expr->type = EXPR_CONSTANT;
   1696 	enum type_storage storage = aexpr->constant.storage;
   1697 	expr->result = builtin_type_for_storage(storage, false);
   1698 	if (storage == STORAGE_ICONST || storage == STORAGE_FCONST
   1699 			|| storage == STORAGE_RCONST) {
   1700 		expr->result = type_create_const(storage,
   1701 			aexpr->constant.ival, aexpr->constant.ival);
   1702 	}
   1703 
   1704 	switch (aexpr->constant.storage) {
   1705 	case STORAGE_I8:
   1706 	case STORAGE_I16:
   1707 	case STORAGE_I32:
   1708 	case STORAGE_I64:
   1709 	case STORAGE_ICONST:
   1710 	case STORAGE_INT:
   1711 		expr->constant.ival = aexpr->constant.ival;
   1712 		break;
   1713 	case STORAGE_U8:
   1714 	case STORAGE_U16:
   1715 	case STORAGE_U32:
   1716 	case STORAGE_U64:
   1717 	case STORAGE_UINT:
   1718 	case STORAGE_SIZE:
   1719 		expr->constant.uval = aexpr->constant.uval;
   1720 		break;
   1721 	case STORAGE_RCONST:
   1722 		expr->constant.rune = aexpr->constant.rune;
   1723 		break;
   1724 	case STORAGE_BOOL:
   1725 		expr->constant.bval = aexpr->constant.bval;
   1726 		break;
   1727 	case STORAGE_NULL:
   1728 	case STORAGE_VOID:
   1729 		// No storage
   1730 		break;
   1731 	case STORAGE_ARRAY:
   1732 		check_expr_array(ctx, aexpr, expr, hint);
   1733 		break;
   1734 	case STORAGE_STRING:
   1735 		expr->constant.string.len = aexpr->constant.string.len;
   1736 		expr->constant.string.value = xcalloc(1, aexpr->constant.string.len);
   1737 		memcpy(expr->constant.string.value, aexpr->constant.string.value,
   1738 			aexpr->constant.string.len);
   1739 		break;
   1740 	case STORAGE_F32:
   1741 	case STORAGE_F64:
   1742 	case STORAGE_FCONST:
   1743 		expr->constant.fval = aexpr->constant.fval;
   1744 		break;
   1745 	case STORAGE_CHAR:
   1746 	case STORAGE_ENUM:
   1747 	case STORAGE_ERROR:
   1748 	case STORAGE_UINTPTR:
   1749 	case STORAGE_ALIAS:
   1750 	case STORAGE_FUNCTION:
   1751 	case STORAGE_POINTER:
   1752 	case STORAGE_RUNE:
   1753 	case STORAGE_SLICE:
   1754 	case STORAGE_TAGGED:
   1755 	case STORAGE_TUPLE:
   1756 	case STORAGE_STRUCT:
   1757 	case STORAGE_UNION:
   1758 	case STORAGE_VALIST:
   1759 		assert(0); // Invariant
   1760 	}
   1761 }
   1762 
   1763 static void
   1764 check_expr_defer(struct context *ctx,
   1765 	const struct ast_expression *aexpr,
   1766 	struct expression *expr,
   1767 	const struct type *hint)
   1768 {
   1769 	if (ctx->deferring) {
   1770 		error(ctx, aexpr->loc, expr,
   1771 			"Cannot defer within another defer expression.");
   1772 		return;
   1773 	}
   1774 	if (ctx->scope->class == SCOPE_FUNC) {
   1775 		error(ctx, aexpr->loc, expr,
   1776 			"Cannot defer in a function scope");
   1777 		return;
   1778 	}
   1779 	expr->type = EXPR_DEFER;
   1780 	expr->result = &builtin_type_void;
   1781 	expr->defer.deferred = xcalloc(1, sizeof(struct expression));
   1782 	ctx->deferring = true;
   1783 	check_expression(ctx, aexpr->defer.deferred, expr->defer.deferred, &builtin_type_void);
   1784 	ctx->deferring = false;
   1785 }
   1786 
   1787 static void
   1788 check_expr_delete(struct context *ctx,
   1789 	const struct ast_expression *aexpr,
   1790 	struct expression *expr,
   1791 	const struct type *hint)
   1792 {
   1793 	expr->type = EXPR_DELETE;
   1794 	expr->delete.is_static = aexpr->delete.is_static;
   1795 	expr->result = &builtin_type_void;
   1796 	struct expression *dexpr = expr->delete.expr =
   1797 		xcalloc(1, sizeof(struct expression));
   1798 	check_expression(ctx, aexpr->delete.expr, expr->delete.expr, NULL);
   1799 	const struct type *otype = NULL;
   1800 	switch (dexpr->type) {
   1801 	case EXPR_SLICE:
   1802 		otype = dexpr->slice.object->result;
   1803 		break;
   1804 	case EXPR_ACCESS:
   1805 		if (dexpr->access.type != ACCESS_INDEX) {
   1806 			error(ctx, aexpr->delete.expr->loc, expr,
   1807 				"Deleted expression must be slicing or indexing expression");
   1808 			return;
   1809 		}
   1810 		otype = dexpr->access.array->result;
   1811 		break;
   1812 	default:
   1813 		error(ctx, aexpr->delete.expr->loc, expr,
   1814 			"Deleted expression must be slicing or indexing expression");
   1815 		return;
   1816 	}
   1817 	otype = type_dereference(otype);
   1818 	if (!otype) {
   1819 		error(ctx, aexpr->loc, expr,
   1820 			"Cannot dereference nullable pointer for delete expression");
   1821 		return;
   1822 	}
   1823 	otype = type_dealias(otype);
   1824 	if (otype->storage != STORAGE_SLICE) {
   1825 		error(ctx, aexpr->delete.expr->loc, expr,
   1826 			"delete must operate on a slice");
   1827 		return;
   1828 	}
   1829 	if (otype->flags & TYPE_CONST) {
   1830 		error(ctx, aexpr->delete.expr->loc, expr,
   1831 			"delete must operate on a mutable slice");
   1832 		return;
   1833 	}
   1834 }
   1835 
   1836 static void
   1837 check_expr_control(struct context *ctx,
   1838 	const struct ast_expression *aexpr,
   1839 	struct expression *expr,
   1840 	const struct type *hint)
   1841 {
   1842 	expr->type = aexpr->type;
   1843 	expr->result = &builtin_type_void;
   1844 	expr->control.label = aexpr->control.label;
   1845 	expr->terminates = true;
   1846 
   1847 	enum scope_class want;
   1848 	switch (expr->type) {
   1849 	case EXPR_BREAK:
   1850 	case EXPR_CONTINUE:
   1851 		want = SCOPE_LOOP;
   1852 		break;
   1853 	case EXPR_YIELD:
   1854 		want = SCOPE_COMPOUND;
   1855 		break;
   1856 	default:
   1857 		abort(); // Invariant
   1858 	}
   1859 
   1860 	struct scope *scope = scope_lookup_ancestor(
   1861 		ctx->scope, want, aexpr->control.label);
   1862 	if (!scope) {
   1863 		// XXX: This error message is bad
   1864 		error(ctx, aexpr->loc, expr, "No eligible loop for operation");
   1865 		return;
   1866 	}
   1867 	expr->control.scope = scope;
   1868 
   1869 	if (expr->type != EXPR_YIELD) {
   1870 		return;
   1871 	}
   1872 
   1873 	expr->control.value = xcalloc(1, sizeof(struct expression));
   1874 	if (aexpr->control.value) {
   1875 		check_expression(ctx, aexpr->control.value,
   1876 			expr->control.value, scope->hint);
   1877 	} else {
   1878 		expr->control.value->type = EXPR_CONSTANT;
   1879 		expr->control.value->result = &builtin_type_void;
   1880 	}
   1881 
   1882 	struct type_tagged_union *result =
   1883 		xcalloc(1, sizeof(struct type_tagged_union));
   1884 	result->type = expr->control.value->result;
   1885 	result->next = scope->results;
   1886 	scope->results = result;
   1887 
   1888 	struct yield *yield = xcalloc(1, sizeof(struct yield));
   1889 	yield->expression = &expr->control.value;
   1890 	yield->next = scope->yields;
   1891 	scope->yields = yield;
   1892 }
   1893 
   1894 static void
   1895 check_expr_for(struct context *ctx,
   1896 	const struct ast_expression *aexpr,
   1897 	struct expression *expr,
   1898 	const struct type *hint)
   1899 {
   1900 	expr->type = EXPR_FOR;
   1901 	expr->result = &builtin_type_void;
   1902 
   1903 	struct scope *scope = scope_push(&ctx->scope, SCOPE_LOOP);
   1904 	expr->_for.scope = scope;
   1905 
   1906 	struct expression *bindings = NULL,
   1907 		*cond = NULL, *afterthought = NULL, *body = NULL;
   1908 
   1909 	if (aexpr->_for.bindings) {
   1910 		bindings = xcalloc(1, sizeof(struct expression));
   1911 		check_expression(ctx, aexpr->_for.bindings, bindings, NULL);
   1912 		expr->_for.bindings = bindings;
   1913 	}
   1914 
   1915 	cond = xcalloc(1, sizeof(struct expression));
   1916 	check_expression(ctx, aexpr->_for.cond, cond, &builtin_type_bool);
   1917 	expr->_for.cond = cond;
   1918 	if (type_dealias(cond->result)->storage != STORAGE_BOOL) {
   1919 		error(ctx, aexpr->_for.cond->loc, expr,
   1920 			"Expected for condition to be boolean");
   1921 		return;
   1922 	}
   1923 
   1924 	if (aexpr->_for.afterthought) {
   1925 		afterthought = xcalloc(1, sizeof(struct expression));
   1926 		check_expression(ctx, aexpr->_for.afterthought, afterthought, &builtin_type_void);
   1927 		expr->_for.afterthought = afterthought;
   1928 	}
   1929 
   1930 	body = xcalloc(1, sizeof(struct expression));
   1931 	check_expression(ctx, aexpr->_for.body, body, &builtin_type_void);
   1932 	expr->_for.body = body;
   1933 
   1934 	scope_pop(&ctx->scope);
   1935 }
   1936 
   1937 static void
   1938 check_expr_free(struct context *ctx,
   1939 	const struct ast_expression *aexpr,
   1940 	struct expression *expr,
   1941 	const struct type *hint)
   1942 {
   1943 	assert(aexpr->type == EXPR_FREE);
   1944 	expr->type = EXPR_FREE;
   1945 	expr->free.expr = xcalloc(sizeof(struct expression), 1);
   1946 	check_expression(ctx, aexpr->free.expr, expr->free.expr, NULL);
   1947 	enum type_storage storage = type_dealias(expr->free.expr->result)->storage;
   1948 	if (storage != STORAGE_SLICE && storage != STORAGE_STRING
   1949 			&& storage != STORAGE_POINTER) {
   1950 		error(ctx, aexpr->free.expr->loc, expr,
   1951 			"free must operate on slice, string, or pointer");
   1952 		return;
   1953 	}
   1954 	expr->result = &builtin_type_void;
   1955 }
   1956 
   1957 static void
   1958 check_expr_if(struct context *ctx,
   1959 	const struct ast_expression *aexpr,
   1960 	struct expression *expr,
   1961 	const struct type *hint)
   1962 {
   1963 	expr->type = EXPR_IF;
   1964 
   1965 	struct expression *cond, *true_branch, *false_branch = NULL;
   1966 
   1967 	cond = xcalloc(1, sizeof(struct expression));
   1968 	check_expression(ctx, aexpr->_if.cond, cond, &builtin_type_bool);
   1969 
   1970 	true_branch = xcalloc(1, sizeof(struct expression));
   1971 	check_expression(ctx, aexpr->_if.true_branch, true_branch, hint);
   1972 
   1973 	if (aexpr->_if.false_branch) {
   1974 		false_branch = xcalloc(1, sizeof(struct expression));
   1975 		check_expression(ctx, aexpr->_if.false_branch, false_branch, hint);
   1976 
   1977 		bool tt = true_branch->terminates, ft = false_branch->terminates;
   1978 		if (tt && ft) {
   1979 			expr->terminates = true;
   1980 			expr->result = &builtin_type_void;
   1981 		} else if (!tt && ft) {
   1982 			expr->result = true_branch->result;
   1983 		} else if (tt && !ft) {
   1984 			expr->result = false_branch->result;
   1985 		} else if (hint && type_is_assignable(hint, true_branch->result)
   1986 				&& type_is_assignable(hint, false_branch->result)) {
   1987 			expr->result = hint;
   1988 		} else {
   1989 			struct type_tagged_union _tags = {
   1990 				.type = false_branch->result,
   1991 				.next = NULL,
   1992 			}, tags = {
   1993 				.type = true_branch->result,
   1994 				.next = &_tags,
   1995 			};
   1996 			expr->result =
   1997 				type_store_reduce_result(ctx->store, aexpr->loc,
   1998 						&tags);
   1999 			if (expr->result == NULL) {
   2000 				error(ctx, aexpr->loc, expr,
   2001 					"Invalid result type (dangling or ambiguous null)");
   2002 				return;
   2003 			}
   2004 		}
   2005 		true_branch = lower_implicit_cast(expr->result, true_branch);
   2006 		false_branch = lower_implicit_cast(expr->result, false_branch);
   2007 	} else {
   2008 		expr->result = &builtin_type_void;
   2009 		expr->terminates = false;
   2010 	}
   2011 
   2012 	if (type_dealias(cond->result)->storage != STORAGE_BOOL) {
   2013 		error(ctx, aexpr->_if.cond->loc, expr,
   2014 			"Expected if condition to be boolean");
   2015 		return;
   2016 	}
   2017 
   2018 	expr->_if.cond = cond;
   2019 	expr->_if.true_branch = true_branch;
   2020 	expr->_if.false_branch = false_branch;
   2021 }
   2022 
   2023 static void
   2024 check_expr_match(struct context *ctx,
   2025 	const struct ast_expression *aexpr,
   2026 	struct expression *expr,
   2027 	const struct type *hint)
   2028 {
   2029 	expr->type = EXPR_MATCH;
   2030 
   2031 	struct expression *value = xcalloc(1, sizeof(struct expression));
   2032 	check_expression(ctx, aexpr->match.value, value, NULL); expr->match.value = value;
   2033 
   2034 	const struct type *type = type_dealias(value->result);
   2035 	bool is_ptr = type->storage == STORAGE_POINTER
   2036 		&& type->pointer.flags & PTR_NULLABLE;
   2037 	if (type->storage != STORAGE_TAGGED && !is_ptr) {
   2038 		error(ctx, aexpr->match.value->loc, expr,
   2039 			"match value must be tagged union or nullable pointer type");
   2040 		return;
   2041 	}
   2042 
   2043 	struct type_tagged_union result_type = {0};
   2044 	struct type_tagged_union *tagged = &result_type,
   2045 		**next_tag = &tagged->next;
   2046 
   2047 	struct match_case **next = &expr->match.cases, *_case = NULL;
   2048 	for (struct ast_match_case *acase = aexpr->match.cases;
   2049 			acase; acase = acase->next) {
   2050 		_case = *next = xcalloc(1, sizeof(struct match_case));
   2051 		next = &_case->next;
   2052 
   2053 		const struct type *ctype = NULL;
   2054 		if (acase->type) {
   2055 			ctype = type_store_lookup_atype(ctx->store, acase->type);
   2056 			if (is_ptr) {
   2057 				switch (ctype->storage) {
   2058 				case STORAGE_NULL:
   2059 					break;
   2060 				case STORAGE_POINTER:
   2061 					if (type->pointer.referent != ctype->pointer.referent) {
   2062 						error(ctx, acase->type->loc, expr,
   2063 							"Match case on incompatible pointer type");
   2064 						return;
   2065 					}
   2066 					break;
   2067 				default:
   2068 					error(ctx, acase->type->loc, expr,
   2069 						"Invalid type for match case (expected null or pointer type)");
   2070 					return;
   2071 				}
   2072 			} else {
   2073 				// TODO: Assign a score to tagged compatibility
   2074 				// and choose the branch with the highest score.
   2075 				if (!type_is_assignable(type, ctype)) {
   2076 					error(ctx, acase->type->loc, expr,
   2077 						"Invalid type for match case (match is not assignable to this type)");
   2078 					return;
   2079 				}
   2080 			}
   2081 		}
   2082 
   2083 		if (acase->name) {
   2084 			assert(ctype);
   2085 			if (ctype->size == 0 || ctype->size == SIZE_UNDEFINED) {
   2086 				error(ctx, acase->type->loc, expr,
   2087 					"Cannot create binding for type of zero or undefined size");
   2088 				return;
   2089 			}
   2090 			if (ctype->storage == STORAGE_NULL) {
   2091 				error(ctx, aexpr->loc, expr,
   2092 					"Null is not a valid type for a binding");
   2093 				return;
   2094 			}
   2095 			struct identifier ident = {
   2096 				.name = acase->name,
   2097 			};
   2098 			struct scope *scope = scope_push(
   2099 				&ctx->scope, SCOPE_MATCH);
   2100 			_case->object = scope_insert(scope, O_BIND,
   2101 				&ident, &ident, ctype, NULL);
   2102 		}
   2103 
   2104 		_case->value = xcalloc(1, sizeof(struct expression));
   2105 		_case->type = ctype;
   2106 
   2107 		// Lower to compound
   2108 		// TODO: This should probably be done in a more first-class way
   2109 		struct ast_expression compound = {
   2110 			.type = EXPR_COMPOUND,
   2111 			.compound = {
   2112 				.list = acase->exprs,
   2113 			},
   2114 		};
   2115 		check_expression(ctx, &compound, _case->value, hint);
   2116 
   2117 		if (acase->name) {
   2118 			scope_pop(&ctx->scope);
   2119 		}
   2120 
   2121 		if (_case->value->terminates) {
   2122 			continue;
   2123 		}
   2124 
   2125 		if (expr->result == NULL) {
   2126 			expr->result = _case->value->result;
   2127 			tagged->type = expr->result;
   2128 		} else if (expr->result != _case->value->result) {
   2129 			tagged = *next_tag =
   2130 				xcalloc(1, sizeof(struct type_tagged_union));
   2131 			next_tag = &tagged->next;
   2132 			tagged->type = _case->value->result;
   2133 		}
   2134 	}
   2135 
   2136 	if (expr->result == NULL) {
   2137 		expr->result = &builtin_type_void;
   2138 		expr->terminates = true;
   2139 	}
   2140 
   2141 	if (result_type.next) {
   2142 		if (hint) {
   2143 			expr->result = hint;
   2144 		} else {
   2145 			expr->result = type_store_reduce_result(
   2146 				ctx->store, aexpr->loc, &result_type);
   2147 			if (expr->result == NULL) {
   2148 				error(ctx, aexpr->loc, expr,
   2149 					"Invalid result type (dangling or ambiguous null)");
   2150 				return;
   2151 			}
   2152 		}
   2153 
   2154 		struct match_case *_case = expr->match.cases;
   2155 		struct ast_match_case *acase = aexpr->match.cases;
   2156 		while (_case) {
   2157 			if (!_case->value->terminates && !type_is_assignable(
   2158 					expr->result, _case->value->result)) {
   2159 				error(ctx, acase->exprs.expr->loc, expr,
   2160 					"Match case is not assignable to result type");
   2161 				return;
   2162 			}
   2163 			_case->value = lower_implicit_cast(
   2164 				expr->result, _case->value);
   2165 			_case = _case->next;
   2166 			acase = acase->next;
   2167 		}
   2168 
   2169 		struct type_tagged_union *tu = result_type.next;
   2170 		while (tu) {
   2171 			struct type_tagged_union *next = tu->next;
   2172 			free(tu);
   2173 			tu = next;
   2174 		}
   2175 	}
   2176 }
   2177 
   2178 static void
   2179 check_expr_measure(struct context *ctx,
   2180 	const struct ast_expression *aexpr,
   2181 	struct expression *expr,
   2182 	const struct type *hint)
   2183 {
   2184 	expr->type = EXPR_MEASURE;
   2185 	expr->result = &builtin_type_size;
   2186 	expr->measure.op = aexpr->measure.op;
   2187 
   2188 	switch (expr->measure.op) {
   2189 	case M_LEN:
   2190 		expr->measure.value = xcalloc(1, sizeof(struct expression));
   2191 		check_expression(ctx, aexpr->measure.value, expr->measure.value, NULL);
   2192 		const struct type *atype =
   2193 			type_dereference(expr->measure.value->result);
   2194 		if (!atype) {
   2195 			error(ctx, aexpr->access.array->loc, expr,
   2196 				"Cannot dereference nullable pointer for len");
   2197 			return;
   2198 		}
   2199 		enum type_storage vstor = type_dealias(atype)->storage;
   2200 		bool valid = vstor == STORAGE_ARRAY || vstor == STORAGE_SLICE
   2201 				|| vstor == STORAGE_STRING;
   2202 		if (!valid) {
   2203 			char *typename = gen_typename(expr->measure.value->result);
   2204 			error(ctx, aexpr->measure.value->loc, expr,
   2205 				"len argument must be of an array, slice, or str type, but got %s",
   2206 				typename);
   2207 			free(typename);
   2208 			return;
   2209 		}
   2210 		if (atype->size == SIZE_UNDEFINED) {
   2211 			error(ctx, aexpr->measure.value->loc, expr,
   2212 				"Cannot take length of array type with undefined length");
   2213 			return;
   2214 		}
   2215 		break;
   2216 	case M_ALIGN:
   2217 		expr->measure.dimensions = type_store_lookup_dimensions(
   2218 			ctx->store, aexpr->measure.type);
   2219 		if (expr->measure.dimensions.align == ALIGN_UNDEFINED) {
   2220 			error(ctx, aexpr->measure.value->loc, expr,
   2221 				"Cannot take alignment of a type with undefined alignment");
   2222 			return;
   2223 		}
   2224 		if (expr->measure.dimensions.size == 0) {
   2225 			error(ctx, aexpr->measure.value->loc, expr,
   2226 				"Cannot take alignment of a type of size 0");
   2227 			return;
   2228 		}
   2229 		break;
   2230 	case M_SIZE:
   2231 		expr->measure.dimensions = type_store_lookup_dimensions(
   2232 			ctx->store, aexpr->measure.type);
   2233 		if (expr->measure.dimensions.size == SIZE_UNDEFINED) {
   2234 			error(ctx, aexpr->measure.value->loc, expr,
   2235 				"Cannot take size of a type with undefined size");
   2236 			return;
   2237 		}
   2238 		break;
   2239 	case M_OFFSET:
   2240 		if (aexpr->measure.value->type != EXPR_ACCESS) {
   2241 			error(ctx, aexpr->measure.value->loc, expr,
   2242 				"offset argument must be a field or tuple access");
   2243 			return;
   2244 		}
   2245 		if (aexpr->measure.value->access.type != ACCESS_FIELD
   2246 				&& aexpr->measure.value->access.type != ACCESS_TUPLE) {
   2247 			error(ctx, aexpr->measure.value->loc, expr,
   2248 				"offset argument must be a field or tuple access");
   2249 			return;
   2250 		}
   2251 		expr->measure.value = xcalloc(1, sizeof(struct expression));
   2252 		check_expression(ctx, aexpr->measure.value,
   2253 			expr->measure.value, NULL);
   2254 		break;
   2255 	}
   2256 }
   2257 
   2258 static void
   2259 check_expr_propagate(struct context *ctx,
   2260 	const struct ast_expression *aexpr,
   2261 	struct expression *expr,
   2262 	const struct type *hint)
   2263 {
   2264 	struct expression *lvalue = xcalloc(1, sizeof(struct expression));
   2265 	check_expression(ctx, aexpr->propagate.value, lvalue, hint == &builtin_type_void ? NULL : hint);
   2266 
   2267 	const struct type *intype = lvalue->result;
   2268 	if (type_dealias(intype)->storage != STORAGE_TAGGED) {
   2269 		char *typename = gen_typename(intype);
   2270 		error(ctx, aexpr->loc, expr,
   2271 			"Cannot use error propagation on non-tagged type %s",
   2272 			typename);
   2273 		free(typename);
   2274 		return;
   2275 	}
   2276 	if (!aexpr->propagate.abort) {
   2277 		if (ctx->deferring) {
   2278 			error(ctx, aexpr->loc, expr,
   2279 				"Cannot use error propagation in a defer expression");
   2280 			return;
   2281 		}
   2282 		if (ctx->fntype->func.flags & FN_NORETURN) {
   2283 			error(ctx, aexpr->loc, expr,
   2284 				"Cannot use error propagation inside @noreturn function");
   2285 			return;
   2286 		}
   2287 	}
   2288 
   2289 	struct type_tagged_union result_tagged = {0};
   2290 	struct type_tagged_union *tagged = &result_tagged,
   2291 		**next_tag = &tagged->next;
   2292 
   2293 	struct type_tagged_union return_tagged = {0};
   2294 	struct type_tagged_union *rtagged = &return_tagged,
   2295 		**next_rtag = &rtagged->next;
   2296 
   2297 	const struct type_tagged_union *intu = &type_dealias(intype)->tagged;
   2298 	for (; intu; intu = intu->next) {
   2299 		if (intu->type->flags & TYPE_ERROR) {
   2300 			if (rtagged->type) {
   2301 				rtagged = *next_rtag =
   2302 					xcalloc(1, sizeof(struct type_tagged_union));
   2303 				next_rtag = &rtagged->next;
   2304 				rtagged->type = intu->type;
   2305 			} else {
   2306 				rtagged->type = intu->type;
   2307 			}
   2308 		} else {
   2309 			if (tagged->type) {
   2310 				tagged = *next_tag =
   2311 					xcalloc(1, sizeof(struct type_tagged_union));
   2312 				next_tag = &tagged->next;
   2313 				tagged->type = intu->type;
   2314 			} else {
   2315 				tagged->type = intu->type;
   2316 			}
   2317 		}
   2318 	}
   2319 
   2320 	if (!return_tagged.type) {
   2321 		error(ctx, aexpr->loc, expr,
   2322 			"No error can occur here, cannot propagate");
   2323 		return;
   2324 	}
   2325 
   2326 	const struct type *return_type;
   2327 	if (return_tagged.next) {
   2328 		return_type = type_store_lookup_tagged(
   2329 			ctx->store, aexpr->loc, &return_tagged);
   2330 	} else {
   2331 		return_type = return_tagged.type;
   2332 	}
   2333 
   2334 	const struct type *result_type;
   2335 	if (!result_tagged.type) {
   2336 		result_type = &builtin_type_void;
   2337 	} else if (result_tagged.next) {
   2338 		result_type = type_store_lookup_tagged(
   2339 			ctx->store, aexpr->loc, &result_tagged);
   2340 	} else {
   2341 		result_type = result_tagged.type;
   2342 	}
   2343 
   2344 	// Lower to a match expression
   2345 	expr->type = EXPR_MATCH;
   2346 	expr->match.value = lvalue;
   2347 
   2348 	struct scope *scope = scope_push(&ctx->scope, SCOPE_MATCH);
   2349 	struct match_case *case_ok = xcalloc(1, sizeof(struct match_case));
   2350 	struct match_case *case_err = xcalloc(1, sizeof(struct match_case));
   2351 	struct identifier ok_name = {0}, err_name = {0};
   2352 
   2353 	ok_name.name = gen_name(&ctx->id, "ok.%d");
   2354 	const struct scope_object *ok_obj = NULL;
   2355 	if (result_type->size != 0 && result_type->size != SIZE_UNDEFINED) {
   2356 		ok_obj = scope_insert(scope, O_BIND, &ok_name,
   2357 			&ok_name, result_type, NULL);
   2358 	}
   2359 
   2360 	err_name.name = gen_name(&ctx->id, "err.%d");
   2361 	const struct scope_object *err_obj = NULL;
   2362 	if (return_type->size != 0 && return_type->size != SIZE_UNDEFINED) {
   2363 		err_obj = scope_insert(scope, O_BIND, &err_name,
   2364 			&err_name, return_type, NULL);
   2365 	}
   2366 
   2367 	case_ok->type = result_type;
   2368 	case_ok->object = ok_obj;
   2369 	case_ok->value = xcalloc(1, sizeof(struct expression));
   2370 	case_ok->value->result = result_type;
   2371 	if (ok_obj) {
   2372 		case_ok->value->type = EXPR_ACCESS;
   2373 		case_ok->value->access.type = ACCESS_IDENTIFIER;
   2374 		case_ok->value->access.object = ok_obj;
   2375 	} else {
   2376 		case_ok->value->type = EXPR_CONSTANT;
   2377 	}
   2378 
   2379 	case_err->type = return_type;
   2380 	case_err->object = err_obj;
   2381 	case_err->value = xcalloc(1, sizeof(struct expression));
   2382 
   2383 	if (aexpr->propagate.abort) {
   2384 		case_err->value->type = EXPR_ASSERT;
   2385 		case_err->value->assert.cond = NULL;
   2386 		case_err->value->assert.is_static = false;
   2387 
   2388 		int n = snprintf(NULL, 0, "Assertion failed: error occured at %s:%d:%d",
   2389 			sources[aexpr->loc.file],
   2390 			aexpr->loc.lineno, aexpr->loc.colno);
   2391 		char *s = xcalloc(1, n + 1);
   2392 		snprintf(s, n, "Assertion failed: error occured at %s:%d:%d",
   2393 			sources[aexpr->loc.file],
   2394 			aexpr->loc.lineno, aexpr->loc.colno);
   2395 
   2396 		case_err->value->assert.message = xcalloc(1, sizeof(struct expression));
   2397 		case_err->value->assert.message->type = EXPR_CONSTANT;
   2398 		case_err->value->assert.message->result = &builtin_type_const_str;
   2399 		case_err->value->assert.message->constant.string.value = s;
   2400 		case_err->value->assert.message->constant.string.len = n;
   2401 	} else {
   2402 		if (!type_is_assignable(ctx->fntype->func.result, return_type)) {
   2403 			char *res = gen_typename(ctx->fntype->func.result);
   2404 			char *ret = gen_typename(return_type);
   2405 			error(ctx, aexpr->loc, expr,
   2406 				"Error type %s is not assignable to function result type %s",
   2407 				ret, res);
   2408 			free(res);
   2409 			free(ret);
   2410 			return;
   2411 		}
   2412 
   2413 		case_err->value->type = EXPR_RETURN;
   2414 
   2415 		struct expression *rval =
   2416 			xcalloc(1, sizeof(struct expression));
   2417 		rval->result = return_type;
   2418 		if (err_obj != NULL) {
   2419 			rval->type = EXPR_ACCESS;
   2420 			rval->access.type = ACCESS_IDENTIFIER;
   2421 			rval->access.object = err_obj;
   2422 		} else {
   2423 			rval->type = EXPR_CONSTANT;
   2424 		}
   2425 		case_err->value->_return.value = lower_implicit_cast(
   2426 				ctx->fntype->func.result, rval);
   2427 	}
   2428 	case_err->value->terminates = true;
   2429 	case_err->value->result = &builtin_type_void;
   2430 
   2431 	expr->match.cases = case_ok;
   2432 	case_ok->next = case_err;
   2433 
   2434 	scope_pop(&ctx->scope);
   2435 	expr->result = result_type;
   2436 }
   2437 
   2438 static void
   2439 check_expr_return(struct context *ctx,
   2440 	const struct ast_expression *aexpr,
   2441 	struct expression *expr,
   2442 	const struct type *hint)
   2443 {
   2444 	if (ctx->deferring) {
   2445 		error(ctx, aexpr->loc, expr,
   2446 			"Cannot return inside a defer expression");
   2447 		return;
   2448 	}
   2449 	if (ctx->fntype == NULL) {
   2450 		error(ctx, aexpr->loc, expr, "Cannot return outside a function body");
   2451 		return;
   2452 	}
   2453 	if (ctx->fntype->func.flags & FN_NORETURN) {
   2454 		error(ctx, aexpr->loc, expr,
   2455 			"Cannot return inside @noreturn function");
   2456 		return;
   2457 	}
   2458 
   2459 	expr->type = EXPR_RETURN;
   2460 	expr->result = &builtin_type_void;
   2461 	expr->terminates = true;
   2462 
   2463 	struct expression *rval = xcalloc(1, sizeof(struct expression));
   2464 	if (aexpr->_return.value) {
   2465 		check_expression(ctx, aexpr->_return.value, rval, ctx->fntype->func.result);
   2466 	} else {
   2467 		rval->type = EXPR_CONSTANT;
   2468 		rval->result = &builtin_type_void;
   2469 	}
   2470 
   2471 	if (!type_is_assignable(ctx->fntype->func.result, rval->result)) {
   2472 		char *rettypename = gen_typename(rval->result);
   2473 		char *fntypename = gen_typename(ctx->fntype->func.result);
   2474 		error(ctx, aexpr->loc, expr,
   2475 			"Return value %s is not assignable to function result type %s",
   2476 			rettypename, fntypename);
   2477 		free(rettypename);
   2478 		free(fntypename);
   2479 		return;
   2480 	}
   2481 	if (ctx->fntype->func.result != rval->result) {
   2482 		rval = lower_implicit_cast(
   2483 			ctx->fntype->func.result, rval);
   2484 	}
   2485 	expr->_return.value = rval;
   2486 }
   2487 
   2488 static void
   2489 slice_bounds_check(struct context *ctx, struct expression *expr)
   2490 {
   2491 	const struct type *atype = type_dereference(expr->slice.object->result);
   2492 	const struct type *dtype = type_dealias(atype);
   2493 
   2494 	struct expression *start = NULL, *end = NULL;
   2495 
   2496 	if (expr->slice.end != NULL) {
   2497 		end = xcalloc(1, sizeof(struct expression));
   2498 		enum eval_result r = eval_expr(ctx, expr->slice.end, end);
   2499 		if (r != EVAL_OK) {
   2500 			free(end);
   2501 			return;
   2502 		}
   2503 
   2504 		if (dtype->storage == STORAGE_ARRAY
   2505 				&& dtype->array.length != SIZE_UNDEFINED) {
   2506 			if (end->constant.uval > dtype->array.length) {
   2507 				error(ctx, expr->loc, expr,
   2508 					"End index must not be greater than array length");
   2509 				free(end);
   2510 				return;
   2511 			}
   2512 		}
   2513 	} else {
   2514 		if (dtype->storage != STORAGE_ARRAY) {
   2515 			return;
   2516 		}
   2517 		assert(dtype->array.length != SIZE_UNDEFINED);
   2518 	}
   2519 
   2520 	if (expr->slice.start == NULL) {
   2521 		if (end) free(end);
   2522 		return;
   2523 	}
   2524 	start = xcalloc(1, sizeof(struct expression));
   2525 	enum eval_result r = eval_expr(ctx, expr->slice.start, start);
   2526 	if (r != EVAL_OK) {
   2527 		free(start);
   2528 		if (end) free(end);
   2529 		return;
   2530 	}
   2531 
   2532 	if (dtype->storage == STORAGE_ARRAY
   2533 			&& dtype->array.length != SIZE_UNDEFINED) {
   2534 		if (start->constant.uval > dtype->array.length) {
   2535 			error(ctx, expr->loc, expr,
   2536 				"Start index must not be greater than array length");
   2537 			free(start);
   2538 			if (end) free(end);
   2539 			return;
   2540 		}
   2541 
   2542 		expr->slice.bounds_checked = true;
   2543 	}
   2544 
   2545 	if (end != NULL) {
   2546 		if (start->constant.uval > end->constant.uval) {
   2547 			error(ctx, expr->loc, expr,
   2548 				"Start index must not be greater than end index");
   2549 		}
   2550 		free(end);
   2551 	}
   2552 	free(start);
   2553 	return;
   2554 }
   2555 
   2556 static void
   2557 check_expr_slice(struct context *ctx,
   2558 	const struct ast_expression *aexpr,
   2559 	struct expression *expr,
   2560 	const struct type *hint)
   2561 {
   2562 	expr->type = EXPR_SLICE;
   2563 
   2564 	expr->slice.object = xcalloc(1, sizeof(struct expression));
   2565 	check_expression(ctx, aexpr->slice.object, expr->slice.object, NULL);
   2566 	const struct type *atype =
   2567 		type_dereference(expr->slice.object->result);
   2568 	if (!atype) {
   2569 		error(ctx, aexpr->slice.object->loc, expr,
   2570 			"Cannot dereference nullable pointer for slicing");
   2571 		return;
   2572 	}
   2573 	const struct type *dtype = type_dealias(atype);
   2574 	if (dtype->storage != STORAGE_SLICE
   2575 			&& dtype->storage != STORAGE_ARRAY) {
   2576 		error(ctx, aexpr->slice.object->loc, expr,
   2577 			"Cannot slice non-array, non-slice object");
   2578 		return;
   2579 	}
   2580 
   2581 	const struct type *itype;
   2582 	if (aexpr->slice.start) {
   2583 		expr->slice.start = xcalloc(1, sizeof(struct expression));
   2584 		check_expression(ctx, aexpr->slice.start, expr->slice.start, &builtin_type_size);
   2585 		itype = type_dealias(expr->slice.start->result);
   2586 		if (!type_is_integer(itype)) {
   2587 			error(ctx, aexpr->slice.start->loc, expr,
   2588 				"Cannot use non-integer %s type as slicing operand",
   2589 				type_storage_unparse(itype->storage));
   2590 			return;
   2591 		}
   2592 		expr->slice.start = lower_implicit_cast(
   2593 			&builtin_type_size, expr->slice.start);
   2594 	}
   2595 
   2596 	if (aexpr->slice.end) {
   2597 		expr->slice.end = xcalloc(1, sizeof(struct expression));
   2598 		check_expression(ctx, aexpr->slice.end, expr->slice.end, &builtin_type_size);
   2599 		itype = type_dealias(expr->slice.end->result);
   2600 		if (!type_is_integer(itype)) {
   2601 			error(ctx, aexpr->slice.end->loc, expr,
   2602 				"Cannot use non-integer %s type as slicing operand",
   2603 				type_storage_unparse(itype->storage));
   2604 			return;
   2605 		}
   2606 		expr->slice.end = lower_implicit_cast(
   2607 			&builtin_type_size, expr->slice.end);
   2608 	} else if (dtype->storage == STORAGE_ARRAY
   2609 			&& dtype->array.length == SIZE_UNDEFINED) {
   2610 		error(ctx, aexpr->loc, expr,
   2611 			"Must have end index on array of undefined length");
   2612 		return;
   2613 	}
   2614 
   2615 	slice_bounds_check(ctx, expr);
   2616 
   2617 	if (dtype->storage == STORAGE_SLICE) {
   2618 		expr->result = atype;
   2619 	} else {
   2620 		expr->result = type_store_lookup_slice(ctx->store, aexpr->loc,
   2621 			dtype->array.members);
   2622 	}
   2623 }
   2624 
   2625 static void
   2626 check_struct_exhaustive(struct context *ctx,
   2627 	const struct ast_expression *aexpr,
   2628 	struct expression *expr,
   2629 	const struct type *stype)
   2630 {
   2631 	stype = type_dealias(stype);
   2632 	if (stype->storage == STORAGE_UNION) {
   2633 		return;
   2634 	}
   2635 	assert(stype->storage == STORAGE_STRUCT);
   2636 	struct struct_field *sf = stype->struct_union.fields;
   2637 	struct ast_field_value *af = aexpr->_struct.fields;
   2638 
   2639 	// XXX: O(n^2)?
   2640 	while (sf) {
   2641 		bool found = false;
   2642 		for (struct ast_field_value *f = af; f;
   2643 				f = f->next) {
   2644 			if (!sf->name) {
   2645 				check_struct_exhaustive(ctx, aexpr, expr,
   2646 					sf->type);
   2647 				found = true;
   2648 				continue;
   2649 			}
   2650 			if (strcmp(f->name, sf->name) == 0) {
   2651 				if (found) {
   2652 					error(ctx, aexpr->loc, expr,
   2653 						"Field '%s' is initialized multiple times",
   2654 						sf->name);
   2655 				}
   2656 				found = true;
   2657 			}
   2658 		}
   2659 
   2660 		if (!found) {
   2661 			error(ctx, aexpr->loc, expr,
   2662 				"Field '%s' is uninitialized",
   2663 				sf->name);
   2664 		}
   2665 
   2666 		sf = sf->next;
   2667 	}
   2668 }
   2669 
   2670 static void
   2671 check_expr_struct(struct context *ctx,
   2672 	const struct ast_expression *aexpr,
   2673 	struct expression *expr,
   2674 	const struct type *hint)
   2675 {
   2676 	expr->type = EXPR_STRUCT;
   2677 
   2678 	const struct type *stype = NULL;
   2679 	if (aexpr->_struct.type.name) {
   2680 		const struct scope_object *obj = scope_lookup(ctx->scope,
   2681 				&aexpr->_struct.type);
   2682 		// resolve the unknown type
   2683 		wrap_resolver(ctx, obj, resolve_type);
   2684 		if (!obj) {
   2685 			error(ctx, aexpr->loc, expr,
   2686 				"Unknown type alias");
   2687 			return;
   2688 		}
   2689 		assert(obj->otype == O_TYPE);
   2690 		stype = obj->type;
   2691 		enum type_storage storage = type_dealias(stype)->storage;
   2692 		if (storage != STORAGE_STRUCT && storage != STORAGE_UNION) {
   2693 			error(ctx, aexpr->loc, expr,
   2694 				"Object named is not a struct or union type");
   2695 			return;
   2696 		}
   2697 	}
   2698 
   2699 	struct ast_type satype = {
   2700 		.storage = STORAGE_STRUCT,
   2701 		.flags = TYPE_CONST,
   2702 	};
   2703 	struct ast_struct_union_field *tfield = &satype.struct_union.fields;
   2704 	struct ast_struct_union_field **tnext = &tfield->next;
   2705 	struct expr_struct_field *sexpr, **snext = &expr->_struct.fields;
   2706 	expr->_struct.autofill = aexpr->_struct.autofill;
   2707 	if (stype == NULL && expr->_struct.autofill) {
   2708 		error(ctx, aexpr->loc, expr,
   2709 				"Autofill is only permitted for named struct initializers");
   2710 		return;
   2711 	}
   2712 
   2713 	struct ast_field_value *afield = aexpr->_struct.fields;
   2714 	while (afield) {
   2715 		const struct type *ftype;
   2716 		*snext = sexpr = xcalloc(1, sizeof(struct expr_struct_field));
   2717 		snext = &sexpr->next;
   2718 		sexpr->value = xcalloc(1, sizeof(struct expression));
   2719 		if (!stype) {
   2720 			assert(afield->name); // TODO
   2721 			if (!afield->type) {
   2722 				error(ctx, aexpr->loc, expr,
   2723 					"Unnamed struct must specify field type");
   2724 				return;
   2725 			}
   2726 			tfield->name = afield->name;
   2727 			tfield->type = afield->type;
   2728 			ftype = type_store_lookup_atype(ctx->store, tfield->type);
   2729 			check_expression(ctx, afield->initializer,
   2730 				sexpr->value, ftype);
   2731 			if (afield->next) {
   2732 				*tnext = tfield = xcalloc(
   2733 					1, sizeof(struct ast_struct_union_type));
   2734 				tnext = &tfield->next;
   2735 			}
   2736 		} else {
   2737 			if (!afield->name) {
   2738 				error(ctx, afield->initializer->loc, expr,
   2739 					"Cannot embed a struct literal into "
   2740 					"a named struct literal");
   2741 				return;
   2742 			}
   2743 			sexpr->field = type_get_field(type_dealias(stype),
   2744 					afield->name);
   2745 			if (!sexpr->field) {
   2746 				error(ctx, afield->initializer->loc, expr,
   2747 					"No field by this name exists for this type");
   2748 				return;
   2749 			}
   2750 			ftype = sexpr->field->type;
   2751 			check_expression(ctx, afield->initializer,
   2752 					sexpr->value, ftype);
   2753 
   2754 			if (!type_is_assignable(sexpr->field->type, sexpr->value->result)) {
   2755 				error(ctx, afield->initializer->loc, expr,
   2756 					"Initializer is not assignable to struct field");
   2757 				return;
   2758 			}
   2759 			sexpr->value = lower_implicit_cast(
   2760 				sexpr->field->type, sexpr->value);
   2761 		}
   2762 
   2763 		afield = afield->next;
   2764 	}
   2765 
   2766 	if (stype) {
   2767 		expr->result = stype;
   2768 		if (!expr->_struct.autofill) {
   2769 			check_struct_exhaustive(ctx, aexpr, expr, stype);
   2770 		}
   2771 	} else {
   2772 		expr->result = type_store_lookup_atype(ctx->store, &satype);
   2773 
   2774 		tfield = &satype.struct_union.fields;
   2775 		sexpr = expr->_struct.fields;
   2776 		while (tfield) {
   2777 			const struct struct_field *field = type_get_field(
   2778 				expr->result, tfield->name);
   2779 			if (!field) {
   2780 				// TODO: Use more specific error location
   2781 				error(ctx, aexpr->loc, expr,
   2782 					"No field by this name exists for this type");
   2783 				return;
   2784 			}
   2785 			if (!type_is_assignable(field->type, sexpr->value->result)) {
   2786 				error(ctx, aexpr->loc, expr,
   2787 					"Cannot initialize struct field '%s' from value of this type",
   2788 					field->name);
   2789 				return;
   2790 			}
   2791 			sexpr->field = field;
   2792 			sexpr->value = lower_implicit_cast(field->type, sexpr->value);
   2793 
   2794 			struct ast_struct_union_field *next = tfield->next;
   2795 			if (tfield != &satype.struct_union.fields) {
   2796 				free(tfield);
   2797 			}
   2798 			tfield = next;
   2799 			sexpr = sexpr->next;
   2800 		}
   2801 	}
   2802 }
   2803 
   2804 static void
   2805 check_expr_switch(struct context *ctx,
   2806 	const struct ast_expression *aexpr,
   2807 	struct expression *expr,
   2808 	const struct type *hint)
   2809 {
   2810 	expr->type = EXPR_SWITCH;
   2811 
   2812 	struct expression *value = xcalloc(1, sizeof(struct expression));
   2813 	check_expression(ctx, aexpr->_switch.value, value, NULL);
   2814 	const struct type *type = type_dealias(value->result);
   2815 	expr->_switch.value = value;
   2816 	if (!type_is_numeric(type)
   2817 			&& type_dealias(type)->storage != STORAGE_POINTER
   2818 			&& type_dealias(type)->storage != STORAGE_STRING
   2819 			&& type_dealias(type)->storage != STORAGE_BOOL
   2820 			&& type_dealias(type)->storage != STORAGE_RCONST
   2821 			&& type_dealias(type)->storage != STORAGE_RUNE) {
   2822 		error(ctx, aexpr->loc, expr,
   2823 			"Cannot switch on %s type",
   2824 			type_storage_unparse(type_dealias(type)->storage));
   2825 		return;
   2826 	}
   2827 
   2828 	struct type_tagged_union result_type = {0};
   2829 	struct type_tagged_union *tagged = &result_type,
   2830 		**next_tag = &tagged->next;
   2831 
   2832 	// TODO: Test for dupes, exhaustiveness
   2833 	struct switch_case **next = &expr->_switch.cases, *_case = NULL;
   2834 	for (struct ast_switch_case *acase = aexpr->_switch.cases;
   2835 			acase; acase = acase->next) {
   2836 		_case = *next = xcalloc(1, sizeof(struct switch_case));
   2837 		next = &_case->next;
   2838 
   2839 		struct case_option *opt, **next_opt = &_case->options;
   2840 		for (struct ast_case_option *aopt = acase->options;
   2841 				aopt; aopt = aopt->next) {
   2842 			opt = *next_opt = xcalloc(1, sizeof(struct case_option));
   2843 			struct expression *value =
   2844 				xcalloc(1, sizeof(struct expression));
   2845 			struct expression *evaled =
   2846 				xcalloc(1, sizeof(struct expression));
   2847 
   2848 			check_expression(ctx, aopt->value, value, type);
   2849 			if (!type_is_assignable(type_dealias(type),
   2850 					type_dealias(value->result))) {
   2851 				error(ctx, aopt->value->loc, expr,
   2852 					"Invalid type for switch case");
   2853 				return;
   2854 			}
   2855 
   2856 			enum eval_result r = eval_expr(ctx, value, evaled);
   2857 			if (r != EVAL_OK) {
   2858 				error(ctx, aopt->value->loc, expr,
   2859 					"Unable to evaluate case at compile time");
   2860 				return;
   2861 			}
   2862 
   2863 			opt->value = evaled;
   2864 			next_opt = &opt->next;
   2865 		}
   2866 
   2867 		_case->value = xcalloc(1, sizeof(struct expression));
   2868 
   2869 		// Lower to compound
   2870 		// TODO: This should probably be done in a more first-class way
   2871 		struct ast_expression compound = {
   2872 			.type = EXPR_COMPOUND,
   2873 			.compound = {
   2874 				.list = acase->exprs,
   2875 			},
   2876 		};
   2877 		check_expression(ctx, &compound, _case->value, hint);
   2878 
   2879 		if (_case->value->terminates) {
   2880 			continue;
   2881 		}
   2882 
   2883 		if (expr->result == NULL) {
   2884 			expr->result = _case->value->result;
   2885 			tagged->type = expr->result;
   2886 		} else if (expr->result != _case->value->result) {
   2887 			tagged = *next_tag =
   2888 				xcalloc(1, sizeof(struct type_tagged_union));
   2889 			next_tag = &tagged->next;
   2890 			tagged->type = _case->value->result;
   2891 		}
   2892 	}
   2893 
   2894 	if (expr->result == NULL) {
   2895 		expr->result = &builtin_type_void;
   2896 		expr->terminates = true;
   2897 	}
   2898 
   2899 	if (result_type.next) {
   2900 		if (hint) {
   2901 			expr->result = hint;
   2902 		} else {
   2903 			expr->result = type_store_reduce_result(
   2904 				ctx->store, aexpr->loc, &result_type);
   2905 			if (expr->result == NULL) {
   2906 				error(ctx, aexpr->loc, expr,
   2907 					"Invalid result type (dangling or ambiguous null)");
   2908 				return;
   2909 			}
   2910 		}
   2911 
   2912 		struct switch_case *_case = expr->_switch.cases;
   2913 		struct ast_switch_case *acase = aexpr->_switch.cases;
   2914 		while (_case) {
   2915 			if (!_case->value->terminates && !type_is_assignable(
   2916 					expr->result, _case->value->result)) {
   2917 				error(ctx, acase->exprs.expr->loc, expr,
   2918 					"Switch case is not assignable to result type");
   2919 				return;
   2920 			}
   2921 			_case->value = lower_implicit_cast(
   2922 				expr->result, _case->value);
   2923 			_case = _case->next;
   2924 			acase = acase->next;
   2925 		}
   2926 
   2927 		struct type_tagged_union *tu = result_type.next;
   2928 		while (tu) {
   2929 			struct type_tagged_union *next = tu->next;
   2930 			free(tu);
   2931 			tu = next;
   2932 		}
   2933 	}
   2934 }
   2935 
   2936 static void
   2937 check_expr_tuple(struct context *ctx,
   2938 	const struct ast_expression *aexpr,
   2939 	struct expression *expr,
   2940 	const struct type *hint)
   2941 {
   2942 	expr->type = EXPR_TUPLE;
   2943 
   2944 	const struct type_tuple *ttuple = NULL;
   2945 	if (hint && type_dealias(hint)->storage == STORAGE_TUPLE) {
   2946 		ttuple = &type_dealias(hint)->tuple;
   2947 	}
   2948 
   2949 	struct type_tuple result = {0};
   2950 	struct type_tuple *rtype = &result;
   2951 
   2952 	struct expression_tuple *tuple = &expr->tuple;
   2953 	for (const struct ast_expression_tuple *atuple = &aexpr->tuple;
   2954 			atuple; atuple = atuple->next) {
   2955 		tuple->value = xcalloc(1, sizeof(struct expression));
   2956 		check_expression(ctx, atuple->expr, tuple->value, ttuple ? ttuple->type : NULL);
   2957 		rtype->type = tuple->value->result;
   2958 
   2959 		if (atuple->next) {
   2960 			rtype->next = xcalloc(1, sizeof(struct type_tuple));
   2961 			rtype = rtype->next;
   2962 			tuple->next = xcalloc(1, sizeof(struct expression_tuple));
   2963 			tuple = tuple->next;
   2964 		}
   2965 
   2966 		if (ttuple) {
   2967 			ttuple = ttuple->next;
   2968 		}
   2969 	}
   2970 
   2971 	if (hint && type_dealias(hint)->storage == STORAGE_TUPLE) {
   2972 		expr->result = hint;
   2973 	} else if (hint && type_dealias(hint)->storage == STORAGE_TAGGED) {
   2974 		for (const struct type_tagged_union *tu =
   2975 				&type_dealias(hint)->tagged;
   2976 				tu; tu = tu->next) {
   2977 			if (type_dealias(tu->type)->storage != STORAGE_TUPLE) {
   2978 				continue;
   2979 			}
   2980 			const struct type_tuple *ttuple =
   2981 				&type_dealias(tu->type)->tuple;
   2982 			const struct expression_tuple *etuple = &expr->tuple;
   2983 			bool valid = true;
   2984 			while (etuple) {
   2985 				if (!ttuple || !type_is_assignable(ttuple->type,
   2986 						etuple->value->result)) {
   2987 					valid = false;
   2988 					break;
   2989 				}
   2990 				ttuple = ttuple->next;
   2991 				etuple = etuple->next;
   2992 			}
   2993 			if (!ttuple && valid) {
   2994 				expr->result = type_dealias(tu->type);
   2995 				break;
   2996 			}
   2997 		}
   2998 		if (!expr->result) {
   2999 			error(ctx, aexpr->loc, expr,
   3000 				"Tuple value is not assignable to tagged union hint");
   3001 			return;
   3002 		}
   3003 	} else {
   3004 		expr->result = type_store_lookup_tuple(ctx->store,
   3005 				aexpr->loc, &result);
   3006 		if (expr->result == &builtin_type_error) {
   3007 			// an error occured
   3008 			return;
   3009 		}
   3010 	}
   3011 
   3012 	ttuple = &type_dealias(expr->result)->tuple;
   3013 	struct expression_tuple *etuple = &expr->tuple;
   3014 	const struct ast_expression_tuple *atuple = &aexpr->tuple;
   3015 	while (etuple) {
   3016 		if (!ttuple) {
   3017 			error(ctx, atuple->expr->loc, expr,
   3018 				"Too many values for tuple type");
   3019 			return;
   3020 		}
   3021 		if (!type_is_assignable(ttuple->type, etuple->value->result)) {
   3022 			error(ctx, atuple->expr->loc, expr,
   3023 				"Value is not assignable to tuple value type");
   3024 			return;
   3025 		}
   3026 		etuple->value = lower_implicit_cast(ttuple->type, etuple->value);
   3027 		etuple = etuple->next;
   3028 		atuple = atuple->next;
   3029 		ttuple = ttuple->next;
   3030 	}
   3031 	if (ttuple) {
   3032 		error(ctx, aexpr->loc, expr,
   3033 			"Too few values for tuple type");
   3034 		return;
   3035 	}
   3036 }
   3037 
   3038 static void
   3039 check_expr_unarithm(struct context *ctx,
   3040 	const struct ast_expression *aexpr,
   3041 	struct expression *expr,
   3042 	const struct type *hint)
   3043 {
   3044 	expr->type = EXPR_UNARITHM;
   3045 
   3046 	struct expression *operand = xcalloc(1, sizeof(struct expression));
   3047 	check_expression(ctx, aexpr->unarithm.operand, operand, NULL);
   3048 	expr->unarithm.operand = operand;
   3049 	expr->unarithm.op = aexpr->unarithm.op;
   3050 
   3051 	switch (expr->unarithm.op) {
   3052 	case UN_LNOT:
   3053 		if (type_dealias(operand->result)->storage != STORAGE_BOOL) {
   3054 			error(ctx, aexpr->unarithm.operand->loc, expr,
   3055 				"Cannot perform logical NOT (!) on non-boolean type");
   3056 			return;
   3057 		}
   3058 		expr->result = &builtin_type_bool;
   3059 		break;
   3060 	case UN_BNOT:
   3061 		if (!type_is_integer(operand->result)) {
   3062 			error(ctx, aexpr->unarithm.operand->loc, expr,
   3063 				"Cannot perform binary NOT (~) on non-integer type");
   3064 			return;
   3065 		}
   3066 		expr->result = operand->result;
   3067 		break;
   3068 	case UN_MINUS:
   3069 		if (operand->result->storage == STORAGE_ICONST) {
   3070 			// Not technically quite right, but we need
   3071 			// operand->result to be lowered with expr->result, and
   3072 			// this is correct enough
   3073 			const struct type *old = operand->result;
   3074 			const struct type *new = type_create_const(
   3075 				STORAGE_ICONST, -old->_const.min,
   3076 				-old->_const.max);
   3077 			lower_const(old, new);
   3078 		}
   3079 		// Fallthrough
   3080 	case UN_PLUS:
   3081 		if (!type_is_numeric(operand->result)) {
   3082 			error(ctx, aexpr->unarithm.operand->loc, expr,
   3083 				"Cannot perform operation on non-numeric type");
   3084 			return;
   3085 		}
   3086 		expr->result = operand->result;
   3087 		break;
   3088 	case UN_ADDRESS:;
   3089 		const struct type *result = type_dealias(operand->result);
   3090 		if (result->storage == STORAGE_VOID) {
   3091 			error(ctx, aexpr->loc, expr,
   3092 				"Can't take address of void");
   3093 			return;
   3094 		}
   3095 		expr->result = type_store_lookup_pointer(
   3096 			ctx->store, aexpr->loc, operand->result, 0);
   3097 		break;
   3098 	case UN_DEREF:
   3099 		if (type_dealias(operand->result)->storage != STORAGE_POINTER) {
   3100 			error(ctx, aexpr->unarithm.operand->loc, expr,
   3101 				"Cannot de-reference non-pointer type");
   3102 			return;
   3103 		}
   3104 		if (type_dealias(operand->result)->pointer.flags
   3105 				& PTR_NULLABLE) {
   3106 			error(ctx, aexpr->unarithm.operand->loc, expr,
   3107 				"Cannot dereference nullable pointer type");
   3108 			return;
   3109 		}
   3110 		if (type_dealias(operand->result)->pointer.referent->size == 0) {
   3111 			error(ctx, aexpr->unarithm.operand->loc, expr,
   3112 				"Cannot dereference pointer to zero-sized type");
   3113 			return;
   3114 		}
   3115 		if (type_dealias(operand->result)->pointer.referent->size
   3116 				== SIZE_UNDEFINED) {
   3117 			error(ctx, aexpr->unarithm.operand->loc, expr,
   3118 				"Cannot dereference pointer to type of undefined size");
   3119 			return;
   3120 		}
   3121 		expr->result = type_dealias(operand->result)->pointer.referent;
   3122 		break;
   3123 	}
   3124 }
   3125 
   3126 static void
   3127 check_expr_vastart(struct context *ctx,
   3128 	const struct ast_expression *aexpr,
   3129 	struct expression *expr,
   3130 	const struct type *hint)
   3131 {
   3132 	if (ctx->fntype->func.variadism != VARIADISM_C) {
   3133 		error(ctx, aexpr->loc, expr,
   3134 			"Cannot use vastart within function which does not use C-style variadism");
   3135 		return;
   3136 	}
   3137 	expr->type = EXPR_VASTART;
   3138 	expr->result = &builtin_type_valist;
   3139 }
   3140 
   3141 static void
   3142 check_expr_vaarg(struct context *ctx,
   3143 	const struct ast_expression *aexpr,
   3144 	struct expression *expr,
   3145 	const struct type *hint)
   3146 {
   3147 	expr->type = EXPR_VAARG;
   3148 	if (hint == NULL) {
   3149 		error(ctx, aexpr->loc, expr,
   3150 			"Cannot infer type of vaarg without hint");
   3151 		return;
   3152 	}
   3153 	expr->vaarg.ap = xcalloc(1, sizeof(struct expression));
   3154 	check_expression(ctx, aexpr->vaarg.ap, expr->vaarg.ap, &builtin_type_valist);
   3155 	if (type_dealias(expr->vaarg.ap->result)->storage != STORAGE_VALIST) {
   3156 		error(ctx, aexpr->loc, expr,
   3157 			"Expected vaarg operand to be valist");
   3158 		return;
   3159 	}
   3160 	expr->result = hint;
   3161 }
   3162 
   3163 static void
   3164 check_expr_vaend(struct context *ctx,
   3165 	const struct ast_expression *aexpr,
   3166 	struct expression *expr,
   3167 	const struct type *hint)
   3168 {
   3169 	expr->type = EXPR_VAEND;
   3170 	expr->vaarg.ap = xcalloc(1, sizeof(struct expression));
   3171 	check_expression(ctx, aexpr->vaarg.ap, expr->vaarg.ap, &builtin_type_valist);
   3172 	if (type_dealias(expr->vaarg.ap->result)->storage != STORAGE_VALIST) {
   3173 		error(ctx, aexpr->loc, expr,
   3174 			"Expected vaend operand to be valist");
   3175 		return;
   3176 	}
   3177 	expr->result = &builtin_type_void;
   3178 }
   3179 
   3180 void
   3181 check_expression(struct context *ctx,
   3182 	const struct ast_expression *aexpr,
   3183 	struct expression *expr,
   3184 	const struct type *hint)
   3185 {
   3186 	expr->loc = aexpr->loc;
   3187 
   3188 	switch (aexpr->type) {
   3189 	case EXPR_ACCESS:
   3190 		check_expr_access(ctx, aexpr, expr, hint);
   3191 		break;
   3192 	case EXPR_ALLOC:
   3193 		check_expr_alloc(ctx, aexpr, expr, hint);
   3194 		break;
   3195 	case EXPR_APPEND:
   3196 		check_expr_append_insert(ctx, aexpr, expr, hint);
   3197 		break;
   3198 	case EXPR_ASSERT:
   3199 		check_expr_assert(ctx, aexpr, expr, hint);
   3200 		break;
   3201 	case EXPR_ASSIGN:
   3202 		check_expr_assign(ctx, aexpr, expr, hint);
   3203 		break;
   3204 	case EXPR_BINARITHM:
   3205 		check_expr_binarithm(ctx, aexpr, expr, hint);
   3206 		break;
   3207 	case EXPR_BINDING:
   3208 		check_expr_binding(ctx, aexpr, expr, hint);
   3209 		break;
   3210 	case EXPR_BREAK:
   3211 	case EXPR_CONTINUE:
   3212 	case EXPR_YIELD:
   3213 		check_expr_control(ctx, aexpr, expr, hint);
   3214 		break;
   3215 	case EXPR_CALL:
   3216 		check_expr_call(ctx, aexpr, expr, hint);
   3217 		break;
   3218 	case EXPR_CAST:
   3219 		check_expr_cast(ctx, aexpr, expr, hint);
   3220 		break;
   3221 	case EXPR_COMPOUND:
   3222 		check_expr_compound(ctx, aexpr, expr, hint);
   3223 		break;
   3224 	case EXPR_CONSTANT:
   3225 		check_expr_constant(ctx, aexpr, expr, hint);
   3226 		break;
   3227 	case EXPR_DEFER:
   3228 		check_expr_defer(ctx, aexpr, expr, hint);
   3229 		break;
   3230 	case EXPR_DELETE:
   3231 		check_expr_delete(ctx, aexpr, expr, hint);
   3232 		break;
   3233 	case EXPR_FOR:
   3234 		check_expr_for(ctx, aexpr, expr, hint);
   3235 		break;
   3236 	case EXPR_FREE:
   3237 		check_expr_free(ctx, aexpr, expr, hint);
   3238 		break;
   3239 	case EXPR_IF:
   3240 		check_expr_if(ctx, aexpr, expr, hint);
   3241 		break;
   3242 	case EXPR_INSERT:
   3243 		check_expr_append_insert(ctx, aexpr, expr, hint);
   3244 		break;
   3245 	case EXPR_MATCH:
   3246 		check_expr_match(ctx, aexpr, expr, hint);
   3247 		break;
   3248 	case EXPR_MEASURE:
   3249 		check_expr_measure(ctx, aexpr, expr, hint);
   3250 		break;
   3251 	case EXPR_PROPAGATE:
   3252 		check_expr_propagate(ctx, aexpr, expr, hint);
   3253 		break;
   3254 	case EXPR_RETURN:
   3255 		check_expr_return(ctx, aexpr, expr, hint);
   3256 		break;
   3257 	case EXPR_SLICE:
   3258 		check_expr_slice(ctx, aexpr, expr, hint);
   3259 		break;
   3260 	case EXPR_STRUCT:
   3261 		check_expr_struct(ctx, aexpr, expr, hint);
   3262 		break;
   3263 	case EXPR_SWITCH:
   3264 		check_expr_switch(ctx, aexpr, expr, hint);
   3265 		break;
   3266 	case EXPR_TUPLE:
   3267 		check_expr_tuple(ctx, aexpr, expr, hint);
   3268 		break;
   3269 	case EXPR_UNARITHM:
   3270 		check_expr_unarithm(ctx, aexpr, expr, hint);
   3271 		break;
   3272 	case EXPR_VAARG:
   3273 		check_expr_vaarg(ctx, aexpr, expr, hint);
   3274 		break;
   3275 	case EXPR_VAEND:
   3276 		check_expr_vaend(ctx, aexpr, expr, hint);
   3277 		break;
   3278 	case EXPR_VASTART:
   3279 		check_expr_vastart(ctx, aexpr, expr, hint);
   3280 		break;
   3281 	}
   3282 	assert(expr->result);
   3283 	const_refer(expr->result, &expr->result);
   3284 	if (hint && hint->storage == STORAGE_VOID) {
   3285 		if ((expr->result->flags & TYPE_ERROR) != 0) {
   3286 			error(ctx, aexpr->loc, expr,
   3287 				"Cannot ignore error here");
   3288 			return;
   3289 		}
   3290 		if (type_dealias(expr->result)->storage != STORAGE_TAGGED) {
   3291 			return;
   3292 		}
   3293 		const struct type_tagged_union *tu =
   3294 			&type_dealias(expr->result)->tagged;
   3295 		for (; tu; tu = tu->next) {
   3296 			if ((tu->type->flags & TYPE_ERROR) == 0) {
   3297 				continue;
   3298 			}
   3299 			error(ctx, aexpr->loc, expr,
   3300 				"Cannot ignore error here");
   3301 			return;
   3302 		}
   3303 	}
   3304 }
   3305 
   3306 static struct declaration *
   3307 check_const(struct context *ctx,
   3308 	const struct scope_object *obj,
   3309 	const struct location *loc,
   3310 	const struct ast_global_decl *adecl)
   3311 {
   3312 	struct declaration *decl = xcalloc(1, sizeof(struct declaration));
   3313 	const struct scope_object *shadow_obj = scope_lookup(
   3314 			ctx->defines, &adecl->ident);
   3315 	if (obj != shadow_obj) {
   3316 		// Shadowed by define
   3317 		if (obj->type != shadow_obj->type) {
   3318 			char *typename = gen_typename(obj->type);
   3319 			char *shadow_typename = gen_typename(shadow_obj->type);
   3320 			error(ctx, *loc, NULL,
   3321 					"Constant of type %s is shadowed by define of incompatible type %s",
   3322 					typename, shadow_typename);
   3323 			free(typename);
   3324 			free(shadow_typename);
   3325 		}
   3326 	}
   3327 	decl->type = DECL_CONST;
   3328 	decl->constant.type = obj->type;
   3329 	decl->constant.value = shadow_obj->value;
   3330 	decl->ident = obj->ident;
   3331 	return decl;
   3332 }
   3333 
   3334 static struct declaration *
   3335 check_function(struct context *ctx,
   3336 	const struct scope_object *obj,
   3337 	const struct ast_decl *adecl)
   3338 {
   3339 	const struct ast_function_decl *afndecl = &adecl->function;
   3340 	if ((adecl->function.flags & FN_TEST) && !ctx->is_test) {
   3341 		return NULL;
   3342 	}
   3343 	ctx->fntype = obj->type;
   3344 
   3345 	struct declaration *decl = xcalloc(1, sizeof(struct declaration));
   3346 	decl->type = DECL_FUNC;
   3347 	decl->func.type = obj->type;
   3348 	decl->func.flags = afndecl->flags;
   3349 
   3350 	decl->symbol = ident_to_sym(&obj->ident);
   3351 	mkident(ctx, &decl->ident, &afndecl->ident, NULL);
   3352 
   3353 	if (!adecl->function.body) {
   3354 		return decl; // Prototype
   3355 	}
   3356 
   3357 	decl->func.scope = scope_push(&ctx->scope, SCOPE_FUNC);
   3358 	struct ast_function_parameters *params = afndecl->prototype.params;
   3359 	while (params) {
   3360 		expect(ctx, &params->loc, params->name,
   3361 			"Function parameters must be named");
   3362 		struct identifier ident = {
   3363 			.name = params->name,
   3364 		};
   3365 		const struct type *type = type_store_lookup_atype(
   3366 				ctx->store, params->type);
   3367 		if (obj->type->func.variadism == VARIADISM_HARE
   3368 				&& !params->next) {
   3369 			type = type_store_lookup_slice(ctx->store,
   3370 				params->loc, type);
   3371 		}
   3372 		scope_insert(decl->func.scope, O_BIND,
   3373 			&ident, &ident, type, NULL);
   3374 		params = params->next;
   3375 	}
   3376 
   3377 	struct expression *body = xcalloc(1, sizeof(struct expression));
   3378 	check_expression(ctx, afndecl->body, body, obj->type->func.result);
   3379 	// TODO: Pass errors up and deal with them at the end of check
   3380 	handle_errors(ctx->errors);
   3381 
   3382 	char *restypename = gen_typename(body->result);
   3383 	char *fntypename = gen_typename(obj->type->func.result);
   3384 	expect(ctx, &afndecl->body->loc,
   3385 		body->terminates || type_is_assignable(obj->type->func.result, body->result),
   3386 		"Result value %s is not assignable to function result type %s",
   3387 		restypename, fntypename);
   3388 	free(restypename);
   3389 	free(fntypename);
   3390 	if (!body->terminates && obj->type->func.result != body->result) {
   3391 		body = lower_implicit_cast(obj->type->func.result, body);
   3392 	}
   3393 	decl->func.body = body;
   3394 
   3395 	// TODO: Add function name to errors
   3396 	if (decl->func.flags != 0) {
   3397 		const char *flag = NULL;
   3398 		switch (decl->func.flags) {
   3399 		case FN_INIT:
   3400 			flag = "@init";
   3401 			break;
   3402 		case FN_FINI:
   3403 			flag = "@fini";
   3404 			break;
   3405 		case FN_TEST:
   3406 			flag = "@test";
   3407 			break;
   3408 		default:
   3409 			expect(ctx, &adecl->loc, 0,
   3410 				"Only one of @init, @fini, or @test may be used in a function declaration");
   3411 		};
   3412 		expect(ctx, &adecl->loc, obj->type->func.result == &builtin_type_void,
   3413 				"%s function must return void", flag);
   3414 		expect(ctx, &adecl->loc, (obj->type->func.flags & FN_NORETURN) == 0,
   3415 				"%s function must return", flag);
   3416 		expect(ctx, &adecl->loc, !decl->exported,
   3417 				"%s function cannot be exported", flag);
   3418 		expect(ctx, &adecl->loc, !afndecl->prototype.params,
   3419 				"%s function cannot have parameters", flag);
   3420 	}
   3421 	if (obj->type->func.flags & FN_NORETURN) {
   3422 		expect(ctx, &adecl->loc, obj->type->func.result == &builtin_type_void,
   3423 				"@noreturn function must return void");
   3424 	};
   3425 
   3426 	scope_pop(&ctx->scope);
   3427 	ctx->fntype = NULL;
   3428 	return decl;
   3429 }
   3430 
   3431 static struct declaration *
   3432 check_global(struct context *ctx,
   3433 	const struct scope_object *obj,
   3434 	const struct ast_global_decl *adecl)
   3435 {
   3436 	struct declaration *decl = xcalloc(1, sizeof(struct declaration));
   3437 	decl->type = DECL_GLOBAL;
   3438 	decl->global.type = obj->type;
   3439 	decl->global.threadlocal = adecl->threadlocal;
   3440 
   3441 	decl->symbol = ident_to_sym(&obj->ident);
   3442 	mkident(ctx, &decl->ident, &adecl->ident, NULL);
   3443 
   3444 	if (!adecl->init) {
   3445 		return decl; // Forward declaration
   3446 	}
   3447 
   3448 	// TODO: Free initialier
   3449 	struct expression *initializer =
   3450 		xcalloc(1, sizeof(struct expression));
   3451 	check_expression(ctx, adecl->init, initializer, obj->type);
   3452 	// TODO: Pass errors up and deal with them at the end of check
   3453 
   3454 	char *typename1 = gen_typename(initializer->result);
   3455 	char *typename2 = gen_typename(obj->type);
   3456 	expect(ctx, &adecl->init->loc,
   3457 		type_is_assignable(obj->type, initializer->result),
   3458 		"Initializer type %s is not assignable to constant type %s",
   3459 		typename1, typename2);
   3460 	free(typename1);
   3461 	free(typename2);
   3462 
   3463 	initializer = lower_implicit_cast(obj->type, initializer);
   3464 
   3465 	struct expression *value =
   3466 		xcalloc(1, sizeof(struct expression));
   3467 	enum eval_result r = eval_expr(ctx, initializer, value);
   3468 	expect(ctx, &adecl->init->loc, r == EVAL_OK,
   3469 		"Unable to evaluate global initializer at compile time");
   3470 
   3471 	decl->global.value = value;
   3472 
   3473 	free(initializer);
   3474 
   3475 	return decl;
   3476 }
   3477 
   3478 static struct declaration *
   3479 check_type(struct context *ctx,
   3480 	const struct scope_object *obj,
   3481 	const struct ast_type_decl *adecl,
   3482 	bool exported)
   3483 {
   3484 	struct declaration *decl = xcalloc(1, sizeof(struct declaration));
   3485 	decl->type = DECL_TYPE;
   3486 	decl->ident = obj->ident;
   3487 	decl->_type = obj->type;
   3488 	return decl;
   3489 }
   3490 
   3491 static struct declarations **
   3492 check_declaration(struct context *ctx,
   3493 		const struct incomplete_declaration *idecl,
   3494 		struct declarations **next)
   3495 {
   3496 	const struct ast_decl *adecl = &idecl->decl;
   3497 	struct declaration *decl = NULL;
   3498 	switch (adecl->decl_type) {
   3499 	case AST_DECL_CONST:
   3500 		decl = check_const(ctx, &idecl->obj, &adecl->loc, &adecl->constant);
   3501 		break;
   3502 	case AST_DECL_FUNC:
   3503 		decl = check_function(ctx, &idecl->obj, adecl);
   3504 		break;
   3505 	case AST_DECL_GLOBAL:
   3506 		decl = check_global(ctx, &idecl->obj, &adecl->global);
   3507 		break;
   3508 	case AST_DECL_TYPE:
   3509 		decl = check_type(ctx, &idecl->obj, &adecl->type, adecl->exported);
   3510 		break;
   3511 	}
   3512 
   3513 	if (decl) {
   3514 		struct declarations *decls = *next =
   3515 			xcalloc(1, sizeof(struct declarations));
   3516 		decl->exported = adecl->exported;
   3517 		decl->loc = adecl->loc;
   3518 		decls->decl = decl;
   3519 		next = &decls->next;
   3520 	}
   3521 	return next;
   3522 }
   3523 
   3524 static struct incomplete_declaration *
   3525 incomplete_declaration_create(struct context *ctx, struct location loc,
   3526 		struct scope *scope, const struct identifier *ident,
   3527 		const struct identifier *name)
   3528 {
   3529 	struct scope *subunit = ctx->unit->parent;
   3530 	ctx->unit->parent = NULL;
   3531 	struct incomplete_declaration *idecl =
   3532 		(struct incomplete_declaration *)scope_lookup(scope, name);
   3533 	ctx->unit->parent = subunit;
   3534 
   3535 	if (idecl) {
   3536 		expect(ctx, &loc, NULL, "Duplicate global identifier '%s'",
   3537 			identifier_unparse(ident));
   3538 		return idecl;
   3539 	}
   3540 	idecl =  xcalloc(1, sizeof(struct incomplete_declaration));
   3541 
   3542 	scope_object_init((struct scope_object *)idecl, O_SCAN,
   3543 			ident, name, NULL, NULL);
   3544 	scope_insert_from_object(scope, (struct scope_object *)idecl);
   3545 	return idecl;
   3546 }
   3547 
   3548 static void
   3549 scan_enum_field(struct context *ctx, struct scope *imports,
   3550 		struct scope *enum_scope, const struct type *etype,
   3551 		struct ast_enum_field *f)
   3552 {
   3553 	// We have to process the last field first
   3554 	// This way, objects in enum_scope will have lnext pointing to
   3555 	// the previous element, which is important for implicit enum values.
   3556 	if (f->next) {
   3557 		scan_enum_field(ctx, imports, enum_scope,
   3558 			etype, f->next);
   3559 	}
   3560 	assert(etype->storage == STORAGE_ENUM);
   3561 	struct incomplete_enum_field *field =
   3562 		xcalloc(1, sizeof(struct incomplete_enum_field));
   3563 	*field = (struct incomplete_enum_field){
   3564 		.field = f,
   3565 		.enum_scope = enum_scope,
   3566 	};
   3567 
   3568 	struct identifier localname = {
   3569 		.name = (char *)f->name,
   3570 	};
   3571 	struct identifier name = {
   3572 		.name = (char *)f->name,
   3573 		.ns = (struct identifier *)&etype->alias.name,
   3574 	};
   3575 	struct incomplete_declaration *fld =
   3576 		incomplete_declaration_create(ctx, f->loc, enum_scope,
   3577 				&name, &localname);
   3578 	fld->type = IDECL_ENUM_FLD;
   3579 	fld->imports = imports;
   3580 	fld->obj.type = etype,
   3581 	fld->field = field;
   3582 }
   3583 
   3584 static void
   3585 scan_types(struct context *ctx, struct scope *imp, struct ast_decl *decl)
   3586 {
   3587 	for (struct ast_type_decl *t = &decl->type; t; t = t->next) {
   3588 		struct identifier with_ns = {0};
   3589 		mkident(ctx, &with_ns, &t->ident, NULL);
   3590 		struct incomplete_declaration *idecl =
   3591 			incomplete_declaration_create(ctx, decl->loc, ctx->scope,
   3592 					&with_ns, &t->ident);
   3593 		idecl->decl = (struct ast_decl){
   3594 			.decl_type = AST_DECL_TYPE,
   3595 			.loc = decl->loc,
   3596 			.type = *t,
   3597 			.exported = decl->exported,
   3598 		};
   3599 		idecl->imports = imp;
   3600 		if (t->type->storage == STORAGE_ENUM) {
   3601 			bool exported = idecl->decl.exported;
   3602 			const struct type *type = type_store_lookup_enum(
   3603 					ctx->store, t->type, exported);
   3604 			if (type->storage == STORAGE_VOID) {
   3605 				return; // error occured
   3606 			}
   3607 			scope_push((struct scope **)&type->_enum.values, SCOPE_ENUM);
   3608 			scan_enum_field(ctx, imp,
   3609 				type->_enum.values, type, t->type->_enum.values);
   3610 			type->_enum.values->parent = ctx->defines;
   3611 			idecl->obj.otype = O_TYPE;
   3612 			idecl->obj.type = type;
   3613 		} else {
   3614 			idecl->type = IDECL_DECL;
   3615 		}
   3616 	}
   3617 }
   3618 
   3619 void
   3620 resolve_const(struct context *ctx, struct incomplete_declaration *idecl)
   3621 {
   3622 	const struct ast_global_decl *decl = &idecl->decl.global;
   3623 
   3624 	assert(!decl->symbol); // Invariant
   3625 
   3626 	const struct type *type = NULL;
   3627 	if (decl->type) {
   3628 		type = type_store_lookup_atype(ctx->store, decl->type);
   3629 	}
   3630 	struct expression *initializer = xcalloc(1, sizeof(struct expression));
   3631 	check_expression(ctx, decl->init, initializer, type);
   3632 	bool context = decl->type
   3633 		&& decl->type->storage == STORAGE_ARRAY
   3634 		&& decl->type->array.contextual;
   3635 	if (context || !decl->type) {
   3636 		// XXX: Do we need to do anything more here
   3637 		type = lower_const(initializer->result, NULL);
   3638 	}
   3639 
   3640 	char *typename1 = gen_typename(initializer->result);
   3641 	char *typename2 = gen_typename(type);
   3642 	expect(ctx, &decl->init->loc, type_is_assignable(type, initializer->result),
   3643 		"Initializer type %s is not assignable to constant type %s",
   3644 		typename1, typename2);
   3645 	free(typename1);
   3646 	free(typename2);
   3647 	initializer = lower_implicit_cast(type, initializer);
   3648 
   3649 	struct expression *value =
   3650 		xcalloc(1, sizeof(struct expression));
   3651 	enum eval_result r = eval_expr(ctx, initializer, value);
   3652 	expect(ctx, &decl->init->loc, r == EVAL_OK,
   3653 		"Unable to evaluate constant initializer at compile time");
   3654 	expect(ctx, &decl->init->loc, type->storage != STORAGE_NULL,
   3655 		"Null is not a valid type for a constant");
   3656 	free(initializer);
   3657 
   3658 	idecl->obj.otype = O_CONST;
   3659 	idecl->obj.type = type;
   3660 	idecl->obj.value = value;
   3661 }
   3662 
   3663 void
   3664 resolve_function(struct context *ctx, struct incomplete_declaration *idecl)
   3665 {
   3666 	const struct ast_function_decl *decl = &idecl->decl.function;
   3667 
   3668 	const struct ast_type fn_atype = {
   3669 		.storage = STORAGE_FUNCTION,
   3670 		.flags = TYPE_CONST,
   3671 		.func = decl->prototype,
   3672 	};
   3673 	const struct type *fntype = type_store_lookup_atype(
   3674 			ctx->store, &fn_atype);
   3675 
   3676 	idecl->obj.otype = O_DECL;
   3677 	idecl->obj.type = fntype;
   3678 }
   3679 
   3680 void
   3681 resolve_global(struct context *ctx, struct incomplete_declaration *idecl)
   3682 {
   3683 	const struct ast_global_decl *decl = &idecl->decl.global;
   3684 
   3685 	const struct type *type = NULL;
   3686 	if (decl->type) {
   3687 		type = type_store_lookup_atype(ctx->store, decl->type);
   3688 		if (decl->type->storage == STORAGE_ARRAY
   3689 				&& decl->type->array.contextual) {
   3690 			expect(ctx, &decl->type->loc, decl->init,
   3691 				"Cannot infer array length without an initializer");
   3692 
   3693 			struct expression *initializer =
   3694 				xcalloc(1, sizeof(struct expression));
   3695 			check_expression(ctx, decl->init, initializer, type);
   3696 			expect(ctx, &decl->init->loc,
   3697 				initializer->result->storage == STORAGE_ARRAY,
   3698 				"Cannot infer array length from non-array type");
   3699 			expect(ctx, &decl->init->loc,
   3700 				initializer->result->array.members == type->array.members,
   3701 				"Initializer is not assignable to binding type");
   3702 			type = initializer->result;
   3703 			free(initializer);
   3704 		}
   3705 	} else {
   3706 		// the type is set by the expression
   3707 		struct expression *initializer =
   3708 			xcalloc(1, sizeof(struct expression));
   3709 		expect(ctx, &idecl->decl.loc, decl->init,
   3710 			"Cannot infer type without an initializer");
   3711 		check_expression(ctx, decl->init, initializer, type);
   3712 		type = lower_const(initializer->result, NULL);
   3713 		assert(type);
   3714 		free(initializer);
   3715 	}
   3716 
   3717 	expect(ctx, &decl->init->loc, type->storage != STORAGE_NULL,
   3718 		"Null is not a valid type for a global");
   3719 
   3720 	idecl->obj.otype = O_DECL;
   3721 	idecl->obj.type = type;
   3722 	idecl->obj.threadlocal = decl->threadlocal;
   3723 }
   3724 
   3725 void
   3726 resolve_enum_field(struct context *ctx, struct incomplete_declaration *idecl)
   3727 {
   3728 	assert(idecl->type == IDECL_ENUM_FLD);
   3729 
   3730 	const struct type *type = idecl->obj.type;
   3731 
   3732 	struct identifier localname = {
   3733 		.name = idecl->obj.ident.name
   3734 	};
   3735 
   3736 	const struct scope_object *new =
   3737 		scope_lookup(idecl->field->enum_scope, &localname);
   3738 	if (new != &idecl->obj) {
   3739 		wrap_resolver(ctx, new, resolve_enum_field);
   3740 		assert(new->otype == O_CONST);
   3741 		idecl->obj.otype = O_CONST;
   3742 		idecl->obj.type = type;
   3743 		idecl->obj.value = new->value;
   3744 		return;
   3745 	}
   3746 
   3747 	ctx->scope = idecl->field->enum_scope;
   3748 	struct expression *value = xcalloc(1, sizeof(struct expression));
   3749 	value->result = type;
   3750 	if (idecl->field->field->value) { // explicit value
   3751 		struct expression *initializer =
   3752 			xcalloc(1, sizeof(struct expression));
   3753 		check_expression(ctx, idecl->field->field->value,
   3754 				initializer, type->alias.type);
   3755 
   3756 		char *inittypename = gen_typename(initializer->result);
   3757 		char *builtintypename = gen_typename(type->alias.type);
   3758 		expect(ctx, &idecl->field->field->value->loc,
   3759 			type_is_assignable(type->alias.type, initializer->result),
   3760 			"Enum value type (%s) is not assignable from initializer type (%s) for value %s",
   3761 			builtintypename, inittypename, idecl->obj.ident.name);
   3762 		free(inittypename);
   3763 		free(builtintypename);
   3764 
   3765 		initializer = lower_implicit_cast(type, initializer);
   3766 		enum eval_result r = eval_expr(ctx, initializer, value);
   3767 		expect(ctx, &idecl->field->field->value->loc, r == EVAL_OK,
   3768 			"Unable to evaluate constant initializer at compile time");
   3769 	} else { // implicit value
   3770 		const struct scope_object *obj = idecl->obj.lnext;
   3771 		// find previous enum value
   3772 		wrap_resolver(ctx, obj, resolve_enum_field);
   3773 		value->type = EXPR_CONSTANT;
   3774 		if (type_is_signed(type_dealias(type))) {
   3775 			if (obj == NULL) {
   3776 				value->constant.ival = 0;
   3777 			} else {
   3778 				value->constant.ival = obj->value->constant.ival + 1;
   3779 			}
   3780 		} else {
   3781 			if (obj == NULL) {
   3782 				value->constant.uval = 0;
   3783 			} else {
   3784 				value->constant.uval = obj->value->constant.uval + 1;
   3785 			}
   3786 		}
   3787 	}
   3788 
   3789 	idecl->obj.otype = O_CONST;
   3790 	idecl->obj.value = value;
   3791 }
   3792 
   3793 const struct type *
   3794 lookup_enum_type(struct context *ctx, const struct scope_object *obj)
   3795 {
   3796 	const struct type *enum_type = NULL;
   3797 
   3798 	switch (obj->otype) {
   3799 	case O_SCAN: {
   3800 		struct incomplete_declaration *idecl =
   3801 			(struct incomplete_declaration *)obj;
   3802 
   3803 		if (idecl->in_progress) {
   3804 			// Type alias cycle will be handled in check
   3805 			return NULL;
   3806 		}
   3807 
   3808 		if (idecl->type != IDECL_DECL ||
   3809 				idecl->decl.decl_type != AST_DECL_TYPE) {
   3810 			return NULL;
   3811 		}
   3812 
   3813 		if (idecl->decl.type.type->storage == STORAGE_ENUM) {
   3814 			assert(false);
   3815 		} else if (idecl->decl.type.type->storage == STORAGE_ALIAS) {
   3816 			ctx->scope->parent = idecl->imports;
   3817 			const struct identifier *alias =
   3818 				&idecl->decl.type.type->alias;
   3819 			const struct scope_object *new = scope_lookup(ctx->scope,
   3820 					alias);
   3821 			if (new) {
   3822 				idecl->in_progress = true;
   3823 				enum_type = lookup_enum_type(ctx, new);
   3824 				idecl->in_progress = false;
   3825 			}
   3826 		}
   3827 		break;
   3828 	}
   3829 	case O_TYPE:
   3830 		enum_type = obj->type;
   3831 		break;
   3832 	default:
   3833 		return NULL;
   3834 	}
   3835 
   3836 	if (!enum_type) {
   3837 		return NULL;
   3838 	}
   3839 
   3840 	enum_type = type_dealias(enum_type);
   3841 	if (enum_type->storage != STORAGE_ENUM) {
   3842 		return NULL;
   3843 	}
   3844 	return enum_type;
   3845 }
   3846 
   3847 static void
   3848 scan_enum_field_aliases(struct context *ctx, const struct scope_object *obj)
   3849 {
   3850 	const struct type *enum_type = lookup_enum_type(ctx, obj);
   3851 
   3852 	if (!enum_type) {
   3853 		return;
   3854 	}
   3855 
   3856 	// orig->type is (perhaps transitively) an alias of a resolved enum
   3857 	// type, which means its dependency graph is a linear chain of
   3858 	// resolved types ending with that enum, so we can immediately resolve it
   3859 	wrap_resolver(ctx, obj, resolve_type);
   3860 
   3861 	for (const struct scope_object *val = enum_type->_enum.values->objects;
   3862 			val; val = val->lnext) {
   3863 		struct identifier name = {
   3864 			.name = val->name.name,
   3865 			.ns = (struct identifier *)&obj->name,
   3866 		};
   3867 		struct identifier ident = {
   3868 			.name = val->name.name,
   3869 			.ns = (struct identifier *)&obj->ident,
   3870 		};
   3871 		struct ast_enum_field *afield =
   3872 			xcalloc(1, sizeof(struct ast_enum_field));
   3873 		*afield = (struct ast_enum_field){
   3874 			.loc = (struct location){0}, // XXX: what to put here?
   3875 			.name = xstrdup(val->name.name),
   3876 		};
   3877 
   3878 		struct incomplete_enum_field *field =
   3879 			xcalloc(1, sizeof(struct incomplete_enum_field));
   3880 		struct incomplete_declaration *idecl =
   3881 			(struct incomplete_declaration *)val;
   3882 		*field = (struct incomplete_enum_field){
   3883 			.field = afield,
   3884 			.enum_scope = idecl->field->enum_scope,
   3885 		};
   3886 
   3887 		idecl = incomplete_declaration_create(ctx, (struct location){0},
   3888 			ctx->scope, &ident, &name);
   3889 		idecl->type = IDECL_ENUM_FLD;
   3890 		idecl->obj.type = obj->type;
   3891 		idecl->field = field;
   3892 	};
   3893 }
   3894 
   3895 void
   3896 resolve_dimensions(struct context *ctx, struct incomplete_declaration *idecl)
   3897 {
   3898 	if (idecl->type != IDECL_DECL || idecl->decl.decl_type != AST_DECL_TYPE) {
   3899 		struct location loc;
   3900 		if (idecl->type == IDECL_ENUM_FLD) {
   3901 			loc = idecl->field->field->loc;
   3902 		} else {
   3903 			loc = idecl->decl.loc;
   3904 		}
   3905 		error(ctx, loc, false, "'%s' is not a type",
   3906 				identifier_unparse(&idecl->obj.name));
   3907 		handle_errors(ctx->errors);
   3908 	}
   3909 	struct dimensions dim = type_store_lookup_dimensions(ctx->store,
   3910 			idecl->decl.type.type);
   3911 	idecl->obj.type = xcalloc(1, sizeof(struct type));
   3912 	*(struct type *)idecl->obj.type = (struct type){
   3913 		.size = dim.size,
   3914 		.align = dim.align,
   3915 	};
   3916 }
   3917 
   3918 void
   3919 resolve_type(struct context *ctx, struct incomplete_declaration *idecl)
   3920 {
   3921 	if (idecl->type != IDECL_DECL || idecl->decl.decl_type != AST_DECL_TYPE) {
   3922 		struct location loc;
   3923 		if (idecl->type == IDECL_ENUM_FLD) {
   3924 			loc = idecl->field->field->loc;
   3925 		} else {
   3926 			loc = idecl->decl.loc;
   3927 		}
   3928 		error(ctx, loc, NULL, "'%s' is not a type",
   3929 				identifier_unparse(&idecl->obj.name));
   3930 		handle_errors(ctx->errors);
   3931 	}
   3932 
   3933 	// 1. compute type dimensions
   3934 	struct dimensions dim = type_store_lookup_dimensions(
   3935 			ctx->store, idecl->decl.type.type);
   3936 
   3937 	handle_errors(ctx->errors);
   3938 	idecl->in_progress = false;
   3939 
   3940 	// 2. compute type representation and store it
   3941 	struct type _alias = {
   3942 		.storage = STORAGE_ALIAS,
   3943 		.alias = {
   3944 			.ident = idecl->obj.ident,
   3945 			.name = idecl->obj.name,
   3946 			.type = NULL,
   3947 			.exported = idecl->decl.exported,
   3948 		},
   3949 		.size = dim.size,
   3950 		.align = dim.align,
   3951 		.flags = idecl->decl.type.type->flags,
   3952 	};
   3953 
   3954 	const struct type *alias = type_store_lookup_alias(
   3955 			ctx->store, &_alias, &dim);
   3956 	idecl->obj.otype = O_TYPE;
   3957 	idecl->obj.type = alias;
   3958 	((struct type *)alias)->alias.type =
   3959 		type_store_lookup_atype(ctx->store, idecl->decl.type.type);
   3960 }
   3961 
   3962 static struct incomplete_declaration *
   3963 scan_const(struct context *ctx, struct scope *imports, bool exported,
   3964 		struct location loc, struct ast_global_decl *decl)
   3965 {
   3966 
   3967 	struct identifier with_ns = {0};
   3968 	mkident(ctx, &with_ns, &decl->ident, NULL);
   3969 	struct incomplete_declaration *idecl =
   3970 		incomplete_declaration_create(ctx, loc,
   3971 				ctx->scope, &with_ns, &decl->ident);
   3972 	idecl->type = IDECL_DECL;
   3973 	idecl->decl = (struct ast_decl){
   3974 		.decl_type = AST_DECL_CONST,
   3975 		.loc = loc,
   3976 		.constant = *decl,
   3977 		.exported = exported,
   3978 	};
   3979 	idecl->imports = imports;
   3980 	return idecl;
   3981 }
   3982 
   3983 static void
   3984 scan_decl(struct context *ctx, struct scope *imports, struct ast_decl *decl)
   3985 {
   3986 	switch (decl->decl_type) {
   3987 	case AST_DECL_CONST:
   3988 		for (struct ast_global_decl *g = &decl->constant; g; g = g->next) {
   3989 			scan_const(ctx, imports, decl->exported, decl->loc, g);
   3990 		}
   3991 		break;
   3992 	case AST_DECL_GLOBAL:
   3993 		for (struct ast_global_decl *g = &decl->global; g; g = g->next) {
   3994 			struct identifier with_ns = {0};
   3995 			mkident(ctx, &with_ns, &g->ident, g->symbol);
   3996 			struct incomplete_declaration *idecl =
   3997 				incomplete_declaration_create(ctx, decl->loc,
   3998 						ctx->scope, &with_ns, &g->ident);
   3999 			idecl->type = IDECL_DECL;
   4000 			idecl->decl = (struct ast_decl){
   4001 				.decl_type = AST_DECL_GLOBAL,
   4002 				.loc = decl->loc,
   4003 				.global = *g,
   4004 				.exported = decl->exported,
   4005 			};
   4006 			idecl->imports = imports;
   4007 		}
   4008 		break;
   4009 	case AST_DECL_FUNC:;
   4010 		struct ast_function_decl *func = &decl->function;
   4011 		struct identifier ident = {0}, *name = NULL;
   4012 		if (func->flags) {
   4013 			const char *template = NULL;
   4014 			if (func->flags & FN_TEST) {
   4015 				template = "testfunc.%d";
   4016 			} else if (func->flags & FN_INIT) {
   4017 				template = "initfunc.%d";
   4018 			} else if (func->flags & FN_FINI) {
   4019 				template = "finifunc.%d";
   4020 			}
   4021 			assert(template);
   4022 			ident.name = gen_name(&ctx->id, template);
   4023 			++ctx->id;
   4024 
   4025 			name = &ident;
   4026 		} else {
   4027 			mkident(ctx, &ident, &func->ident, func->symbol);
   4028 			name = &func->ident;
   4029 		}
   4030 		struct incomplete_declaration *idecl =
   4031 			incomplete_declaration_create(ctx, decl->loc,
   4032 					ctx->scope, &ident, name);
   4033 		idecl->type = IDECL_DECL;
   4034 		idecl->decl = (struct ast_decl){
   4035 			.decl_type = AST_DECL_FUNC,
   4036 			.loc = decl->loc,
   4037 			.function = *func,
   4038 			.exported = decl->exported,
   4039 		};
   4040 		idecl->imports = imports;
   4041 		break;
   4042 	case AST_DECL_TYPE:
   4043 		scan_types(ctx, imports, decl);
   4044 		break;
   4045 	}
   4046 }
   4047 
   4048 void
   4049 resolve_decl(struct context *ctx, struct incomplete_declaration *idecl)
   4050 {
   4051 	switch (idecl->type) {
   4052 	case IDECL_ENUM_FLD:
   4053 		resolve_enum_field(ctx, idecl);
   4054 		return;
   4055 	case IDECL_DECL:
   4056 		break;
   4057 	}
   4058 
   4059 	switch (idecl->decl.decl_type) {
   4060 	case AST_DECL_CONST:
   4061 		resolve_const(ctx, idecl);
   4062 		return;
   4063 	case AST_DECL_GLOBAL:
   4064 		resolve_global(ctx, idecl);
   4065 		return;
   4066 	case AST_DECL_FUNC:
   4067 		resolve_function(ctx, idecl);
   4068 		return;
   4069 	case AST_DECL_TYPE:
   4070 		resolve_type(ctx, idecl);
   4071 		return;
   4072 	}
   4073 	abort();
   4074 }
   4075 
   4076 void
   4077 wrap_resolver(struct context *ctx, const struct scope_object *obj,
   4078 	resolvefn resolver)
   4079 {
   4080 	// save current subunit and enum context
   4081 	struct scope *scope = ctx->scope;
   4082 	struct scope *subunit = ctx->unit->parent;
   4083 	ctx->unit->parent = NULL;
   4084 	const struct type *fntype = ctx->fntype;
   4085 	ctx->fntype = NULL;
   4086 	bool deferring = ctx->deferring;
   4087 	ctx->deferring = false;
   4088 
   4089 	// ensure this declaration wasn't already scanned
   4090 	if (!obj || obj->otype != O_SCAN) {
   4091 		goto exit;
   4092 	}
   4093 
   4094 	struct incomplete_declaration *idecl = (struct incomplete_declaration *)obj;
   4095 
   4096 	// load this declaration's subunit context
   4097 	ctx->scope = ctx->defines;
   4098 	ctx->unit->parent = idecl->imports;
   4099 
   4100 	// resolving a declaration that is already in progress -> cycle
   4101 	if (idecl->in_progress) {
   4102 		struct location loc;
   4103 		if (idecl->type == IDECL_ENUM_FLD) {
   4104 			loc = idecl->field->field->loc;
   4105 		} else {
   4106 			loc = idecl->decl.loc;
   4107 		}
   4108 		error(ctx, loc, NULL, "Circular dependency for '%s'\n",
   4109 			identifier_unparse(&idecl->obj.name));
   4110 		handle_errors(ctx->errors);
   4111 	}
   4112 	idecl->in_progress = true;
   4113 
   4114 	resolver(ctx, idecl);
   4115 
   4116 	idecl->in_progress = false;
   4117 exit:
   4118 	// load stored context
   4119 	ctx->deferring = deferring;
   4120 	ctx->fntype = fntype;
   4121 	ctx->unit->parent = subunit;
   4122 	ctx->scope = scope;
   4123 }
   4124 
   4125 static void
   4126 load_import(struct context *ctx, struct ast_global_decl *defines,
   4127 	struct ast_imports *import, struct type_store *ts, struct scope *scope)
   4128 {
   4129 	struct context *old_ctx = ctx->store->check_context;
   4130 	struct scope *mod = module_resolve(ctx->modcache,
   4131 			defines, &import->ident, ts);
   4132 	ctx->store->check_context = old_ctx;
   4133 
   4134 	struct identifier _ident = {0};
   4135 	struct identifier *mod_ident = &_ident;
   4136 	if (import->mode & (AST_IMPORT_WILDCARD | AST_IMPORT_ALIAS)) {
   4137 		mod_ident = import->alias;
   4138 	} else {
   4139 		mod_ident->name = import->ident.name;
   4140 	}
   4141 	if (import->mode & AST_IMPORT_MEMBERS) {
   4142 		assert(!(import->mode & AST_IMPORT_WILDCARD));
   4143 		for (struct ast_imports *member = import->members;
   4144 				member; member = member->next) {
   4145 			struct identifier name = {
   4146 				.name = member->alias?
   4147 					member->alias->name : member->ident.name,
   4148 				.ns = import->alias,
   4149 			};
   4150 			struct identifier ident = {
   4151 				.name = member->ident.name,
   4152 				.ns = &import->ident,
   4153 			};
   4154 			const struct scope_object *obj = scope_lookup(mod, &ident);
   4155 			if (!obj) {
   4156 				expect(ctx, &member->loc, false, "Unknown object '%s'",
   4157 						identifier_unparse(&ident));
   4158 			}
   4159 			struct scope_object *new = scope_insert(
   4160 					scope, obj->otype, &obj->ident,
   4161 					&name, obj->type, obj->value);
   4162 			new->threadlocal = obj->threadlocal;
   4163 			if (obj->otype != O_TYPE
   4164 					|| type_dealias(obj->type)->storage
   4165 						!= STORAGE_ENUM) {
   4166 				continue;
   4167 			};
   4168 			struct scope *enum_scope =
   4169 				type_dealias(obj->type)->_enum.values;
   4170 			for (struct scope_object *o = enum_scope->objects;
   4171 					o; o = o->lnext) {
   4172 				struct identifier value_ident = {
   4173 					.name = o->name.name,
   4174 					.ns = &ident,
   4175 				};
   4176 				struct identifier value_name = {
   4177 					.name = o->name.name,
   4178 					.ns = &name,
   4179 				};
   4180 				scope_insert(scope, o->otype, &value_ident,
   4181 					&value_name, o->type, o->value);
   4182 			};
   4183 
   4184 		}
   4185 	} else {
   4186 		for (struct scope_object *obj = mod->objects;
   4187 				obj; obj = obj->lnext) {
   4188 			assert(obj->otype != O_SCAN);
   4189 
   4190 			struct scope_object *new;
   4191 			if (!(import->mode & AST_IMPORT_ALIAS)
   4192 					&& import->ident.ns != NULL) {
   4193 				new = scope_insert(scope, obj->otype, &obj->ident,
   4194 					&obj->name, obj->type, obj->value);
   4195 				new->threadlocal = obj->threadlocal;
   4196 			}
   4197 
   4198 			struct identifier ns, name = {
   4199 				.name = obj->name.name,
   4200 				.ns = mod_ident,
   4201 			};
   4202 			if (type_dealias(obj->type)->storage == STORAGE_ENUM
   4203 					&& obj->otype == O_CONST) {
   4204 				ns = (struct identifier){
   4205 					.name = obj->name.ns->name,
   4206 					.ns = mod_ident,
   4207 				};
   4208 				name.ns = &ns;
   4209 			};
   4210 			new = scope_insert(scope, obj->otype, &obj->ident,
   4211 				&name, obj->type, obj->value);
   4212 			new->threadlocal = obj->threadlocal;
   4213 		}
   4214 	}
   4215 }
   4216 
   4217 static const struct location defineloc = {
   4218 	.file = 0,
   4219 	.lineno = 1,
   4220 	.colno = 1,
   4221 };
   4222 
   4223 struct scope *
   4224 check_internal(struct type_store *ts,
   4225 	struct modcache **cache,
   4226 	bool is_test,
   4227 	struct ast_global_decl *defines,
   4228 	const struct ast_unit *aunit,
   4229 	struct unit *unit,
   4230 	bool scan_only)
   4231 {
   4232 	struct context ctx = {0};
   4233 	ctx.ns = unit->ns;
   4234 	ctx.is_test = is_test;
   4235 	ctx.store = ts;
   4236 	ctx.store->check_context = &ctx;
   4237 	ctx.next = &ctx.errors;
   4238 	ctx.modcache = cache;
   4239 
   4240 	// Top-level scope management involves:
   4241 	//
   4242 	// - Creating a top-level scope for the whole unit, to which
   4243 	//   declarations are added.
   4244 	// - Creating a scope for each sub-unit, and populating it with imports.
   4245 	//
   4246 	// Further down the call frame, subsequent functions will create
   4247 	// sub-scopes for each declaration, expression-list, etc.
   4248 
   4249 	// Put defines into a temporary scope (-D on the command line)
   4250 	sources[0] = "-D";
   4251 	ctx.scope = NULL;
   4252 	ctx.unit = scope_push(&ctx.scope, SCOPE_DEFINES);
   4253 	for (struct ast_global_decl *def = defines; def; def = def->next) {
   4254 		struct incomplete_declaration *idecl =
   4255 			scan_const(&ctx, NULL, false , defineloc, def);
   4256 		resolve_const(&ctx, idecl);
   4257 	}
   4258 	ctx.defines = ctx.scope;
   4259 	ctx.scope = NULL;
   4260 	ctx.defines->parent = ctx.unit = scope_push(&ctx.scope, SCOPE_UNIT);
   4261 	sources[0] = "<unknown>";
   4262 
   4263 	// Populate the imports and put declarations into a scope.
   4264 	// Each declaration holds a reference to its subunit's imports
   4265 	// A scope gets us:
   4266 	//  a) duplicate detection for free
   4267 	//  b) a way to find declaration's definition when it's refered to
   4268 	struct scopes *subunit_scopes = NULL, **next = &subunit_scopes;
   4269 	struct scope *su_scope = NULL;
   4270 	struct identifiers **inext = &unit->imports;
   4271 	for (const struct ast_subunit *su = &aunit->subunits;
   4272 			su; su = su->next) {
   4273 		su_scope = NULL;
   4274 		scope_push(&su_scope, SCOPE_SUBUNIT);
   4275 		for (struct ast_imports *imports = su->imports;
   4276 				imports; imports = imports->next) {
   4277 			load_import(&ctx, defines, imports, ts, su_scope);
   4278 
   4279 			bool found = false;
   4280 			for (struct identifiers *uimports = unit->imports;
   4281 					uimports; uimports = uimports->next) {
   4282 				if (identifier_eq(&uimports->ident, &imports->ident)) {
   4283 					found = true;
   4284 					break;
   4285 				}
   4286 			}
   4287 			if (!found) {
   4288 				struct identifiers *uimport = *inext =
   4289 					xcalloc(1, sizeof(struct identifiers));
   4290 				identifier_dup(&uimport->ident, &imports->ident);
   4291 				inext = &uimport->next;
   4292 			}
   4293 		}
   4294 
   4295 		for (struct ast_decls *d = su->decls; d; d = d->next) {
   4296 			scan_decl(&ctx, su_scope, &d->decl);
   4297 		};
   4298 
   4299 		*next = xcalloc(1, sizeof(struct scopes));
   4300 		(*next)->scope = su_scope;
   4301 		next = &(*next)->next;
   4302 	}
   4303 
   4304 	// Find enum aliases and store them in incomplete enum value declarations
   4305 	for (const struct scope_object *obj = ctx.scope->objects;
   4306 			obj; obj = obj->lnext) {
   4307 		scan_enum_field_aliases(&ctx, obj);
   4308 	}
   4309 
   4310 	// XXX: shadowed declarations are not checked for consistency
   4311 	ctx.scope = ctx.defines;
   4312 
   4313 	for (const struct scope_object *obj = ctx.scope->objects;
   4314 			obj; obj = obj->lnext) {
   4315 		const struct scope_object *shadowed_obj =
   4316 			scope_lookup(ctx.unit, &obj->name);
   4317 		if (!shadowed_obj) {
   4318 			continue;
   4319 		}
   4320 		if (shadowed_obj->otype == O_CONST) {
   4321 			continue;
   4322 		}
   4323 		if (shadowed_obj->otype == O_SCAN) {
   4324 			const struct incomplete_declaration *idecl =
   4325 				(struct incomplete_declaration *)shadowed_obj;
   4326 			if (idecl->type == IDECL_DECL &&
   4327 					idecl->decl.decl_type == AST_DECL_CONST) {
   4328 				continue;
   4329 			}
   4330 		}
   4331 		error(&ctx, defineloc, NULL, "Define shadows a non-define object");
   4332 	}
   4333 
   4334 	struct declarations **next_decl = &unit->declarations;
   4335 	// Perform actual declaration resolution
   4336 	for (const struct scope_object *obj = ctx.unit->objects;
   4337 			obj; obj = obj->lnext) {
   4338 		wrap_resolver(&ctx, obj, resolve_decl);
   4339 		// Populate the expression graph
   4340 		const struct incomplete_declaration *idecl =
   4341 			(const struct incomplete_declaration *)obj;
   4342 		if (idecl->type != IDECL_DECL) {
   4343 			continue;
   4344 		}
   4345 		ctx.unit->parent = idecl->imports;
   4346 		next_decl = check_declaration(&ctx, idecl, next_decl);
   4347 	}
   4348 
   4349 	handle_errors(ctx.errors);
   4350 
   4351 	if (!(scan_only || unit->declarations)) {
   4352 		fprintf(stderr, "Error: module contains no declarations\n");
   4353 		exit(EXIT_FAILURE);
   4354 	}
   4355 
   4356 	ctx.store->check_context = NULL;
   4357 	ctx.unit->parent = NULL;
   4358 	return ctx.unit;
   4359 }
   4360 
   4361 struct scope *
   4362 check(struct type_store *ts,
   4363 	bool is_test,
   4364 	struct ast_global_decl *defines,
   4365 	const struct ast_unit *aunit,
   4366 	struct unit *unit)
   4367 {
   4368 	struct modcache *modcache[MODCACHE_BUCKETS];
   4369 	memset(modcache, 0, sizeof(modcache));
   4370 	return check_internal(ts, modcache, is_test, defines, aunit, unit, false);
   4371 }