Skip to content

Visual Studio Code, rebuilt in Rust

Rust
11.6 KB
Raw Blame
use super::*;

fn length_of_string(text: &str) -> Length {
    let lines = text.matches('\n').count();
    Length::new(lines, text.rsplit('\n').next().expect("split yields a part").chars().count())
}

fn edit(start: (usize, usize), end: (usize, usize), text: &str) -> (TextEditInfo, String) {
    (TextEditInfo { start: Length::new(start.0, start.1), end: Length::new(end.0, end.1), new_length: length_of_string(text) }, text.to_string())
}

/// `applyLineColumnEdits` over chars.
fn apply(text: &str, edits: &[(TextEditInfo, String)]) -> String {
    let mut chars: Vec<char> = text.chars().collect();
    let mut line_starts = vec![0];
    for (index, c) in chars.iter().enumerate() {
        if *c == '\n' {
            line_starts.push(index + 1);
        }
    }
    let offset = |at: Length| line_starts[at.lines] + at.columns;
    let mut edits: Vec<_> = edits.iter().map(|(edit, text)| (offset(edit.start), offset(edit.end), text)).collect();
    edits.sort_by_key(|&(start, ..)| std::cmp::Reverse(start));
    for (start, end, text) in edits {
        chars.splice(start..end, text.chars());
    }
    chars.into_iter().collect()
}

/// beforeEditPositionMapper.test.ts `compute`: each new line, then the old line and column of each position in it,
/// then the line and column count to the next change.
fn compute(input: &[&str], edits: &[(TextEditInfo, String)]) -> Vec<String> {
    let new_text = apply(&input.join("\n"), edits);
    let infos: Vec<_> = edits.iter().map(|(edit, _)| *edit).collect();
    let mut mapper = BeforeEditPositionMapper::new(&infos);
    let pad = |text: String| format!("{text:<3}");
    let mut result = Vec::new();
    for (line_index, line) in new_text.split('\n').enumerate() {
        let chars: Vec<char> = line.chars().collect();
        let mut rows = [String::new(), String::new(), String::new(), String::new(), String::new()];
        for column in 0..=chars.len() {
            let before = mapper.offset_before_change(Length::new(line_index, column));
            if column < chars.len() {
                rows[0] += &pad(chars[column].to_string());
            }
            rows[1] += &pad(before.lines.to_string());
            rows[2] += &pad(before.columns.to_string());
            let distance = mapper.distance_to_next_change(Length::new(line_index, column));
            rows[3] += &pad(distance.map_or("∞".into(), |distance| distance.lines.to_string()));
            rows[4] += &pad(distance.map_or("∞".into(), |distance| distance.columns.to_string()));
        }
        result.extend(rows);
    }
    result
}

#[test]
fn single_line_1() {
    assert_eq!(
        compute(&["0123456789"], &[edit((0, 4), (0, 7), "xy")]),
        ["0  1  2  3  x  y  7  8  9  ", "0  0  0  0  0  0  0  0  0  0  ", "0  1  2  3  4  5  7  8  9  10 ", "0  0  0  0  0  0  ∞  ∞  ∞  ∞  ", "4  3  2  1  0  0  ∞  ∞  ∞  ∞  "]
    );
}

#[test]
fn single_line_2() {
    assert_eq!(
        compute(&["0123456789"], &[edit((0, 2), (0, 4), "xxxx"), edit((0, 6), (0, 6), "yy")]),
        [
            "0  1  x  x  x  x  4  5  y  y  6  7  8  9  ",
            "0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  ",
            "0  1  2  3  4  5  4  5  6  7  6  7  8  9  10 ",
            "0  0  0  0  0  0  0  0  0  0  ∞  ∞  ∞  ∞  ∞  ",
            "2  1  0  0  0  0  2  1  0  0  ∞  ∞  ∞  ∞  ∞  ",
        ]
    );
}

const UNTOUCHED_SUPERSCRIPTS: [&str; 5] = ["⁰  ¹  ²  ³  ⁴  ⁵  ⁶  ⁷  ⁸  ⁹  ", "2  2  2  2  2  2  2  2  2  2  2  ", "0  1  2  3  4  5  6  7  8  9  10 ", "∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ", "∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞  "];

#[test]
fn multi_line_replace_1() {
    let mut expected = vec![
        "₀  ₁  ₂  x  y  3  4  5  6  7  8  9  ",
        "0  0  0  0  0  1  1  1  1  1  1  1  1  ",
        "0  1  2  3  4  3  4  5  6  7  8  9  10 ",
        "0  0  0  0  0  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ",
        "3  2  1  0  0  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ",
    ];
    expected.extend(UNTOUCHED_SUPERSCRIPTS);
    assert_eq!(compute(&["₀₁₂₃₄₅₆₇₈₉", "0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹"], &[edit((0, 3), (1, 3), "xy")]), expected);
}

