Skip to content

Commit c48da43

Browse files
astnav: Expand coverage, remove Node dependency, fix bugs (#65778)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent de7ccae commit c48da43

20 files changed

Lines changed: 42570 additions & 967 deletions

‎packages/typescript/src/ast/astnav.ts‎

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { NodeFlags } from "../../enums/nodeFlags.js";
22
import { SyntaxKind } from "../../enums/syntaxKind.js";
33
import type { TokenSyntaxKind } from "./ast.generated.ts";
44
import type {
5+
JsxText,
56
Node,
67
NodeArray,
78
SourceFile,
@@ -411,7 +412,7 @@ function findPrecedingTokenImpl(sourceFile: SourceFile, position: number, startN
411412

412413
if (foundChild !== undefined) {
413414
const start = getTokenPosOfNode(foundChild, sourceFile, /*includeJSDoc*/ true);
414-
if (start >= position) {
415+
if (start >= position || !isValidPrecedingNode(foundChild, sourceFile)) {
415416
if (position >= foundChild.pos) {
416417
// We are in the leading trivia of foundChild. Check for JSDoc nodes of n
417418
// preceding foundChild, mirroring Go's findPrecedingToken logic.
@@ -453,7 +454,7 @@ function findRightmostValidToken(sourceFile: SourceFile, endPos: number, contain
453454
}
454455

455456
const find = (n: Node, endPos: number): Node | undefined => {
456-
if (isTokenKind(n.kind) && n.kind !== SyntaxKind.EndOfFile) {
457+
if (isTokenKind(n.kind) && !isWhitespaceOnlyJsxText(n)) {
457458
return n;
458459
}
459460

@@ -521,12 +522,15 @@ function findRightmostValidToken(sourceFile: SourceFile, endPos: number, contain
521522
let lastToken: Node | undefined;
522523
while (pos < targetEnd) {
523524
const tokenStart = scanner.getTokenStart();
524-
if (tokenStart >= position) break;
525+
if (tokenStart >= targetEnd) break;
525526
const tokenFullStart = scanner.getTokenFullStart();
526527
const tokenEnd = scanner.getTokenEnd();
527528
const token = scanner.getToken();
528529
const flags = scanner.getTokenFlags();
529-
lastToken = getOrCreateToken(sourceFile, token, tokenFullStart, tokenEnd, n, flags);
530+
const scannedToken = getOrCreateToken(sourceFile, token, tokenFullStart, tokenEnd, n, flags);
531+
if (!isWhitespaceOnlyJsxText(scannedToken)) {
532+
lastToken = scannedToken;
533+
}
530534
pos = tokenEnd;
531535
scanner.scan();
532536
}
@@ -556,11 +560,15 @@ function findRightmostValidToken(sourceFile: SourceFile, endPos: number, contain
556560

557561
function isValidPrecedingNode(node: Node, sourceFile: SourceFile): boolean {
558562
if (node.kind === SyntaxKind.EndOfFile) {
559-
return false;
563+
return !!node.jsDoc?.length;
560564
}
561565
const start = getTokenPosOfNode(node, sourceFile);
562566
const width = node.end - start;
563-
return width > 0;
567+
return width > 0 && !isWhitespaceOnlyJsxText(node);
568+
}
569+
570+
function isWhitespaceOnlyJsxText(node: Node): boolean {
571+
return node.kind === SyntaxKind.JsxText && (node as JsxText).containsOnlyTriviaWhiteSpaces;
564572
}
565573

566574
function shouldSkipChild(node: Node): boolean {
@@ -886,20 +894,25 @@ function binarySearchForPrecedingToken(nodes: NodeArray<Node>, position: number)
886894
let result = -1;
887895
while (lo <= hi) {
888896
const mid = (lo + hi) >>> 1;
889-
const node = nodes[mid];
890-
if (node.flags & NodeFlags.Reparsed) {
891-
lo = mid + 1;
897+
// Reparsed nodes are materialized from JSDoc and are not ordered relative to their
898+
// siblings, so compare against the next non-reparsed node instead.
899+
let index = mid;
900+
while (index <= hi && nodes[index].flags & NodeFlags.Reparsed) index++;
901+
if (index > hi) {
902+
hi = mid - 1;
892903
continue;
893904
}
894-
if (position < node.end) {
895-
if (mid === 0 || position >= nodes[mid - 1].end) {
896-
result = mid;
905+
if (position < nodes[index].end) {
906+
let previous = index - 1;
907+
while (previous >= 0 && nodes[previous].flags & NodeFlags.Reparsed) previous--;
908+
if (previous < 0 || position >= nodes[previous].end) {
909+
result = index;
897910
break;
898911
}
899912
hi = mid - 1;
900913
}
901914
else {
902-
lo = mid + 1;
915+
lo = index + 1;
903916
}
904917
}
905918
return result;

‎packages/typescript/test/async/astnav.test.ts‎

Lines changed: 107 additions & 101 deletions
Original file line numberDiff line numberDiff line change
@@ -72,119 +72,125 @@ function toTokenInfo(node: Node): { kind: string; pos: number; end: number; } {
7272
// ---------------------------------------------------------------------------
7373

7474
const repoRoot = resolve(import.meta.dirname, "..", "..", "..", "..");
75-
const testFile = resolve(repoRoot, "tsc/testdata/fixtures/services/mapCode.ts");
75+
const fixtureDir = resolve(repoRoot, "tsc/testdata/fixtures/services");
76+
const fixtureFiles = ["mapCode.ts", "jsxReactTestSuite.tsx", "jsdocInJs.js"];
7677
const baselineDir = resolve(repoRoot, "tsc/testdata/baselines/reference/astnav");
7778

7879
// ---------------------------------------------------------------------------
7980
// Tests
8081
// ---------------------------------------------------------------------------
8182

8283
describe("astnav", { concurrency: areTestsFiltered() }, () => {
83-
let fileText: string;
84+
for (const fixtureFile of fixtureFiles) {
85+
describe(fixtureFile, () => {
86+
let fileText: string;
8487

85-
try {
86-
fileText = readFileSync(testFile, "utf-8");
87-
}
88-
catch {
89-
console.log("Skipping astnav tests: compiler fixtures not available");
90-
fileText = "";
91-
}
92-
93-
if (!fileText) return;
94-
95-
// Use the Go API to parse the file — the resulting SourceFile is already
96-
// in our SyntaxKind/NodeFlags enum space with correct JSDoc structure.
97-
let api: API;
98-
let sourceFile: SourceFile;
99-
100-
before(async () => {
101-
api = new API({
102-
cwd: fileURLToPath(new URL("../../../../", import.meta.url).toString()),
103-
fs: createVirtualFileSystem({
104-
"/tsconfig.json": JSON.stringify({ files: ["/src/testFile.ts"] }),
105-
"/src/testFile.ts": fileText,
106-
}),
107-
});
88+
try {
89+
fileText = readFileSync(resolve(fixtureDir, fixtureFile), "utf-8");
90+
}
91+
catch {
92+
console.log("Skipping astnav tests: compiler fixtures not available");
93+
fileText = "";
94+
}
10895

109-
const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] });
110-
const project = snapshot.getConfiguredProject("/tsconfig.json")!;
111-
const sf = await project.program.getSourceFile("/src/testFile.ts");
112-
assert.ok(sf, "Failed to get source file from API");
113-
sourceFile = sf;
114-
});
115-
116-
after(async () => {
117-
await api.close();
118-
});
119-
120-
const testCases = [
121-
{
122-
name: "getTokenAtPosition",
123-
baselineFile: "GetTokenAtPosition.mapCode.ts.baseline.json",
124-
fn: (sf: SourceFile, pos: number) => getTokenAtPosition(sf, pos) as Node | undefined,
125-
},
126-
{
127-
name: "getTouchingPropertyName",
128-
baselineFile: "GetTouchingPropertyName.mapCode.ts.baseline.json",
129-
fn: (sf: SourceFile, pos: number) => getTouchingPropertyName(sf, pos) as Node | undefined,
130-
},
131-
{
132-
name: "findPrecedingToken",
133-
baselineFile: "FindPrecedingToken.mapCode.ts.baseline.json",
134-
fn: (sf: SourceFile, pos: number) => findPrecedingToken(sf, pos),
135-
},
136-
{
137-
name: "findNextToken",
138-
baselineFile: "FindNextToken.mapCode.ts.baseline.json",
139-
fn: (sf: SourceFile, pos: number) => findNextToken(getTokenAtPosition(sf, pos), sf, sf),
140-
},
141-
];
142-
143-
for (const tc of testCases) {
144-
test(tc.name, () => {
145-
const baselinePath = resolve(baselineDir, tc.baselineFile);
146-
const runs: TokenRun[] = JSON.parse(readFileSync(baselinePath, "utf-8"));
147-
const expected = expandBaseline(runs);
148-
149-
const failures: string[] = [];
150-
151-
for (let pos = 0; pos < fileText.length; pos++) {
152-
const node = tc.fn(sourceFile, pos);
153-
const goExpected = expected.get(pos);
154-
155-
if (!goExpected) continue;
156-
157-
if (node === undefined) {
158-
failures.push(
159-
` pos ${pos}: expected ${goExpected.kind} [${goExpected.pos}, ${goExpected.end}), got undefined`,
160-
);
161-
if (failures.length >= 50) {
162-
failures.push(" ... (truncated, too many failures)");
163-
break;
164-
}
165-
continue;
166-
}
167-
168-
const result = toTokenInfo(node);
169-
if (result.kind !== goExpected.kind || result.pos !== goExpected.pos || result.end !== goExpected.end) {
170-
failures.push(
171-
` pos ${pos}: expected ${goExpected.kind} [${goExpected.pos}, ${goExpected.end}), ` +
172-
`got ${result.kind} [${result.pos}, ${result.end})`,
173-
);
174-
if (failures.length >= 50) {
175-
failures.push(" ... (truncated, too many failures)");
176-
break;
96+
if (!fileText) return;
97+
98+
// Use the Go API to parse the file — the resulting SourceFile is already
99+
// in our SyntaxKind/NodeFlags enum space with correct JSDoc structure.
100+
const sourcePath = `/src/${fixtureFile}`;
101+
let api: API;
102+
let sourceFile: SourceFile;
103+
104+
before(async () => {
105+
api = new API({
106+
cwd: fileURLToPath(new URL("../../../../", import.meta.url).toString()),
107+
fs: createVirtualFileSystem({
108+
"/tsconfig.json": JSON.stringify({ compilerOptions: { allowJs: true }, files: [sourcePath] }),
109+
[sourcePath]: fileText,
110+
}),
111+
});
112+
113+
const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] });
114+
const project = snapshot.getConfiguredProject("/tsconfig.json")!;
115+
const sf = await project.program.getSourceFile(sourcePath);
116+
assert.ok(sf, "Failed to get source file from API");
117+
sourceFile = sf;
118+
});
119+
120+
after(async () => {
121+
await api.close();
122+
});
123+
124+
const testCases = [
125+
{
126+
name: "getTokenAtPosition",
127+
baselineFile: `GetTokenAtPosition.${fixtureFile}.baseline.json`,
128+
fn: (sf: SourceFile, pos: number) => getTokenAtPosition(sf, pos) as Node | undefined,
129+
},
130+
{
131+
name: "getTouchingPropertyName",
132+
baselineFile: `GetTouchingPropertyName.${fixtureFile}.baseline.json`,
133+
fn: (sf: SourceFile, pos: number) => getTouchingPropertyName(sf, pos) as Node | undefined,
134+
},
135+
{
136+
name: "findPrecedingToken",
137+
baselineFile: `FindPrecedingToken.${fixtureFile}.baseline.json`,
138+
fn: (sf: SourceFile, pos: number) => findPrecedingToken(sf, pos),
139+
},
140+
{
141+
name: "findNextToken",
142+
baselineFile: `FindNextToken.${fixtureFile}.baseline.json`,
143+
fn: (sf: SourceFile, pos: number) => findNextToken(getTokenAtPosition(sf, pos), sf, sf),
144+
},
145+
];
146+
147+
for (const tc of testCases) {
148+
test(tc.name, () => {
149+
const baselinePath = resolve(baselineDir, tc.baselineFile);
150+
const runs: TokenRun[] = JSON.parse(readFileSync(baselinePath, "utf-8"));
151+
const expected = expandBaseline(runs);
152+
153+
const failures: string[] = [];
154+
155+
for (let pos = 0; pos < fileText.length; pos++) {
156+
const node = tc.fn(sourceFile, pos);
157+
const goExpected = expected.get(pos);
158+
159+
if (!goExpected) continue;
160+
161+
if (node === undefined) {
162+
failures.push(
163+
` pos ${pos}: expected ${goExpected.kind} [${goExpected.pos}, ${goExpected.end}), got undefined`,
164+
);
165+
if (failures.length >= 50) {
166+
failures.push(" ... (truncated, too many failures)");
167+
break;
168+
}
169+
continue;
170+
}
171+
172+
const result = toTokenInfo(node);
173+
if (result.kind !== goExpected.kind || result.pos !== goExpected.pos || result.end !== goExpected.end) {
174+
failures.push(
175+
` pos ${pos}: expected ${goExpected.kind} [${goExpected.pos}, ${goExpected.end}), ` +
176+
`got ${result.kind} [${result.pos}, ${result.end})`,
177+
);
178+
if (failures.length >= 50) {
179+
failures.push(" ... (truncated, too many failures)");
180+
break;
181+
}
182+
}
177183
}
178-
}
179-
}
180184

181-
console.log(` ${tc.name}: checked ${fileText.length} positions`);
185+
console.log(` ${tc.name}: checked ${fileText.length} positions`);
182186

183-
if (failures.length > 0) {
184-
assert.fail(
185-
`${tc.name}: ${failures.length} position(s) differ from Go baseline:\n` +
186-
failures.join("\n"),
187-
);
187+
if (failures.length > 0) {
188+
assert.fail(
189+
`${tc.name}: ${failures.length} position(s) differ from Go baseline:\n` +
190+
failures.join("\n"),
191+
);
192+
}
193+
});
188194
}
189195
});
190196
}

0 commit comments

Comments
 (0)