oxc_allocator/replace_with.rs
1use std::{
2 boxed::Box as StdBox, cell::Cell, marker::PhantomData, mem, ptr::NonNull, sync::Mutex,
3 vec::Vec as StdVec,
4};
5
6use crate::{Allocator, Box, Dummy, Vec};
7
8/// A trait to replace an existing AST node in place with a new node built from the old one.
9pub trait ReplaceWith<'a>: Dummy<'a> {
10 /// Replace the node in place with the value returned by `replacer`.
11 ///
12 /// `replacer` is called with an owned copy of the node, and whatever it returns is written back in its place.
13 /// This is for the common case where a node is taken purely to build a new node out of it
14 /// (typically wrapping the old node, or extracting just a part of it), which is then stored back in the same slot.
15 ///
16 /// Prefer this over [`take_in`] + writing the result back. That writes a dummy node into arena,
17 /// which takes up space in arena forever, even though it's pointless - it's overwritten immediately.
18 /// This method avoids the need for the dummy node, so is faster, and takes less memory.
19 ///
20 /// ```
21 /// # use oxc_allocator::{Allocator, Box, Dummy};
22 /// # enum Expression<'a> {
23 /// # ParenthesizedExpression(Box<'a, ParenthesizedExpression<'a>>),
24 /// # Empty,
25 /// # }
26 /// # struct ParenthesizedExpression<'a> {
27 /// # expression: Expression<'a>,
28 /// # }
29 /// # impl<'a> Dummy<'a> for Expression<'a> {
30 /// # fn dummy(allocator: &'a Allocator) -> Self {
31 /// # Self::Empty
32 /// # }
33 /// # }
34 /// # impl<'a> ReplaceWith<'a> for Expression<'a> {}
35 /// use oxc_allocator::ReplaceWith;
36 ///
37 /// // If `expr` is a parenthesized expression `(inner)`, unwrap it to `inner` in place
38 /// fn unwrap_parens<'a>(expr: &mut Expression<'a>) {
39 /// if matches!(expr, Expression::ParenthesizedExpression(_)) {
40 /// expr.replace_with(|expr| {
41 /// let Expression::ParenthesizedExpression(paren) = expr else { unreachable!() };
42 /// paren.unbox().expression
43 /// });
44 /// }
45 /// }
46 /// ```
47 ///
48 /// # Panic handling
49 ///
50 /// If `replacer` panics, the original place is left holding a dummy (see [`Dummy`]), so it always
51 /// remains valid and usable. Building that dummy is the only situation in which this method allocates,
52 /// so the common (non-panicking) path allocates nothing.
53 ///
54 /// When compiled with `panic = "abort"`, the code for writing the dummy is optimized out entirely.
55 ///
56 /// Handling panics in this way is only required to avoid UB in obscure cases where `catch_unwind`
57 /// is used and the original value is accessed after the panic.
58 ///
59 /// Without the panic handling, these would both be Undefined Behavior:
60 ///
61 /// #### Double drop
62 ///
63 /// ```
64 /// use std::{
65 /// boxed::Box as StdBox,
66 /// mem::ManuallyDrop,
67 /// panic::{AssertUnwindSafe, catch_unwind},
68 /// };
69 /// use oxc_allocator::{Allocator, Dummy, ReplaceWith};
70 ///
71 /// // `ManuallyDrop` wrapper is not required here, but it demonstrates that
72 /// // a const assertion in `replace_with` that `Self: !Drop` would not be
73 /// // sufficient to prevent UB - `Wrapper` is `!Drop`.
74 /// struct Wrapper(ManuallyDrop<StdBox<u32>>);
75 ///
76 /// impl ReplaceWith<'_> for Wrapper {}
77 ///
78 /// impl<'a> Dummy<'a> for Wrapper {
79 /// fn dummy(_allocator: &'a Allocator) -> Self {
80 /// Self(ManuallyDrop::new(StdBox::new(0)))
81 /// }
82 /// }
83 ///
84 /// let mut wrapper = Wrapper(ManuallyDrop::new(StdBox::new(123)));
85 ///
86 /// let _ = catch_unwind(AssertUnwindSafe(|| {
87 /// wrapper.replace_with(|old| {
88 /// let boxed: StdBox<u32> = ManuallyDrop::into_inner(old.0);
89 /// // `Box` is freed
90 /// drop(boxed);
91 /// panic!("Unwind before write-back");
92 /// });
93 /// }));
94 ///
95 /// let boxed: StdBox<u32> = ManuallyDrop::into_inner(wrapper.0);
96 /// // Without the panic guard, `boxed` would be the same `Box`
97 /// // that was freed in closure above. Double drop!
98 /// drop(boxed);
99 /// ```
100 ///
101 /// #### Aliasing violation
102 ///
103 /// ```
104 /// use std::panic::{AssertUnwindSafe, catch_unwind};
105 /// use oxc_allocator::{Allocator, ArenaBox, Dummy, ReplaceWith};
106 ///
107 /// struct Wrapper<'a>(ArenaBox<'a, u32>);
108 ///
109 /// impl<'a> ReplaceWith<'a> for Wrapper<'a> {}
110 ///
111 /// impl<'a> Dummy<'a> for Wrapper<'a> {
112 /// fn dummy(allocator: &'a Allocator) -> Self {
113 /// Self(ArenaBox::new_in(0, &allocator))
114 /// }
115 /// }
116 ///
117 /// let allocator = Allocator::new();
118 /// let allocator = &allocator;
119 ///
120 /// let mut wrapper = Wrapper(ArenaBox::new_in(1, &allocator));
121 /// let mut copy: Option<Wrapper> = None;
122 ///
123 /// let _ = catch_unwind(AssertUnwindSafe(|| {
124 /// wrapper.replace_with(|old| {
125 /// // Move the copy out of the closure
126 /// copy = Some(old);
127 /// panic!("Unwind before write-back");
128 /// });
129 /// }));
130 ///
131 /// let mut boxed: ArenaBox<u32> = wrapper.0;
132 /// let mut copy: ArenaBox<u32> = copy.unwrap().0;
133 /// let boxed_mut: &mut u32 = boxed.as_mut();
134 /// let copy_mut: &mut u32 = copy.as_mut();
135 /// // Without the panic guard, `boxed` and `copy` would both point to same `u32`.
136 /// // We'd now have 2 `&mut u32`s pointing to same place. Aliasing violation!
137 /// *boxed_mut = 2;
138 /// *copy_mut = 3;
139 /// ```
140 ///
141 /// [`take_in`]: crate::TakeIn::take_in
142 //
143 // `#[inline]` so that compiler can elide reading fields of struct which are not used,
144 // rather than pulling whole struct onto the stack
145 #[inline]
146 fn replace_with(&mut self, replacer: impl FnOnce(Self) -> Self) {
147 let ptr = NonNull::from(self);
148
149 // SAFETY: `ptr` is derived from a `&mut Self`, so is valid for reads and writes, aligned,
150 // and points to an initialized `Self`. `ptr.read()` makes an owned bitwise copy of the node.
151 //
152 // This leaves a bitwise duplicate in `*ptr`, but it is never dropped or exposed as a value:
153 //
154 // * On success, `ptr.write(new)` below overwrites it (`write` does not drop the old contents -
155 // correct, as ownership moved into `old`, and thence into `new`).
156 // * On panic, `PanicGuard::drop` overwrites it with a fresh dummy (again without dropping it),
157 // before it can be accessed by any other code.
158 //
159 // So `*ptr` never retains a duplicate that could be observed alongside `old` (which would allow
160 // aliasing `&mut`s, double frees, etc), and no value is ever dropped twice.
161 // This holds for any `Self: Dummy` - `Drop` types included.
162 let old = unsafe { ptr.read() };
163
164 // Create a guard before calling `replacer`.
165 // If `replacer` unwinds, `guard`'s `Drop` writes a fresh dummy into `*ptr`,
166 // so the slot never keeps a bitwise duplicate of the value moved into `replacer`.
167 let guard = PanicGuard::<'a, Self> { ptr, marker: PhantomData };
168
169 let new = replacer(old);
170
171 // `replacer` returned normally. Disarm the guard - we write `new` ourselves below.
172 mem::forget(guard);
173
174 // Overwrite original value without dropping it.
175 // SAFETY: See above.
176 unsafe { ptr.write(new) };
177 }
178}
179
180// Blanket impls on wrapper types.
181//
182// `ReplaceWith` is not implemented on all types which implement `Dummy`, because there is no point
183// in using `replace_with` on `Copy` types - just copying these types is cheaper and simpler.
184//
185// Similarly, bound of `T: ReplaceWith` on `Option<T>` is to avoid implementing `ReplaceWith`
186// on `Option<T>` where `T: Copy`, and therefore `Option<T>` is `Copy` too.
187//
188// `Cell<T>` is not `Copy` even if `T` is, but `Cell::get` is available where `T: Copy`,
189// and is a better choice than `replace_with` in this case. So it's also bound on `T: ReplaceWith`.
190
191impl<'a, T: ReplaceWith<'a>> ReplaceWith<'a> for Option<T> {}
192
193impl<'a, T: Dummy<'a>> ReplaceWith<'a> for Box<'a, T> {}
194impl<'a, T> ReplaceWith<'a> for Box<'a, [T]> {}
195
196impl<'a, T> ReplaceWith<'a> for Vec<'a, T> {}
197
198impl<'a, T: ReplaceWith<'a>> ReplaceWith<'a> for Cell<T> {}
199
200/// Guard which restores a valid value to a slot if [`replace_with`]'s `replacer` panics.
201///
202/// `replace_with` reads the old node out of the slot with `NonNull::read`, leaving a bitwise duplicate behind,
203/// then calls `replacer`. If `replacer` panics, this guard's `Drop` overwrites that duplicate with a fresh dummy,
204/// so the slot cannot be observed holding a copy that aliases the value which was moved into `replacer`.
205/// On the success path the guard is `mem::forget`-ed, so it costs nothing.
206///
207/// [`replace_with`]: ReplaceWith::replace_with
208struct PanicGuard<'a, T: Dummy<'a>> {
209 ptr: NonNull<T>,
210 marker: PhantomData<&'a ()>,
211}
212
213impl<'a, T: Dummy<'a>> Drop for PanicGuard<'a, T> {
214 // A trivial forwarder to `write_dummy`, which is `#[inline(never)]` and does the real work.
215 //
216 // Keeping `drop` itself `#[inline]` lets it inline into the caller's unwind landing pad,
217 // where it reads `self.ptr` straight from a register and passes it *by value* to `write_dummy`.
218 // So the guard never has to be spilled to the stack - which it would be if `drop` were
219 // the out-of-line function, because then the landing pad would have to form `&guard`
220 // in memory to call it.
221 //
222 // `write_dummy` being `#[inline(never)]` still keeps the expensive work out of every `#[inline]`d
223 // `replace_with` call site's landing pad.
224 #[inline]
225 fn drop(&mut self) {
226 write_dummy(self.ptr);
227 }
228}
229
230/// Overwrite the bitwise duplicate left in `*ptr` (by `replace_with`) with a fresh dummy.
231///
232/// This is the cold panic-path body of `PanicGuard::drop`, factored out as a free function that takes
233/// `ptr` *by value* so it can be `#[inline(never)]` while `PanicGuard::drop` stays an inlinable
234/// forwarder (see the comment there for why that matters).
235#[cold]
236#[inline(never)]
237fn write_dummy<'a, T: Dummy<'a>>(ptr: NonNull<T>) {
238 // `replacer` panicked. Build a fresh dummy in its own dedicated `'static` allocator.
239 let allocator = fresh_dummy_allocator();
240 let dummy = T::dummy(allocator);
241
242 // Write the dummy into `*ptr`.
243 // SAFETY: `ptr` was derived from a `&mut Self` in `replace_with` and remains valid.
244 // `write` overwrites the leftover duplicate without dropping it - correct, as that value's
245 // ownership was moved into `replacer`.
246 unsafe { ptr.write(dummy) };
247}
248
249/// Storage for the [`Allocator`]s that dummies are created in on the panic path of [`replace_with`].
250///
251/// A dummy written into a node's slot on panic must be a valid value for `'a`,
252/// which means allocating it in an [`Allocator`] that lives for at least `'a`.
253///
254/// `replace_with` can't reuse the AST's own allocator, because that isn't available there,
255/// and it can't share a single global allocator, because the dummy may retain a handle to whatever allocator
256/// it was built in (e.g. `Vec` contains a reference to the `Allocator`, and reallocates through it on `push`).
257/// A shared allocator would then be mutated without synchronization from whichever thread owns the AST.
258///
259/// We also can't have 1 `Allocator` per thread (in a `thread_local!`) because they don't live for `'static` -
260/// they're dropped when the thread exits. Some code moves ASTs to other threads (using `self_cell`)
261/// so there's no guarantee the thread would live long enough, and the synchronization problem discussed above
262/// could also come into play.
263///
264/// So each dummy gets its *own* dedicated [`Allocator`]. These allocators must:
265///
266/// 1. live for `'static` (the dummy escapes into the AST, whose lifetime we can't bound here), and
267/// 2. have stable addresses (a `Vec` in the dummy holds an `&Allocator` pointing to one).
268///
269/// We get both by boxing each `Allocator` and keeping the boxes alive forever in this `static`.
270/// The `Box` gives a stable heap address, and `Vec` growth only moves the `Box`es themselves,
271/// not the *contents* of the `Box`es (the `Allocator`s).
272///
273/// This is only ever touched on the panic path - i.e. when there is a bug in a `replacer` closure.
274/// So the `Mutex` is effectively never contended.
275///
276/// If the panic is caught (with `catch_unwind`) and the process kept alive, this leaks memory,
277/// because `Allocator`s are added to the `Vec`, but never removed, never freed.
278/// But panics should not be happening at all (and if they do, that's a bug and we'll fix it),
279/// so this is not a problem in practice.
280///
281/// No memory is leaked unless there's a panic in a `replacer` closure.
282///
283/// [`replace_with`]: ReplaceWith::replace_with
284#[expect(clippy::vec_box)]
285static DUMMY_ALLOCATORS: Mutex<StdVec<StdBox<Allocator>>> = Mutex::new(StdVec::new());
286
287/// Get a fresh [`Allocator`], dedicated to a single dummy, which lives for `'static`.
288///
289/// See [`DUMMY_ALLOCATORS`] for why each dummy needs its own `'static` allocator.
290fn fresh_dummy_allocator() -> &'static Allocator {
291 // `unwrap` can never fire here. `fresh_dummy_allocator` is only ever called from `PanicGuard::drop`,
292 // i.e. while unwinding from a `replacer` panic.
293 // The one operation below that could panic - `push` on capacity overflow - would therefore panic
294 // during an existing unwind, which is a double panic that aborts the process immediately.
295 // So the mutex can never be observed poisoned - anything that could poison it aborts first.
296 // Capacity overflow is unreachable anyway - the `Vec`'s reallocation OOMs and aborts long before
297 // ~`isize::MAX` entries.
298 let mut allocators = DUMMY_ALLOCATORS.lock().unwrap();
299
300 // Create an `Allocator` and store it in a `Box` in `DUMMY_ALLOCATORS`.
301 // Get reference to the `Allocator` on the heap.
302 let allocator = &**allocators.push_mut(StdBox::new(Allocator::new()));
303
304 // Extend `&Allocator`'s lifetime to `'static`.
305 // SAFETY: The `Allocator` is owned by `DUMMY_ALLOCATORS`, a `static` from which allocators
306 // are never removed, so it lives for `'static`. Growing the `Vec` later would move the `Box`
307 // but never moves its *contents* (the `Allocator` itself), so this reference remains valid.
308 unsafe { NonNull::from(allocator).as_ref() }
309}
310
311#[cfg(test)]
312mod test {
313 use std::{
314 iter,
315 panic::{AssertUnwindSafe, catch_unwind},
316 };
317
318 use crate::{Allocator, Dummy, Vec};
319
320 use super::ReplaceWith;
321
322 #[test]
323 fn replace_with_wraps_old_value() {
324 let allocator = Allocator::default();
325 let allocator = &allocator;
326
327 let mut vec = Vec::from_iter_in([1u32, 2, 3], &allocator);
328 vec.replace_with(|old| {
329 // The closure receives the old value, not a dummy.
330 assert_eq!(&*old, &[1, 2, 3]);
331 // Build a new value out of the old one (prepend `0`).
332 Vec::from_iter_in(iter::once(0).chain(old), &allocator)
333 });
334 assert_eq!(&*vec, &[0, 1, 2, 3]);
335 }
336
337 #[test]
338 fn replace_with_extracts_part_of_old_value() {
339 let allocator = Allocator::default();
340 let allocator = &allocator;
341
342 let mut vec = Vec::from_iter_in([10u32, 20, 30], &allocator);
343 // Keep just the first element of the old value.
344 vec.replace_with(|old| {
345 let first = old.into_iter().next().unwrap();
346 Vec::from_iter_in([first], &allocator)
347 });
348 assert_eq!(&*vec, &[10]);
349 }
350
351 #[test]
352 fn replace_with_identity_leaves_value_unchanged() {
353 let allocator = Allocator::default();
354 let allocator = &allocator;
355
356 let mut vec = Vec::from_iter_in([7u32], &allocator);
357 vec.replace_with(|old| old);
358 assert_eq!(&*vec, &[7]);
359 }
360
361 #[test]
362 fn replace_with_writes_dummy_on_panic() {
363 let allocator = Allocator::default();
364 let allocator = &allocator;
365
366 let mut vec = Vec::from_iter_in([1u32, 2, 3], &allocator);
367 let result = catch_unwind(AssertUnwindSafe(|| {
368 vec.replace_with(|_old| panic!("boom"));
369 }));
370 assert!(result.is_err());
371
372 // The slot holds a fresh empty dummy - *not* a bitwise duplicate of the old value.
373 assert_eq!(&*vec, &[] as &[u32]);
374 // The dummy is fully usable: it has its own dedicated `'static` allocator, so it can grow.
375 vec.push(42);
376 assert_eq!(&*vec, &[42]);
377 }
378
379 /// A type holding a `&mut`. Duplicating a `&mut` is the classic way to make `replace_with` unsound.
380 /// This checks the panic guard prevents that - the guard replaces the slot with a dummy holding a *fresh* `&mut`,
381 /// so it never aliases the moved-out value.
382 struct RefHolder<'a>(&'a mut u64);
383
384 impl<'a> Dummy<'a> for RefHolder<'a> {
385 fn dummy(allocator: &'a Allocator) -> Self {
386 RefHolder(allocator.alloc(0u64))
387 }
388 }
389
390 impl<'a> ReplaceWith<'a> for RefHolder<'a> {}
391
392 #[test]
393 fn replace_with_mutating_through_moved_out_ref() {
394 let mut value = 10u64;
395 let mut holder = RefHolder(&mut value);
396
397 // Mutate through the moved-out reference, then put the same reference back.
398 holder.replace_with(|old| {
399 *old.0 += 1;
400 old
401 });
402 // The reference left in the slot is still valid and points at `value`.
403 *holder.0 += 100;
404
405 assert_eq!(value, 111);
406 }
407
408 #[test]
409 fn replace_with_swapping_in_a_different_ref() {
410 let mut a = 1u64;
411 let mut b = 2u64;
412
413 let mut holder = RefHolder(&mut a);
414 // Drop the old reference (to `a`) and store a reference to `b` instead.
415 holder.replace_with(|_old| RefHolder(&mut b));
416 *holder.0 += 40;
417
418 assert_eq!(a, 1);
419 assert_eq!(b, 42);
420 }
421}