Skip to content

Don't rewrite composition/existential types to Self in prefer_self_in_static_references - #6749

Merged
SimplyDanny merged 5 commits into
realm:mainfrom
Brett-Best:fix/prefer-self-static-references-composition
Jun 5, 2026
Merged

SimplyDanny merged 5 commits into
realm:mainfrom
Brett-Best:fix/prefer-self-static-references-composition

Conversation

@Brett-Best

Copy link
Copy Markdown
Contributor

Summary

prefer_self_in_static_references treats an extension as class-like and rewrites references to the extended type into Self. It also did this when the type appeared inside a protocol composition (any A & B) or as the constraint of an existential/opaque type (any A, some A), where Self is not interchangeable with the named type — this changes the code's meaning and, for existentials, produces code that does not compile.

For example, inside a protocol extension:

protocol A {}
protocol B {}
extension A {
    func f(_ x: Any) -> Bool { x is any A & B }   // was autocorrected to `any Self & B`
    func g(_ x: Any) -> Bool { x is any A }        // was autocorrected to the invalid `any Self`
}

Changes

  • Skip these positions in both visitPost(IdentifierTypeSyntax) and visitPost(MemberTypeSyntax) by bailing out when the parent is a CompositionTypeElementSyntax or SomeOrAnyTypeSyntax.
  • Add non-triggering examples covering any A, any A & B, and the member-type composition Outer.Inner & B. (Non-triggering examples are verified both for linting and for being unchanged by the corrector.)
  • CHANGELOG entry.

Genuine static references in the same extension (e.g. K.i → Self.i) continue to be corrected.

Fixes #6748

🤖 Generated with Claude Code

`prefer_self_in_static_references` treats an extension as class-like and
rewrites references to the extended type into `Self`. It also did this when
the type appeared inside a protocol composition (`any A & B`) or as the
constraint of an existential/opaque type (`any A`, `some A`), where `Self`
is not interchangeable with the named type — changing the code's meaning
and, for existentials, producing code that does not compile.

Skip these positions in both the identifier and member-type handlers, and
add non-triggering examples covering them.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Copilot AI review requested due to automatic review settings June 5, 2026 13:56

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Updates prefer_self_in_static_references to avoid unsafe rewrites to Self in Swift type contexts where Self is not equivalent to a named type (protocol compositions and any/some constraints).

Changes:

  • Skip violations when a referenced type is part of a protocol composition (A & B / any A & B).
  • Skip violations when a referenced type is the constraint of any / some.
  • Add non-triggering examples and document the behavior change in the changelog.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.

File Description
Source/SwiftLintBuiltInRules/Rules/Style/PreferSelfInStaticReferencesRule.swift Adds early-returns to prevent rewriting in composition and any/some constraint contexts.
Source/SwiftLintBuiltInRules/Rules/Style/PreferSelfInStaticReferencesRuleExamples.swift Adds non-triggering examples covering any and composition cases.
CHANGELOG.md Records the behavioral change for the rule.

Comment thread CHANGELOG.md Resolved
@Brett-Best
Brett-Best marked this pull request as draft June 5, 2026 13:59
- Extract the composition / existential-or-opaque skip logic into a single
  `isNonSubstitutableTypeContext(_:)` helper, removing the duplication between
  the `IdentifierTypeSyntax` and `MemberTypeSyntax` visitors.
- Disable `file_length` on the rule file and `type_body_length` on the examples
  enum, matching the convention used by other rules (e.g. `NoMagicNumbersRule`),
  since `swiftlint lint --strict` in CI would otherwise fail on the additions.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@SwiftLintBot

SwiftLintBot commented Jun 5, 2026 •

Copy link
Copy Markdown
1 Warning
⚠️ This PR may need tests.
21 Messages
📖 Building this branch resulted in a binary size of 27519.66 KiB vs 27519.12 KiB when built on main (0% larger).
📖 Linting Aerial with this PR took 0.74 s vs 0.76 s on main (2% faster).
📖 Linting Alamofire with this PR took 1.03 s vs 1.06 s on main (2% faster).
📖 Linting Brave with this PR took 7.07 s vs 7.08 s on main (0% faster).
📖 Linting DuckDuckGo with this PR took 29.26 s vs 29.23 s on main (0% slower).
📖 Linting Firefox with this PR took 12.24 s vs 12.27 s on main (0% faster).
📖 Linting Kickstarter with this PR took 8.25 s vs 8.3 s on main (0% faster).
📖 Linting Moya with this PR took 0.43 s vs 0.41 s on main (4% slower).
📖 Linting NetNewsWire with this PR took 2.71 s vs 2.72 s on main (0% faster).
📖 Linting Nimble with this PR took 0.63 s vs 0.64 s on main (1% faster).
📖 Linting PocketCasts with this PR took 8.04 s vs 7.94 s on main (1% slower).
📖 Linting Quick with this PR took 0.4 s vs 0.39 s on main (2% slower).
📖 Linting Realm with this PR took 2.89 s vs 2.89 s on main (0% slower).
📖 Linting Sourcery with this PR took 1.83 s vs 1.8 s on main (1% slower).
📖 Linting Swift with this PR took 4.6 s vs 4.58 s on main (0% slower).
📖 Linting SwiftLintPerformanceTests with this PR took 0.16 s vs 0.16 s on main (0% slower).
📖 Linting VLC with this PR took 1.19 s vs 1.19 s on main (0% slower).
📖 Linting Wire with this PR took 18.3 s vs 18.31 s on main (0% faster).
📖 Linting WordPress with this PR took 12.44 s vs 12.49 s on main (0% faster).
📖 This PR fixed a violation in DuckDuckGo: /SharedPackages/BrowserServicesKit/Sources/Common/DDGError.swift:196:45: Warning: Use Self to refer to the surrounding type name (prefer_self_in_static_references)
📖 This PR fixed a violation in DuckDuckGo: /SharedPackages/BrowserServicesKit/Sources/Common/DDGError.swift:226:46: Warning: Use Self to refer to the surrounding type name (prefer_self_in_static_references)

