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