I am trying to use the TypeScript compiler API (1.4) to rename symbols across source files, for example renaming a global variable and all references to it. I started with the instructions here, then I used this to get all identifiers
function getNodes(sf: ts.SourceFile): ts.Node[]
{
var nodes: ts.Node[] = [];
function allNodes(n: ts.Node)
{
ts.forEachChild(n, n => { if (n.kind == ts.SyntaxKind.Identifier) nodes.push(n); allNodes(n); return false; })
};
allNodes(sf);
return nodes;
}
Once you create your type checker, you can then resolve your nodes (where every reference to the identifier has a separate instance) into symbols (where references to the same variable have the same instance):
var checker = program.getTypeChecker(true);
var symbols = getNodes(sourceFile).map((n, i, array) => checker.getSymbolAtLocation(n));
Great. But now I am stuck, since the symbol seems to be immutable. Are you supposed to clone it and then provide some kind of lookup table to the emitter? Or a custom SymbolWriter, or SymbolDisplayBuilder? I can't see many extension points in the classes.
for example renaming a global variable and all references to it.
Symbols have declarations stored inside them (some docs https://basarat.gitbook.io/typescript/overview/binder/binder-declarations)
You can get access to these using let declarations = symbol.getDeclarations(); and in fact that is exactly what getRenameInfo in services.ts does (source code).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With