AST of other Files in Tweaks


I am currently developing some new Tweaks (FixIts, Refactoring functions or whatever you wanna call them) in clangd. I am trying to develop a multi-file tweak, but it seems that from Tweak::Selection I can only get the AST of the current main file. Is there a way to get the AST of other files inside of a Tweak::apply() implementation? I found the location of my symbols in other files with locateSymbolAt(), but I need more information about that symbol.


There is currently no infrastructure in place to get the ASTs for other files in the tweaks. All you can do really query the SymbolIndex and read the source files.

Thanks for the reply!
What would be the best way to extract the SourceRange of a symbol ( in my case function definition and static variable definitions) in these other files?

I could try to write a small parser myself, but I guess that’s not the way to go.

You can find this information in the index. The exact workflow will depend on the scenario, but if e.g. you’re looking for the source range of the definition of a symbol which is referenced in the main AST, you could:

  • Use getSymbolID(const Decl*) to compute a SymbolID for the symbol
  • Use SymbolIndex::lookup() to look up the Symbol correponding to the SymbolID
  • The source range is contained within Symbol::Definition

That would only get the source range of the identifier not the whole function or static variable definition, which I think is what he is after.

I think it is not in the main AST since getDefinition() returns a null-ptr(my main file is a header and the defnition is in the cpp file). Thats why I use the locateSymbolAt() function.

@njames93 yes, that is right.

I just meant referenced in the main AST, such that you can get a Decl* for it.

Indeed, the full range is not stored in the index. We could perhaps consider storing it, it would fix Populate TypeHierarchyItem.range correctly for subtypes · Issue #59 · clangd/clangd · GitHub as well.

Ok, but how would I build here a lightweight AST (dunno if there are different modes) that contains the information I need. I cannot really find anything about this.

I don’t think there is anything like a “lightweight AST” in clang right now. The closest thing I know of is FrontendOpts.SkipFunctionBodies which makes the building of a regular AST somewhat faster, but parsing declarations (particularly in included headers) is still going to take a while.

There’s been talk of a “pseudoparser” which doesn’t look at included headers, but I don’t believe such a thing exists in clang yet.

Ok thanks, then I will write something small myself.