Skip to content

Commit 0a6a288

Browse files
committed
refactor(linter/plugins): add debugAssert function (#15969)
Add a `debugAssert` function, which works the same as `debug_assert!` in Rust. We can use this to add more assertions to rest of code. Same as `debugAssertIsNonNull` and `typeAssertIs`, this function will be removed entirely in release build - it only performs the check in debug build (which is used in the tests).
1 parent ae13704 commit 0a6a288

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

apps/oxlint/src-js/utils/asserts.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ export function typeAssertIs<T>(value: unknown): asserts value is T {}
1515
* In release builds, is a no-op. Only does runtime checks in debug builds.
1616
* Minification removes this function and all calls to it in release builds, so it has zero runtime cost.
1717
*
18+
* Use this for testing conditions which would indicate a bug in the code.
19+
* Do NOT use this for validating user input.
20+
*
1821
* @param value - Value
1922
*/
2023
export function debugAssertIsNonNull<T>(value: T | null | undefined): asserts value is T {
@@ -25,3 +28,32 @@ export function debugAssertIsNonNull<T>(value: T | null | undefined): asserts va
2528
throw new Error(`Expected non-null value, got ${value}`);
2629
}
2730
}
31+
32+
/**
33+
* Assert a condition.
34+
*
35+
* In release builds, is a no-op. Only does runtime checks in debug builds.
36+
* Minification removes this function and all calls to it in release builds, so it has zero runtime cost.
37+
*
38+
* Use this for testing conditions which would indicate a bug in the code.
39+
* Do NOT use this for validating user input.
40+
*
41+
* If creating the error message is expensive, or potentially creating the message itself can result in an error
42+
* when the assertion passes, pass a function which returns the message.
43+
*
44+
* ```ts
45+
* debugAssert(condition, () => `Condition failed: ${getErrorMessage()}`);
46+
* ```
47+
*
48+
* @param condition - Condition which is expected to be `true`
49+
* @param message - Message to include in error if condition is `false`,
50+
* or a function which returns the message to include in error if condition is `false` (optional).
51+
*/
52+
export function debugAssert(condition: boolean, message?: string | (() => string)): asserts condition {
53+
if (!DEBUG) return;
54+
55+
if (!condition) {
56+
if (typeof message === 'function') message = message();
57+
throw new Error(message ?? 'Assertion failed');
58+
}
59+
}

0 commit comments

Comments
 (0)