Home | History | Annotate | Download | only in Frontend
      1 //===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This code simply runs the preprocessor on the input file and prints out the
     11 // result.  This is the traditional behavior of the -E option.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "clang/Frontend/Utils.h"
     16 #include "clang/Basic/CharInfo.h"
     17 #include "clang/Basic/Diagnostic.h"
     18 #include "clang/Basic/SourceManager.h"
     19 #include "clang/Frontend/PreprocessorOutputOptions.h"
     20 #include "clang/Lex/MacroInfo.h"
     21 #include "clang/Lex/PPCallbacks.h"
     22 #include "clang/Lex/Pragma.h"
     23 #include "clang/Lex/Preprocessor.h"
     24 #include "clang/Lex/TokenConcatenation.h"
     25 #include "llvm/ADT/STLExtras.h"
     26 #include "llvm/ADT/SmallString.h"
     27 #include "llvm/ADT/StringRef.h"
     28 #include "llvm/Support/ErrorHandling.h"
     29 #include "llvm/Support/raw_ostream.h"
     30 #include <cstdio>
     31 using namespace clang;
     32 
     33 /// PrintMacroDefinition - Print a macro definition in a form that will be
     34 /// properly accepted back as a definition.
     35 static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
     36                                  Preprocessor &PP, raw_ostream &OS) {
     37   OS << "#define " << II.getName();
     38 
     39   if (MI.isFunctionLike()) {
     40     OS << '(';
     41     if (!MI.arg_empty()) {
     42       MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
     43       for (; AI+1 != E; ++AI) {
     44         OS << (*AI)->getName();
     45         OS << ',';
     46       }
     47 
     48       // Last argument.
     49       if ((*AI)->getName() == "__VA_ARGS__")
     50         OS << "...";
     51       else
     52         OS << (*AI)->getName();
     53     }
     54 
     55     if (MI.isGNUVarargs())
     56       OS << "...";  // #define foo(x...)
     57 
     58     OS << ')';
     59   }
     60 
     61   // GCC always emits a space, even if the macro body is empty.  However, do not
     62   // want to emit two spaces if the first token has a leading space.
     63   if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
     64     OS << ' ';
     65 
     66   SmallString<128> SpellingBuffer;
     67   for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end();
     68        I != E; ++I) {
     69     if (I->hasLeadingSpace())
     70       OS << ' ';
     71 
     72     OS << PP.getSpelling(*I, SpellingBuffer);
     73   }
     74 }
     75 
     76 //===----------------------------------------------------------------------===//
     77 // Preprocessed token printer
     78 //===----------------------------------------------------------------------===//
     79 
     80 namespace {
     81 class PrintPPOutputPPCallbacks : public PPCallbacks {
     82   Preprocessor &PP;
     83   SourceManager &SM;
     84   TokenConcatenation ConcatInfo;
     85 public:
     86   raw_ostream &OS;
     87 private:
     88   unsigned CurLine;
     89 
     90   bool EmittedTokensOnThisLine;
     91   bool EmittedDirectiveOnThisLine;
     92   SrcMgr::CharacteristicKind FileType;
     93   SmallString<512> CurFilename;
     94   bool Initialized;
     95   bool DisableLineMarkers;
     96   bool DumpDefines;
     97   bool UseLineDirective;
     98   bool IsFirstFileEntered;
     99 public:
    100   PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os,
    101                            bool lineMarkers, bool defines)
    102      : PP(pp), SM(PP.getSourceManager()),
    103        ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
    104        DumpDefines(defines) {
    105     CurLine = 0;
    106     CurFilename += "<uninit>";
    107     EmittedTokensOnThisLine = false;
    108     EmittedDirectiveOnThisLine = false;
    109     FileType = SrcMgr::C_User;
    110     Initialized = false;
    111     IsFirstFileEntered = false;
    112 
    113     // If we're in microsoft mode, use normal #line instead of line markers.
    114     UseLineDirective = PP.getLangOpts().MicrosoftExt;
    115   }
    116 
    117   void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
    118   bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
    119 
    120   void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
    121   bool hasEmittedDirectiveOnThisLine() const {
    122     return EmittedDirectiveOnThisLine;
    123   }
    124 
    125   bool startNewLineIfNeeded(bool ShouldUpdateCurrentLine = true);
    126 
    127   virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
    128                            SrcMgr::CharacteristicKind FileType,
    129                            FileID PrevFID);
    130   virtual void InclusionDirective(SourceLocation HashLoc,
    131                                   const Token &IncludeTok,
    132                                   StringRef FileName,
    133                                   bool IsAngled,
    134                                   CharSourceRange FilenameRange,
    135                                   const FileEntry *File,
    136                                   StringRef SearchPath,
    137                                   StringRef RelativePath,
    138                                   const Module *Imported);
    139   virtual void Ident(SourceLocation Loc, const std::string &str);
    140   virtual void PragmaCaptured(SourceLocation Loc, StringRef Str);
    141   virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
    142                              const std::string &Str);
    143   virtual void PragmaDetectMismatch(SourceLocation Loc,
    144                                     const std::string &Name,
    145                                     const std::string &Value);
    146   virtual void PragmaMessage(SourceLocation Loc, StringRef Namespace,
    147                              PragmaMessageKind Kind, StringRef Str);
    148   virtual void PragmaDebug(SourceLocation Loc, StringRef DebugType);
    149   virtual void PragmaDiagnosticPush(SourceLocation Loc,
    150                                     StringRef Namespace);
    151   virtual void PragmaDiagnosticPop(SourceLocation Loc,
    152                                    StringRef Namespace);
    153   virtual void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
    154                                 diag::Mapping Map, StringRef Str);
    155 
    156   bool HandleFirstTokOnLine(Token &Tok);
    157 
    158   /// Move to the line of the provided source location. This will
    159   /// return true if the output stream required adjustment or if
    160   /// the requested location is on the first line.
    161   bool MoveToLine(SourceLocation Loc) {
    162     PresumedLoc PLoc = SM.getPresumedLoc(Loc);
    163     if (PLoc.isInvalid())
    164       return false;
    165     return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
    166   }
    167   bool MoveToLine(unsigned LineNo);
    168 
    169   bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
    170                    const Token &Tok) {
    171     return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
    172   }
    173   void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
    174   bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
    175   void HandleNewlinesInToken(const char *TokStr, unsigned Len);
    176 
    177   /// MacroDefined - This hook is called whenever a macro definition is seen.
    178   void MacroDefined(const Token &MacroNameTok, const MacroDirective *MD);
    179 
    180   /// MacroUndefined - This hook is called whenever a macro #undef is seen.
    181   void MacroUndefined(const Token &MacroNameTok, const MacroDirective *MD);
    182 };
    183 }  // end anonymous namespace
    184 
    185 void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
    186                                              const char *Extra,
    187                                              unsigned ExtraLen) {
    188   startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
    189 
    190   // Emit #line directives or GNU line markers depending on what mode we're in.
    191   if (UseLineDirective) {
    192     OS << "#line" << ' ' << LineNo << ' ' << '"';
    193     OS.write(CurFilename.data(), CurFilename.size());
    194     OS << '"';
    195   } else {
    196     OS << '#' << ' ' << LineNo << ' ' << '"';
    197     OS.write(CurFilename.data(), CurFilename.size());
    198     OS << '"';
    199 
    200     if (ExtraLen)
    201       OS.write(Extra, ExtraLen);
    202 
    203     if (FileType == SrcMgr::C_System)
    204       OS.write(" 3", 2);
    205     else if (FileType == SrcMgr::C_ExternCSystem)
    206       OS.write(" 3 4", 4);
    207   }
    208   OS << '\n';
    209 }
    210 
    211 /// MoveToLine - Move the output to the source line specified by the location
    212 /// object.  We can do this by emitting some number of \n's, or be emitting a
    213 /// #line directive.  This returns false if already at the specified line, true
    214 /// if some newlines were emitted.
    215 bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
    216   // If this line is "close enough" to the original line, just print newlines,
    217   // otherwise print a #line directive.
    218   if (LineNo-CurLine <= 8) {
    219     if (LineNo-CurLine == 1)
    220       OS << '\n';
    221     else if (LineNo == CurLine)
    222       return false;    // Spelling line moved, but expansion line didn't.
    223     else {
    224       const char *NewLines = "\n\n\n\n\n\n\n\n";
    225       OS.write(NewLines, LineNo-CurLine);
    226     }
    227   } else if (!DisableLineMarkers) {
    228     // Emit a #line or line marker.
    229     WriteLineInfo(LineNo, 0, 0);
    230   } else {
    231     // Okay, we're in -P mode, which turns off line markers.  However, we still
    232     // need to emit a newline between tokens on different lines.
    233     startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
    234   }
    235 
    236   CurLine = LineNo;
    237   return true;
    238 }
    239 
    240 bool
    241 PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
    242   if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
    243     OS << '\n';
    244     EmittedTokensOnThisLine = false;
    245     EmittedDirectiveOnThisLine = false;
    246     if (ShouldUpdateCurrentLine)
    247       ++CurLine;
    248     return true;
    249   }
    250 
    251   return false;
    252 }
    253 
    254 /// FileChanged - Whenever the preprocessor enters or exits a #include file
    255 /// it invokes this handler.  Update our conception of the current source
    256 /// position.
    257 void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
    258                                            FileChangeReason Reason,
    259                                        SrcMgr::CharacteristicKind NewFileType,
    260                                        FileID PrevFID) {
    261   // Unless we are exiting a #include, make sure to skip ahead to the line the
    262   // #include directive was at.
    263   SourceManager &SourceMgr = SM;
    264 
    265   PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
    266   if (UserLoc.isInvalid())
    267     return;
    268 
    269   unsigned NewLine = UserLoc.getLine();
    270 
    271   if (Reason == PPCallbacks::EnterFile) {
    272     SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
    273     if (IncludeLoc.isValid())
    274       MoveToLine(IncludeLoc);
    275   } else if (Reason == PPCallbacks::SystemHeaderPragma) {
    276     // GCC emits the # directive for this directive on the line AFTER the
    277     // directive and emits a bunch of spaces that aren't needed. This is because
    278     // otherwise we will emit a line marker for THIS line, which requires an
    279     // extra blank line after the directive to avoid making all following lines
    280     // off by one. We can do better by simply incrementing NewLine here.
    281     NewLine += 1;
    282   }
    283 
    284   CurLine = NewLine;
    285 
    286   CurFilename.clear();
    287   CurFilename += UserLoc.getFilename();
    288   Lexer::Stringify(CurFilename);
    289   FileType = NewFileType;
    290 
    291   if (DisableLineMarkers) {
    292     startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
    293     return;
    294   }
    295 
    296   if (!Initialized) {
    297     WriteLineInfo(CurLine);
    298     Initialized = true;
    299   }
    300 
    301   // Do not emit an enter marker for the main file (which we expect is the first
    302   // entered file). This matches gcc, and improves compatibility with some tools
    303   // which track the # line markers as a way to determine when the preprocessed
    304   // output is in the context of the main file.
    305   if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
    306     IsFirstFileEntered = true;
    307     return;
    308   }
    309 
    310   switch (Reason) {
    311   case PPCallbacks::EnterFile:
    312     WriteLineInfo(CurLine, " 1", 2);
    313     break;
    314   case PPCallbacks::ExitFile:
    315     WriteLineInfo(CurLine, " 2", 2);
    316     break;
    317   case PPCallbacks::SystemHeaderPragma:
    318   case PPCallbacks::RenameFile:
    319     WriteLineInfo(CurLine);
    320     break;
    321   }
    322 }
    323 
    324 void PrintPPOutputPPCallbacks::InclusionDirective(SourceLocation HashLoc,
    325                                                   const Token &IncludeTok,
    326                                                   StringRef FileName,
    327                                                   bool IsAngled,
    328                                                   CharSourceRange FilenameRange,
    329                                                   const FileEntry *File,
    330                                                   StringRef SearchPath,
    331                                                   StringRef RelativePath,
    332                                                   const Module *Imported) {
    333   // When preprocessing, turn implicit imports into @imports.
    334   // FIXME: This is a stop-gap until a more comprehensive "preprocessing with
    335   // modules" solution is introduced.
    336   if (Imported) {
    337     startNewLineIfNeeded();
    338     MoveToLine(HashLoc);
    339     OS << "@import " << Imported->getFullModuleName() << ";"
    340        << " /* clang -E: implicit import for \"" << File->getName() << "\" */";
    341     EmittedTokensOnThisLine = true;
    342   }
    343 }
    344 
    345 /// Ident - Handle #ident directives when read by the preprocessor.
    346 ///
    347 void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
    348   MoveToLine(Loc);
    349 
    350   OS.write("#ident ", strlen("#ident "));
    351   OS.write(&S[0], S.size());
    352   EmittedTokensOnThisLine = true;
    353 }
    354 
    355 void PrintPPOutputPPCallbacks::PragmaCaptured(SourceLocation Loc,
    356                                               StringRef Str) {
    357   startNewLineIfNeeded();
    358   MoveToLine(Loc);
    359   OS << "#pragma captured";
    360 
    361   setEmittedDirectiveOnThisLine();
    362 }
    363 
    364 /// MacroDefined - This hook is called whenever a macro definition is seen.
    365 void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
    366                                             const MacroDirective *MD) {
    367   const MacroInfo *MI = MD->getMacroInfo();
    368   // Only print out macro definitions in -dD mode.
    369   if (!DumpDefines ||
    370       // Ignore __FILE__ etc.
    371       MI->isBuiltinMacro()) return;
    372 
    373   MoveToLine(MI->getDefinitionLoc());
    374   PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
    375   setEmittedDirectiveOnThisLine();
    376 }
    377 
    378 void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
    379                                               const MacroDirective *MD) {
    380   // Only print out macro definitions in -dD mode.
    381   if (!DumpDefines) return;
    382 
    383   MoveToLine(MacroNameTok.getLocation());
    384   OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
    385   setEmittedDirectiveOnThisLine();
    386 }
    387 
    388 static void outputPrintable(llvm::raw_ostream& OS,
    389                                              const std::string &Str) {
    390     for (unsigned i = 0, e = Str.size(); i != e; ++i) {
    391       unsigned char Char = Str[i];
    392       if (isPrintable(Char) && Char != '\\' && Char != '"')
    393         OS << (char)Char;
    394       else  // Output anything hard as an octal escape.
    395         OS << '\\'
    396            << (char)('0'+ ((Char >> 6) & 7))
    397            << (char)('0'+ ((Char >> 3) & 7))
    398            << (char)('0'+ ((Char >> 0) & 7));
    399     }
    400 }
    401 
    402 void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
    403                                              const IdentifierInfo *Kind,
    404                                              const std::string &Str) {
    405   startNewLineIfNeeded();
    406   MoveToLine(Loc);
    407   OS << "#pragma comment(" << Kind->getName();
    408 
    409   if (!Str.empty()) {
    410     OS << ", \"";
    411     outputPrintable(OS, Str);
    412     OS << '"';
    413   }
    414 
    415   OS << ')';
    416   setEmittedDirectiveOnThisLine();
    417 }
    418 
    419 void PrintPPOutputPPCallbacks::PragmaDetectMismatch(SourceLocation Loc,
    420                                                     const std::string &Name,
    421                                                     const std::string &Value) {
    422   startNewLineIfNeeded();
    423   MoveToLine(Loc);
    424   OS << "#pragma detect_mismatch(\"" << Name << '"';
    425   outputPrintable(OS, Name);
    426   OS << "\", \"";
    427   outputPrintable(OS, Value);
    428   OS << "\")";
    429   setEmittedDirectiveOnThisLine();
    430 }
    431 
    432 void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
    433                                              StringRef Namespace,
    434                                              PragmaMessageKind Kind,
    435                                              StringRef Str) {
    436   startNewLineIfNeeded();
    437   MoveToLine(Loc);
    438   OS << "#pragma ";
    439   if (!Namespace.empty())
    440     OS << Namespace << ' ';
    441   switch (Kind) {
    442     case PMK_Message:
    443       OS << "message(\"";
    444       break;
    445     case PMK_Warning:
    446       OS << "warning \"";
    447       break;
    448     case PMK_Error:
    449       OS << "error \"";
    450       break;
    451   }
    452 
    453   outputPrintable(OS, Str);
    454   OS << '"';
    455   if (Kind == PMK_Message)
    456     OS << ')';
    457   setEmittedDirectiveOnThisLine();
    458 }
    459 
    460 void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
    461                                            StringRef DebugType) {
    462   startNewLineIfNeeded();
    463   MoveToLine(Loc);
    464 
    465   OS << "#pragma clang __debug ";
    466   OS << DebugType;
    467 
    468   setEmittedDirectiveOnThisLine();
    469 }
    470 
    471 void PrintPPOutputPPCallbacks::
    472 PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
    473   startNewLineIfNeeded();
    474   MoveToLine(Loc);
    475   OS << "#pragma " << Namespace << " diagnostic push";
    476   setEmittedDirectiveOnThisLine();
    477 }
    478 
    479 void PrintPPOutputPPCallbacks::
    480 PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
    481   startNewLineIfNeeded();
    482   MoveToLine(Loc);
    483   OS << "#pragma " << Namespace << " diagnostic pop";
    484   setEmittedDirectiveOnThisLine();
    485 }
    486 
    487 void PrintPPOutputPPCallbacks::
    488 PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
    489                  diag::Mapping Map, StringRef Str) {
    490   startNewLineIfNeeded();
    491   MoveToLine(Loc);
    492   OS << "#pragma " << Namespace << " diagnostic ";
    493   switch (Map) {
    494   case diag::MAP_WARNING:
    495     OS << "warning";
    496     break;
    497   case diag::MAP_ERROR:
    498     OS << "error";
    499     break;
    500   case diag::MAP_IGNORE:
    501     OS << "ignored";
    502     break;
    503   case diag::MAP_FATAL:
    504     OS << "fatal";
    505     break;
    506   }
    507   OS << " \"" << Str << '"';
    508   setEmittedDirectiveOnThisLine();
    509 }
    510 
    511 /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
    512 /// is called for the first token on each new line.  If this really is the start
    513 /// of a new logical line, handle it and return true, otherwise return false.
    514 /// This may not be the start of a logical line because the "start of line"
    515 /// marker is set for spelling lines, not expansion ones.
    516 bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
    517   // Figure out what line we went to and insert the appropriate number of
    518   // newline characters.
    519   if (!MoveToLine(Tok.getLocation()))
    520     return false;
    521 
    522   // Print out space characters so that the first token on a line is
    523   // indented for easy reading.
    524   unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
    525 
    526   // This hack prevents stuff like:
    527   // #define HASH #
    528   // HASH define foo bar
    529   // From having the # character end up at column 1, which makes it so it
    530   // is not handled as a #define next time through the preprocessor if in
    531   // -fpreprocessed mode.
    532   if (ColNo <= 1 && Tok.is(tok::hash))
    533     OS << ' ';
    534 
    535   // Otherwise, indent the appropriate number of spaces.
    536   for (; ColNo > 1; --ColNo)
    537     OS << ' ';
    538 
    539   return true;
    540 }
    541 
    542 void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
    543                                                      unsigned Len) {
    544   unsigned NumNewlines = 0;
    545   for (; Len; --Len, ++TokStr) {
    546     if (*TokStr != '\n' &&
    547         *TokStr != '\r')
    548       continue;
    549 
    550     ++NumNewlines;
    551 
    552     // If we have \n\r or \r\n, skip both and count as one line.
    553     if (Len != 1 &&
    554         (TokStr[1] == '\n' || TokStr[1] == '\r') &&
    555         TokStr[0] != TokStr[1])
    556       ++TokStr, --Len;
    557   }
    558 
    559   if (NumNewlines == 0) return;
    560 
    561   CurLine += NumNewlines;
    562 }
    563 
    564 
    565 namespace {
    566 struct UnknownPragmaHandler : public PragmaHandler {
    567   const char *Prefix;
    568   PrintPPOutputPPCallbacks *Callbacks;
    569 
    570   UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
    571     : Prefix(prefix), Callbacks(callbacks) {}
    572   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
    573                             Token &PragmaTok) {
    574     // Figure out what line we went to and insert the appropriate number of
    575     // newline characters.
    576     Callbacks->startNewLineIfNeeded();
    577     Callbacks->MoveToLine(PragmaTok.getLocation());
    578     Callbacks->OS.write(Prefix, strlen(Prefix));
    579     // Read and print all of the pragma tokens.
    580     while (PragmaTok.isNot(tok::eod)) {
    581       if (PragmaTok.hasLeadingSpace())
    582         Callbacks->OS << ' ';
    583       std::string TokSpell = PP.getSpelling(PragmaTok);
    584       Callbacks->OS.write(&TokSpell[0], TokSpell.size());
    585       PP.LexUnexpandedToken(PragmaTok);
    586     }
    587     Callbacks->setEmittedDirectiveOnThisLine();
    588   }
    589 };
    590 } // end anonymous namespace
    591 
    592 
    593 static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
    594                                     PrintPPOutputPPCallbacks *Callbacks,
    595                                     raw_ostream &OS) {
    596   bool DropComments = PP.getLangOpts().TraditionalCPP &&
    597                       !PP.getCommentRetentionState();
    598 
    599   char Buffer[256];
    600   Token PrevPrevTok, PrevTok;
    601   PrevPrevTok.startToken();
    602   PrevTok.startToken();
    603   while (1) {
    604     if (Callbacks->hasEmittedDirectiveOnThisLine()) {
    605       Callbacks->startNewLineIfNeeded();
    606       Callbacks->MoveToLine(Tok.getLocation());
    607     }
    608 
    609     // If this token is at the start of a line, emit newlines if needed.
    610     if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
    611       // done.
    612     } else if (Tok.hasLeadingSpace() ||
    613                // If we haven't emitted a token on this line yet, PrevTok isn't
    614                // useful to look at and no concatenation could happen anyway.
    615                (Callbacks->hasEmittedTokensOnThisLine() &&
    616                 // Don't print "-" next to "-", it would form "--".
    617                 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
    618       OS << ' ';
    619     }
    620 
    621     if (DropComments && Tok.is(tok::comment)) {
    622       // Skip comments. Normally the preprocessor does not generate
    623       // tok::comment nodes at all when not keeping comments, but under
    624       // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
    625       SourceLocation StartLoc = Tok.getLocation();
    626       Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
    627     } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
    628       OS << II->getName();
    629     } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
    630                Tok.getLiteralData()) {
    631       OS.write(Tok.getLiteralData(), Tok.getLength());
    632     } else if (Tok.getLength() < 256) {
    633       const char *TokPtr = Buffer;
    634       unsigned Len = PP.getSpelling(Tok, TokPtr);
    635       OS.write(TokPtr, Len);
    636 
    637       // Tokens that can contain embedded newlines need to adjust our current
    638       // line number.
    639       if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
    640         Callbacks->HandleNewlinesInToken(TokPtr, Len);
    641     } else {
    642       std::string S = PP.getSpelling(Tok);
    643       OS.write(&S[0], S.size());
    644 
    645       // Tokens that can contain embedded newlines need to adjust our current
    646       // line number.
    647       if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
    648         Callbacks->HandleNewlinesInToken(&S[0], S.size());
    649     }
    650     Callbacks->setEmittedTokensOnThisLine();
    651 
    652     if (Tok.is(tok::eof)) break;
    653 
    654     PrevPrevTok = PrevTok;
    655     PrevTok = Tok;
    656     PP.Lex(Tok);
    657   }
    658 }
    659 
    660 typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
    661 static int MacroIDCompare(const void* a, const void* b) {
    662   const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
    663   const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
    664   return LHS->first->getName().compare(RHS->first->getName());
    665 }
    666 
    667 static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
    668   // Ignore unknown pragmas.
    669   PP.AddPragmaHandler(new EmptyPragmaHandler());
    670 
    671   // -dM mode just scans and ignores all tokens in the files, then dumps out
    672   // the macro table at the end.
    673   PP.EnterMainSourceFile();
    674 
    675   Token Tok;
    676   do PP.Lex(Tok);
    677   while (Tok.isNot(tok::eof));
    678 
    679   SmallVector<id_macro_pair, 128> MacrosByID;
    680   for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
    681        I != E; ++I) {
    682     if (I->first->hasMacroDefinition())
    683       MacrosByID.push_back(id_macro_pair(I->first, I->second->getMacroInfo()));
    684   }
    685   llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
    686 
    687   for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
    688     MacroInfo &MI = *MacrosByID[i].second;
    689     // Ignore computed macros like __LINE__ and friends.
    690     if (MI.isBuiltinMacro()) continue;
    691 
    692     PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
    693     *OS << '\n';
    694   }
    695 }
    696 
    697 /// DoPrintPreprocessedInput - This implements -E mode.
    698 ///
    699 void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
    700                                      const PreprocessorOutputOptions &Opts) {
    701   // Show macros with no output is handled specially.
    702   if (!Opts.ShowCPP) {
    703     assert(Opts.ShowMacros && "Not yet implemented!");
    704     DoPrintMacros(PP, OS);
    705     return;
    706   }
    707 
    708   // Inform the preprocessor whether we want it to retain comments or not, due
    709   // to -C or -CC.
    710   PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
    711 
    712   PrintPPOutputPPCallbacks *Callbacks =
    713       new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
    714                                    Opts.ShowMacros);
    715   PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
    716   PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
    717   PP.AddPragmaHandler("clang",
    718                       new UnknownPragmaHandler("#pragma clang", Callbacks));
    719 
    720   PP.addPPCallbacks(Callbacks);
    721 
    722   // After we have configured the preprocessor, enter the main file.
    723   PP.EnterMainSourceFile();
    724 
    725   // Consume all of the tokens that come from the predefines buffer.  Those
    726   // should not be emitted into the output and are guaranteed to be at the
    727   // start.
    728   const SourceManager &SourceMgr = PP.getSourceManager();
    729   Token Tok;
    730   do {
    731     PP.Lex(Tok);
    732     if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
    733       break;
    734 
    735     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
    736     if (PLoc.isInvalid())
    737       break;
    738 
    739     if (strcmp(PLoc.getFilename(), "<built-in>"))
    740       break;
    741   } while (true);
    742 
    743   // Read all the preprocessed tokens, printing them out to the stream.
    744   PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
    745   *OS << '\n';
    746 }
    747