Skip to content

Commit 74e1f3d

Browse files
committed
refactor(linter/plugins): more debug assertions in initTokensWithComments (#16116)
Follow-on after #16071. Add more debug assertions to ensure `comments` and `tokens` are merged correctly. This code is removed in release build - just for tests.
1 parent 4691c72 commit 74e1f3d

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

apps/oxlint/src-js/plugins/tokens.ts

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -217,9 +217,34 @@ function initTokensWithComments() {
217217
while (commentsIndex < commentsLength) tokensWithComments.push(comments[commentsIndex++]);
218218
while (tokensIndex < tokensLength) tokensWithComments.push(tokens[tokensIndex++]);
219219

220-
if (DEBUG) {
221-
if (tokensWithComments.length !== tokensLength + commentsLength) {
222-
throw new Error("Not all tokens and comments were merged");
220+
debugCheckTokensWithComments();
221+
}
222+
223+
/**
224+
* Check `tokensWithComments` contains all tokens and comments, in ascending order.
225+
*
226+
* Only runs in debug build (tests). In release build, this function is entirely removed by minifier.
227+
*/
228+
function debugCheckTokensWithComments() {
229+
if (!DEBUG) return;
230+
231+
debugAssertIsNonNull(tokens);
232+
debugAssertIsNonNull(comments);
233+
debugAssertIsNonNull(tokensWithComments);
234+
235+
const expected = [...tokens, ...comments];
236+
expected.sort((a, b) => {
237+
if (a.range[0] === b.range[0]) throw new Error("2 tokens/comments have the same start");
238+
return a.range[0] - b.range[0];
239+
});
240+
241+
if (tokensWithComments.length !== expected.length) {
242+
throw new Error("`tokensWithComments` has wrong length");
243+
}
244+
245+
for (let i = 0; i < tokensWithComments.length; i++) {
246+
if (tokensWithComments[i] !== expected[i]) {
247+
throw new Error("`tokensWithComments` is not correctly ordered");
223248
}
224249
}
225250
}

0 commit comments

Comments
 (0)