Skip to content

Add newline after consecutive declarations #1698

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
merged 3 commits into from
Jun 13, 2023
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
4 changes: 3 additions & 1 deletion Sources/SwiftBasicFormat/Trivia+FormatExtensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ extension Trivia {

/// Returns the indentation of the last trivia piece in this trivia that is
/// not a whitespace.
func indentation(isOnNewline: Bool) -> Trivia? {
/// - Parameter isOnNewline: Specifies if the character before this trivia is a newline character, i.e. if this trivia already starts on a new line.
/// - Returns: An optional ``Trivia`` with indentation of the last trivia piece.
public func indentation(isOnNewline: Bool) -> Trivia? {
let lastNonWhitespaceTriviaPieceIndex = self.pieces.lastIndex(where: { !$0.isWhitespace }) ?? self.pieces.endIndex
let piecesBeforeLastNonWhitespace = self.pieces[..<lastNonWhitespaceTriviaPieceIndex]
let indentation: ArraySlice<TriviaPiece>
Expand Down
67 changes: 61 additions & 6 deletions Sources/SwiftParserDiagnostics/ParseDiagnosticsGenerator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,31 @@ fileprivate func getTokens(between first: TokenSyntax, and second: TokenSyntax)
}

fileprivate extension TokenSyntax {
/// The indentation of this token
///
/// In contrast to `indentation`, this does not walk to previous tokens to
/// find the indentation of the line this token occurs on.
private var indentation: Trivia? {
let previous = self.previousToken(viewMode: .sourceAccurate)
return ((previous?.trailingTrivia ?? []) + leadingTrivia).indentation(isOnNewline: false)
}

/// Returns the indentation of the line this token occurs on
var indentationOfLine: Trivia {
var token: TokenSyntax = self
if let indentation = token.indentation {
return indentation
}
while let previous = token.previousToken(viewMode: .sourceAccurate) {
token = previous
if let indentation = token.indentation {
return indentation
}
}

return []
}

/// Assuming this token is a `poundAvailableKeyword` or `poundUnavailableKeyword`
/// returns the opposite keyword.
var negatedAvailabilityKeyword: TokenSyntax {
Expand Down Expand Up @@ -702,13 +727,28 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor {
// Only diagnose the missing semicolon if the item doesn't contain any errors.
// If the item contains errors, the root cause is most likely something different and not the missing semicolon.
let position = semicolon.previousToken(viewMode: .sourceAccurate)?.endPositionBeforeTrailingTrivia
var fixIts: [FixIt] = [
FixIt(message: .insertSemicolon, changes: .makePresent(semicolon))
]
if let firstToken = node.firstToken(viewMode: .sourceAccurate),
let lastToken = node.lastToken(viewMode: .sourceAccurate)
{
fixIts.insert(
FixIt(
message: .insertNewline,
changes: [
.replaceTrailingTrivia(token: lastToken, newTrivia: lastToken.trailingTrivia + .newlines(1) + firstToken.indentationOfLine)
]
),
at: 0
)
}

addDiagnostic(
semicolon,
position: position,
.consecutiveStatementsOnSameLine,
fixIts: [
FixIt(message: .insertSemicolon, changes: .makePresent(semicolon))
],
fixIts: fixIts,
handledNodes: [semicolon.id]
)
} else {
Expand Down Expand Up @@ -1155,13 +1195,28 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor {
// Only diagnose the missing semicolon if the decl doesn't contain any errors.
// If the decl contains errors, the root cause is most likely something different and not the missing semicolon.
let position = semicolon.previousToken(viewMode: .sourceAccurate)?.endPositionBeforeTrailingTrivia
var fixIts: [FixIt] = [
FixIt(message: .insertSemicolon, changes: .makePresent(semicolon))
]
if let firstToken = node.firstToken(viewMode: .sourceAccurate),
let lastToken = node.lastToken(viewMode: .sourceAccurate)
{
fixIts.insert(
FixIt(
message: .insertNewline,
changes: [
.replaceTrailingTrivia(token: lastToken, newTrivia: lastToken.trailingTrivia + .newlines(1) + firstToken.indentationOfLine)
]
),
at: 0
)
}

addDiagnostic(
semicolon,
position: position,
.consecutiveDeclarationsOnSameLine,
fixIts: [
FixIt(message: .insertSemicolon, changes: .makePresent(semicolon))
],
fixIts: fixIts,
handledNodes: [semicolon.id]
)
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,10 @@ extension DiagnosticMessage where Self == StaticParserError {
.init("'class' constraint can only appear on protocol declarations")
}
public static var consecutiveDeclarationsOnSameLine: Self {
.init("consecutive declarations on a line must be separated by ';'")
.init("consecutive declarations on a line must be separated by newline or ';'")
}
public static var consecutiveStatementsOnSameLine: Self {
.init("consecutive statements on a line must be separated by ';'")
.init("consecutive statements on a line must be separated by newline or ';'")
}
public static var cStyleForLoop: Self {
.init("C-style for statement has been removed in Swift 3")
Expand Down
8 changes: 3 additions & 5 deletions Tests/SwiftParserTest/Assertions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -275,15 +275,13 @@ class FixItApplier: SyntaxRewriter {
var changes: [FixIt.Change]

init(diagnostics: [Diagnostic], withMessages messages: [String]?) {
let messages = messages ?? diagnostics.compactMap { $0.fixIts.first?.message.message }

self.changes =
diagnostics
.flatMap { $0.fixIts }
.filter {
if let messages {
return messages.contains($0.message.message)
} else {
return true
}
return messages.contains($0.message.message)
}
.flatMap { $0.changes }
}
Expand Down
135 changes: 128 additions & 7 deletions Tests/SwiftParserTest/DeclarationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -329,9 +329,54 @@ final class DeclarationTests: XCTestCase {
internal(set) var defaultProp = 0
""",
diagnostics: [
DiagnosticSpec(locationMarker: "1️⃣", message: "consecutive statements on a line must be separated by ';'", fixIts: ["insert ';'"]),
DiagnosticSpec(locationMarker: "2️⃣", message: "consecutive statements on a line must be separated by ';'", fixIts: ["insert ';'"]),
DiagnosticSpec(
locationMarker: "1️⃣",
message: "consecutive statements on a line must be separated by newline or ';'",
fixIts: ["insert newline", "insert ';'"]
),
DiagnosticSpec(
locationMarker: "2️⃣",
message: "consecutive statements on a line must be separated by newline or ';'",
fixIts: ["insert newline", "insert ';'"]
),
],
applyFixIts: ["insert newline"],
fixedSource: """
open
open(set)
var openProp = 0
public public(set) var publicProp = 0
package package(set) var packageProp = 0
internal internal(set) var internalProp = 0
fileprivate fileprivate(set) var fileprivateProp = 0
private private(set) var privateProp = 0
internal(set) var defaultProp = 0
"""
)

assertParse(
"""
open1️⃣ open(set)2️⃣ var openProp = 0
public public(set) var publicProp = 0
package package(set) var packageProp = 0
internal internal(set) var internalProp = 0
fileprivate fileprivate(set) var fileprivateProp = 0
private private(set) var privateProp = 0
internal(set) var defaultProp = 0
""",
diagnostics: [
DiagnosticSpec(
locationMarker: "1️⃣",
message: "consecutive statements on a line must be separated by newline or ';'",
fixIts: ["insert newline", "insert ';'"]
),
DiagnosticSpec(
locationMarker: "2️⃣",
message: "consecutive statements on a line must be separated by newline or ';'",
fixIts: ["insert newline", "insert ';'"]
),
],
applyFixIts: ["insert ';'"],
fixedSource: """
open; open(set); var openProp = 0
public public(set) var publicProp = 0
Expand Down Expand Up @@ -1025,18 +1070,74 @@ final class DeclarationTests: XCTestCase {
)
}

func testTextRecovery() {
func testTextRecovery1() {
assertParse(
"""
Lorem1️⃣ ipsum2️⃣ dolor3️⃣ sit4️⃣ amet5️⃣, consectetur adipiscing elit
""",
diagnostics: [
DiagnosticSpec(
locationMarker: "1️⃣",
message: "consecutive statements on a line must be separated by newline or ';'",
fixIts: ["insert newline", "insert ';'"]
),
DiagnosticSpec(
locationMarker: "2️⃣",
message: "consecutive statements on a line must be separated by newline or ';'",
fixIts: ["insert newline", "insert ';'"]
),
DiagnosticSpec(
locationMarker: "3️⃣",
message: "consecutive statements on a line must be separated by newline or ';'",
fixIts: ["insert newline", "insert ';'"]
),
DiagnosticSpec(
locationMarker: "4️⃣",
message: "consecutive statements on a line must be separated by newline or ';'",
fixIts: ["insert newline", "insert ';'"]
),
DiagnosticSpec(locationMarker: "5️⃣", message: "extraneous code ', consectetur adipiscing elit' at top level"),
],
applyFixIts: ["insert newline"],
fixedSource: """
Lorem
ipsum
dolor
sit
amet, consectetur adipiscing elit
"""
)
}

func testTextRecovery2() {
assertParse(
"""
Lorem1️⃣ ipsum2️⃣ dolor3️⃣ sit4️⃣ amet5️⃣, consectetur adipiscing elit
""",
diagnostics: [
DiagnosticSpec(locationMarker: "1️⃣", message: "consecutive statements on a line must be separated by ';'", fixIts: ["insert ';'"]),
DiagnosticSpec(locationMarker: "2️⃣", message: "consecutive statements on a line must be separated by ';'", fixIts: ["insert ';'"]),
DiagnosticSpec(locationMarker: "3️⃣", message: "consecutive statements on a line must be separated by ';'", fixIts: ["insert ';'"]),
DiagnosticSpec(locationMarker: "4️⃣", message: "consecutive statements on a line must be separated by ';'", fixIts: ["insert ';'"]),
DiagnosticSpec(
locationMarker: "1️⃣",
message: "consecutive statements on a line must be separated by newline or ';'",
fixIts: ["insert newline", "insert ';'"]
),
DiagnosticSpec(
locationMarker: "2️⃣",
message: "consecutive statements on a line must be separated by newline or ';'",
fixIts: ["insert newline", "insert ';'"]
),
DiagnosticSpec(
locationMarker: "3️⃣",
message: "consecutive statements on a line must be separated by newline or ';'",
fixIts: ["insert newline", "insert ';'"]
),
DiagnosticSpec(
locationMarker: "4️⃣",
message: "consecutive statements on a line must be separated by newline or ';'",
fixIts: ["insert newline", "insert ';'"]
),
DiagnosticSpec(locationMarker: "5️⃣", message: "extraneous code ', consectetur adipiscing elit' at top level"),
],
applyFixIts: ["insert ';'"],
fixedSource: """
Lorem; ipsum; dolor; sit; amet, consectetur adipiscing elit
"""
Expand Down Expand Up @@ -2409,4 +2510,24 @@ final class DeclarationTests: XCTestCase {
fixedSource: "protocol X<<#identifier#>> {}"
)
}

func testCorrectIndentationWithNewline() {
assertParse(
"""
func
test() {}1️⃣ var other: Int
""",
diagnostics: [
DiagnosticSpec(
message: "consecutive statements on a line must be separated by newline or ';'",
fixIts: ["insert newline", "insert ';'"]
)
],
fixedSource: """
func
test() {}
var other: Int
"""
)
}
}
Loading