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
15#[derive(Debug)]
16pub struct SyntaxFactory {
17 // Stored in a refcell so that the factory methods can be &self
18 mappings: Option<RefCell<SyntaxMapping>>,
19}
20
21impl SyntaxFactory {
22 /// Creates a new [`SyntaxFactory`], generating mappings between input nodes and generated nodes.
23 pub(crate) fn with_mappings() -> Self {
24 Self { mappings: Some(RefCell::new(SyntaxMapping::default())) }
25 }
26
27 /// Creates a [`SyntaxFactory`] without generating mappings.
28 pub fn without_mappings() -> Self {
29 Self { mappings: None }
30 }
31
32 /// Take all of the tracked syntax mappings, leaving `SyntaxMapping::default()` in its place, if any.
33 pub(crate) fn take(&self) -> SyntaxMapping {
34 self.mappings.as_ref().map(|mappings| mappings.take()).unwrap_or_default()
35 }
36
37 pub(crate) fn mappings(&self) -> Option<RefMut<'_, SyntaxMapping>> {
38 self.mappings.as_ref().map(|it| it.borrow_mut())
39 }
40}
41
42impl Default for SyntaxFactory {
43 fn default() -> Self {
44 Self::without_mappings()
45 }
46}