Respect word boundaries when detecting function signature in docs (#13388)

## Summary

Closes https://github.com/astral-sh/ruff/issues/13242.
This commit is contained in:
Charlie Marsh 2024-09-18 00:01:38 -04:00 committed by GitHub
parent dcfebaa4a8
commit 70748950ae
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 46 additions and 1 deletions

View file

@ -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"))]

View file

@ -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

View file

@ -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
|