Skip to content

Commit

Permalink
Respect word boundaries when detecting function signature in docs
Browse files Browse the repository at this point in the history
  • Loading branch information
charliermarsh committed Sep 18, 2024
1 parent dcfebaa commit 8e9d6b7
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 1 deletion.
8 changes: 8 additions & 0 deletions crates/ruff_linter/resources/test/fixtures/pydocstyle/D402.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def foo():
"""Returns foo()."""

def foo():
""""Use prefix_foo()."""

def foo():
""""Use this function; foo()."""
1 change: 1 addition & 0 deletions crates/ruff_linter/src/rules/pydocstyle/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ mod tests {
#[test_case(Rule::OverIndentation, Path::new("D.py"))]
#[test_case(Rule::OverIndentation, Path::new("D208.py"))]
#[test_case(Rule::NoSignature, Path::new("D.py"))]
#[test_case(Rule::NoSignature, Path::new("D402.py"))]
#[test_case(Rule::SurroundingWhitespace, Path::new("D.py"))]
#[test_case(Rule::DocstringStartsWithThis, Path::new("D.py"))]
#[test_case(Rule::UnderIndentation, Path::new("D.py"))]
Expand Down
20 changes: 19 additions & 1 deletion crates/ruff_linter/src/rules/pydocstyle/rules/no_signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,25 @@ pub(crate) fn no_signature(checker: &mut Checker, docstring: &Docstring) {
// a function named `foo`).
if first_line
.match_indices(function.name.as_str())
.any(|(index, _)| first_line[index + function.name.len()..].starts_with('('))
.any(|(index, _)| {
// The function name must be preceded by a word boundary.
let preceded_by_word_boundary = first_line[..index]
.chars()
.next_back()
.map_or(true, |c| matches!(c, ' ' | '\t' | ';' | ','));
if !preceded_by_word_boundary {
return false;
}

// The function name must be followed by an open parenthesis.
let followed_by_open_parenthesis =
first_line[index + function.name.len()..].starts_with('(');
if !followed_by_open_parenthesis {
return false;
}

true
})
{
checker
.diagnostics
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
source: crates/ruff_linter/src/rules/pydocstyle/mod.rs
---
D402.py:2:5: D402 First line should not be the function's signature
|
1 | def foo():
2 | """Returns foo()."""
| ^^^^^^^^^^^^^^^^^^^^ D402
3 |
4 | def foo():
|

D402.py:8:5: D402 First line should not be the function's signature
|
7 | def foo():
8 | """"Use this function; foo()."""
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ D402
|

0 comments on commit 8e9d6b7

Please sign in to comment.