harper-core 3.2.0

The language checker for developers.
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
use std::sync::Arc;

use crate::{
    expr::{Expr, SequenceExpr},
    linting::{ExprLinter, Lint, LintKind, Suggestion, expr_linter::Chunk},
    spell::{Dictionary, FstDictionary},
    {OrthFlags, Token},
};

pub struct OrthographicConsistency {
    dict: Arc<FstDictionary>,
    expr: SequenceExpr,
}

impl OrthographicConsistency {
    pub fn new() -> Self {
        Self {
            dict: FstDictionary::curated(),
            expr: SequenceExpr::any_word(),
        }
    }
}

impl Default for OrthographicConsistency {
    fn default() -> Self {
        Self::new()
    }
}

impl ExprLinter for OrthographicConsistency {
    type Unit = Chunk;

    fn description(&self) -> &str {
        "Ensures word casing matches the dictionary's canonical orthography."
    }

    fn expr(&self) -> &dyn Expr {
        &self.expr
    }

    fn match_to_lint_with_context(
        &self,
        matched_tokens: &[Token],
        source: &[char],
        context: Option<(&[Token], &[Token])>,
    ) -> Option<Lint> {
        if let Some((pre, post)) = context {
            if let Some(pre_tok) = pre.last()
                && pre_tok.kind.is_hyphen()
            {
                return None;
            }

            if let Some(post_tok) = post.first()
                && post_tok.kind.is_hyphen()
            {
                return None;
            }
        }

        let word = &matched_tokens[0];

        let Some(Some(metadata)) = word.kind.as_word() else {
            return None;
        };

        let chars = word.get_ch(source);

        if self.dict.contains_exact_word(chars) {
            // Exit if the dictionary contains the exact word.
            return None;
        }

        let cur_flags = OrthFlags::from_letters(chars);

        if metadata.is_allcaps()
            && !cur_flags.contains(OrthFlags::ALLCAPS)
            && metadata.orth_info.case_flags().bits().count_ones() == 1
        {
            return Some(Lint {
                span: word.span,
                lint_kind: LintKind::Capitalization,
                suggestions: vec![Suggestion::ReplaceWith(
                    chars.iter().map(|c| c.to_ascii_uppercase()).collect(),
                )],
                message: "This word's canonical spelling is all-caps.".to_owned(),
                // Two-letter matches are often typos (`ot` for `to`), so `SpellCheck` should win.
                priority: if chars.len() > 2 { 31 } else { 127 },
            });
        }

        let canonical_flags = metadata.orth_info;

        // Correct an accidental second capital without changing the initial capital.
        if chars.len() >= 3
            && chars[0].is_ascii_uppercase()
            && chars[1].is_ascii_uppercase()
            && chars[2..].iter().all(char::is_ascii_lowercase)
            && let Some(canonical) = self.dict.get_correct_capitalization_of(chars)
            && OrthFlags::from_letters(canonical)
                .intersects(OrthFlags::LOWERCASE | OrthFlags::TITLECASE)
        {
            let mut corrected = chars.to_vec();
            corrected[1].make_ascii_lowercase();

            return Some(Lint {
                span: word.span,
                lint_kind: LintKind::Capitalization,
                message: format!(
                    "Did you mean `{}`? Only the first letter should be capitalized.",
                    corrected.iter().collect::<String>()
                ),
                suggestions: vec![Suggestion::ReplaceWith(corrected)],
                priority: 31,
            });
        }

        let flags_to_check = [
            OrthFlags::LOWER_CAMEL,
            OrthFlags::UPPER_CAMEL,
            OrthFlags::APOSTROPHE,
            OrthFlags::HYPHENATED,
        ];

        if flags_to_check
            .into_iter()
            .filter(|flag| {
                canonical_flags.contains(*flag) != cur_flags.contains(*flag)
                    && ([OrthFlags::UPPER_CAMEL, OrthFlags::LOWER_CAMEL].contains(flag))
                    && !canonical_flags.contains(OrthFlags::LOWERCASE)
                    && !canonical_flags.contains(OrthFlags::TITLECASE)
            })
            .count()
            != 0
            && let Some(canonical) = self.dict.get_correct_capitalization_of(chars)
            && alphabetic_differs(canonical, chars)
        {
            return Some(Lint {
                span: word.span,
                lint_kind: LintKind::Capitalization,
                suggestions: vec![Suggestion::ReplaceWith(canonical.to_vec())],
                message: format!(
                    "The canonical dictionary spelling is `{}`.",
                    canonical.iter().collect::<String>()
                ),
                priority: 31,
            });
        }

        if metadata.is_titlecase()
            && cur_flags.contains(OrthFlags::LOWERCASE)
            && let Some(canonical) = self.dict.get_correct_capitalization_of(chars)
            && alphabetic_differs(canonical, chars)
        {
            return Some(Lint {
                span: word.span,
                lint_kind: LintKind::Capitalization,
                suggestions: vec![Suggestion::ReplaceWith(canonical.to_vec())],
                message: format!(
                    "The canonical dictionary spelling is title case: `{}`.",
                    canonical.iter().collect::<String>()
                ),
                priority: 127,
            });
        }

        None
    }
}

