From b806bafb51db948146d570a19be54536b5de76f1 Mon Sep 17 00:00:00 2001 From: Krzosa Karol Date: Thu, 28 Jul 2022 13:29:25 +0200 Subject: [PATCH] Fixing array code generation --- c_language_codegen.cpp | 15 +++++++++++++-- examples/arrays_and_slices.kl | 29 +++++++++++++++++++++++------ 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/c_language_codegen.cpp b/c_language_codegen.cpp index 78ab5f6..679485a 100644 --- a/c_language_codegen.cpp +++ b/c_language_codegen.cpp @@ -520,8 +520,18 @@ gen_ast(Ast *ast){ // Array iter if(node->is_array_traversal){ gen("for(S64 _i%d = 0; _i%d < ", node->pos->line, node->pos->line); - gen_expr(node->cond); - gen(".len; _i%d+=1)", node->pos->line); + if(is_array(node->cond->resolved_type)){ + gen("_buff_cap("); + gen_expr(node->cond); + gen(")"); + } else{ + assert(is_slice(node->cond->resolved_type)); + gen_expr(node->cond); + gen(".len"); + } + + + gen("; _i%d+=1)", node->pos->line); gen("{"); global_indent++; genln(""); @@ -719,6 +729,7 @@ typedef S64 Type; #define false 0 #define assert(x) do{if(!(x))__debugbreak();}while(0) #define assert_msg(x,...) assert(x) +#define _buff_cap(x) (sizeof(x)/sizeof((x)[0])) typedef struct String{ U8 *str; S64 len; diff --git a/examples/arrays_and_slices.kl b/examples/arrays_and_slices.kl index 4ddc0b7..2ce7daa 100644 --- a/examples/arrays_and_slices.kl +++ b/examples/arrays_and_slices.kl @@ -17,11 +17,28 @@ main :: (): int // We can get size of array using length_of builtin #assert(length_of(static_array) == 8) - element: int = static_array[0] - assert(static_array[1] == 0) - assert(element == 0) + // Accessing values is like in C // Variables are zeroed by default - // assert(static_array[7] == 0) + assert(static_array[1] == 0) + + element2 := static_array[2] + element0: int = static_array[0] + assert(element0 == 0 && element2 == 0) + + // We can loop through arrays + // this implicitly defines 'it' variable + for static_array + *it = 1 + + // We set all variables to 1 so + assert(static_array[6] == 1) + + + // This is how slice is defined, no [] index in between brackets + // slice is array pointer + length + // Other then that it works exactly like regular array + slice: []int = static_array + + // We can't do a compile time assert anymore + assert(length_of(slice) == 8) - // for static_array - // it = 1