Skip to content

Commit

Permalink
fix: #437 - Fix findReferencesAsNodes having an undefined entry whe…
Browse files Browse the repository at this point in the history
…n the reference is within a string literal.

Also, it won't ever return undefined now.
  • Loading branch information
dsherret committed Sep 29, 2018
1 parent ae73ed5 commit 06943a9
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
34 changes: 32 additions & 2 deletions src/compiler/tools/results/DocumentSpan.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SourceFile } from "../../../compiler";
import { SourceFile, Node } from "../../../compiler";
import { ProjectContext } from "../../../ProjectContext";
import { ts } from "../../../typescript";
import { Memoize } from "../../../utils";
Expand Down Expand Up @@ -56,7 +56,37 @@ export class DocumentSpan<TCompilerObject extends ts.DocumentSpan = ts.DocumentS
*/
@Memoize
getNode() {
return this.getSourceFile().getDescendantAtStartWithWidth(this.getTextSpan().getStart(), this.getTextSpan().getLength())!;
const textSpan = this.getTextSpan();
const sourceFile = this.getSourceFile();
const start = textSpan.getStart();
const width = textSpan.getEnd();

return findBestMatchingNode();

function findBestMatchingNode() {
// more relaxed getDescendantAtStartWithWidth because the position may be within a string literal
let bestNode: Node | undefined;

sourceFile.context.compilerFactory.forgetNodesCreatedInBlock(remember => {
let foundNode: Node | undefined;
let nextNode: Node | undefined = sourceFile;

while (nextNode != null) {
if (foundNode == null)
bestNode = nextNode;
if (nextNode.getStart() === start && nextNode.getWidth() === width)
bestNode = foundNode = nextNode;
else if (foundNode != null)
break; // no need to keep looking
nextNode = nextNode.getChildAtPos(start);
}

if (bestNode != null)
remember(bestNode);
});

return bestNode!;
}
}

/**
Expand Down
13 changes: 13 additions & 0 deletions src/tests/issues/437tests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { expect } from "chai";
import { SyntaxKind } from "../../typescript";
import { getInfoFromText } from "../compiler/testHelpers";

describe("tests for issue #437", () => {
it("should not return undefined for findReferencesAsNodes", () => {
const { sourceFile } = getInfoFromText("const f: { a: string; } = {a: '23'}; f['a'];");
const varDec = sourceFile.getVariableDeclarationOrThrow("f");
const results = varDec.getFirstDescendantByKindOrThrow(SyntaxKind.PropertySignature).findReferencesAsNodes();

expect(results.map(r => r.getText())).to.deep.equal(["a", "'a'"]);
});
});

0 comments on commit 06943a9

Please sign in to comment.