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
use crate::expr::{Expr, ExprExt};
use blanket::blanket;
use crate::{Document, LSend, Token, TokenStringExt};
use super::{Lint, Linter};
pub trait DocumentIterator {
type Unit;
fn iter_units<'a>(document: &'a Document) -> Box<dyn Iterator<Item = &'a [Token]> + 'a>;
}
/// Process text in chunks (clauses between commas)
pub struct Chunk;
/// Process text in full sentences
pub struct Sentence;
impl DocumentIterator for Chunk {
type Unit = Chunk;
fn iter_units<'a>(document: &'a Document) -> Box<dyn Iterator<Item = &'a [Token]> + 'a> {
Box::new(document.iter_chunks())
}
}
impl DocumentIterator for Sentence {
type Unit = Sentence;
fn iter_units<'a>(document: &'a Document) -> Box<dyn Iterator<Item = &'a [Token]> + 'a> {
Box::new(document.iter_sentences())
}
}
/// A trait that searches for tokens that fulfil [`Expr`]s in a [`Document`].
///
/// Makes use of [`TokenStringExt::iter_chunks`] by default, or [`TokenStringExt::iter_sentences`] to process either
/// a chunk (clause) or a sentence at a time.
#[blanket(derive(Box))]
pub trait ExprLinter: LSend {
type Unit: DocumentIterator;
/// A simple getter for the expression you want Harper to search for.
fn expr(&self) -> &dyn Expr;
/// If any portions of a [`Document`] match [`Self::expr`], they are passed through [`ExprLinter::match_to_lint`]
/// or [`ExprLinter::match_to_lint_with_context`] to be transformed into a [`Lint`] for editor consumption.
///
/// Transform matched tokens into a [`Lint`] for editor consumption.
///
/// This is the simple version that only sees the matched tokens. For context-aware linting,
/// implement `match_to_lint_with_context` instead.
///
/// Return `None` to skip producing a lint for this match.
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
self.match_to_lint_with_context(matched_tokens, source, None)
}
/// Transform matched tokens into a [`Lint`] with access to surrounding context.
///
/// The context provides access to tokens before and after the match. When implementing
/// this method, you can call `self.match_to_lint()` as a fallback if the context isn't needed.
///
/// Return `None` to skip producing a lint for this match.
fn match_to_lint_with_context(
&self,
matched_tokens: &[Token],
source: &[char],
_context: Option<(&[Token], &[Token])>,
) -> Option<Lint> {
// Default implementation falls back to the simple version
self.match_to_lint(matched_tokens, source)
}
/// A user-facing description of what kinds of grammatical errors this rule looks for.
/// It is usually shown in settings menus.
fn description(&self) -> &str;
}
/// Helper function to find the only occurrence of a token matching a predicate
///
/// Returns `Some(token)` if exactly one token matches the predicate, `None` otherwise.
/// TODO: This can be used in the [`ThenThan`] linter when #1819 is merged.
pub fn find_the_only_token_matching<'a, F>(
tokens: &'a [Token],
source: &[char],
predicate: F,
) -> Option<&'a Token>
where
F: Fn(&Token, &[char]) -> bool,
{
find_the_only_token_index_matching(tokens, source, predicate).map(|idx| &tokens[idx])
}
/// Helper function to find the index of the only occurrence of a token matching a predicate.
///
/// Returns `Some(index)` if exactly one token matches the predicate, `None` otherwise.
pub fn find_the_only_token_index_matching<F>(
tokens: &[Token],
source: &[char],
predicate: F,
) -> Option<usize>
where
F: Fn(&Token, &[char]) -> bool,
{
let mut matches = tokens
.iter()
.enumerate()
.filter(|&(_, tok)| predicate(tok, source));
match (matches.next(), matches.next()) {
(Some((idx, _)), None) => Some(idx),
_ => None,
}
}
impl<L, U> Linter for L
where
L: ExprLinter<Unit = U>,
U: DocumentIterator,
{
fn lint(&mut self, document: &Document) -> Vec<Lint> {
let mut lints = Vec::new();
let source = document.get_source();
for unit in U::iter_units(document) {
lints.extend(run_on_chunk(self, unit, source));
}
lints
}
fn description(&self) -> &str {
self.description()
}
}
pub fn run_on_chunk<'a>(
linter: &'a impl ExprLinter,
unit: &'a [Token],
source: &'a [char],
) -> impl Iterator<Item = Lint> + 'a {
linter
.expr()
.iter_matches(unit, source)
.filter_map(|match_span| {
linter.match_to_lint_with_context(
&unit[match_span.start..match_span.end],
source,
Some((&unit[..match_span.start], &unit[match_span.end..])),
)
})
}
/// Check for sentence continuation after a matched span.
///
/// Validates that the "after" context starts with whitespace followed by a word token,
/// allowing flexible inspection of that word's properties (POS tags, etc.) via the predicate.
/// The predicate can be used to confirm matches, suppress false positives, or apply conditional logic.
///
/// Returns `false` if context is `None`, missing tokens, or the structure is malformed.
pub fn followed_by_word(
context: Option<(&[Token], &[Token])>,
predicate: impl Fn(&Token) -> bool,
) -> bool {
if let Some((_, after)) = context
&& let [ws, word, ..] = after
&& ws.kind.is_whitespace()
{
return predicate(word);
}
false
}
/// Check for a specific token type after a matched span.
///
/// Validates that the "after" context starts with a token that matches the predicate.
/// This is useful for checking for specific punctuation or other token types.
///
/// Returns `false` if context is `None`, missing tokens, or the structure is malformed.
pub fn followed_by_token(
context: Option<(&[Token], &[Token])>,
predicate: impl Fn(&Token) -> bool,
) -> bool {
context
.and_then(|(_, after)| after.first())
.is_some_and(predicate)
}
pub fn followed_by_hyphen(context: Option<(&[Token], &[Token])>) -> bool {
followed_by_token(context, |hy| hy.kind.is_hyphen())
}
/// Counterintuitively, a sentence includes the whitespace after
/// the sentence-final punctuation.
pub fn at_start_of_sentence(context: Option<(&[Token], &[Token])>) -> bool {
if let Some((before, _)) = context
&& (before.is_empty() || (before.len() == 1 && before[0].kind.is_whitespace()))
{
return true;
}
false
}
/// Check for sentence context immediately before a matched span.
///
/// Validates that the "before" context ends with a word token followed by whitespace,
/// allowing flexible inspection of that word's properties (POS tags, etc.) via the predicate.
/// The predicate can be used to confirm matches, suppress false positives, or apply conditional logic.
///
/// Returns `false` if context is `None`, missing tokens, or the structure is malformed.
pub fn preceded_by_word(
context: Option<(&[Token], &[Token])>,
predicate: impl Fn(&Token) -> bool,
) -> bool {
if let Some((before, _)) = context
&& let [.., word, ws] = before
&& ws.kind.is_whitespace()
{
return predicate(word);
}
false
}
/// Check for sentence context surrounding a matched span on both sides.
///
/// Validates that the "before" context ends with a word token followed by whitespace,
/// and the "after" context starts with whitespace followed by a word token, allowing
/// flexible inspection of both words' properties (POS tags, etc.) via the predicate.
/// The predicate can be used to confirm matches, suppress false positives, or apply conditional logic.
///
/// Returns `false` if context is `None`, missing tokens, or the structure is malformed.
pub fn surrounded_by_words(
context: Option<(&[Token], &[Token])>,
predicate: impl Fn(&Token, &Token) -> bool,
) -> bool {
if let Some((before, after)) = context
&& let [.., word_before, ws_before] = before
&& let [ws_after, word_after, ..] = after
&& ws_before.kind.is_whitespace()
&& ws_after.kind.is_whitespace()
{
return predicate(word_before, word_after);
}
false
}
#[cfg(test)]
mod tests_context {
use crate::expr::{Expr, FixedPhrase};
use crate::linting::expr_linter::{Chunk, Sentence};
use crate::linting::tests::assert_suggestion_result;
use crate::linting::{ExprLinter, Suggestion};
use crate::token_string_ext::TokenStringExt;
use crate::{Lint, Token};
pub struct TestSimpleLinter {
expr: Box<dyn Expr>,
}
impl Default for TestSimpleLinter {
fn default() -> Self {
Self {
expr: Box::new(FixedPhrase::from_phrase("two")),
}
}
}
impl ExprLinter for TestSimpleLinter {
type Unit = Chunk;
fn expr(&self) -> &dyn Expr {
&*self.expr
}
fn match_to_lint(&self, toks: &[Token], _src: &[char]) -> Option<Lint> {
Some(Lint {
span: toks.span()?,
message: "simple".to_owned(),
suggestions: vec![Suggestion::ReplaceWith(vec!['2'])],
..Default::default()
})
}
fn description(&self) -> &str {
"test linter"
}
}
pub struct TestContextLinter {
expr: Box<dyn Expr>,
}
impl Default for TestContextLinter {
fn default() -> Self {
Self {
expr: Box::new(FixedPhrase::from_phrase("two")),
}
}
}
impl ExprLinter for TestContextLinter {
type Unit = Chunk;
fn expr(&self) -> &dyn Expr {
&*self.expr
}
fn match_to_lint_with_context(
&self,
toks: &[Token],
src: &[char],
context: Option<(&[Token], &[Token])>,
) -> Option<Lint> {
if let Some((before, after)) = context {
let before = before.span()?.get_content_string(src);
let after = after.span()?.get_content_string(src);
let (message, suggestions) = if before.eq_ignore_ascii_case("one ")
&& after.eq_ignore_ascii_case(" three")
{
(
"ascending".to_owned(),
vec![Suggestion::ReplaceWith(vec!['>'])],
)
} else if before.eq_ignore_ascii_case("three ")
&& after.eq_ignore_ascii_case(" one")
{
(
"descending".to_owned(),
vec![Suggestion::ReplaceWith(vec!['<'])],
)
} else {
("dunno".to_owned(), vec![Suggestion::ReplaceWith(vec!['?'])])
};
return Some(Lint {
span: toks.span()?,
message,
suggestions,
..Default::default()
});
} else {
None
}
}
fn description(&self) -> &str {
"context linter"
}
}
pub struct TestSentenceLinter {
expr: Box<dyn Expr>,
}
impl Default for TestSentenceLinter {
fn default() -> Self {
Self {
expr: Box::new(FixedPhrase::from_phrase("two, two")),
}
}
}
impl ExprLinter for TestSentenceLinter {
type Unit = Sentence;
fn expr(&self) -> &dyn Expr {
self.expr.as_ref()
}
fn match_to_lint(&self, toks: &[Token], _src: &[char]) -> Option<Lint> {
Some(Lint {
span: toks.span()?,
message: "sentence".to_owned(),
suggestions: vec![Suggestion::ReplaceWith(vec!['2', '&', '2'])],
..Default::default()
})
}
fn description(&self) -> &str {
"sentence linter"
}
}
#[test]
fn simple_test_123() {
assert_suggestion_result("one two three", TestSimpleLinter::default(), "one 2 three");
}
#[test]
fn context_test_123() {
assert_suggestion_result("one two three", TestContextLinter::default(), "one > three");
}
#[test]
fn context_test_321() {
assert_suggestion_result("three two one", TestContextLinter::default(), "three < one");
}
#[test]
fn sentence_test_123() {
assert_suggestion_result(
"one, two, two, three",
TestSentenceLinter::default(),
"one, 2&2, three",
);
}
}