PPCallbacks - If function param SourceRange returns whole file


In my libtooling project I have a class implementing the PPCallbacks interface to get that information. When the “If” function is triggered, I am passed a condition range. I expect that would be whatever followed "#if " on that line.

To extract the raw source text information as a string, I followed the advice of the below thread and have the below implementation. The string “source” I retrieve contains the entire source of the file, after the "#if " statement. Why is that? How can I get only the information for the text on the line following the "#if "? I’m using Clang 8.0.0.


void PreprocessorInfoListener::If(SourceLocation sourceLoc, SourceRange conditionRange, PPCallbacks::ConditionValueKind conditionValue)

{LangOptions langOptions;
llvm::StringRef source = Lexer::getSourceText(CharSourceRange::getTokenRange(conditionRange), m_sourceManager, langOptions);}


The source which I am compiling looking at does include a macro, which I suspect might be part of the problem.

This is the file we are compiling. PLATFORM_WINDOWS is a #define.
// Other code.

I found a solution/workaround and wanted to close the loop on this one.

The reason the string from getSourceText was not what I expected was because the sourceRange included source locations from different files. I’m not sure how to properly grab information in this case, but have found a workaround. I was able to extract the desired source information by starting at the starting source location, and building a string up to the first found newline character.