#[test]
fn multi_line_replace_2() {
    let mut expected = vec![
        "₀  ₁  ₂  a  b  0  1  2  3  4  c  7  8  ",
        "0  0  0  0  0  1  1  1  1  1  1  1  1  1  ",
        "0  1  2  3  4  0  1  2  3  4  5  7  8  9  ",
        "0  0  0  0  0  0  0  0  0  0  0  ∞  ∞  ∞  ",
        "3  2  1  0  0  5  4  3  2  1  0  ∞  ∞  ∞  ",
    ];
    expected.extend(UNTOUCHED_SUPERSCRIPTS);
    assert_eq!(compute(&["₀₁₂₃₄₅₆₇₈₉", "012345678", "⁰¹²³⁴⁵⁶⁷⁸⁹"], &[edit((0, 3), (1, 0), "ab"), edit((1, 5), (1, 7), "c")]), expected);
}

#[test]
fn multi_line_replace_3() {
    assert_eq!(
        compute(&["₀₁₂₃₄₅₆₇₈₉", "012345678", "⁰¹²³⁴⁵⁶⁷⁸⁹"], &[edit((0, 3), (1, 0), "ab"), edit((1, 5), (1, 7), "c"), edit((1, 8), (2, 4), "d")]),
        [
            "₀  ₁  ₂  a  b  0  1  2  3  4  c  7  d  ⁴  ⁵  ⁶  ⁷  ⁸  ⁹  ",
            "0  0  0  0  0  1  1  1  1  1  1  1  1  2  2  2  2  2  2  2  ",
            "0  1  2  3  4  0  1  2  3  4  5  7  8  4  5  6  7  8  9  10 ",
            "0  0  0  0  0  0  0  0  0  0  0  0  0  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ",
            "3  2  1  0  0  5  4  3  2  1  0  1  0  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ",
        ]
    );
}

#[test]
fn multi_line_insert_1() {
    assert_eq!(
        compute(&["012345678"], &[edit((0, 3), (0, 5), "a\nb")]),
        ["0  1  2  a  ", "0  0  0  0  0  ", "0  1  2  3  4  ", "0  0  0  0  0  ", "3  2  1  0  0  ", "b  5  6  7  8  ", "1  0  0  0  0  0  ", "0  5  6  7  8  9  ", "0  ∞  ∞  ∞  ∞  ∞  ", "0  ∞  ∞  ∞  ∞  ∞  "]
    );
}

#[test]
fn multi_line_insert_2() {
    assert_eq!(
        compute(&["012345678"], &[edit((0, 3), (0, 5), "a\nb"), edit((0, 7), (0, 8), "x\ny")]),
        [
            "0  1  2  a  ",
            "0  0  0  0  0  ",
            "0  1  2  3  4  ",
            "0  0  0  0  0  ",
            "3  2  1  0  0  ",
            "b  5  6  x  ",
            "1  0  0  0  0  ",
            "0  5  6  7  8  ",
            "0  0  0  0  0  ",
            "0  2  1  0  0  ",
            "y  8  ",
            "1  0  0  ",
            "0  8  9  ",
            "0  ∞  ∞  ",
            "0  ∞  ∞  ",
        ]
    );
}

#[test]
fn multi_line_replace_insert_1() {
    let mut expected = vec![
        "₀  ₁  ₂  a  a  a  ",
        "0  0  0  0  0  0  0  ",
        "0  1  2  3  4  5  6  ",
        "0  0  0  0  0  0  0  ",
        "3  2  1  0  0  0  0  ",
        "b  b  b  1  2  3  4  5  6  7  8  ",
        "1  1  1  1  1  1  1  1  1  1  1  1  ",
        "0  1  2  1  2  3  4  5  6  7  8  9  ",
        "0  0  0  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ",
        "0  0  0  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ",
    ];
    expected.extend(UNTOUCHED_SUPERSCRIPTS);
    assert_eq!(compute(&["₀₁₂₃₄₅₆₇₈₉", "012345678", "⁰¹²³⁴⁵⁶⁷⁸⁹"], &[edit((0, 3), (1, 1), "aaa\nbbb")]), expected);
}

