#include "clang/Frontend/Utils.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/PreprocessorOutputOptions.h"
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Lex/Pragma.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/TokenConcatenation.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdio>
using namespace clang;
static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
Preprocessor &PP, raw_ostream &OS) {
OS << "#define " << II.getName();
if (MI.isFunctionLike()) {
OS << '(';
if (!MI.param_empty()) {
MacroInfo::param_iterator AI = MI.param_begin(), E = MI.param_end();
for (; AI+1 != E; ++AI) {
OS << (*AI)->getName();
OS << ',';
}
if ((*AI)->getName() == "__VA_ARGS__")
OS << "...";
else
OS << (*AI)->getName();
}
if (MI.isGNUVarargs())
OS << "...";
OS << ')';
}
if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
OS << ' ';
SmallString<128> SpellingBuffer;
for (const auto &T : MI.tokens()) {
if (T.hasLeadingSpace())
OS << ' ';
OS << PP.getSpelling(T, SpellingBuffer);
}
}
namespace {
class PrintPPOutputPPCallbacks : public PPCallbacks {
Preprocessor &PP;
SourceManager &SM;
TokenConcatenation ConcatInfo;
public:
raw_ostream &OS;
private:
unsigned CurLine;
bool EmittedTokensOnThisLine;
bool EmittedDirectiveOnThisLine;
SrcMgr::CharacteristicKind FileType;
SmallString<512> CurFilename;
bool Initialized;
bool DisableLineMarkers;
bool DumpDefines;
bool DumpIncludeDirectives;
bool UseLineDirectives;
bool IsFirstFileEntered;
bool MinimizeWhitespace;
bool DirectivesOnly;
Token PrevTok;
Token PrevPrevTok;
public:
PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os, bool lineMarkers,
bool defines, bool DumpIncludeDirectives,
bool UseLineDirectives, bool MinimizeWhitespace,
bool DirectivesOnly)
: PP(pp), SM(PP.getSourceManager()), ConcatInfo(PP), OS(os),
DisableLineMarkers(lineMarkers), DumpDefines(defines),
DumpIncludeDirectives(DumpIncludeDirectives),
UseLineDirectives(UseLineDirectives),
MinimizeWhitespace(MinimizeWhitespace), DirectivesOnly(DirectivesOnly) {
CurLine = 0;
CurFilename += "<uninit>";
EmittedTokensOnThisLine = false;
EmittedDirectiveOnThisLine = false;
FileType = SrcMgr::C_User;
Initialized = false;
IsFirstFileEntered = false;
PrevTok.startToken();
PrevPrevTok.startToken();
}
bool isMinimizeWhitespace() const { return MinimizeWhitespace; }
void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
bool hasEmittedDirectiveOnThisLine() const {
return EmittedDirectiveOnThisLine;
}
void startNewLineIfNeeded();
void FileChanged(SourceLocation Loc, FileChangeReason Reason,
SrcMgr::CharacteristicKind FileType,
FileID PrevFID) override;
void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
StringRef FileName, bool IsAngled,
CharSourceRange FilenameRange,
Optional<FileEntryRef> File, StringRef SearchPath,
StringRef RelativePath, const Module *Imported,
SrcMgr::CharacteristicKind FileType) override;
void Ident(SourceLocation Loc, StringRef str) override;
void PragmaMessage(SourceLocation Loc, StringRef Namespace,
PragmaMessageKind Kind, StringRef Str) override;
void PragmaDebug(SourceLocation Loc, StringRef DebugType) override;
void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override;
void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override;
void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
diag::Severity Map, StringRef Str) override;
void PragmaWarning(SourceLocation Loc, PragmaWarningSpecifier WarningSpec,
ArrayRef<int> Ids) override;
void PragmaWarningPush(SourceLocation Loc, int Level) override;
void PragmaWarningPop(SourceLocation Loc) override;
void PragmaExecCharsetPush(SourceLocation Loc, StringRef Str) override;
void PragmaExecCharsetPop(SourceLocation Loc) override;
void PragmaAssumeNonNullBegin(SourceLocation Loc) override;
void PragmaAssumeNonNullEnd(SourceLocation Loc) override;
void HandleWhitespaceBeforeTok(const Token &Tok, bool RequireSpace,
bool RequireSameLine);
bool MoveToLine(const Token &Tok, bool RequireStartOfLine) {
PresumedLoc PLoc = SM.getPresumedLoc(Tok.getLocation());
unsigned TargetLine = PLoc.isValid() ? PLoc.getLine() : CurLine;
bool IsFirstInFile =
Tok.isAtStartOfLine() && PLoc.isValid() && PLoc.getLine() == 1;
return MoveToLine(TargetLine, RequireStartOfLine) || IsFirstInFile;
}
bool MoveToLine(SourceLocation Loc, bool RequireStartOfLine) {
PresumedLoc PLoc = SM.getPresumedLoc(Loc);
unsigned TargetLine = PLoc.isValid() ? PLoc.getLine() : CurLine;
return MoveToLine(TargetLine, RequireStartOfLine);
}
bool MoveToLine(unsigned LineNo, bool RequireStartOfLine);
bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
const Token &Tok) {
return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
}
void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
unsigned ExtraLen=0);
bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
void HandleNewlinesInToken(const char *TokStr, unsigned Len);
void MacroDefined(const Token &MacroNameTok,
const MacroDirective *MD) override;
void MacroUndefined(const Token &MacroNameTok,
const MacroDefinition &MD,
const MacroDirective *Undef) override;
void BeginModule(const Module *M);
void EndModule(const Module *M);
};
}
void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
const char *Extra,
unsigned ExtraLen) {
startNewLineIfNeeded();
if (UseLineDirectives) {
OS << "#line" << ' ' << LineNo << ' ' << '"';
OS.write_escaped(CurFilename);
OS << '"';
} else {
OS << '#' << ' ' << LineNo << ' ' << '"';
OS.write_escaped(CurFilename);
OS << '"';
if (ExtraLen)
OS.write(Extra, ExtraLen);
if (FileType == SrcMgr::C_System)
OS.write(" 3", 2);
else if (FileType == SrcMgr::C_ExternCSystem)
OS.write(" 3 4", 4);
}
OS << '\n';
}
bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo,
bool RequireStartOfLine) {
bool StartedNewLine = false;
if ((RequireStartOfLine && EmittedTokensOnThisLine) ||
EmittedDirectiveOnThisLine) {
OS << '\n';
StartedNewLine = true;
CurLine += 1;
EmittedTokensOnThisLine = false;
EmittedDirectiveOnThisLine = false;
}
if (CurLine == LineNo) {
} else if (MinimizeWhitespace && DisableLineMarkers) {
} else if (!StartedNewLine && LineNo - CurLine == 1) {
OS << '\n';
StartedNewLine = true;
} else if (!DisableLineMarkers) {
if (LineNo - CurLine <= 8) {
const char *NewLines = "\n\n\n\n\n\n\n\n";
OS.write(NewLines, LineNo - CurLine);
} else {
WriteLineInfo(LineNo, nullptr, 0);
}
StartedNewLine = true;
} else if (EmittedTokensOnThisLine) {
OS << '\n';
StartedNewLine = true;
}
if (StartedNewLine) {
EmittedTokensOnThisLine = false;
EmittedDirectiveOnThisLine = false;
}
CurLine = LineNo;
return StartedNewLine;
}
void PrintPPOutputPPCallbacks::startNewLineIfNeeded() {
if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
OS << '\n';
EmittedTokensOnThisLine = false;
EmittedDirectiveOnThisLine = false;
}
}
void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
FileChangeReason Reason,
SrcMgr::CharacteristicKind NewFileType,
FileID PrevFID) {
SourceManager &SourceMgr = SM;
PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
if (UserLoc.isInvalid())
return;
unsigned NewLine = UserLoc.getLine();
if (Reason == PPCallbacks::EnterFile) {
SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
if (IncludeLoc.isValid())
MoveToLine(IncludeLoc, false);
} else if (Reason == PPCallbacks::SystemHeaderPragma) {
NewLine += 1;
}
CurLine = NewLine;
CurFilename.clear();
CurFilename += UserLoc.getFilename();
FileType = NewFileType;
if (DisableLineMarkers) {
if (!MinimizeWhitespace)
startNewLineIfNeeded();
return;
}
if (!Initialized) {
WriteLineInfo(CurLine);
Initialized = true;
}
if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
IsFirstFileEntered = true;
return;
}
switch (Reason) {
case PPCallbacks::EnterFile:
WriteLineInfo(CurLine, " 1", 2);
break;
case PPCallbacks::ExitFile:
WriteLineInfo(CurLine, " 2", 2);
break;
case PPCallbacks::SystemHeaderPragma:
case PPCallbacks::RenameFile:
WriteLineInfo(CurLine);
break;
}
}
void PrintPPOutputPPCallbacks::InclusionDirective(
SourceLocation HashLoc,
const Token &IncludeTok,
StringRef FileName,
bool IsAngled,
CharSourceRange FilenameRange,
Optional<FileEntryRef> File,
StringRef SearchPath,
StringRef RelativePath,
const Module *Imported,
SrcMgr::CharacteristicKind FileType) {
if (DumpIncludeDirectives) {
MoveToLine(HashLoc, true);
const std::string TokenText = PP.getSpelling(IncludeTok);
assert(!TokenText.empty());
OS << "#" << TokenText << " "
<< (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
<< " /* clang -E -dI */";
setEmittedDirectiveOnThisLine();
}
if (Imported) {
switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
case tok::pp_include:
case tok::pp_import:
case tok::pp_include_next:
MoveToLine(HashLoc, true);
OS << "#pragma clang module import " << Imported->getFullModuleName(true)
<< " /* clang -E: implicit import for "
<< "#" << PP.getSpelling(IncludeTok) << " "
<< (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
<< " */";
setEmittedDirectiveOnThisLine();
break;
case tok::pp___include_macros:
break;
default:
llvm_unreachable("unknown include directive kind");
break;
}
}
}
void PrintPPOutputPPCallbacks::BeginModule(const Module *M) {
startNewLineIfNeeded();
OS << "#pragma clang module begin " << M->getFullModuleName(true);
setEmittedDirectiveOnThisLine();
}
void PrintPPOutputPPCallbacks::EndModule(const Module *M) {
startNewLineIfNeeded();
OS << "#pragma clang module end /*" << M->getFullModuleName(true) << "*/";
setEmittedDirectiveOnThisLine();
}
void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
MoveToLine(Loc, true);
OS.write("#ident ", strlen("#ident "));
OS.write(S.begin(), S.size());
setEmittedTokensOnThisLine();
}
void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
const MacroDirective *MD) {
const MacroInfo *MI = MD->getMacroInfo();
if ((!DumpDefines && !DirectivesOnly) ||
MI->isBuiltinMacro())
return;
SourceLocation DefLoc = MI->getDefinitionLoc();
if (DirectivesOnly && !MI->isUsed()) {
SourceManager &SM = PP.getSourceManager();
if (SM.isWrittenInBuiltinFile(DefLoc) ||
SM.isWrittenInCommandLineFile(DefLoc))
return;
}
MoveToLine(DefLoc, true);
PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
setEmittedDirectiveOnThisLine();
}
void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
const MacroDefinition &MD,
const MacroDirective *Undef) {
if (!DumpDefines && !DirectivesOnly)
return;
MoveToLine(MacroNameTok.getLocation(), true);
OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
setEmittedDirectiveOnThisLine();
}
static void outputPrintable(raw_ostream &OS, StringRef Str) {
for (unsigned char Char : Str) {
if (isPrintable(Char) && Char != '\\' && Char != '"')
OS << (char)Char;
else OS << '\\'
<< (char)('0' + ((Char >> 6) & 7))
<< (char)('0' + ((Char >> 3) & 7))
<< (char)('0' + ((Char >> 0) & 7));
}
}
void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
StringRef Namespace,
PragmaMessageKind Kind,
StringRef Str) {
MoveToLine(Loc, true);
OS << "#pragma ";
if (!Namespace.empty())
OS << Namespace << ' ';
switch (Kind) {
case PMK_Message:
OS << "message(\"";
break;
case PMK_Warning:
OS << "warning \"";
break;
case PMK_Error:
OS << "error \"";
break;
}
outputPrintable(OS, Str);
OS << '"';
if (Kind == PMK_Message)
OS << ')';
setEmittedDirectiveOnThisLine();
}
void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
StringRef DebugType) {
MoveToLine(Loc, true);
OS << "#pragma clang __debug ";
OS << DebugType;
setEmittedDirectiveOnThisLine();
}
void PrintPPOutputPPCallbacks::
PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
MoveToLine(Loc, true);
OS << "#pragma " << Namespace << " diagnostic push";
setEmittedDirectiveOnThisLine();
}
void PrintPPOutputPPCallbacks::
PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
MoveToLine(Loc, true);
OS << "#pragma " << Namespace << " diagnostic pop";
setEmittedDirectiveOnThisLine();
}
void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
StringRef Namespace,
diag::Severity Map,
StringRef Str) {
MoveToLine(Loc, true);
OS << "#pragma " << Namespace << " diagnostic ";
switch (Map) {
case diag::Severity::Remark:
OS << "remark";
break;
case diag::Severity::Warning:
OS << "warning";
break;
case diag::Severity::Error:
OS << "error";
break;
case diag::Severity::Ignored:
OS << "ignored";
break;
case diag::Severity::Fatal:
OS << "fatal";
break;
}
OS << " \"" << Str << '"';
setEmittedDirectiveOnThisLine();
}
void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
PragmaWarningSpecifier WarningSpec,
ArrayRef<int> Ids) {
MoveToLine(Loc, true);
OS << "#pragma warning(";
switch(WarningSpec) {
case PWS_Default: OS << "default"; break;
case PWS_Disable: OS << "disable"; break;
case PWS_Error: OS << "error"; break;
case PWS_Once: OS << "once"; break;
case PWS_Suppress: OS << "suppress"; break;
case PWS_Level1: OS << '1'; break;
case PWS_Level2: OS << '2'; break;
case PWS_Level3: OS << '3'; break;
case PWS_Level4: OS << '4'; break;
}
OS << ':';
for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
OS << ' ' << *I;
OS << ')';
setEmittedDirectiveOnThisLine();
}
void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
int Level) {
MoveToLine(Loc, true);
OS << "#pragma warning(push";
if (Level >= 0)
OS << ", " << Level;
OS << ')';
setEmittedDirectiveOnThisLine();
}
void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
MoveToLine(Loc, true);
OS << "#pragma warning(pop)";
setEmittedDirectiveOnThisLine();
}
void PrintPPOutputPPCallbacks::PragmaExecCharsetPush(SourceLocation Loc,
StringRef Str) {
MoveToLine(Loc, true);
OS << "#pragma character_execution_set(push";
if (!Str.empty())
OS << ", " << Str;
OS << ')';
setEmittedDirectiveOnThisLine();
}
void PrintPPOutputPPCallbacks::PragmaExecCharsetPop(SourceLocation Loc) {
MoveToLine(Loc, true);
OS << "#pragma character_execution_set(pop)";
setEmittedDirectiveOnThisLine();
}
void PrintPPOutputPPCallbacks::
PragmaAssumeNonNullBegin(SourceLocation Loc) {
MoveToLine(Loc, true);
OS << "#pragma clang assume_nonnull begin";
setEmittedDirectiveOnThisLine();
}
void PrintPPOutputPPCallbacks::
PragmaAssumeNonNullEnd(SourceLocation Loc) {
MoveToLine(Loc, true);
OS << "#pragma clang assume_nonnull end";
setEmittedDirectiveOnThisLine();
}
void PrintPPOutputPPCallbacks::HandleWhitespaceBeforeTok(const Token &Tok,
bool RequireSpace,
bool RequireSameLine) {
if (Tok.is(tok::eof) ||
(Tok.isAnnotation() && !Tok.is(tok::annot_header_unit) &&
!Tok.is(tok::annot_module_begin) && !Tok.is(tok::annot_module_end)))
return;
if ((!RequireSameLine || EmittedDirectiveOnThisLine) &&
MoveToLine(Tok, EmittedDirectiveOnThisLine)) {
if (MinimizeWhitespace) {
if (Tok.is(tok::hash))
OS << ' ';
} else {
unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
if (ColNo == 1 && Tok.hasLeadingSpace())
ColNo = 2;
if (ColNo <= 1 && Tok.is(tok::hash))
OS << ' ';
for (; ColNo > 1; --ColNo)
OS << ' ';
}
} else {
if (RequireSpace || (!MinimizeWhitespace && Tok.hasLeadingSpace()) ||
((EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) &&
AvoidConcat(PrevPrevTok, PrevTok, Tok)))
OS << ' ';
}
PrevPrevTok = PrevTok;
PrevTok = Tok;
}
void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
unsigned Len) {
unsigned NumNewlines = 0;
for (; Len; --Len, ++TokStr) {
if (*TokStr != '\n' &&
*TokStr != '\r')
continue;
++NumNewlines;
if (Len != 1 &&
(TokStr[1] == '\n' || TokStr[1] == '\r') &&
TokStr[0] != TokStr[1]) {
++TokStr;
--Len;
}
}
if (NumNewlines == 0) return;
CurLine += NumNewlines;
}
namespace {
struct UnknownPragmaHandler : public PragmaHandler {
const char *Prefix;
PrintPPOutputPPCallbacks *Callbacks;
bool ShouldExpandTokens;
UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
bool RequireTokenExpansion)
: Prefix(prefix), Callbacks(callbacks),
ShouldExpandTokens(RequireTokenExpansion) {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &PragmaTok) override {
Callbacks->MoveToLine(PragmaTok.getLocation(), true);
Callbacks->OS.write(Prefix, strlen(Prefix));
Callbacks->setEmittedTokensOnThisLine();
if (ShouldExpandTokens) {
auto Toks = std::make_unique<Token[]>(1);
Toks[0] = PragmaTok;
PP.EnterTokenStream(std::move(Toks), 1,
false,
false);
PP.Lex(PragmaTok);
}
bool IsFirst = true;
while (PragmaTok.isNot(tok::eod)) {
Callbacks->HandleWhitespaceBeforeTok(PragmaTok, IsFirst,
true);
IsFirst = false;
std::string TokSpell = PP.getSpelling(PragmaTok);
Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Callbacks->setEmittedTokensOnThisLine();
if (ShouldExpandTokens)
PP.Lex(PragmaTok);
else
PP.LexUnexpandedToken(PragmaTok);
}
Callbacks->setEmittedDirectiveOnThisLine();
}
};
}
static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
PrintPPOutputPPCallbacks *Callbacks,
raw_ostream &OS) {
bool DropComments = PP.getLangOpts().TraditionalCPP &&
!PP.getCommentRetentionState();
bool IsStartOfLine = false;
char Buffer[256];
while (true) {
IsStartOfLine = IsStartOfLine || Tok.isAtStartOfLine();
Callbacks->HandleWhitespaceBeforeTok(Tok, false,
!IsStartOfLine);
if (DropComments && Tok.is(tok::comment)) {
PP.Lex(Tok);
continue;
} else if (Tok.is(tok::eod)) {
PP.Lex(Tok);
IsStartOfLine = true;
continue;
} else if (Tok.is(tok::annot_module_include)) {
PP.Lex(Tok);
IsStartOfLine = true;
continue;
} else if (Tok.is(tok::annot_module_begin)) {
Callbacks->BeginModule(
reinterpret_cast<Module *>(Tok.getAnnotationValue()));
PP.Lex(Tok);
IsStartOfLine = true;
continue;
} else if (Tok.is(tok::annot_module_end)) {
Callbacks->EndModule(
reinterpret_cast<Module *>(Tok.getAnnotationValue()));
PP.Lex(Tok);
IsStartOfLine = true;
continue;
} else if (Tok.is(tok::annot_header_unit)) {
Module *M = reinterpret_cast<Module *>(Tok.getAnnotationValue());
std::string Name = M->getFullModuleName();
OS.write(Name.data(), Name.size());
Callbacks->HandleNewlinesInToken(Name.data(), Name.size());
} else if (Tok.isAnnotation()) {
PP.Lex(Tok);
continue;
} else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
OS << II->getName();
} else if (Tok.isLiteral() && !Tok.needsCleaning() &&
Tok.getLiteralData()) {
OS.write(Tok.getLiteralData(), Tok.getLength());
} else if (Tok.getLength() < llvm::array_lengthof(Buffer)) {
const char *TokPtr = Buffer;
unsigned Len = PP.getSpelling(Tok, TokPtr);
OS.write(TokPtr, Len);
if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Callbacks->HandleNewlinesInToken(TokPtr, Len);
if (Tok.is(tok::comment) && Len >= 2 && TokPtr[0] == '/' &&
TokPtr[1] == '/') {
Callbacks->setEmittedDirectiveOnThisLine();
}
} else {
std::string S = PP.getSpelling(Tok);
OS.write(S.data(), S.size());
if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Callbacks->HandleNewlinesInToken(S.data(), S.size());
if (Tok.is(tok::comment) && S.size() >= 2 && S[0] == '/' && S[1] == '/') {
Callbacks->setEmittedDirectiveOnThisLine();
}
}
Callbacks->setEmittedTokensOnThisLine();
IsStartOfLine = false;
if (Tok.is(tok::eof)) break;
PP.Lex(Tok);
}
}
typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
return LHS->first->getName().compare(RHS->first->getName());
}
static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
PP.IgnorePragmas();
PP.EnterMainSourceFile();
Token Tok;
do PP.Lex(Tok);
while (Tok.isNot(tok::eof));
SmallVector<id_macro_pair, 128> MacrosByID;
for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
I != E; ++I) {
auto *MD = I->second.getLatest();
if (MD && MD->isDefined())
MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
}
llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
MacroInfo &MI = *MacrosByID[i].second;
if (MI.isBuiltinMacro()) continue;
PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
*OS << '\n';
}
}
void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
const PreprocessorOutputOptions &Opts) {
if (!Opts.ShowCPP) {
assert(Opts.ShowMacros && "Not yet implemented!");
DoPrintMacros(PP, OS);
return;
}
PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
Opts.ShowIncludeDirectives, Opts.UseLineDirectives,
Opts.MinimizeWhitespace, Opts.DirectivesOnly);
std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(
new UnknownPragmaHandler(
"#pragma", Callbacks,
PP.getLangOpts().MicrosoftExt));
std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(
"#pragma GCC", Callbacks,
PP.getLangOpts().MicrosoftExt));
std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(
"#pragma clang", Callbacks,
PP.getLangOpts().MicrosoftExt));
PP.AddPragmaHandler(MicrosoftExtHandler.get());
PP.AddPragmaHandler("GCC", GCCHandler.get());
PP.AddPragmaHandler("clang", ClangHandler.get());
std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(
new UnknownPragmaHandler("#pragma omp", Callbacks,
true));
PP.AddPragmaHandler("omp", OpenMPHandler.get());
PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
PP.EnterMainSourceFile();
if (Opts.DirectivesOnly)
PP.SetMacroExpansionOnlyInDirectives();
const SourceManager &SourceMgr = PP.getSourceManager();
Token Tok;
do {
PP.Lex(Tok);
if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
break;
PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
if (PLoc.isInvalid())
break;
if (strcmp(PLoc.getFilename(), "<built-in>"))
break;
} while (true);
PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
*OS << '\n';
PP.RemovePragmaHandler(MicrosoftExtHandler.get());
PP.RemovePragmaHandler("GCC", GCCHandler.get());
PP.RemovePragmaHandler("clang", ClangHandler.get());
PP.RemovePragmaHandler("omp", OpenMPHandler.get());
}