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