aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_text_edit/src/test_utils.rs
blob: 2dc0e71af2693201c6558a2637ca96dd7b4740d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use proptest::prelude::*;
use text_unit::{TextUnit, TextRange};
use crate::{AtomTextEdit, TextEdit};

pub fn arb_text() -> proptest::string::RegexGeneratorStrategy<String> {
    // generate multiple newlines
    proptest::string::string_regex("(.*\n?)*").unwrap()
}

fn text_offsets(text: &str) -> Vec<TextUnit> {
    text.char_indices().map(|(i, _)| TextUnit::from_usize(i)).collect()
}

pub fn arb_offset(text: &str) -> BoxedStrategy<TextUnit> {
    let offsets = text_offsets(text);
    // this is necessary to avoid "Uniform::new called with `low >= high`" panic
    if offsets.is_empty() {
        Just(TextUnit::from(0)).boxed()
    } else {
        prop::sample::select(offsets).boxed()
    }
}

pub fn arb_text_edit(text: &str) -> BoxedStrategy<TextEdit> {
    if text.is_empty() {
        // only valid edits
        return Just(vec![])
            .boxed()
            .prop_union(
                arb_text()
                    .prop_map(|text| vec![AtomTextEdit::insert(TextUnit::from(0), text)])
                    .boxed(),
            )
            .prop_map(TextEdit::from_atoms)
            .boxed();
    }

    let offsets = text_offsets(text);
    let max_cuts = 7.min(offsets.len());

    proptest::sample::subsequence(offsets, 0..max_cuts)
        .prop_flat_map(|cuts| {
            let strategies: Vec<_> = cuts
                .chunks(2)
                .map(|chunk| match *chunk {
                    [from, to] => {
                        let range = TextRange::from_to(from, to);
                        Just(AtomTextEdit::delete(range))
                            .boxed()
                            .prop_union(
                                arb_text()
                                    .prop_map(move |text| AtomTextEdit::replace(range, text))
                                    .boxed(),
                            )
                            .boxed()
                    }
                    [x] => arb_text().prop_map(move |text| AtomTextEdit::insert(x, text)).boxed(),
                    _ => unreachable!(),
                })
                .collect();
            strategies
        })
        .prop_map(TextEdit::from_atoms)
        .boxed()
}

#[derive(Debug, Clone)]
pub struct ArbTextWithEdit {
    pub text: String,
    pub edit: TextEdit,
}

pub fn arb_text_with_edit() -> BoxedStrategy<ArbTextWithEdit> {
    let text = arb_text();
    text.prop_flat_map(|s| {
        let edit = arb_text_edit(&s);
        (Just(s), edit)
    })
    .prop_map(|(text, edit)| ArbTextWithEdit { text, edit })
    .boxed()
}