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
15use std::cell::RefCell;
16
17use super::{collect_idents, walk};
18
19/// Validation pass: checks structural integrity of the IR.
20///
21/// Produces warnings for suspicious patterns and errors for violations
22/// that would cause incorrect Zig output. Does NOT modify the IR.
23pub struct ValidatePass {
24    /// Collected diagnostics for the current run.
25    diagnostics: Vec<IrDiagnostic>,
26}
27
28impl ValidatePass {
29    pub fn new() -> Self {
30        Self {
31            diagnostics: Vec::new(),
32        }
33    }
34
35    fn error(&mut self, msg: String) {
36        self.diagnostics.push(IrDiagnostic {
37            level: DiagnosticLevel::Error,
38            span: None,
39            message: msg,
40        });
41    }
42
43    fn warn(&mut self, msg: String) {
44        self.diagnostics.push(IrDiagnostic {
45            level: DiagnosticLevel::Warning,
46            span: None,
47            message: msg,
48        });
49    }
50
51    // ── Top-level name uniqueness ────────────────────
52
53    fn check_name_uniqueness(&mut self, module: &IrModule) {
54        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
55
56        // Check typedefs
57        for td in &module.typedefs {
58            if !seen.insert(td.name.clone()) {
59                self.error(format!("duplicate top-level name: '{}'", td.name));
60            }
61        }
62
63        // Check closure structs
64        for cs in &module.closure_structs {
65            let zig_name = cs.name.zig_name.clone();
66            if !seen.insert(zig_name.clone()) {
67                self.error(format!("duplicate top-level name: '{}'", zig_name));
68            }
69        }
70
71        // Check declarations
72        for decl in &module.declarations {
73            let name = match decl {
74                IrDecl::Var(v) => v.name.zig_name.clone(),
75                IrDecl::Fn(f) => f.name.zig_name.clone(),
76                IrDecl::Class(c) => c.name.zig_name.clone(),
77                IrDecl::CompileError { .. } => continue,
78            };
79            if !seen.insert(name.clone()) {
80                self.error(format!("duplicate top-level name: '{}'", name));
81            }
82        }
83    }
84
85    // ── C ABI compatibility ──────────────────────────
86
87    fn check_cabi_compatibility(&mut self, module: &IrModule) {
88        for decl in &module.declarations {
89            if let IrDecl::Fn(f) = decl
90                && f.is_cabi
91            {
92                self.check_cabi_fn(f);
93            }
94        }
95        for export in &module.cabi_exports {
96            // Skip exports with Anytype/AsyncIo params/return — they'll be const-aliased
97            // or have AsyncIo filtered from C ABI wrappers, so C-safety validation doesn't apply.
98            let skip_type = matches!(export.return_type, ZigType::Anytype | ZigType::AsyncIo)
99                || export
100                    .params
101                    .iter()
102                    .any(|p| matches!(p.zig_type, ZigType::Anytype | ZigType::AsyncIo));
103            if skip_type {
104                continue;
105            }
106            // Async exports with NamedStruct returns use out-pointer C ABI wrappers
107            let ret_ok = is_c_safe_type(&export.return_type)
108                || (export.is_async && matches!(export.return_type, ZigType::NamedStruct(_)));
109            if !ret_ok {
110                self.error(format!(
111                    "C ABI export '{}' has non-C-safe return type: {:?}",
112                    export.name, export.return_type
113                ));
114            }
115            for param in &export.params {
116                if !is_c_safe_type(&param.zig_type) {
117                    self.error(format!(
118                        "C ABI export '{}' has non-C-safe parameter '{}': {:?}",
119                        export.name, param.name.zig_name, param.zig_type
120                    ));
121                }
122            }
123        }
124    }
125
126    fn check_cabi_fn(&mut self, f: &IrFnDecl) {
127        // The 'io: AsyncIo' parameter is injected by the lowerer for async functions
128        // and replaced by js_runtime.getIo() in C ABI wrappers — skip it.
129        // NamedStruct/Str returns for async functions use out-pointer/String C ABI wrappers.
130        let async_ret_exempt =
131            f.is_async && matches!(f.return_type, ZigType::NamedStruct(_) | ZigType::Str);
132        if !is_c_safe_type(&f.return_type) && !async_ret_exempt {
133            self.error(format!(
134                "C ABI function '{}' has non-C-safe return type: {:?}",
135                f.name.zig_name, f.return_type
136            ));
137        }
138        for param in &f.params {
139            if matches!(param.zig_type, ZigType::AsyncIo) {
140                continue;
141            }
142            if !is_c_safe_type(&param.zig_type) {
143                self.error(format!(
144                    "C ABI function '{}' has non-C-safe parameter '{}': {:?}",
145                    f.name.zig_name, param.name.zig_name, param.zig_type
146                ));
147            }
148        }
149    }
150
151    // ── Closure integrity ────────────────────────────
152
153    fn check_closure_integrity(&mut self, module: &IrModule) {
154        for cs in &module.closure_structs {
155            // Check that each captured variable is actually referenced in the body
156            let referenced = {
157                let mut names = std::collections::HashSet::new();
158                collect_idents::collect_block_idents(&cs.body, &mut names);
159                names
160            };
161            for capture in &cs.captured {
162                if !referenced.contains(&capture.name.zig_name) {
163                    self.warn(format!(
164                        "closure struct '{}' captures '{}' but it is not referenced in the body",
165                        cs.name.zig_name, capture.name.zig_name
166                    ));
167                }
168            }
169        }
170
171        // Check IrClosure expressions in declarations
172        for decl in &module.declarations {
173            self.check_closure_refs_in_decl(decl);
174        }
175    }
176
177    fn check_closure_refs_in_decl(&mut self, decl: &IrDecl) {
178        let this = RefCell::new(&mut *self);
179        walk::for_each_decl_child(
180            decl,
181            &mut |block| {
182                this.borrow_mut().check_closure_refs_in_block(block);
183            },
184            &mut |expr| {
185                this.borrow_mut().check_closure_refs_in_expr(expr);
186            },
187        );
188    }
189
190    fn check_closure_refs_in_block(&mut self, block: &IrBlock) {
191        for stmt in &block.stmts {
192            self.check_closure_refs_in_stmt(stmt);
193        }
194    }
195
196    fn check_closure_refs_in_stmt(&mut self, stmt: &IrStmt) {
197        // Special case: NestedFnDecl — check struct body + capture names (not closure body)
198        if let IrStmt::NestedFnDecl {
199            struct_def,
200            instance,
201        } = stmt
202        {
203            self.check_closure_refs_in_block(&struct_def.body);
204            if let Some(closure) = instance {
205                for cap in &closure.captured {
206                    self.check_closure_refs_in_expr(&IrExpr::Ident(cap.name.clone()));
207                }
208            }
209            return;
210        }
211
212        // Standard walk; on_target is no-op because validate at stmt level
213        // does not visit Assign.target (that's done at expr level)
214        let this = RefCell::new(&mut *self);
215        walk::for_each_stmt_child(
216            stmt,
217            &mut |block| {
218                this.borrow_mut().check_closure_refs_in_block(block);
219            },
220            &mut |s| {
221                this.borrow_mut().check_closure_refs_in_stmt(s);
222            },
223            &mut |expr| {
224                this.borrow_mut().check_closure_refs_in_expr(expr);
225            },
226            &mut |_| {},
227        );
228    }
229
230    fn check_closure_refs_in_expr(&mut self, expr: &IrExpr) {
231        // Special case: Closure — check capture references (don't recurse into body)
232        if let IrExpr::Closure(closure) = expr {
233            let referenced = {
234                let mut names = std::collections::HashSet::new();
235                collect_idents::collect_block_idents(&closure.body, &mut names);
236                names
237            };
238            for capture in &closure.captured {
239                if !referenced.contains(&capture.name.zig_name) {
240                    self.warn(format!(
241                        "closure '{}' captures '{}' but it is not referenced in the body",
242                        closure.struct_name.zig_name, capture.name.zig_name
243                    ));
244                }
245            }
246            return;
247        }
248
249        let this = RefCell::new(&mut *self);
250        walk::for_each_expr_child(
251            expr,
252            &mut |block| {
253                this.borrow_mut().check_closure_refs_in_block(block);
254            },
255            &mut |s| {
256                this.borrow_mut().check_closure_refs_in_stmt(s);
257            },
258            &mut |expr| {
259                this.borrow_mut().check_closure_refs_in_expr(expr);
260            },
261            &mut |target| {
262                this.borrow_mut()
263                    .check_closure_refs_in_assign_target(target);
264            },
265        );
266    }
267
268    fn check_closure_refs_in_assign_target(&mut self, target: &IrAssignTarget) {
269        let this = RefCell::new(&mut *self);
270        walk::for_each_target_child(target, &mut |expr| {
271            this.borrow_mut().check_closure_refs_in_expr(expr);
272        });
273    }
274}
275
276impl IrPass for ValidatePass {
277    fn name(&self) -> &'static str {
278        "validate"
279    }
280
281    fn description(&self) -> &'static str {
282        "Validates structural integrity of the IR (name uniqueness, C ABI compatibility, closure integrity)"
283    }
284
285    fn run(&mut self, module: &mut IrModule) -> PassResult {
286        self.diagnostics.clear();
287
288        self.check_name_uniqueness(module);
289        self.check_cabi_compatibility(module);
290        self.check_closure_integrity(module);
291
292        let diagnostics = std::mem::take(&mut self.diagnostics);
293        PassResult::with_diagnostics(diagnostics)
294    }
295}
296
297impl Default for ValidatePass {
298    fn default() -> Self {
299        Self::new()
300    }
301}
302
303// ═══════════════════════════════════════════════════════
304//  Helpers
305// ═══════════════════════════════════════════════════════
306
307/// Check if a ZigType is safe for C ABI boundaries.
308///
309/// C-safe types: i64, f64, Bool, Void, Str (as pointer).
310/// NOT safe: JsAny, ArrayList, HashMap, NamedStruct, Anytype, AnytypeReturn, etc.
311fn is_c_safe_type(ty: &ZigType) -> bool {
312    matches!(
313        ty,
314        ZigType::I64 | ZigType::F64 | ZigType::Bool | ZigType::Void | ZigType::Str
315    )
316}
317
318// ═══════════════════════════════════════════════════════
319//  Tests
320// ═══════════════════════════════════════════════════════
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325    use crate::zigir::ident::IrIdent;
326    use crate::zigir::types::{IrBlock, IrCapture, IrDecl, IrFnDecl, IrParam, IrStmt, IrVarDecl};
327
328    #[test]
329    fn test_validate_clean_module() {
330        let mut module = super::super::make_clean_add_module();
331
332        let mut pass = ValidatePass::new();
333        let result = pass.run(&mut module);
334        assert!(
335            result.diagnostics.is_empty(),
336            "clean module should have no diagnostics: {:?}",
337            result.diagnostics
338        );
339    }
340
341    #[test]
342    fn test_validate_duplicate_names() {
343        let mut module = IrModule::new("test".to_string());
344        // Add two variables with the same name
345        module.declarations.push(IrDecl::Var(IrVarDecl::new_const(
346            "x",
347            Some(ZigType::I64),
348            Some(IrExpr::IntLiteral(1)),
349        )));
350        module.declarations.push(IrDecl::Var(IrVarDecl::new_const(
351            "x",
352            Some(ZigType::I64),
353            Some(IrExpr::IntLiteral(2)),
354        )));
355
356        let mut pass = ValidatePass::new();
357        let result = pass.run(&mut module);
358        assert_eq!(result.diagnostics.len(), 1);
359        assert!(matches!(
360            result.diagnostics[0].level,
361            DiagnosticLevel::Error
362        ));
363        assert!(result.diagnostics[0].message.contains("duplicate"));
364    }
365
366    #[test]
367    fn test_validate_cabi_unsafe_type() {
368        let mut module = IrModule::new("test".to_string());
369        module.declarations.push(IrDecl::Fn(IrFnDecl {
370            name: IrIdent::new("export_fn"),
371            params: vec![IrParam {
372                name: IrIdent::new("data"),
373                zig_type: ZigType::JsAny, // NOT C-safe
374                is_unused: false,
375                is_rest: false,
376            }],
377            return_type: ZigType::JsAny, // NOT C-safe
378            body: IrBlock::new(vec![]),
379            is_export: false,
380            is_async: false,
381            can_throw: false,
382            is_cabi: true,
383            typeof_return_body: None,
384        }));
385
386        let mut pass = ValidatePass::new();
387        let result = pass.run(&mut module);
388        let errors: Vec<_> = result
389            .diagnostics
390            .iter()
391            .filter(|d| matches!(d.level, DiagnosticLevel::Error))
392            .collect();
393        assert_eq!(
394            errors.len(),
395            2,
396            "should have 2 C ABI errors (param + return), got: {:?}",
397            result.diagnostics
398        );
399    }
400
401    #[test]
402    fn test_validate_closure_capture_not_referenced() {
403        let mut module = IrModule::new("test".to_string());
404        // Add a closure struct with a captured var not referenced in body
405        module
406            .closure_structs
407            .push(crate::zigir::types::IrClosureStruct {
408                name: IrIdent::new("_closure_0"),
409                captured: vec![IrCapture {
410                    name: IrIdent::new("unused_var"),
411                    zig_type: ZigType::I64,
412                    is_mut: false,
413                    init_expr: None,
414                }],
415                fn_params: vec![IrParam {
416                    name: IrIdent::new("x"),
417                    zig_type: ZigType::I64,
418                    is_unused: false,
419                    is_rest: false,
420                }],
421                return_type: ZigType::I64,
422                typeof_return_body: None,
423                body: IrBlock::new(vec![IrStmt::Return {
424                    value: Some(IrExpr::Ident(IrIdent::new("x"))),
425                }]),
426            });
427
428        let mut pass = ValidatePass::new();
429        let result = pass.run(&mut module);
430        let warnings: Vec<_> = result
431            .diagnostics
432            .iter()
433            .filter(|d| matches!(d.level, DiagnosticLevel::Warning))
434            .collect();
435        assert_eq!(warnings.len(), 1, "should warn about unreferenced capture");
436        assert!(warnings[0].message.contains("unused_var"));
437    }
438}