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