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 /// Whether the body contains BigInt division/modulo (can throw RangeError).
45 pub has_bigint_div: bool,
46 /// Whether the body contains operations that emit @panic for JS-semantic errors
47 /// (BigInt mixed types, BigInt >>>, JSON.parse). These need to be converted to
48 /// `return error.JsThrow` so they can be caught by JS try/catch.
49 pub has_catchable_error: bool,
50 /// JS-const variables that are reassigned (emit runtime TypeError guard).
51 /// In JS, `const x = 1; x = 2` throws TypeError at runtime, but Zig uses
52 /// `var` for reassigned variables so the assignment succeeds. We track these
53 /// to insert a throw before the actual assignment.
54 pub js_const_reassigned: HashSet<String>,
55 /// Currently inside a return value expression.
56 pub in_return_expr: bool,
57 /// Currently at the top-level of an ExpressionStatement.
58 pub in_expr_stmt: bool,
59 /// Current call generated a catch block.
60 pub call_generated_catch: bool,
61 /// Inside a try block: label name for `break :label`.
62 pub inside_try_block: Option<String>,
63 /// Inside a class method: class name (for this.x → self.x).
64 pub current_class: Option<String>,
65 /// Nested function declaration names (rewrite to .call()).
66 pub nested_fn_names: HashSet<String>,
67 /// Currently generating a nested fn's body (override signature).
68 pub current_nested_fn_name: Option<String>,
69 /// Variable names in current function scope (shadow detection).
70 pub fn_scope_vars: HashSet<String>,
71 /// Per-function local variable types (takes priority over global var_types).
72 /// Populated during lowering when VarDecl is processed.
73 pub fn_local_types: HashMap<String, ZigType>,
74 /// Variables holding TypedArray instances (name → element type suffix).
75 pub typedarray_vars: HashMap<String, String>,
76 /// Variables holding RegExp instances.
77 pub regexp_vars: HashSet<String>,
78 /// Identifiers referenced in expressions that were resolved at compile time
79 /// (e.g., typeof x → "number" when x's type is known). These references
80 /// must be tracked to avoid falsely marking parameters as unused.
81 pub compile_time_referenced_idents: HashSet<String>,
82}
83
84impl FnContext {
85 /// Create a new FnContext for a function with the given name.
86 pub fn new(name: &str, is_export: bool, return_type: Option<ZigType>) -> Self {
87 Self {
88 name: name.to_string(),
89 is_export,
90 return_type,
91 seen_return: false,
92 fn_has_throw: false,
93 has_bigint_div: false,
94 has_catchable_error: false,
95 js_const_reassigned: HashSet::new(),
96 in_return_expr: false,
97 in_expr_stmt: false,
98 call_generated_catch: false,
99 inside_try_block: None,
100 current_class: None,
101 nested_fn_names: HashSet::new(),
102 current_nested_fn_name: None,
103 fn_scope_vars: HashSet::new(),
104 fn_local_types: HashMap::new(),
105 typedarray_vars: HashMap::new(),
106 regexp_vars: HashSet::new(),
107 compile_time_referenced_idents: HashSet::new(),
108 }
109 }
110
111 /// Register a variable in the current function scope.
112 pub fn add_scope_var(&mut self, name: &str) {
113 self.fn_scope_vars.insert(name.to_string());
114 }
115
116 /// Register a nested function name.
117 pub fn add_nested_fn(&mut self, name: &str) {
118 self.nested_fn_names.insert(name.to_string());
119 }
120
121 /// Check if a name is a nested function.
122 pub fn is_nested_fn(&self, name: &str) -> bool {
123 self.nested_fn_names.contains(name)
124 }
125
126 /// Register a TypedArray variable.
127 pub fn add_typedarray_var(&mut self, name: &str, suffix: &str) {
128 self.typedarray_vars
129 .insert(name.to_string(), suffix.to_string());
130 }
131
132 /// Register a RegExp variable.
133 pub fn add_regexp_var(&mut self, name: &str) {
134 self.regexp_vars.insert(name.to_string());
135 }
136}
137
138// ═══════════════════════════════════════════════════════
139// Lowering guard helpers
140// ═══════════════════════════════════════════════════════
141
142/// RAII guard for temporarily setting a FnContext flag.
143///
144/// Automatically restores the previous value on drop.
145pub struct SetFlagGuard<'a> {
146 field: &'a mut bool,
147 old_value: bool,
148}
149
150impl<'a> SetFlagGuard<'a> {
151 pub fn new(field: &'a mut bool, value: bool) -> Self {
152 let old_value = *field;
153 *field = value;
154 Self { field, old_value }
155 }
156}
157
158impl Drop for SetFlagGuard<'_> {
159 fn drop(&mut self) {
160 *self.field = self.old_value;
161 }
162}
163
164// ═══════════════════════════════════════════════════════
165// Tests
166// ═══════════════════════════════════════════════════════
167
168#[cfg(test)]
169mod tests {
170 use super::*;
171
172 #[test]
173 fn test_fn_context_new() {
174 let ctx = FnContext::new("add", true, Some(ZigType::I64));
175 assert_eq!(ctx.name, "add");
176 assert!(ctx.is_export);
177 assert_eq!(ctx.return_type, Some(ZigType::I64));
178 assert!(!ctx.seen_return);
179 assert!(!ctx.fn_has_throw);
180 assert!(ctx.nested_fn_names.is_empty());
181 }
182
183 #[test]
184 fn test_fn_context_register_vars() {
185 let mut ctx = FnContext::new("test", false, None);
186 ctx.add_scope_var("x");
187 ctx.add_scope_var("y");
188 assert!(ctx.fn_scope_vars.contains("x"));
189 assert!(ctx.fn_scope_vars.contains("y"));
190
191 ctx.add_nested_fn("helper");
192 assert!(ctx.is_nested_fn("helper"));
193 assert!(!ctx.is_nested_fn("other"));
194
195 ctx.add_typedarray_var("buf", "U8");
196 assert_eq!(ctx.typedarray_vars.get("buf"), Some(&"U8".to_string()));
197
198 ctx.add_regexp_var("re");
199 assert!(ctx.regexp_vars.contains("re"));
200 }
201
202 #[test]
203 fn test_set_flag_guard() {
204 let mut ctx = FnContext::new("test", false, None);
205 assert!(!ctx.in_return_expr);
206
207 {
208 let _guard = SetFlagGuard::new(&mut ctx.in_return_expr, true);
209 // The flag is set while the guard is alive
210 // (can't assert ctx.in_return_expr here due to borrow conflict,
211 // but we verify the restored value after the guard drops)
212 }
213
214 assert!(!ctx.in_return_expr); // Restored on drop
215 }
216}
217
218// ═══════════════════════════════════════════════════════
219// Throw detection — unified AST walker
220// ═══════════════════════════════════════════════════════
221
222/// Check whether a statement contains a `throw`, recursing into
223/// blocks / if / loops / switch.
224/// TryStatement counts as containing throw (conservative — any try
225/// implies potential throw).
226pub(crate) fn stmt_has_throw(stmt: &oxc_ast::ast::Statement) -> bool {
227 use oxc_ast::ast::Statement;
228 match stmt {
229 Statement::ThrowStatement(_) => true,
230 Statement::BlockStatement(bs) => bs.body.iter().any(|s| stmt_has_throw(s)),
231 Statement::IfStatement(is) => {
232 stmt_has_throw(&is.consequent)
233 || is.alternate.as_ref().is_some_and(|a| stmt_has_throw(a))
234 }
235 Statement::WhileStatement(ws) => stmt_has_throw(&ws.body),
236 Statement::DoWhileStatement(dws) => stmt_has_throw(&dws.body),
237 Statement::ForStatement(fs) => stmt_has_throw(&fs.body),
238 Statement::ForOfStatement(fos) => stmt_has_throw(&fos.body),
239 Statement::ForInStatement(fis) => stmt_has_throw(&fis.body),
240 Statement::LabeledStatement(ls) => stmt_has_throw(&ls.body),
241 Statement::SwitchStatement(ss) => ss
242 .cases
243 .iter()
244 .any(|c| c.consequent.iter().any(|s| stmt_has_throw(s))),
245 Statement::TryStatement(_) => true,
246 _ => false,
247 }
248}
249
250/// Determine the Zig format specifier for a given type.
251/// Used by string concatenation and template literal lowering.
252/// Note: `{any}` is used as the catch-all because Zig 0.16 does not
253/// allow `{}` for slice types (`[]const u8`); `{any}` works for all types.
254pub(crate) fn format_specifier_for_type(ty: &ZigType) -> &'static str {
255 match ty {
256 ZigType::Str => "{s}",
257 ZigType::I64 => "{d}",
258 ZigType::F64 => "{d:.15}",
259 ZigType::Bool => "{}",
260 _ => "{any}",
261 }
262}