Skip to content

Commit

Permalink
Preserve attached comments for printing ChainExpression nodes in Pret…
Browse files Browse the repository at this point in the history
…tier V2

Summary: This fixes a bug we've identified while running codemods that causes some comments to get dropped when they are attached to `ChainExpression` nodes.  This problem only exists in Prettier V2.

Reviewed By: gkz

Differential Revision: D50851144

fbshipit-source-id: 1acda37f80e301a6fe0ed52838df3de82ff2c8c1
  • Loading branch information
Alex Taylor (alta) authored and facebook-github-bot committed Nov 2, 2023
1 parent 20e0f44 commit e0592c9
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,22 @@

'use strict';

import type {ESNode, Program} from 'hermes-estree';
import type {ESNode, Program, Comment} from 'hermes-estree';
import type {VisitorKeysType} from '../traverse/getVisitorKeys';
import {SimpleTransform} from '../transform/SimpleTransform';

// https://github.com/prettier/prettier/blob/d962466a828f8ef51435e3e8840178d90b7ec6cd/src/language-js/parse/postprocess/index.js#L161-L182
function transformChainExpression(node: ESNode): ESNode {
function transformChainExpression(
node: ESNode,
comments: ?$ReadOnlyArray<Comment>,
): ESNode {
if (comments != null) {
// $FlowExpectedError[prop-missing]
const joinedComments = comments.concat(node.comments ?? []);
// $FlowExpectedError[prop-missing]
// $FlowFixMe[cannot-write]
node.comments = joinedComments;
}
switch (node.type) {
case 'CallExpression':
// $FlowExpectedError[cannot-spread-interface]
Expand Down Expand Up @@ -59,7 +69,8 @@ export default function mutate(
// so we have to apply their transform to our AST so it can actually format it.
// Note: Only needed for prettier V2, this is supported in V3
if (node.type === 'ChainExpression') {
return transformChainExpression(node.expression);
// $FlowFixMe[prop-missing]
return transformChainExpression(node.expression, node?.comments);
}

// Prettier currently relies on comparing the `node` vs `node.value` start positions to know if an
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1284,6 +1284,36 @@ foo?.[0]?.bar;
`);
});

it('should preserve attached comments on ChainExpression nodes', async () => {
const code = `\
foo(
// $FlowFixMe[prop-missing]
bar.baz,
// $FlowFixMe[prop-missing]
bar?.baz,
);
`;
const result = await transform(code, context => ({
Identifier(node) {
context.replaceNode(
node,
t.Identifier({
name: node.name,
}),
);
return;
},
}));
expect(result).toBe(`\
foo(
// $FlowFixMe[prop-missing]
bar.baz,
// $FlowFixMe[prop-missing]
bar?.baz,
);
`);
});

it('should correctly print method functions', async () => {
const code = `\
type A = {};`;
Expand Down

0 comments on commit e0592c9

Please sign in to comment.