js2zig_core/zigir/lower/helpers.rs
1// zigir/lower/helpers.rs
2// FnContext sub-structure and lowering utility methods.
3
4use std::collections::{HashMap, HashSet};
5
6use crate::types::ZigType;
7
8// ═══════════════════════════════════════════════════════
9// FnContext — per-function lowering state
10// ═══════════════════════════════════════════════════════
11
12/// Per-function context for the Lowerer.
13///
14/// Groups the 6+ flags and per-function sets:
15///
16/// | Field | Purpose |
17/// |-------------------------------|------------------------|
18/// | name | current fn name |
19/// | is_export | C ABI export flag |
20/// | return_type | fn return type |
21/// | seen_return | has return expr |
22/// | fn_has_throw | contains throw/try |
23/// | in_return_expr | inside return expr |
24/// | in_expr_stmt | inside expr statement |
25/// | call_generated_catch | catch dispatch needed |
26/// | inside_try_block | inside try block |
27/// | current_class | current class name |
28/// | nested_fn_names | nested fn name set |
29/// | current_nested_fn_name | current nested fn |
30/// | fn_scope_vars | fn-local var types |
31/// | typedarray_vars | typedarray var set |
32/// | regexp_vars | regexp var set |
33pub struct FnContext {
34 /// Current function name.
35 pub name: String,
36 /// Whether this is an export function.
37 pub is_export: bool,
38 /// Inferred return type (None = let Zig infer).
39 pub return_type: Option<ZigType>,
40 /// Whether a return/throw was seen in the body.
41 pub seen_return: bool,
42 /// Whether the body contains throw/try-catch.
43 pub fn_has_throw: bool,
44 /// Currently inside a return value expression.
45 pub in_return_expr: bool,
46 /// Currently at the top-level of an ExpressionStatement.
47 pub in_expr_stmt: bool,
48 /// Current call generated a catch block.
49 pub call_generated_catch: bool,
50 /// Inside a try block: label name for `break :label`.
51 pub inside_try_block: Option<String>,
52 /// Inside a class method: class name (for this.x → self.x).
53 pub current_class: Option<String>,
54 /// Nested function declaration names (rewrite to .call()).
55 pub nested_fn_names: HashSet<String>,
56 /// Currently generating a nested fn's body (override signature).
57 pub current_nested_fn_name: Option<String>,
58 /// Variable names in current function scope (shadow detection).
59 pub fn_scope_vars: HashSet<String>,
60 /// Variables holding TypedArray instances (name → element type suffix).
61 pub typedarray_vars: HashMap<String, String>,
62 /// Variables holding RegExp instances.
63 pub regexp_vars: HashSet<String>,
64 /// Identifiers referenced in expressions that were resolved at compile time
65 /// (e.g., typeof x → "number" when x's type is known). These references
66 /// must be tracked to avoid falsely marking parameters as unused.
67 pub compile_time_referenced_idents: HashSet<String>,
68}
69
70impl FnContext {
71 /// Create a new FnContext for a function with the given name.
72 pub fn new(name: &str, is_export: bool, return_type: Option<ZigType>) -> Self {
73 Self {
74 name: name.to_string(),
75 is_export,
76 return_type,
77 seen_return: false,
78 fn_has_throw: false,
79 in_return_expr: false,
80 in_expr_stmt: false,
81 call_generated_catch: false,
82 inside_try_block: None,
83 current_class: None,
84 nested_fn_names: HashSet::new(),
85 current_nested_fn_name: None,
86 fn_scope_vars: HashSet::new(),
87 typedarray_vars: HashMap::new(),
88 regexp_vars: HashSet::new(),
89 compile_time_referenced_idents: HashSet::new(),
90 }
91 }
92
93 /// Register a variable in the current function scope.
94 pub fn add_scope_var(&mut self, name: &str) {
95 self.fn_scope_vars.insert(name.to_string());
96 }
97
98 /// Register a nested function name.
99 pub fn add_nested_fn(&mut self, name: &str) {
100 self.nested_fn_names.insert(name.to_string());
101 }
102
103 /// Check if a name is a nested function.
104 pub fn is_nested_fn(&self, name: &str) -> bool {
105 self.nested_fn_names.contains(name)
106 }
107
108 /// Register a TypedArray variable.
109 pub fn add_typedarray_var(&mut self, name: &str, suffix: &str) {
110 self.typedarray_vars
111 .insert(name.to_string(), suffix.to_string());
112 }
113
114 /// Register a RegExp variable.
115 pub fn add_regexp_var(&mut self, name: &str) {
116 self.regexp_vars.insert(name.to_string());
117 }
118}
119
120// ═══════════════════════════════════════════════════════
121// Lowering guard helpers
122// ═══════════════════════════════════════════════════════
123
124/// RAII guard for temporarily setting a FnContext flag.
125///
126/// Automatically restores the previous value on drop.
127pub struct SetFlagGuard<'a> {
128 field: &'a mut bool,
129 old_value: bool,
130}
131
132impl<'a> SetFlagGuard<'a> {
133 pub fn new(field: &'a mut bool, value: bool) -> Self {
134 let old_value = *field;
135 *field = value;
136 Self { field, old_value }
137 }
138}
139
140impl Drop for SetFlagGuard<'_> {
141 fn drop(&mut self) {
142 *self.field = self.old_value;
143 }
144}
145
146// ═══════════════════════════════════════════════════════
147// Tests
148// ═══════════════════════════════════════════════════════
149
150#[cfg(test)]
151mod tests {
152 use super::*;
153
154 #[test]
155 fn test_fn_context_new() {
156 let ctx = FnContext::new("add", true, Some(ZigType::I64));
157 assert_eq!(ctx.name, "add");
158 assert!(ctx.is_export);
159 assert_eq!(ctx.return_type, Some(ZigType::I64));
160 assert!(!ctx.seen_return);
161 assert!(!ctx.fn_has_throw);
162 assert!(ctx.nested_fn_names.is_empty());
163 }
164
165 #[test]
166 fn test_fn_context_register_vars() {
167 let mut ctx = FnContext::new("test", false, None);
168 ctx.add_scope_var("x");
169 ctx.add_scope_var("y");
170 assert!(ctx.fn_scope_vars.contains("x"));
171 assert!(ctx.fn_scope_vars.contains("y"));
172
173 ctx.add_nested_fn("helper");
174 assert!(ctx.is_nested_fn("helper"));
175 assert!(!ctx.is_nested_fn("other"));
176
177 ctx.add_typedarray_var("buf", "U8");
178 assert_eq!(ctx.typedarray_vars.get("buf"), Some(&"U8".to_string()));
179
180 ctx.add_regexp_var("re");
181 assert!(ctx.regexp_vars.contains("re"));
182 }
183
184 #[test]
185 fn test_set_flag_guard() {
186 let mut ctx = FnContext::new("test", false, None);
187 assert!(!ctx.in_return_expr);
188
189 {
190 let _guard = SetFlagGuard::new(&mut ctx.in_return_expr, true);
191 // The flag is set while the guard is alive
192 // (can't assert ctx.in_return_expr here due to borrow conflict,
193 // but we verify the restored value after the guard drops)
194 }
195
196 assert!(!ctx.in_return_expr); // Restored on drop
197 }
198}