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