dsherret / ts-morph

TypeScript Compiler API wrapper for static analysis and programmatic code changes.
https://ts-morph.com
MIT License
4.9k stars 194 forks source link

Bug: Unable to rename identifier #1530

Closed marvinhagemeister closed 5 months ago

marvinhagemeister commented 5 months ago

Describe the bug

Renaming the right-hand side of a member expression doesn't seem to work. Calling .rename() on an identifier seems to do nothing.

Version: 22.0.0

To Reproduce

// input: foo.ts
function foo(ctx: any) {
  ctx.renderNotFound();
}
import * as tsmorph from "ts-morph";

const project = new tsmorph.Project();
const source = project.addSourceFileAtPath("./foo.ts");
const fnDecl = source.getFunctionOrThrow("foo");
if (fnDecl) {
  const callExpr = fnDecl.getDescendantsOfKind(
    tsmorph.ts.SyntaxKind.CallExpression,
  );
  const fn = callExpr[0];

  const member = fn.getChildrenOfKind(
    tsmorph.ts.SyntaxKind.PropertyAccessExpression,
  )[0];

  const right = member.getChildren()[2].asKind(
    tsmorph.ts.SyntaxKind.Identifier,
  )!;
  right.rename("asdf");
}

source.saveSync();

Expected behavior

The renderNotFound identifier should have been renamed to asdf. This would be the expected output:

function foo(ctx: any) {
  ctx.asdf();
}
dsherret commented 5 months ago

Does that work in an editor if you try to rename? The rename function is just calling the language server. You might need to use setText instead (or it's called something like that, just on my phone) which will work directly on the ast.

marvinhagemeister commented 5 months ago

Sweet, can confirm that using .replaceWithText() works!