Skip to content

Add SwiftLint rule to prevent multiple variable declarations on one line #5990

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 14 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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@

### Enhancements

* Add `multiple_statements` opt-in rule
that triggers when there are multiple statements on the same line.
[Ahmad Zaghloul](https://github.com/AhmedZaghloul19)

* Exclude types with a `@Suite` attribute and functions annotated with `@Test` from `no_magic_numbers` rule.
Also treat a type as a `@Suite` if it contains `@Test` functions.
[SimplyDanny](https://github.com/SimplyDanny)
Expand Down
1 change: 1 addition & 0 deletions Source/SwiftLintBuiltInRules/Models/BuiltInRules.swift
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ public let builtInRules: [any Rule.Type] = [
MultilineParametersBracketsRule.self,
MultilineParametersRule.self,
MultipleClosuresWithTrailingClosureRule.self,
MultipleStatementsRule.self,
NSLocalizedStringKeyRule.self,
NSLocalizedStringRequireBundleRule.self,
NSNumberInitAsFunctionReferenceRule.self,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import SwiftSyntax

@SwiftSyntaxRule(explicitRewriter: true, optIn: true)
struct MultipleStatementsRule: Rule {
var configuration = SeverityConfiguration<Self>(.warning)

static let description = RuleDescription(
identifier: "multiple_statements",
name: "Multiple Statements",
description: "Every statement should be on its own line",
kind: .idiomatic,
nonTriggeringExamples: [
Example(
"""
let a = 1;
let b = 2;
"""
),
Example(
"""
var x = 10
var y = 20;
"""
),
Example(
"""
let a = 1;
return a
"""
),
Example(
"""
if b { return };
let a = 1
"""
),
],
triggeringExamples: [
Example("let a = 1; return a"),
Example("if b { return }; let a = 1"),
Example("if b { return }; if c { return }"),
Example("let a = 1; let b = 2; let c = 0"),
Example("var x = 10; var y = 20"),
Example("let x = 10; var y = 20"),
],
corrections: [
Example("let a = 0↓; let b = 0"):
Example(
"""
let a = 0
let b = 0
"""
),
Example("let a = 0↓; let b = 0↓; let c = 0"):
Example(
"""
let a = 0
let b = 0
let c = 0
"""
),
Example("let a = 0↓; print(\"Hello\")"):
Example(
"""
let a = 0
print(\"Hello\")
"""
),
]
)
}

private extension MultipleStatementsRule {
final class Visitor: ViolationsSyntaxVisitor<ConfigurationType> {
override func visitPost(_ node: TokenSyntax) {
if node.isThereStatementAfterSemicolon {
violations.append(node.positionAfterSkippingLeadingTrivia)
}
}
}

final class Rewriter: ViolationsSyntaxRewriter<ConfigurationType> {
override func visit(_ node: TokenSyntax) -> TokenSyntax {
guard node.isThereStatementAfterSemicolon else {
return super.visit(node)
}

correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
let newNode = TokenSyntax(
.unknown(""),
leadingTrivia: node.leadingTrivia,
trailingTrivia: .newlines(1),
presence: .present
)
return super.visit(newNode)
}
}
}

private extension TokenSyntax {
var isThereStatementAfterSemicolon: Bool {
guard tokenKind == .semicolon,
!trailingTrivia.isEmpty else { return false }

if let nextToken = nextToken(viewMode: .sourceAccurate),
isFollowedOnlyByWhitespaceOrNewline {
return nextToken.leadingTrivia.containsNewlines() == false
}
return true
}

var isFollowedOnlyByWhitespaceOrNewline: Bool {
guard let nextToken = nextToken(viewMode: .sourceAccurate),
!nextToken.trailingTrivia.isEmpty else {
return true
}
return nextToken.leadingTrivia.allSatisfy { $0.isWhitespaceOrNewline }
}
}

private extension TriviaPiece {
var isWhitespaceOrNewline: Bool {
switch self {
case .spaces, .tabs, .newlines, .carriageReturns, .carriageReturnLineFeeds:
return true
default:
return false
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,10 @@ internal extension Configuration.FileGraph.FilePath {
// Block main thread until timeout is reached / task is done
while true {
if taskDone { break }
if Date().timeIntervalSince(startDate) > timeout { task.cancel(); break }
if Date().timeIntervalSince(startDate) > timeout {
task.cancel()
break
}
Copy link
Collaborator

@SimplyDanny SimplyDanny Mar 9, 2025

Choose a reason for hiding this comment

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

This doesn't look like it got auto-fixed by the rule. The only cases that can be fixed automatically are the ones where the statements are on their own line without leading tokens. We should probably restrict the rewriter to these cases.

usleep(50_000) // Sleep for 50 ms
}

Expand Down
6 changes: 6 additions & 0 deletions Tests/GeneratedTests/GeneratedTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -715,6 +715,12 @@ final class MultipleClosuresWithTrailingClosureRuleGeneratedTests: SwiftLintTest
}
}

final class MultipleStatementsRuleGeneratedTests: SwiftLintTestCase {
func testWithDefaultConfiguration() {
verifyRule(MultipleStatementsRule.description)
}
}

final class NSLocalizedStringKeyRuleGeneratedTests: SwiftLintTestCase {
func testWithDefaultConfiguration() {
verifyRule(NSLocalizedStringKeyRule.description)
Expand Down
4 changes: 4 additions & 0 deletions Tests/IntegrationTests/default_rule_configurations.yml
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,10 @@ multiple_closures_with_trailing_closure:
severity: warning
meta:
opt-in: false
multiple_statements_declaration:
severity: warning
meta:
opt-in: true
nesting:
type_level:
warning: 1
Expand Down