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