codebook 0.3.39

A code-aware spell checker library (dependency for codebook-lsp)
Documentation
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use codebook::{
    parser::{TextRange, WordLocation},
    queries::LanguageType,
};


/// Strategy:
/// Use distinct misspellings to test location sensitive checking.
/// This simpler to write than asserting exact locations.
/// Granted - it doesn't test that the spell_check return correct locations,
/// but should be sufficient that some tests tests this.
/// This can be used to test language-specific grammar rules with less effort.
///
/// `not_expected` does not have to be exhaustive.
fn assert_simple_misspellings(
    processor: &codebook::Codebook,
    sample_text: &str,
    expected_misspellings: Vec<&str>,
    not_expected: Vec<&str>,
    language: LanguageType,
) {
    // Check that the misspelled words used are distinct,
    // otherwise the test could fail to properly test location sensitive properties
    for word in expected_misspellings.iter() {
        let count = sample_text.matches(word).count();
        assert_eq!(
            count, 1,
            "Word '{}' should occur exactly once in sample_text, but found {} occurrences",
            word, count
        );
    }

    let binding = processor
        .spell_check(sample_text, Some(language), None)
        .to_vec();
    let mut misspelled = binding
        .iter()
        .map(|r| r.word.as_str())
        .collect::<Vec<&str>>();
    misspelled.sort();
    println!("Misspelled words: {misspelled:?}");

    let mut expected_misspellings_sorted = expected_misspellings.clone();
    expected_misspellings_sorted.sort();
    assert_eq!(misspelled, expected_misspellings_sorted);

    for word in not_expected {
        println!("Not expecting: {word:?}");
        assert!(!misspelled.contains(&word));
    }
}

#[test]
fn test_python_simple() {
    super::utils::init_logging();
    let processor = super::utils::get_processor();
    let sample_text = r#"
        def calculat_user_age(bithDate) -> int:
            # This is an examle_function that calculates age
            usrAge = get_curent_date() - bithDate
            userAge
    "#;
    let expected = vec!["bith", "calculat", "examle"];
    let binding = processor
        .spell_check(sample_text, Some(LanguageType::Python), None)
        .to_vec();
    let mut misspelled = binding
        .iter()
        .map(|r| r.word.as_str())
        .collect::<Vec<&str>>();
    misspelled.sort();
    println!("Misspelled words: {misspelled:?}");
    assert_eq!(misspelled, expected);
}

#[test]
fn test_python_multi_line_comment() {
    super::utils::init_logging();
    let sample_python = r#"
multi_line_comment = '''
    This is a multi line comment with a typo: mment
    Another linet
'''
        "#;
    let expected = vec![
        WordLocation::new(
            "mment".to_string(),
            vec![TextRange {
                start_byte: 72,
                end_byte: 77,
            }],
        ),
        WordLocation::new(
            "linet".to_string(),
            vec![TextRange {
                start_byte: 90,
                end_byte: 95,
            }],
        ),
    ];
    let processor = super::utils::get_processor();
    let misspelled = processor
        .spell_check(sample_python, Some(LanguageType::Python), None)
        .to_vec();
    println!("Misspelled words: {misspelled:?}");
    for e in &expected {
        let miss = misspelled.iter().find(|r| r.word == e.word).unwrap();
        println!("Expecting: {e:?}");
        assert_eq!(miss.locations, e.locations);
    }
}

