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 /// The name of the rest parameter for the current function (if any).
79 /// Used to rewrite `arguments` → rest param name (`__arguments` for synthetic,
80 /// or the explicit rest param name like `args`).
81 /// `None` for functions without a rest param (export functions using `arguments`
82 /// fall back to `__arguments` VarDecl injection).
83 pub rest_param_name: Option<String>,
84 /// Identifiers referenced in expressions that were resolved at compile time
85 /// (e.g., typeof x → "number" when x's type is known). These references
86 /// must be tracked to avoid falsely marking parameters as unused.
87 pub compile_time_referenced_idents: HashSet<String>,
88}
89
90impl FnContext {
91 /// Create a new FnContext for a function with the given name.
92 pub fn new(name: &str, is_export: bool, return_type: Option<ZigType>) -> Self {
93 Self {
94 name: name.to_string(),
95 is_export,
96 return_type,
97 seen_return: false,
98 fn_has_throw: false,
99 has_bigint_div: false,
100 has_catchable_error: false,
101 js_const_reassigned: HashSet::new(),
102 in_return_expr: false,
103 in_expr_stmt: false,
104 call_generated_catch: false,
105 inside_try_block: None,
106 current_class: None,
107 nested_fn_names: HashSet::new(),
108 current_nested_fn_name: None,
109 fn_scope_vars: HashSet::new(),
110 fn_local_types: HashMap::new(),
111 typedarray_vars: HashMap::new(),
112 regexp_vars: HashSet::new(),
113 rest_param_name: None,
114 compile_time_referenced_idents: HashSet::new(),
115 }
116 }
117
118 /// Register a variable in the current function scope.
119 pub fn add_scope_var(&mut self, name: &str) {
120 self.fn_scope_vars.insert(name.to_string());
121 }
122
123 /// Register a nested function name.
124 pub fn add_nested_fn(&mut self, name: &str) {
125 self.nested_fn_names.insert(name.to_string());
126 }
127
128 /// Check if a name is a nested function.
129 pub fn is_nested_fn(&self, name: &str) -> bool {
130 self.nested_fn_names.contains(name)
131 }
132
133 /// Register a TypedArray variable.
134 pub fn add_typedarray_var(&mut self, name: &str, suffix: &str) {
135 self.typedarray_vars
136 .insert(name.to_string(), suffix.to_string());
137 }
138
139 /// Register a RegExp variable.
140 pub fn add_regexp_var(&mut self, name: &str) {
141 self.regexp_vars.insert(name.to_string());
142 }
143}
144
145// ═══════════════════════════════════════════════════════
146// Lowering guard helpers
147// ═══════════════════════════════════════════════════════
148
149/// RAII guard for temporarily setting a FnContext flag.
150///
151/// Automatically restores the previous value on drop.
152pub struct SetFlagGuard<'a> {
153 field: &'a mut bool,
154 old_value: bool,
155}
156
157impl<'a> SetFlagGuard<'a> {
158 pub fn new(field: &'a mut bool, value: bool) -> Self {
159 let old_value = *field;
160 *field = value;
161 Self { field, old_value }
162 }
163}
164
165impl Drop for SetFlagGuard<'_> {
166 fn drop(&mut self) {
167 *self.field = self.old_value;
168 }
169}
170
171// ═══════════════════════════════════════════════════════
172// Tests
173// ═══════════════════════════════════════════════════════
174
175#[cfg(test)]
176mod tests {
177 use super::*;
178
179 #[test]
180 fn test_fn_context_new() {
181 let ctx = FnContext::new("add", true, Some(ZigType::I64));
182 assert_eq!(ctx.name, "add");
183 assert!(ctx.is_export);
184 assert_eq!(ctx.return_type, Some(ZigType::I64));
185 assert!(!ctx.seen_return);
186 assert!(!ctx.fn_has_throw);
187 assert!(ctx.nested_fn_names.is_empty());
188 }
189
190 #[test]
191 fn test_fn_context_register_vars() {
192 let mut ctx = FnContext::new("test", false, None);
193 ctx.add_scope_var("x");
194 ctx.add_scope_var("y");
195 assert!(ctx.fn_scope_vars.contains("x"));
196 assert!(ctx.fn_scope_vars.contains("y"));
197
198 ctx.add_nested_fn("helper");
199 assert!(ctx.is_nested_fn("helper"));
200 assert!(!ctx.is_nested_fn("other"));
201
202 ctx.add_typedarray_var("buf", "U8");
203 assert_eq!(ctx.typedarray_vars.get("buf"), Some(&"U8".to_string()));
204
205 ctx.add_regexp_var("re");
206 assert!(ctx.regexp_vars.contains("re"));
207 }
208
209 #[test]
210 fn test_set_flag_guard() {
211 let mut ctx = FnContext::new("test", false, None);
212 assert!(!ctx.in_return_expr);
213
214 {
215 let _guard = SetFlagGuard::new(&mut ctx.in_return_expr, true);
216 // The flag is set while the guard is alive
217 // (can't assert ctx.in_return_expr here due to borrow conflict,
218 // but we verify the restored value after the guard drops)
219 }
220
221 assert!(!ctx.in_return_expr); // Restored on drop
222 }
223}
224
225// ═══════════════════════════════════════════════════════
226// Throw detection — unified AST walker
227// ═══════════════════════════════════════════════════════
228
229/// Check whether a statement contains a `throw`, recursing into
230/// blocks / if / loops / switch.
231/// TryStatement counts as containing throw (conservative — any try
232/// implies potential throw).
233pub(crate) fn stmt_has_throw(stmt: &oxc_ast::ast::Statement) -> bool {
234 use oxc_ast::ast::Statement;
235 match stmt {
236 Statement::ThrowStatement(_) => true,
237 Statement::BlockStatement(bs) => bs.body.iter().any(|s| stmt_has_throw(s)),
238 Statement::IfStatement(is) => {
239 stmt_has_throw(&is.consequent)
240 || is.alternate.as_ref().is_some_and(|a| stmt_has_throw(a))
241 }
242 Statement::WhileStatement(ws) => stmt_has_throw(&ws.body),
243 Statement::DoWhileStatement(dws) => stmt_has_throw(&dws.body),
244 Statement::ForStatement(fs) => stmt_has_throw(&fs.body),
245 Statement::ForOfStatement(fos) => stmt_has_throw(&fos.body),
246 Statement::ForInStatement(fis) => stmt_has_throw(&fis.body),
247 Statement::LabeledStatement(ls) => stmt_has_throw(&ls.body),
248 Statement::SwitchStatement(ss) => ss
249 .cases
250 .iter()
251 .any(|c| c.consequent.iter().any(|s| stmt_has_throw(s))),
252 Statement::TryStatement(_) => true,
253 _ => false,
254 }
255}
256
257/// Determine the Zig format specifier for a given type.
258/// Used by string concatenation and template literal lowering.
259/// Note: `{any}` is used as the catch-all because Zig 0.16 does not
260/// allow `{}` for slice types (`[]const u8`); `{any}` works for all types.
261pub(crate) fn format_specifier_for_type(ty: &ZigType) -> &'static str {
262 match ty {
263 ZigType::Str => "{s}",
264 ZigType::I64 => "{d}",
265 ZigType::F64 => "{d:.15}",
266 ZigType::Bool => "{}",
267 _ => "{any}",
268 }
269}