Skip to content

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

fix: further issues with multiline comments due to improper newline handling

Elijah Potter75a1af6dd127
diff --git a/harper-cli/src/main.rs b/harper-cli/src/main.rs
index 6fd172fc2..7705f4d1c 100644
--- a/harper-cli/src/main.rs
+++ b/harper-cli/src/main.rs
@@ -75,7 +75,7 @@ fn main() -> anyhow::Result<()> {
let (doc, _) = load_file(&file)?;
for token in doc.tokens() {
- dbg!(token);
+ println!("{:?}", token);
}
Ok(())
diff --git a/harper-core/src/document.rs b/harper-core/src/document.rs
index af5a61c8e..c8ce19ccd 100644
--- a/harper-core/src/document.rs
+++ b/harper-core/src/document.rs
@@ -1,4 +1,5 @@
use std::cmp::Ordering;
+use std::collections::VecDeque;
use std::fmt::Display;
use itertools::Itertools;
@@ -55,6 +56,7 @@ impl Document {
/// Should be run after every change to the underlying [`Self::source`].
fn parse(&mut self) {
self.tokens = self.parser.parse(&self.source);
+ self.condense_newlines();
self.condense_contractions();
self.condense_number_suffixes();
self.match_quotes();
@@ -282,6 +284,44 @@ impl Document {
self.condense_indices(&replace_starts, 2);
}
+ /// Searches for multiple sequential newline tokens and condenses them down
+ /// into one.
+ fn condense_newlines(&mut self) {
+ let mut cursor = 0;
+ let copy = self.tokens.clone();
+
+ let mut remove_these = VecDeque::new();
+
+ while cursor < self.tokens.len() {
+ // Locate a stretch of one or more newline tokens.
+ let start_tok = &mut self.tokens[cursor];
+
+ if let TokenKind::Newline(start_count) = &mut start_tok.kind {
+ loop {
+ cursor += 1;
+
+ if cursor >= copy.len() {
+ break;
+ }
+
+ let child_tok = &copy[cursor];
+ if let TokenKind::Newline(n) = child_tok.kind {
+ *start_count += n;
+ start_tok.span.end = child_tok.span.end;
+ remove_these.push_back(cursor);
+ cursor += 1;
+ } else {
+ break;
+ };
+ }
+ }
+
+ cursor += 1;
+ }
+
+ remove_indices(&mut self.tokens, remove_these);
+ }
+
/// Searches for contractions and condenses them down into single
/// tokens.
fn condense_contractions(&mut self) {
@@ -404,9 +444,35 @@ fn is_sentence_terminator(token: &TokenKind) -> bool {
}
}
+/// Removes a list of indices from a Vector.
+/// Assumes that the provided indices are already in sorted order.
+fn remove_indices<T>(vec: &mut Vec<T>, mut to_remove: VecDeque<usize>) {
+ let mut i = 0;
+
+ let mut next_remove = to_remove.pop_front();
+
+ vec.retain(|_| {
+ let keep = if let Some(next_remove) = next_remove {
+ i != next_remove
+ } else {
+ true
+ };
+
+ if !keep {
+ next_remove = to_remove.pop_front();
+ }
+
+ i += 1;
+ keep
+ });
+}
+
#[cfg(test)]
mod tests {
+ use std::collections::{vec_deque, VecDeque};
+
use super::Document;
+ use crate::document::remove_indices;
use crate::parsers::{Markdown, PlainEnglish};
use crate::token::TokenStringExt;
use crate::{Span, Token, TokenKind};
@@ -441,8 +507,7 @@ mod tests {
let markdown_parser = Markdown;
let document = Document::new(text, Box::new(markdown_parser));
- // We add one because the Markdown parser inserts a newline at end-of-input.
- assert_eq!(document.tokens.len(), final_tok_count + 1);
+ assert_eq!(document.tokens.len(), final_tok_count);
}
#[test]
@@ -499,4 +564,14 @@ mod tests {
18
);
}
+
+ #[test]
+ fn removes_requested_indices() {
+ let mut data: Vec<i32> = (0..10).collect();
+ let remove: VecDeque<usize> = vec![1, 4, 6].into_iter().collect();
+
+ remove_indices(&mut data, remove);
+
+ assert_eq!(data, vec![0, 2, 3, 5, 7, 8, 9])
+ }
}
diff --git a/harper-core/src/linting/matcher.rs b/harper-core/src/linting/matcher.rs
index 8b1c13775..bb88f9a4b 100644
--- a/harper-core/src/linting/matcher.rs
+++ b/harper-core/src/linting/matcher.rs
@@ -135,7 +135,7 @@ impl Matcher {
"hr" => "hour",
"w/o" => "without",
"w/" => "with",
- "wordlist" => "word list",
+ "wordlist" => "word list"
,
"the","challenged" => "that challenged",
"stdin" => "standard input",
"stdout" => "standard output",
diff --git a/harper-core/src/parsers/markdown.rs b/harper-core/src/parsers/markdown.rs
index dafdcaa4b..d36c3ccd0 100644
--- a/harper-core/src/parsers/markdown.rs
+++ b/harper-core/src/parsers/markdown.rs
@@ -100,6 +100,17 @@ impl Parser for Markdown {
}
}
+ if matches!(
+ tokens.last(),
+ Some(Token {
+ kind: TokenKind::Newline(_),
+ ..
+ })
+ ) && source.last() != Some(&'\n')
+ {
+ tokens.pop();
+ }
+
tokens
}
}
@@ -115,4 +126,17 @@ mod tests {
Markdown.parse_str(source);
}
+
+ /// Check whether the Markdown parser will emit a breaking newline
+ /// at the end of each input.
+ ///
+ /// It should _not_ do this.
+ #[test]
+ fn ends_with_newline() {
+ let source = "This is a test.";
+
+ let tokens = Markdown.parse_str(source);
+ assert_ne!(tokens.len(), 0);
+ assert!(!tokens.last().unwrap().kind.is_newline());
+ }
}
diff --git a/harper-core/src/parsers/mod.rs b/harper-core/src/parsers/mod.rs
index 98ed7a586..17cbfa3cc 100644
--- a/harper-core/src/parsers/mod.rs
+++ b/harper-core/src/parsers/mod.rs
@@ -87,8 +87,7 @@ mod tests {
Space(1),
Word,
Space(1),
- Word,
- Newline(2)
+ Word
]
);
}
@@ -105,8 +104,7 @@ mod tests {
Newline(2),
Word,
Space(1),
- Word,
- Newline(2)
+ Word
]
);
}
diff --git a/harper-core/src/token.rs b/harper-core/src/token.rs
index 424b4d47c..9198fe365 100644
--- a/harper-core/src/token.rs
+++ b/harper-core/src/token.rs
@@ -13,6 +13,10 @@ pub struct Token {
}
impl Token {
+ pub fn new(span: Span, kind: TokenKind) -> Self {
+ Self { span, kind }
+ }
+
/// Convert to an allocated [`FatToken`].
pub fn to_fat(&self, source: &[char]) -> FatToken {
let content = self.span.get_content(source).to_vec();
diff --git a/harper-tree-sitter/src/comment_parsers/go.rs b/harper-tree-sitter/src/comment_parsers/go.rs
index 8441f77ca..37ac0c354 100644
--- a/harper-tree-sitter/src/comment_parsers/go.rs
+++ b/harper-tree-sitter/src/comment_parsers/go.rs
@@ -1,14 +1,14 @@
use harper_core::parsers::{Markdown, Parser};
use harper_core::Token;
-use super::without_intiators;
+use super::without_initiators;
#[derive(Debug, Clone, Copy)]
pub struct Go;
impl Parser for Go {
fn parse(&mut self, source: &[char]) -> Vec<Token> {
- let mut actual = without_intiators(source);
+ let mut actual = without_initiators(source);
let mut actual_source = actual.get_content(source);
if matches!(actual_source, ['g', 'o', ':', ..]) {
diff --git a/harper-tree-sitter/src/comment_parsers/mod.rs b/harper-tree-sitter/src/comment_parsers/mod.rs
index b5422ad83..37965327d 100644
--- a/harper-tree-sitter/src/comment_parsers/mod.rs
+++ b/harper-tree-sitter/src/comment_parsers/mod.rs
@@ -7,19 +7,19 @@ pub use unit::Unit;
/// Get the span of a tree-sitter-produced comment that doesn't include the
/// comment openers and closers.
-fn without_intiators(source: &[char]) -> Span {
+fn without_initiators(source: &[char]) -> Span {
// Skip over the comment start characters
let actual_start = source
.iter()
- .position(|c| !is_comment_character(*c))
- .unwrap_or(0);
+ .position(|c| !is_comment_character(*c) && !c.is_whitespace())
+ .unwrap_or(source.len());
// Chop off the end
let actual_end = source.len()
- source
.iter()
.rev()
- .position(|c| !is_comment_character(*c))
+ .position(|c| !is_comment_character(*c) && !c.is_whitespace())
.unwrap_or(0);
Span::new(actual_start, actual_end)
@@ -28,3 +28,20 @@ fn without_intiators(source: &[char]) -> Span {
fn is_comment_character(c: char) -> bool {
matches!(c, '#' | '-' | '/' | '*')
}
+
+#[cfg(test)]
+mod tests {
+ use super::without_initiators;
+
+ #[test]
+ fn cleans_empty_comment() {
+ let source: Vec<_> = "///".chars().collect();
+ assert_eq!(without_initiators(&source).len(), 0);
+ }
+
+ #[test]
+ fn cleans_empty_comment_with_whitespace() {
+ let source: Vec<_> = "/// ".chars().collect();
+ assert_eq!(without_initiators(&source).len(), 0);
+ }
+}
diff --git a/harper-tree-sitter/src/comment_parsers/unit.rs b/harper-tree-sitter/src/comment_parsers/unit.rs
index 24a16d2b6..359bb2653 100644
--- a/harper-tree-sitter/src/comment_parsers/unit.rs
+++ b/harper-tree-sitter/src/comment_parsers/unit.rs
@@ -1,7 +1,7 @@
use harper_core::parsers::{Markdown, Parser};
use harper_core::Token;
-use super::without_intiators;
+use super::without_initiators;
/// A comment parser that strips starting `/` and `*` characters.
///
@@ -13,7 +13,12 @@ pub struct Unit;
impl Parser for Unit {
fn parse(&mut self, source: &[char]) -> Vec<Token> {
- let actual = without_intiators(source);
+ let actual = without_initiators(source);
+
+ if actual.is_empty() {
+ return Vec::new();
+ }
+
let source = actual.get_content(source);
let mut markdown_parser = Markdown;
diff --git a/harper-tree-sitter/src/tree_sitter_parser.rs b/harper-tree-sitter/src/tree_sitter_parser.rs
index d8115b14d..7ac5fee57 100644
--- a/harper-tree-sitter/src/tree_sitter_parser.rs
+++ b/harper-tree-sitter/src/tree_sitter_parser.rs
@@ -158,28 +158,15 @@ impl Parser for TreeSitterParser {
byte_spans_to_char_spans(&mut comments_spans, &text);
- dbg!(comments_spans
- .iter()
- .map(|span| span.get_content_string(text.chars().collect::<Vec<_>>().as_slice()))
- .collect::<Vec<_>>());
-
let mut tokens = Vec::new();
- for (s_index, span) in comments_spans.iter().enumerate() {
+ for span in comments_spans.iter() {
let mut new_tokens = self.comment_parser.parse(span.get_content(source));
new_tokens
.iter_mut()
.for_each(|v| v.span.push_by(span.start));
- // The comment parser will insert a newline at end-of-input.
- // If the next tree-sitter chunk is a comment, we want to remove that.
- if let Some(next_start) = comments_spans.get(s_index + 1).map(|v| v.start) {
- if is_span_whitespace(Span::new(span.end, next_start), source) {
- new_tokens.pop();
- }
- }
-
// Same goes for newlines within the comment
for t in new_tokens.iter_mut() {
if let TokenKind::Newline(n) = &mut t.kind {
@@ -188,21 +175,21 @@ impl Parser for TreeSitterParser {
}
tokens.append(&mut new_tokens);
+
+ // Insert a newline manually since we didn't pass the last one (if it existed)
+ // to the comment parser.
+ if let Some(last) = tokens.last() {
+ tokens.push(Token::new(
+ Span::new_with_len(last.span.end, 1),
+ TokenKind::Newline(1)
+ ));
+ }
}
tokens
}
}
-/// Check if the contents of a span is just white-space.
-fn is_span_whitespace(span: Span, source: &[char]) -> bool {
- span.get_content(source)
- .iter()
- .filter(|c| !c.is_whitespace())
- .count()
- == 0
-}
-
/// Converts a set of byte-indexed [`Span`]s to char-index Spans, in-place.
/// NOTE: Will sort the given slice by their [`Span::start`].
///
diff --git a/harper-tree-sitter/tests/language_support.rs b/harper-tree-sitter/tests/language_support.rs
index d730f1e75..b31f0a078 100644
--- a/harper-tree-sitter/tests/language_support.rs
+++ b/harper-tree-sitter/tests/language_support.rs
@@ -36,3 +36,4 @@ macro_rules! create_test {
create_test!(multiline_comments.cpp, 3);
create_test!(multiline_comments.ts, 3);
+create_test!(clean.rs, 0);
diff --git a/harper-tree-sitter/tests/language_support_sources/clean.rs b/harper-tree-sitter/tests/language_support_sources/clean.rs
new file mode 100644
index 000000000..3eab8feae
--- /dev/null
+++ b/harper-tree-sitter/tests/language_support_sources/clean.rs
@@ -0,0 +1,24 @@
+/// This is an example Rust file that should produce no Harper lints.
+
+struct TestStruct {}
+
+impl TestStruct {
+ /// This is a test function.
+ /// It has a [link](https://example.com) embedded inside
+ fn test_function() {}
+
+ /// This is another test function.
+ /// It has another [link](https://example.com) embedded inside
+ fn test_function() {}
+
+ /// This is some gibberish to try to trigger a lint for sentences that continue for too long
+ ///
+ /// This is some gibberish to try to trigger a lint for sentences that continue for too long
+ ///
+ /// This is some gibberish to try to trigger a lint for sentences that continue for too long
+ ///
+ /// This is some gibberish to try to trigger a lint for sentences that continue for too long
+ ///
+ /// This is some gibberish to try to trigger a lint for sentences that continue for too long
+}
+
diff --git a/yarn.lock b/yarn.lock
new file mode 100644
index 000000000..fb57ccd13
--- /dev/null
+++ b/yarn.lock
@@ -0,0 +1,4 @@
+# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
+# yarn lockfile v1
+
+