Skip to content

Comments

[refurb] Correctly handle lengths of literal strings in slice-to-remove-prefix-or-suffix (FURB188)#16237

Merged
dylwil3 merged 3 commits intoastral-sh:mainfrom
dylwil3:removeaffix-literal-len
Feb 18, 2025
Merged

[refurb] Correctly handle lengths of literal strings in slice-to-remove-prefix-or-suffix (FURB188)#16237
dylwil3 merged 3 commits intoastral-sh:mainfrom
dylwil3:removeaffix-literal-len

Conversation

@dylwil3
Copy link
Collaborator

@dylwil3 dylwil3 commented Feb 18, 2025

Fixes false negative when slice bound uses length of string literal.

We were meant to check the following, for example. Given:

  text[:bound] if text.endswith(suffix) else text

We want to know whether:

  • suffix is a string literal and bound is a number literal
  • suffix is an expression and bound is
    exactly -len(suffix) (as AST nodes, prior to evaluation.)

The issue is that negative number literals like -10 are stored as unary operators applied to a number literal in the AST. So when suffix was a string literal but bound was -len(suffix) we were getting caught in the match arm where bound needed to be a number. This is now fixed with a guard.

Closes #16231

@dylwil3 dylwil3 added the bug Something isn't working label Feb 18, 2025
@github-actions
Copy link
Contributor

ruff-ecosystem results

Linter (stable)

✅ ecosystem check detected no linter changes.

Linter (preview)

✅ ecosystem check detected no linter changes.

@dylwil3 dylwil3 merged commit a23e489 into astral-sh:main Feb 18, 2025
21 checks passed
dcreager added a commit that referenced this pull request Feb 19, 2025
* main:
  [red-knot] Allow any `Ranged` argument for `report_lint` and `report_diagnostic` (#16252)
  [pycodestyle] Exempt `site.addsitedir(...)` calls (E402) (#16251)
  red_knot_python_semantic: improve diagnostic message for "invalid argument type"
  ruff_db: add "secondary" messages to `Diagnostic` trait
  ruff_db: refactor snippet rendering
  red_knot_python_semantic: remove `Ranged` impl for `TypeCheckDiagnostic`
  [red-knot] Refactor `infer_chained_boolean_types` to have access to `TypeInferenceBuilder` (#16222)
  Add `red_knot/README.md` (#16230)
  [airflow] move class attributed related cases to AIR302_class_attribute (AIR302) (#16226)
  [red-knot] Update tests for attributes inferred from parameters (#16208)
  [red-knot] update TODO comment in mdtest (#16242)
  [`refurb`] Correctly handle lengths of literal strings in `slice-to-remove-prefix-or-suffix` (`FURB188`) (#16237)
  Pass `ast::PythonVersion` to `type_hint_resolves_to_any` (#16236)
  Use `ast::PythonVersion` internally in the formatter and linter (#16170)
  Add `SECURITY.md` (#16224)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

False negative - FURB188 removesuffix with string literal

2 participants