harper-core 2.0.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
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);

        let cur_flags = OrthFlags::from_letters(chars);

        if metadata.is_allcaps()
            && !metadata.is_lowercase()
            && !metadata.is_upper_camel()
            && !cur_flags.contains(OrthFlags::ALLCAPS)
        {
            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(),
                priority: 127,
            });
        }

        let canonical_flags = metadata.orth_info;
        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))
            .count()
            == 1
            && 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::linting::tests::{assert_no_lints, assert_suggestion_result};

    use super::OrthographicConsistency;

    #[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 lego_should_be_all_caps() {
        assert_suggestion_result(
            "Lego bricks encourage creativity.",
            OrthographicConsistency::default(),
            "LEGO bricks encourage creativity.",
        );
    }

    #[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 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 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(),
        );
    }
}