#[test]
fn multi_line_replace_insert_2() {
    assert_eq!(
        compute(&["₀₁₂₃₄₅₆₇₈₉", "012345678", "⁰¹²³⁴⁵⁶⁷⁸⁹"], &[edit((0, 3), (1, 1), "aaa\nbbb"), edit((1, 5), (1, 5), "x\ny"), edit((1, 7), (2, 4), "k\nl")]),
        [
            "₀  ₁  ₂  a  a  a  ",
            "0  0  0  0  0  0  0  ",
            "0  1  2  3  4  5  6  ",
            "0  0  0  0  0  0  0  ",
            "3  2  1  0  0  0  0  ",
            "b  b  b  1  2  3  4  x  ",
            "1  1  1  1  1  1  1  1  1  ",
            "0  1  2  1  2  3  4  5  6  ",
            "0  0  0  0  0  0  0  0  0  ",
            "0  0  0  4  3  2  1  0  0  ",
            "y  5  6  k  ",
            "2  1  1  1  1  ",
            "0  5  6  7  8  ",
            "0  0  0  0  0  ",
            "0  2  1  0  0  ",
            "l  ⁴  ⁵  ⁶  ⁷  ⁸  ⁹  ",
            "2  2  2  2  2  2  2  2  ",
            "0  4  5  6  7  8  9  10 ",
            "0  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ",
            "0  ∞  ∞  ∞  ∞  ∞  ∞  ∞  ",
        ]
    );
}

/// A text model enough for combineTextEditInfos.test.ts: char offsets and positions over a string.
struct Model(Vec<char>);

impl Model {
    fn position_at(&self, offset: usize) -> Length {
        let before = &self.0[..offset];
        match before.iter().rposition(|c| *c == '\n') {
            Some(newline) => Length::new(before.iter().filter(|c| **c == '\n').count(), offset - newline - 1),
            None => Length::new(0, offset),
        }
    }

    fn offset_at(&self, position: Length) -> usize {
        let line_start = match position.lines {
            0 => 0,
            lines => self.0.iter().enumerate().filter(|(_, c)| **c == '\n').nth(lines - 1).expect("the line exists").0 + 1,
        };
        line_start + position.columns
    }

    fn value_in(&self, start: Length, end: Length) -> String {
        self.0[self.offset_at(start)..self.offset_at(end)].iter().collect()
    }

    fn replace(&mut self, start: Length, end: Length, text: &str) {
        let range = self.offset_at(start)..self.offset_at(end);
        self.0.splice(range, text.chars());
    }

    /// The edits apply to the text before all of them, so they replace from the last one.
    fn apply(&mut self, edits: &[TextEditInfo]) {
        for edit in edits.iter().rev() {
            self.replace(edit.start, edit.end, &new_text(edit.new_length));
        }
    }
}

fn new_text(length: Length) -> String {
    "LLL\n".repeat(length.lines) + &"C".repeat(length.columns)
}

/// xorshift in place of upstream's `Random`: the cases differ, the property checked is the same.
struct Random(u64);

impl Random {
    fn next_int_range(&mut self, start: usize, end: usize) -> usize {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 7;
        self.0 ^= self.0 << 17;
        if end <= start {
            return start;
        }
        start + (self.0 % (end - start) as u64) as usize
    }
}

/// combineTextEditInfos.test.ts `getRandomEditInfos`.
fn random_edits(model: &Model, count: usize, random: &mut Random) -> Vec<TextEditInfo> {
    let mut edits = Vec::new();
    let mut from = 0;
    for _ in 0..count {
        let start = random.next_int_range(from, model.0.len());
        let end = random.next_int_range(start, model.0.len());
        let new_length = Length::new(random.next_int_range(0, 3), random.next_int_range(0, 5));
        let edit = TextEditInfo { start: model.position_at(start), end: model.position_at(end), new_length };
        from = model.offset_at(edit.end);
        edits.push(edit);
    }
    edits
}

/// combineTextEditInfos.test.ts: undoing the combined edits on the twice edited text gives the original back.
#[test]
fn combined_edits_map_the_text_before_both_to_the_text_after_both() {
    for seed in 0..50 {
        let mut random = Random(seed * 2654435761 + 1);
        let s0 = Model("abcde\nfghij\nklmno\npqrst\n".chars().collect());
        let edits1 = random_edits(&s0, random.next_int_range(1, 4), &mut random);
        let mut s1 = Model(s0.0.clone());
        s1.apply(&edits1);
        let edits2 = random_edits(&s1, random.next_int_range(1, 4), &mut random);
        let mut s2 = Model(s1.0.clone());
        s2.apply(&edits2);

        for edit in combine_text_edit_infos(&edits1, &edits2) {
            let end = edit.start + edit.new_length;
            let value = s2.value_in(edit.start, end);
            assert!(value.chars().all(|c| matches!(c, 'L' | 'C' | '\n')), "seed {seed}: invalid edit {edit:?} over {value:?}");
            s2.replace(edit.start, end, &s0.value_in(edit.start, edit.end));
        }
        assert_eq!(s2.0, s0.0, "seed {seed}");
    }
}