PrintPreprocessedOutput.cpp 20 KB

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