Skip to content

Commit c8edaa8

Browse files
committed
Add a conditional compilation flag to disable preconditions
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
1 parent 3d53f9d commit c8edaa8

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

Sources/SwiftSyntax/Assert.swift

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,12 @@
2929
/// Use this instead of `precondition` in places where the assertion has a
3030
/// non-trivial cost but provides little value in release builds.
3131
@_transparent
32-
public func assert(_ condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String = String(), file: StaticString = #file, line: UInt = #line) {
32+
public func assert(
33+
_ condition: @autoclosure () -> Bool,
34+
_ message: @autoclosure () -> String = String(),
35+
file: StaticString = #file,
36+
line: UInt = #line
37+
) {
3338
#if SWIFTSYNTAX_ENABLE_ASSERTIONS
3439
if !_fastPath(condition()) {
3540
fatalError(message(), file: file, line: line)
@@ -44,10 +49,34 @@ public func assert(_ condition: @autoclosure () -> Bool, _ message: @autoclosure
4449
/// requested by setting the `SWIFTSYNTAX_ENABLE_ASSERTIONS` conditional
4550
/// compilation flag.
4651
@_transparent
47-
public func assertionFailure(_ message: @autoclosure () -> String = String(), file: StaticString = #file, line: UInt = #line) {
52+
public func assertionFailure(
53+
_ message: @autoclosure () -> String = String(),
54+
file: StaticString = #file,
55+
line: UInt = #line
56+
) {
4857
#if SWIFTSYNTAX_ENABLE_ASSERTIONS
4958
fatalError(message(), file: file, line: line)
5059
#else
5160
Swift.assertionFailure(message(), file: file, line: line)
5261
#endif
5362
}
63+
64+
// MARK: - Precondition
65+
66+
/// Override Swift’s `precondition` with slightly changed semantics.
67+
/// In release builds, it also emits the error message upon failure, like `fatalError`.
68+
/// It can also be disabled by setting the `SWIFTSYNTAX_DISABLE_PRECONDITION` conditional compilation flag.
69+
/// Note that `SWIFTSYNTAX_DISABLE_PRECONDITION` does not disable `preconditionFailure`.
70+
@_transparent
71+
public func precondition(
72+
_ condition: @autoclosure () -> Bool,
73+
_ message: @autoclosure () -> String = String(),
74+
file: StaticString = #file,
75+
line: UInt = #line
76+
) {
77+
#if !SWIFTSYNTAX_DISABLE_PRECONDITIONS
78+
if !_fastPath(condition()) {
79+
fatalError(message(), file: file, line: line)
80+
}
81+
#endif
82+
}

0 commit comments

Comments
 (0)