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