-
-
Notifications
You must be signed in to change notification settings - Fork 421
feat: forbid redundant trailing colon in slice (fixes #1071) #3642
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
f1sherFM
wants to merge
2
commits into
wemake-services:master
Choose a base branch
from
f1sherFM:fix-issue-1071
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
69 changes: 69 additions & 0 deletions
69
tests/test_visitors/test_tokenize/test_subscripts/test_redundant_trailing_slice.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| import pytest | ||
|
|
||
| from wemake_python_styleguide.violations.consistency import ( | ||
| RedundantTrailingSliceViolation, | ||
| ) | ||
| from wemake_python_styleguide.visitors.tokenize.subscripts import ( | ||
| RedundantTrailingSliceVisitor, | ||
| ) | ||
|
|
||
| # Wrong: | ||
| trailing_colon_cases = [ | ||
| 'a[1:4:]', | ||
| 'a[1::]', | ||
| 'a[:4:]', | ||
| 'a[None::]', | ||
| 'a[1:None:]', | ||
| 'a[1 + 2::]', | ||
| ] | ||
|
|
||
| # Correct: | ||
| correct_cases = [ | ||
| 'a[1:4]', | ||
| 'a[1:]', | ||
| 'a[:4]', | ||
| 'a[::]', # caught by NonStrictSliceOperationsViolation | ||
| 'a[1:4:5]', | ||
| 'a[1:4:None]', | ||
| 'a[1]', | ||
| 'a[1:4:1]', # caught by RedundantSubscriptViolation, not ours | ||
| 'a[b[1:4:5]]', # nested valid slice | ||
| 'a[b[1:4:]]', # nested invalid — should flag inner | ||
| 'a[{1: 2}]', # dict literal inside subscript | ||
| 'a[(1, 2)]', # tuple inside subscript | ||
| 'a[lambda x: x]', # lambda inside subscript | ||
| ] | ||
|
|
||
|
|
||
| @pytest.mark.parametrize('code', trailing_colon_cases) | ||
| def test_redundant_trailing_colon( | ||
| parse_tokens, | ||
| assert_errors, | ||
| default_options, | ||
| code, | ||
| ): | ||
| """Ensure trailing colon in slice is forbidden.""" | ||
| file_tokens = parse_tokens(code) | ||
| visitor = RedundantTrailingSliceVisitor( | ||
| default_options, | ||
| file_tokens=file_tokens, | ||
| ) | ||
| visitor.run() | ||
| assert_errors(visitor, [RedundantTrailingSliceViolation]) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize('code', correct_cases) | ||
| def test_correct_slice_not_flagged( | ||
| parse_tokens, | ||
| assert_errors, | ||
| default_options, | ||
| code, | ||
| ): | ||
| """Ensure valid slices do not raise violation.""" | ||
| file_tokens = parse_tokens(code) | ||
| visitor = RedundantTrailingSliceVisitor( | ||
| default_options, | ||
| file_tokens=file_tokens, | ||
| ) | ||
| visitor.run() | ||
| assert_errors(visitor, []) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| import tokenize | ||
| from typing import Final, TypedDict, final | ||
|
|
||
| from wemake_python_styleguide.violations import consistency | ||
| from wemake_python_styleguide.visitors.base import BaseTokenVisitor | ||
|
|
||
| _INSIGNIFICANT_TYPES: Final = frozenset(( | ||
| tokenize.NL, | ||
| tokenize.NEWLINE, | ||
| tokenize.COMMENT, | ||
| tokenize.INDENT, | ||
| tokenize.DEDENT, | ||
| tokenize.ENCODING, | ||
| tokenize.ENDMARKER, | ||
| )) | ||
|
|
||
|
|
||
| _COLON_COUNT: Final = 'colon_count' | ||
| _LAST_WAS_COLON: Final = 'last_was_colon' | ||
| _LAST_COLON: Final = 'last_colon' | ||
| _HAS_NON_COLON: Final = 'has_non_colon' | ||
|
|
||
|
|
||
| @final | ||
| class _SliceBracketState(TypedDict): | ||
| """Mutable state tracker for a single ``[...]`` bracket level.""" | ||
|
|
||
| colon_count: int | ||
| last_was_colon: bool | ||
| last_colon: tokenize.TokenInfo | None | ||
| has_non_colon: bool | ||
|
|
||
|
|
||
| @final | ||
| class RedundantTrailingSliceVisitor(BaseTokenVisitor): | ||
| """Check for redundant trailing colon in subscript slices.""" | ||
|
|
||
| def __init__(self, *args, **kwargs) -> None: | ||
| """Initialize state for bracket tracking.""" | ||
| super().__init__(*args, **kwargs) | ||
| self._bracket_stack: list[_SliceBracketState] = [] | ||
|
|
||
| def visit(self, token: tokenize.TokenInfo) -> None: | ||
| """Track brackets and colons to detect trailing colon.""" | ||
| self._maybe_push_bracket(token) | ||
| self._maybe_pop_bracket(token) | ||
| self._maybe_track_colon(token) | ||
| self._maybe_track_other(token) | ||
| super().visit(token) | ||
|
|
||
| def _maybe_push_bracket(self, token: tokenize.TokenInfo) -> None: | ||
| if token.exact_type == tokenize.OP and token.string == '[': | ||
| self._bracket_stack.append({ | ||
| _COLON_COUNT: 0, | ||
| _LAST_WAS_COLON: False, | ||
| _LAST_COLON: None, | ||
| _HAS_NON_COLON: False, | ||
| }) | ||
|
|
||
| def _maybe_pop_bracket(self, token: tokenize.TokenInfo) -> None: | ||
| if not (token.exact_type == tokenize.OP and token.string == ']'): | ||
| return | ||
| if not self._bracket_stack: | ||
| return | ||
| entry = self._bracket_stack.pop() | ||
| if ( | ||
| entry[_LAST_WAS_COLON] | ||
| and entry[_COLON_COUNT] >= 2 | ||
| and entry[_HAS_NON_COLON] | ||
| ): | ||
| self.add_violation( | ||
| consistency.RedundantTrailingSliceViolation( | ||
| entry[_LAST_COLON], | ||
| ), | ||
| ) | ||
|
|
||
| def _maybe_track_colon(self, token: tokenize.TokenInfo) -> None: | ||
| if not ( | ||
| token.exact_type == tokenize.OP | ||
| and token.string == ':' | ||
| and self._bracket_stack | ||
| ): | ||
| return | ||
| entry = self._bracket_stack[-1] | ||
| entry[_COLON_COUNT] += 1 | ||
| entry[_LAST_WAS_COLON] = True | ||
| entry[_LAST_COLON] = token | ||
|
|
||
| def _maybe_track_other(self, token: tokenize.TokenInfo) -> None: | ||
| if token.type in _INSIGNIFICANT_TYPES or not self._bracket_stack: | ||
| return | ||
| entry = self._bracket_stack[-1] | ||
| entry[_LAST_WAS_COLON] = False | ||
| if token.string != ':': | ||
| entry[_HAS_NON_COLON] = True | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.