PrintPreprocessedOutput.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  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/CharInfo.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/STLExtras.h"
  25. #include "llvm/ADT/SmallString.h"
  26. #include "llvm/ADT/StringRef.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/raw_ostream.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. 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 EmittedDirectiveOnThisLine;
  80. SrcMgr::CharacteristicKind FileType;
  81. SmallString<512> CurFilename;
  82. bool Initialized;
  83. bool DisableLineMarkers;
  84. bool DumpDefines;
  85. bool UseLineDirective;
  86. bool IsFirstFileEntered;
  87. public:
  88. PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os,
  89. bool lineMarkers, bool defines)
  90. : PP(pp), SM(PP.getSourceManager()),
  91. ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
  92. DumpDefines(defines) {
  93. CurLine = 0;
  94. CurFilename += "<uninit>";
  95. EmittedTokensOnThisLine = false;
  96. EmittedDirectiveOnThisLine = false;
  97. FileType = SrcMgr::C_User;
  98. Initialized = false;
  99. IsFirstFileEntered = false;
  100. // If we're in microsoft mode, use normal #line instead of line markers.
  101. UseLineDirective = PP.getLangOpts().MicrosoftExt;
  102. }
  103. void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
  104. bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
  105. void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
  106. bool hasEmittedDirectiveOnThisLine() const {
  107. return EmittedDirectiveOnThisLine;
  108. }
  109. bool startNewLineIfNeeded(bool ShouldUpdateCurrentLine = true);
  110. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  111. SrcMgr::CharacteristicKind FileType,
  112. FileID PrevFID) override;
  113. void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
  114. StringRef FileName, bool IsAngled,
  115. CharSourceRange FilenameRange, const FileEntry *File,
  116. StringRef SearchPath, StringRef RelativePath,
  117. const Module *Imported) override;
  118. void Ident(SourceLocation Loc, const std::string &str) override;
  119. void PragmaMessage(SourceLocation Loc, StringRef Namespace,
  120. PragmaMessageKind Kind, StringRef Str) override;
  121. void PragmaDebug(SourceLocation Loc, StringRef DebugType) override;
  122. void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override;
  123. void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override;
  124. void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
  125. diag::Severity Map, StringRef Str) override;
  126. void PragmaWarning(SourceLocation Loc, StringRef WarningSpec,
  127. ArrayRef<int> Ids) override;
  128. void PragmaWarningPush(SourceLocation Loc, int Level) override;
  129. void PragmaWarningPop(SourceLocation Loc) override;
  130. bool HandleFirstTokOnLine(Token &Tok);
  131. /// Move to the line of the provided source location. This will
  132. /// return true if the output stream required adjustment or if
  133. /// the requested location is on the first line.
  134. bool MoveToLine(SourceLocation Loc) {
  135. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  136. if (PLoc.isInvalid())
  137. return false;
  138. return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
  139. }
  140. bool MoveToLine(unsigned LineNo);
  141. bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
  142. const Token &Tok) {
  143. return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
  144. }
  145. void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
  146. unsigned ExtraLen=0);
  147. bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
  148. void HandleNewlinesInToken(const char *TokStr, unsigned Len);
  149. /// MacroDefined - This hook is called whenever a macro definition is seen.
  150. void MacroDefined(const Token &MacroNameTok,
  151. const MacroDirective *MD) override;
  152. /// MacroUndefined - This hook is called whenever a macro #undef is seen.
  153. void MacroUndefined(const Token &MacroNameTok,
  154. const MacroDirective *MD) override;
  155. };
  156. } // end anonymous namespace
  157. void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
  158. const char *Extra,
  159. unsigned ExtraLen) {
  160. startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
  161. // Emit #line directives or GNU line markers depending on what mode we're in.
  162. if (UseLineDirective) {
  163. OS << "#line" << ' ' << LineNo << ' ' << '"';
  164. OS.write_escaped(CurFilename);
  165. OS << '"';
  166. } else {
  167. OS << '#' << ' ' << LineNo << ' ' << '"';
  168. OS.write_escaped(CurFilename);
  169. OS << '"';
  170. if (ExtraLen)
  171. OS.write(Extra, ExtraLen);
  172. if (FileType == SrcMgr::C_System)
  173. OS.write(" 3", 2);
  174. else if (FileType == SrcMgr::C_ExternCSystem)
  175. OS.write(" 3 4", 4);
  176. }
  177. OS << '\n';
  178. }
  179. /// MoveToLine - Move the output to the source line specified by the location
  180. /// object. We can do this by emitting some number of \n's, or be emitting a
  181. /// #line directive. This returns false if already at the specified line, true
  182. /// if some newlines were emitted.
  183. bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
  184. // If this line is "close enough" to the original line, just print newlines,
  185. // otherwise print a #line directive.
  186. if (LineNo-CurLine <= 8) {
  187. if (LineNo-CurLine == 1)
  188. OS << '\n';
  189. else if (LineNo == CurLine)
  190. return false; // Spelling line moved, but expansion line didn't.
  191. else {
  192. const char *NewLines = "\n\n\n\n\n\n\n\n";
  193. OS.write(NewLines, LineNo-CurLine);
  194. }
  195. } else if (!DisableLineMarkers) {
  196. // Emit a #line or line marker.
  197. WriteLineInfo(LineNo, nullptr, 0);
  198. } else {
  199. // Okay, we're in -P mode, which turns off line markers. However, we still
  200. // need to emit a newline between tokens on different lines.
  201. startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
  202. }
  203. CurLine = LineNo;
  204. return true;
  205. }
  206. bool
  207. PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
  208. if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
  209. OS << '\n';
  210. EmittedTokensOnThisLine = false;
  211. EmittedDirectiveOnThisLine = false;
  212. if (ShouldUpdateCurrentLine)
  213. ++CurLine;
  214. return true;
  215. }
  216. return false;
  217. }
  218. /// FileChanged - Whenever the preprocessor enters or exits a #include file
  219. /// it invokes this handler. Update our conception of the current source
  220. /// position.
  221. void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
  222. FileChangeReason Reason,
  223. SrcMgr::CharacteristicKind NewFileType,
  224. FileID PrevFID) {
  225. // Unless we are exiting a #include, make sure to skip ahead to the line the
  226. // #include directive was at.
  227. SourceManager &SourceMgr = SM;
  228. PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
  229. if (UserLoc.isInvalid())
  230. return;
  231. unsigned NewLine = UserLoc.getLine();
  232. if (Reason == PPCallbacks::EnterFile) {
  233. SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
  234. if (IncludeLoc.isValid())
  235. MoveToLine(IncludeLoc);
  236. } else if (Reason == PPCallbacks::SystemHeaderPragma) {
  237. // GCC emits the # directive for this directive on the line AFTER the
  238. // directive and emits a bunch of spaces that aren't needed. This is because
  239. // otherwise we will emit a line marker for THIS line, which requires an
  240. // extra blank line after the directive to avoid making all following lines
  241. // off by one. We can do better by simply incrementing NewLine here.
  242. NewLine += 1;
  243. }
  244. CurLine = NewLine;
  245. CurFilename.clear();
  246. CurFilename += UserLoc.getFilename();
  247. FileType = NewFileType;
  248. if (DisableLineMarkers) {
  249. startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
  250. return;
  251. }
  252. if (!Initialized) {
  253. WriteLineInfo(CurLine);
  254. Initialized = true;
  255. }
  256. // Do not emit an enter marker for the main file (which we expect is the first
  257. // entered file). This matches gcc, and improves compatibility with some tools
  258. // which track the # line markers as a way to determine when the preprocessed
  259. // output is in the context of the main file.
  260. if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
  261. IsFirstFileEntered = true;
  262. return;
  263. }
  264. switch (Reason) {
  265. case PPCallbacks::EnterFile:
  266. WriteLineInfo(CurLine, " 1", 2);
  267. break;
  268. case PPCallbacks::ExitFile:
  269. WriteLineInfo(CurLine, " 2", 2);
  270. break;
  271. case PPCallbacks::SystemHeaderPragma:
  272. case PPCallbacks::RenameFile:
  273. WriteLineInfo(CurLine);
  274. break;
  275. }
  276. }
  277. void PrintPPOutputPPCallbacks::InclusionDirective(SourceLocation HashLoc,
  278. const Token &IncludeTok,
  279. StringRef FileName,
  280. bool IsAngled,
  281. CharSourceRange FilenameRange,
  282. const FileEntry *File,
  283. StringRef SearchPath,
  284. StringRef RelativePath,
  285. const Module *Imported) {
  286. // When preprocessing, turn implicit imports into @imports.
  287. // FIXME: This is a stop-gap until a more comprehensive "preprocessing with
  288. // modules" solution is introduced.
  289. if (Imported) {
  290. startNewLineIfNeeded();
  291. MoveToLine(HashLoc);
  292. OS << "@import " << Imported->getFullModuleName() << ";"
  293. << " /* clang -E: implicit import for \"" << File->getName() << "\" */";
  294. EmittedTokensOnThisLine = true;
  295. }
  296. }
  297. /// Ident - Handle #ident directives when read by the preprocessor.
  298. ///
  299. void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
  300. MoveToLine(Loc);
  301. OS.write("#ident ", strlen("#ident "));
  302. OS.write(&S[0], S.size());
  303. EmittedTokensOnThisLine = true;
  304. }
  305. /// MacroDefined - This hook is called whenever a macro definition is seen.
  306. void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
  307. const MacroDirective *MD) {
  308. const MacroInfo *MI = MD->getMacroInfo();
  309. // Only print out macro definitions in -dD mode.
  310. if (!DumpDefines ||
  311. // Ignore __FILE__ etc.
  312. MI->isBuiltinMacro()) return;
  313. MoveToLine(MI->getDefinitionLoc());
  314. PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
  315. setEmittedDirectiveOnThisLine();
  316. }
  317. void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
  318. const MacroDirective *MD) {
  319. // Only print out macro definitions in -dD mode.
  320. if (!DumpDefines) return;
  321. MoveToLine(MacroNameTok.getLocation());
  322. OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
  323. setEmittedDirectiveOnThisLine();
  324. }
  325. static void outputPrintable(llvm::raw_ostream& OS,
  326. const std::string &Str) {
  327. for (unsigned i = 0, e = Str.size(); i != e; ++i) {
  328. unsigned char Char = Str[i];
  329. if (isPrintable(Char) && Char != '\\' && Char != '"')
  330. OS << (char)Char;
  331. else // Output anything hard as an octal escape.
  332. OS << '\\'
  333. << (char)('0'+ ((Char >> 6) & 7))
  334. << (char)('0'+ ((Char >> 3) & 7))
  335. << (char)('0'+ ((Char >> 0) & 7));
  336. }
  337. }
  338. void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
  339. StringRef Namespace,
  340. PragmaMessageKind Kind,
  341. StringRef Str) {
  342. startNewLineIfNeeded();
  343. MoveToLine(Loc);
  344. OS << "#pragma ";
  345. if (!Namespace.empty())
  346. OS << Namespace << ' ';
  347. switch (Kind) {
  348. case PMK_Message:
  349. OS << "message(\"";
  350. break;
  351. case PMK_Warning:
  352. OS << "warning \"";
  353. break;
  354. case PMK_Error:
  355. OS << "error \"";
  356. break;
  357. }
  358. outputPrintable(OS, Str);
  359. OS << '"';
  360. if (Kind == PMK_Message)
  361. OS << ')';
  362. setEmittedDirectiveOnThisLine();
  363. }
  364. void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
  365. StringRef DebugType) {
  366. startNewLineIfNeeded();
  367. MoveToLine(Loc);
  368. OS << "#pragma clang __debug ";
  369. OS << DebugType;
  370. setEmittedDirectiveOnThisLine();
  371. }
  372. void PrintPPOutputPPCallbacks::
  373. PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
  374. startNewLineIfNeeded();
  375. MoveToLine(Loc);
  376. OS << "#pragma " << Namespace << " diagnostic push";
  377. setEmittedDirectiveOnThisLine();
  378. }
  379. void PrintPPOutputPPCallbacks::
  380. PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
  381. startNewLineIfNeeded();
  382. MoveToLine(Loc);
  383. OS << "#pragma " << Namespace << " diagnostic pop";
  384. setEmittedDirectiveOnThisLine();
  385. }
  386. void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
  387. StringRef Namespace,
  388. diag::Severity Map,
  389. StringRef Str) {
  390. startNewLineIfNeeded();
  391. MoveToLine(Loc);
  392. OS << "#pragma " << Namespace << " diagnostic ";
  393. switch (Map) {
  394. case diag::MAP_REMARK:
  395. OS << "remark";
  396. break;
  397. case diag::MAP_WARNING:
  398. OS << "warning";
  399. break;
  400. case diag::MAP_ERROR:
  401. OS << "error";
  402. break;
  403. case diag::MAP_IGNORE:
  404. OS << "ignored";
  405. break;
  406. case diag::MAP_FATAL:
  407. OS << "fatal";
  408. break;
  409. }
  410. OS << " \"" << Str << '"';
  411. setEmittedDirectiveOnThisLine();
  412. }
  413. void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
  414. StringRef WarningSpec,
  415. ArrayRef<int> Ids) {
  416. startNewLineIfNeeded();
  417. MoveToLine(Loc);
  418. OS << "#pragma warning(" << WarningSpec << ':';
  419. for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
  420. OS << ' ' << *I;
  421. OS << ')';
  422. setEmittedDirectiveOnThisLine();
  423. }
  424. void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
  425. int Level) {
  426. startNewLineIfNeeded();
  427. MoveToLine(Loc);
  428. OS << "#pragma warning(push";
  429. if (Level >= 0)
  430. OS << ", " << Level;
  431. OS << ')';
  432. setEmittedDirectiveOnThisLine();
  433. }
  434. void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
  435. startNewLineIfNeeded();
  436. MoveToLine(Loc);
  437. OS << "#pragma warning(pop)";
  438. setEmittedDirectiveOnThisLine();
  439. }
  440. /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
  441. /// is called for the first token on each new line. If this really is the start
  442. /// of a new logical line, handle it and return true, otherwise return false.
  443. /// This may not be the start of a logical line because the "start of line"
  444. /// marker is set for spelling lines, not expansion ones.
  445. bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
  446. // Figure out what line we went to and insert the appropriate number of
  447. // newline characters.
  448. if (!MoveToLine(Tok.getLocation()))
  449. return false;
  450. // Print out space characters so that the first token on a line is
  451. // indented for easy reading.
  452. unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
  453. // The first token on a line can have a column number of 1, yet still expect
  454. // leading white space, if a macro expansion in column 1 starts with an empty
  455. // macro argument, or an empty nested macro expansion. In this case, move the
  456. // token to column 2.
  457. if (ColNo == 1 && Tok.hasLeadingSpace())
  458. ColNo = 2;
  459. // This hack prevents stuff like:
  460. // #define HASH #
  461. // HASH define foo bar
  462. // From having the # character end up at column 1, which makes it so it
  463. // is not handled as a #define next time through the preprocessor if in
  464. // -fpreprocessed mode.
  465. if (ColNo <= 1 && Tok.is(tok::hash))
  466. OS << ' ';
  467. // Otherwise, indent the appropriate number of spaces.
  468. for (; ColNo > 1; --ColNo)
  469. OS << ' ';
  470. return true;
  471. }
  472. void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
  473. unsigned Len) {
  474. unsigned NumNewlines = 0;
  475. for (; Len; --Len, ++TokStr) {
  476. if (*TokStr != '\n' &&
  477. *TokStr != '\r')
  478. continue;
  479. ++NumNewlines;
  480. // If we have \n\r or \r\n, skip both and count as one line.
  481. if (Len != 1 &&
  482. (TokStr[1] == '\n' || TokStr[1] == '\r') &&
  483. TokStr[0] != TokStr[1])
  484. ++TokStr, --Len;
  485. }
  486. if (NumNewlines == 0) return;
  487. CurLine += NumNewlines;
  488. }
  489. namespace {
  490. struct UnknownPragmaHandler : public PragmaHandler {
  491. const char *Prefix;
  492. PrintPPOutputPPCallbacks *Callbacks;
  493. UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
  494. : Prefix(prefix), Callbacks(callbacks) {}
  495. void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
  496. Token &PragmaTok) override {
  497. // Figure out what line we went to and insert the appropriate number of
  498. // newline characters.
  499. Callbacks->startNewLineIfNeeded();
  500. Callbacks->MoveToLine(PragmaTok.getLocation());
  501. Callbacks->OS.write(Prefix, strlen(Prefix));
  502. // Read and print all of the pragma tokens.
  503. while (PragmaTok.isNot(tok::eod)) {
  504. if (PragmaTok.hasLeadingSpace())
  505. Callbacks->OS << ' ';
  506. std::string TokSpell = PP.getSpelling(PragmaTok);
  507. Callbacks->OS.write(&TokSpell[0], TokSpell.size());
  508. // Expand macros in pragmas with -fms-extensions. The assumption is that
  509. // the majority of pragmas in such a file will be Microsoft pragmas.
  510. if (PP.getLangOpts().MicrosoftExt)
  511. PP.Lex(PragmaTok);
  512. else
  513. PP.LexUnexpandedToken(PragmaTok);
  514. }
  515. Callbacks->setEmittedDirectiveOnThisLine();
  516. }
  517. };
  518. } // end anonymous namespace
  519. static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
  520. PrintPPOutputPPCallbacks *Callbacks,
  521. raw_ostream &OS) {
  522. bool DropComments = PP.getLangOpts().TraditionalCPP &&
  523. !PP.getCommentRetentionState();
  524. char Buffer[256];
  525. Token PrevPrevTok, PrevTok;
  526. PrevPrevTok.startToken();
  527. PrevTok.startToken();
  528. while (1) {
  529. if (Callbacks->hasEmittedDirectiveOnThisLine()) {
  530. Callbacks->startNewLineIfNeeded();
  531. Callbacks->MoveToLine(Tok.getLocation());
  532. }
  533. // If this token is at the start of a line, emit newlines if needed.
  534. if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
  535. // done.
  536. } else if (Tok.hasLeadingSpace() ||
  537. // If we haven't emitted a token on this line yet, PrevTok isn't
  538. // useful to look at and no concatenation could happen anyway.
  539. (Callbacks->hasEmittedTokensOnThisLine() &&
  540. // Don't print "-" next to "-", it would form "--".
  541. Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
  542. OS << ' ';
  543. }
  544. if (DropComments && Tok.is(tok::comment)) {
  545. // Skip comments. Normally the preprocessor does not generate
  546. // tok::comment nodes at all when not keeping comments, but under
  547. // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
  548. SourceLocation StartLoc = Tok.getLocation();
  549. Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
  550. } else if (Tok.is(tok::annot_module_include) ||
  551. Tok.is(tok::annot_module_begin) ||
  552. Tok.is(tok::annot_module_end)) {
  553. // PrintPPOutputPPCallbacks::InclusionDirective handles producing
  554. // appropriate output here. Ignore this token entirely.
  555. PP.Lex(Tok);
  556. continue;
  557. } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
  558. OS << II->getName();
  559. } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
  560. Tok.getLiteralData()) {
  561. OS.write(Tok.getLiteralData(), Tok.getLength());
  562. } else if (Tok.getLength() < 256) {
  563. const char *TokPtr = Buffer;
  564. unsigned Len = PP.getSpelling(Tok, TokPtr);
  565. OS.write(TokPtr, Len);
  566. // Tokens that can contain embedded newlines need to adjust our current
  567. // line number.
  568. if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
  569. Callbacks->HandleNewlinesInToken(TokPtr, Len);
  570. } else {
  571. std::string S = PP.getSpelling(Tok);
  572. OS.write(&S[0], S.size());
  573. // Tokens that can contain embedded newlines need to adjust our current
  574. // line number.
  575. if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
  576. Callbacks->HandleNewlinesInToken(&S[0], S.size());
  577. }
  578. Callbacks->setEmittedTokensOnThisLine();
  579. if (Tok.is(tok::eof)) break;
  580. PrevPrevTok = PrevTok;
  581. PrevTok = Tok;
  582. PP.Lex(Tok);
  583. }
  584. }
  585. typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
  586. static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
  587. return LHS->first->getName().compare(RHS->first->getName());
  588. }
  589. static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
  590. // Ignore unknown pragmas.
  591. PP.IgnorePragmas();
  592. // -dM mode just scans and ignores all tokens in the files, then dumps out
  593. // the macro table at the end.
  594. PP.EnterMainSourceFile();
  595. Token Tok;
  596. do PP.Lex(Tok);
  597. while (Tok.isNot(tok::eof));
  598. SmallVector<id_macro_pair, 128> MacrosByID;
  599. for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
  600. I != E; ++I) {
  601. if (I->first->hasMacroDefinition())
  602. MacrosByID.push_back(id_macro_pair(I->first, I->second->getMacroInfo()));
  603. }
  604. llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
  605. for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
  606. MacroInfo &MI = *MacrosByID[i].second;
  607. // Ignore computed macros like __LINE__ and friends.
  608. if (MI.isBuiltinMacro()) continue;
  609. PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
  610. *OS << '\n';
  611. }
  612. }
  613. /// DoPrintPreprocessedInput - This implements -E mode.
  614. ///
  615. void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
  616. const PreprocessorOutputOptions &Opts) {
  617. // Show macros with no output is handled specially.
  618. if (!Opts.ShowCPP) {
  619. assert(Opts.ShowMacros && "Not yet implemented!");
  620. DoPrintMacros(PP, OS);
  621. return;
  622. }
  623. // Inform the preprocessor whether we want it to retain comments or not, due
  624. // to -C or -CC.
  625. PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
  626. PrintPPOutputPPCallbacks *Callbacks =
  627. new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
  628. Opts.ShowMacros);
  629. PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
  630. PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
  631. PP.AddPragmaHandler("clang",
  632. new UnknownPragmaHandler("#pragma clang", Callbacks));
  633. PP.addPPCallbacks(Callbacks);
  634. // After we have configured the preprocessor, enter the main file.
  635. PP.EnterMainSourceFile();
  636. // Consume all of the tokens that come from the predefines buffer. Those
  637. // should not be emitted into the output and are guaranteed to be at the
  638. // start.
  639. const SourceManager &SourceMgr = PP.getSourceManager();
  640. Token Tok;
  641. do {
  642. PP.Lex(Tok);
  643. if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
  644. break;
  645. PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
  646. if (PLoc.isInvalid())
  647. break;
  648. if (strcmp(PLoc.getFilename(), "<built-in>"))
  649. break;
  650. } while (true);
  651. // Read all the preprocessed tokens, printing them out to the stream.
  652. PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
  653. *OS << '\n';
  654. }