dsherret / dsherret/ts-morph

getParentIfKindOrThrow throws on CallExpression syntax

Open
#1,468 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
6.2k
Forks
238
Avg merge
2m
Merged PRs (30d)
1

Description

**Describe the bug**

Version: 20.0.0

Error received: "Error: The parent was not a syntax kind of CallExpression."

When using `getParentIfKindOrThrow`, this sometimes throws on the `callExpression` syntax. This seems to occur depending on the length of the script.

**To Reproduce**

```ts
import { Project } from "ts-morph";

const generateSourceFile = (script: string): SourceFile => {
const project = new Project({
useInMemoryFileSystem: true
});
project.createSourceFile("script.ts", script)

const sourceFile = project.getSourceFileOrThrow("script.ts");
return sourceFile;
}

// This script throws...
const script = `declare function getSomeField(id: string): boolean;getSomeField(“abcdefg wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww”);`

const sourceFile = generateSourceFile(script);
const func = sourceFile.getFunction("getSomeField");

try {
const getFieldByIdNodes = func?.findReferencesAsNodes();
for(const node of getFieldByIdNodes) {
const callExpression = node.getParentIfKindOrThrow(SyntaxKind.CallExpression);
....
}
} catch (err) {
console.log(error);
}

```
But updating `script` to be:
const script = `\n declare function getSomeField(id: string): boolean;getSomeField(“abcdefg wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww”); \n`

Then it no longer throws.

Also adding in a few extra characters into the script such as:

const script = `declare function getSomeField(id: string): boolean;getSomeField("abcdefg wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww zz");` results in it no longer throwing too.

Why would wrapping this in newline stop it from throwing?

Contributor guide

Open the contributing guide

Research direction

Start with CONTRIBUTING.md and run the TypeScript reproduction using the two script variants shown in the issue. Trace the node returned by findReferencesAsNodes() and the getParentIfKindOrThrow entry point to determine why the parent differs. Done means the reported case is handled consistently and the reproduction no longer throws.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.