From 66e3aa09104781f460da1ea721b083d18eec351b Mon Sep 17 00:00:00 2001 From: Josh Wolfe Date: Sun, 6 Dec 2015 23:33:10 -0700 Subject: [PATCH] initialize mutable variables to zero --- src/analyze.cpp | 4 ++-- src/codegen.cpp | 10 +++++----- test/run_tests.cpp | 7 +++++-- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/analyze.cpp b/src/analyze.cpp index b55c5251e4..a626649323 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -454,8 +454,8 @@ static TypeTableEntry * analyze_expression(CodeGen *g, ImportTableEntry *import, buf_sprintf("variable initialization is unreachable")); } - if (implicit_type == nullptr) { - add_node_error(g, node, buf_sprintf("initial values are required for variable declaration")); + if (implicit_type == nullptr && variable_declaration->is_const) { + add_node_error(g, node, buf_sprintf("variables must have initial values or be declared 'mut'.")); } TypeTableEntry *type = explicit_type != nullptr ? explicit_type : implicit_type; diff --git a/src/codegen.cpp b/src/codegen.cpp index be4d695279..e1a5525e37 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -526,14 +526,14 @@ static LLVMValueRef gen_expr(CodeGen *g, AstNode *node) { variable->value_ref = gen_expr(g, node->data.variable_declaration.expr); return nullptr; } else { + LLVMValueRef value; if (node->data.variable_declaration.expr) { - LLVMValueRef value = gen_expr(g, node->data.variable_declaration.expr); - - add_debug_source_node(g, node); - return LLVMBuildStore(g->builder, value, variable->value_ref); + value = gen_expr(g, node->data.variable_declaration.expr); } else { - + value = LLVMConstNull(variable->type->type_ref); } + add_debug_source_node(g, node); + return LLVMBuildStore(g->builder, value, variable->value_ref); } } case NodeTypeCastExpr: diff --git a/test/run_tests.cpp b/test/run_tests.cpp index 2f0243d5af..fac093670d 100644 --- a/test/run_tests.cpp +++ b/test/run_tests.cpp @@ -332,7 +332,7 @@ fn void_fun(a : i32, b : void, c : i32) { } )SOURCE", "OK\n"); - add_simple_case("void parameters", R"SOURCE( + add_simple_case("mutable local variables", R"SOURCE( #link("c") extern { fn puts(s: *const u8) -> i32; @@ -340,6 +340,9 @@ extern { } export fn _start() -> unreachable { + let mut zero : i32; + if (zero == 0) { puts("zero"); } + let mut i = 0; loop_start: if i == 3 { @@ -351,7 +354,7 @@ loop_start: done: exit(0); } - )SOURCE", "loop\nloop\nloop\n"); + )SOURCE", "zero\nloop\nloop\nloop\n"); } static void add_compile_failure_test_cases(void) {