PrintPreprocessedOutput.cpp 28 KB

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