Skip to main content

syntax/syntax_editor/
mapping.rs

1//! Maps syntax elements through disjoint syntax nodes.
2//!
3//! [`SyntaxMappingBuilder`] should be used to create mappings to add to a `SyntaxEditor`
4
5use itertools::Itertools;
6use rustc_hash::FxHashMap;
7
8use crate::{SyntaxElement, SyntaxNode};
9
10use super::index_no_trivia;
11
12#[derive(Debug, Default)]
13pub struct SyntaxMapping {
14    // important information to keep track of:
15    // node -> node
16    // token -> token (implicit in mappings)
17    // input parent -> output parent (for deep lookups)
18
19    // mappings ->  parents
20    entry_parents: Vec<SyntaxNode>,
21    node_mappings: FxHashMap<SyntaxNode, MappingEntry>,
22}
23
24impl SyntaxMapping {
25    /// Like [`SyntaxMapping::upmap_child`] but for syntax elements.
26    pub(super) fn upmap_child_element(
27        &self,
28        child: &SyntaxElement,
29        input_ancestor: &SyntaxNode,
30        output_ancestor: &SyntaxNode,
31    ) -> Result<SyntaxElement, MissingMapping> {
32        match child {
33            SyntaxElement::Node(node) => {
34                self.upmap_child(node, input_ancestor, output_ancestor).map(SyntaxElement::Node)
35            }
36            SyntaxElement::Token(token) => {
37                let upmap_parent =
38                    self.upmap_child(&token.parent().unwrap(), input_ancestor, output_ancestor)?;
39
40                let element =
41                    upmap_parent.children_with_tokens().nth(index_no_trivia(child)).unwrap();
42                debug_assert!(
43                    element.as_token().is_some_and(|it| it.kind() == token.kind()),
44                    "token upmapping mapped to the wrong node ({token:?} -> {element:?})"
45                );
46
47                Ok(element)
48            }
49        }
50    }
51
52    /// Maps a child node of the input ancestor to the corresponding node in
53    /// the output ancestor.
54    pub(super) fn upmap_child(
55        &self,
56        child: &SyntaxNode,
57        input_ancestor: &SyntaxNode,
58        output_ancestor: &SyntaxNode,
59    ) -> Result<SyntaxNode, MissingMapping> {
60        debug_assert!(
61            child == input_ancestor
62                || child.ancestors().any(|ancestor| &ancestor == input_ancestor)
63        );
64
65        // Build a list mapping up to the first mappable ancestor
66        let to_first_upmap = if child != input_ancestor {
67            std::iter::successors(Some((child.index(), child.clone())), |(_, current)| {
68                let parent = current.parent().unwrap();
69
70                if &parent == input_ancestor {
71                    return None;
72                }
73
74                Some((parent.index(), parent))
75            })
76            .map(|(i, _)| i)
77            .collect::<Vec<_>>()
78        } else {
79            vec![]
80        };
81
82        // Progressively up-map the input ancestor until we get to the output ancestor
83        let to_output_ancestor = if input_ancestor != output_ancestor {
84            self.upmap_to_ancestor(input_ancestor, output_ancestor)?
85        } else {
86            vec![]
87        };
88
89        let to_map_down =
90            to_output_ancestor.into_iter().rev().chain(to_first_upmap.into_iter().rev());
91
92        let mut target = output_ancestor.clone();
93
94        for index in to_map_down {
95            target = target
96                .children_with_tokens()
97                .nth(index)
98                .and_then(|it| it.into_node())
99                .expect("equivalent ancestor node should be present in target tree");
100        }
101
102        debug_assert_eq!(child.kind(), target.kind());
103
104        Ok(target)
105    }
106
107    fn upmap_to_ancestor(
108        &self,
109        input_ancestor: &SyntaxNode,
110        output_ancestor: &SyntaxNode,
111    ) -> Result<Vec<usize>, MissingMapping> {
112        let mut current =
113            self.upmap_node_single(input_ancestor).unwrap_or_else(|| input_ancestor.clone());
114        let mut upmap_chain = vec![current.index()];
115
116        loop {
117            let Some(parent) = current.parent() else { break };
118
119            if &parent == output_ancestor {
120                return Ok(upmap_chain);
121            }
122
123            current = match self.upmap_node_single(&parent) {
124                Some(next) => next,
125                None => parent,
126            };
127            upmap_chain.push(current.index());
128        }
129
130        Err(MissingMapping(current))
131    }
132
133    pub(super) fn upmap_element(&self, input: &SyntaxElement) -> SyntaxElement {
134        let mut current = input.clone();
135
136        loop {
137            let node = match &current {
138                SyntaxElement::Node(node) => node.clone(),
139                SyntaxElement::Token(token) => token.parent().unwrap(),
140            };
141            let Some((input_ancestor, output_ancestor)) = node.ancestors().find_map(|ancestor| {
142                self.upmap_node_single(&ancestor).map(|output_ancestor| (ancestor, output_ancestor))
143            }) else {
144                return current;
145            };
146            current = self
147                .upmap_child_element(&current, &input_ancestor, &output_ancestor.parent().unwrap())
148                .expect("the nearest mapped ancestor must map its descendants");
149        }
150    }
151
152    pub fn merge(&mut self, mut other: SyntaxMapping) {
153        // Remap other's entry parents to be after the current list of entry parents
154        let remap_base: u32 = self.entry_parents.len().try_into().unwrap();
155
156        self.entry_parents.append(&mut other.entry_parents);
157        self.node_mappings.extend(other.node_mappings.into_iter().map(|(node, entry)| {
158            (node, MappingEntry { parent: entry.parent + remap_base, ..entry })
159        }));
160    }
161
162    /// Follows the input one step along the syntax mapping tree
163    fn upmap_node_single(&self, input: &SyntaxNode) -> Option<SyntaxNode> {
164        let MappingEntry { parent, child_slot } = self.node_mappings.get(input)?;
165
166        let output = self.entry_parents[*parent as usize]
167            .children_with_tokens()
168            .nth(*child_slot as usize)
169            .and_then(SyntaxElement::into_node)
170            .unwrap();
171
172        debug_assert_eq!(input.kind(), output.kind());
173        Some(output)
174    }
175
176    pub fn add_mapping(&mut self, syntax_mapping: SyntaxMappingBuilder) {
177        let SyntaxMappingBuilder { parent_node, node_mappings } = syntax_mapping;
178
179        let parent_entry: u32 = self.entry_parents.len().try_into().unwrap();
180        self.entry_parents.push(parent_node);
181
182        let node_entries = node_mappings
183            .into_iter()
184            .map(|(node, slot)| (node, MappingEntry { parent: parent_entry, child_slot: slot }));
185
186        self.node_mappings.extend(node_entries);
187    }
188}
189
190#[derive(Debug)]
191pub struct SyntaxMappingBuilder {
192    parent_node: SyntaxNode,
193    node_mappings: Vec<(SyntaxNode, u32)>,
194}
195
196impl SyntaxMappingBuilder {
197    pub fn new(parent_node: SyntaxNode) -> Self {
198        Self { parent_node, node_mappings: vec![] }
199    }
200
201    pub fn map_node(&mut self, input: SyntaxNode, output: SyntaxNode) {
202        debug_assert_eq!(output.parent().as_ref(), Some(&self.parent_node));
203        self.node_mappings.push((input, output.index() as u32));
204    }
205
206    pub fn map_children(
207        &mut self,
208        input: impl IntoIterator<Item = SyntaxNode>,
209        output: impl IntoIterator<Item = SyntaxNode>,
210    ) {
211        for pairs in input.into_iter().zip_longest(output) {
212            let (input, output) = match pairs {
213                itertools::EitherOrBoth::Both(l, r) => (l, r),
214                itertools::EitherOrBoth::Left(_) => {
215                    unreachable!("mapping more input nodes than there are output nodes")
216                }
217                itertools::EitherOrBoth::Right(_) => break,
218            };
219
220            self.map_node(input, output);
221        }
222    }
223
224    pub fn finish(self, mappings: &mut SyntaxMapping) {
225        mappings.add_mapping(self);
226    }
227}
228
229#[derive(Debug)]
230pub(super) struct MissingMapping(pub SyntaxNode);
231
232#[derive(Debug, Clone, Copy)]
233struct MappingEntry {
234    parent: u32,
235    child_slot: u32,
236}