Skip to content

Commit 546f71b

Browse files
authored
Add additional newline to first token in file (#6141)
For all first tokens in a line the newline character causing the new line is part of the leading trivia. The only exception is the very first token in a file because at the beginning of a file, there is no previous line that needs to be broken.
1 parent d4fbe69 commit 546f71b

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

Source/SwiftLintBuiltInRules/Rules/Style/VerticalWhitespaceRule.swift

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,28 @@ struct VerticalWhitespaceRule: Rule {
1616
Example("/* bcs \n\n\n\n*/"),
1717
Example("// bca \n\n"),
1818
Example("class CCCC {\n \n}"),
19+
Example("""
20+
// comment
21+
22+
import Foundation
23+
"""),
24+
Example("""
25+
26+
// comment
27+
28+
import Foundation
29+
"""),
1930
],
2031
triggeringExamples: [
2132
Example("let aaaa = 0\n\n\n"),
2233
Example("struct AAAA {}\n\n\n\n"),
2334
Example("class BBBB {}\n\n\n"),
2435
Example("class CCCC {\n \n \n}"),
36+
Example("""
37+
38+
39+
import Foundation
40+
"""),
2541
],
2642
corrections: [
2743
Example("let b = 0\n\n\nclass AAA {}\n"): Example("let b = 0\n\nclass AAA {}\n"),
@@ -34,7 +50,13 @@ struct VerticalWhitespaceRule: Rule {
3450

3551
private extension VerticalWhitespaceRule {
3652
final class Visitor: ViolationsSyntaxVisitor<ConfigurationType> {
53+
/// The number of additional newlines to expect before the first token.
54+
private var firstTokenAdditionalNewlines = 1
55+
3756
override func visit(_ token: TokenSyntax) -> SyntaxVisitorContinueKind {
57+
// Reset immediately. Only the first token has an additional leading newline.
58+
defer { firstTokenAdditionalNewlines = 0 }
59+
3860
// The strategy here is to keep track of the position of the _first_ violating newline
3961
// in each consecutive run, and report the violation when the run _ends_.
4062

@@ -47,7 +69,7 @@ private extension VerticalWhitespaceRule {
4769
var violationPosition: AbsolutePosition?
4870

4971
func process(_ count: Int, _ offset: Int) {
50-
for _ in 0..<count {
72+
for _ in 0..<(count + firstTokenAdditionalNewlines) {
5173
if consecutiveNewlines > configuration.maxEmptyLines && violationPosition == nil {
5274
violationPosition = currentPosition
5375
}
@@ -65,6 +87,8 @@ private extension VerticalWhitespaceRule {
6587
case .spaces, .tabs:
6688
currentPosition += piece.sourceLength
6789
default:
90+
// A comment breaks the chain of newlines.
91+
firstTokenAdditionalNewlines = 0
6892
if let violationPosition {
6993
report(violationPosition, consecutiveNewlines)
7094
}

0 commit comments

Comments
 (0)