diff --git a/crates/plotnik-compiler/src/compile/collapse_up.rs b/crates/plotnik-compiler/src/compile/collapse_up.rs new file mode 100644 index 0000000..0c3ae7f --- /dev/null +++ b/crates/plotnik-compiler/src/compile/collapse_up.rs @@ -0,0 +1,134 @@ +//! Up-collapse optimization: merge consecutive Up instructions of the same mode. +//! +//! Transforms: Up(1) → Up(1) → Up(2) into Up(4) +//! +//! Constraints: +//! - Same mode only (Up, UpSkipTrivia, UpExact can't mix) +//! - Effectless only (no pre_effects, post_effects, neg_fields) +//! - Max 63 (6-bit payload limit) +//! - Single successor (can't merge branching instructions) + +use std::collections::{HashMap, HashSet}; + +use plotnik_bytecode::Nav; + +use crate::bytecode::{InstructionIR, Label, MatchIR, NodeTypeIR}; +use crate::compile::CompileResult; + +const MAX_UP_LEVEL: u8 = 63; + +/// Collapse consecutive Up instructions of the same mode. +pub fn collapse_up(result: &mut CompileResult) { + let label_to_idx: HashMap = result + .instructions + .iter() + .enumerate() + .map(|(i, instr)| (instr.label(), i)) + .collect(); + + let mut removed: HashSet