From 2bb788e4bbfb77fd133c624a40465638b33ff957 Mon Sep 17 00:00:00 2001
From: David Mak <chmakac@connect.ust.hk>
Date: Sat, 5 Oct 2024 16:13:03 +0800
Subject: [PATCH] [core] codegen/expr: Materialize implicit globals

Required for when globals are read without the use of a global
declaration.
---
 nac3core/src/codegen/expr.rs | 26 +++++++++++++++++++++++++-
 1 file changed, 25 insertions(+), 1 deletion(-)

diff --git a/nac3core/src/codegen/expr.rs b/nac3core/src/codegen/expr.rs
index 52146145..65e5db2b 100644
--- a/nac3core/src/codegen/expr.rs
+++ b/nac3core/src/codegen/expr.rs
@@ -2886,7 +2886,31 @@ pub fn gen_expr<'ctx, G: CodeGenerator>(
             Some((_, Some(static_value), _)) => ValueEnum::Static(static_value.clone()),
             None => {
                 let resolver = ctx.resolver.clone();
-                resolver.get_symbol_value(*id, ctx, generator).unwrap()
+                let value = resolver.get_symbol_value(*id, ctx, generator).unwrap();
+
+                let globals = ctx
+                    .top_level
+                    .definitions
+                    .read()
+                    .iter()
+                    .filter_map(|def| {
+                        if let TopLevelDef::Variable { simple_name, ty, .. } = &*def.read() {
+                            Some((*simple_name, *ty))
+                        } else {
+                            None
+                        }
+                    })
+                    .collect_vec();
+
+                if let Some((_, ty)) = globals.iter().find(|(name, _)| name == id) {
+                    let ptr = value
+                        .to_basic_value_enum(ctx, generator, *ty)
+                        .map(BasicValueEnum::into_pointer_value)?;
+
+                    ctx.builder.build_load(ptr, id.to_string().as_str()).map(Into::into).unwrap()
+                } else {
+                    value
+                }
             }
         },
         ExprKind::List { elts, .. } => {