mirror of
https://github.com/rust-lang/rust-analyzer.git
synced 2025-09-27 20:42:04 +00:00
internal: Add SyntaxFactory
to ease generating nodes with syntax mappings
This commit is contained in:
parent
af9a658864
commit
05b48e4005
5 changed files with 186 additions and 101 deletions
45
crates/syntax/src/ast/syntax_factory.rs
Normal file
45
crates/syntax/src/ast/syntax_factory.rs
Normal file
|
@ -0,0 +1,45 @@
|
|||
//! Builds upon [`crate::ast::make`] constructors to create ast fragments with
|
||||
//! optional syntax mappings.
|
||||
//!
|
||||
//! Instead of forcing make constructors to perform syntax mapping, we instead
|
||||
//! let [`SyntaxFactory`] handle constructing the mappings. Care must be taken
|
||||
//! to remember to feed the syntax mappings into a [`SyntaxEditor`](crate::syntax_editor::SyntaxEditor),
|
||||
//! if applicable.
|
||||
|
||||
mod constructors;
|
||||
|
||||
use std::cell::{RefCell, RefMut};
|
||||
|
||||
use crate::syntax_editor::SyntaxMapping;
|
||||
|
||||
pub struct SyntaxFactory {
|
||||
// Stored in a refcell so that the factory methods can be &self
|
||||
mappings: Option<RefCell<SyntaxMapping>>,
|
||||
}
|
||||
|
||||
impl SyntaxFactory {
|
||||
/// Creates a new [`SyntaxFactory`], generating mappings between input nodes and generated nodes.
|
||||
pub fn new() -> Self {
|
||||
Self { mappings: Some(RefCell::new(SyntaxMapping::new())) }
|
||||
}
|
||||
|
||||
/// Creates a [`SyntaxFactory`] without generating mappings.
|
||||
pub fn without_mappings() -> Self {
|
||||
Self { mappings: None }
|
||||
}
|
||||
|
||||
/// Gets all of the tracked syntax mappings, if any.
|
||||
pub fn finish_with_mappings(self) -> SyntaxMapping {
|
||||
self.mappings.unwrap_or_default().into_inner()
|
||||
}
|
||||
|
||||
fn mappings(&self) -> Option<RefMut<'_, SyntaxMapping>> {
|
||||
self.mappings.as_ref().map(|it| it.borrow_mut())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for SyntaxFactory {
|
||||
fn default() -> Self {
|
||||
Self::without_mappings()
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue