harper-core 2.4.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
use crate::{
    CharStringExt, Token,
    expr::{Expr, FirstMatchOf, SequenceExpr},
    linting::{ExprLinter, Lint, LintKind, Suggestion, expr_linter::Chunk},
    patterns::Word,
    token_string_ext::TokenStringExt,
};

enum Flag {
    /// Some acronyms should only be matched when all caps, like "PIN"
    AllCapsOnly,
    /// Some acronyms should not be pluralized, like "USD"
    DontPluralizeAcronym,
    /// No special flags
    None,
}
use Flag::*;

// (acronym, first_words, last_word)
const ACRONYMS: &[(&str, &[&str], &str, Flag)] = &[
    (
        "ATM",
        &["automated teller", "automatic teller"],
        "machine",
        None,
    ),
    ("GUI", &["graphical user"], "interface", None),
    ("LCD", &["liquid crystal"], "display", None),
    ("LLM", &["large language"], "model", None),
    // Note: "pin number" (not capitalized) is used to refer to GPIO pins etc.
    ("PIN", &["personal identification"], "number", AllCapsOnly),
    (
        "TUI",
        &["text-based user", "terminal user"],
        "interface",
        None,
    ),
    ("UI", &["user"], "interface", None),
    ("USD", &["US"], "dollars", DontPluralizeAcronym),
    ("VIN", &["vehicle identification"], "number", None),
];

pub struct RedundantAcronyms {
    expr: FirstMatchOf,
}

impl Default for RedundantAcronyms {
    fn default() -> Self {
        let exprs: Vec<Box<dyn Expr>> = ACRONYMS
            .iter()
            .map(|&(acronym, _, last_str, _)| {
                let last_string = last_str.to_string();
                Box::new(SequenceExpr::aco(acronym).t_ws().then_any_of(vec![
                    Box::new(Word::new(last_str)),
                    Box::new(move |t: &Token, src: &[char]| {
                        t.get_ch(src).eq_str(&format!("{last_string}s"))
                    }),
                ])) as Box<dyn Expr>
            })
            .collect();

        Self {
            expr: FirstMatchOf::new(exprs),
        }
    }
}

impl ExprLinter for RedundantAcronyms {
    type Unit = Chunk;

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

    fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {
        let last_word_span = toks.last()?.span;
        let last_word_chars = last_word_span.get_content(src);
        let acronym_str = toks.first()?.get_str(src);

        let (_, middle_words, _, flag) = ACRONYMS
            .iter()
            .find(|(a, _, _, _)| (*a).eq_ignore_ascii_case(&acronym_str))?;

        // Skip if AllCapsOnly flag is set and acronym is not all caps
        if matches!(flag, AllCapsOnly) && !acronym_str.chars().all(|c| c.is_ascii_uppercase()) {
            return Option::None;
        }

        let is_all_caps = last_word_chars
            .iter()
            .all(|c| c.is_ascii_alphabetic() && c.is_ascii_uppercase());

        let plural_ending = if matches!(flag, DontPluralizeAcronym) {
            String::new()
        } else {
            last_word_chars
                .last()
                .filter(|&&c| c.eq_ignore_ascii_case(&'s'))
                .map(|c| c.to_string())
                .unwrap_or_default()
        };

        let suggestions: Vec<Suggestion> = std::iter::once(Suggestion::ReplaceWith(
            format!("{acronym_str}{plural_ending}").chars().collect(),
        ))
        .chain(middle_words.iter().map(|mw| {
            let middle_words = if is_all_caps {
                mw.to_ascii_uppercase()
            } else {
                mw.to_string()
            };
            Suggestion::ReplaceWith(
                format!("{middle_words} {}", last_word_span.get_content_string(src))
                    .chars()
                    .collect(),
            )
        }))
        .collect();

        Some(Lint {
        span: toks.span()?,
        lint_kind: LintKind::Redundancy,
        suggestions,
        message: "The acronym's last letter already stands for the last word. Use just the acronym or the full phrase.".to_string(),
        ..Default::default()
    })
    }

    fn description(&self) -> &str {
        "Identifies redundant acronyms where the last word repeats the last letter's meaning (e.g., `ATM machine` → `ATM` or `automated teller machine`)."
    }
}

#[cfg(test)]
mod tests {
    use super::RedundantAcronyms;
    use crate::linting::tests::{assert_good_and_bad_suggestions, assert_no_lints};

