Skip to main content

js2zig_core/zigir/passes/
validate.rs

1// zigir/passes/validate.rs
2// ValidatePass — structural validation of an IrModule.
3//
4// Checks:
5//   1. Type consistency: expressions have plausible types
6//   2. Name uniqueness: no duplicate top-level identifiers
7//   3. Closure integrity: captured lists match actual references
8//   4. C ABI compatibility: exported function signatures use C-safe types
9
10use crate::types::ZigType;
11use crate::zigir::passes::{IrPass, PassResult};
12use crate::zigir::source_span::{DiagnosticLevel, IrDiagnostic};
13use crate::zigir::types::{IrAssignTarget, IrBlock, IrDecl, IrExpr, IrFnDecl, IrModule, IrStmt};
14
15/// Validation pass: checks structural integrity of the IR.
16///
17/// Produces warnings for suspicious patterns and errors for violations
18/// that would cause incorrect Zig output. Does NOT modify the IR.
19pub struct ValidatePass {
20    /// Collected diagnostics for the current run.
21    diagnostics: Vec<IrDiagnostic>,
22}
23
24impl ValidatePass {
25    pub fn new() -> Self {
26        Self {
27            diagnostics: Vec::new(),
28        }
29    }
30
31    fn error(&mut self, msg: String) {
32        self.diagnostics.push(IrDiagnostic {
33            level: DiagnosticLevel::Error,
34            span: None,
35            message: msg,
36        });
37    }
38
39    fn warn(&mut self, msg: String) {
40        self.diagnostics.push(IrDiagnostic {
41            level: DiagnosticLevel::Warning,
42            span: None,
43            message: msg,
44        });
45    }
46
47    // ── Top-level name uniqueness ────────────────────
48
49    fn check_name_uniqueness(&mut self, module: &IrModule) {
50        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
51
52        // Check typedefs
53        for td in &module.typedefs {
54            if !seen.insert(td.name.clone()) {
55                self.error(format!("duplicate top-level name: '{}'", td.name));
56            }
57        }
58
59        // Check closure structs
60        for cs in &module.closure_structs {
61            let zig_name = cs.name.zig_name.clone();
62            if !seen.insert(zig_name.clone()) {
63                self.error(format!("duplicate top-level name: '{}'", zig_name));
64            }
65        }
66
67        // Check declarations
68        for decl in &module.declarations {
69            let name = match decl {
70                IrDecl::Var(v) => v.name.zig_name.clone(),
71                IrDecl::Fn(f) => f.name.zig_name.clone(),
72                IrDecl::Class(c) => c.name.zig_name.clone(),
73                IrDecl::CompileError { .. } => continue,
74            };
75            if !seen.insert(name.clone()) {
76                self.error(format!("duplicate top-level name: '{}'", name));
77            }
78        }
79    }
80
81    // ── C ABI compatibility ──────────────────────────
82
83    fn check_cabi_compatibility(&mut self, module: &IrModule) {
84        for decl in &module.declarations {
85            if let IrDecl::Fn(f) = decl
86                && f.is_cabi
87            {
88                self.check_cabi_fn(f);
89            }
90        }
91        for export in &module.cabi_exports {
92            if !is_c_safe_type(&export.return_type) {
93                self.error(format!(
94                    "C ABI export '{}' has non-C-safe return type: {:?}",
95                    export.name, export.return_type
96                ));
97            }
98            for param in &export.params {
99                if !is_c_safe_type(&param.zig_type) {
100                    self.error(format!(
101                        "C ABI export '{}' has non-C-safe parameter '{}': {:?}",
102                        export.name, param.name.zig_name, param.zig_type
103                    ));
104                }
105            }
106        }
107    }
108
109    fn check_cabi_fn(&mut self, f: &IrFnDecl) {
110        if !is_c_safe_type(&f.return_type) {
111            self.error(format!(
112                "C ABI function '{}' has non-C-safe return type: {:?}",
113                f.name.zig_name, f.return_type
114            ));
115        }
116        for param in &f.params {
117            if !is_c_safe_type(&param.zig_type) {
118                self.error(format!(
119                    "C ABI function '{}' has non-C-safe parameter '{}': {:?}",
120                    f.name.zig_name, param.name.zig_name, param.zig_type
121                ));
122            }
123        }
124    }
125
126    // ── Closure integrity ────────────────────────────
127
128    fn check_closure_integrity(&mut self, module: &IrModule) {
129        for cs in &module.closure_structs {
130            // Check that each captured variable is actually referenced in the body
131            let referenced = collect_ident_names(&cs.body);
132            for capture in &cs.captured {
133                if !referenced.contains(&capture.name.zig_name) {
134                    self.warn(format!(
135                        "closure struct '{}' captures '{}' but it is not referenced in the body",
136                        cs.name.zig_name, capture.name.zig_name
137                    ));
138                }
139            }
140        }
141
142        // Check IrClosure expressions in declarations
143        for decl in &module.declarations {
144            self.check_closure_refs_in_decl(decl);
145        }
146    }
147
148    fn check_closure_refs_in_decl(&mut self, decl: &IrDecl) {
149        match decl {
150            IrDecl::Fn(f) => self.check_closure_refs_in_block(&f.body),
151            IrDecl::Var(v) => {
152                if let Some(expr) = &v.init {
153                    self.check_closure_refs_in_expr(expr);
154                }
155            }
156            IrDecl::Class(c) => {
157                if let Some(ctor) = &c.constructor {
158                    self.check_closure_refs_in_block(&ctor.body);
159                }
160                for m in &c.methods {
161                    self.check_closure_refs_in_block(&m.body);
162                }
163            }
164            IrDecl::CompileError { .. } => {}
165        }
166    }
167
168    fn check_closure_refs_in_block(&mut self, block: &IrBlock) {
169        for stmt in &block.stmts {
170            self.check_closure_refs_in_stmt(stmt);
171        }
172    }
173
174    fn check_closure_refs_in_stmt(&mut self, stmt: &IrStmt) {
175        match stmt {
176            IrStmt::VarDecl(v) => {
177                if let Some(expr) = &v.init {
178                    self.check_closure_refs_in_expr(expr);
179                }
180            }
181            IrStmt::Assign { value, .. } => {
182                self.check_closure_refs_in_expr(value);
183            }
184            IrStmt::If { cond, then, else_ } => {
185                self.check_closure_refs_in_expr(cond);
186                self.check_closure_refs_in_block(then);
187                if let Some(e) = else_ {
188                    self.check_closure_refs_in_block(e);
189                }
190            }
191            IrStmt::While { cond, body, .. } => {
192                self.check_closure_refs_in_expr(cond);
193                self.check_closure_refs_in_block(body);
194            }
195            IrStmt::DoWhile { body, cond, .. } => {
196                self.check_closure_refs_in_block(body);
197                self.check_closure_refs_in_expr(cond);
198            }
199            IrStmt::For {
200                init,
201                cond,
202                update,
203                body,
204                ..
205            } => {
206                if let Some(i) = init {
207                    self.check_closure_refs_in_stmt(i);
208                }
209                if let Some(c) = cond {
210                    self.check_closure_refs_in_expr(c);
211                }
212                if let Some(u) = update {
213                    self.check_closure_refs_in_stmt(u);
214                }
215                self.check_closure_refs_in_block(body);
216            }
217            IrStmt::ForIn { iterable, body, .. } => {
218                self.check_closure_refs_in_expr(iterable);
219                self.check_closure_refs_in_block(body);
220            }
221            IrStmt::ForOf { iterable, body, .. } => {
222                self.check_closure_refs_in_expr(iterable);
223                self.check_closure_refs_in_block(body);
224            }
225            IrStmt::Switch { expr, cases } => {
226                self.check_closure_refs_in_expr(expr);
227                for case in cases {
228                    for s in &case.body {
229                        self.check_closure_refs_in_stmt(s);
230                    }
231                }
232            }
233            IrStmt::Try {
234                try_block,
235                catch_block,
236                finally,
237                ..
238            } => {
239                self.check_closure_refs_in_block(try_block);
240                self.check_closure_refs_in_block(catch_block);
241                if let Some(f) = finally {
242                    self.check_closure_refs_in_block(f);
243                }
244            }
245            IrStmt::Throw { value } => {
246                self.check_closure_refs_in_expr(value);
247            }
248            IrStmt::Return { value } => {
249                if let Some(v) = value {
250                    self.check_closure_refs_in_expr(v);
251                }
252            }
253            IrStmt::Break { .. } | IrStmt::Continue { .. } => {}
254            IrStmt::Expr(e) => {
255                self.check_closure_refs_in_expr(e);
256            }
257            IrStmt::Block(b) => {
258                self.check_closure_refs_in_block(b);
259            }
260            IrStmt::CompileError { .. } | IrStmt::Comment(_) => {}
261            IrStmt::DestructureDecl(data) => {
262                self.check_closure_refs_in_expr(&data.init);
263                for binding in &data.bindings {
264                    if let Some(d) = &binding.default {
265                        self.check_closure_refs_in_expr(d);
266                    }
267                }
268            }
269            IrStmt::NestedFnDecl {
270                struct_def,
271                instance,
272            } => {
273                self.check_closure_refs_in_block(&struct_def.body);
274                if let Some(closure) = instance {
275                    for cap in &closure.captured {
276                        self.check_closure_refs_in_expr(&crate::zigir::types::IrExpr::Ident(
277                            cap.name.clone(),
278                        ));
279                    }
280                }
281            }
282        }
283    }
284
285    fn check_closure_refs_in_expr(&mut self, expr: &IrExpr) {
286        match expr {
287            IrExpr::Closure(closure) => {
288                let referenced = collect_ident_names(&closure.body);
289                for capture in &closure.captured {
290                    if !referenced.contains(&capture.name.zig_name) {
291                        self.warn(format!(
292                            "closure '{}' captures '{}' but it is not referenced in the body",
293                            closure.struct_name.zig_name, capture.name.zig_name
294                        ));
295                    }
296                }
297            }
298            // Recurse into sub-expressions
299            IrExpr::Binary { left, right, .. } => {
300                self.check_closure_refs_in_expr(left);
301                self.check_closure_refs_in_expr(right);
302            }
303            IrExpr::Unary { operand, .. } => {
304                self.check_closure_refs_in_expr(operand);
305            }
306            IrExpr::Logical { left, right, .. } => {
307                self.check_closure_refs_in_expr(left);
308                self.check_closure_refs_in_expr(right);
309            }
310            IrExpr::Call(call) => {
311                self.check_closure_refs_in_expr(&call.callee);
312                for arg in &call.args {
313                    self.check_closure_refs_in_expr(arg);
314                }
315            }
316            IrExpr::BuiltinCall(bc) => {
317                for arg in &bc.args {
318                    self.check_closure_refs_in_expr(arg);
319                }
320            }
321            IrExpr::HostCall(hc) => {
322                for arg in &hc.args {
323                    self.check_closure_refs_in_expr(arg);
324                }
325            }
326            IrExpr::FieldAccess { object, .. } => {
327                self.check_closure_refs_in_expr(object);
328            }
329            IrExpr::IndexAccess { object, index, .. } => {
330                self.check_closure_refs_in_expr(object);
331                self.check_closure_refs_in_expr(index);
332            }
333            IrExpr::ComputedField { object, key, .. } => {
334                self.check_closure_refs_in_expr(object);
335                self.check_closure_refs_in_expr(key);
336            }
337            IrExpr::Conditional { cond, then, else_ } => {
338                self.check_closure_refs_in_expr(cond);
339                self.check_closure_refs_in_expr(then);
340                self.check_closure_refs_in_expr(else_);
341            }
342            IrExpr::TemplateLiteral { exprs, .. } => {
343                for e in exprs {
344                    self.check_closure_refs_in_expr(e);
345                }
346            }
347            IrExpr::ArrayLiteral(arr) => {
348                for e in &arr.elements {
349                    self.check_closure_refs_in_expr(e);
350                }
351            }
352            IrExpr::ObjectLiteral(obj) => {
353                use crate::zigir::types::IrObjectItem;
354                for item in &obj.items {
355                    match item {
356                        IrObjectItem::Field(f) => {
357                            self.check_closure_refs_in_expr(&f.value);
358                        }
359                        IrObjectItem::Spread(e) => {
360                            self.check_closure_refs_in_expr(e);
361                        }
362                    }
363                }
364            }
365            IrExpr::Assign { target, value, .. } => {
366                self.check_closure_refs_in_assign_target(target);
367                self.check_closure_refs_in_expr(value);
368            }
369            IrExpr::Update { target, .. } => {
370                self.check_closure_refs_in_assign_target(target);
371            }
372            IrExpr::Await(a) => {
373                self.check_closure_refs_in_expr(&a.callee);
374                for arg in &a.args {
375                    self.check_closure_refs_in_expr(arg);
376                }
377            }
378            IrExpr::New(n) => {
379                for arg in &n.args {
380                    self.check_closure_refs_in_expr(arg);
381                }
382            }
383            IrExpr::BlockExpr { body, result, .. } => {
384                for s in body {
385                    self.check_closure_refs_in_stmt(s);
386                }
387                self.check_closure_refs_in_expr(result);
388            }
389            IrExpr::AllocPrint { args, .. } => {
390                for a in args {
391                    self.check_closure_refs_in_expr(a);
392                }
393            }
394            IrExpr::Spread(e) | IrExpr::Typeof(e) | IrExpr::Void(e) | IrExpr::Paren(e) => {
395                self.check_closure_refs_in_expr(e);
396            }
397            IrExpr::Sequence(exprs) => {
398                for e in exprs {
399                    self.check_closure_refs_in_expr(e);
400                }
401            }
402            IrExpr::ArrowFn(af) => {
403                self.check_closure_refs_in_block(&af.body);
404            }
405            IrExpr::FnExpr(fe) => {
406                self.check_closure_refs_in_block(&fe.body);
407            }
408            IrExpr::ArrayCallbackInline(inline_data) => {
409                for stmt in &inline_data.body {
410                    self.check_closure_refs_in_stmt(stmt);
411                }
412            }
413            IrExpr::ArrayMethodInline(inline_data) => {
414                for arg in &inline_data.args {
415                    self.check_closure_refs_in_expr(arg);
416                }
417            }
418            IrExpr::OptionalChain { object, body, .. } => {
419                self.check_closure_refs_in_expr(object);
420                self.check_closure_refs_in_expr(body);
421            }
422            IrExpr::PowExpr { base, exp, .. } => {
423                self.check_closure_refs_in_expr(base);
424                self.check_closure_refs_in_expr(exp);
425            }
426            // Leaf expressions: no sub-expressions to check
427            IrExpr::IntLiteral(_)
428            | IrExpr::FloatLiteral(_)
429            | IrExpr::StringLiteral(_)
430            | IrExpr::BoolLiteral(_)
431            | IrExpr::BigIntLiteral(_)
432            | IrExpr::Null
433            | IrExpr::Undefined
434            | IrExpr::Ident(_)
435            | IrExpr::This
436            | IrExpr::CompileError { .. } => {}
437        }
438    }
439
440    fn check_closure_refs_in_assign_target(&mut self, target: &IrAssignTarget) {
441        match target {
442            IrAssignTarget::Ident(_) => {}
443            IrAssignTarget::Member { object, .. } => {
444                self.check_closure_refs_in_expr(object);
445            }
446            IrAssignTarget::Index { object, index } => {
447                self.check_closure_refs_in_expr(object);
448                self.check_closure_refs_in_expr(index);
449            }
450            IrAssignTarget::Destructure(bindings) => {
451                for b in bindings {
452                    if let Some(d) = &b.default {
453                        self.check_closure_refs_in_expr(d);
454                    }
455                }
456            }
457        }
458    }
459}
460
461impl IrPass for ValidatePass {
462    fn name(&self) -> &'static str {
463        "validate"
464    }
465
466    fn description(&self) -> &'static str {
467        "Validates structural integrity of the IR (name uniqueness, C ABI compatibility, closure integrity)"
468    }
469
470    fn run(&mut self, module: &mut IrModule) -> PassResult {
471        self.diagnostics.clear();
472
473        self.check_name_uniqueness(module);
474        self.check_cabi_compatibility(module);
475        self.check_closure_integrity(module);
476
477        let diagnostics = std::mem::take(&mut self.diagnostics);
478        PassResult::with_diagnostics(diagnostics)
479    }
480}
481
482impl Default for ValidatePass {
483    fn default() -> Self {
484        Self::new()
485    }
486}
487
488// ═══════════════════════════════════════════════════════
489//  Helpers
490// ═══════════════════════════════════════════════════════
491
492/// Collect all identifier names referenced in a block.
493fn collect_ident_names(block: &IrBlock) -> std::collections::HashSet<String> {
494    let mut names = std::collections::HashSet::new();
495    collect_idents_from_stmts(&block.stmts, &mut names);
496    names
497}
498
499fn collect_idents_from_block(block: &IrBlock, names: &mut std::collections::HashSet<String>) {
500    collect_idents_from_stmts(&block.stmts, names);
501}
502
503fn collect_idents_from_stmts(stmts: &[IrStmt], names: &mut std::collections::HashSet<String>) {
504    for stmt in stmts {
505        collect_idents_from_stmt(stmt, names);
506    }
507}
508
509fn collect_idents_from_stmt(stmt: &IrStmt, names: &mut std::collections::HashSet<String>) {
510    match stmt {
511        IrStmt::VarDecl(v) => {
512            if let Some(e) = &v.init {
513                collect_idents_from_expr(e, names);
514            }
515        }
516        IrStmt::Assign { target, value, .. } => {
517            collect_idents_from_target(target, names);
518            collect_idents_from_expr(value, names);
519        }
520        IrStmt::If { cond, then, else_ } => {
521            collect_idents_from_expr(cond, names);
522            collect_idents_from_stmts(&then.stmts, names);
523            if let Some(e) = else_ {
524                collect_idents_from_stmts(&e.stmts, names);
525            }
526        }
527        IrStmt::While { cond, body, .. } => {
528            collect_idents_from_expr(cond, names);
529            collect_idents_from_stmts(&body.stmts, names);
530        }
531        IrStmt::DoWhile { body, cond, .. } => {
532            collect_idents_from_stmts(&body.stmts, names);
533            collect_idents_from_expr(cond, names);
534        }
535        IrStmt::For {
536            init,
537            cond,
538            update,
539            body,
540            ..
541        } => {
542            if let Some(i) = init {
543                collect_idents_from_stmt(i, names);
544            }
545            if let Some(c) = cond {
546                collect_idents_from_expr(c, names);
547            }
548            if let Some(u) = update {
549                collect_idents_from_stmt(u, names);
550            }
551            collect_idents_from_stmts(&body.stmts, names);
552        }
553        IrStmt::ForIn { iterable, body, .. } => {
554            collect_idents_from_expr(iterable, names);
555            collect_idents_from_stmts(&body.stmts, names);
556        }
557        IrStmt::ForOf { iterable, body, .. } => {
558            collect_idents_from_expr(iterable, names);
559            collect_idents_from_stmts(&body.stmts, names);
560        }
561        IrStmt::Switch { expr, cases } => {
562            collect_idents_from_expr(expr, names);
563            for case in cases {
564                collect_idents_from_stmts(&case.body, names);
565            }
566        }
567        IrStmt::Try {
568            try_block,
569            catch_block,
570            finally,
571            ..
572        } => {
573            collect_idents_from_stmts(&try_block.stmts, names);
574            collect_idents_from_stmts(&catch_block.stmts, names);
575            if let Some(f) = finally {
576                collect_idents_from_stmts(&f.stmts, names);
577            }
578        }
579        IrStmt::Throw { value } => {
580            collect_idents_from_expr(value, names);
581        }
582        IrStmt::Return { value } => {
583            if let Some(v) = value {
584                collect_idents_from_expr(v, names);
585            }
586        }
587        IrStmt::Expr(e) => {
588            collect_idents_from_expr(e, names);
589        }
590        IrStmt::Block(b) => {
591            collect_idents_from_stmts(&b.stmts, names);
592        }
593        IrStmt::Break { .. }
594        | IrStmt::Continue { .. }
595        | IrStmt::CompileError { .. }
596        | IrStmt::Comment(_) => {}
597        IrStmt::DestructureDecl(data) => {
598            collect_idents_from_expr(&data.init, names);
599            for binding in &data.bindings {
600                if let Some(d) = &binding.default {
601                    collect_idents_from_expr(d, names);
602                }
603            }
604        }
605        IrStmt::NestedFnDecl {
606            struct_def,
607            instance,
608        } => {
609            collect_idents_from_block(&struct_def.body, names);
610            if let Some(closure) = instance {
611                for cap in &closure.captured {
612                    names.insert(cap.name.js_name.clone());
613                }
614            }
615        }
616    }
617}
618
619fn collect_idents_from_expr(expr: &IrExpr, names: &mut std::collections::HashSet<String>) {
620    match expr {
621        IrExpr::Ident(id) => {
622            names.insert(id.zig_name.clone());
623        }
624        IrExpr::Binary { left, right, .. } => {
625            collect_idents_from_expr(left, names);
626            collect_idents_from_expr(right, names);
627        }
628        IrExpr::Unary { operand, .. } => {
629            collect_idents_from_expr(operand, names);
630        }
631        IrExpr::Logical { left, right, .. } => {
632            collect_idents_from_expr(left, names);
633            collect_idents_from_expr(right, names);
634        }
635        IrExpr::Call(call) => {
636            collect_idents_from_expr(&call.callee, names);
637            for arg in &call.args {
638                collect_idents_from_expr(arg, names);
639            }
640        }
641        IrExpr::BuiltinCall(bc) => {
642            for arg in &bc.args {
643                collect_idents_from_expr(arg, names);
644            }
645        }
646        IrExpr::HostCall(hc) => {
647            for arg in &hc.args {
648                collect_idents_from_expr(arg, names);
649            }
650        }
651        IrExpr::FieldAccess { object, .. } => {
652            collect_idents_from_expr(object, names);
653        }
654        IrExpr::IndexAccess { object, index, .. } => {
655            collect_idents_from_expr(object, names);
656            collect_idents_from_expr(index, names);
657        }
658        IrExpr::ComputedField { object, key, .. } => {
659            collect_idents_from_expr(object, names);
660            collect_idents_from_expr(key, names);
661        }
662        IrExpr::Conditional { cond, then, else_ } => {
663            collect_idents_from_expr(cond, names);
664            collect_idents_from_expr(then, names);
665            collect_idents_from_expr(else_, names);
666        }
667        IrExpr::TemplateLiteral { exprs, .. } => {
668            for e in exprs {
669                collect_idents_from_expr(e, names);
670            }
671        }
672        IrExpr::ArrayLiteral(arr) => {
673            for e in &arr.elements {
674                collect_idents_from_expr(e, names);
675            }
676        }
677        IrExpr::ObjectLiteral(obj) => {
678            use crate::zigir::types::IrObjectItem;
679            for item in &obj.items {
680                match item {
681                    IrObjectItem::Field(f) => {
682                        collect_idents_from_expr(&f.value, names);
683                    }
684                    IrObjectItem::Spread(e) => {
685                        collect_idents_from_expr(e, names);
686                    }
687                }
688            }
689        }
690        IrExpr::Assign { target, value, .. } => {
691            collect_idents_from_target(target, names);
692            collect_idents_from_expr(value, names);
693        }
694        IrExpr::Update { target, .. } => {
695            collect_idents_from_target(target, names);
696        }
697        IrExpr::Closure(c) => {
698            collect_idents_from_stmts(&c.body.stmts, names);
699        }
700        IrExpr::ArrowFn(af) => {
701            collect_idents_from_stmts(&af.body.stmts, names);
702        }
703        IrExpr::FnExpr(fe) => {
704            collect_idents_from_stmts(&fe.body.stmts, names);
705        }
706        IrExpr::Await(a) => {
707            collect_idents_from_expr(&a.callee, names);
708            for arg in &a.args {
709                collect_idents_from_expr(arg, names);
710            }
711        }
712        IrExpr::New(n) => {
713            for arg in &n.args {
714                collect_idents_from_expr(arg, names);
715            }
716        }
717        IrExpr::BlockExpr { body, result, .. } => {
718            collect_idents_from_stmts(body, names);
719            collect_idents_from_expr(result, names);
720        }
721        IrExpr::AllocPrint { args, .. } => {
722            for a in args {
723                collect_idents_from_expr(a, names);
724            }
725        }
726        IrExpr::Spread(e) | IrExpr::Typeof(e) | IrExpr::Void(e) | IrExpr::Paren(e) => {
727            collect_idents_from_expr(e, names);
728        }
729        IrExpr::Sequence(exprs) => {
730            for e in exprs {
731                collect_idents_from_expr(e, names);
732            }
733        }
734        IrExpr::ArrayCallbackInline(inline_data) => {
735            for stmt in &inline_data.body {
736                collect_idents_from_stmt(stmt, names);
737            }
738        }
739        IrExpr::ArrayMethodInline(inline_data) => {
740            for arg in &inline_data.args {
741                collect_idents_from_expr(arg, names);
742            }
743        }
744        IrExpr::OptionalChain { object, body, .. } => {
745            collect_idents_from_expr(object, names);
746            collect_idents_from_expr(body, names);
747        }
748        IrExpr::PowExpr { base, exp, .. } => {
749            collect_idents_from_expr(base, names);
750            collect_idents_from_expr(exp, names);
751        }
752        IrExpr::IntLiteral(_)
753        | IrExpr::FloatLiteral(_)
754        | IrExpr::StringLiteral(_)
755        | IrExpr::BoolLiteral(_)
756        | IrExpr::BigIntLiteral(_)
757        | IrExpr::Null
758        | IrExpr::Undefined
759        | IrExpr::This
760        | IrExpr::CompileError { .. } => {}
761    }
762}
763
764fn collect_idents_from_target(
765    target: &IrAssignTarget,
766    names: &mut std::collections::HashSet<String>,
767) {
768    match target {
769        IrAssignTarget::Ident(id) => {
770            names.insert(id.zig_name.clone());
771        }
772        IrAssignTarget::Member { object, .. } => {
773            collect_idents_from_expr(object, names);
774        }
775        IrAssignTarget::Index { object, index } => {
776            collect_idents_from_expr(object, names);
777            collect_idents_from_expr(index, names);
778        }
779        IrAssignTarget::Destructure(bindings) => {
780            for b in bindings {
781                if let Some(d) = &b.default {
782                    collect_idents_from_expr(d, names);
783                }
784            }
785        }
786    }
787}
788
789/// Check if a ZigType is safe for C ABI boundaries.
790///
791/// C-safe types: i64, f64, Bool, Void, Str (as pointer).
792/// NOT safe: JsAny, ArrayList, HashMap, NamedStruct, Anytype, AnytypeReturn, etc.
793fn is_c_safe_type(ty: &ZigType) -> bool {
794    matches!(
795        ty,
796        ZigType::I64 | ZigType::F64 | ZigType::Bool | ZigType::Void | ZigType::Str
797    )
798}
799
800// ═══════════════════════════════════════════════════════
801//  Tests
802// ═══════════════════════════════════════════════════════
803
804#[cfg(test)]
805mod tests {
806    use super::*;
807    use crate::zigir::ident::IrIdent;
808    use crate::zigir::ops::BinOp;
809    use crate::zigir::types::{IrBlock, IrCapture, IrDecl, IrFnDecl, IrParam, IrStmt, IrVarDecl};
810
811    #[test]
812    fn test_validate_clean_module() {
813        let mut module = IrModule::new("test".to_string());
814        module.declarations.push(IrDecl::Fn(IrFnDecl {
815            name: IrIdent::new("add"),
816            params: vec![
817                IrParam {
818                    name: IrIdent::new("a"),
819                    zig_type: ZigType::I64,
820                    is_unused: false,
821                    is_rest: false,
822                },
823                IrParam {
824                    name: IrIdent::new("b"),
825                    zig_type: ZigType::I64,
826                    is_unused: false,
827                    is_rest: false,
828                },
829            ],
830            return_type: ZigType::I64,
831            body: IrBlock::new(vec![IrStmt::Return {
832                value: Some(IrExpr::Binary {
833                    op: BinOp::Add,
834                    left: Box::new(IrExpr::Ident(IrIdent::new("a"))),
835                    right: Box::new(IrExpr::Ident(IrIdent::new("b"))),
836                    left_type: None,
837                    right_type: None,
838                }),
839            }]),
840            is_export: true,
841            is_async: false,
842            can_throw: false,
843            is_cabi: false,
844            typeof_return_body: None,
845        }));
846
847        let mut pass = ValidatePass::new();
848        let result = pass.run(&mut module);
849        assert!(
850            result.diagnostics.is_empty(),
851            "clean module should have no diagnostics: {:?}",
852            result.diagnostics
853        );
854    }
855
856    #[test]
857    fn test_validate_duplicate_names() {
858        let mut module = IrModule::new("test".to_string());
859        // Add two variables with the same name
860        module.declarations.push(IrDecl::Var(IrVarDecl {
861            name: IrIdent::new("x"),
862            is_const: true,
863            zig_type: Some(ZigType::I64),
864            init: Some(IrExpr::IntLiteral(1)),
865            is_json_parse: false,
866            needs_var_suppression: false,
867        }));
868        module.declarations.push(IrDecl::Var(IrVarDecl {
869            name: IrIdent::new("x"),
870            is_const: true,
871            zig_type: Some(ZigType::I64),
872            init: Some(IrExpr::IntLiteral(2)),
873            is_json_parse: false,
874            needs_var_suppression: false,
875        }));
876
877        let mut pass = ValidatePass::new();
878        let result = pass.run(&mut module);
879        assert_eq!(result.diagnostics.len(), 1);
880        assert!(matches!(
881            result.diagnostics[0].level,
882            DiagnosticLevel::Error
883        ));
884        assert!(result.diagnostics[0].message.contains("duplicate"));
885    }
886
887    #[test]
888    fn test_validate_cabi_unsafe_type() {
889        let mut module = IrModule::new("test".to_string());
890        module.declarations.push(IrDecl::Fn(IrFnDecl {
891            name: IrIdent::new("export_fn"),
892            params: vec![IrParam {
893                name: IrIdent::new("data"),
894                zig_type: ZigType::JsAny, // NOT C-safe
895                is_unused: false,
896                is_rest: false,
897            }],
898            return_type: ZigType::JsAny, // NOT C-safe
899            body: IrBlock::new(vec![]),
900            is_export: false,
901            is_async: false,
902            can_throw: false,
903            is_cabi: true,
904            typeof_return_body: None,
905        }));
906
907        let mut pass = ValidatePass::new();
908        let result = pass.run(&mut module);
909        let errors: Vec<_> = result
910            .diagnostics
911            .iter()
912            .filter(|d| matches!(d.level, DiagnosticLevel::Error))
913            .collect();
914        assert_eq!(
915            errors.len(),
916            2,
917            "should have 2 C ABI errors (param + return), got: {:?}",
918            result.diagnostics
919        );
920    }
921
922    #[test]
923    fn test_validate_closure_capture_not_referenced() {
924        let mut module = IrModule::new("test".to_string());
925        // Add a closure struct with a captured var not referenced in body
926        module
927            .closure_structs
928            .push(crate::zigir::types::IrClosureStruct {
929                name: IrIdent::new("_closure_0"),
930                captured: vec![IrCapture {
931                    name: IrIdent::new("unused_var"),
932                    zig_type: ZigType::I64,
933                    is_mut: false,
934                }],
935                fn_params: vec![IrParam {
936                    name: IrIdent::new("x"),
937                    zig_type: ZigType::I64,
938                    is_unused: false,
939                    is_rest: false,
940                }],
941                return_type: ZigType::I64,
942                typeof_return_body: None,
943                body: IrBlock::new(vec![IrStmt::Return {
944                    value: Some(IrExpr::Ident(IrIdent::new("x"))),
945                }]),
946            });
947
948        let mut pass = ValidatePass::new();
949        let result = pass.run(&mut module);
950        let warnings: Vec<_> = result
951            .diagnostics
952            .iter()
953            .filter(|d| matches!(d.level, DiagnosticLevel::Warning))
954            .collect();
955        assert_eq!(warnings.len(), 1, "should warn about unreferenced capture");
956        assert!(warnings[0].message.contains("unused_var"));
957    }
958}