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