PrintPreprocessedOutput.cpp 20 KB

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