#[test]
fn test_python_class() {
    super::utils::init_logging();
    let sample_python = r#"
class BadSpelin:
    def nospel(self):
        return self.zzzznomethod() # This should not get checked
    def bad_spelin(self): # This should get checked
        return "Spelling is hardz" # This should get checked

@decorated
def constructor():
    return BadSpelin(hardx=bad.hardd, thing="hardg")  # Some of this should get checked
'''
        "#;
    let expected = vec![
        WordLocation::new(
            "Spelin".to_string(),
            vec![TextRange {
                start_byte: 10,
                end_byte: 16,
            }],
        ),
        WordLocation::new(
            "nospel".to_string(),
            vec![TextRange {
                start_byte: 26,
                end_byte: 32,
            }],
        ),
        WordLocation::new(
            "hardz".to_string(),
            vec![TextRange {
                start_byte: 185,
                end_byte: 190,
            }],
        ),
        WordLocation::new(
            "hardg".to_string(),
            vec![TextRange {
                start_byte: 294,
                end_byte: 299,
            }],
        ),
    ];
    let not_expected = vec!["zzzznomethod", "hardx", "hardd"];
    let processor = super::utils::get_processor();
    let misspelled = processor
        .spell_check(sample_python, Some(LanguageType::Python), None)
        .to_vec();
    println!("Misspelled words: {misspelled:?}");
    for e in &expected {
        let miss = misspelled.iter().find(|r| r.word == e.word).unwrap();
        println!("Expecting: {e:?}");
        assert_eq!(miss.locations, e.locations);
    }
    for word in not_expected {
        println!("Not expecting: {word:?}");
        assert!(!misspelled.iter().any(|r| r.word == word));
    }
}

#[test]
fn test_python_global_variables() {
    super::utils::init_logging();
    let processor = super::utils::get_processor();
    let sample_text = r#"
# Globul variables
globalCountr = 0
mesage = "Helllo Wolrd!"
    "#;
    let expected = vec![
        WordLocation::new(
            "Globul".to_string(),
            vec![TextRange {
                start_byte: 3,
                end_byte: 9,
            }],
        ),
        WordLocation::new(
            "Countr".to_string(),
            vec![TextRange {
                start_byte: 26,
                end_byte: 32,
            }],
        ),
        WordLocation::new(
            "mesage".to_string(),
            vec![TextRange {
                start_byte: 37,
                end_byte: 43,
            }],
        ),
        WordLocation::new(
            "Helllo".to_string(),
            vec![TextRange {
                start_byte: 47,
                end_byte: 53,
            }],
        ),
        WordLocation::new(
            "Wolrd".to_string(),
            vec![TextRange {
                start_byte: 54,
                end_byte: 59,
            }],
        ),
    ];

    let misspelled = processor
        .spell_check(sample_text, Some(LanguageType::Python), None)
        .to_vec();
    println!("Misspelled words: {misspelled:?}");

    for e in &expected {
        let miss = misspelled
            .iter()
            .find(|r| r.word == e.word)
            .unwrap_or_else(|| panic!("Word '{}' not found in misspelled list", e.word));
        println!("Expecting: {e:?}");
        assert_eq!(miss.locations, e.locations);
    }
}

#[test]
fn test_python_f_strings() {
    super::utils::init_logging();
    let processor = super::utils::get_processor();
    let sample_text = r#"
name = "John"
age = 25
message = f'Hello, my naem is {namz} and I am {age} years oldd'
another = f"This is antoher examle with {name} varibles"
simple = f'check these wordz {but} {not} {the} {variables}'
    "#;

    let expected = vec![
        WordLocation::new(
            "naem".to_string(),
            vec![TextRange {
                start_byte: 46,
                end_byte: 50,
            }],
        ),
        WordLocation::new(
            "oldd".to_string(),
            vec![TextRange {
                start_byte: 82,
                end_byte: 86,
            }],
        ),
        WordLocation::new(
            "antoher".to_string(),
            vec![TextRange {
                start_byte: 108,
                end_byte: 115,
            }],
        ),
        WordLocation::new(
            "examle".to_string(),
            vec![TextRange {
                start_byte: 116,
                end_byte: 122,
            }],
        ),
        WordLocation::new(
            "varibles".to_string(),
            vec![TextRange {
                start_byte: 135,
                end_byte: 143,
            }],
        ),
        WordLocation::new(
            "wordz".to_string(),
            vec![TextRange {
                start_byte: 168,
                end_byte: 173,
            }],
        ),
    ];

    let not_expected = vec!["namz", "age", "but", "not", "the", "variables"];

    let misspelled = processor
        .spell_check(sample_text, Some(LanguageType::Python), None)
        .to_vec();
    println!("Misspelled words: {misspelled:?}");

    for e in &expected {
        let miss = misspelled
            .iter()
            .find(|r| r.word == e.word)
            .unwrap_or_else(|| panic!("Word '{}' not found in misspelled list", e.word));
        println!("Expecting: {e:?}");
        assert_eq!(miss.locations, e.locations);
    }

    for word in not_expected {
        println!("Not expecting: {word:?}");
        assert!(!misspelled.iter().any(|r| r.word == word));
    }
}

#[test]
fn test_python_import_statements() {
    super::utils::init_logging();
    let processor = super::utils::get_processor();
    let sample_text = r#"
        import no_typpoa
        import no_typpob.no_typpoc

        import no_typpod as yes_typpoe
        import no_typpof.no_typpog as yes_typpoh

        from no_typpoi import no_typpoj
        from no_typpok.no_typpol import no_typpom

        from no_typpoo import no_typpop as yes_typpoq
        from no_typpor.no_typpos import no_typpot as yes_typpou
        from .. import no_typpov as yes_typpow
    "#;
    let expected = vec!["typpoe", "typpoh", "typpoq", "typpou", "typpow"];
    let binding = processor
        .spell_check(sample_text, Some(LanguageType::Python), None)
        .to_vec();
    let mut misspelled = binding
        .iter()
        .map(|r| r.word.as_str())
        .collect::<Vec<&str>>();
    misspelled.sort();
    println!("Misspelled words: {misspelled:?}");
    assert_eq!(misspelled, expected);
}

#[test]
fn test_python_functions() {
    super::utils::init_logging();
    let processor = super::utils::get_processor();

    // Test simple function - function name and parameter names should be checked
    let simple_function = r#"
def simple_wrngfunction_name(wrngparam, correct, wrngdefaultparam=1, correct_default=2):
    pass
    "#;
    assert_simple_misspellings(
        &processor,
        simple_function,
        vec!["wrngfunction", "wrngparam", "wrngdefaultparam"],
        vec!["simple", "correct", "def", "name", "default"],
        LanguageType::Python,
    );

    // Test typed function - function names and parameters should be checked, but not types or modules
    let simple_typed_function = r#"
def simple_wrngfunction(wrngparam: str, correct: Wrngtype, other: wrngmod.Wrngmodtype, correct_default: Nons | int = 2) -> Wrngret:
    pass
    "#;
    assert_simple_misspellings(
        &processor,
        simple_typed_function,
        vec!["wrngfunction", "wrngparam"],
        vec![
            "simple",
            "correct",
            "str",
            "Wrngtype",
            "wrngmod",
            "Wrngmodtype",
            "Wrngret",
            "def",
            "Nons",
            "default",
        ],
        LanguageType::Python,
    );

    // Test generic function 1 - function names and parameters should be checked, but not types
    let generic_function_1 = r#"
def simple_wrngfunction(wrngparam: str, correct: Wrngtype[Wrngtemplate]):
    pass
    "#;
    assert_simple_misspellings(
        &processor,
        generic_function_1,
        vec!["wrngfunction", "wrngparam"],
        vec!["simple", "correct", "str", "Wrngtype", "Wrngtemplate"],
        LanguageType::Python,
    );

    // Test generic function 2 - function names and parameters should be checked, but not type templates
    let generic_function_2 = r#"
def simple_wrngfunction[Wrgtemplate](wrngparam: str, correct: Wrngtype[Wrngtemplate]):
    pass
    "#;
    assert_simple_misspellings(
        &processor,
        generic_function_2,
        vec!["wrngfunction", "wrngparam"],
        vec![
            "simple",
            "correct",
            "str",
            "Wrgtemplate",
            "Wrngtype",
            "Wrngtemplate",
        ],
        LanguageType::Python,
    );
}