    #[test]
    fn test_made_up() {
        assert_good_and_bad_suggestions(
            "I forgot my PIN number!",
            RedundantAcronyms::default(),
            &[
                "I forgot my PIN!",
                "I forgot my personal identification number!",
            ],
            &[],
        );
    }

    #[test]
    fn test_all_caps_singular() {
        assert_good_and_bad_suggestions(
            "CAN TWO CARS HAVE THE SAME VIN NUMBER?",
            RedundantAcronyms::default(),
            &[
                "CAN TWO CARS HAVE THE SAME VIN?",
                "CAN TWO CARS HAVE THE SAME VEHICLE IDENTIFICATION NUMBER?",
            ],
            &[],
        );
    }

    #[test]
    fn test_all_caps_plural() {
        assert_good_and_bad_suggestions(
            "THESE ATM MACHINES ALL HAVE HIGH FEES!",
            RedundantAcronyms::default(),
            &[
                "THESE ATMS ALL HAVE HIGH FEES!",
                "THESE AUTOMATED TELLER MACHINES ALL HAVE HIGH FEES!",
            ],
            &[],
        );
    }

    #[test]
    fn test_all_lowercase_singular() {
        assert_good_and_bad_suggestions(
            "the atm machine at my card",
            RedundantAcronyms::default(),
            &[
                "the atm at my card",
                "the automated teller machine at my card",
            ],
            &[],
        );
    }

    #[test]
    fn test_all_lowercase_plural() {
        assert_good_and_bad_suggestions(
            "gui interfaces were sooo trendy in 1984!",
            RedundantAcronyms::default(),
            &[
                "guis were sooo trendy in 1984!",
                "graphical user interfaces were sooo trendy in 1984!",
            ],
            &[],
        );
    }

    #[test]
    fn correct_atm_machine() {
        assert_good_and_bad_suggestions(
            "Developed an ATM machine application for Raspberry Pi",
            RedundantAcronyms::default(),
            &[
                "Developed an ATM application for Raspberry Pi",
                "Developed an automatic teller machine application for Raspberry Pi",
                "Developed an automated teller machine application for Raspberry Pi",
            ],
            &[],
        );
    }

    #[test]
    fn correct_atm_machines() {
        assert_good_and_bad_suggestions(
            "ATM machines allow 4 or 6 digit PIN codes",
            RedundantAcronyms::default(),
            &[
                "ATMs allow 4 or 6 digit PIN codes",
                "automated teller machines allow 4 or 6 digit PIN codes",
                "automatic teller machines allow 4 or 6 digit PIN codes",
            ],
            &[],
        );
    }

    #[test]
    fn correct_gui_interface() {
        assert_good_and_bad_suggestions(
            "This project develops using java language with GUI interface.",
            RedundantAcronyms::default(),
            &[
                "This project develops using java language with GUI.",
                "This project develops using java language with graphical user interface.",
            ],
            &[],
        );
    }

    #[test]
    fn correct_gui_interfaces() {
        assert_good_and_bad_suggestions(
            "In non-crafting GUI interfaces, such as a mod's own recipe tree, the shortcut key cannot be used to view item usage or crafting methods.",
            RedundantAcronyms::default(),
            &[
                "In non-crafting GUIs, such as a mod's own recipe tree, the shortcut key cannot be used to view item usage or crafting methods.",
                "In non-crafting graphical user interfaces, such as a mod's own recipe tree, the shortcut key cannot be used to view item usage or crafting methods.",
            ],
            &[],
        );
    }

    #[test]
    fn correct_lcd_display() {
        assert_good_and_bad_suggestions(
            "This function accepts I2C shield address for LCD display, number of columns, rows and dot size",
            RedundantAcronyms::default(),
            &[
                "This function accepts I2C shield address for LCD, number of columns, rows and dot size",
                "This function accepts I2C shield address for liquid crystal display, number of columns, rows and dot size",
            ],
            &[],
        );
    }

    #[test]
    fn correct_lcd_displays() {
        assert_good_and_bad_suggestions(
            "ScreenUi makes it easy to build simple or complex character based user interfaces on small LCD displays like those commonly used with Arduinos.",
            RedundantAcronyms::default(),
            &[
                "ScreenUi makes it easy to build simple or complex character based user interfaces on small LCDs like those commonly used with Arduinos.",
                "ScreenUi makes it easy to build simple or complex character based user interfaces on small liquid crystal displays like those commonly used with Arduinos.",
            ],
            &[],
        );
    }

