@@ -2,12 +2,24 @@ import { NonterminalKind } from '@nomicfoundation/slang/kinds/index.js';
22import { util } from 'prettier' ;
33import { getNextNonSpaceNonCommentCharacter } from '../../slang-utils/backward-compatibility.js' ;
44import addHubNodeFirstComment from './add-hub-node-first-comment.js' ;
5- import addHubNodeLastComment from './add-hub-node-last-comment.js' ;
65
76import type { HandlerParams } from './types' ;
7+ import type { StatementVariant } from '../../slang-nodes/index.js' ;
8+ import type { Comment } from '../../types.js' ;
89
910const { addLeadingComment, addTrailingComment } = util ;
1011
12+ function addIfStatementBodyFirstComment (
13+ node : StatementVariant ,
14+ comment : Comment
15+ ) : void {
16+ if ( node . kind === NonterminalKind . Block ) {
17+ addHubNodeFirstComment ( node . statements , comment ) ;
18+ } else {
19+ addLeadingComment ( node , comment ) ;
20+ }
21+ }
22+
1123export default function handleIfStatementComments ( {
1224 text,
1325 precedingNode,
@@ -31,26 +43,29 @@ export default function handleIfStatementComments({
3143 }
3244
3345 // Comments before `else`:
34- // - treat as trailing comments of the consequent , if it's a BlockStatement
46+ // - treat as leading comments of the elseBranch , if it's a BlockStatement
3547 // - treat as a dangling comment otherwise
3648 if (
3749 precedingNode === enclosingNode . body &&
3850 followingNode === enclosingNode . elseBranch
3951 ) {
40- if ( precedingNode . variant . kind === NonterminalKind . Block ) {
41- addHubNodeLastComment ( precedingNode . variant . statements , comment ) ;
52+ if ( followingNode . body . variant . kind === NonterminalKind . Block ) {
53+ addHubNodeFirstComment ( followingNode . body . variant . statements , comment ) ;
54+ } else if (
55+ followingNode . body . variant . kind === NonterminalKind . IfStatement
56+ ) {
57+ addIfStatementBodyFirstComment (
58+ followingNode . body . variant . body . variant ,
59+ comment
60+ ) ;
4261 } else {
43- addTrailingComment ( precedingNode , comment ) ;
62+ addLeadingComment ( followingNode . body . variant , comment ) ;
4463 }
4564 return true ;
4665 }
4766
4867 if ( followingNode . kind === NonterminalKind . IfStatement ) {
49- if ( followingNode . body . variant . kind === NonterminalKind . Block ) {
50- addHubNodeFirstComment ( followingNode . body . variant . statements , comment ) ;
51- } else {
52- addLeadingComment ( followingNode . body . variant , comment ) ;
53- }
68+ addIfStatementBodyFirstComment ( followingNode . body . variant , comment ) ;
5469 return true ;
5570 }
5671
0 commit comments