|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +/// How to choose `assert` vs. `precondition`: |
| 14 | +/// - Wherever possible, it is preferrable to emit a diagnostic instead of |
| 15 | +/// using `precondition`. This way the parser won't crash if the condition is |
| 16 | +/// violated. |
| 17 | +/// - If you think the diagnostic added above should never be emitted, it is |
| 18 | +/// fine to also emit an `assertionFailure` in debug builds to make it easier |
| 19 | +/// to debug the unexpected diagnostic. |
| 20 | +/// - If in doubt always use `precondition` |
| 21 | +/// - `assert` should only be used if checking the assertion has a non-trivial |
| 22 | +/// cost and provides little benefit in terms of safety in release builds. |
| 23 | + |
| 24 | +// MARK: - Assert |
| 25 | + |
| 26 | +/// An assertion that is active in DEBUG builds, just like `Swift.assert` and |
| 27 | +/// additionally if assertions are explicitly requested by setting the |
| 28 | +/// `SWIFTSYNTAX_ENABLE_ASSERTIONS` conditional compilation flag. |
| 29 | +/// Use this instead of `precondition` in places where the assertion has a |
| 30 | +/// non-trivial cost but provides little value in release builds. |
| 31 | +@_transparent |
| 32 | +public func assert(_ condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String = String(), file: StaticString = #file, line: UInt = #line) { |
| 33 | + #if SWIFTSYNTAX_ENABLE_ASSERTIONS |
| 34 | + if !_fastPath(condition()) { |
| 35 | + fatalError(message(), file: file, line: line) |
| 36 | + } |
| 37 | + #else |
| 38 | + Swift.assert(condition(), message(), file: file, line: line) |
| 39 | + #endif |
| 40 | +} |
| 41 | + |
| 42 | +/// An assertion that is active in DEBUG builds, just like |
| 43 | +/// `Swift.assertionFailure` and additionally if assertions are explicitly |
| 44 | +/// requested by setting the `SWIFTSYNTAX_ENABLE_ASSERTIONS` conditional |
| 45 | +/// compilation flag. |
| 46 | +@_transparent |
| 47 | +public func assertionFailure(_ message: @autoclosure () -> String = String(), file: StaticString = #file, line: UInt = #line) { |
| 48 | + #if SWIFTSYNTAX_ENABLE_ASSERTIONS |
| 49 | + fatalError(message(), file: file, line: line) |
| 50 | + #else |
| 51 | + Swift.assertionFailure(message(), file: file, line: line) |
| 52 | + #endif |
| 53 | +} |
0 commit comments