Skip to content

Commit ae6c9cd

Browse files
authored
Merge pull request microsoft#28489 from ajafff/shebang-comments
fix comment parsing at start of file
2 parents 0df89cc + 0604ae1 commit ae6c9cd

File tree

4 files changed

+42
-1
lines changed

4 files changed

+42
-1
lines changed

src/compiler/scanner.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -661,8 +661,15 @@ namespace ts {
661661
let pendingKind!: CommentKind;
662662
let pendingHasTrailingNewLine!: boolean;
663663
let hasPendingCommentRange = false;
664-
let collecting = trailing || pos === 0;
664+
let collecting = trailing;
665665
let accumulator = initial;
666+
if (pos === 0) {
667+
collecting = true;
668+
const shebang = getShebang(text);
669+
if (shebang) {
670+
pos = shebang.length;
671+
}
672+
}
666673
scan: while (pos >= 0 && pos < text.length) {
667674
const ch = text.charCodeAt(pos);
668675
switch (ch) {

src/testRunner/tsconfig.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
"unittests/asserts.ts",
4444
"unittests/base64.ts",
4545
"unittests/builder.ts",
46+
"unittests/comments.ts",
4647
"unittests/compilerCore.ts",
4748
"unittests/convertToBase64.ts",
4849
"unittests/customTransforms.ts",

src/testRunner/unittests/comments.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
namespace ts {
2+
describe("comment parsing", () => {
3+
const withShebang = `#! node
4+
/** comment */
5+
// another one
6+
;`;
7+
const noShebang = `/** comment */
8+
// another one
9+
;`;
10+
const withTrailing = `;/* comment */
11+
// another one
12+
`;
13+
it("skips shebang", () => {
14+
const result = getLeadingCommentRanges(withShebang, 0);
15+
assert.isDefined(result);
16+
assert.strictEqual(result!.length, 2);
17+
});
18+
19+
it("treats all comments at start of file as leading comments", () => {
20+
const result = getLeadingCommentRanges(noShebang, 0);
21+
assert.isDefined(result);
22+
assert.strictEqual(result!.length, 2);
23+
});
24+
25+
it("returns leading comments if position is not 0", () => {
26+
const result = getLeadingCommentRanges(withTrailing, 1);
27+
assert.isDefined(result);
28+
assert.strictEqual(result!.length, 1);
29+
assert.strictEqual(result![0].kind, SyntaxKind.SingleLineCommentTrivia);
30+
});
31+
});
32+
}

tests/baselines/reference/shebangBeforeReferences.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use(x);
1717
//// [f.js]
1818
#!/usr/bin/env node
1919
"use strict";
20+
/// <reference path="f.d.ts"/>
2021
exports.__esModule = true;
2122
var test_1 = require("test");
2223
use(test_1.x);

0 commit comments

Comments
 (0)