Skip to main content

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