/// Check if the alphabetic characters in the string differ from one another.
/// Ignores non-alphabetic characters.
fn alphabetic_differs(a: &[char], b: &[char]) -> bool {
    a.iter()
        .zip(b.iter())
        .any(|(a, b)| a.is_alphabetic() && b.is_alphabetic() && a != b)
}

#[cfg(test)]
mod tests {
    use crate::Dialect;
    use crate::linting::LintGroup;
    use crate::linting::tests::{
        assert_good_and_bad_suggestions, assert_lint_count, assert_no_lints,
        assert_suggestion_result,
    };
    use crate::spell::FstDictionary;

    use super::OrthographicConsistency;

    fn curated_linter() -> LintGroup {
        LintGroup::new_curated(FstDictionary::curated(), Dialect::American)
    }

    #[test]
    fn lowercase_bbc_beats_spell_check() {
        assert_suggestion_result(
            "The bbc reported it.",
            curated_linter(),
            "The BBC reported it.",
        );
    }

    #[test]
    fn title_case_bbc_beats_spell_check() {
        assert_suggestion_result(
            "The Bbc reported it.",
            curated_linter(),
            "The BBC reported it.",
        );
    }

    #[test]
    fn lowercase_html_beats_spell_check() {
        assert_suggestion_result(
            "Validate the html first.",
            curated_linter(),
            "Validate the HTML first.",
        );
    }

    #[test]
    fn lowercase_nhs_beats_spell_check() {
        assert_suggestion_result(
            "The nhs is very busy.",
            curated_linter(),
            "The NHS is very busy.",
        );
    }

    #[test]
    fn two_letter_typo_stays_with_spell_check() {
        assert_suggestion_result(
            "We went ot the shop.",
            curated_linter(),
            "We went out the shop.",
        );
    }

    // `us`, `who` and `it` are common words, even though `US`, `WHO` and `IT` are also dictionary
    // entries, so they shouldn't be changed to all-caps.
    #[test]
    fn dont_capitalize_common_words_that_match_acronyms() {
        assert_no_lints(
            "They told us who it was.",
            OrthographicConsistency::default(),
        );
    }

    #[test]
    fn nasa_should_be_all_caps() {
        assert_suggestion_result(
            "Nasa is a governmental institution.",
            OrthographicConsistency::default(),
            "NASA is a governmental institution.",
        );
    }

    #[test]
    fn ikea_should_be_all_caps() {
        assert_suggestion_result(
            "Ikea operates a vast retail network.",
            OrthographicConsistency::default(),
            "IKEA operates a vast retail network.",
        );
    }

    #[test]
    fn nato_should_be_all_caps() {
        assert_suggestion_result(
            "Nato is a military alliance.",
            OrthographicConsistency::default(),
            "NATO is a military alliance.",
        );
    }

    #[test]
    fn fbi_should_be_all_caps() {
        assert_suggestion_result(
            "Fbi investigates federal crimes.",
            OrthographicConsistency::default(),
            "FBI investigates federal crimes.",
        );
    }

    #[test]
    fn cia_should_be_all_caps() {
        assert_suggestion_result(
            "Cia gathers intelligence.",
            OrthographicConsistency::default(),
            "CIA gathers intelligence.",
        );
    }

    #[test]
    fn hiv_should_be_all_caps() {
        assert_suggestion_result(
            "Hiv is a virus.",
            OrthographicConsistency::default(),
            "HIV is a virus.",
        );
    }

