From c093f16fd0e6108fd51bec2a04f22cd47788c4e2 Mon Sep 17 00:00:00 2001 From: Christoffer Lerno Date: Mon, 14 Nov 2022 15:05:01 +0100 Subject: [PATCH] Fix missing check on foreach indexing. --- src/compiler/sema_stmts.c | 6 +++++ .../statements/foreach_wrong_index.c3 | 27 +++++++++++++++++++ .../statements/foreach_wrong_index.c3 | 27 +++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 test/test_suite/statements/foreach_wrong_index.c3 create mode 100644 test/test_suite2/statements/foreach_wrong_index.c3 diff --git a/src/compiler/sema_stmts.c b/src/compiler/sema_stmts.c index 1cf2d2a05..d0d95cf9d 100644 --- a/src/compiler/sema_stmts.c +++ b/src/compiler/sema_stmts.c @@ -1242,7 +1242,13 @@ static inline bool sema_analyse_foreach_stmt(SemaContext *context, Ast *statemen return false; } index_macro = value_by_ref ? by_ref : by_val; + assert(index_macro); index_type = index_macro->func_decl.signature.params[1]->type; + if (!type_is_integer(index_type)) + { + SEMA_ERROR(enumerator, "Only integer indexed types may be used with foreach."); + return false; + } TypeInfoId rtype = index_macro->func_decl.signature.rtype; value_type = rtype ? type_infoptr(rtype)->type : NULL; } diff --git a/test/test_suite/statements/foreach_wrong_index.c3 b/test/test_suite/statements/foreach_wrong_index.c3 new file mode 100644 index 000000000..a89041c8b --- /dev/null +++ b/test/test_suite/statements/foreach_wrong_index.c3 @@ -0,0 +1,27 @@ +import std::io; + +struct Foo +{ + int[3] elements; +} + +fn int Foo.at(Foo *vector, float index) @operator([]) +{ + return 1; +} + +fn int Foo.len(Foo *vector) @operator(len) +{ + return 3; +} + +fn void main() +{ + + Foo f; + io::printfln("%s", f[12.2]); + foreach (int i, value : f) // #error: Only integer + { + io::printfln("v[%s] = %s", i, value); + } +} \ No newline at end of file diff --git a/test/test_suite2/statements/foreach_wrong_index.c3 b/test/test_suite2/statements/foreach_wrong_index.c3 new file mode 100644 index 000000000..a89041c8b --- /dev/null +++ b/test/test_suite2/statements/foreach_wrong_index.c3 @@ -0,0 +1,27 @@ +import std::io; + +struct Foo +{ + int[3] elements; +} + +fn int Foo.at(Foo *vector, float index) @operator([]) +{ + return 1; +} + +fn int Foo.len(Foo *vector) @operator(len) +{ + return 3; +} + +fn void main() +{ + + Foo f; + io::printfln("%s", f[12.2]); + foreach (int i, value : f) // #error: Only integer + { + io::printfln("v[%s] = %s", i, value); + } +} \ No newline at end of file