From 41589320deafdfac15d6dc99d8af5a02fff4657c Mon Sep 17 00:00:00 2001 From: tocariimaa Date: Wed, 15 Jan 2025 13:47:59 -0300 Subject: [PATCH] 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. --- compiler/sema.c | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/compiler/sema.c b/compiler/sema.c index 8b8deae..405f524 100644 --- a/compiler/sema.c +++ b/compiler/sema.c @@ -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,