PrintPreprocessedOutput.cpp 27 KB

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