PrintPreprocessedOutput.cpp revision df721408f54f87a790fb986dfd64984472a1f892
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/Diagnostic.h" 17#include "clang/Basic/SourceManager.h" 18#include "clang/Frontend/PreprocessorOutputOptions.h" 19#include "clang/Lex/MacroInfo.h" 20#include "clang/Lex/PPCallbacks.h" 21#include "clang/Lex/Pragma.h" 22#include "clang/Lex/Preprocessor.h" 23#include "clang/Lex/TokenConcatenation.h" 24#include "llvm/ADT/SmallString.h" 25#include "llvm/ADT/STLExtras.h" 26#include "llvm/Config/config.h" 27#include "llvm/Support/raw_ostream.h" 28#include <cstdio> 29using namespace clang; 30 31/// PrintMacroDefinition - Print a macro definition in a form that will be 32/// properly accepted back as a definition. 33static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI, 34 Preprocessor &PP, llvm::raw_ostream &OS) { 35 OS << "#define " << II.getName(); 36 37 if (MI.isFunctionLike()) { 38 OS << '('; 39 if (!MI.arg_empty()) { 40 MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end(); 41 for (; AI+1 != E; ++AI) { 42 OS << (*AI)->getName(); 43 OS << ','; 44 } 45 46 // Last argument. 47 if ((*AI)->getName() == "__VA_ARGS__") 48 OS << "..."; 49 else 50 OS << (*AI)->getName(); 51 } 52 53 if (MI.isGNUVarargs()) 54 OS << "..."; // #define foo(x...) 55 56 OS << ')'; 57 } 58 59 // GCC always emits a space, even if the macro body is empty. However, do not 60 // want to emit two spaces if the first token has a leading space. 61 if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace()) 62 OS << ' '; 63 64 llvm::SmallString<128> SpellingBuffer; 65 for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end(); 66 I != E; ++I) { 67 if (I->hasLeadingSpace()) 68 OS << ' '; 69 70 OS << PP.getSpelling(*I, SpellingBuffer); 71 } 72} 73 74//===----------------------------------------------------------------------===// 75// Preprocessed token printer 76//===----------------------------------------------------------------------===// 77 78namespace { 79class PrintPPOutputPPCallbacks : public PPCallbacks { 80 Preprocessor &PP; 81 SourceManager &SM; 82 TokenConcatenation ConcatInfo; 83public: 84 llvm::raw_ostream &OS; 85private: 86 unsigned CurLine; 87 bool EmittedTokensOnThisLine; 88 bool EmittedMacroOnThisLine; 89 SrcMgr::CharacteristicKind FileType; 90 llvm::SmallString<512> CurFilename; 91 bool Initialized; 92 bool DisableLineMarkers; 93 bool DumpDefines; 94 bool UseLineDirective; 95public: 96 PrintPPOutputPPCallbacks(Preprocessor &pp, llvm::raw_ostream &os, 97 bool lineMarkers, bool defines) 98 : PP(pp), SM(PP.getSourceManager()), 99 ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers), 100 DumpDefines(defines) { 101 CurLine = 0; 102 CurFilename += "<uninit>"; 103 EmittedTokensOnThisLine = false; 104 EmittedMacroOnThisLine = false; 105 FileType = SrcMgr::C_User; 106 Initialized = false; 107 108 // If we're in microsoft mode, use normal #line instead of line markers. 109 UseLineDirective = PP.getLangOptions().Microsoft; 110 } 111 112 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; } 113 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; } 114 115 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason, 116 SrcMgr::CharacteristicKind FileType); 117 virtual void Ident(SourceLocation Loc, const std::string &str); 118 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind, 119 const std::string &Str); 120 121 122 bool HandleFirstTokOnLine(Token &Tok); 123 bool MoveToLine(SourceLocation Loc) { 124 return MoveToLine(SM.getPresumedLoc(Loc).getLine()); 125 } 126 bool MoveToLine(unsigned LineNo); 127 128 bool AvoidConcat(const Token &PrevTok, const Token &Tok) { 129 return ConcatInfo.AvoidConcat(PrevTok, Tok); 130 } 131 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0); 132 133 void HandleNewlinesInToken(const char *TokStr, unsigned Len); 134 135 /// MacroDefined - This hook is called whenever a macro definition is seen. 136 void MacroDefined(const IdentifierInfo *II, const MacroInfo *MI); 137 138}; 139} // end anonymous namespace 140 141void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo, 142 const char *Extra, 143 unsigned ExtraLen) { 144 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) { 145 OS << '\n'; 146 EmittedTokensOnThisLine = false; 147 EmittedMacroOnThisLine = false; 148 } 149 150 // Emit #line directives or GNU line markers depending on what mode we're in. 151 if (UseLineDirective) { 152 OS << "#line" << ' ' << LineNo << ' ' << '"'; 153 OS.write(&CurFilename[0], CurFilename.size()); 154 OS << '"'; 155 } else { 156 OS << '#' << ' ' << LineNo << ' ' << '"'; 157 OS.write(&CurFilename[0], CurFilename.size()); 158 OS << '"'; 159 160 if (ExtraLen) 161 OS.write(Extra, ExtraLen); 162 163 if (FileType == SrcMgr::C_System) 164 OS.write(" 3", 2); 165 else if (FileType == SrcMgr::C_ExternCSystem) 166 OS.write(" 3 4", 4); 167 } 168 OS << '\n'; 169} 170 171/// MoveToLine - Move the output to the source line specified by the location 172/// object. We can do this by emitting some number of \n's, or be emitting a 173/// #line directive. This returns false if already at the specified line, true 174/// if some newlines were emitted. 175bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) { 176 if (DisableLineMarkers) { 177 if (LineNo == CurLine) return false; 178 179 CurLine = LineNo; 180 181 if (!EmittedTokensOnThisLine && !EmittedMacroOnThisLine) 182 return true; 183 184 OS << '\n'; 185 EmittedTokensOnThisLine = false; 186 EmittedMacroOnThisLine = false; 187 return true; 188 } 189 190 // If this line is "close enough" to the original line, just print newlines, 191 // otherwise print a #line directive. 192 if (LineNo-CurLine <= 8) { 193 if (LineNo-CurLine == 1) 194 OS << '\n'; 195 else if (LineNo == CurLine) 196 return false; // Spelling line moved, but instantiation line didn't. 197 else { 198 const char *NewLines = "\n\n\n\n\n\n\n\n"; 199 OS.write(NewLines, LineNo-CurLine); 200 } 201 } else { 202 WriteLineInfo(LineNo, 0, 0); 203 } 204 205 CurLine = LineNo; 206 return true; 207} 208 209 210/// FileChanged - Whenever the preprocessor enters or exits a #include file 211/// it invokes this handler. Update our conception of the current source 212/// position. 213void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc, 214 FileChangeReason Reason, 215 SrcMgr::CharacteristicKind NewFileType) { 216 // Unless we are exiting a #include, make sure to skip ahead to the line the 217 // #include directive was at. 218 SourceManager &SourceMgr = SM; 219 220 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc); 221 unsigned NewLine = UserLoc.getLine()+1; 222 223 if (Reason == PPCallbacks::EnterFile) { 224 SourceLocation IncludeLoc = SourceMgr.getPresumedLoc(Loc).getIncludeLoc(); 225 if (IncludeLoc.isValid()) 226 MoveToLine(IncludeLoc); 227 } else if (Reason == PPCallbacks::SystemHeaderPragma) { 228 MoveToLine(NewLine); 229 230 // TODO GCC emits the # directive for this directive on the line AFTER the 231 // directive and emits a bunch of spaces that aren't needed. Emulate this 232 // strange behavior. 233 } 234 235 CurLine = NewLine; 236 237 if (DisableLineMarkers) return; 238 239 CurFilename.clear(); 240 CurFilename += UserLoc.getFilename(); 241 Lexer::Stringify(CurFilename); 242 FileType = NewFileType; 243 244 if (!Initialized) { 245 WriteLineInfo(CurLine); 246 Initialized = true; 247 } 248 249 switch (Reason) { 250 case PPCallbacks::EnterFile: 251 WriteLineInfo(CurLine, " 1", 2); 252 break; 253 case PPCallbacks::ExitFile: 254 WriteLineInfo(CurLine, " 2", 2); 255 break; 256 case PPCallbacks::SystemHeaderPragma: 257 case PPCallbacks::RenameFile: 258 WriteLineInfo(CurLine); 259 break; 260 } 261} 262 263/// Ident - Handle #ident directives when read by the preprocessor. 264/// 265void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) { 266 MoveToLine(Loc); 267 268 OS.write("#ident ", strlen("#ident ")); 269 OS.write(&S[0], S.size()); 270 EmittedTokensOnThisLine = true; 271} 272 273/// MacroDefined - This hook is called whenever a macro definition is seen. 274void PrintPPOutputPPCallbacks::MacroDefined(const IdentifierInfo *II, 275 const MacroInfo *MI) { 276 // Only print out macro definitions in -dD mode. 277 if (!DumpDefines || 278 // Ignore __FILE__ etc. 279 MI->isBuiltinMacro()) return; 280 281 MoveToLine(MI->getDefinitionLoc()); 282 PrintMacroDefinition(*II, *MI, PP, OS); 283 EmittedMacroOnThisLine = true; 284} 285 286 287void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc, 288 const IdentifierInfo *Kind, 289 const std::string &Str) { 290 MoveToLine(Loc); 291 OS << "#pragma comment(" << Kind->getName(); 292 293 if (!Str.empty()) { 294 OS << ", \""; 295 296 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 297 unsigned char Char = Str[i]; 298 if (isprint(Char) && Char != '\\' && Char != '"') 299 OS << (char)Char; 300 else // Output anything hard as an octal escape. 301 OS << '\\' 302 << (char)('0'+ ((Char >> 6) & 7)) 303 << (char)('0'+ ((Char >> 3) & 7)) 304 << (char)('0'+ ((Char >> 0) & 7)); 305 } 306 OS << '"'; 307 } 308 309 OS << ')'; 310 EmittedTokensOnThisLine = true; 311} 312 313 314/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this 315/// is called for the first token on each new line. If this really is the start 316/// of a new logical line, handle it and return true, otherwise return false. 317/// This may not be the start of a logical line because the "start of line" 318/// marker is set for spelling lines, not instantiation ones. 319bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) { 320 // Figure out what line we went to and insert the appropriate number of 321 // newline characters. 322 if (!MoveToLine(Tok.getLocation())) 323 return false; 324 325 // Print out space characters so that the first token on a line is 326 // indented for easy reading. 327 unsigned ColNo = SM.getInstantiationColumnNumber(Tok.getLocation()); 328 329 // This hack prevents stuff like: 330 // #define HASH # 331 // HASH define foo bar 332 // From having the # character end up at column 1, which makes it so it 333 // is not handled as a #define next time through the preprocessor if in 334 // -fpreprocessed mode. 335 if (ColNo <= 1 && Tok.is(tok::hash)) 336 OS << ' '; 337 338 // Otherwise, indent the appropriate number of spaces. 339 for (; ColNo > 1; --ColNo) 340 OS << ' '; 341 342 return true; 343} 344 345void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr, 346 unsigned Len) { 347 unsigned NumNewlines = 0; 348 for (; Len; --Len, ++TokStr) { 349 if (*TokStr != '\n' && 350 *TokStr != '\r') 351 continue; 352 353 ++NumNewlines; 354 355 // If we have \n\r or \r\n, skip both and count as one line. 356 if (Len != 1 && 357 (TokStr[1] == '\n' || TokStr[1] == '\r') && 358 TokStr[0] != TokStr[1]) 359 ++TokStr, --Len; 360 } 361 362 if (NumNewlines == 0) return; 363 364 CurLine += NumNewlines; 365} 366 367 368namespace { 369struct UnknownPragmaHandler : public PragmaHandler { 370 const char *Prefix; 371 PrintPPOutputPPCallbacks *Callbacks; 372 373 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks) 374 : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {} 375 virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) { 376 // Figure out what line we went to and insert the appropriate number of 377 // newline characters. 378 Callbacks->MoveToLine(PragmaTok.getLocation()); 379 Callbacks->OS.write(Prefix, strlen(Prefix)); 380 381 // Read and print all of the pragma tokens. 382 while (PragmaTok.isNot(tok::eom)) { 383 if (PragmaTok.hasLeadingSpace()) 384 Callbacks->OS << ' '; 385 std::string TokSpell = PP.getSpelling(PragmaTok); 386 Callbacks->OS.write(&TokSpell[0], TokSpell.size()); 387 PP.LexUnexpandedToken(PragmaTok); 388 } 389 Callbacks->OS << '\n'; 390 } 391}; 392} // end anonymous namespace 393 394 395static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok, 396 PrintPPOutputPPCallbacks *Callbacks, 397 llvm::raw_ostream &OS) { 398 char Buffer[256]; 399 Token PrevTok; 400 while (1) { 401 402 // If this token is at the start of a line, emit newlines if needed. 403 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) { 404 // done. 405 } else if (Tok.hasLeadingSpace() || 406 // If we haven't emitted a token on this line yet, PrevTok isn't 407 // useful to look at and no concatenation could happen anyway. 408 (Callbacks->hasEmittedTokensOnThisLine() && 409 // Don't print "-" next to "-", it would form "--". 410 Callbacks->AvoidConcat(PrevTok, Tok))) { 411 OS << ' '; 412 } 413 414 if (IdentifierInfo *II = Tok.getIdentifierInfo()) { 415 OS << II->getName(); 416 } else if (Tok.isLiteral() && !Tok.needsCleaning() && 417 Tok.getLiteralData()) { 418 OS.write(Tok.getLiteralData(), Tok.getLength()); 419 } else if (Tok.getLength() < 256) { 420 const char *TokPtr = Buffer; 421 unsigned Len = PP.getSpelling(Tok, TokPtr); 422 OS.write(TokPtr, Len); 423 424 // Tokens that can contain embedded newlines need to adjust our current 425 // line number. 426 if (Tok.getKind() == tok::comment) 427 Callbacks->HandleNewlinesInToken(TokPtr, Len); 428 } else { 429 std::string S = PP.getSpelling(Tok); 430 OS.write(&S[0], S.size()); 431 432 // Tokens that can contain embedded newlines need to adjust our current 433 // line number. 434 if (Tok.getKind() == tok::comment) 435 Callbacks->HandleNewlinesInToken(&S[0], S.size()); 436 } 437 Callbacks->SetEmittedTokensOnThisLine(); 438 439 if (Tok.is(tok::eof)) break; 440 441 PrevTok = Tok; 442 PP.Lex(Tok); 443 } 444} 445 446typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair; 447static int MacroIDCompare(const void* a, const void* b) { 448 const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a); 449 const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b); 450 return LHS->first->getName().compare(RHS->first->getName()); 451} 452 453static void DoPrintMacros(Preprocessor &PP, llvm::raw_ostream *OS) { 454 // -dM mode just scans and ignores all tokens in the files, then dumps out 455 // the macro table at the end. 456 if (PP.EnterMainSourceFile()) 457 return; 458 459 Token Tok; 460 do PP.Lex(Tok); 461 while (Tok.isNot(tok::eof)); 462 463 llvm::SmallVector<id_macro_pair, 128> 464 MacrosByID(PP.macro_begin(), PP.macro_end()); 465 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare); 466 467 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) { 468 MacroInfo &MI = *MacrosByID[i].second; 469 // Ignore computed macros like __LINE__ and friends. 470 if (MI.isBuiltinMacro()) continue; 471 472 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS); 473 *OS << '\n'; 474 } 475} 476 477/// DoPrintPreprocessedInput - This implements -E mode. 478/// 479void clang::DoPrintPreprocessedInput(Preprocessor &PP, llvm::raw_ostream *OS, 480 const PreprocessorOutputOptions &Opts) { 481 // Show macros with no output is handled specially. 482 if (!Opts.ShowCPP) { 483 assert(Opts.ShowMacros && "Not yet implemented!"); 484 DoPrintMacros(PP, OS); 485 return; 486 } 487 488 // Inform the preprocessor whether we want it to retain comments or not, due 489 // to -C or -CC. 490 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments); 491 492 OS->SetBufferSize(64*1024); 493 494 PrintPPOutputPPCallbacks *Callbacks = 495 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers, 496 Opts.ShowMacros); 497 PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks)); 498 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC", 499 Callbacks)); 500 501 PP.addPPCallbacks(Callbacks); 502 503 // After we have configured the preprocessor, enter the main file. 504 if (PP.EnterMainSourceFile()) 505 return; 506 507 // Consume all of the tokens that come from the predefines buffer. Those 508 // should not be emitted into the output and are guaranteed to be at the 509 // start. 510 const SourceManager &SourceMgr = PP.getSourceManager(); 511 Token Tok; 512 do PP.Lex(Tok); 513 while (Tok.isNot(tok::eof) && Tok.getLocation().isFileID() && 514 !strcmp(SourceMgr.getPresumedLoc(Tok.getLocation()).getFilename(), 515 "<built-in>")); 516 517 // Read all the preprocessed tokens, printing them out to the stream. 518 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS); 519 *OS << '\n'; 520} 521 522