forked from swiftlang/swift-format
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUseEarlyExits.swift
More file actions
109 lines (97 loc) · 4.08 KB
/
UseEarlyExits.swift
File metadata and controls
109 lines (97 loc) · 4.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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 SwiftFormatCore
import SwiftSyntax
/// Early exits should be used whenever possible.
///
/// This means that `if ... else { return/throw/break/continue }` constructs should be replaced by
/// `guard ... else { return/throw/break/continue }` constructs in order to keep indentation levels
/// low. Specifically, code of the following form:
///
/// ```swift
/// if condition {
/// trueBlock
/// } else {
/// falseBlock
/// return/throw/break/continue
/// }
/// ```
///
/// will be transformed into:
///
/// ```swift
/// guard condition else {
/// falseBlock
/// return/throw/break/continue
/// }
/// trueBlock
/// ```
///
/// Lint: `if ... else { return/throw/break/continue }` constructs will yield a lint error.
///
/// Format: `if ... else { return/throw/break/continue }` constructs will be replaced with
/// equivalent `guard ... else { return/throw/break/continue }` constructs.
public final class UseEarlyExits: SyntaxFormatRule {
/// Identifies this rule as being opt-in. This rule is experimental and not yet stable enough to
/// be enabled by default.
public override class var isOptIn: Bool { return true }
public override func visit(_ node: CodeBlockItemListSyntax) -> Syntax {
// 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 result = SyntaxFactory.makeCodeBlockItemList(
codeBlockItems.flatMap { (codeBlockItem: CodeBlockItemSyntax) -> [CodeBlockItemSyntax] in
// The `elseBody` of an `IfStmtSyntax` will be a `CodeBlockSyntax` if it's an `else` block,
// or another `IfStmtSyntax` if it's an `else if` block. We only want to handle the former.
guard let ifStatement = codeBlockItem.item.as(IfStmtSyntax.self),
let elseBody = ifStatement.elseBody?.as(CodeBlockSyntax.self),
codeBlockEndsWithEarlyExit(elseBody)
else {
return [codeBlockItem]
}
diagnose(.useGuardStatement, on: ifStatement.elseKeyword)
let trueBlock = ifStatement.body.withLeftBrace(nil).withRightBrace(nil)
let guardKeyword = SyntaxFactory.makeGuardKeyword(
leadingTrivia: ifStatement.ifKeyword.leadingTrivia,
trailingTrivia: .spaces(1))
let guardStatement = SyntaxFactory.makeGuardStmt(
guardKeyword: guardKeyword,
conditions: ifStatement.conditions,
elseKeyword: SyntaxFactory.makeElseKeyword(trailingTrivia: .spaces(1)),
body: elseBody)
return [
SyntaxFactory.makeCodeBlockItem(item: Syntax(guardStatement), semicolon: nil, errorTokens: nil),
SyntaxFactory.makeCodeBlockItem(item: Syntax(trueBlock), semicolon: nil, errorTokens: nil),
]
})
return Syntax(result)
}
/// Returns true if the last statement in the given code block is one that will cause an early
/// exit from the control flow construct or function.
private func codeBlockEndsWithEarlyExit(_ codeBlock: CodeBlockSyntax) -> Bool {
guard let lastStatement = codeBlock.statements.last else { return false }
switch lastStatement.item.as(SyntaxEnum.self) {
case .returnStmt, .throwStmt, .breakStmt, .continueStmt:
return true
default:
return false
}
}
}
extension Diagnostic.Message {
public static let useGuardStatement = Diagnostic.Message(
.warning,
"replace the `if/else` block with a `guard` statement containing the early exit"
)
}