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