Skip to content

Commit eaefea6

Browse files
committed
Replace assert by precondition
1 parent 9764512 commit eaefea6

File tree

56 files changed

+2300
-1229
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+2300
-1229
lines changed

CodeGeneration/Sources/SyntaxSupport/Node.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,6 @@ public class Node {
162162
self.elementsSeparatedByNewline = elementsSeparatedByNewline
163163

164164
// For SyntaxCollections make sure that the elementName is set.
165-
assert(!isSyntaxCollection || elementName != nil || element != "")
165+
precondition(!isSyntaxCollection || elementName != nil || element != "")
166166
}
167167
}

CodeGeneration/Sources/Utils/SyntaxBuildableChild.swift

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ public extension Child {
6363
}
6464

6565
/// If this node is a token that can't contain arbitrary text, generate a Swift
66-
/// `assert` statement that verifies the variable with name var_name and of type
66+
/// `precondition` statement that verifies the variable with name var_name and of type
6767
/// `TokenSyntax` contains one of the supported text options. Otherwise return `nil`.
6868
func generateAssertStmtTextChoices(varName: String) -> FunctionCallExprSyntax? {
6969
guard case .token(choices: let choices, requiresLeadingSpace: _, requiresTrailingSpace: _) = kind else {
@@ -79,7 +79,7 @@ public extension Child {
7979

8080
let choicesTexts: [String]
8181
if tokenCanContainArbitraryText {
82-
// Don't generate an assert statement if token can contain arbitrary text.
82+
// Don't generate an precondition statement if token can contain arbitrary text.
8383
return nil
8484
} else if !choices.isEmpty {
8585
choicesTexts = choices.compactMap {
@@ -92,9 +92,9 @@ public extension Child {
9292
return nil
9393
}
9494

95-
var assertChoices: [ExprSyntax] = []
95+
var preconditionChoices: [ExprSyntax] = []
9696
if type.isOptional {
97-
assertChoices.append(
97+
preconditionChoices.append(
9898
ExprSyntax(
9999
SequenceExprSyntax {
100100
IdentifierExprSyntax(identifier: .identifier(varName))
@@ -105,7 +105,7 @@ public extension Child {
105105
)
106106
}
107107
for textChoice in choicesTexts {
108-
assertChoices.append(
108+
preconditionChoices.append(
109109
ExprSyntax(
110110
SequenceExprSyntax {
111111
MemberAccessExprSyntax(base: type.forceUnwrappedIfNeeded(expr: IdentifierExprSyntax(identifier: .identifier(varName))), name: "text")
@@ -115,8 +115,8 @@ public extension Child {
115115
)
116116
)
117117
}
118-
let disjunction = ExprListSyntax(assertChoices.flatMap { [$0, ExprSyntax(BinaryOperatorExprSyntax(text: "||"))] }.dropLast())
119-
return FunctionCallExprSyntax(callee: ExprSyntax("assert")) {
118+
let disjunction = ExprListSyntax(preconditionChoices.flatMap { [$0, ExprSyntax(BinaryOperatorExprSyntax(text: "||"))] }.dropLast())
119+
return FunctionCallExprSyntax(callee: ExprSyntax("precondition")) {
120120
TupleExprElementSyntax(expression: SequenceExprSyntax(elements: disjunction))
121121
}
122122
}

CodeGeneration/Sources/Utils/SyntaxBuildableNode.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,14 +44,14 @@ public extension Node {
4444

4545
/// Assuming this node is a syntax collection, the type of its elements.
4646
var collectionElementType: SyntaxBuildableType {
47-
assert(isSyntaxCollection)
47+
precondition(isSyntaxCollection)
4848
return SyntaxBuildableType(syntaxKind: collectionElement)
4949
}
5050

5151
/// Assuming this node has a single child without a default value, that child.
5252
var singleNonDefaultedChild: Child {
5353
let nonDefaultedParams = children.filter { $0.type.defaultInitialization == nil }
54-
assert(nonDefaultedParams.count == 1)
54+
precondition(nonDefaultedParams.count == 1)
5555
return nonDefaultedParams[0]
5656
}
5757

CodeGeneration/Sources/generate-swiftsyntax/templates/swiftparser/ParserEntryFile.swift

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,7 @@ let parserEntryFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
7878
"""
7979
mutating func parseRemainder<R: RawSyntaxNodeProtocol>(into: R) -> R {
8080
guard !into.raw.kind.isSyntaxCollection, let layout = into.raw.layoutView else {
81-
assertionFailure("Only support parsing of non-collection layout nodes")
82-
return into
81+
preconditionFailure("Only support parsing of non-collection layout nodes")
8382
}
8483
8584
let remainingTokens = self.consumeRemainingTokens()
@@ -89,7 +88,7 @@ let parserEntryFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
8988
9089
let existingUnexpected: [RawSyntax]
9190
if let unexpectedNode = layout.children[layout.children.count - 1] {
92-
assert(unexpectedNode.is(RawUnexpectedNodesSyntax.self))
91+
precondition(unexpectedNode.is(RawUnexpectedNodesSyntax.self))
9392
existingUnexpected = unexpectedNode.as(RawUnexpectedNodesSyntax.self).elements
9493
} else {
9594
existingUnexpected = []

CodeGeneration/Sources/generate-swiftsyntax/templates/swiftsyntax/RawSyntaxNodesFile.swift

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,15 @@ let rawSyntaxNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
129129
DeclSyntax(
130130
"""
131131
init(raw: RawSyntax) {
132-
assert(Self.isKindOf(raw))
132+
precondition(Self.isKindOf(raw))
133+
self.raw = raw
134+
}
135+
"""
136+
)
137+
138+
DeclSyntax(
139+
"""
140+
private init(unchecked raw: RawSyntax) {
133141
self.raw = raw
134142
}
135143
"""
@@ -139,7 +147,7 @@ let rawSyntaxNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
139147
"""
140148
public init?<Node: RawSyntaxNodeProtocol>(_ other: Node) {
141149
guard Self.isKindOf(other.raw) else { return nil }
142-
self.init(raw: other.raw)
150+
self.init(unchecked: other.raw)
143151
}
144152
"""
145153
)
@@ -148,7 +156,7 @@ let rawSyntaxNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
148156
DeclSyntax(
149157
"""
150158
public init<Node: Raw\(raw: node.name)NodeProtocol>(_ other: Node) {
151-
self.init(raw: other.raw)
159+
self.init(unchecked: other.raw)
152160
}
153161
"""
154162
)
@@ -167,7 +175,7 @@ let rawSyntaxNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
167175
ptr += 1
168176
}
169177
}
170-
self.init(raw: raw)
178+
self.init(unchecked: raw)
171179
}
172180
"""
173181
)
@@ -217,7 +225,7 @@ let rawSyntaxNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
217225
} else {
218226
DeclSyntax("let raw = RawSyntax.makeEmptyLayout(kind: .\(raw: node.swiftSyntaxKind), arena: arena)")
219227
}
220-
ExprSyntax("self.init(raw: raw)")
228+
ExprSyntax("self.init(unchecked: raw)")
221229
}
222230

223231
for (index, child) in node.children.enumerated() {

CodeGeneration/Sources/generate-swiftsyntax/templates/swiftsyntax/SyntaxCollectionsFile.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ let syntaxCollectionsFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
158158
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
159159
/// is undefined.
160160
internal init(_ data: SyntaxData) {
161-
assert(data.raw.kind == .\(raw: node.swiftSyntaxKind))
161+
precondition(data.raw.kind == .\(raw: node.swiftSyntaxKind))
162162
self._syntaxNode = Syntax(data)
163163
}
164164
"""

CodeGeneration/Sources/generate-swiftsyntax/templates/swiftsyntax/SyntaxNodeFile.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ func syntaxNode(emitKind: String) -> SourceFileSyntax {
5959
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
6060
/// is undefined.
6161
internal init(_ data: SyntaxData) {
62-
assert(data.raw.kind == .\(raw: node.swiftSyntaxKind))
62+
precondition(data.raw.kind == .\(raw: node.swiftSyntaxKind))
6363
self._syntaxNode = Syntax(data)
6464
}
6565
"""

CodeGeneration/Sources/generate-swiftsyntax/templates/swiftsyntax/SyntaxRewriterFile.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,7 @@ let syntaxRewriterFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
320320
// A child node was rewritten. Build the updated node.
321321
322322
// Sanity check, ensure the new children are the same length.
323-
assert(newLayout.count == node.raw.layoutView!.children.count)
323+
precondition(newLayout.count == node.raw.layoutView!.children.count)
324324
325325
let arena = SyntaxArena()
326326
let newRaw = node.raw.layoutView!.replacingLayout(with: Array(newLayout), arena: arena)

CodeGeneration/Sources/generate-swiftsyntax/templates/swiftsyntax/TokenKindFile.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ let tokenKindFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
282282
}
283283
} else if token.text != nil {
284284
SwitchCaseSyntax("case .\(raw: token.swiftKind):") {
285-
ExprSyntax("assert(text.isEmpty || rawKind.defaultText.map(String.init) == text)")
285+
ExprSyntax("precondition(text.isEmpty || rawKind.defaultText.map(String.init) == text)")
286286
StmtSyntax("return .\(raw: token.swiftKind)")
287287
}
288288
} else {

Sources/IDEUtils/SyntaxClassifier.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ private struct ClassificationVisitor {
189189
byteOffset += piece.byteLength
190190
}
191191

192-
assert(byteOffset == descriptor.byteOffset + descriptor.node.byteLength)
192+
precondition(byteOffset == descriptor.byteOffset + descriptor.node.byteLength)
193193
return .continue
194194
}
195195

Sources/SwiftCompilerPlugin/CompilerPlugin.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ internal struct PluginHostConnection: MessageConnection {
179179
// Write the header (a 64-bit length field in little endian byte order).
180180
var count = UInt64(payload.count).littleEndian
181181
let header = Swift.withUnsafeBytes(of: &count) { Data($0) }
182-
assert(header.count == 8)
182+
precondition(header.count == 8)
183183

184184
// Write the header and payload.
185185
try outputStream._write(contentsOf: header)

Sources/SwiftCompilerPluginMessageHandling/PluginMacroExpansionContext.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ class SourceManager {
127127
}
128128
let localStartPosition = node.position(at: startKind)
129129
let localEndPosition = node.position(at: endKind)
130-
assert(localStartPosition <= localEndPosition)
130+
precondition(localStartPosition <= localEndPosition)
131131

132132
let positionOffset = base.location.offset
133133

Sources/SwiftDiagnostics/Diagnostic.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ public struct DiagnosticsError: Error {
8080
public init(diagnostics: [Diagnostic]) {
8181
self.diagnostics = diagnostics
8282

83-
assert(
83+
precondition(
8484
diagnostics.contains(where: { $0.diagMessage.severity == .error }),
8585
"at least one diagnostic must have severity == .error"
8686
)

Sources/SwiftDiagnostics/DiagnosticsFormatter.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ extension Sequence where Element == Range<Int> {
2929
}
3030

3131
// If the ranges overlap, expand the prior range.
32-
assert(priorRange.lowerBound <= range.lowerBound)
32+
precondition(priorRange.lowerBound <= range.lowerBound)
3333
if priorRange.overlaps(range) {
3434
let lower = priorRange.lowerBound
3535
let upper = Swift.max(priorRange.upperBound, range.upperBound)

Sources/SwiftDiagnostics/FixIt.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ public struct FixIt {
5757
public let changes: Changes
5858

5959
public init(message: FixItMessage, changes: Changes) {
60-
assert(!changes.changes.isEmpty, "A Fix-It must have at least one change associated with it")
60+
precondition(!changes.changes.isEmpty, "A Fix-It must have at least one change associated with it")
6161
self.message = message
6262
self.changes = changes
6363
}

Sources/SwiftParser/Declarations.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -464,7 +464,7 @@ extension Parser {
464464
)
465465
}
466466

467-
assert(self.currentToken.starts(with: "<"))
467+
precondition(self.currentToken.starts(with: "<"))
468468
let langle = self.consumeAnyToken(remapping: .leftAngle)
469469
var elements = [RawGenericParameterSyntax]()
470470
do {

Sources/SwiftParser/Expressions.swift

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ extension Parser {
192192
return lastElement
193193
}
194194

195-
assert(
195+
precondition(
196196
elements.count.isMultiple(of: 2),
197197
"elements must have a even number of elements"
198198
)
@@ -619,7 +619,7 @@ extension Parser {
619619
declNameArgs: RawDeclNameArgumentsSyntax?,
620620
generics: RawGenericArgumentClauseSyntax?
621621
) {
622-
assert(self.at(.period))
622+
precondition(self.at(.period))
623623
let (unexpectedPeriod, period, skipMemberName) = self.consumeMemberPeriod(previousNode: previousNode)
624624
if skipMemberName {
625625
let missingIdentifier = missingToken(.identifier)
@@ -685,7 +685,7 @@ extension Parser {
685685
_ flavor: ExprFlavor,
686686
forDirective: Bool
687687
) -> RawExprSyntax {
688-
assert(self.at(.poundIfKeyword))
688+
precondition(self.at(.poundIfKeyword))
689689

690690
let config = self.parsePoundIfDirective { (parser, isFirstElement) -> RawExprSyntax? in
691691
if !isFirstElement {
@@ -978,7 +978,7 @@ extension Parser {
978978
if self.currentToken.starts(with: "!") {
979979
questionOrExclaim = self.consumePrefix("!", as: .exclamationMark)
980980
} else {
981-
assert(self.currentToken.starts(with: "?"))
981+
precondition(self.currentToken.starts(with: "?"))
982982
questionOrExclaim = self.consumePrefix("?", as: .postfixQuestionMark)
983983
}
984984

@@ -1044,7 +1044,7 @@ extension Parser {
10441044
period = nil
10451045
}
10461046

1047-
assert(self.at(.leftSquareBracket))
1047+
precondition(self.at(.leftSquareBracket))
10481048
let lsquare = self.consumeAnyToken()
10491049
let args: [RawTupleExprElementSyntax]
10501050
if self.at(.rightSquareBracket) {
@@ -2085,7 +2085,7 @@ extension Parser.Lookahead {
20852085
/// handle this by doing some lookahead in common situations. And later, Sema
20862086
/// will emit a diagnostic with a fixit to add wrapping parens.
20872087
mutating func isValidTrailingClosure(_ flavor: Parser.ExprFlavor) -> Bool {
2088-
assert(self.at(.leftBrace), "Couldn't be a trailing closure")
2088+
precondition(self.at(.leftBrace), "Couldn't be a trailing closure")
20892089

20902090
// If this is the start of a get/set accessor, then it isn't a trailing
20912091
// closure.
@@ -2270,7 +2270,7 @@ extension Parser {
22702270
{ (parser, _) in parser.parseSwitchCases(allowStandaloneStmtRecovery: allowStandaloneStmtRecovery) },
22712271
syntax: { parser, cases in
22722272
guard cases.count == 1, let firstCase = cases.first else {
2273-
assert(cases.isEmpty)
2273+
precondition(cases.isEmpty)
22742274
return .switchCases(RawSwitchCaseListSyntax(elements: [], arena: parser.arena))
22752275
}
22762276
return .switchCases(firstCase)

0 commit comments

Comments
 (0)