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