Generated by 🚫 Danger

@SimplyDanny SimplyDanny left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the prompt fix!

Replace the parent-context checks in the `visitPost` handlers (and the
`isNonSubstitutableTypeContext` helper) with `visit(_:) -> .skipChildren`
overrides for `SomeOrAnyTypeSyntax` and `CompositionTypeSyntax` in class-like
scopes, matching how the rest of the visitor excludes contexts (generic
lists, parameter clauses, etc.).

`SomeOrAnyTypeSyntax` covers `any A`, `some A`, and `any A & B`;
`CompositionTypeSyntax` additionally covers a bare `A & B` composition
written without `any` (e.g. a class-and-protocol existential in Swift 5
mode), as exercised by the `Outer.Inner & B` example.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Brett-Best
Brett-Best marked this pull request as ready for review June 5, 2026 14:28
An empirical sweep of `any`/`some`/`&`/metatype edge cases (verified against
the corrector and swiftc) surfaced one more miscorrection: in a protocol
extension, `P.Protocol` was rewritten to the invalid `Self.Protocol`
("cannot use 'Protocol' with non-protocol type 'Self'").

Skip the base of a `.Protocol` existential metatype in class-like scopes via
`visit(MetatypeTypeSyntax)`. `.Type` metatypes stay correctable, since
`Self.Type` is valid.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Brett-Best
Brett-Best requested a review from Copilot June 5, 2026 14:51

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

Comment on lines +229 to +247
// The surrounding type must not be rewritten to `Self` when it appears in
// a composition (`A & B`, `any A & B`) or as the constraint of an
// existential or opaque type (`any A`, `some A`): `Self` is not
// interchangeable with the named type in a composition, and
// `any Self`/`some Self` is not valid. Skip these whole type constructs
// so neither their identifier nor member-type components are flagged.
override func visit(_: CompositionTypeSyntax) -> SyntaxVisitorContinueKind {
if case .likeClass = parentDeclScopes.peek() {
return .skipChildren
}
return .visitChildren
}

override func visit(_: SomeOrAnyTypeSyntax) -> SyntaxVisitorContinueKind {
if case .likeClass = parentDeclScopes.peek() {
return .skipChildren
}
return .visitChildren
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I tried to turn this into a concrete false-negative sample before changing the visitor. The cases I could think of either are already intentionally skipped by the older generic-argument handling (any P<Self>), or produce invalid Swift when rewritten: Self & B, any Self & B, any Self, any Self.Type, and Self.P/any Self.P. So I do not currently have a troublesome code sample that would justify moving away from the subtree skip. @SimplyDanny, can you think of any other case Copilot might be referring to here?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think it refers to something like

class S {
  protocol P {}
}

class T: S.P {}

extension S {
  func f() -> any S.P { T() } // `any Self.P` would be an error
}

which would be invalid either. Skipping the entire type and all children should thus be fine.

Comment thread CHANGELOG.md Resolved
@Brett-Best
Brett-Best marked this pull request as draft June 5, 2026 14:59
@Brett-Best
Brett-Best marked this pull request as ready for review June 5, 2026 17:56
- Move the existential/opaque half of the shared comment onto
  `visit(SomeOrAnyTypeSyntax)`; keep the composition half on
  `visit(CompositionTypeSyntax)`.
- Add a triggering + correction example for `.Type` metatypes
  (`A.Type` -> `Self.Type`), confirming `.Type` stays correctable while
  `.Protocol` is skipped.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@SimplyDanny
SimplyDanny enabled auto-merge (squash) June 5, 2026 18:20
@SimplyDanny
SimplyDanny merged commit affa4fb into realm:main Jun 5, 2026
19 checks passed
@Brett-Best
Brett-Best deleted the fix/prefer-self-static-references-composition branch June 5, 2026 19:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

prefer_self_in_static_references rewrites composition/existential types to Self in extensions (e.g. any A & B → any Self & B)

4 participants