From af78acba9450a7cdd0b207e7ab69d9902a6b941c Mon Sep 17 00:00:00 2001 From: overlookmotel <557937+overlookmotel@users.noreply.github.com> Date: Fri, 21 Mar 2025 14:08:06 +0000 Subject: [PATCH] feat(transformer): add `StatementInjectorStore::move_insertions` method (#9951) Introduce a new method on `StatementInjectorStore` to move any injections attached to one statement to another statement. This is used in #9952. --- .../src/common/statement_injector.rs | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/oxc_transformer/src/common/statement_injector.rs b/crates/oxc_transformer/src/common/statement_injector.rs index a8b2b958a311f..5724ce4e5e532 100644 --- a/crates/oxc_transformer/src/common/statement_injector.rs +++ b/crates/oxc_transformer/src/common/statement_injector.rs @@ -12,7 +12,7 @@ //! self.ctx.statement_injector.insert_many_after(address, statements); //! ``` -use std::cell::RefCell; +use std::{cell::RefCell, collections::hash_map::Entry}; use rustc_hash::FxHashMap; @@ -153,6 +153,34 @@ impl<'a> StatementInjectorStore<'a> { stmts.into_iter().map(|stmt| AdjacentStatement { stmt, direction: Direction::After }), ); } + + /// Move insertions from one [`Address`] to another. + /// + /// Use this if you convert one statement to another, and other code may have attached + /// insertions to the original statement. + #[expect(dead_code)] + #[inline] + pub fn move_insertions( + &self, + old_target: &A1, + new_target: &A2, + ) { + self.move_insertions_address(old_target.address(), new_target.address()); + } + + fn move_insertions_address(&self, old_address: Address, new_address: Address) { + let mut insertions = self.insertions.borrow_mut(); + let Some(mut adjacent_stmts) = insertions.remove(&old_address) else { return }; + + match insertions.entry(new_address) { + Entry::Occupied(entry) => { + entry.into_mut().append(&mut adjacent_stmts); + } + Entry::Vacant(entry) => { + entry.insert(adjacent_stmts); + } + } + } } // Internal methods