Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix mapping of tokens with generated nodes in between #16948

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/babel-generator/src/token-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,8 @@ export class TokenMap {
const indexes = [];

for (const child of children) {
if (!child) continue;
if (child == null) continue;
if (child.start == null || child.end == null) continue;
Comment on lines +161 to +162

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (child == null) continue;
if (child.start == null || child.end == null) continue;
if (child == null || child.start == null || child.end == null) continue;

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Heheh unfortunately typescript-eslint complains that child == null || child.start == null should be rewritten to child?.start == null, but I find child?.start == null || child.end == null to be terrible so this two-lines solution was the compromise I reached with the linter :P


const childTok = this._findTokensOfNode(child, low, last);

Expand Down
42 changes: 42 additions & 0 deletions packages/babel-generator/test/preserve-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,5 +203,47 @@ describe("experimental_preserveFormat", () => {

expect(out.code.trimEnd()).toBe(expected.trimEnd());
});

it("node injection", () => {
const input = `
const foo
= 3;
const bar =
3;
bax
`;
const expected = `
const foo
= 3;hello;
const bar =
3;
bax
`;

const out = babel.transformSync(input, {
configFile: false,
plugins: [
({ types: t }) => ({
visitor: {
Program(path) {
path
.get("body.0")
.insertAfter(t.expressionStatement(t.identifier("hello")));
},
},
}),
],
parserOpts: {
createParenthesizedExpressions: true,
tokens: true,
},
generatorOpts: {
retainLines: true,
experimental_preserveFormat: true,
},
});

expect(out.code.trimEnd()).toBe(expected.trimEnd());
});
});
});
Loading