    #[test]
    fn dna_should_be_all_caps() {
        assert_suggestion_result(
            "Dna carries genetic information.",
            OrthographicConsistency::default(),
            "DNA carries genetic information.",
        );
    }

    #[test]
    fn rna_should_be_all_caps() {
        assert_suggestion_result(
            "Rna participates in protein synthesis.",
            OrthographicConsistency::default(),
            "RNA participates in protein synthesis.",
        );
    }

    #[test]
    fn cpu_should_be_all_caps() {
        assert_suggestion_result(
            "Cpu executes instructions.",
            OrthographicConsistency::default(),
            "CPU executes instructions.",
        );
    }

    #[test]
    fn gpu_should_be_all_caps() {
        assert_suggestion_result(
            "Gpu accelerates graphics.",
            OrthographicConsistency::default(),
            "GPU accelerates graphics.",
        );
    }

    #[test]
    fn html_should_be_all_caps() {
        assert_suggestion_result(
            "Html structures web documents.",
            OrthographicConsistency::default(),
            "HTML structures web documents.",
        );
    }

    #[test]
    fn url_should_be_all_caps() {
        assert_suggestion_result(
            "Url identifies a resource.",
            OrthographicConsistency::default(),
            "URL identifies a resource.",
        );
    }

    #[test]
    fn faq_should_be_all_caps() {
        assert_suggestion_result(
            "Faq answers common questions.",
            OrthographicConsistency::default(),
            "FAQ answers common questions.",
        );
    }

    #[test]
    fn linkedin_should_use_canonical_case() {
        assert_suggestion_result(
            "I updated my linkedin profile yesterday.",
            OrthographicConsistency::default(),
            "I updated my LinkedIn profile yesterday.",
        );
    }

    #[test]
    fn wordpress_should_use_canonical_case() {
        assert_suggestion_result(
            "She writes daily on her wordpress blog.",
            OrthographicConsistency::default(),
            "She writes daily on her WordPress blog.",
        );
    }

    #[test]
    fn iphone_should_use_canonical_case() {
        assert_suggestion_result(
            "She bought a new iphone last week.",
            OrthographicConsistency::default(),
            "She bought a new iPhone last week.",
        );
    }

    #[test]
    fn ipad_should_use_canonical_case() {
        assert_suggestion_result(
            "He reads on his ipad every morning.",
            OrthographicConsistency::default(),
            "He reads on his iPad every morning.",
        );
    }

    #[test]
    fn ipod_should_use_canonical_case() {
        assert_suggestion_result(
            "She still listens to her ipod on long flights.",
            OrthographicConsistency::default(),
            "She still listens to her iPod on long flights.",
        );
    }

    #[test]
    fn imac_should_use_canonical_case() {
        assert_suggestion_result(
            "She edits photos on her imac at home.",
            OrthographicConsistency::default(),
            "She edits photos on her iMac at home.",
        );
    }

    #[test]
    fn itunes_should_use_canonical_case() {
        assert_suggestion_result(
            "She bought the album on itunes years ago.",
            OrthographicConsistency::default(),
            "She bought the album on iTunes years ago.",
        );
    }

    #[test]
    fn pdf_should_be_all_caps() {
        assert_suggestion_result(
            "Pdf preserves formatting.",
            OrthographicConsistency::default(),
            "PDF preserves formatting.",
        );
    }

    #[test]
    fn ceo_should_be_all_caps() {
        assert_suggestion_result(
            "Our Ceo approved the budget.",
            OrthographicConsistency::default(),
            "Our CEO approved the budget.",
        );
    }

    #[test]
    fn cfo_should_be_all_caps() {
        assert_suggestion_result(
            "The Cfo presented the report.",
            OrthographicConsistency::default(),
            "The CFO presented the report.",
        );
    }

    #[test]
    fn hr_should_be_all_caps() {
        assert_suggestion_result(
            "The Hr team scheduled interviews.",
            OrthographicConsistency::default(),
            "The HR team scheduled interviews.",
        );
    }

    #[test]
    fn ai_should_be_all_caps() {
        assert_suggestion_result(
            "Ai enables new capabilities.",
            OrthographicConsistency::default(),
            "AI enables new capabilities.",
        );
    }

    #[test]
    fn ufo_should_be_all_caps() {
        assert_suggestion_result(
            "Ufo sightings provoke debate.",
            OrthographicConsistency::default(),
            "UFO sightings provoke debate.",
        );
    }

