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_REMARK: 463 OS << "remark"; 464 break; 465 case diag::MAP_WARNING: 466 OS << "warning"; 467 break; 468 case diag::MAP_ERROR: 469 OS << "error"; 470 break; 471 case diag::MAP_IGNORE: 472 OS << "ignored"; 473 break; 474 case diag::MAP_FATAL: 475 OS << "fatal"; 476 break; 477 } 478 OS << " \"" << Str << '"'; 479 setEmittedDirectiveOnThisLine(); 480 } 481 482 void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc, 483 StringRef WarningSpec, 484 ArrayRef<int> Ids) { 485 startNewLineIfNeeded(); 486 MoveToLine(Loc); 487 OS << "#pragma warning(" << WarningSpec << ':'; 488 for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I) 489 OS << ' ' << *I; 490 OS << ')'; 491 setEmittedDirectiveOnThisLine(); 492 } 493 494 void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc, 495 int Level) { 496 startNewLineIfNeeded(); 497 MoveToLine(Loc); 498 OS << "#pragma warning(push"; 499 if (Level >= 0) 500 OS << ", " << Level; 501 OS << ')'; 502 setEmittedDirectiveOnThisLine(); 503 } 504 505 void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) { 506 startNewLineIfNeeded(); 507 MoveToLine(Loc); 508 OS << "#pragma warning(pop)"; 509 setEmittedDirectiveOnThisLine(); 510 } 511 512 /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this 513 /// is called for the first token on each new line. If this really is the start 514 /// of a new logical line, handle it and return true, otherwise return false. 515 /// This may not be the start of a logical line because the "start of line" 516 /// marker is set for spelling lines, not expansion ones. 517 bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) { 518 // Figure out what line we went to and insert the appropriate number of 519 // newline characters. 520 if (!MoveToLine(Tok.getLocation())) 521 return false; 522 523 // Print out space characters so that the first token on a line is 524 // indented for easy reading. 525 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation()); 526 527 // The first token on a line can have a column number of 1, yet still expect 528 // leading white space, if a macro expansion in column 1 starts with an empty 529 // macro argument, or an empty nested macro expansion. In this case, move the 530 // token to column 2. 531 if (ColNo == 1 && Tok.hasLeadingSpace()) 532 ColNo = 2; 533 534 // This hack prevents stuff like: 535 // #define HASH # 536 // HASH define foo bar 537 // From having the # character end up at column 1, which makes it so it 538 // is not handled as a #define next time through the preprocessor if in 539 // -fpreprocessed mode. 540 if (ColNo <= 1 && Tok.is(tok::hash)) 541 OS << ' '; 542 543 // Otherwise, indent the appropriate number of spaces. 544 for (; ColNo > 1; --ColNo) 545 OS << ' '; 546 547 return true; 548 } 549 550 void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr, 551 unsigned Len) { 552 unsigned NumNewlines = 0; 553 for (; Len; --Len, ++TokStr) { 554 if (*TokStr != '\n' && 555 *TokStr != '\r') 556 continue; 557 558 ++NumNewlines; 559 560 // If we have \n\r or \r\n, skip both and count as one line. 561 if (Len != 1 && 562 (TokStr[1] == '\n' || TokStr[1] == '\r') && 563 TokStr[0] != TokStr[1]) 564 ++TokStr, --Len; 565 } 566 567 if (NumNewlines == 0) return; 568 569 CurLine += NumNewlines; 570 } 571 572 573 namespace { 574 struct UnknownPragmaHandler : public PragmaHandler { 575 const char *Prefix; 576 PrintPPOutputPPCallbacks *Callbacks; 577 578 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks) 579 : Prefix(prefix), Callbacks(callbacks) {} 580 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 581 Token &PragmaTok) { 582 // Figure out what line we went to and insert the appropriate number of 583 // newline characters. 584 Callbacks->startNewLineIfNeeded(); 585 Callbacks->MoveToLine(PragmaTok.getLocation()); 586 Callbacks->OS.write(Prefix, strlen(Prefix)); 587 // Read and print all of the pragma tokens. 588 while (PragmaTok.isNot(tok::eod)) { 589 if (PragmaTok.hasLeadingSpace()) 590 Callbacks->OS << ' '; 591 std::string TokSpell = PP.getSpelling(PragmaTok); 592 Callbacks->OS.write(&TokSpell[0], TokSpell.size()); 593 594 // Expand macros in pragmas with -fms-extensions. The assumption is that 595 // the majority of pragmas in such a file will be Microsoft pragmas. 596 if (PP.getLangOpts().MicrosoftExt) 597 PP.Lex(PragmaTok); 598 else 599 PP.LexUnexpandedToken(PragmaTok); 600 } 601 Callbacks->setEmittedDirectiveOnThisLine(); 602 } 603 }; 604 } // end anonymous namespace 605 606 607 static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok, 608 PrintPPOutputPPCallbacks *Callbacks, 609 raw_ostream &OS) { 610 bool DropComments = PP.getLangOpts().TraditionalCPP && 611 !PP.getCommentRetentionState(); 612 613 char Buffer[256]; 614 Token PrevPrevTok, PrevTok; 615 PrevPrevTok.startToken(); 616 PrevTok.startToken(); 617 while (1) { 618 if (Callbacks->hasEmittedDirectiveOnThisLine()) { 619 Callbacks->startNewLineIfNeeded(); 620 Callbacks->MoveToLine(Tok.getLocation()); 621 } 622 623 // If this token is at the start of a line, emit newlines if needed. 624 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) { 625 // done. 626 } else if (Tok.hasLeadingSpace() || 627 // If we haven't emitted a token on this line yet, PrevTok isn't 628 // useful to look at and no concatenation could happen anyway. 629 (Callbacks->hasEmittedTokensOnThisLine() && 630 // Don't print "-" next to "-", it would form "--". 631 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) { 632 OS << ' '; 633 } 634 635 if (DropComments && Tok.is(tok::comment)) { 636 // Skip comments. Normally the preprocessor does not generate 637 // tok::comment nodes at all when not keeping comments, but under 638 // -traditional-cpp the lexer keeps /all/ whitespace, including comments. 639 SourceLocation StartLoc = Tok.getLocation(); 640 Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength())); 641 } else if (Tok.is(tok::annot_module_include) || 642 Tok.is(tok::annot_module_begin) || 643 Tok.is(tok::annot_module_end)) { 644 // PrintPPOutputPPCallbacks::InclusionDirective handles producing 645 // appropriate output here. Ignore this token entirely. 646 PP.Lex(Tok); 647 continue; 648 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) { 649 OS << II->getName(); 650 } else if (Tok.isLiteral() && !Tok.needsCleaning() && 651 Tok.getLiteralData()) { 652 OS.write(Tok.getLiteralData(), Tok.getLength()); 653 } else if (Tok.getLength() < 256) { 654 const char *TokPtr = Buffer; 655 unsigned Len = PP.getSpelling(Tok, TokPtr); 656 OS.write(TokPtr, Len); 657 658 // Tokens that can contain embedded newlines need to adjust our current 659 // line number. 660 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown) 661 Callbacks->HandleNewlinesInToken(TokPtr, Len); 662 } else { 663 std::string S = PP.getSpelling(Tok); 664 OS.write(&S[0], S.size()); 665 666 // Tokens that can contain embedded newlines need to adjust our current 667 // line number. 668 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown) 669 Callbacks->HandleNewlinesInToken(&S[0], S.size()); 670 } 671 Callbacks->setEmittedTokensOnThisLine(); 672 673 if (Tok.is(tok::eof)) break; 674 675 PrevPrevTok = PrevTok; 676 PrevTok = Tok; 677 PP.Lex(Tok); 678 } 679 } 680 681 typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair; 682 static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) { 683 return LHS->first->getName().compare(RHS->first->getName()); 684 } 685 686 static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) { 687 // Ignore unknown pragmas. 688 PP.AddPragmaHandler(new EmptyPragmaHandler()); 689 690 // -dM mode just scans and ignores all tokens in the files, then dumps out 691 // the macro table at the end. 692 PP.EnterMainSourceFile(); 693 694 Token Tok; 695 do PP.Lex(Tok); 696 while (Tok.isNot(tok::eof)); 697 698 SmallVector<id_macro_pair, 128> MacrosByID; 699 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end(); 700 I != E; ++I) { 701 if (I->first->hasMacroDefinition()) 702 MacrosByID.push_back(id_macro_pair(I->first, I->second->getMacroInfo())); 703 } 704 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare); 705 706 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) { 707 MacroInfo &MI = *MacrosByID[i].second; 708 // Ignore computed macros like __LINE__ and friends. 709 if (MI.isBuiltinMacro()) continue; 710 711 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS); 712 *OS << '\n'; 713 } 714 } 715 716 /// DoPrintPreprocessedInput - This implements -E mode. 717 /// 718 void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS, 719 const PreprocessorOutputOptions &Opts) { 720 // Show macros with no output is handled specially. 721 if (!Opts.ShowCPP) { 722 assert(Opts.ShowMacros && "Not yet implemented!"); 723 DoPrintMacros(PP, OS); 724 return; 725 } 726 727 // Inform the preprocessor whether we want it to retain comments or not, due 728 // to -C or -CC. 729 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments); 730 731 PrintPPOutputPPCallbacks *Callbacks = 732 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers, 733 Opts.ShowMacros); 734 PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks)); 735 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks)); 736 PP.AddPragmaHandler("clang", 737 new UnknownPragmaHandler("#pragma clang", Callbacks)); 738 739 PP.addPPCallbacks(Callbacks); 740 741 // After we have configured the preprocessor, enter the main file. 742 PP.EnterMainSourceFile(); 743 744 // Consume all of the tokens that come from the predefines buffer. Those 745 // should not be emitted into the output and are guaranteed to be at the 746 // start. 747 const SourceManager &SourceMgr = PP.getSourceManager(); 748 Token Tok; 749 do { 750 PP.Lex(Tok); 751 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID()) 752 break; 753 754 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); 755 if (PLoc.isInvalid()) 756 break; 757 758 if (strcmp(PLoc.getFilename(), "<built-in>")) 759 break; 760 } while (true); 761 762 // Read all the preprocessed tokens, printing them out to the stream. 763 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS); 764 *OS << '\n'; 765 } 766