From c3ba03a6fb22362f3ec643efcb083bb54f4cd6c7 Mon Sep 17 00:00:00 2001 From: Alex Hoppen Date: Fri, 28 Apr 2023 15:52:09 -0700 Subject: [PATCH] Add a conditional compilation flag to disable preconditions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In some situations, like an IDE that runs SwiftSyntax in process, crashing is the worst possible outcome and it’s preferrable to continue running, possibly accepting a misparse. These use cases can disable preconditions in SwiftSyntax using a conditional compilation flag rdar://108666839 --- Sources/SwiftSyntax/Assert.swift | 33 ++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/Sources/SwiftSyntax/Assert.swift b/Sources/SwiftSyntax/Assert.swift index 003947160de..a7607c65abb 100644 --- a/Sources/SwiftSyntax/Assert.swift +++ b/Sources/SwiftSyntax/Assert.swift @@ -29,7 +29,12 @@ /// Use this instead of `precondition` in places where the assertion has a /// non-trivial cost but provides little value in release builds. @_transparent -public func assert(_ condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String = String(), file: StaticString = #file, line: UInt = #line) { +public func assert( + _ condition: @autoclosure () -> Bool, + _ message: @autoclosure () -> String = String(), + file: StaticString = #file, + line: UInt = #line +) { #if SWIFTSYNTAX_ENABLE_ASSERTIONS if !_fastPath(condition()) { fatalError(message(), file: file, line: line) @@ -44,10 +49,34 @@ public func assert(_ condition: @autoclosure () -> Bool, _ message: @autoclosure /// requested by setting the `SWIFTSYNTAX_ENABLE_ASSERTIONS` conditional /// compilation flag. @_transparent -public func assertionFailure(_ message: @autoclosure () -> String = String(), file: StaticString = #file, line: UInt = #line) { +public func assertionFailure( + _ message: @autoclosure () -> String = String(), + file: StaticString = #file, + line: UInt = #line +) { #if SWIFTSYNTAX_ENABLE_ASSERTIONS fatalError(message(), file: file, line: line) #else Swift.assertionFailure(message(), file: file, line: line) #endif } + +// MARK: - Precondition + +/// Override Swift’s `precondition` with slightly changed semantics. +/// In release builds, it also emits the error message upon failure, like `fatalError`. +/// It can also be disabled by setting the `SWIFTSYNTAX_DISABLE_PRECONDITION` conditional compilation flag. +/// Note that `SWIFTSYNTAX_DISABLE_PRECONDITION` does not disable `preconditionFailure`. +@_transparent +public func precondition( + _ condition: @autoclosure () -> Bool, + _ message: @autoclosure () -> String = String(), + file: StaticString = #file, + line: UInt = #line +) { + #if !SWIFTSYNTAX_DISABLE_PRECONDITIONS + if !_fastPath(condition()) { + fatalError(message(), file: file, line: line) + } + #endif +}