Skip to content

Replace assert by precondition in most places #1427

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 1 commit into from
Mar 24, 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
2 changes: 1 addition & 1 deletion CodeGeneration/Sources/SyntaxSupport/Node.swift
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,6 @@ public class Node {
self.elementsSeparatedByNewline = elementsSeparatedByNewline

// For SyntaxCollections make sure that the elementName is set.
assert(!isSyntaxCollection || elementName != nil || element != "")
precondition(!isSyntaxCollection || elementName != nil || element != "")
}
}
14 changes: 7 additions & 7 deletions CodeGeneration/Sources/Utils/SyntaxBuildableChild.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public extension Child {
}

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

let choicesTexts: [String]
if tokenCanContainArbitraryText {
// Don't generate an assert statement if token can contain arbitrary text.
// Don't generate an precondition statement if token can contain arbitrary text.
return nil
} else if !choices.isEmpty {
choicesTexts = choices.compactMap {
Expand All @@ -92,9 +92,9 @@ public extension Child {
return nil
}

var assertChoices: [ExprSyntax] = []
var preconditionChoices: [ExprSyntax] = []
if type.isOptional {
assertChoices.append(
preconditionChoices.append(
ExprSyntax(
SequenceExprSyntax {
IdentifierExprSyntax(identifier: .identifier(varName))
Expand All @@ -105,7 +105,7 @@ public extension Child {
)
}
for textChoice in choicesTexts {
assertChoices.append(
preconditionChoices.append(
ExprSyntax(
SequenceExprSyntax {
MemberAccessExprSyntax(base: type.forceUnwrappedIfNeeded(expr: IdentifierExprSyntax(identifier: .identifier(varName))), name: "text")
Expand All @@ -115,8 +115,8 @@ public extension Child {
)
)
}
let disjunction = ExprListSyntax(assertChoices.flatMap { [$0, ExprSyntax(BinaryOperatorExprSyntax(text: "||"))] }.dropLast())
return FunctionCallExprSyntax(callee: ExprSyntax("assert")) {
let disjunction = ExprListSyntax(preconditionChoices.flatMap { [$0, ExprSyntax(BinaryOperatorExprSyntax(text: "||"))] }.dropLast())
return FunctionCallExprSyntax(callee: ExprSyntax("precondition")) {
TupleExprElementSyntax(expression: SequenceExprSyntax(elements: disjunction))
}
}
Expand Down
4 changes: 2 additions & 2 deletions CodeGeneration/Sources/Utils/SyntaxBuildableNode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,14 @@ public extension Node {

/// Assuming this node is a syntax collection, the type of its elements.
var collectionElementType: SyntaxBuildableType {
assert(isSyntaxCollection)
precondition(isSyntaxCollection)
return SyntaxBuildableType(syntaxKind: collectionElement)
}

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,7 @@ let parserEntryFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
"""
mutating func parseRemainder<R: RawSyntaxNodeProtocol>(into: R) -> R {
guard !into.raw.kind.isSyntaxCollection, let layout = into.raw.layoutView else {
assertionFailure("Only support parsing of non-collection layout nodes")
return into
preconditionFailure("Only support parsing of non-collection layout nodes")
}

let remainingTokens = self.consumeRemainingTokens()
Expand All @@ -89,7 +88,7 @@ let parserEntryFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {

let existingUnexpected: [RawSyntax]
if let unexpectedNode = layout.children[layout.children.count - 1] {
assert(unexpectedNode.is(RawUnexpectedNodesSyntax.self))
precondition(unexpectedNode.is(RawUnexpectedNodesSyntax.self))
existingUnexpected = unexpectedNode.as(RawUnexpectedNodesSyntax.self).elements
} else {
existingUnexpected = []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,15 @@ let rawSyntaxNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
DeclSyntax(
"""
init(raw: RawSyntax) {
assert(Self.isKindOf(raw))
precondition(Self.isKindOf(raw))
self.raw = raw
}
"""
)

DeclSyntax(
"""
private init(unchecked raw: RawSyntax) {
self.raw = raw
}
"""
Expand All @@ -139,7 +147,7 @@ let rawSyntaxNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
"""
public init?<Node: RawSyntaxNodeProtocol>(_ other: Node) {
guard Self.isKindOf(other.raw) else { return nil }
self.init(raw: other.raw)
self.init(unchecked: other.raw)
}
"""
)
Expand All @@ -148,7 +156,7 @@ let rawSyntaxNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
DeclSyntax(
"""
public init<Node: Raw\(raw: node.name)NodeProtocol>(_ other: Node) {
self.init(raw: other.raw)
self.init(unchecked: other.raw)
}
"""
)
Expand All @@ -167,7 +175,7 @@ let rawSyntaxNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
ptr += 1
}
}
self.init(raw: raw)
self.init(unchecked: raw)
}
"""
)
Expand Down Expand Up @@ -217,7 +225,7 @@ let rawSyntaxNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
} else {
DeclSyntax("let raw = RawSyntax.makeEmptyLayout(kind: .\(raw: node.swiftSyntaxKind), arena: arena)")
}
ExprSyntax("self.init(raw: raw)")
ExprSyntax("self.init(unchecked: raw)")
}

for (index, child) in node.children.enumerated() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ let syntaxCollectionsFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .\(raw: node.swiftSyntaxKind))
precondition(data.raw.kind == .\(raw: node.swiftSyntaxKind))
self._syntaxNode = Syntax(data)
}
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func syntaxNode(emitKind: String) -> SourceFileSyntax {
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .\(raw: node.swiftSyntaxKind))
precondition(data.raw.kind == .\(raw: node.swiftSyntaxKind))
self._syntaxNode = Syntax(data)
}
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ let syntaxRewriterFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
// A child node was rewritten. Build the updated node.

// Sanity check, ensure the new children are the same length.
assert(newLayout.count == node.raw.layoutView!.children.count)
precondition(newLayout.count == node.raw.layoutView!.children.count)

let arena = SyntaxArena()
let newRaw = node.raw.layoutView!.replacingLayout(with: Array(newLayout), arena: arena)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ let tokenKindFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
}
} else if token.text != nil {
SwitchCaseSyntax("case .\(raw: token.swiftKind):") {
ExprSyntax("assert(text.isEmpty || rawKind.defaultText.map(String.init) == text)")
ExprSyntax("precondition(text.isEmpty || rawKind.defaultText.map(String.init) == text)")
StmtSyntax("return .\(raw: token.swiftKind)")
}
} else {
Expand Down
2 changes: 1 addition & 1 deletion Sources/IDEUtils/SyntaxClassifier.swift
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ private struct ClassificationVisitor {
byteOffset += piece.byteLength
}

assert(byteOffset == descriptor.byteOffset + descriptor.node.byteLength)
precondition(byteOffset == descriptor.byteOffset + descriptor.node.byteLength)
return .continue
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftCompilerPlugin/CompilerPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ internal struct PluginHostConnection: MessageConnection {
// Write the header (a 64-bit length field in little endian byte order).
var count = UInt64(payload.count).littleEndian
let header = Swift.withUnsafeBytes(of: &count) { Data($0) }
assert(header.count == 8)
precondition(header.count == 8)

// Write the header and payload.
try outputStream._write(contentsOf: header)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ class SourceManager {
}
let localStartPosition = node.position(at: startKind)
let localEndPosition = node.position(at: endKind)
assert(localStartPosition <= localEndPosition)
precondition(localStartPosition <= localEndPosition)

let positionOffset = base.location.offset

Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftDiagnostics/Diagnostic.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public struct DiagnosticsError: Error {
public init(diagnostics: [Diagnostic]) {
self.diagnostics = diagnostics

assert(
precondition(
diagnostics.contains(where: { $0.diagMessage.severity == .error }),
"at least one diagnostic must have severity == .error"
)
Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftDiagnostics/DiagnosticsFormatter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ extension Sequence where Element == Range<Int> {
}

// If the ranges overlap, expand the prior range.
assert(priorRange.lowerBound <= range.lowerBound)
precondition(priorRange.lowerBound <= range.lowerBound)
if priorRange.overlaps(range) {
let lower = priorRange.lowerBound
let upper = Swift.max(priorRange.upperBound, range.upperBound)
Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftDiagnostics/FixIt.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public struct FixIt {
public let changes: Changes

public init(message: FixItMessage, changes: Changes) {
assert(!changes.changes.isEmpty, "A Fix-It must have at least one change associated with it")
precondition(!changes.changes.isEmpty, "A Fix-It must have at least one change associated with it")
self.message = message
self.changes = changes
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftParser/Declarations.swift
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,7 @@ extension Parser {
)
}

assert(self.currentToken.starts(with: "<"))
precondition(self.currentToken.starts(with: "<"))
let langle = self.consumeAnyToken(remapping: .leftAngle)
var elements = [RawGenericParameterSyntax]()
do {
Expand Down
14 changes: 7 additions & 7 deletions Sources/SwiftParser/Expressions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ extension Parser {
return lastElement
}

assert(
precondition(
elements.count.isMultiple(of: 2),
"elements must have a even number of elements"
)
Expand Down Expand Up @@ -619,7 +619,7 @@ extension Parser {
declNameArgs: RawDeclNameArgumentsSyntax?,
generics: RawGenericArgumentClauseSyntax?
) {
assert(self.at(.period))
precondition(self.at(.period))
let (unexpectedPeriod, period, skipMemberName) = self.consumeMemberPeriod(previousNode: previousNode)
if skipMemberName {
let missingIdentifier = missingToken(.identifier)
Expand Down Expand Up @@ -685,7 +685,7 @@ extension Parser {
_ flavor: ExprFlavor,
forDirective: Bool
) -> RawExprSyntax {
assert(self.at(.poundIfKeyword))
precondition(self.at(.poundIfKeyword))

let config = self.parsePoundIfDirective { (parser, isFirstElement) -> RawExprSyntax? in
if !isFirstElement {
Expand Down Expand Up @@ -978,7 +978,7 @@ extension Parser {
if self.currentToken.starts(with: "!") {
questionOrExclaim = self.consumePrefix("!", as: .exclamationMark)
} else {
assert(self.currentToken.starts(with: "?"))
precondition(self.currentToken.starts(with: "?"))
questionOrExclaim = self.consumePrefix("?", as: .postfixQuestionMark)
}

Expand Down Expand Up @@ -1044,7 +1044,7 @@ extension Parser {
period = nil
}

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

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