forked from crate-ci/typos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdict.rs
363 lines (329 loc) · 10.9 KB
/
dict.rs
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
use std::borrow::Cow;
use std::collections::HashMap;
use unicase::UniCase;
use typos::tokens::Case;
use typos::Status;
#[derive(Default)]
pub struct BuiltIn {
locale: Option<varcon_core::Category>,
}
impl BuiltIn {
pub const fn new(locale: crate::config::Locale) -> Self {
Self {
locale: locale.category(),
}
}
pub fn correct_ident<'s, 'w>(
&'s self,
_ident: typos::tokens::Identifier<'w>,
) -> Option<Status<'s>> {
None
}
pub fn correct_word<'s, 'w>(
&'s self,
word_token: typos::tokens::Word<'w>,
) -> Option<Status<'s>> {
if word_token.case() == typos::tokens::Case::None {
return None;
}
let word = word_token.token();
let word_case = unicase::UniCase::new(word);
let mut corrections = if let Some(corrections) = self.correct_with_dict(word_case) {
if corrections.is_empty() {
Status::Invalid
} else {
self.chain_with_vars(corrections)
}
} else {
self.correct_with_vars(word_case)?
};
corrections
.corrections_mut()
.for_each(|s| case_correct(s, word_token.case()));
Some(corrections)
}
}
#[cfg(feature = "dict")]
impl BuiltIn {
// Not using `Status` to avoid the allocations
fn correct_with_dict(&self, word: unicase::UniCase<&str>) -> Option<&'static [&'static str]> {
typos_dict::WORD_TRIE.find(&word).copied()
}
}
#[cfg(not(feature = "dict"))]
impl BuiltIn {
fn correct_with_dict(&self, _word: unicase::UniCase<&str>) -> Option<&'static [&'static str]> {
None
}
}
#[cfg(feature = "vars")]
impl BuiltIn {
fn chain_with_vars(&self, corrections: &'static [&'static str]) -> Status<'static> {
if self.is_vars_enabled() {
let mut chained: Vec<_> = corrections
.iter()
.flat_map(|c| match self.correct_with_vars(unicase::UniCase::new(c)) {
Some(Status::Valid) | None => vec![Cow::Borrowed(*c)],
Some(Status::Corrections(vars)) => vars,
Some(Status::Invalid) => {
unreachable!("correct_with_vars should always have valid suggestions")
}
})
.collect();
if chained.len() != 1 {
chained.sort_unstable();
chained.dedup();
}
debug_assert!(!chained.is_empty());
Status::Corrections(chained)
} else {
Status::Corrections(corrections.iter().map(|c| Cow::Borrowed(*c)).collect())
}
}
fn correct_with_vars(&self, word: unicase::UniCase<&str>) -> Option<Status<'static>> {
if self.is_vars_enabled() {
typos_vars::VARS_TRIE
.find(&word)
.map(|variants| self.select_variant(variants))
} else {
None
}
}
fn is_vars_enabled(&self) -> bool {
#![allow(clippy::assertions_on_constants)]
debug_assert!(typos_vars::NO_INVALID);
self.locale.is_some()
}
fn select_variant(
&self,
vars: &'static [(u8, &'static typos_vars::VariantsMap)],
) -> Status<'static> {
let var = vars[0];
let var_categories = unsafe {
// Code-genned from a checked category-set, so known to be safe
typos_vars::CategorySet::from_bits_unchecked(var.0)
};
if let Some(locale) = self.locale {
if var_categories.contains(locale) {
// Already valid for the current locale.
Status::Valid
} else {
Status::Corrections(
typos_vars::corrections(locale, *var.1)
.iter()
.copied()
.map(Cow::Borrowed)
.collect(),
)
}
} else {
// All locales are valid
if var_categories.is_empty() {
// But the word is never valid.
let mut unique: Vec<_> = var
.1
.iter()
.flat_map(|v| v.iter())
.copied()
.map(Cow::Borrowed)
.collect();
unique.sort_unstable();
unique.dedup();
Status::Corrections(unique)
} else {
Status::Valid
}
}
}
}
#[cfg(not(feature = "vars"))]
impl BuiltIn {
fn chain_with_vars(&self, corrections: &'static [&'static str]) -> Status<'static> {
Status::Corrections(corrections.iter().map(|c| Cow::Borrowed(*c)).collect())
}
fn correct_with_vars(&self, _word: unicase::UniCase<&str>) -> Option<Status<'static>> {
None
}
}
impl typos::Dictionary for BuiltIn {
fn correct_ident<'s, 'w>(&'s self, ident: typos::tokens::Identifier<'w>) -> Option<Status<'s>> {
BuiltIn::correct_ident(self, ident)
}
fn correct_word<'s, 'w>(&'s self, word: typos::tokens::Word<'w>) -> Option<Status<'s>> {
BuiltIn::correct_word(self, word)
}
}
fn case_correct(correction: &mut Cow<'_, str>, case: Case) {
match case {
Case::Lower | Case::None => (),
Case::Title => match correction {
Cow::Borrowed(s) => {
let mut s = String::from(*s);
s[0..1].make_ascii_uppercase();
*correction = s.into();
}
Cow::Owned(s) => {
s[0..1].make_ascii_uppercase();
}
},
Case::Upper => match correction {
Cow::Borrowed(s) => {
let mut s = String::from(*s);
s.make_ascii_uppercase();
*correction = s.into();
}
Cow::Owned(s) => {
s.make_ascii_uppercase();
}
},
}
}
pub struct Override<'i, 'w, D> {
identifiers: HashMap<&'i str, Status<'i>, ahash::RandomState>,
words: HashMap<unicase::UniCase<&'w str>, Status<'w>, ahash::RandomState>,
inner: D,
}
impl<'i, 'w, D: typos::Dictionary> Override<'i, 'w, D> {
pub fn new(inner: D) -> Self {
Self {
identifiers: Default::default(),
words: Default::default(),
inner,
}
}
pub fn identifiers<I: Iterator<Item = (&'i str, &'i str)>>(&mut self, identifiers: I) {
self.identifiers = Self::interpret(identifiers).collect();
}
pub fn words<I: Iterator<Item = (&'w str, &'w str)>>(&mut self, words: I) {
self.words = Self::interpret(words)
.map(|(k, v)| (UniCase::new(k), v))
.collect();
}
fn interpret<'z, I: Iterator<Item = (&'z str, &'z str)>>(
cases: I,
) -> impl Iterator<Item = (&'z str, Status<'z>)> {
cases.map(|(typo, correction)| {
let correction = if typo == correction {
Status::Valid
} else if correction.is_empty() {
Status::Invalid
} else {
Status::Corrections(vec![Cow::Borrowed(correction)])
};
(typo, correction)
})
}
}
impl<'i, 'w, D: typos::Dictionary> typos::Dictionary for Override<'i, 'w, D> {
fn correct_ident<'s, 't>(&'s self, ident: typos::tokens::Identifier<'t>) -> Option<Status<'s>> {
// Skip hashing if we can
if !self.identifiers.is_empty() {
self.identifiers
.get(ident.token())
.map(|c| c.borrow())
.or_else(|| self.inner.correct_ident(ident))
} else {
None
}
}
fn correct_word<'s, 't>(&'s self, word: typos::tokens::Word<'t>) -> Option<Status<'s>> {
if word.case() == typos::tokens::Case::None {
return None;
}
// Skip hashing if we can
let custom = if !self.words.is_empty() {
let w = UniCase::new(word.token());
// HACK: couldn't figure out the lifetime issue with replacing `cloned` with `borrow`
self.words.get(&w).cloned()
} else {
None
};
custom.or_else(|| self.inner.correct_word(word))
}
}
#[cfg(test)]
mod test {
use super::*;
#[cfg(feature = "dict")]
#[test]
fn test_dict_correct() {
let dict = BuiltIn::new(crate::config::Locale::default());
let correction = dict.correct_word(typos::tokens::Word::new_unchecked(
"finallizes",
typos::tokens::Case::Lower,
0,
));
assert_eq!(
correction,
Some(Status::Corrections(vec!["finalizes".into()]))
);
}
#[cfg(feature = "vars")]
#[test]
fn test_varcon_no_locale() {
let dict = BuiltIn::new(crate::config::Locale::En);
let correction = dict.correct_word(typos::tokens::Word::new_unchecked(
"finalizes",
typos::tokens::Case::Lower,
0,
));
assert_eq!(correction, None);
}
#[cfg(feature = "vars")]
#[test]
fn test_varcon_same_locale() {
let dict = BuiltIn::new(crate::config::Locale::EnUs);
let correction = dict.correct_word(typos::tokens::Word::new_unchecked(
"finalizes",
typos::tokens::Case::Lower,
0,
));
assert_eq!(correction, Some(Status::Valid));
}
#[cfg(feature = "vars")]
#[test]
fn test_varcon_different_locale() {
let dict = BuiltIn::new(crate::config::Locale::EnGb);
let correction = dict.correct_word(typos::tokens::Word::new_unchecked(
"finalizes",
typos::tokens::Case::Lower,
0,
));
assert_eq!(
correction,
Some(Status::Corrections(vec!["finalises".into()]))
);
}
#[cfg(all(feature = "dict", feature = "vars"))]
#[test]
fn test_dict_to_varcon() {
let dict = BuiltIn::new(crate::config::Locale::EnGb);
let correction = dict.correct_word(typos::tokens::Word::new_unchecked(
"finallizes",
typos::tokens::Case::Lower,
0,
));
assert_eq!(
correction,
Some(Status::Corrections(vec!["finalises".into()]))
);
}
#[test]
fn test_case_correct() {
let cases = [
("foo", Case::Lower, "foo"),
("foo", Case::None, "foo"),
("foo", Case::Title, "Foo"),
("foo", Case::Upper, "FOO"),
("fOo", Case::None, "fOo"),
];
for (correction, case, expected) in cases.iter() {
let mut actual = Cow::Borrowed(*correction);
case_correct(&mut actual, *case);
assert_eq!(*expected, actual);
let mut actual = Cow::Owned(String::from(*correction));
case_correct(&mut actual, *case);
assert_eq!(*expected, actual);
}
}
}