Typecheck list initializer for structs

This commit is contained in:
Sofia 2026-04-15 19:28:09 +03:00
parent 1265040f29
commit b664ca8f9d
2 changed files with 31 additions and 1 deletions

View File

@ -330,6 +330,36 @@ namespace AST {
} }
}; };
} }
else if ((*expected_ty)->m_kind == types::TypeKind::Struct) {
auto struct_ty = dynamic_cast<types::StructType*>(expected_ty->get());
if (struct_ty->m_fields) {
if (this->m_expressions.size() > struct_ty->m_fields->size()) {
state.errors.push_back(CompileError(
"Too many initializer values for " + struct_ty->formatted(),
this->m_meta));
return *expected_ty;
}
for (int i = 0; i < static_cast<int>(this->m_expressions.size()); i++) {
auto expected_field = (*struct_ty->m_fields)[i];
auto expr_ty = this->m_expressions[i]->typecheck(state, scope, expected_field.second);
auto res = check_type(state, expr_ty, expected_field.second);
this->m_expressions[i] = handle_res(std::move(this->m_expressions[i]), res, state);
}
return *expected_ty;
}
else {
if (this->m_expressions.size() > 0) {
state.errors.push_back(CompileError(
"Too many initializer values for " + struct_ty->formatted(),
this->m_meta));
return *expected_ty;
}
}
}
else { else {
return std::shared_ptr<types::Type> { return std::shared_ptr<types::Type> {
new types::FundamentalType{ types::FundamentalTypeKind::Void } new types::FundamentalType{ types::FundamentalTypeKind::Void }

2
test.c
View File

@ -24,7 +24,7 @@ int main() {
printf(" first element: %d!", somelist[0]); printf(" first element: %d!", somelist[0]);
struct Otus otus; struct Otus otus = { 5 };
return 0; return 0;
} }