syntax/ast/syntax_factory.rs
1//! Builds upon [`crate::ast::make`] constructors to create ast fragments with
2//! optional syntax mappings.
3//!
4//! Instead of forcing make constructors to perform syntax mapping, we instead
5//! let [`SyntaxFactory`] handle constructing the mappings. Care must be taken
6//! to remember to feed the syntax mappings into a [`SyntaxEditor`](crate::syntax_editor::SyntaxEditor),
7//! if applicable.
8
9mod constructors;
10
11use std::cell::{RefCell, RefMut};
12
13use crate::syntax_editor::SyntaxMapping;
14
15pub struct SyntaxFactory {
16 // Stored in a refcell so that the factory methods can be &self
17 mappings: Option<RefCell<SyntaxMapping>>,
18}
19
20impl SyntaxFactory {
21 /// Creates a new [`SyntaxFactory`], generating mappings between input nodes and generated nodes.
22 pub fn with_mappings() -> Self {
23 Self { mappings: Some(RefCell::new(SyntaxMapping::default())) }
24 }
25
26 /// Creates a [`SyntaxFactory`] without generating mappings.
27 pub fn without_mappings() -> Self {
28 Self { mappings: None }
29 }
30
31 /// Gets all of the tracked syntax mappings, if any.
32 pub fn finish_with_mappings(self) -> SyntaxMapping {
33 self.mappings.unwrap_or_default().into_inner()
34 }
35
36 /// Take all of the tracked syntax mappings, leaving `SyntaxMapping::default()` in its place, if any.
37 pub fn take(&self) -> SyntaxMapping {
38 self.mappings.as_ref().map(|mappings| mappings.take()).unwrap_or_default()
39 }
40
41 pub(crate) fn mappings(&self) -> Option<RefMut<'_, SyntaxMapping>> {
42 self.mappings.as_ref().map(|it| it.borrow_mut())
43 }
44}
45
46impl Default for SyntaxFactory {
47 fn default() -> Self {
48 Self::without_mappings()
49 }
50}