Skip to content
Open
Show file tree
Hide file tree
Changes from 11 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_declaration` opt-in rule

Check failure on line 15 in CHANGELOG.md

View workflow job for this annotation

GitHub Actions / Lint Markdown

Trailing spaces

CHANGELOG.md:15:52 MD009/no-trailing-spaces Trailing spaces [Expected: 0 or 2; Actual: 1] https://github.com/DavidAnson/markdownlint/blob/v0.37.4/doc/md009.md
that triggers when the there's multiple statements at 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,
MultipleStatementsDeclarationRule.self,
NSLocalizedStringKeyRule.self,
NSLocalizedStringRequireBundleRule.self,
NSNumberInitAsFunctionReferenceRule.self,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import SwiftSyntax

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

static let description = RuleDescription(
identifier: "multiple_statements_declaration",
name: "Multiple Statements Declaration",
description: "Statements should not be on the same line",
kind: .idiomatic,
nonTriggeringExamples: [
Example("let a = 1;\nlet b = 2;"),
Example("var x = 10\nvar y = 20;"),
Example("let a = 1;\nreturn a"),
Example("if b { return }; \nlet 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\nlet b = 0"),
Example("let a = 0↓; let b = 0↓; let c = 0"):
Example("let a = 0\nlet b = 0\nlet c = 0"),
Example("let a = 0↓; print(\"Hello\")"): Example("let a = 0\nprint(\"Hello\")"),
]
)
}

private extension MultipleStatementsDeclarationRule {
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),
Copy link
Collaborator

Choose a reason for hiding this comment

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

This doesn't indent the following statement. Consider the example

{
    let a = 0; let b = 0
}

which should be corrected to

{
    let a = 0;
    let b = 0
}

Copy link
Author

@AhmedZaghloul19 AhmedZaghloul19 Mar 27, 2025

Choose a reason for hiding this comment

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

The autocorrect version is

{
    let a = 0
    let b = 0
}

as we're removing the semicolon, as it's swift code styling
We can keep the semicolon as well

Copy link
Collaborator

Choose a reason for hiding this comment

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

Correct. My bad. Except this example wouldn't be formatted like that with the current implementation.

Copy link
Author

Choose a reason for hiding this comment

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

@SimplyDanny So, do i have to do anything else for this rule except fixing the conflict?

Copy link
Collaborator

Choose a reason for hiding this comment

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

The examples isn't formatted like you suggest. That needs to be fixed.

presence: .present
)
return super.visit(newNode)
}
}
}

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

Choose a reason for hiding this comment

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

I don't comprehend this condition. Why is no trivia after the semicolon allowed? I think an example like let a = 0;let b = 0 should trigger as well.


if let nextToken = nextToken(viewMode: .sourceAccurate),
isFollowedOnlyByWhitespaceOrNewline {
return nextToken.leadingTrivia.containsNewlines() == false
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think what you actually want to know is whether the next token is on the same line as the semicolon. You can use locationConverter in every visitor and rewriter. It can tell you on which line a certain token is located. If you compare the line of the semicolon with the line of the next token, you know whether to trigger a violation or not.

}
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 MultipleStatementsDeclarationRuleGeneratedTests: SwiftLintTestCase {
func testWithDefaultConfiguration() {
verifyRule(MultipleStatementsDeclarationRule.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
Loading