harec

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

check.c (122868B)


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