Add additional #include header file as a result of a refactor

Hi!

I’m refactoring some code with libtooling, replacing one API call with a new another one. This requires me to insert a new header file. How can this be done?

Thanks,
Kenth

Hi Keneth!,

Did you try clang::PPCallbacks or clang::PreprocessorFrontEndAction?

Probably PPCallbacks is what you are looking for.

Let me know if that help!

Regards.

CAUTION: This email originated from outside of the organization. Do not click links or open attachments unless you recognize the sender and know the content is safe.

Hi Keneth!,

Did you try clang::PPCallbacks or clang::PreprocessorFrontEndAction?

Probably PPCallbacks is what you are looking for.

Would it be possible to get the location for the header includes from
the source manager? E.g. SourceManager::getLocForStartOfFile gives me
the beginning of the file. But how can I get the location for the
header files via SM?

> CAUTION: This email originated from outside of the organization. Do not click links or open attachments unless you recognize the sender and know the content is safe.
>
> Hi Keneth!,
>
> Did you try clang::PPCallbacks or clang::PreprocessorFrontEndAction?
>
> Probably PPCallbacks is what you are looking for.
>
Would it be possible to get the location for the header includes from
the source manager? E.g. SourceManager::getLocForStartOfFile gives me
the beginning of the file. But how can I get the location for the
header files via SM?

What do you mean by this? Headers can be included anywhere in a file.
Having a big block of include directives close to the top of the file
is just a convention. If you're looking for the include directive for
a specific header (e.g. the one for the old API that you're
replacing), overriding PPCallbacks::InclusionDirective will probably
get you there. Otherwise, you need to think of a way to be more
specific about where you want to include your file (but you should be
very careful because include directives could be part of #if blocks).

Hope that helps,
Diana

Like Diana said, overriding InclusionDirective will help you getting the include that you want to replace. That method will give you everything you need (location, name, if is an angled include, etc). Since is called in when it finds an include one you TU.

https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#ad5509ca394c21faaead91ec8add75dd2

Take a look to the details of the InclusionDirective.

Thanks, I'm now able to get all the included files after implementing
InclusionDirective in PPCallbacks.