js2zig_core/zigir/passes/
mod.rs1mod 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#[derive(Debug, Clone)]
26pub struct PassResult {
27 pub changed: bool,
29 pub diagnostics: Vec<IrDiagnostic>,
31}
32
33impl PassResult {
34 pub fn unchanged() -> Self {
36 Self {
37 changed: false,
38 diagnostics: Vec::new(),
39 }
40 }
41
42 pub fn changed() -> Self {
44 Self {
45 changed: true,
46 diagnostics: Vec::new(),
47 }
48 }
49
50 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 pub fn merge(&mut self, other: PassResult) {
65 self.changed = self.changed || other.changed;
66 self.diagnostics.extend(other.diagnostics);
67 }
68}
69
70pub trait IrPass {
76 fn name(&self) -> &'static str;
78
79 fn description(&self) -> &'static str;
81
82 fn run(&mut self, module: &mut IrModule) -> PassResult;
87}
88
89pub struct PassPipeline {
98 passes: Vec<Box<dyn IrPass>>,
99 pub continue_on_error: bool,
101}
102
103#[derive(Debug, Clone)]
105pub struct PipelineResult {
106 pub passes_run: usize,
109 pub changed: bool,
111 pub diagnostics: Vec<IrDiagnostic>,
113 pub changed_passes: Vec<&'static str>,
115}
116
117impl PassPipeline {
118 pub fn new() -> Self {
120 Self {
121 passes: Vec::new(),
122 continue_on_error: false,
123 }
124 }
125
126 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 pub fn add_pass(&mut self, pass: impl IrPass + 'static) {
141 self.passes.push(Box::new(pass));
142 }
143
144 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#[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#[cfg(test)]
236mod tests {
237 use super::*;
238 use crate::types::ZigType;
239 use crate::zigir::types::{IrDecl, IrVarDecl};
240
241 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 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 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); 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 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}