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 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::Mapping 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. 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 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); 167 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 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. 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 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. 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 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 EmittedTokensOnThisLine = true; 336 } 337 } 338 339 /// Ident - Handle #ident directives when read by the preprocessor. 340 /// 341 void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) { 342 MoveToLine(Loc); 343 344 OS.write("#ident ", strlen("#ident ")); 345 OS.write(&S[0], S.size()); 346 EmittedTokensOnThisLine = true; 347 } 348 349 /// MacroDefined - This hook is called whenever a macro definition is seen. 350 void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok, 351 const MacroDirective *MD) { 352 const MacroInfo *MI = MD->getMacroInfo(); 353 // Only print out macro definitions in -dD mode. 354 if (!DumpDefines || 355 // Ignore __FILE__ etc. 356 MI->isBuiltinMacro()) return; 357 358 MoveToLine(MI->getDefinitionLoc()); 359 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS); 360 setEmittedDirectiveOnThisLine(); 361 } 362 363 void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok, 364 const MacroDirective *MD) { 365 // Only print out macro definitions in -dD mode. 366 if (!DumpDefines) return; 367 368 MoveToLine(MacroNameTok.getLocation()); 369 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName(); 370 setEmittedDirectiveOnThisLine(); 371 } 372 373 static void outputPrintable(llvm::raw_ostream& OS, 374 const std::string &Str) { 375 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 376 unsigned char Char = Str[i]; 377 if (isPrintable(Char) && Char != '\\' && Char != '"') 378 OS << (char)Char; 379 else // Output anything hard as an octal escape. 380 OS << '\\' 381 << (char)('0'+ ((Char >> 6) & 7)) 382 << (char)('0'+ ((Char >> 3) & 7)) 383 << (char)('0'+ ((Char >> 0) & 7)); 384 } 385 } 386 387 void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc, 388 StringRef Namespace, 389 PragmaMessageKind Kind, 390 StringRef Str) { 391 startNewLineIfNeeded(); 392 MoveToLine(Loc); 393 OS << "#pragma "; 394 if (!Namespace.empty()) 395 OS << Namespace << ' '; 396 switch (Kind) { 397 case PMK_Message: 398 OS << "message(\""; 399 break; 400 case PMK_Warning: 401 OS << "warning \""; 402 break; 403 case PMK_Error: 404 OS << "error \""; 405 break; 406 } 407 408 outputPrintable(OS, Str); 409 OS << '"'; 410 if (Kind == PMK_Message) 411 OS << ')'; 412 setEmittedDirectiveOnThisLine(); 413 } 414 415 void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc, 416 StringRef DebugType) { 417 startNewLineIfNeeded(); 418 MoveToLine(Loc); 419 420 OS << "#pragma clang __debug "; 421 OS << DebugType; 422 423 setEmittedDirectiveOnThisLine(); 424 } 425 426 void PrintPPOutputPPCallbacks:: 427 PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) { 428 startNewLineIfNeeded(); 429 MoveToLine(Loc); 430 OS << "#pragma " << Namespace << " diagnostic push"; 431 setEmittedDirectiveOnThisLine(); 432 } 433 434 void PrintPPOutputPPCallbacks:: 435 PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) { 436 startNewLineIfNeeded(); 437 MoveToLine(Loc); 438 OS << "#pragma " << Namespace << " diagnostic pop"; 439 setEmittedDirectiveOnThisLine(); 440 } 441 442 void PrintPPOutputPPCallbacks:: 443 PragmaDiagnostic(SourceLocation Loc, StringRef Namespace, 444 diag::Mapping Map, StringRef Str) { 445 startNewLineIfNeeded(); 446 MoveToLine(Loc); 447 OS << "#pragma " << Namespace << " diagnostic "; 448 switch (Map) { 449 case diag::MAP_REMARK: 450 OS << "remark"; 451 break; 452 case diag::MAP_WARNING: 453 OS << "warning"; 454 break; 455 case diag::MAP_ERROR: 456 OS << "error"; 457 break; 458 case diag::MAP_IGNORE: 459 OS << "ignored"; 460 break; 461 case diag::MAP_FATAL: 462 OS << "fatal"; 463 break; 464 } 465 OS << " \"" << Str << '"'; 466 setEmittedDirectiveOnThisLine(); 467 } 468 469 void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc, 470 StringRef WarningSpec, 471 ArrayRef<int> Ids) { 472 startNewLineIfNeeded(); 473 MoveToLine(Loc); 474 OS << "#pragma warning(" << WarningSpec << ':'; 475 for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I) 476 OS << ' ' << *I; 477 OS << ')'; 478 setEmittedDirectiveOnThisLine(); 479 } 480 481 void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc, 482 int Level) { 483 startNewLineIfNeeded(); 484 MoveToLine(Loc); 485 OS << "#pragma warning(push"; 486 if (Level >= 0) 487 OS << ", " << Level; 488 OS << ')'; 489 setEmittedDirectiveOnThisLine(); 490 } 491 492 void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) { 493 startNewLineIfNeeded(); 494 MoveToLine(Loc); 495 OS << "#pragma warning(pop)"; 496 setEmittedDirectiveOnThisLine(); 497 } 498 499 /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this 500 /// is called for the first token on each new line. If this really is the start 501 /// of a new logical line, handle it and return true, otherwise return false. 502 /// This may not be the start of a logical line because the "start of line" 503 /// marker is set for spelling lines, not expansion ones. 504 bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) { 505 // Figure out what line we went to and insert the appropriate number of 506 // newline characters. 507 if (!MoveToLine(Tok.getLocation())) 508 return false; 509 510 // Print out space characters so that the first token on a line is 511 // indented for easy reading. 512 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation()); 513 514 // The first token on a line can have a column number of 1, yet still expect 515 // leading white space, if a macro expansion in column 1 starts with an empty 516 // macro argument, or an empty nested macro expansion. In this case, move the 517 // token to column 2. 518 if (ColNo == 1 && Tok.hasLeadingSpace()) 519 ColNo = 2; 520 521 // This hack prevents stuff like: 522 // #define HASH # 523 // HASH define foo bar 524 // From having the # character end up at column 1, which makes it so it 525 // is not handled as a #define next time through the preprocessor if in 526 // -fpreprocessed mode. 527 if (ColNo <= 1 && Tok.is(tok::hash)) 528 OS << ' '; 529 530 // Otherwise, indent the appropriate number of spaces. 531 for (; ColNo > 1; --ColNo) 532 OS << ' '; 533 534 return true; 535 } 536 537 void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr, 538 unsigned Len) { 539 unsigned NumNewlines = 0; 540 for (; Len; --Len, ++TokStr) { 541 if (*TokStr != '\n' && 542 *TokStr != '\r') 543 continue; 544 545 ++NumNewlines; 546 547 // If we have \n\r or \r\n, skip both and count as one line. 548 if (Len != 1 && 549 (TokStr[1] == '\n' || TokStr[1] == '\r') && 550 TokStr[0] != TokStr[1]) 551 ++TokStr, --Len; 552 } 553 554 if (NumNewlines == 0) return; 555 556 CurLine += NumNewlines; 557 } 558 559 560 namespace { 561 struct UnknownPragmaHandler : public PragmaHandler { 562 const char *Prefix; 563 PrintPPOutputPPCallbacks *Callbacks; 564 565 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks) 566 : Prefix(prefix), Callbacks(callbacks) {} 567 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 568 Token &PragmaTok) override { 569 // Figure out what line we went to and insert the appropriate number of 570 // newline characters. 571 Callbacks->startNewLineIfNeeded(); 572 Callbacks->MoveToLine(PragmaTok.getLocation()); 573 Callbacks->OS.write(Prefix, strlen(Prefix)); 574 // Read and print all of the pragma tokens. 575 while (PragmaTok.isNot(tok::eod)) { 576 if (PragmaTok.hasLeadingSpace()) 577 Callbacks->OS << ' '; 578 std::string TokSpell = PP.getSpelling(PragmaTok); 579 Callbacks->OS.write(&TokSpell[0], TokSpell.size()); 580 581 // Expand macros in pragmas with -fms-extensions. The assumption is that 582 // the majority of pragmas in such a file will be Microsoft pragmas. 583 if (PP.getLangOpts().MicrosoftExt) 584 PP.Lex(PragmaTok); 585 else 586 PP.LexUnexpandedToken(PragmaTok); 587 } 588 Callbacks->setEmittedDirectiveOnThisLine(); 589 } 590 }; 591 } // end anonymous namespace 592 593 594 static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok, 595 PrintPPOutputPPCallbacks *Callbacks, 596 raw_ostream &OS) { 597 bool DropComments = PP.getLangOpts().TraditionalCPP && 598 !PP.getCommentRetentionState(); 599 600 char Buffer[256]; 601 Token PrevPrevTok, PrevTok; 602 PrevPrevTok.startToken(); 603 PrevTok.startToken(); 604 while (1) { 605 if (Callbacks->hasEmittedDirectiveOnThisLine()) { 606 Callbacks->startNewLineIfNeeded(); 607 Callbacks->MoveToLine(Tok.getLocation()); 608 } 609 610 // If this token is at the start of a line, emit newlines if needed. 611 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) { 612 // done. 613 } else if (Tok.hasLeadingSpace() || 614 // If we haven't emitted a token on this line yet, PrevTok isn't 615 // useful to look at and no concatenation could happen anyway. 616 (Callbacks->hasEmittedTokensOnThisLine() && 617 // Don't print "-" next to "-", it would form "--". 618 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) { 619 OS << ' '; 620 } 621 622 if (DropComments && Tok.is(tok::comment)) { 623 // Skip comments. Normally the preprocessor does not generate 624 // tok::comment nodes at all when not keeping comments, but under 625 // -traditional-cpp the lexer keeps /all/ whitespace, including comments. 626 SourceLocation StartLoc = Tok.getLocation(); 627 Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength())); 628 } else if (Tok.is(tok::annot_module_include) || 629 Tok.is(tok::annot_module_begin) || 630 Tok.is(tok::annot_module_end)) { 631 // PrintPPOutputPPCallbacks::InclusionDirective handles producing 632 // appropriate output here. Ignore this token entirely. 633 PP.Lex(Tok); 634 continue; 635 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) { 636 OS << II->getName(); 637 } else if (Tok.isLiteral() && !Tok.needsCleaning() && 638 Tok.getLiteralData()) { 639 OS.write(Tok.getLiteralData(), Tok.getLength()); 640 } else if (Tok.getLength() < 256) { 641 const char *TokPtr = Buffer; 642 unsigned Len = PP.getSpelling(Tok, TokPtr); 643 OS.write(TokPtr, Len); 644 645 // Tokens that can contain embedded newlines need to adjust our current 646 // line number. 647 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown) 648 Callbacks->HandleNewlinesInToken(TokPtr, Len); 649 } else { 650 std::string S = PP.getSpelling(Tok); 651 OS.write(&S[0], S.size()); 652 653 // Tokens that can contain embedded newlines need to adjust our current 654 // line number. 655 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown) 656 Callbacks->HandleNewlinesInToken(&S[0], S.size()); 657 } 658 Callbacks->setEmittedTokensOnThisLine(); 659 660 if (Tok.is(tok::eof)) break; 661 662 PrevPrevTok = PrevTok; 663 PrevTok = Tok; 664 PP.Lex(Tok); 665 } 666 } 667 668 typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair; 669 static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) { 670 return LHS->first->getName().compare(RHS->first->getName()); 671 } 672 673 static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) { 674 // Ignore unknown pragmas. 675 PP.IgnorePragmas(); 676 677 // -dM mode just scans and ignores all tokens in the files, then dumps out 678 // the macro table at the end. 679 PP.EnterMainSourceFile(); 680 681 Token Tok; 682 do PP.Lex(Tok); 683 while (Tok.isNot(tok::eof)); 684 685 SmallVector<id_macro_pair, 128> MacrosByID; 686 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end(); 687 I != E; ++I) { 688 if (I->first->hasMacroDefinition()) 689 MacrosByID.push_back(id_macro_pair(I->first, I->second->getMacroInfo())); 690 } 691 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare); 692 693 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) { 694 MacroInfo &MI = *MacrosByID[i].second; 695 // Ignore computed macros like __LINE__ and friends. 696 if (MI.isBuiltinMacro()) continue; 697 698 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS); 699 *OS << '\n'; 700 } 701 } 702 703 /// DoPrintPreprocessedInput - This implements -E mode. 704 /// 705 void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS, 706 const PreprocessorOutputOptions &Opts) { 707 // Show macros with no output is handled specially. 708 if (!Opts.ShowCPP) { 709 assert(Opts.ShowMacros && "Not yet implemented!"); 710 DoPrintMacros(PP, OS); 711 return; 712 } 713 714 // Inform the preprocessor whether we want it to retain comments or not, due 715 // to -C or -CC. 716 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments); 717 718 PrintPPOutputPPCallbacks *Callbacks = 719 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers, 720 Opts.ShowMacros); 721 PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks)); 722 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks)); 723 PP.AddPragmaHandler("clang", 724 new UnknownPragmaHandler("#pragma clang", Callbacks)); 725 726 PP.addPPCallbacks(Callbacks); 727 728 // After we have configured the preprocessor, enter the main file. 729 PP.EnterMainSourceFile(); 730 731 // Consume all of the tokens that come from the predefines buffer. Those 732 // should not be emitted into the output and are guaranteed to be at the 733 // start. 734 const SourceManager &SourceMgr = PP.getSourceManager(); 735 Token Tok; 736 do { 737 PP.Lex(Tok); 738 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID()) 739 break; 740 741 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); 742 if (PLoc.isInvalid()) 743 break; 744 745 if (strcmp(PLoc.getFilename(), "<built-in>")) 746 break; 747 } while (true); 748 749 // Read all the preprocessed tokens, printing them out to the stream. 750 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS); 751 *OS << '\n'; 752 } 753