Skip to main content

vvv_engine/capabilities/moves/
extraction.rs

1//! The text a declaration takes with it when it moves.
2
3use std::collections::BTreeSet;
4
5use vvv_core::{Edit, Facts, RelPath, Span, Symbol, SymbolKind};
6
7use crate::SourceFile;
8
9/// Invalid declaration extents or edits in the text selected for a move.
10#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
11pub enum ExtractionError {
12    #[error("{}: invalid source span {span:?}", path.display())]
13    InvalidSpan { path: RelPath, span: Span },
14    #[error("{}: declaration pieces overlap: {first:?} and {second:?}", path.display())]
15    OverlappingPieces {
16        path: RelPath,
17        first: Span,
18        second: Span,
19    },
20    #[error("{}: edit {span:?} is outside the moved pieces", path.display())]
21    OutsidePieces { path: RelPath, span: Span },
22    #[error("{}: moving edits overlap: {first:?} and {second:?}", path.display())]
23    OverlappingEdits {
24        path: RelPath,
25        first: Span,
26        second: Span,
27    },
28}
29
30/// A declaration and its pieces — in Rust, the `impl` blocks for it — as
31/// spans of the file it leaves. Knows what is inside the moved text, what
32/// names it uses, how to cut it out and how to paste it elsewhere.
33pub(crate) struct Extraction<'a> {
34    pub symbol: &'a Symbol,
35    /// The symbol's own extent and its companions, in source order.
36    pieces: Vec<&'a Symbol>,
37    source: &'a SourceFile,
38}
39
40impl<'a> Extraction<'a> {
41    /// Construct from the selected declaration and explicit owned pieces.
42    pub fn of(
43        source: &'a SourceFile,
44        symbol: &'a Symbol,
45        pieces: impl IntoIterator<Item = &'a Symbol>,
46    ) -> Result<Self, ExtractionError> {
47        let mut pieces: Vec<_> = pieces.into_iter().collect();
48        pieces.sort_by_key(|piece| piece.extent);
49        pieces.dedup_by_key(|piece| piece.extent);
50        let extraction = Self {
51            symbol,
52            pieces,
53            source,
54        };
55        for piece in &extraction.pieces {
56            extraction.validate_span(piece.extent)?;
57        }
58        for pair in extraction.pieces.windows(2) {
59            if pair[0].extent.overlaps(&pair[1].extent) {
60                return Err(ExtractionError::OverlappingPieces {
61                    path: source.path().into(),
62                    first: pair[0].extent,
63                    second: pair[1].extent,
64                });
65            }
66        }
67        Ok(extraction)
68    }
69
70    /// Whether `span` lies inside the moved text.
71    pub fn contains(&self, span: Span) -> bool {
72        self.pieces
73            .iter()
74            .any(|p| p.extent.start <= span.start && span.end <= p.extent.end)
75    }
76
77    /// Bare same-named declarations in other lexical scopes do not use this binding.
78    pub fn shadowed(
79        &self,
80        facts: &Facts,
81        span: Span,
82        is_addressable: impl Fn(SymbolKind) -> bool,
83    ) -> bool {
84        facts
85            .symbols
86            .iter()
87            .filter(|symbol| {
88                symbol.name == self.symbol.name
89                    && symbol.span != self.symbol.span
90                    && is_addressable(symbol.kind)
91            })
92            .any(|symbol| {
93                facts.declaration_pieces.iter().any(|pieces| {
94                    pieces.declaration == symbol.span
95                        && !pieces.top_level
96                        && pieces.scope.contains(&span)
97                })
98            })
99    }
100
101    /// Distinct identifier texts inside the moved text: what it may need
102    /// imported where it lands.
103    pub fn names_used(&self, facts: &Facts) -> BTreeSet<String> {
104        facts
105            .tokens()
106            .filter(|(_, _, span)| self.contains(*span))
107            .map(|(name, _, _)| name.to_owned())
108            .collect()
109    }
110
111    /// The spans to delete from the old file: each piece's extent plus the
112    /// newline that ends it, and one blank line after it when there is one,
113    /// so the gap closes cleanly.
114    pub fn cuts(&self) -> impl Iterator<Item = Span> + '_ {
115        self.pieces.iter().enumerate().map(|(i, piece)| {
116            let mut end = piece.extent.end;
117            if self.source.text()[end..].starts_with('\n') {
118                end += 1;
119                if self.source.text()[end..].starts_with('\n') {
120                    end += 1;
121                }
122            }
123            if let Some(next) = self.pieces.get(i + 1) {
124                end = end.min(next.extent.start);
125            }
126            Span::new(piece.extent.start, end)
127        })
128    }
129
130    /// The moved text with `edits` (in the old file's coordinates, all inside
131    /// the pieces) applied, pieces joined by a blank line.
132    pub fn assemble(&self, edits: &[Edit]) -> Result<String, ExtractionError> {
133        let mut assigned = vec![Vec::<&Edit>::new(); self.pieces.len()];
134        for edit in edits {
135            self.validate_span(edit.span)?;
136            // At a shared boundary an insertion belongs to the following piece.
137            let owner = self
138                .pieces
139                .iter()
140                .position(|p| p.extent.start == edit.span.start && p.extent.contains(&edit.span))
141                .or_else(|| {
142                    self.pieces
143                        .iter()
144                        .position(|p| p.extent.contains(&edit.span))
145                });
146            let Some(owner) = owner else {
147                return Err(ExtractionError::OutsidePieces {
148                    path: self.source.path().into(),
149                    span: edit.span,
150                });
151            };
152            for previous in &assigned[owner] {
153                if previous.span.overlaps(&edit.span) {
154                    return Err(ExtractionError::OverlappingEdits {
155                        path: self.source.path().into(),
156                        first: previous.span,
157                        second: edit.span,
158                    });
159                }
160            }
161            assigned[owner].push(edit);
162        }
163        let mut out = String::new();
164        for (i, (piece, inside)) in self.pieces.iter().zip(&mut assigned).enumerate() {
165            if i > 0 {
166                out.push_str("\n\n");
167            }
168            // Stable order preserves coincident insertions, before a replacement
169            // beginning at the same byte. End-boundary insertions follow it.
170            inside.sort_by_key(|e| (e.span.start, !e.span.is_empty()));
171            let mut cursor = piece.extent.start;
172            for edit in inside {
173                out.push_str(&self.source.text()[cursor..edit.span.start]);
174                out.push_str(&edit.replacement);
175                cursor = edit.span.end;
176            }
177            out.push_str(&self.source.text()[cursor..piece.extent.end]);
178        }
179        Ok(out)
180    }
181
182    fn validate_span(&self, span: Span) -> Result<(), ExtractionError> {
183        let text = self.source.text();
184        if span.start > span.end
185            || span.end > text.len()
186            || !text.is_char_boundary(span.start)
187            || !text.is_char_boundary(span.end)
188        {
189            return Err(ExtractionError::InvalidSpan {
190                path: self.source.path().into(),
191                span,
192            });
193        }
194        Ok(())
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201
202    struct Fixture {
203        source: SourceFile,
204        facts: Facts,
205    }
206
207    impl Fixture {
208        fn new(text: &str, extents: &[Span]) -> Self {
209            Self {
210                source: SourceFile::new("source.fake", text),
211                facts: Facts::new(
212                    extents
213                        .iter()
214                        .map(|&span| Symbol::plain(SymbolKind::Function, "f", span, span))
215                        .collect(),
216                    vec![],
217                    vec![],
218                ),
219            }
220        }
221
222        fn extraction(&self) -> Result<Extraction<'_>, ExtractionError> {
223            Extraction::of(
224                &self.source,
225                &self.facts.symbols[0],
226                self.facts.symbols.iter(),
227            )
228        }
229    }
230
231    #[test]
232    fn moving_edits_must_not_overlap() {
233        let fixture = Fixture::new("abcdef", &[Span::new(0, 6)]);
234        let result = fixture.extraction().unwrap().assemble(&[
235            Edit::replace(Span::new(1, 4), "x"),
236            Edit::replace(Span::new(3, 5), "y"),
237        ]);
238        assert!(
239            matches!(result, Err(ExtractionError::OverlappingEdits { first, second, .. })
240            if first == Span::new(1, 4) && second == Span::new(3, 5))
241        );
242    }
243
244    #[test]
245    fn every_moving_edit_belongs_to_a_piece() {
246        let fixture = Fixture::new("abcdef", &[Span::new(0, 2), Span::new(4, 6)]);
247        assert!(matches!(
248            fixture
249                .extraction()
250                .unwrap()
251                .assemble(&[Edit::replace(Span::new(1, 5), "x")]),
252            Err(ExtractionError::OutsidePieces { .. })
253        ));
254    }
255
256    #[test]
257    fn extents_and_edits_are_valid_source_ranges() {
258        for span in [Span { start: 3, end: 1 }, Span::new(0, 8), Span::new(1, 2)] {
259            let fixture = Fixture::new("éabc", &[span]);
260            assert!(
261                matches!(fixture.extraction(), Err(ExtractionError::InvalidSpan { span: invalid, .. }) if invalid == span)
262            );
263            let fixture = Fixture::new("éabc", &[Span::new(0, 5)]);
264            assert!(
265                matches!(fixture.extraction().unwrap().assemble(&[Edit::replace(span, "x")]),
266                Err(ExtractionError::InvalidSpan { span: invalid, .. }) if invalid == span)
267            );
268        }
269    }
270
271    #[test]
272    fn distinct_piece_extents_must_not_overlap() {
273        let fixture = Fixture::new("abcdef", &[Span::new(0, 3), Span::new(0, 5)]);
274        assert!(matches!(
275            fixture.extraction(),
276            Err(ExtractionError::OverlappingPieces { .. })
277        ));
278        let fixture = Fixture::new("abcdef", &[Span::new(0, 3), Span::new(2, 5)]);
279        assert!(matches!(
280            fixture.extraction(),
281            Err(ExtractionError::OverlappingPieces { .. })
282        ));
283    }
284
285    #[test]
286    fn identical_pieces_are_extracted_once() {
287        let fixture = Fixture::new(
288            "abcdef",
289            &[Span::new(0, 3), Span::new(0, 3), Span::new(4, 6)],
290        );
291        assert_eq!(
292            fixture.extraction().unwrap().assemble(&[]).unwrap(),
293            "abc\n\nef"
294        );
295    }
296
297    #[test]
298    fn boundary_and_coincident_insertions_keep_their_order() {
299        let fixture = Fixture::new("abcdef", &[Span::new(0, 6)]);
300        let edits = [
301            Edit::replace(Span::new(1, 3), "X"),
302            Edit::insert(1, "A"),
303            Edit::insert(1, "B"),
304            Edit::insert(3, "C"),
305        ];
306        assert_eq!(
307            fixture.extraction().unwrap().assemble(&edits).unwrap(),
308            "aABXCdef"
309        );
310    }
311
312    #[test]
313    fn a_shared_boundary_insertion_is_applied_once() {
314        let fixture = Fixture::new("abcd", &[Span::new(0, 2), Span::new(2, 4)]);
315        assert_eq!(
316            fixture
317                .extraction()
318                .unwrap()
319                .assemble(&[Edit::insert(2, "X")])
320                .unwrap(),
321            "ab\n\nXcd"
322        );
323    }
324
325    #[test]
326    fn edits_in_multiple_pieces_keep_source_coordinates() {
327        let fixture = Fixture::new("abc---def", &[Span::new(0, 3), Span::new(6, 9)]);
328        assert_eq!(
329            fixture
330                .extraction()
331                .unwrap()
332                .assemble(&[
333                    Edit::replace(Span::new(1, 2), "B"),
334                    Edit::replace(Span::new(7, 8), "E")
335                ])
336                .unwrap(),
337            "aBc\n\ndEf"
338        );
339    }
340}