preliminary variable decl type inference from expr

Start work on basic type inference, here for inferring the type of a
variable declaration from its assigned expression.
This commit is contained in:
tocariimaa 2025-01-15 13:47:59 -03:00
parent 001a06dd2d
commit 41589320de

View file

@ -688,24 +688,29 @@ sema_var_decl(SemaCtx *sctx, AstVarDecl *decl, Location loc)
}
Ast *dexpr = decl->expr;
DataType *dexpr_dt = nil;
if (dexpr != nil) {
sema_expr(sctx, dexpr, loc); /* check the assignment expression */
} else {
/* check the assignment expression */
dexpr_dt = sema_expr(sctx, dexpr, loc);
} else if (dexpr == nil && decl->datatype != nil) {
sema_warning(sctx, &loc, "variable is unitialized");
}
if (decl->datatype == nil) {
sema_error(sctx, nil, "we don't do type inference yet sorry");
return;
DataType *dtype = nil;
if (decl->datatype != nil) { /* explicit data type specified */
compiler_assert(sctx->cm, decl->datatype->type == AST_IDENT);
dtype = resolve_datatype(sctx, decl->datatype->ident, decl->datatype->loc);
/* Note that we ignore whether `resolve_datatype` return an invalid type,
* since we still want to insert the variable into the symbol table,
* otherwise we would have spurious "undeclared identifier" errors. */
decl->type = dtype;
} else {
/* the parser should catch this (the grammar requires it) */
compiler_assert(sctx->cm, dexpr != nil);
compiler_assert(sctx->cm, dexpr_dt != nil);
decl->type = dexpr_dt;
}
compiler_assert(sctx->cm, decl->datatype->type == AST_IDENT);
DataType *dtype = resolve_datatype(sctx, decl->datatype->ident, decl->datatype->loc);
/* Note that we ignore whether `resolve_datatype` return an invalid type,
* since we still want to insert the variable into the symbol table,
* otherwise we would have spurious "undeclared identifier" errors. */
decl->type = dtype;
Symbol sym = {
.kind = decl->kind,
.dtype = dtype,