diff --git a/integration_tests/CMakeLists.txt b/integration_tests/CMakeLists.txt index b9e40ed31a..e34703c508 100644 --- a/integration_tests/CMakeLists.txt +++ b/integration_tests/CMakeLists.txt @@ -444,3 +444,4 @@ RUN(NAME global_syms_03_b LABELS cpython llvm c) RUN(NAME global_syms_03_c LABELS cpython llvm c) RUN(NAME global_syms_04 LABELS cpython llvm c wasm wasm_x64) RUN(NAME global_syms_05 LABELS cpython llvm c) +RUN(NAME global_syms_06 LABELS cpython llvm c) diff --git a/integration_tests/global_syms_06.py b/integration_tests/global_syms_06.py new file mode 100644 index 0000000000..0b396d1408 --- /dev/null +++ b/integration_tests/global_syms_06.py @@ -0,0 +1,9 @@ +from lpython import i32 + +def test() -> i32: + temp: i32 = 0 + return temp + +x: i32 = test() +i: i32 = 10 +j: i32 = i diff --git a/src/lpython/semantics/python_ast_to_asr.cpp b/src/lpython/semantics/python_ast_to_asr.cpp index ddcc6e26f7..662ee6ac31 100644 --- a/src/lpython/semantics/python_ast_to_asr.cpp +++ b/src/lpython/semantics/python_ast_to_asr.cpp @@ -2245,15 +2245,15 @@ class CommonVisitor : public AST::BaseVisitor { ASR::symbol_t* v_sym = ASR::down_cast(v); ASR::Variable_t* v_variable = ASR::down_cast(v_sym); - if( init_expr && (current_body || ASR::is_a(*type)) && - (is_runtime_expression || !is_variable_const)) { + if( init_expr && (current_body || ASR::is_a(*type) || + is_runtime_expression) && !is_variable_const) { ASR::expr_t* v_expr = ASRUtils::EXPR(ASR::make_Var_t(al, loc, v_sym)); cast_helper(v_expr, init_expr, true); ASR::asr_t* assign = ASR::make_Assignment_t(al, loc, v_expr, init_expr, nullptr); if (current_body) { current_body->push_back(al, ASRUtils::STMT(assign)); - } else if (ASR::is_a(*type)) { + } else if (ASR::is_a(*type) || is_runtime_expression) { global_init.push_back(al, assign); } @@ -3978,10 +3978,23 @@ class BodyVisitor : public CommonVisitor { // Erase the function in TranslationUnit unit->m_global_scope->erase_symbol(func_name); } + global_init.p = nullptr; + global_init.n = 0; + } + + if (global_init.n > 0) { + // copy all the item's from `items` (global_statements) + // into `global_init` + for (auto &i: items) { + global_init.push_back(al, i); + } + unit->m_items = global_init.p; + unit->n_items = global_init.size(); + } else { + unit->m_items = items.p; + unit->n_items = items.size(); } - unit->m_items = items.p; - unit->n_items = items.size(); if (items.n > 0 && main_module_sym) { std::string func_name = "global_statements"; // Wrap all the global statements into a Function