From 156f6aabc895a5839994e8c34fa22a8d8a627a96 Mon Sep 17 00:00:00 2001 From: woxtu Date: Mon, 12 Jun 2023 00:22:06 +0900 Subject: [PATCH] Fix false positives in `sorted_first_last` rule when `first`/`last` have a predicate (#5038) --- CHANGELOG.md | 5 +++++ .../Rules/Performance/SortedFirstLastRule.swift | 7 ++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f8ff2a946..81b31fdc4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,11 @@ [Haoocen](https://github.com/Haoocen) [#5023](https://github.com/realm/SwiftLint/pull/5023) +* Fix false positives on `sorted_first_last` rule when `first`/`last` have + a predicate. + [woxtu](https://github.com/woxtu) + [#3023](https://github.com/realm/SwiftLint/issues/3023) + ## 0.52.2: Crisper Clearer Pleats #### Breaking diff --git a/Source/SwiftLintBuiltInRules/Rules/Performance/SortedFirstLastRule.swift b/Source/SwiftLintBuiltInRules/Rules/Performance/SortedFirstLastRule.swift index 84d630e14..b2b82fda7 100644 --- a/Source/SwiftLintBuiltInRules/Rules/Performance/SortedFirstLastRule.swift +++ b/Source/SwiftLintBuiltInRules/Rules/Performance/SortedFirstLastRule.swift @@ -21,7 +21,11 @@ struct SortedFirstLastRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRul Example("myList.sorted().firstIndex(where: someFunction)"), Example("myList.sorted().lastIndex(where: someFunction)"), Example("myList.sorted().firstIndex { $0 == key }"), - Example("myList.sorted().lastIndex { $0 == key }") + Example("myList.sorted().lastIndex { $0 == key }"), + Example("myList.sorted().first(where: someFunction)"), + Example("myList.sorted().last(where: someFunction)"), + Example("myList.sorted().first { $0 == key }"), + Example("myList.sorted().last { $0 == key }") ], triggeringExamples: [ Example("↓myList.sorted().first\n"), @@ -50,6 +54,7 @@ private extension SortedFirstLastRule { override func visitPost(_ node: MemberAccessExprSyntax) { guard node.name.text == "first" || node.name.text == "last", + node.parent?.is(FunctionCallExprSyntax.self) != true, let firstBase = node.base?.asFunctionCall, let firstBaseCalledExpression = firstBase.calledExpression.as(MemberAccessExprSyntax.self), firstBaseCalledExpression.name.text == "sorted",