Skip to content

Commit

Permalink
Fix ugly emitted comments when removing code between tokens (alangpie…
Browse files Browse the repository at this point in the history
…rce#286)

Fixes alangpierce#281

Previously, it seemed best to remove all whitespace, but that makes comments
look really weird, since all spaces are removed in the comment. Instead, for
now, we remove whitespace and comments in their entirety (except newlines).
  • Loading branch information
alangpierce authored and aleclarson committed Jul 1, 2018
1 parent 6faa84d commit 94121e5
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
10 changes: 5 additions & 5 deletions src/TokenProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ export default class TokenProcessor {
return this.matches1(type) && this.currentToken().contextId === contextId;
}

previousWhitespace(): string {
previousWhitespaceAndComments(): string {
let whitespaceAndComments = this.code.slice(
this.tokenIndex > 0 ? this.tokens[this.tokenIndex - 1].end : 0,
this.tokenIndex < this.tokens.length ? this.tokens[this.tokenIndex].start : this.code.length,
Expand All @@ -150,13 +150,13 @@ export default class TokenProcessor {
}

replaceToken(newCode: string): void {
this.resultCode += this.previousWhitespace();
this.resultCode += this.previousWhitespaceAndComments();
this.resultCode += newCode;
this.tokenIndex++;
}

replaceTokenTrimmingLeftWhitespace(newCode: string): void {
this.resultCode += this.previousWhitespace().replace(/[\t ]/g, "");
this.resultCode += this.previousWhitespaceAndComments().replace(/[^\r\n]/g, "");
this.resultCode += newCode;
this.tokenIndex++;
}
Expand All @@ -177,7 +177,7 @@ export default class TokenProcessor {
}

copyToken(): void {
this.resultCode += this.previousWhitespace();
this.resultCode += this.previousWhitespaceAndComments();
this.resultCode += this.code.slice(
this.tokens[this.tokenIndex].start,
this.tokens[this.tokenIndex].end,
Expand Down Expand Up @@ -225,7 +225,7 @@ export default class TokenProcessor {
if (this.tokenIndex !== this.tokens.length) {
throw new Error("Tried to finish processing tokens before reaching the end.");
}
this.resultCode += this.previousWhitespace();
this.resultCode += this.previousWhitespaceAndComments();
return this.resultCode;
}

Expand Down
16 changes: 16 additions & 0 deletions test/sucrase-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -567,4 +567,20 @@ describe("sucrase", () => {
{transforms: ["imports", "typescript"]},
);
});

it("removes comments within removed ranges rather than removing all whitespace", () => {
assertResult(
`
interface A {
// This is a comment.
}
`,
`"use strict";
`,
{transforms: ["imports", "typescript"]},
);
});
});

0 comments on commit 94121e5

Please sign in to comment.