-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpunctuation.rs
365 lines (309 loc) · 11.7 KB
/
punctuation.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
364
365
//! Typographical mistakes related to punctuation.
//!
//! Here is a list of typos it can find:
//! - [A space *before* a punctuation mark](`TypoSpaceBeforePunctuationMarks`)
use std::ops::Range;
use miette::{Diagnostic, SourceSpan};
use thiserror::Error;
use winnow::ascii::{alphanumeric1, digit1};
use winnow::combinator::{alt, delimited, not, preceded, repeat, repeat_till, terminated};
use winnow::error::InputError;
use winnow::token::{none_of, one_of, take};
use winnow::{LocatingSlice, Parser};
use super::{Fix, SharedSource};
use super::{Rule, Typo};
/// A space *before* a punctuation mark has been detected.
///
/// In English and German typography, one must not put a space before a colon (`:`),
/// a semicolon (`;`), a question mark (`?`), an exclamation mark (`!`),
/// or an interrobang (`‽`).
///
/// # Examples
///
/// Here is a list of mistakes that trigger this rule:
/// - `Oh no !`, should be `Oh no!`
/// - `here is a list of things :`, should be `here is a list of things:`
#[derive(Error, Debug, Diagnostic)]
#[error("In English typography there is no space before a punctuation mark")]
#[diagnostic(code("typope::space-before-punctuation-mark"), url(docsrs))]
pub struct TypoSpaceBeforePunctuationMarks {
#[source_code]
src: Option<SharedSource>,
#[label("Invalid space here")]
span: SourceSpan,
#[help]
help: String,
}
impl TypoSpaceBeforePunctuationMarks {
fn new(span: impl Into<SourceSpan>, punctuation_mark: char) -> Self {
Self {
src: None,
span: span.into(),
help: format!("remove the space before `{punctuation_mark}`"),
}
}
}
impl Typo for TypoSpaceBeforePunctuationMarks {
fn span(&self) -> SourceSpan {
self.span
}
fn with_source(&mut self, src: SharedSource, offset: usize) {
self.src = Some(src);
self.span = (self.span.offset() + offset, self.span.len()).into();
}
fn fix(&self) -> Fix {
Fix::Remove { span: self.span }
}
}
/// A rule that detects typographical mistakes related to punctuation.
///
/// Currently, it can only find and generate the following typo: [`TypoSpaceBeforePunctuationMarks`].
pub struct Punctuation;
impl Rule for Punctuation {
#[allow(clippy::type_complexity)]
fn check(&self, bytes: &[u8]) -> Vec<Box<dyn Typo>> {
fn space_before_colon<'s>(
input: &mut LocatingSlice<&'s [u8]>,
) -> Result<(char, Range<usize>), InputError<LocatingSlice<&'s [u8]>>> {
let (_space, range) =
delimited(none_of([' ', '>']), ' '.with_span(), ':').parse_next(input)?;
// Handles cases when we have an emoji like `:fire:` or `:)`.
// In such cases, we should not mark them as a typo.
not(none_of([' '])).parse_next(input)?;
Ok((':', range))
}
fn space_before_exclamation_mark<'s>(
input: &mut LocatingSlice<&'s [u8]>,
) -> Result<(char, Range<usize>), InputError<LocatingSlice<&'s [u8]>>> {
let (_space, range) =
delimited(none_of([' ', '&', '=', '>', '|']), ' '.with_span(), '!')
.parse_next(input)?;
// Do not mark such a string `x != y` as a typo
not('=').parse_next(input)?;
not('(').parse_next(input)?;
// Do not mark strings like ` !Send` as a typo: it has a meaning in Rust
not(alt(("Send", "Sync"))).parse_next(input)?;
// A string might contain some kind of shell script like `[ ! -e /some/file ]`
// See `man test` for the possible options.
not(preceded(
" -",
alt((
one_of('b'..='h'),
one_of([
'G', 'k', 'L', 'N', 'O', 'p', 'r', 's', 'S', 't', 'u', 'w', 'x',
]),
)),
))
.parse_next(input)?;
// Can be found in code generating C macros (e.g., `#elif !defined(condition)`)
not("defined(").parse_next(input)?;
Ok(('!', range))
}
fn space_before_question_mark<'s>(
input: &mut LocatingSlice<&'s [u8]>,
) -> Result<(char, Range<usize>), InputError<LocatingSlice<&'s [u8]>>> {
let (_space, range) =
delimited(none_of([' ']), ' '.with_span(), '?').parse_next(input)?;
// Do not mark strings like ` ?Sized` as a typo: it has a meaning in Rust
not("Sized").parse_next(input)?;
// Can be found in a text that gives an example of the parameters to use in a URL (e.g., `add ?param=2¶m2=40 to the URL`)
not(terminated(alphanumeric1, '=')).parse_next(input)?;
// Can be found in SQL queries (e.g., `SELECT a FROM b WHERE c = ?1 AND d = ?2`)
// See <https://www.sqlite.org/c3ref/bind_blob.html>
not(digit1).parse_next(input)?;
Ok(('?', range))
}
fn space_before_char<'s, const C: char>(
input: &mut LocatingSlice<&'s [u8]>,
) -> Result<(char, Range<usize>), InputError<LocatingSlice<&'s [u8]>>> {
let (_space, range) = terminated(' '.with_span(), C).parse_next(input)?;
Ok((C, range))
}
fn space_before_punctuation<'s>(
input: &mut LocatingSlice<&'s [u8]>,
) -> Result<(char, Range<usize>), InputError<LocatingSlice<&'s [u8]>>> {
alt((
space_before_colon,
space_before_exclamation_mark,
space_before_question_mark,
space_before_char::<'‽'>,
space_before_char::<'⸘'>,
))
.parse_next(input)
}
fn locate_space_before_punctuation<'s>(
input: &mut LocatingSlice<&'s [u8]>,
) -> Result<Box<dyn Typo>, InputError<LocatingSlice<&'s [u8]>>> {
let (_, (punctuation_mark, range)): (Vec<u8>, (char, Range<usize>)) = repeat_till(
1..,
take::<_, _, InputError<_>>(1usize),
space_before_punctuation,
)
.parse_next(input)?;
// We only mark the space that is invalid not the rest
let span = (range.start, 1);
Ok(Box::new(TypoSpaceBeforePunctuationMarks::new(
span,
punctuation_mark,
)))
}
repeat(0.., locate_space_before_punctuation)
.parse_next(&mut LocatingSlice::new(bytes))
.unwrap_or_default()
}
}
#[cfg(test)]
mod tests {
use crate::lint::{Rule, SharedSource};
use super::Punctuation;
#[test]
fn empty() {
assert!(Punctuation.check(br"").is_empty());
}
#[test]
fn space_after_colon() {
let typos = Punctuation.check(br"test: foobar");
assert!(typos.is_empty());
}
#[test]
fn typo_colon() {
let mut typos = Punctuation.check(br"test : foobar");
let typo = typos.pop().unwrap();
assert_eq!(typo.span(), (4, 1).into());
assert!(typos.is_empty());
}
#[test]
fn typo_question_mark() {
let mut typos = Punctuation.check(br"footest ? foobar ?fooooo");
let typo = typos.pop().unwrap();
assert_eq!(typo.span(), (16, 1).into());
let typo = typos.pop().unwrap();
assert_eq!(typo.span(), (7, 1).into());
assert!(typos.is_empty());
}
#[test]
fn typo_exclamation_mark() {
let mut typos = Punctuation.check(br"footest ! barfoobar");
let typo = typos.pop().unwrap();
assert_eq!(typo.span(), (7, 1).into());
assert!(typos.is_empty());
}
#[test]
fn typo_exclamation_mark_repeated() {
let mut typos = Punctuation.check(br"footest !!!! barfoobar");
let typo = typos.pop().unwrap();
assert_eq!(typo.span(), (7, 1).into());
assert!(typos.is_empty());
}
#[test]
fn typo_neq() {
assert!(Punctuation.check(br"maybe 0 != 1?").is_empty());
}
#[test]
fn typo_before_end_of_line() {
let mut typos = Punctuation.check(br"footest !");
let typo = typos.pop().unwrap();
assert_eq!(typo.span(), (7, 1).into());
assert!(typos.is_empty());
let mut typos = Punctuation.check(br"footest ?");
let typo = typos.pop().unwrap();
assert_eq!(typo.span(), (7, 1).into());
assert!(typos.is_empty());
let mut typos = Punctuation.check(br"footest :");
let typo = typos.pop().unwrap();
assert_eq!(typo.span(), (7, 1).into());
assert!(typos.is_empty());
}
#[test]
fn multiple_typos() {
let mut typos = Punctuation.check(br"footest ! barfoobar : oh no ?");
let typo = typos.pop().unwrap();
assert_eq!(typo.span(), (27, 1).into());
let typo = typos.pop().unwrap();
assert_eq!(typo.span(), (19, 1).into());
let typo = typos.pop().unwrap();
assert_eq!(typo.span(), (7, 1).into());
assert!(typos.is_empty());
}
#[test]
fn typo_colon_multiple_spaces() {
let typos = Punctuation.check(br"test : foobar");
assert!(typos.is_empty());
}
#[test]
fn typo_rust_sized() {
let typos = Punctuation.check(br"test: ?Sized foobar");
assert!(typos.is_empty());
}
#[test]
fn emoji() {
assert!(Punctuation.check(br":waving_hand:").is_empty());
assert!(Punctuation.check(br"footest :fire: bar").is_empty());
assert!(Punctuation.check(br"foobar :)").is_empty());
assert!(Punctuation.check(br":D").is_empty());
assert!(Punctuation.check(br" :> ").is_empty());
assert!(Punctuation.check(br"foo :'( bar").is_empty());
}
#[test]
fn typo_source() {
let source = r#""test : foobar""#;
let mut typos = Punctuation.check(source.trim_matches('"').as_bytes());
let mut typo = typos.pop().unwrap();
assert_eq!(typo.span(), (4, 1).into());
let source = SharedSource::new("fake.rs", source.to_owned().into_bytes());
typo.with_source(source, 1);
assert_eq!(typo.span(), (5, 1).into());
assert!(typos.is_empty());
}
#[test]
fn interrobang() {
assert!(Punctuation.check(r"test‽".as_bytes()).is_empty());
assert!(Punctuation.check(br"test?!").is_empty());
assert!(Punctuation.check(br"test!?").is_empty());
assert!(Punctuation.check(r"test⸘".as_bytes()).is_empty());
let mut typos = Punctuation.check(r"test ‽".as_bytes());
let typo = typos.pop().unwrap();
assert_eq!(typo.span(), (4, 1).into());
assert!(typos.is_empty());
let mut typos = Punctuation.check(r"test ?! abc ⸘".as_bytes());
let typo = typos.pop().unwrap();
assert_eq!(typo.span(), (11, 1).into());
let typo = typos.pop().unwrap();
assert_eq!(typo.span(), (4, 1).into());
assert!(typos.is_empty());
}
#[test]
fn looks_like_shell() {
assert!(Punctuation
.check(br"[ ! -e /run/dbus ] || mount -t tmpfs none /run/dbus")
.is_empty());
}
#[test]
fn looks_like_c_macro_generated() {
assert!(Punctuation
.check(br"# elif !defined(missing_arch_template)")
.is_empty());
}
#[test]
fn looks_like_url_parameter() {
assert!(Punctuation
.check(br"Add ?var=1&var2=44 to the URL")
.is_empty());
}
#[test]
fn sqlite_prepared_statement() {
assert!(Punctuation
.check(br"SELECT a FROM b WHERE c = ?1 AND d = ?2")
.is_empty());
}
#[test]
fn fn_return() {
assert!(Punctuation.check(br"fn() -> !").is_empty());
}
#[test]
fn condition() {
assert!(Punctuation
.check(br"a & !b & !c | !z or !(y | w)")
.is_empty());
}
}