Skip to main content

js2zig_core/zigir/passes/
mod.rs

1// zigir/passes/mod.rs
2// Optimization and validation passes for the ZigIR pipeline.
3//
4// Each pass implements the `IrPass` trait and can be composed into a
5// `PassPipeline` that runs them in sequence on an `IrModule`.
6
7mod collect_idents;
8mod constant_fold;
9mod dead_code;
10mod validate;
11pub(crate) mod walk;
12
13pub use constant_fold::ConstantFoldPass;
14pub use dead_code::DeadCodeElimPass;
15pub use validate::ValidatePass;
16
17use crate::zigir::source_span::IrDiagnostic;
18use crate::zigir::types::IrModule;
19
20// ═══════════════════════════════════════════════════════
21//  IrPass trait
22// ═══════════════════════════════════════════════════════
23
24/// Result of running a single pass on an IrModule.
25#[derive(Debug, Clone)]
26pub struct PassResult {
27    /// Whether the pass modified the IR.
28    pub changed: bool,
29    /// Diagnostics produced by this pass (warnings/errors).
30    pub diagnostics: Vec<IrDiagnostic>,
31}
32
33impl PassResult {
34    /// Create an unchanged result with no diagnostics.
35    pub fn unchanged() -> Self {
36        Self {
37            changed: false,
38            diagnostics: Vec::new(),
39        }
40    }
41
42    /// Create a changed result with no diagnostics.
43    pub fn changed() -> Self {
44        Self {
45            changed: true,
46            diagnostics: Vec::new(),
47        }
48    }
49
50    /// Create a result with diagnostics. `changed` is true if any diagnostic
51    /// is an error (errors typically indicate the IR was invalid and may
52    /// have been repaired), false for pure warnings.
53    pub fn with_diagnostics(diagnostics: Vec<IrDiagnostic>) -> Self {
54        let changed = diagnostics
55            .iter()
56            .any(|d| matches!(d.level, crate::zigir::source_span::DiagnosticLevel::Error));
57        Self {
58            changed,
59            diagnostics,
60        }
61    }
62
63    /// Merge another result into this one.
64    pub fn merge(&mut self, other: PassResult) {
65        self.changed = self.changed || other.changed;
66        self.diagnostics.extend(other.diagnostics);
67    }
68}
69
70/// A transformation or validation pass over the IR.
71///
72/// Passes should be idempotent where possible: running the same pass
73/// twice on the same module should produce the same result, and the
74/// second run should return `changed: false`.
75pub trait IrPass {
76    /// Human-readable name of the pass (for logging/diagnostics).
77    fn name(&self) -> &'static str;
78
79    /// Short description of what the pass does.
80    fn description(&self) -> &'static str;
81
82    /// Run the pass on the module, potentially mutating it in place.
83    ///
84    /// Returns a `PassResult` indicating whether the IR was modified
85    /// and any diagnostics produced.
86    fn run(&mut self, module: &mut IrModule) -> PassResult;
87}
88
89// ═══════════════════════════════════════════════════════
90//  PassPipeline
91// ═══════════════════════════════════════════════════════
92
93/// A sequence of IR passes that are run in order on a module.
94///
95/// The pipeline stops early if a pass produces error-level diagnostics
96/// (unless `continue_on_error` is set).
97pub struct PassPipeline {
98    passes: Vec<Box<dyn IrPass>>,
99    /// Whether to continue running passes after one produces errors.
100    pub continue_on_error: bool,
101}
102
103/// Summary of a pipeline run.
104#[derive(Debug, Clone)]
105pub struct PipelineResult {
106    /// Total number of passes that were run (may be less than total
107    /// if stopped early due to errors).
108    pub passes_run: usize,
109    /// Whether any pass modified the IR.
110    pub changed: bool,
111    /// All diagnostics from all passes, in order.
112    pub diagnostics: Vec<IrDiagnostic>,
113    /// Names of passes that reported changes, in order.
114    pub changed_passes: Vec<&'static str>,
115}
116
117impl PassPipeline {
118    /// Create an empty pipeline.
119    pub fn new() -> Self {
120        Self {
121            passes: Vec::new(),
122            continue_on_error: false,
123        }
124    }
125
126    /// Create the default optimization pipeline.
127    ///
128    /// Order: Validate → DeadCodeElim → ConstantFold → Validate
129    /// (validate again after transforms to check invariants hold).
130    pub fn default_pipeline() -> Self {
131        let mut pipeline = Self::new();
132        pipeline.add_pass(ValidatePass::new());
133        pipeline.add_pass(DeadCodeElimPass::new());
134        pipeline.add_pass(ConstantFoldPass::new());
135        pipeline.add_pass(ValidatePass::new());
136        pipeline
137    }
138
139    /// Add a pass to the end of the pipeline.
140    pub fn add_pass(&mut self, pass: impl IrPass + 'static) {
141        self.passes.push(Box::new(pass));
142    }
143
144    /// Run all passes in sequence on the module.
145    pub fn run(&mut self, module: &mut IrModule) -> PipelineResult {
146        let mut result = PipelineResult {
147            passes_run: 0,
148            changed: false,
149            diagnostics: Vec::new(),
150            changed_passes: Vec::new(),
151        };
152
153        for pass in &mut self.passes {
154            let pass_result = pass.run(module);
155            result.passes_run += 1;
156
157            let had_errors = pass_result
158                .diagnostics
159                .iter()
160                .any(|d| matches!(d.level, crate::zigir::source_span::DiagnosticLevel::Error));
161
162            result.diagnostics.extend(pass_result.diagnostics);
163
164            if pass_result.changed {
165                result.changed = true;
166                result.changed_passes.push(pass.name());
167            }
168
169            if had_errors && !self.continue_on_error {
170                break;
171            }
172        }
173
174        result
175    }
176}
177
178impl Default for PassPipeline {
179    fn default() -> Self {
180        Self::new()
181    }
182}
183
184// ═══════════════════════════════════════════════════════
185//  Shared test helpers (available to all pass submodules)
186// ═══════════════════════════════════════════════════════
187
188#[cfg(test)]
189pub(crate) fn make_clean_add_module() -> IrModule {
190    use crate::types::ZigType;
191    use crate::zigir::ident::IrIdent;
192    use crate::zigir::ops::BinOp;
193    use crate::zigir::types::*;
194
195    let mut module = IrModule::new("test".to_string());
196    module.declarations.push(IrDecl::Fn(IrFnDecl {
197        name: IrIdent::new("add"),
198        params: vec![
199            IrParam {
200                name: IrIdent::new("a"),
201                zig_type: ZigType::I64,
202                is_unused: false,
203                is_rest: false,
204            },
205            IrParam {
206                name: IrIdent::new("b"),
207                zig_type: ZigType::I64,
208                is_unused: false,
209                is_rest: false,
210            },
211        ],
212        return_type: ZigType::I64,
213        body: IrBlock::new(vec![IrStmt::Return {
214            value: Some(IrExpr::Binary {
215                op: BinOp::Add,
216                left: Box::new(IrExpr::Ident(IrIdent::new("a"))),
217                right: Box::new(IrExpr::Ident(IrIdent::new("b"))),
218                left_type: None,
219                right_type: None,
220            }),
221        }]),
222        is_export: true,
223        is_async: false,
224        can_throw: false,
225        is_cabi: false,
226        typeof_return_body: None,
227    }));
228    module
229}
230
231// ═══════════════════════════════════════════════════════
232//  Tests
233// ═══════════════════════════════════════════════════════
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238    use crate::types::ZigType;
239    use crate::zigir::types::{IrDecl, IrVarDecl};
240
241    /// A no-op pass for testing the pipeline infrastructure.
242    struct NoOpPass;
243
244    impl IrPass for NoOpPass {
245        fn name(&self) -> &'static str {
246            "no-op"
247        }
248        fn description(&self) -> &'static str {
249            "does nothing"
250        }
251        fn run(&mut self, _module: &mut IrModule) -> PassResult {
252            PassResult::unchanged()
253        }
254    }
255
256    /// A pass that adds a diagnostic for testing.
257    struct WarnPass;
258
259    impl IrPass for WarnPass {
260        fn name(&self) -> &'static str {
261            "warn"
262        }
263        fn description(&self) -> &'static str {
264            "emits a warning"
265        }
266        fn run(&mut self, _module: &mut IrModule) -> PassResult {
267            PassResult::with_diagnostics(vec![IrDiagnostic::warning("test warning".to_string())])
268        }
269    }
270
271    /// A pass that adds a variable declaration for testing change detection.
272    struct AddVarPass;
273
274    impl IrPass for AddVarPass {
275        fn name(&self) -> &'static str {
276            "add-var"
277        }
278        fn description(&self) -> &'static str {
279            "adds a variable"
280        }
281        fn run(&mut self, module: &mut IrModule) -> PassResult {
282            module.declarations.push(IrDecl::Var(IrVarDecl::new_const(
283                "__test_added",
284                Some(ZigType::I64),
285                Some(crate::zigir::types::IrExpr::IntLiteral(0)),
286            )));
287            PassResult::changed()
288        }
289    }
290
291    #[test]
292    fn test_empty_pipeline() {
293        let mut pipeline = PassPipeline::new();
294        let mut module = IrModule::new("test".to_string());
295        let result = pipeline.run(&mut module);
296        assert_eq!(result.passes_run, 0);
297        assert!(!result.changed);
298    }
299
300    #[test]
301    fn test_noop_pass() {
302        let mut pipeline = PassPipeline::new();
303        pipeline.add_pass(NoOpPass);
304        let mut module = IrModule::new("test".to_string());
305        let result = pipeline.run(&mut module);
306        assert_eq!(result.passes_run, 1);
307        assert!(!result.changed);
308        assert!(result.changed_passes.is_empty());
309    }
310
311    #[test]
312    fn test_warn_pass() {
313        let mut pipeline = PassPipeline::new();
314        pipeline.add_pass(WarnPass);
315        let mut module = IrModule::new("test".to_string());
316        let result = pipeline.run(&mut module);
317        assert_eq!(result.passes_run, 1);
318        assert!(!result.changed); // warnings don't count as "changed"
319        assert_eq!(result.diagnostics.len(), 1);
320    }
321
322    #[test]
323    fn test_change_detection() {
324        let mut pipeline = PassPipeline::new();
325        pipeline.add_pass(AddVarPass);
326        let mut module = IrModule::new("test".to_string());
327        let result = pipeline.run(&mut module);
328        assert_eq!(result.passes_run, 1);
329        assert!(result.changed);
330        assert_eq!(result.changed_passes, vec!["add-var"]);
331        assert_eq!(module.declarations.len(), 1);
332    }
333
334    #[test]
335    fn test_multi_pass_pipeline() {
336        let mut pipeline = PassPipeline::new();
337        pipeline.add_pass(NoOpPass);
338        pipeline.add_pass(WarnPass);
339        pipeline.add_pass(AddVarPass);
340        let mut module = IrModule::new("test".to_string());
341        let result = pipeline.run(&mut module);
342        assert_eq!(result.passes_run, 3);
343        assert!(result.changed);
344        assert_eq!(result.changed_passes, vec!["add-var"]);
345        assert_eq!(result.diagnostics.len(), 1);
346    }
347
348    #[test]
349    fn test_default_pipeline_runs() {
350        let mut pipeline = PassPipeline::default_pipeline();
351        let mut module = IrModule::new("test".to_string());
352        let result = pipeline.run(&mut module);
353        // 4 passes: Validate → DeadCodeElim → ConstantFold → Validate
354        assert_eq!(result.passes_run, 4);
355    }
356
357    #[test]
358    fn test_pass_result_merge() {
359        let mut r1 = PassResult::changed();
360        let r2 = PassResult::with_diagnostics(vec![IrDiagnostic::warning("w".to_string())]);
361        r1.merge(r2);
362        assert!(r1.changed);
363        assert_eq!(r1.diagnostics.len(), 1);
364    }
365}