Skip to content

Commit 2617557

Browse files
committed
different approach to find pragma comments as previous did not work in all cases
1 parent c9cedd6 commit 2617557

File tree

1 file changed

+45
-22
lines changed

1 file changed

+45
-22
lines changed

scripts/babel/transform-test-gate-pragma.js

Lines changed: 45 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -263,9 +263,54 @@ function transform(babel) {
263263
}
264264
}
265265

266+
function getComments(path) {
267+
if (path.node.leadingComments) {
268+
// Babel AST includes comments.
269+
return path.node.leadingComments;
270+
}
271+
// In Hermes AST we need to find the comments by range.
272+
const comments = [];
273+
let line = path.node.loc.start.line;
274+
let i = allComments.length - 1;
275+
while (i >= 0 && allComments[i].loc.end.line >= line) {
276+
i--;
277+
}
278+
while (i >= 0 && allComments[i].loc.end.line === line - 1) {
279+
const comment = allComments[i];
280+
line = comment.loc.start.line;
281+
comments.unshift(comment);
282+
if (usedComments.has(comment)) {
283+
throw new Error('expected to find just one place for comment');
284+
}
285+
usedComments.add(comment);
286+
i--;
287+
}
288+
return comments;
289+
}
290+
291+
let usedComments;
292+
let allComments;
266293
return {
267294
name: 'test-gate-pragma',
268295
visitor: {
296+
Program: {
297+
enter(path) {
298+
usedComments = new Set();
299+
allComments = path.parent.comments;
300+
},
301+
exit(path) {
302+
let unusedPragmaComment = allComments.find(
303+
c => c.value.trim().startsWith('@gate ') && !usedComments.has(c)
304+
);
305+
if (unusedPragmaComment != null) {
306+
throw path.hub.buildError(
307+
unusedPragmaComment,
308+
'@gate directive needs to be immediately before test/it call',
309+
Error
310+
);
311+
}
312+
},
313+
},
269314
ExpressionStatement(path) {
270315
const statement = path.node;
271316
const expression = statement.expression;
@@ -331,26 +376,4 @@ function transform(babel) {
331376
};
332377
}
333378

334-
function getComments(path) {
335-
if (path.node.leadingComments) {
336-
// Babel AST includes comments.
337-
return path.node.leadingComments;
338-
}
339-
// In Hermes AST we need to find the comments by range.
340-
const comments = path.hub.file.ast.comments;
341-
let prevSibling = path.getPrevSibling();
342-
let searchStart;
343-
if (prevSibling.node) {
344-
searchStart = prevSibling.node.end;
345-
} else if (path.parentPath.node) {
346-
searchStart = path.parentPath.node.start;
347-
} else {
348-
throw new Error('Unexpected AST structure');
349-
}
350-
const filteredComments = comments.filter(
351-
c => c.start >= searchStart && c.end <= path.node.start
352-
);
353-
return filteredComments.length > 0 ? filteredComments : undefined;
354-
}
355-
356379
module.exports = transform;

0 commit comments

Comments
 (0)