Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

feat: Add get_rel() to get a token relative to the end of a slice (#2461)

Andrew Dunbar81b633d1c712
diff --git a/harper-core/src/linting/good_at.rs b/harper-core/src/linting/good_at.rs
index 69ec34648..23b2d5618 100644
--- a/harper-core/src/linting/good_at.rs
+++ b/harper-core/src/linting/good_at.rs
@@ -1,5 +1,5 @@
use crate::{
- Lint, Token,
+ Lint, Token, TokenStringExt,
expr::{Expr, FirstMatchOf, SequenceExpr},
linting::{ExprLinter, LintKind, Suggestion, expr_linter::Chunk},
patterns::{InflectionOfBe, WordSet},
@@ -80,9 +80,7 @@ impl ExprLinter for GoodAt {
}
fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {
- let prep_idx = toks.len() - 3;
- let prep_tok = &toks[prep_idx];
- let prep_span = prep_tok.span;
+ let prep_span = toks.get_rel(-3)?.span;
Some(Lint {
span: prep_span,
diff --git a/harper-core/src/linting/open_the_light.rs b/harper-core/src/linting/open_the_light.rs
index e2381120a..a85fc210e 100644
--- a/harper-core/src/linting/open_the_light.rs
+++ b/harper-core/src/linting/open_the_light.rs
@@ -68,8 +68,7 @@ impl ExprLinter for OpenTheLight {
fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {
// If I try to do this in the Pattern, the shorter pattern matches, without the context token.
if toks.len() == 7 {
- let device_tok = &toks[toks.len() - 3];
- let context_tok = &toks[toks.len() - 1];
+ let (device_tok, context_tok) = (toks.get_rel(-3)?, toks.get_rel(-1)?);
// The device word is part of compound noun if it's singular and followed by another noun
if !device_tok.kind.is_plural_noun() || !context_tok.kind.is_noun() {
return None;
diff --git a/harper-core/src/linting/pronoun_inflection_be.rs b/harper-core/src/linting/pronoun_inflection_be.rs
index b76b7f0c5..cbf3b50d3 100644
--- a/harper-core/src/linting/pronoun_inflection_be.rs
+++ b/harper-core/src/linting/pronoun_inflection_be.rs
@@ -2,7 +2,7 @@ use harper_brill::UPOS;
use crate::expr::{All, AnchorStart, Expr, ExprMap, SequenceExpr};
use crate::patterns::{NominalPhrase, UPOSSet};
-use crate::{Lrc, Token, TokenKind};
+use crate::{Lrc, Token, TokenKind, TokenStringExt};
use super::Suggestion;
use super::{ExprLinter, Lint, LintKind};
@@ -150,7 +150,7 @@ impl ExprLinter for PronounInflectionBe {
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
- let span = matched_tokens.get(matched_tokens.len() - 3)?.span;
+ let span = matched_tokens.get_rel(-3)?.span;
// Determine the correct inflection of "be".
let correct = self.map.lookup(0, matched_tokens, source)?;
diff --git a/harper-core/src/linting/spaces.rs b/harper-core/src/linting/spaces.rs
index 34082b479..d51954d24 100644
--- a/harper-core/src/linting/spaces.rs
+++ b/harper-core/src/linting/spaces.rs
@@ -51,11 +51,10 @@ impl Linter for Spaces {
..
}
]
- ) {
+ ) && let Some(space) = sentence.get_rel(-2)
+ {
output.push(Lint {
- span: sentence[sentence.len() - 2..sentence.len() - 1]
- .span()
- .unwrap(),
+ span: space.span,
lint_kind: LintKind::Formatting,
suggestions: vec![Suggestion::Remove],
message: "Unnecessary space at the end of the sentence.".to_string(),
diff --git a/harper-core/src/token_string_ext.rs b/harper-core/src/token_string_ext.rs
index 5a510e5f0..20e6753bb 100644
--- a/harper-core/src/token_string_ext.rs
+++ b/harper-core/src/token_string_ext.rs
@@ -90,6 +90,41 @@ pub trait TokenStringExt: private::Sealed {
create_decl_for!(word_like);
create_decl_for!(heading_start);
+ /// Get a reference to a token by index, with negative numbers counting from the end.
+ ///
+ /// # Examples
+ /// ```
+ /// # use harper_core::{Token, TokenStringExt, parsers::{Parser, PlainEnglish}};
+ /// # fn main() {
+ /// let source = "The cat sat on the mat.".chars().collect::<Vec<_>>();
+ /// let tokens = PlainEnglish.parse(&source);
+ /// assert_eq!(tokens.get_rel(0).unwrap().span.get_content_string(&source), "The");
+ /// assert_eq!(tokens.get_rel(1).unwrap().kind.is_whitespace(), true);
+ /// assert_eq!(tokens.get_rel(-1).unwrap().kind.is_punctuation(), true);
+ /// assert_eq!(tokens.get_rel(-2).unwrap().span.get_content_string(&source), "mat");
+ /// # }
+ /// ```
+ ///
+ /// # Returns
+ ///
+ /// * `Some(&Token)` - If the index is in bounds
+ /// * `None` - If the index is out of bounds
+ fn get_rel(&self, index: isize) -> Option<&Token>
+ where
+ Self: AsRef<[Token]>,
+ {
+ let slice = self.as_ref();
+ let len = slice.len() as isize;
+
+ if index >= len || -index > len {
+ return None;
+ }
+
+ let idx = if index >= 0 { index } else { len + index } as usize;
+
+ slice.get(idx)
+ }
+
fn iter_linking_verb_indices(&self) -> impl Iterator<Item = usize> + '_;
fn iter_linking_verbs(&self) -> impl Iterator<Item = &Token> + '_;