Skip to content

Add NoEmptyLinesOpeningClosingBraces rule #797

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

Merged
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
11 changes: 11 additions & 0 deletions Documentation/RuleDocumentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ Here's the list of available rules:
- [NoAssignmentInExpressions](#NoAssignmentInExpressions)
- [NoBlockComments](#NoBlockComments)
- [NoCasesWithOnlyFallthrough](#NoCasesWithOnlyFallthrough)
- [NoEmptyLinesOpeningClosingBraces](#NoEmptyLinesOpeningClosingBraces)
- [NoEmptyTrailingClosureParentheses](#NoEmptyTrailingClosureParentheses)
- [NoLabelsInCasePatterns](#NoLabelsInCasePatterns)
- [NoLeadingUnderscores](#NoLeadingUnderscores)
Expand Down Expand Up @@ -271,6 +272,16 @@ Format: The fallthrough `case` is added as a prefix to the next case unless the

`NoCasesWithOnlyFallthrough` rule can format your code automatically.

### NoEmptyLinesOpeningClosingBraces

Empty lines are forbidden after opening braces and before closing braces.

Lint: Empty lines after opening braces and before closing braces yield a lint error.

Format: Empty lines after opening braces and before closing braces will be removed.

`NoEmptyLinesOpeningClosingBraces` rule can format your code automatically.

### NoEmptyTrailingClosureParentheses

Function calls with no arguments and a trailing closure should not have empty parentheses.
Expand Down
1 change: 1 addition & 0 deletions Sources/SwiftFormat/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ add_library(SwiftFormat
Rules/NoAssignmentInExpressions.swift
Rules/NoBlockComments.swift
Rules/NoCasesWithOnlyFallthrough.swift
Rules/NoEmptyLineOpeningClosingBraces.swift
Rules/NoEmptyTrailingClosureParentheses.swift
Rules/NoLabelsInCasePatterns.swift
Rules/NoLeadingUnderscores.swift
Expand Down
19 changes: 19 additions & 0 deletions Sources/SwiftFormat/Core/Pipelines+Generated.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ class LintPipeline: SyntaxVisitor {
super.init(viewMode: .sourceAccurate)
}

override func visit(_ node: AccessorBlockSyntax) -> SyntaxVisitorContinueKind {
visitIfEnabled(NoEmptyLinesOpeningClosingBraces.visit, for: node)
return .visitChildren
}
override func visitPost(_ node: AccessorBlockSyntax) {
onVisitPost(rule: NoEmptyLinesOpeningClosingBraces.self, for: node)
}

override func visit(_ node: ActorDeclSyntax) -> SyntaxVisitorContinueKind {
visitIfEnabled(AllPublicDeclarationsHaveDocumentation.visit, for: node)
visitIfEnabled(TypeNamesShouldBeCapitalized.visit, for: node)
Expand Down Expand Up @@ -93,10 +101,12 @@ class LintPipeline: SyntaxVisitor {
}

override func visit(_ node: ClosureExprSyntax) -> SyntaxVisitorContinueKind {
visitIfEnabled(NoEmptyLinesOpeningClosingBraces.visit, for: node)
visitIfEnabled(OmitExplicitReturns.visit, for: node)
return .visitChildren
}
override func visitPost(_ node: ClosureExprSyntax) {
onVisitPost(rule: NoEmptyLinesOpeningClosingBraces.self, for: node)
onVisitPost(rule: OmitExplicitReturns.self, for: node)
}

Expand Down Expand Up @@ -134,10 +144,12 @@ class LintPipeline: SyntaxVisitor {

override func visit(_ node: CodeBlockSyntax) -> SyntaxVisitorContinueKind {
visitIfEnabled(AmbiguousTrailingClosureOverload.visit, for: node)
visitIfEnabled(NoEmptyLinesOpeningClosingBraces.visit, for: node)
return .visitChildren
}
override func visitPost(_ node: CodeBlockSyntax) {
onVisitPost(rule: AmbiguousTrailingClosureOverload.self, for: node)
onVisitPost(rule: NoEmptyLinesOpeningClosingBraces.self, for: node)
}

override func visit(_ node: ConditionElementSyntax) -> SyntaxVisitorContinueKind {
Expand Down Expand Up @@ -384,10 +396,12 @@ class LintPipeline: SyntaxVisitor {

override func visit(_ node: MemberBlockSyntax) -> SyntaxVisitorContinueKind {
visitIfEnabled(AmbiguousTrailingClosureOverload.visit, for: node)
visitIfEnabled(NoEmptyLinesOpeningClosingBraces.visit, for: node)
return .visitChildren
}
override func visitPost(_ node: MemberBlockSyntax) {
onVisitPost(rule: AmbiguousTrailingClosureOverload.self, for: node)
onVisitPost(rule: NoEmptyLinesOpeningClosingBraces.self, for: node)
}

override func visit(_ node: OptionalBindingConditionSyntax) -> SyntaxVisitorContinueKind {
Expand All @@ -411,10 +425,12 @@ class LintPipeline: SyntaxVisitor {
}

override func visit(_ node: PrecedenceGroupDeclSyntax) -> SyntaxVisitorContinueKind {
visitIfEnabled(NoEmptyLinesOpeningClosingBraces.visit, for: node)
visitIfEnabled(NoLeadingUnderscores.visit, for: node)
return .visitChildren
}
override func visitPost(_ node: PrecedenceGroupDeclSyntax) {
onVisitPost(rule: NoEmptyLinesOpeningClosingBraces.self, for: node)
onVisitPost(rule: NoLeadingUnderscores.self, for: node)
}

Expand Down Expand Up @@ -511,10 +527,12 @@ class LintPipeline: SyntaxVisitor {
}

override func visit(_ node: SwitchExprSyntax) -> SyntaxVisitorContinueKind {
visitIfEnabled(NoEmptyLinesOpeningClosingBraces.visit, for: node)
visitIfEnabled(NoParensAroundConditions.visit, for: node)
return .visitChildren
}
override func visitPost(_ node: SwitchExprSyntax) {
onVisitPost(rule: NoEmptyLinesOpeningClosingBraces.self, for: node)
onVisitPost(rule: NoParensAroundConditions.self, for: node)
}

Expand Down Expand Up @@ -597,6 +615,7 @@ extension FormatPipeline {
node = NoAccessLevelOnExtensionDeclaration(context: context).rewrite(node)
node = NoAssignmentInExpressions(context: context).rewrite(node)
node = NoCasesWithOnlyFallthrough(context: context).rewrite(node)
node = NoEmptyLinesOpeningClosingBraces(context: context).rewrite(node)
node = NoEmptyTrailingClosureParentheses(context: context).rewrite(node)
node = NoLabelsInCasePatterns(context: context).rewrite(node)
node = NoParensAroundConditions(context: context).rewrite(node)
Expand Down
1 change: 1 addition & 0 deletions Sources/SwiftFormat/Core/RuleNameCache+Generated.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public let ruleNameCache: [ObjectIdentifier: String] = [
ObjectIdentifier(NoAssignmentInExpressions.self): "NoAssignmentInExpressions",
ObjectIdentifier(NoBlockComments.self): "NoBlockComments",
ObjectIdentifier(NoCasesWithOnlyFallthrough.self): "NoCasesWithOnlyFallthrough",
ObjectIdentifier(NoEmptyLinesOpeningClosingBraces.self): "NoEmptyLinesOpeningClosingBraces",
ObjectIdentifier(NoEmptyTrailingClosureParentheses.self): "NoEmptyTrailingClosureParentheses",
ObjectIdentifier(NoLabelsInCasePatterns.self): "NoLabelsInCasePatterns",
ObjectIdentifier(NoLeadingUnderscores.self): "NoLeadingUnderscores",
Expand Down
1 change: 1 addition & 0 deletions Sources/SwiftFormat/Core/RuleRegistry+Generated.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"NoAssignmentInExpressions": true,
"NoBlockComments": true,
"NoCasesWithOnlyFallthrough": true,
"NoEmptyLinesOpeningClosingBraces": false,
"NoEmptyTrailingClosureParentheses": true,
"NoLabelsInCasePatterns": true,
"NoLeadingUnderscores": false,
Expand Down
131 changes: 131 additions & 0 deletions Sources/SwiftFormat/Rules/NoEmptyLineOpeningClosingBraces.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import SwiftSyntax

/// Empty lines are forbidden after opening braces and before closing braces.
///
/// Lint: Empty lines after opening braces and before closing braces yield a lint error.
///
/// Format: Empty lines after opening braces and before closing braces will be removed.
@_spi(Rules)
public final class NoEmptyLinesOpeningClosingBraces: SyntaxFormatRule {
Copy link
Member

Choose a reason for hiding this comment

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

It's too bad we don't have a convenient way to just visit anything that conforms to BracedSyntax here.

Can you add PrecedenceGroupDeclSyntax and SwitchExprSyntax, which look like the only two other BracedSyntax node types that are missing here?

Copy link
Member

Choose a reason for hiding this comment

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

To visit anything conforming to BracedSyntax you can do the following

public override func visitAny(_ node: Syntax) -> Syntax? {
  if let braced = node.as(BracedSyntax.self) {
    // do things
  } else {
    super.visitAny(node)
  }
}

Copy link
Member

Choose a reason for hiding this comment

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

In general that would work for a regular visitor, but generate-swift-format scans the rules to figure out which concrete nodes they visit so that it can generate the pipeline visitor.

It might not be difficult to add visitAny support to the pipeline, but it would be better to do it separately from this PR.

Copy link
Member

Choose a reason for hiding this comment

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

👍🏽 Just wanted to put this pattern out there because it’s not terribly obvious.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I've wished more than once that override func f(value: some T) in a class would override any concrete method that matches.

Copy link
Member

Choose a reason for hiding this comment

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

Can you please add a doc comment for this rule using a similar format to the other rules? RuleDocumentation.md should be generated from that when you run generate-swift-format; you don't need to update it manually.

public override class var isOptIn: Bool { return true }

public override func visit(_ node: AccessorBlockSyntax) -> AccessorBlockSyntax {
var result = node
switch node.accessors {
case .accessors(let accessors):
result.accessors = .init(rewritten(accessors))
case .getter(let getter):
result.accessors = .init(rewritten(getter))
}
result.rightBrace = rewritten(node.rightBrace)
return result
}

public override func visit(_ node: CodeBlockSyntax) -> CodeBlockSyntax {
var result = node
result.statements = rewritten(node.statements)
result.rightBrace = rewritten(node.rightBrace)
return result
}

public override func visit(_ node: MemberBlockSyntax) -> MemberBlockSyntax {
var result = node
result.members = rewritten(node.members)
result.rightBrace = rewritten(node.rightBrace)
return result
}

public override func visit(_ node: ClosureExprSyntax) -> ExprSyntax {
var result = node
result.statements = rewritten(node.statements)
result.rightBrace = rewritten(node.rightBrace)
return ExprSyntax(result)
}

public override func visit(_ node: SwitchExprSyntax) -> ExprSyntax {
var result = node
result.cases = rewritten(node.cases)
result.rightBrace = rewritten(node.rightBrace)
return ExprSyntax(result)
}

public override func visit(_ node: PrecedenceGroupDeclSyntax) -> DeclSyntax {
var result = node
result.attributes = rewritten(node.attributes)
result.rightBrace = rewritten(node.rightBrace)
return DeclSyntax(result)
}

func rewritten(_ token: TokenSyntax) -> TokenSyntax {
let (trimmedLeadingTrivia, count) = token.leadingTrivia.trimmingSuperfluousNewlines()
if trimmedLeadingTrivia.sourceLength != token.leadingTriviaLength {
diagnose(.removeEmptyLinesBefore(count), on: token, anchor: .start)
return token.with(\.leadingTrivia, trimmedLeadingTrivia)
} else {
return token
}
}

func rewritten<C: SyntaxCollection>(_ collection: C) -> C {
var result = collection
if let first = collection.first, first.leadingTrivia.containsNewlines,
let index = collection.index(of: first)
{
let (trimmedLeadingTrivia, count) = first.leadingTrivia.trimmingSuperfluousNewlines()
if trimmedLeadingTrivia.sourceLength != first.leadingTriviaLength {
diagnose(.removeEmptyLinesAfter(count), on: first, anchor: .leadingTrivia(0))
result[index] = first.with(\.leadingTrivia, trimmedLeadingTrivia)
}
}
return rewrite(result).as(C.self)!
}
}

extension Trivia {
func trimmingSuperfluousNewlines() -> (Trivia, Int) {
var trimmmed = 0
let pieces = self.indices.reduce([TriviaPiece]()) { (partialResult, index) in
let piece = self[index]
// Collapse consecutive newlines into a single one
if case .newlines(let count) = piece {
if let last = partialResult.last, last.isNewline {
trimmmed += count
return partialResult
} else {
trimmmed += count - 1
return partialResult + [.newlines(1)]
}
}
// Remove spaces/tabs surrounded by newlines
if piece.isSpaceOrTab, index > 0, index < self.count - 1, self[index - 1].isNewline, self[index + 1].isNewline {
return partialResult
}
// Retain other trivia pieces
return partialResult + [piece]
}

return (Trivia(pieces: pieces), trimmmed)
}
}

extension Finding.Message {
fileprivate static func removeEmptyLinesAfter(_ count: Int) -> Finding.Message {
"remove empty \(count > 1 ? "lines" : "line") after '{'"
}

fileprivate static func removeEmptyLinesBefore(_ count: Int) -> Finding.Message {
"remove empty \(count > 1 ? "lines" : "line") before '}'"
}
}
Loading