Skip to content

Commit

Permalink
Don't emit duplicate triple-slash directives when using API to print …
Browse files Browse the repository at this point in the history
…a .d.ts (#40968)
  • Loading branch information
rbuckton authored Oct 23, 2020
2 parents 6092ecf + 14714bb commit 8ed645a
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/compiler/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5136,7 +5136,12 @@ namespace ts {
hasWrittenComment = false;

if (isEmittedNode) {
forEachLeadingCommentToEmit(pos, emitLeadingComment);
if (pos === 0 && currentSourceFile?.isDeclarationFile) {
forEachLeadingCommentToEmit(pos, emitNonTripleSlashLeadingComment);
}
else {
forEachLeadingCommentToEmit(pos, emitLeadingComment);
}
}
else if (pos === 0) {
// If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
Expand All @@ -5157,6 +5162,12 @@ namespace ts {
}
}

function emitNonTripleSlashLeadingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) {
if (!isTripleSlashComment(commentPos, commentEnd)) {
emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
}
}

function shouldWriteComment(text: string, pos: number) {
if (printerOptions.onlyPrintJsDocStyle) {
return (isJSDocLikeText(text, pos) || isPinnedComment(text, pos));
Expand Down
27 changes: 27 additions & 0 deletions src/testRunner/unittests/printer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,33 @@ namespace ts {
});
});

describe("No duplicate ref directives when emiting .d.ts->.d.ts", () => {
it("without statements", () => {
const host = new fakes.CompilerHost(new vfs.FileSystem(true, {
files: {
"/test.d.ts": `/// <reference types="node" />\n/// <reference path="./src/test.d.ts />\n`
}
}));
const program = createProgram(["/test.d.ts"], { }, host);
const file = program.getSourceFile("/test.d.ts")!;
const printer = createPrinter({ newLine: NewLineKind.CarriageReturnLineFeed });
const output = printer.printFile(file);
assert.equal(output.split(/\r?\n/g).length, 3);
});
it("with statements", () => {
const host = new fakes.CompilerHost(new vfs.FileSystem(true, {
files: {
"/test.d.ts": `/// <reference types="node" />\n/// <reference path="./src/test.d.ts />\nvar a: number;\n`
}
}));
const program = createProgram(["/test.d.ts"], { }, host);
const file = program.getSourceFile("/test.d.ts")!;
const printer = createPrinter({ newLine: NewLineKind.CarriageReturnLineFeed });
const output = printer.printFile(file);
assert.equal(output.split(/\r?\n/g).length, 4);
});
});

describe("printBundle", () => {
const printsCorrectly = makePrintsCorrectly("printsBundleCorrectly");
let bundle: Bundle;
Expand Down

0 comments on commit 8ed645a

Please sign in to comment.