From 42a2f243b5c8d6336151ff7d9f8243664bdf2d01 Mon Sep 17 00:00:00 2001 From: David Mak Date: Sat, 5 Oct 2024 17:08:46 +0800 Subject: [PATCH] [core] typecheck: Disallow redeclaration of var shadowing global --- nac3core/src/typecheck/function_check.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/nac3core/src/typecheck/function_check.rs b/nac3core/src/typecheck/function_check.rs index 25fc6b76..0893adec 100644 --- a/nac3core/src/typecheck/function_check.rs +++ b/nac3core/src/typecheck/function_check.rs @@ -34,6 +34,20 @@ impl<'a> Inferencer<'a> { Err(HashSet::from([format!("cannot assign to a `none` (at {})", pattern.location)])) } ExprKind::Name { id, .. } => { + // If `id` refers to a declared symbol, reject this assignment if it is used in the + // context of an (implicit) global variable + if let Some(id_info) = self.defined_identifiers.get(id) { + if matches!( + id_info.source, + DeclarationSource::Global { is_explicit: Some(false) } + ) { + return Err(HashSet::from([format!( + "cannot access local variable '{id}' before it is declared (at {})", + pattern.location + )])); + } + } + if !defined_identifiers.contains_key(id) { defined_identifiers.insert(*id, IdentifierInfo::default()); }