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 /// Saved `this_rewrite_fields` value from before entering this function's
89 /// context (R8-C7). `enter_fn` resets the active flag to `None` so that
90 /// `this.field = value` inside a NESTED function is NOT rewritten (its
91 /// `this` differs from the constructor's). `exit_fn` restores it.
92 pub saved_this_rewrite_fields: Option<Vec<String>>,
93}
94
95impl FnContext {
96 /// Create a new FnContext for a function with the given name.
97 pub fn new(name: &str, is_export: bool, return_type: Option<ZigType>) -> Self {
98 Self {
99 name: name.to_string(),
100 is_export,
101 return_type,
102 seen_return: false,
103 fn_has_throw: false,
104 has_bigint_div: false,
105 has_catchable_error: false,
106 js_const_reassigned: HashSet::new(),
107 in_return_expr: false,
108 in_expr_stmt: false,
109 call_generated_catch: false,
110 inside_try_block: None,
111 current_class: None,
112 nested_fn_names: HashSet::new(),
113 current_nested_fn_name: None,
114 fn_scope_vars: HashSet::new(),
115 fn_local_types: HashMap::new(),
116 typedarray_vars: HashMap::new(),
117 regexp_vars: HashSet::new(),
118 rest_param_name: None,
119 compile_time_referenced_idents: HashSet::new(),
120 saved_this_rewrite_fields: None,
121 }
122 }
123
124 /// Register a variable in the current function scope.
125 pub fn add_scope_var(&mut self, name: &str) {
126 self.fn_scope_vars.insert(name.to_string());
127 }
128
129 /// Register a nested function name.
130 pub fn add_nested_fn(&mut self, name: &str) {
131 self.nested_fn_names.insert(name.to_string());
132 }
133
134 /// Check if a name is a nested function.
135 pub fn is_nested_fn(&self, name: &str) -> bool {
136 self.nested_fn_names.contains(name)
137 }
138
139 /// Register a TypedArray variable.
140 pub fn add_typedarray_var(&mut self, name: &str, suffix: &str) {
141 self.typedarray_vars
142 .insert(name.to_string(), suffix.to_string());
143 }
144
145 /// Register a RegExp variable.
146 pub fn add_regexp_var(&mut self, name: &str) {
147 self.regexp_vars.insert(name.to_string());
148 }
149}
150
151// ═══════════════════════════════════════════════════════
152// Lowering guard helpers
153// ═══════════════════════════════════════════════════════
154
155/// RAII guard for temporarily setting a FnContext flag.
156///
157/// Automatically restores the previous value on drop.
158pub struct SetFlagGuard<'a> {
159 field: &'a mut bool,
160 old_value: bool,
161}
162
163impl<'a> SetFlagGuard<'a> {
164 pub fn new(field: &'a mut bool, value: bool) -> Self {
165 let old_value = *field;
166 *field = value;
167 Self { field, old_value }
168 }
169}
170
171impl Drop for SetFlagGuard<'_> {
172 fn drop(&mut self) {
173 *self.field = self.old_value;
174 }
175}
176
177// ═══════════════════════════════════════════════════════
178// Tests
179// ═══════════════════════════════════════════════════════
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184
185 #[test]
186 fn test_fn_context_new() {
187 let ctx = FnContext::new("add", true, Some(ZigType::I64));
188 assert_eq!(ctx.name, "add");
189 assert!(ctx.is_export);
190 assert_eq!(ctx.return_type, Some(ZigType::I64));
191 assert!(!ctx.seen_return);
192 assert!(!ctx.fn_has_throw);
193 assert!(ctx.nested_fn_names.is_empty());
194 }
195
196 #[test]
197 fn test_fn_context_register_vars() {
198 let mut ctx = FnContext::new("test", false, None);
199 ctx.add_scope_var("x");
200 ctx.add_scope_var("y");
201 assert!(ctx.fn_scope_vars.contains("x"));
202 assert!(ctx.fn_scope_vars.contains("y"));
203
204 ctx.add_nested_fn("helper");
205 assert!(ctx.is_nested_fn("helper"));
206 assert!(!ctx.is_nested_fn("other"));
207
208 ctx.add_typedarray_var("buf", "U8");
209 assert_eq!(ctx.typedarray_vars.get("buf"), Some(&"U8".to_string()));
210
211 ctx.add_regexp_var("re");
212 assert!(ctx.regexp_vars.contains("re"));
213 }
214
215 #[test]
216 fn test_set_flag_guard() {
217 let mut ctx = FnContext::new("test", false, None);
218 assert!(!ctx.in_return_expr);
219
220 {
221 let _guard = SetFlagGuard::new(&mut ctx.in_return_expr, true);
222 // The flag is set while the guard is alive
223 // (can't assert ctx.in_return_expr here due to borrow conflict,
224 // but we verify the restored value after the guard drops)
225 }
226
227 assert!(!ctx.in_return_expr); // Restored on drop
228 }
229}
230
231// ═══════════════════════════════════════════════════════
232// Throw detection — unified AST walker
233// ═══════════════════════════════════════════════════════
234
235/// Check whether a statement contains a `throw`, recursing into
236/// blocks / if / loops / switch.
237/// TryStatement counts as containing throw (conservative — any try
238/// implies potential throw).
239pub(crate) fn stmt_has_throw(stmt: &oxc_ast::ast::Statement) -> bool {
240 use oxc_ast::ast::Statement;
241 match stmt {
242 Statement::ThrowStatement(_) => true,
243 Statement::BlockStatement(bs) => bs.body.iter().any(|s| stmt_has_throw(s)),
244 Statement::IfStatement(is) => {
245 stmt_has_throw(&is.consequent)
246 || is.alternate.as_ref().is_some_and(|a| stmt_has_throw(a))
247 }
248 Statement::WhileStatement(ws) => stmt_has_throw(&ws.body),
249 Statement::DoWhileStatement(dws) => stmt_has_throw(&dws.body),
250 Statement::ForStatement(fs) => stmt_has_throw(&fs.body),
251 Statement::ForOfStatement(fos) => stmt_has_throw(&fos.body),
252 Statement::ForInStatement(fis) => stmt_has_throw(&fis.body),
253 Statement::LabeledStatement(ls) => stmt_has_throw(&ls.body),
254 Statement::SwitchStatement(ss) => ss
255 .cases
256 .iter()
257 .any(|c| c.consequent.iter().any(|s| stmt_has_throw(s))),
258 Statement::TryStatement(_) => true,
259 _ => false,
260 }
261}
262
263/// Determine the Zig format specifier for a given type.
264/// Used by string concatenation and template literal lowering.
265/// Note: `{any}` is used as the catch-all because Zig 0.16 does not
266/// allow `{}` for slice types (`[]const u8`); `{any}` works for all types.
267pub(crate) fn format_specifier_for_type(ty: &ZigType) -> &'static str {
268 match ty {
269 ZigType::Str => "{s}",
270 ZigType::I64 => "{d}",
271 // R8-E2: Use `{}` (default specifier) for f64 — Zig's default
272 // float formatting produces the shortest round-trip fixed-point
273 // representation (e.g. 1.5 → "1.5", 123.456 → "123.456"), matching
274 // JS Number.prototype.toString() for the common range.
275 // Previously `{d:.15}` padded to 15 digits → "1.500000000000000".
276 // NOTE: `{d}` (not `{}`) would wrongly use exponential for values
277 // like 100000 → "1e5"; `{}` keeps fixed-point. Remaining JS-spec
278 // deviations (exponential for |x|>=1e21 / |x|<1e-6, and -0 → "0")
279 // are shared with JsValue.asString and tracked for a future full
280 // ECMA numberToString helper.
281 ZigType::F64 => "{}",
282 ZigType::Bool => "{}",
283 // R8-P1-7: {f} dispatches to the custom `format` method
284 // (JsAny.format → JsValue.format), which emits JS-correct
285 // "NaN"/"Infinity"/"true"/"null" etc. The previous {any} produced
286 // the debug repr `.{ .value = .{ .float = nan } }` for tagged unions.
287 ZigType::JsAny => "{f}",
288 _ => "{any}",
289 }
290}