Skip to main content

dprint_core/formatting/
arena.rs

1use std::sync::Arc;
2use std::sync::Mutex;
3
4use super::Condition;
5use super::ConditionResolver;
6use super::ConditionResolverContext;
7use super::PrintNodeCell;
8use super::SavePoint;
9use super::StringContainer;
10use super::WriteItem;
11use super::collections::GraphNode;
12use super::collections::LookAheadSavePointsNode;
13use super::collections::NodeStackNode;
14use super::thread_state;
15use super::thread_state::Counts;
16
17/// The memory that print items, and the printer's state when printing them, are allocated in.
18///
19/// Everything allocated in an arena lives as long as the arena is borrowed, so the
20/// compiler ensures print items aren't used after the arena is dropped. Since the
21/// arena is created by the caller, the print items can also borrow data that outlives
22/// it, such as the text of the file being formatted.
23///
24/// ```ignore
25/// let arena = Arena::new();
26/// let print_items = generate(&arena, &file);
27/// let text = print(print_items, options);
28/// ```
29///
30/// An arena should be created for each file that's formatted, and arenas should be
31/// dropped in the reverse order they're created in (ex. when formatting within a format).
32///
33/// The memory of an arena is freed when it's dropped. To reuse it for the next file
34/// instead, create the arenas from an [`ArenaPool`].
35///
36/// Print items can't be used after their arena is dropped:
37///
38/// ```compile_fail
39/// use dprint_core::formatting::Arena;
40/// use dprint_core::formatting::PrintItems;
41///
42/// let print_items = {
43///   let arena = Arena::new();
44///   PrintItems::new(&arena)
45/// };
46/// ```
47pub struct Arena {
48  bump: bumpalo::Bump,
49  /// The counts of the infos and conditions created before this arena, which are
50  /// restored when it's dropped.
51  outer_counts: Counts,
52  /// The pool the memory is returned to when the arena is dropped.
53  pool: Option<ArenaPool>,
54}
55
56impl Default for Arena {
57  fn default() -> Self {
58    Self::new()
59  }
60}
61
62impl Drop for Arena {
63  fn drop(&mut self) {
64    if let Some(pool) = self.pool.take() {
65      let mut bump = std::mem::take(&mut self.bump);
66      bump.reset();
67      pool.lock_bumps().push(bump);
68    }
69    thread_state::set_counts(std::mem::take(&mut self.outer_counts));
70  }
71}
72
73impl Arena {
74  /// Creates an arena whose memory is freed when it's dropped.
75  ///
76  /// This also starts the identifiers of the infos and conditions created while it's alive
77  /// from zero, which keeps the printer's storage of them small.
78  pub fn new() -> Self {
79    Self::new_internal(bumpalo::Bump::new(), None)
80  }
81
82  fn new_internal(bump: bumpalo::Bump, pool: Option<ArenaPool>) -> Self {
83    Self {
84      bump,
85      outer_counts: thread_state::take_counts(),
86      pool,
87    }
88  }
89
90  /// Gets the bump allocator, which can be used to allocate other values that
91  /// should live as long as the print items.
92  ///
93  /// Note that values allocated in it don't have their destructors run.
94  pub fn bump(&self) -> &bumpalo::Bump {
95    &self.bump
96  }
97
98  /// Allocates a condition resolver in the arena.
99  ///
100  /// The resolver needs to be `Copy` because the arena doesn't run the destructors of
101  /// what's allocated in it. For a resolver that needs state, allocate the state in the
102  /// arena and capture a reference to it (ex. `arena.bump().alloc(Cell::new(false))`),
103  /// using bumpalo's collections for state that allocates.
104  ///
105  /// ```compile_fail
106  /// use dprint_core::formatting::Arena;
107  ///
108  /// let arena = Arena::new();
109  /// let text = String::from("text");
110  /// // a `String` isn't `Copy`, so this would never be dropped
111  /// arena.alloc_resolver(move |_| Some(text.is_empty()));
112  /// ```
113  pub fn alloc_resolver<'a>(&'a self, resolver: impl Fn(&mut ConditionResolverContext) -> Option<bool> + Copy + 'a) -> ConditionResolver<'a> {
114    self.bump.alloc(resolver)
115  }
116
117  pub(super) fn alloc_condition<'a>(&'a self, condition: Condition<'a>) -> &'a Condition<'a> {
118    self.bump.alloc(condition)
119  }
120
121  /// Copies the text into the arena.
122  pub(super) fn alloc_str<'a>(&'a self, text: &str) -> &'a StringContainer<'a> {
123    let text = self.bump.alloc_str(text);
124    self.alloc_string_container(text)
125  }
126
127  pub(super) fn alloc_string_container<'a>(&'a self, text: &'a str) -> &'a StringContainer<'a> {
128    self.bump.alloc(StringContainer::new(text))
129  }
130
131  pub(super) fn alloc_print_node_cell<'a>(&'a self, cell: PrintNodeCell<'a>) -> &'a PrintNodeCell<'a> {
132    self.bump.alloc(cell)
133  }
134
135  pub(super) fn alloc_write_item_graph_node<'a>(&'a self, node: GraphNode<'a, WriteItem<'a>>) -> &'a GraphNode<'a, WriteItem<'a>> {
136    self.bump.alloc(node)
137  }
138
139  pub(super) fn alloc_node_stack_node<'a>(&'a self, node: NodeStackNode<'a>) -> &'a NodeStackNode<'a> {
140    self.bump.alloc(node)
141  }
142
143  pub(super) fn alloc_save_point<'a>(&'a self, save_point: SavePoint<'a>) -> &'a SavePoint<'a> {
144    self.bump.alloc(save_point)
145  }
146
147  pub(super) fn alloc_look_ahead_save_points_node<'a>(&'a self, node: LookAheadSavePointsNode<'a>) -> &'a LookAheadSavePointsNode<'a> {
148    self.bump.alloc(node)
149  }
150}
151
152/// Keeps the memory of dropped arenas so the arenas created after them can reuse it,
153/// instead of allocating it again for each file that's formatted.
154///
155/// The memory is kept until it's cleared or the pool is dropped, so store the pool
156/// for as long as it's useful to reuse the memory (ex. in a plugin's state). Each
157/// arena's memory keeps the largest chunk it needed, so the pool holds about as much
158/// as the largest files that were formatted at the same time.
159///
160/// ```ignore
161/// let arena = self.arena_pool.create_arena();
162/// let print_items = generate(&arena, &file);
163/// let text = print(print_items, options);
164/// ```
165///
166/// Wasm plugins are given a pool in the format request (`request.arena_pool`).
167///
168/// Cloning the pool is cheap and the clones share the same memory.
169#[derive(Clone, Default)]
170pub struct ArenaPool {
171  bumps: Arc<Mutex<Vec<bumpalo::Bump>>>,
172}
173
174impl ArenaPool {
175  pub fn new() -> Self {
176    Self::default()
177  }
178
179  /// Creates an arena that reuses memory from the pool when there is some, and
180  /// returns its memory to the pool when it's dropped.
181  pub fn create_arena(&self) -> Arena {
182    let bump = self.lock_bumps().pop().unwrap_or_default();
183    Arena::new_internal(bump, Some(self.clone()))
184  }
185
186  /// Frees the memory kept by the pool.
187  ///
188  /// The memory of arenas from the pool that are still alive is kept when they're dropped.
189  pub fn clear(&self) {
190    self.lock_bumps().clear();
191  }
192
193  fn lock_bumps(&self) -> std::sync::MutexGuard<'_, Vec<bumpalo::Bump>> {
194    // the bumps are still usable if a thread panicked while holding the lock
195    self.bumps.lock().unwrap_or_else(|err| err.into_inner())
196  }
197}
198
199#[cfg(test)]
200mod test {
201  use super::*;
202
203  #[test]
204  fn should_reuse_the_memory_of_arenas_from_the_pool() {
205    let pool = ArenaPool::new();
206    {
207      let arena = pool.create_arena();
208      arena.bump().alloc_slice_fill_copy(10_000, 0u8);
209    }
210    assert_eq!(pool.lock_bumps().len(), 1);
211    {
212      let arena = pool.create_arena();
213      assert_eq!(pool.lock_bumps().len(), 0);
214      assert!(arena.bump().allocated_bytes() >= 10_000);
215    }
216    assert_eq!(pool.lock_bumps().len(), 1);
217  }
218
219  #[test]
220  fn should_keep_the_memory_of_arenas_alive_at_the_same_time() {
221    let pool = ArenaPool::new();
222    {
223      let _outer = pool.create_arena();
224      let _inner = pool.create_arena();
225    }
226    assert_eq!(pool.lock_bumps().len(), 2);
227  }
228
229  #[test]
230  fn should_free_the_memory_when_cleared() {
231    let pool = ArenaPool::new();
232    drop(pool.create_arena());
233    assert_eq!(pool.lock_bumps().len(), 1);
234    pool.clear();
235    assert_eq!(pool.lock_bumps().len(), 0);
236  }
237
238  #[test]
239  fn should_not_keep_the_memory_of_arenas_without_a_pool() {
240    let pool = ArenaPool::new();
241    drop(Arena::new());
242    assert_eq!(pool.lock_bumps().len(), 0);
243  }
244
245  #[test]
246  fn should_be_able_to_share_the_pool_between_threads() {
247    fn assert_send_sync<T: Send + Sync>() {}
248    assert_send_sync::<ArenaPool>();
249  }
250}