    #[test]
    fn correct_pin_numbers_caps() {
        assert_good_and_bad_suggestions(
            "Randomly generating PIN numbers for ATM access.",
            RedundantAcronyms::default(),
            &[
                "Randomly generating PINs for ATM access.",
                "Randomly generating personal identification numbers for ATM access.",
            ],
            &[],
        );
    }

    #[test]
    fn correct_pin_number_all_caps() {
        assert_good_and_bad_suggestions(
            "DON'T LET ANYONE SEE YOUR PIN NUMBER",
            RedundantAcronyms::default(),
            &[
                "DON'T LET ANYONE SEE YOUR PIN",
                "DON'T LET ANYONE SEE YOUR PERSONAL IDENTIFICATION NUMBER",
            ],
            &[],
        );
    }

    #[test]
    fn dont_correct_pin_number_lowercase() {
        assert_no_lints(
            "GPIO 26 (pin 37) on the Pi4 is mapped to pin nummer GPIO 425 on the pi5",
            RedundantAcronyms::default(),
        );
    }

    #[test]
    fn dont_correct_pin_number_titlecase() {
        assert_no_lints(
            "Pin Number Match Project in Javascript.",
            RedundantAcronyms::default(),
        )
    }

    #[test]
    fn correct_tui_interface() {
        assert_good_and_bad_suggestions(
            "Could a history search TUI interface be added for xonsh?",
            RedundantAcronyms::default(),
            &[
                "Could a history search TUI be added for xonsh?",
                "Could a history search text-based user interface be added for xonsh?",
                "Could a history search terminal user interface be added for xonsh?",
            ],
            &[],
        );
    }

    #[test]
    fn correct_ui_interface() {
        assert_good_and_bad_suggestions(
            "call ESPUI.begin(\"Some Title\"); to start the UI interface",
            RedundantAcronyms::default(),
            &[
                "call ESPUI.begin(\"Some Title\"); to start the UI",
                "call ESPUI.begin(\"Some Title\"); to start the user interface",
            ],
            &[],
        );
    }

    #[test]
    fn correct_vin_numbers() {
        assert_good_and_bad_suggestions(
            "That was actually accurate in decoding the VIN numbers but it costed me a 1000 USD.",
            RedundantAcronyms::default(),
            &[
                "That was actually accurate in decoding the VINs but it costed me a 1000 USD.",
                "That was actually accurate in decoding the vehicle identification numbers but it costed me a 1000 USD.",
            ],
            &[],
        );
    }

    #[test]
    fn correct_vin_number() {
        assert_good_and_bad_suggestions(
            "we have implemented verification algorithms, which ensure that VIN number received is correct",
            RedundantAcronyms::default(),
            &[
                "we have implemented verification algorithms, which ensure that VIN received is correct",
                "we have implemented verification algorithms, which ensure that vehicle identification number received is correct",
            ],
            &[],
        );
    }

    #[test]
    fn correct_llm_model() {
        assert_good_and_bad_suggestions(
            "They end up attributing a lot of what they're doing to the capabilities of the LLM model.",
            RedundantAcronyms::default(),
            &[
                "They end up attributing a lot of what they're doing to the capabilities of the LLM.",
                "They end up attributing a lot of what they're doing to the capabilities of the large language model.",
            ],
            &[],
        );
    }

    #[test]
    fn correct_llm_models() {
        assert_good_and_bad_suggestions(
            "Ollama is an open-source tool for running LLM models locally.",
            RedundantAcronyms::default(),
            &[
                "Ollama is an open-source tool for running LLMs locally.",
                "Ollama is an open-source tool for running large language models locally.",
            ],
            &[],
        );
    }

    #[test]
    fn correct_usd() {
        assert_good_and_bad_suggestions(
            "And because I didn't have USD dollars, I used zip ties [music] instead of a proper microonal bass.",
            RedundantAcronyms::default(),
            &[
                "And because I didn't have US dollars, I used zip ties [music] instead of a proper microonal bass.",
                "And because I didn't have USD, I used zip ties [music] instead of a proper microonal bass.",
            ],
            &[],
        );
    }
}