-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathhandle-while-statement-comments.ts
More file actions
48 lines (42 loc) · 1.38 KB
/
handle-while-statement-comments.ts
File metadata and controls
48 lines (42 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { NonterminalKind } from '@nomicfoundation/slang/cst';
import { util } from 'prettier';
import { locEnd } from '../../slang-utils/loc.js';
import addCollectionFirstComment from './add-collection-first-comment.js';
import type { HandlerParams } from './types.d.ts';
const { addLeadingComment, addTrailingComment } = util;
export default function handleWhileStatementComments({
text,
precedingNode,
enclosingNode,
followingNode,
comment
}: HandlerParams): boolean {
if (
enclosingNode?.kind !== NonterminalKind.WhileStatement ||
!followingNode
) {
return false;
}
// We unfortunately have no way using the AST or location of nodes to know
// if the comment is positioned before the condition parenthesis:
// while (a /* comment */) {}
// The only workaround I found is to look at the next character to see if
// it is a ).
const nextCharacter = util.getNextNonSpaceNonCommentCharacter(
text,
locEnd(comment)
);
if (nextCharacter === ')' || enclosingNode.condition === precedingNode) {
addTrailingComment(precedingNode, comment);
return true;
}
if (enclosingNode.body === followingNode) {
if (followingNode.variant.kind === NonterminalKind.Block) {
addCollectionFirstComment(followingNode.variant.statements, comment);
} else {
addLeadingComment(followingNode, comment);
}
return true;
}
return false;
}