Skip to content

Update for the more restrictive return types in SyntaxRewriter #433

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
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
12 changes: 6 additions & 6 deletions Sources/SwiftFormatPrettyPrint/TokenStreamCreator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3583,23 +3583,23 @@ class CommentMovingRewriter: SyntaxRewriter {
/// Map of tokens to alternate trivia to use as the token's leading trivia.
var rewriteTokenTriviaMap: [TokenSyntax: Trivia] = [:]

override func visit(_ node: SourceFileSyntax) -> Syntax {
override func visit(_ node: SourceFileSyntax) -> SourceFileSyntax {
if shouldFormatterIgnore(file: node) {
return Syntax(node)
return node
}
return super.visit(node)
}

override func visit(_ node: CodeBlockItemSyntax) -> Syntax {
override func visit(_ node: CodeBlockItemSyntax) -> CodeBlockItemSyntax {
if shouldFormatterIgnore(node: Syntax(node)) {
return Syntax(node)
return node
}
return super.visit(node)
}

override func visit(_ node: MemberDeclListItemSyntax) -> Syntax {
override func visit(_ node: MemberDeclListItemSyntax) -> MemberDeclListItemSyntax {
if shouldFormatterIgnore(node: Syntax(node)) {
return Syntax(node)
return node
}
return super.visit(node)
}
Expand Down
8 changes: 4 additions & 4 deletions Sources/SwiftFormatRules/DoNotUseSemicolons.swift
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,12 @@ public final class DoNotUseSemicolons: SyntaxFormatRule {
return nodeCreator(newItems)
}

public override func visit(_ node: CodeBlockItemListSyntax) -> Syntax {
return Syntax(nodeByRemovingSemicolons(from: node, nodeCreator: CodeBlockItemListSyntax.init))
public override func visit(_ node: CodeBlockItemListSyntax) -> CodeBlockItemListSyntax {
return nodeByRemovingSemicolons(from: node, nodeCreator: CodeBlockItemListSyntax.init)
}

public override func visit(_ node: MemberDeclListSyntax) -> Syntax {
return Syntax(nodeByRemovingSemicolons(from: node, nodeCreator: MemberDeclListSyntax.init))
public override func visit(_ node: MemberDeclListSyntax) -> MemberDeclListSyntax {
return nodeByRemovingSemicolons(from: node, nodeCreator: MemberDeclListSyntax.init)
}
}

Expand Down
4 changes: 2 additions & 2 deletions Sources/SwiftFormatRules/FileScopedDeclarationPrivacy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ import SwiftSyntax
/// Format: File-scoped declarations that have formal access opposite to the desired access level in
/// the formatter's configuration will have their access level changed.
public final class FileScopedDeclarationPrivacy: SyntaxFormatRule {
public override func visit(_ node: SourceFileSyntax) -> Syntax {
public override func visit(_ node: SourceFileSyntax) -> SourceFileSyntax {
let newStatements = rewrittenCodeBlockItems(node.statements)
return Syntax(node.withStatements(newStatements))
return node.withStatements(newStatements)
}

/// Returns a list of code block items equivalent to the given list, but where any file-scoped
Expand Down
14 changes: 7 additions & 7 deletions Sources/SwiftFormatRules/NoCasesWithOnlyFallthrough.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@ import SwiftSyntax
/// `default`; in that case, the fallthrough `case` is deleted.
public final class NoCasesWithOnlyFallthrough: SyntaxFormatRule {

public override func visit(_ node: SwitchCaseListSyntax) -> Syntax {
public override func visit(_ node: SwitchCaseListSyntax) -> SwitchCaseListSyntax {
var newChildren: [Syntax] = []
var fallthroughOnlyCases: [SwitchCaseSyntax] = []

/// Flushes any un-collapsed violations to the new cases list.
func flushViolations() {
fallthroughOnlyCases.forEach {
newChildren.append(super.visit($0))
newChildren.append(Syntax(super.visit($0)))
}
fallthroughOnlyCases.removeAll()
}
Expand All @@ -50,14 +50,14 @@ public final class NoCasesWithOnlyFallthrough: SyntaxFormatRule {
guard !fallthroughOnlyCases.isEmpty else {
// If there are no violations recorded, just append the case. There's nothing we can try
// to merge into it.
newChildren.append(visit(switchCase))
newChildren.append(Syntax(visit(switchCase)))
continue
}

if canMergeWithPreviousCases(switchCase) {
// If the current case can be merged with the ones before it, merge them all, leaving no
// `fallthrough`-only cases behind.
newChildren.append(visit(mergedCases(fallthroughOnlyCases + [switchCase])))
newChildren.append(Syntax(visit(mergedCases(fallthroughOnlyCases + [switchCase]))))
} else {
// If the current case can't be merged with the ones before it, merge the previous ones
// into a single `fallthrough`-only case and then append the current one. This could
Expand All @@ -71,8 +71,8 @@ public final class NoCasesWithOnlyFallthrough: SyntaxFormatRule {
// the program's behavior.
// 3. The current case is `@unknown default`, which can't be merged notwithstanding the
// side-effect issues discussed above.
newChildren.append(visit(mergedCases(fallthroughOnlyCases)))
newChildren.append(visit(switchCase))
newChildren.append(Syntax(visit(mergedCases(fallthroughOnlyCases))))
newChildren.append(Syntax(visit(switchCase)))
}

fallthroughOnlyCases.removeAll()
Expand All @@ -83,7 +83,7 @@ public final class NoCasesWithOnlyFallthrough: SyntaxFormatRule {
// anything.
flushViolations()

return Syntax(SwitchCaseListSyntax(newChildren))
return SwitchCaseListSyntax(newChildren)
}

/// Returns true if this case can definitely be merged with any that come before it.
Expand Down
4 changes: 2 additions & 2 deletions Sources/SwiftFormatRules/NoLabelsInCasePatterns.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import SwiftSyntax
///
/// Format: Redundant labels in case patterns are removed.
public final class NoLabelsInCasePatterns: SyntaxFormatRule {
public override func visit(_ node: SwitchCaseLabelSyntax) -> Syntax {
public override func visit(_ node: SwitchCaseLabelSyntax) -> SwitchCaseLabelSyntax {
var newCaseItems: [CaseItemSyntax] = []
for item in node.caseItems {
guard let expPat = item.pattern.as(ExpressionPatternSyntax.self) else {
Expand Down Expand Up @@ -66,7 +66,7 @@ public final class NoLabelsInCasePatterns: SyntaxFormatRule {
newCaseItems.append(newItem)
}
let newCaseItemList = CaseItemListSyntax(newCaseItems)
return Syntax(node.withCaseItems(newCaseItemList))
return node.withCaseItems(newCaseItemList)
}
}

Expand Down
12 changes: 6 additions & 6 deletions Sources/SwiftFormatRules/NoParensAroundConditions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,23 +53,23 @@ public final class NoParensAroundConditions: SyntaxFormatRule {
}

public override func visit(_ node: IfStmtSyntax) -> StmtSyntax {
let conditions = visit(node.conditions).as(ConditionElementListSyntax.self)!
let conditions = visit(node.conditions)
var result = node.withIfKeyword(node.ifKeyword.withOneTrailingSpace())
.withConditions(conditions)
.withBody(CodeBlockSyntax(visit(node.body)))
.withBody(visit(node.body))
if let elseBody = node.elseBody {
result = result.withElseBody(visit(elseBody))
}
return StmtSyntax(result)
}

public override func visit(_ node: ConditionElementSyntax) -> Syntax {
public override func visit(_ node: ConditionElementSyntax) -> ConditionElementSyntax {
guard let tup = node.condition.as(TupleExprSyntax.self),
tup.elementList.firstAndOnly != nil
else {
return super.visit(node)
}
return Syntax(node.withCondition(Syntax(extractExpr(tup))))
return node.withCondition(Syntax(extractExpr(tup)))
}

/// FIXME(hbh): Parsing for SwitchStmtSyntax is not implemented.
Expand All @@ -80,7 +80,7 @@ public final class NoParensAroundConditions: SyntaxFormatRule {
return super.visit(node)
}
return StmtSyntax(
node.withExpression(extractExpr(tup)).withCases(SwitchCaseListSyntax(visit(node.cases))))
node.withExpression(extractExpr(tup)).withCases(visit(node.cases)))
}

public override func visit(_ node: RepeatWhileStmtSyntax) -> StmtSyntax {
Expand All @@ -91,7 +91,7 @@ public final class NoParensAroundConditions: SyntaxFormatRule {
}
let newNode = node.withCondition(extractExpr(tup))
.withWhileKeyword(node.whileKeyword.withOneTrailingSpace())
.withBody(CodeBlockSyntax(visit(node.body)))
.withBody(visit(node.body))
return StmtSyntax(newNode)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,16 @@ public final class NoVoidReturnOnFunctionSignature: SyntaxFormatRule {
/// Remove the `-> Void` return type for function signatures. Do not remove
/// it for closure signatures, because that may introduce an ambiguity when closure signatures
/// are inferred.
public override func visit(_ node: FunctionSignatureSyntax) -> Syntax {
public override func visit(_ node: FunctionSignatureSyntax) -> FunctionSignatureSyntax {
if let ret = node.output?.returnType.as(SimpleTypeIdentifierSyntax.self), ret.name.text == "Void" {
diagnose(.removeRedundantReturn("Void"), on: ret)
return Syntax(node.withOutput(nil))
return node.withOutput(nil)
}
if let tup = node.output?.returnType.as(TupleTypeSyntax.self), tup.elements.isEmpty {
diagnose(.removeRedundantReturn("()"), on: tup)
return Syntax(node.withOutput(nil))
return node.withOutput(nil)
}
return Syntax(node)
return node
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import SwiftSyntax
/// split into multiple declarations, each declaring one of the variables, as
/// long as the result would still be syntactically valid.
public final class OneVariableDeclarationPerLine: SyntaxFormatRule {
public override func visit(_ node: CodeBlockItemListSyntax) -> Syntax {
public override func visit(_ node: CodeBlockItemListSyntax) -> CodeBlockItemListSyntax {
guard node.contains(where: codeBlockItemHasMultipleVariableBindings) else {
return super.visit(node)
}
Expand All @@ -36,7 +36,7 @@ public final class OneVariableDeclarationPerLine: SyntaxFormatRule {
// It's not a variable declaration with multiple bindings, so visit it
// recursively (in case it's something that contains bindings that need
// to be split) but otherwise do nothing.
let newItem = super.visit(codeBlockItem).as(CodeBlockItemSyntax.self)!
let newItem = super.visit(codeBlockItem)
newItems.append(newItem)
continue
}
Expand All @@ -57,7 +57,7 @@ public final class OneVariableDeclarationPerLine: SyntaxFormatRule {
newItems.append(contentsOf: splitter.nodes(bySplitting: visitedDecl))
}

return Syntax(CodeBlockItemListSyntax(newItems))
return CodeBlockItemListSyntax(newItems)
}

/// Returns true if the given `CodeBlockItemSyntax` contains a `let` or `var`
Expand Down
4 changes: 2 additions & 2 deletions Sources/SwiftFormatRules/OrderedImports.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import SwiftSyntax
/// Format: Imports will be reordered and grouped at the top of the file.
public final class OrderedImports: SyntaxFormatRule {

public override func visit(_ node: SourceFileSyntax) -> Syntax {
public override func visit(_ node: SourceFileSyntax) -> SourceFileSyntax {
let lines = generateLines(codeBlockItemList: node.statements, context: context)

// Stores the formatted and sorted lines that will be used to reconstruct the list of code block
Expand Down Expand Up @@ -134,7 +134,7 @@ public final class OrderedImports: SyntaxFormatRule {
let newNode = node.withStatements(
CodeBlockItemListSyntax(convertToCodeBlockItems(lines: formattedLines))
)
return Syntax(newNode)
return newNode
}

/// Raise lint errors if the different import types appear in the wrong order, and if import
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,12 @@ public final class ReturnVoidInsteadOfEmptyTuple: SyntaxFormatRule {

// Make sure that function types nested in the argument list are also rewritten (for example,
// `(Int -> ()) -> ()` should become `(Int -> Void) -> Void`).
let arguments = visit(node.arguments).as(TupleTypeElementListSyntax.self)!
let arguments = visit(node.arguments)
let voidKeyword = makeVoidIdentifierType(toReplace: returnType)
return TypeSyntax(node.withArguments(arguments).withReturnType(TypeSyntax(voidKeyword)))
}

public override func visit(_ node: ClosureSignatureSyntax) -> Syntax {
public override func visit(_ node: ClosureSignatureSyntax) -> ClosureSignatureSyntax {
guard let output = node.output,
let returnType = output.returnType.as(TupleTypeSyntax.self),
returnType.elements.count == 0
Expand All @@ -69,14 +69,14 @@ public final class ReturnVoidInsteadOfEmptyTuple: SyntaxFormatRule {
// If the closure input is a complete parameter clause (variables and types), make sure that
// nested function types are also rewritten (for example, `label: (Int -> ()) -> ()` should
// become `label: (Int -> Void) -> Void`).
input = visit(parameterClause)
input = Syntax(visit(parameterClause))
} else {
// Otherwise, it's a simple signature (just variable names, no types), so there is nothing to
// rewrite.
input = node.input
}
let voidKeyword = makeVoidIdentifierType(toReplace: returnType)
return Syntax(node.withInput(input).withOutput(output.withReturnType(TypeSyntax(voidKeyword))))
return node.withInput(input).withOutput(output.withReturnType(TypeSyntax(voidKeyword)))
}

/// Returns a value indicating whether the leading trivia of the given token contained any
Expand Down
11 changes: 4 additions & 7 deletions Sources/SwiftFormatRules/UseEarlyExits.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,10 @@ public final class UseEarlyExits: SyntaxFormatRule {
/// be enabled by default.
public override class var isOptIn: Bool { return true }

public override func visit(_ node: CodeBlockItemListSyntax) -> Syntax {
public override func visit(_ node: CodeBlockItemListSyntax) -> CodeBlockItemListSyntax {
// Continue recursing down the tree first, so that any nested/child nodes get transformed first.
let nodeAfterTransformingChildren = super.visit(node)
guard let codeBlockItems = nodeAfterTransformingChildren.as(CodeBlockItemListSyntax.self) else {
return nodeAfterTransformingChildren
}

let codeBlockItems = super.visit(node)

let result = CodeBlockItemListSyntax(
codeBlockItems.flatMap { (codeBlockItem: CodeBlockItemSyntax) -> [CodeBlockItemSyntax] in
// The `elseBody` of an `IfStmtSyntax` will be a `CodeBlockSyntax` if it's an `else` block,
Expand Down Expand Up @@ -84,7 +81,7 @@ public final class UseEarlyExits: SyntaxFormatRule {
CodeBlockItemSyntax(item: Syntax(trueBlock), semicolon: nil, errorTokens: nil),
]
})
return Syntax(result)
return result
}

/// Returns true if the last statement in the given code block is one that will cause an early
Expand Down
6 changes: 3 additions & 3 deletions Sources/SwiftFormatRules/UseShorthandTypeNames.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public final class UseShorthandTypeNames: SyntaxFormatRule {

// Ensure that all arguments in the clause are shortened and in the expected format by visiting
// the argument list, first.
let genericArgumentList = visit(genericArgumentClause.arguments).as(GenericArgumentListSyntax.self)!
let genericArgumentList = visit(genericArgumentClause.arguments)

let (leadingTrivia, trailingTrivia) = boundaryTrivia(around: Syntax(node))
let newNode: TypeSyntax?
Expand Down Expand Up @@ -125,7 +125,7 @@ public final class UseShorthandTypeNames: SyntaxFormatRule {
// Ensure that all arguments in the clause are shortened and in the expected format by visiting
// the argument list, first.
let genericArgumentList =
visit(node.genericArgumentClause.arguments).as(GenericArgumentListSyntax.self)!
visit(node.genericArgumentClause.arguments)

let (leadingTrivia, trailingTrivia) = boundaryTrivia(around: Syntax(node))
let newNode: ExprSyntax?
Expand Down Expand Up @@ -371,7 +371,7 @@ public final class UseShorthandTypeNames: SyntaxFormatRule {
// the identifier and the generic arguments. Otherwise, we can return just the
// `IdentifierExpr` itself.
if let genericArgumentClause = simpleTypeIdentifier.genericArgumentClause {
let newGenericArgumentClause = visit(genericArgumentClause).as(GenericArgumentClauseSyntax.self)!
let newGenericArgumentClause = visit(genericArgumentClause)
let result = SpecializeExprSyntax(
expression: ExprSyntax(identifierExpr),
genericArgumentClause: newGenericArgumentClause)
Expand Down
6 changes: 3 additions & 3 deletions Sources/SwiftFormatRules/UseSingleLinePropertyGetter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import SwiftSyntax
/// Format: Explicit `get` blocks are rendered implicit by removing the `get`.
public final class UseSingleLinePropertyGetter: SyntaxFormatRule {

public override func visit(_ node: PatternBindingSyntax) -> Syntax {
public override func visit(_ node: PatternBindingSyntax) -> PatternBindingSyntax {
guard
let accessorBlock = node.accessor?.as(AccessorBlockSyntax.self),
let acc = accessorBlock.accessors.first,
Expand All @@ -31,14 +31,14 @@ public final class UseSingleLinePropertyGetter: SyntaxFormatRule {
acc.modifier == nil,
acc.asyncKeyword == nil,
acc.throwsKeyword == nil
else { return Syntax(node) }
else { return node }

diagnose(.removeExtraneousGetBlock, on: acc)

let newBlock = CodeBlockSyntax(
leftBrace: accessorBlock.leftBrace, statements: body.statements,
rightBrace: accessorBlock.rightBrace)
return Syntax(node.withAccessor(Syntax(newBlock)))
return node.withAccessor(Syntax(newBlock))
}
}

Expand Down