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_escaped(CurFilename);
194     OS << '"';
195   } else {
196     OS << '#' << ' ' << LineNo << ' ' << '"';
197     OS.write_escaped(CurFilename);
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   FileType = NewFileType;
289 
290   if (DisableLineMarkers) {
291     startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
292     return;
293   }
294 
295   if (!Initialized) {
296     WriteLineInfo(CurLine);
297     Initialized = true;
298   }
299 
300   // Do not emit an enter marker for the main file (which we expect is the first
301   // entered file). This matches gcc, and improves compatibility with some tools
302   // which track the # line markers as a way to determine when the preprocessed
303   // output is in the context of the main file.
304   if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
305     IsFirstFileEntered = true;
306     return;
307   }
308 
309   switch (Reason) {
310   case PPCallbacks::EnterFile:
311     WriteLineInfo(CurLine, " 1", 2);
312     break;
313   case PPCallbacks::ExitFile:
314     WriteLineInfo(CurLine, " 2", 2);
315     break;
316   case PPCallbacks::SystemHeaderPragma:
317   case PPCallbacks::RenameFile:
318     WriteLineInfo(CurLine);
319     break;
320   }
321 }
322 
323 void PrintPPOutputPPCallbacks::InclusionDirective(SourceLocation HashLoc,
324                                                   const Token &IncludeTok,
325                                                   StringRef FileName,
326                                                   bool IsAngled,
327                                                   CharSourceRange FilenameRange,
328                                                   const FileEntry *File,
329                                                   StringRef SearchPath,
330                                                   StringRef RelativePath,
331                                                   const Module *Imported) {
332   // When preprocessing, turn implicit imports into @imports.
333   // FIXME: This is a stop-gap until a more comprehensive "preprocessing with
334   // modules" solution is introduced.
335   if (Imported) {
336     startNewLineIfNeeded();
337     MoveToLine(HashLoc);
338     OS << "@import " << Imported->getFullModuleName() << ";"
339        << " /* clang -E: implicit import for \"" << File->getName() << "\" */";
340     EmittedTokensOnThisLine = true;
341   }
342 }
343 
344 /// Ident - Handle #ident directives when read by the preprocessor.
345 ///
346 void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
347   MoveToLine(Loc);
348 
349   OS.write("#ident ", strlen("#ident "));
350   OS.write(&S[0], S.size());
351   EmittedTokensOnThisLine = true;
352 }
353 
354 void PrintPPOutputPPCallbacks::PragmaCaptured(SourceLocation Loc,
355                                               StringRef Str) {
356   startNewLineIfNeeded();
357   MoveToLine(Loc);
358   OS << "#pragma captured";
359 
360   setEmittedDirectiveOnThisLine();
361 }
362 
363 /// MacroDefined - This hook is called whenever a macro definition is seen.
364 void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
365                                             const MacroDirective *MD) {
366   const MacroInfo *MI = MD->getMacroInfo();
367   // Only print out macro definitions in -dD mode.
368   if (!DumpDefines ||
369       // Ignore __FILE__ etc.
370       MI->isBuiltinMacro()) return;
371 
372   MoveToLine(MI->getDefinitionLoc());
373   PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
374   setEmittedDirectiveOnThisLine();
375 }
376 
377 void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
378                                               const MacroDirective *MD) {
379   // Only print out macro definitions in -dD mode.
380   if (!DumpDefines) return;
381 
382   MoveToLine(MacroNameTok.getLocation());
383   OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
384   setEmittedDirectiveOnThisLine();
385 }
386 
387 static void outputPrintable(llvm::raw_ostream& OS,
388                                              const std::string &Str) {
389     for (unsigned i = 0, e = Str.size(); i != e; ++i) {
390       unsigned char Char = Str[i];
391       if (isPrintable(Char) && Char != '\\' && Char != '"')
392         OS << (char)Char;
393       else  // Output anything hard as an octal escape.
394         OS << '\\'
395            << (char)('0'+ ((Char >> 6) & 7))
396            << (char)('0'+ ((Char >> 3) & 7))
397            << (char)('0'+ ((Char >> 0) & 7));
398     }
399 }
400 
401 void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
402                                              const IdentifierInfo *Kind,
403                                              const std::string &Str) {
404   startNewLineIfNeeded();
405   MoveToLine(Loc);
406   OS << "#pragma comment(" << Kind->getName();
407 
408   if (!Str.empty()) {
409     OS << ", \"";
410     outputPrintable(OS, Str);
411     OS << '"';
412   }
413 
414   OS << ')';
415   setEmittedDirectiveOnThisLine();
416 }
417 
418 void PrintPPOutputPPCallbacks::PragmaDetectMismatch(SourceLocation Loc,
419                                                     const std::string &Name,
420                                                     const std::string &Value) {
421   startNewLineIfNeeded();
422   MoveToLine(Loc);
423   OS << "#pragma detect_mismatch(\"" << Name << '"';
424   outputPrintable(OS, Name);
425   OS << "\", \"";
426   outputPrintable(OS, Value);
427   OS << "\")";
428   setEmittedDirectiveOnThisLine();
429 }
430 
431 void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
432                                              StringRef Namespace,
433                                              PragmaMessageKind Kind,
434                                              StringRef Str) {
435   startNewLineIfNeeded();
436   MoveToLine(Loc);
437   OS << "#pragma ";
438   if (!Namespace.empty())
439     OS << Namespace << ' ';
440   switch (Kind) {
441     case PMK_Message:
442       OS << "message(\"";
443       break;
444     case PMK_Warning:
445       OS << "warning \"";
446       break;
447     case PMK_Error:
448       OS << "error \"";
449       break;
450   }
451 
452   outputPrintable(OS, Str);
453   OS << '"';
454   if (Kind == PMK_Message)
455     OS << ')';
456   setEmittedDirectiveOnThisLine();
457 }
458 
459 void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
460                                            StringRef DebugType) {
461   startNewLineIfNeeded();
462   MoveToLine(Loc);
463 
464   OS << "#pragma clang __debug ";
465   OS << DebugType;
466 
467   setEmittedDirectiveOnThisLine();
468 }
469 
470 void PrintPPOutputPPCallbacks::
471 PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
472   startNewLineIfNeeded();
473   MoveToLine(Loc);
474   OS << "#pragma " << Namespace << " diagnostic push";
475   setEmittedDirectiveOnThisLine();
476 }
477 
478 void PrintPPOutputPPCallbacks::
479 PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
480   startNewLineIfNeeded();
481   MoveToLine(Loc);
482   OS << "#pragma " << Namespace << " diagnostic pop";
483   setEmittedDirectiveOnThisLine();
484 }
485 
486 void PrintPPOutputPPCallbacks::
487 PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
488                  diag::Mapping Map, StringRef Str) {
489   startNewLineIfNeeded();
490   MoveToLine(Loc);
491   OS << "#pragma " << Namespace << " diagnostic ";
492   switch (Map) {
493   case diag::MAP_WARNING:
494     OS << "warning";
495     break;
496   case diag::MAP_ERROR:
497     OS << "error";
498     break;
499   case diag::MAP_IGNORE:
500     OS << "ignored";
501     break;
502   case diag::MAP_FATAL:
503     OS << "fatal";
504     break;
505   }
506   OS << " \"" << Str << '"';
507   setEmittedDirectiveOnThisLine();
508 }
509 
510 /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
511 /// is called for the first token on each new line.  If this really is the start
512 /// of a new logical line, handle it and return true, otherwise return false.
513 /// This may not be the start of a logical line because the "start of line"
514 /// marker is set for spelling lines, not expansion ones.
515 bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
516   // Figure out what line we went to and insert the appropriate number of
517   // newline characters.
518   if (!MoveToLine(Tok.getLocation()))
519     return false;
520 
521   // Print out space characters so that the first token on a line is
522   // indented for easy reading.
523   unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
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 
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 
569   UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
570     : Prefix(prefix), Callbacks(callbacks) {}
571   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
572                             Token &PragmaTok) {
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       PP.LexUnexpandedToken(PragmaTok);
585     }
586     Callbacks->setEmittedDirectiveOnThisLine();
587   }
588 };
589 } // end anonymous namespace
590 
591 
592 static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
593                                     PrintPPOutputPPCallbacks *Callbacks,
594                                     raw_ostream &OS) {
595   bool DropComments = PP.getLangOpts().TraditionalCPP &&
596                       !PP.getCommentRetentionState();
597 
598   char Buffer[256];
599   Token PrevPrevTok, PrevTok;
600   PrevPrevTok.startToken();
601   PrevTok.startToken();
602   while (1) {
603     if (Callbacks->hasEmittedDirectiveOnThisLine()) {
604       Callbacks->startNewLineIfNeeded();
605       Callbacks->MoveToLine(Tok.getLocation());
606     }
607 
608     // If this token is at the start of a line, emit newlines if needed.
609     if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
610       // done.
611     } else if (Tok.hasLeadingSpace() ||
612                // If we haven't emitted a token on this line yet, PrevTok isn't
613                // useful to look at and no concatenation could happen anyway.
614                (Callbacks->hasEmittedTokensOnThisLine() &&
615                 // Don't print "-" next to "-", it would form "--".
616                 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
617       OS << ' ';
618     }
619 
620     if (DropComments && Tok.is(tok::comment)) {
621       // Skip comments. Normally the preprocessor does not generate
622       // tok::comment nodes at all when not keeping comments, but under
623       // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
624       SourceLocation StartLoc = Tok.getLocation();
625       Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
626     } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
627       OS << II->getName();
628     } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
629                Tok.getLiteralData()) {
630       OS.write(Tok.getLiteralData(), Tok.getLength());
631     } else if (Tok.getLength() < 256) {
632       const char *TokPtr = Buffer;
633       unsigned Len = PP.getSpelling(Tok, TokPtr);
634       OS.write(TokPtr, Len);
635 
636       // Tokens that can contain embedded newlines need to adjust our current
637       // line number.
638       if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
639         Callbacks->HandleNewlinesInToken(TokPtr, Len);
640     } else {
641       std::string S = PP.getSpelling(Tok);
642       OS.write(&S[0], S.size());
643 
644       // Tokens that can contain embedded newlines need to adjust our current
645       // line number.
646       if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
647         Callbacks->HandleNewlinesInToken(&S[0], S.size());
648     }
649     Callbacks->setEmittedTokensOnThisLine();
650 
651     if (Tok.is(tok::eof)) break;
652 
653     PrevPrevTok = PrevTok;
654     PrevTok = Tok;
655     PP.Lex(Tok);
656   }
657 }
658 
659 typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
660 static int MacroIDCompare(const void* a, const void* b) {
661   const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
662   const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
663   return LHS->first->getName().compare(RHS->first->getName());
664 }
665 
666 static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
667   // Ignore unknown pragmas.
668   PP.AddPragmaHandler(new EmptyPragmaHandler());
669 
670   // -dM mode just scans and ignores all tokens in the files, then dumps out
671   // the macro table at the end.
672   PP.EnterMainSourceFile();
673 
674   Token Tok;
675   do PP.Lex(Tok);
676   while (Tok.isNot(tok::eof));
677 
678   SmallVector<id_macro_pair, 128> MacrosByID;
679   for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
680        I != E; ++I) {
681     if (I->first->hasMacroDefinition())
682       MacrosByID.push_back(id_macro_pair(I->first, I->second->getMacroInfo()));
683   }
684   llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
685 
686   for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
687     MacroInfo &MI = *MacrosByID[i].second;
688     // Ignore computed macros like __LINE__ and friends.
689     if (MI.isBuiltinMacro()) continue;
690 
691     PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
692     *OS << '\n';
693   }
694 }
695 
696 /// DoPrintPreprocessedInput - This implements -E mode.
697 ///
698 void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
699                                      const PreprocessorOutputOptions &Opts) {
700   // Show macros with no output is handled specially.
701   if (!Opts.ShowCPP) {
702     assert(Opts.ShowMacros && "Not yet implemented!");
703     DoPrintMacros(PP, OS);
704     return;
705   }
706 
707   // Inform the preprocessor whether we want it to retain comments or not, due
708   // to -C or -CC.
709   PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
710 
711   PrintPPOutputPPCallbacks *Callbacks =
712       new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
713                                    Opts.ShowMacros);
714   PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
715   PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
716   PP.AddPragmaHandler("clang",
717                       new UnknownPragmaHandler("#pragma clang", Callbacks));
718 
719   PP.addPPCallbacks(Callbacks);
720 
721   // After we have configured the preprocessor, enter the main file.
722   PP.EnterMainSourceFile();
723 
724   // Consume all of the tokens that come from the predefines buffer.  Those
725   // should not be emitted into the output and are guaranteed to be at the
726   // start.
727   const SourceManager &SourceMgr = PP.getSourceManager();
728   Token Tok;
729   do {
730     PP.Lex(Tok);
731     if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
732       break;
733 
734     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
735     if (PLoc.isInvalid())
736       break;
737 
738     if (strcmp(PLoc.getFilename(), "<built-in>"))
739       break;
740   } while (true);
741 
742   // Read all the preprocessed tokens, printing them out to the stream.
743   PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
744   *OS << '\n';
745 }
746