    #[test]
    fn markdown_should_be_caps() {
        assert_suggestion_result(
            "I adore markdown.",
            OrthographicConsistency::default(),
            "I adore Markdown.",
        );
    }

    #[test]
    fn canonical_forms_should_not_be_flagged() {
        let sentences = [
            "NASA is a governmental institution.",
            "IKEA operates a vast retail network.",
            "LEGO bricks encourage creativity.",
            "NATO is a military alliance.",
            "FBI investigates federal crimes.",
            "CIA gathers intelligence.",
            "HIV is a virus.",
            "DNA carries genetic information.",
            "RNA participates in protein synthesis.",
            "CPU executes instructions.",
            "GPU accelerates graphics.",
            "HTML structures web documents.",
            "URL identifies a resource.",
            "FAQ answers common questions.",
            "I updated my LinkedIn profile yesterday.",
            "She writes daily on her WordPress blog.",
            "PDF preserves formatting.",
            "Our CEO approved the budget.",
            "The CFO presented the report.",
            "The HR team scheduled interviews.",
            "AI enables new capabilities.",
            "UFO sightings provoke debate.",
            "I adore Markdown.",
        ];

        for sentence in sentences {
            assert_no_lints(sentence, OrthographicConsistency::default());
        }
    }

    #[test]
    fn corrects_accidental_double_initial_capitals() {
        for (input, expected) in [
            ("THe", "The"),
            ("LIzard", "Lizard"),
            ("DOor", "Door"),
            ("THe lizard opened the door.", "The lizard opened the door."),
            ("A LIzard opened the door.", "A Lizard opened the door."),
            ("Open the DOor.", "Open the Door."),
            ("\"THe\"", "\"The\""),
            ("LIzard!", "Lizard!"),
            ("DOor?", "Door?"),
            ("THe, DOor", "The, Door"),
            ("THe\nLIzard", "The\nLizard"),
            ("THe\tDOor", "The\tDoor"),
            ("HEllo", "Hello"),
            ("WOrld", "World"),
            ("ENgland", "England"),
        ] {
            assert_suggestion_result(input, OrthographicConsistency::default(), expected);
        }
    }

    #[test]
    fn preserves_other_casing_and_unknown_words() {
        for input in [
            "The lizard opened the door.",
            "Lizard Door",
            "THE LIZARD DOOR",
            "NASA",
            "iPhone",
            "LinkedIn",
            "WordPress",
            "macOS",
            "YouTube",
            "DO",
            "PR",
            "QZxqzq",
            "tHe",
            "lIzard",
            "DOOr",
            "THe-like",
            "pre-DOor",
        ] {
            assert_no_lints(input, OrthographicConsistency::default());
        }
    }

    #[test]
    fn allows_news() {
        assert_no_lints(
            "This is the best part of the news broadcast.",
            OrthographicConsistency::default(),
        );
    }

    #[test]
    fn allows_issue_2465() {
        assert_no_lints(
            "The post’s problem was not in its complexity.",
            OrthographicConsistency::default(),
        );
    }

    #[test]
    fn no_improper_suggestion_for_macos() {
        assert_good_and_bad_suggestions(
            "MacOS",
            OrthographicConsistency::default(),
            &["macOS"],
            &["MacOS"],
        );
    }

    #[test]
    fn accept_case_variants() {
        // At the time of writing this test, "Pr" (despite being a word in the curated dictionary)
        // would be linted for the supposed reason of the canonical spelling being "PR".
        // Since both words are in the curated dictionary, neither should be linted.
        assert_no_lints("Pr PR", OrthographicConsistency::default());
        assert_no_lints("Apr APR", OrthographicConsistency::default()); // https://github.com/Automattic/harper/issues/3080
        assert_no_lints("install.md", OrthographicConsistency::default()); // https://github.com/Automattic/harper/issues/3073
    }

    #[test]
    #[ignore = "Words with multiple known orthographic variants are not currently supported"]
    fn dont_accept_undefined_case_variants() {
        // "pr" isn't defined in the dictionary, so it should be linted.
        assert_lint_count("pr", OrthographicConsistency::default(), 1);
    }

    #[test]
    fn lets_confusion_description() {
        assert_no_lints(
            "It's often hard to determine where the subject should go with the word `let`. This rule attempts to find common errors with redundancy and contractions that may lead to confusion for readers.",
            OrthographicConsistency::default(),
        )
    }
}