Skip to content

Allow prefer_key_paths to ignore identity closures ({ $0 }) #6068

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
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@

### Enhancements

* None.
* Add new `ignore_identity_closures` parameter to `prefer_key_paths` rule to skip conversion of identity closures
(`{ $0 }`) to identity key paths (`\self`).
Add a small note to the rule description stating that identity key path conversion is Swift 6+ only.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's have the note here as well instead of a reference to the note:

Suggested change
Add a small note to the rule description stating that identity key path conversion is Swift 6+ only.
Note that identity key paths are only support from Swift 6 on, hence this option
will be implicitly ignored/set to `true` when SwiftLint detects a Swift <6 compiler
to avoid causing compilation errors.

[p4checo](https://github.com/p4checo)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please reference the issue here as well.


### Bug Fixes

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,21 @@ struct PreferKeyPathRule: Rule {
var configuration = PreferKeyPathConfiguration()

private static let extendedMode = ["restrict_to_standard_functions": false]
private static let ignoreIdentity = ["ignore_identity_closures": true]
private static let extendedModeAndIgnoreIdentity = [
"restrict_to_standard_functions": false,
"ignore_identity_closures": true,
]
Comment on lines +10 to +13
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should work, shouldn't it?

Suggested change
private static let extendedModeAndIgnoreIdentity = [
"restrict_to_standard_functions": false,
"ignore_identity_closures": true,
]
private static let extendedModeAndIgnoreIdentity = extendedMode + ignoreIdentity


static let description = RuleDescription(
identifier: "prefer_key_path",
name: "Prefer Key Path",
description: "Use a key path argument instead of a closure with property access",
description: """
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's keep the existing description as it's currently also used as the violation message and add a rational property instead to explain this detail.

Use a key path argument instead of a closure with property access

Note: Swift 5 doesn't support identity key path conversion (`{ $0 }` -> `(\\.self)`), regardless of
`ignore_identity_closures` parameter value
""",
kind: .idiomatic,
minSwiftVersion: .fiveDotTwo,
nonTriggeringExamples: [
Expand All @@ -25,6 +35,8 @@ struct PreferKeyPathRule: Rule {
Example("f { (a, b) in a.b }", configuration: extendedMode),
Example("f { $0.a } g: { $0.b }", configuration: extendedMode),
Example("[1, 2, 3].reduce(1) { $0 + $1 }", configuration: extendedMode),
Example("f { $0 }", configuration: extendedModeAndIgnoreIdentity),
Example("f.map { $0 }", configuration: ignoreIdentity),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's also add a correction example.

Example("f.map(1) { $0.a }"),
Example("f.filter({ $0.a }, x)"),
Example("#Predicate { $0.a }"),
Expand Down Expand Up @@ -92,8 +104,12 @@ private extension PreferKeyPathRule {
return
}
if let onlyStmt = node.onlyExprStmt,
SwiftVersion.current >= .six || !onlyStmt.is(DeclReferenceExprSyntax.self),
onlyStmt.accesses(identifier: node.onlyParameter) {
if onlyStmt.is(DeclReferenceExprSyntax.self),
configuration.ignoreIdentityClosures || SwiftVersion.current < .six {
return
}

violations.append(node.positionAfterSkippingLeadingTrivia)
}
}
Expand All @@ -106,7 +122,7 @@ private extension PreferKeyPathRule {
!closure.isInvalid(restrictToStandardFunctions: configuration.restrictToStandardFunctions),
let expr = closure.onlyExprStmt,
expr.accesses(identifier: closure.onlyParameter) == true,
let replacement = expr.asKeyPath,
let replacement = expr.asKeyPath(ignoreIdentityClosures: configuration.ignoreIdentityClosures),
let calleeName = node.calleeName else {
return super.visit(node)
}
Expand Down Expand Up @@ -136,7 +152,7 @@ private extension PreferKeyPathRule {
}
if let expr = node.onlyExprStmt,
expr.accesses(identifier: node.onlyParameter) == true,
let replacement = expr.asKeyPath {
let replacement = expr.asKeyPath(ignoreIdentityClosures: configuration.ignoreIdentityClosures) {
numberOfCorrections += 1
let node = replacement
.with(\.leadingTrivia, node.leadingTrivia)
Expand Down Expand Up @@ -226,7 +242,7 @@ private extension FunctionCallExprSyntax {
}

private extension ExprSyntax {
var asKeyPath: ExprSyntax? {
func asKeyPath(ignoreIdentityClosures: Bool) -> ExprSyntax? {
if let memberAccess = `as`(MemberAccessExprSyntax.self) {
var this = memberAccess.base
var elements = [memberAccess.declName]
Expand All @@ -238,7 +254,8 @@ private extension ExprSyntax {
}
return "\\.\(raw: elements.reversed().map(\.baseName.text).joined(separator: "."))" as ExprSyntax
}
if SwiftVersion.current >= .six, `is`(DeclReferenceExprSyntax.self) {

if !ignoreIdentityClosures, SwiftVersion.current >= .six, `is`(DeclReferenceExprSyntax.self) {
return "\\.self"
}
return nil
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ struct PreferKeyPathConfiguration: SeverityBasedRuleConfiguration {
private(set) var severityConfiguration = SeverityConfiguration<Parent>(.warning)
@ConfigurationElement(key: "restrict_to_standard_functions")
private(set) var restrictToStandardFunctions = true
@ConfigurationElement(key: "ignore_identity_closures")
private(set) var ignoreIdentityClosures = false
}
7 changes: 7 additions & 0 deletions Tests/BuiltInRulesTests/PreferKeyPathRuleTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import XCTest

final class PreferKeyPathRuleTests: SwiftLintTestCase {
private static let extendedMode = ["restrict_to_standard_functions": false]
private static let ignoreIdentity = ["ignore_identity_closures": true]
private static let extendedModeAndIgnoreIdentity = [
"restrict_to_standard_functions": false,
"ignore_identity_closures": true,
]

func testIdentityExpressionInSwift6() throws {
try XCTSkipIf(SwiftVersion.current < .six)
Expand All @@ -12,6 +17,8 @@ final class PreferKeyPathRuleTests: SwiftLintTestCase {
.with(nonTriggeringExamples: [
Example("f.filter { a in b }"),
Example("f.g { $1 }", configuration: Self.extendedMode),
Example("f { $0 }", configuration: Self.extendedModeAndIgnoreIdentity),
Example("f.map { $0 }", configuration: Self.ignoreIdentity),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's also add a correction example to proof that nothing is changed with the option enabled.

])
.with(triggeringExamples: [
Example("f.compactMap ↓{ $0 }"),
Expand Down