-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathhandle-if-statement-comments.ts
More file actions
68 lines (60 loc) · 2.11 KB
/
handle-if-statement-comments.ts
File metadata and controls
68 lines (60 loc) · 2.11 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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 handleIfStatementComments({
text,
precedingNode,
enclosingNode,
followingNode,
comment
}: HandlerParams): boolean {
if (enclosingNode?.kind !== NonterminalKind.IfStatement || !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:
// if (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 === ')') {
addTrailingComment(precedingNode, comment);
return true;
}
// Comments before `else`:
// - treat as leading comments of the elseBranch, if it's a BlockStatement
// - treat as a dangling comment otherwise
if (
precedingNode === enclosingNode.body &&
followingNode === enclosingNode.elseBranch
) {
addTrailingComment(precedingNode.variant, comment);
return true;
}
if (followingNode.kind === NonterminalKind.IfStatement) {
if (followingNode.body.variant.kind === NonterminalKind.Block) {
addCollectionFirstComment(followingNode.body.variant.statements, comment);
} else {
addLeadingComment(followingNode.body.variant, comment);
}
return true;
}
// For comments positioned after the condition parenthesis in an if statement
// before the consequent without brackets on, such as
// if (a) /* comment */ true
if (enclosingNode.body === followingNode) {
if (followingNode.variant.kind === NonterminalKind.Block) {
addCollectionFirstComment(followingNode.variant.statements, comment);
} else {
addLeadingComment(followingNode, comment);
}
return true;
}
return false;
}