Skip to content

Commit

Permalink
Falback to printing inner comments as trailing (#15144)
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed Nov 7, 2022
1 parent f6336da commit 156b608
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 12 deletions.
31 changes: 22 additions & 9 deletions packages/babel-generator/src/printer.ts
Expand Up @@ -787,15 +787,28 @@ class Printer {
}

_printTrailingComments(node: t.Node, parent?: t.Node, lineOffset?: number) {
const comments = node.trailingComments;
if (!comments?.length) return;
this._printComments(
COMMENT_TYPE.TRAILING,
comments,
node,
parent,
lineOffset,
);
const { innerComments, trailingComments } = node;
// We print inner comments here, so that if for some reason they couldn't
// be printed in earlier locations they are still printed *somehwere*,
// even if at the end of the node.
if (innerComments?.length) {
this._printComments(
COMMENT_TYPE.TRAILING,
innerComments,
node,
parent,
lineOffset,
);
}
if (trailingComments?.length) {
this._printComments(
COMMENT_TYPE.TRAILING,
trailingComments,
node,
parent,
lineOffset,
);
}
}

_printLeadingComments(node: t.Node, parent: t.Node) {
Expand Down
Expand Up @@ -6,8 +6,8 @@ C /* 2 */[

type T2 = U.
/* 1 */
C /* 2 */[];

C /* 2 */[]
/* 3 */;


type T3 = U.
Expand Down
34 changes: 34 additions & 0 deletions packages/babel-generator/test/index.js
Expand Up @@ -1133,6 +1133,40 @@ describe("programmatic generation", function () {
expect(output).toBe("for ((let)[x];;);");
});
});

describe("should print inner comments even if there are no suitable inner locations", () => {
it("atomic node", () => {
const id = t.identifier("foo");
id.innerComments = [{ type: "CommentBlock", value: "foo" }];
expect(generate(id).code).toMatchInlineSnapshot(`"foo /*foo*/"`);
});

it("node without inner locations", () => {
const expr = t.binaryExpression(
"+",
t.numericLiteral(1),
t.numericLiteral(2),
);
expr.innerComments = [{ type: "CommentBlock", value: "foo" }];
expect(generate(expr).code).toMatchInlineSnapshot(`"1 + 2 /*foo*/"`);
});

it("comment skipped because of newlines", () => {
const arrow = t.arrowFunctionExpression(
[t.identifier("x"), t.identifier("y")],
t.identifier("z"),
);
arrow.innerComments = [
{ type: "CommentBlock", value: "foo" },
{ type: "CommentBlock", value: "new\nline" },
];
expect(generate(arrow).code).toMatchInlineSnapshot(`
"(x, y) /*foo*/ => z
/*new
line*/"
`);
});
});
});

describe("CodeGenerator", function () {
Expand Down
Expand Up @@ -18,7 +18,7 @@ var Baz;
Baz[Baz["b"] = 1] = "b";
Baz[Baz["x"] = Baz.a.toString()] = "x";
})(Baz || (Baz = {}));
var A;
var A; // a refers to A.a
(function (A) {
A[A["a"] = 0] = "a";
A[A["b"] = (() => {
Expand Down

0 comments on commit 156b608

Please sign in to comment.