PrintPreprocessedOutput.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  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) 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 (UseLineDirectives) {
  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. if (Imported) {
  287. // When preprocessing, turn implicit imports into @imports.
  288. // FIXME: This is a stop-gap until a more comprehensive "preprocessing with
  289. // modules" solution is introduced.
  290. startNewLineIfNeeded();
  291. MoveToLine(HashLoc);
  292. if (PP.getLangOpts().ObjC2) {
  293. OS << "@import " << Imported->getFullModuleName() << ";"
  294. << " /* clang -E: implicit import for \"" << File->getName()
  295. << "\" */";
  296. } else {
  297. const std::string TokenText = PP.getSpelling(IncludeTok);
  298. assert(!TokenText.empty());
  299. OS << "#" << TokenText << " "
  300. << (IsAngled ? '<' : '"')
  301. << FileName
  302. << (IsAngled ? '>' : '"')
  303. << " /* clang -E: implicit import for module "
  304. << Imported->getFullModuleName() << " */";
  305. }
  306. // Since we want a newline after the @import, but not a #<line>, start a new
  307. // line immediately.
  308. EmittedTokensOnThisLine = true;
  309. startNewLineIfNeeded();
  310. } else {
  311. // Not a module import; it's a more vanilla inclusion of some file using one
  312. // of: #include, #import, #include_next, #include_macros.
  313. if (DumpIncludeDirectives) {
  314. startNewLineIfNeeded();
  315. MoveToLine(HashLoc);
  316. const std::string TokenText = PP.getSpelling(IncludeTok);
  317. assert(!TokenText.empty());
  318. OS << "#" << TokenText << " "
  319. << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
  320. << " /* clang -E -dI */";
  321. setEmittedDirectiveOnThisLine();
  322. startNewLineIfNeeded();
  323. }
  324. }
  325. }
  326. /// Ident - Handle #ident directives when read by the preprocessor.
  327. ///
  328. void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
  329. MoveToLine(Loc);
  330. OS.write("#ident ", strlen("#ident "));
  331. OS.write(S.begin(), S.size());
  332. EmittedTokensOnThisLine = true;
  333. }
  334. /// MacroDefined - This hook is called whenever a macro definition is seen.
  335. void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
  336. const MacroDirective *MD) {
  337. const MacroInfo *MI = MD->getMacroInfo();
  338. // Only print out macro definitions in -dD mode.
  339. if (!DumpDefines ||
  340. // Ignore __FILE__ etc.
  341. MI->isBuiltinMacro()) return;
  342. MoveToLine(MI->getDefinitionLoc());
  343. PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
  344. setEmittedDirectiveOnThisLine();
  345. }
  346. void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
  347. const MacroDefinition &MD) {
  348. // Only print out macro definitions in -dD mode.
  349. if (!DumpDefines) return;
  350. MoveToLine(MacroNameTok.getLocation());
  351. OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
  352. setEmittedDirectiveOnThisLine();
  353. }
  354. static void outputPrintable(raw_ostream &OS, StringRef Str) {
  355. for (unsigned char Char : Str) {
  356. if (isPrintable(Char) && Char != '\\' && Char != '"')
  357. OS << (char)Char;
  358. else // Output anything hard as an octal escape.
  359. OS << '\\'
  360. << (char)('0' + ((Char >> 6) & 7))
  361. << (char)('0' + ((Char >> 3) & 7))
  362. << (char)('0' + ((Char >> 0) & 7));
  363. }
  364. }
  365. void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
  366. StringRef Namespace,
  367. PragmaMessageKind Kind,
  368. StringRef Str) {
  369. startNewLineIfNeeded();
  370. MoveToLine(Loc);
  371. OS << "#pragma ";
  372. if (!Namespace.empty())
  373. OS << Namespace << ' ';
  374. switch (Kind) {
  375. case PMK_Message:
  376. OS << "message(\"";
  377. break;
  378. case PMK_Warning:
  379. OS << "warning \"";
  380. break;
  381. case PMK_Error:
  382. OS << "error \"";
  383. break;
  384. }
  385. outputPrintable(OS, Str);
  386. OS << '"';
  387. if (Kind == PMK_Message)
  388. OS << ')';
  389. setEmittedDirectiveOnThisLine();
  390. }
  391. void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
  392. StringRef DebugType) {
  393. startNewLineIfNeeded();
  394. MoveToLine(Loc);
  395. OS << "#pragma clang __debug ";
  396. OS << DebugType;
  397. setEmittedDirectiveOnThisLine();
  398. }
  399. void PrintPPOutputPPCallbacks::
  400. PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
  401. startNewLineIfNeeded();
  402. MoveToLine(Loc);
  403. OS << "#pragma " << Namespace << " diagnostic push";
  404. setEmittedDirectiveOnThisLine();
  405. }
  406. void PrintPPOutputPPCallbacks::
  407. PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
  408. startNewLineIfNeeded();
  409. MoveToLine(Loc);
  410. OS << "#pragma " << Namespace << " diagnostic pop";
  411. setEmittedDirectiveOnThisLine();
  412. }
  413. void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
  414. StringRef Namespace,
  415. diag::Severity Map,
  416. StringRef Str) {
  417. startNewLineIfNeeded();
  418. MoveToLine(Loc);
  419. OS << "#pragma " << Namespace << " diagnostic ";
  420. switch (Map) {
  421. case diag::Severity::Remark:
  422. OS << "remark";
  423. break;
  424. case diag::Severity::Warning:
  425. OS << "warning";
  426. break;
  427. case diag::Severity::Error:
  428. OS << "error";
  429. break;
  430. case diag::Severity::Ignored:
  431. OS << "ignored";
  432. break;
  433. case diag::Severity::Fatal:
  434. OS << "fatal";
  435. break;
  436. }
  437. OS << " \"" << Str << '"';
  438. setEmittedDirectiveOnThisLine();
  439. }
  440. void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
  441. StringRef WarningSpec,
  442. ArrayRef<int> Ids) {
  443. startNewLineIfNeeded();
  444. MoveToLine(Loc);
  445. OS << "#pragma warning(" << WarningSpec << ':';
  446. for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
  447. OS << ' ' << *I;
  448. OS << ')';
  449. setEmittedDirectiveOnThisLine();
  450. }
  451. void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
  452. int Level) {
  453. startNewLineIfNeeded();
  454. MoveToLine(Loc);
  455. OS << "#pragma warning(push";
  456. if (Level >= 0)
  457. OS << ", " << Level;
  458. OS << ')';
  459. setEmittedDirectiveOnThisLine();
  460. }
  461. void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
  462. startNewLineIfNeeded();
  463. MoveToLine(Loc);
  464. OS << "#pragma warning(pop)";
  465. setEmittedDirectiveOnThisLine();
  466. }
  467. /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
  468. /// is called for the first token on each new line. If this really is the start
  469. /// of a new logical line, handle it and return true, otherwise return false.
  470. /// This may not be the start of a logical line because the "start of line"
  471. /// marker is set for spelling lines, not expansion ones.
  472. bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
  473. // Figure out what line we went to and insert the appropriate number of
  474. // newline characters.
  475. if (!MoveToLine(Tok.getLocation()))
  476. return false;
  477. // Print out space characters so that the first token on a line is
  478. // indented for easy reading.
  479. unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
  480. // The first token on a line can have a column number of 1, yet still expect
  481. // leading white space, if a macro expansion in column 1 starts with an empty
  482. // macro argument, or an empty nested macro expansion. In this case, move the
  483. // token to column 2.
  484. if (ColNo == 1 && Tok.hasLeadingSpace())
  485. ColNo = 2;
  486. // This hack prevents stuff like:
  487. // #define HASH #
  488. // HASH define foo bar
  489. // From having the # character end up at column 1, which makes it so it
  490. // is not handled as a #define next time through the preprocessor if in
  491. // -fpreprocessed mode.
  492. if (ColNo <= 1 && Tok.is(tok::hash))
  493. OS << ' ';
  494. // Otherwise, indent the appropriate number of spaces.
  495. for (; ColNo > 1; --ColNo)
  496. OS << ' ';
  497. return true;
  498. }
  499. void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
  500. unsigned Len) {
  501. unsigned NumNewlines = 0;
  502. for (; Len; --Len, ++TokStr) {
  503. if (*TokStr != '\n' &&
  504. *TokStr != '\r')
  505. continue;
  506. ++NumNewlines;
  507. // If we have \n\r or \r\n, skip both and count as one line.
  508. if (Len != 1 &&
  509. (TokStr[1] == '\n' || TokStr[1] == '\r') &&
  510. TokStr[0] != TokStr[1]) {
  511. ++TokStr;
  512. --Len;
  513. }
  514. }
  515. if (NumNewlines == 0) return;
  516. CurLine += NumNewlines;
  517. }
  518. namespace {
  519. struct UnknownPragmaHandler : public PragmaHandler {
  520. const char *Prefix;
  521. PrintPPOutputPPCallbacks *Callbacks;
  522. // Set to true if tokens should be expanded
  523. bool ShouldExpandTokens;
  524. UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
  525. bool RequireTokenExpansion)
  526. : Prefix(prefix), Callbacks(callbacks),
  527. ShouldExpandTokens(RequireTokenExpansion) {}
  528. void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
  529. Token &PragmaTok) override {
  530. // Figure out what line we went to and insert the appropriate number of
  531. // newline characters.
  532. Callbacks->startNewLineIfNeeded();
  533. Callbacks->MoveToLine(PragmaTok.getLocation());
  534. Callbacks->OS.write(Prefix, strlen(Prefix));
  535. if (ShouldExpandTokens) {
  536. // The first token does not have expanded macros. Expand them, if
  537. // required.
  538. auto Toks = llvm::make_unique<Token[]>(1);
  539. Toks[0] = PragmaTok;
  540. PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
  541. /*DisableMacroExpansion=*/false);
  542. PP.Lex(PragmaTok);
  543. }
  544. Token PrevToken;
  545. Token PrevPrevToken;
  546. PrevToken.startToken();
  547. PrevPrevToken.startToken();
  548. // Read and print all of the pragma tokens.
  549. while (PragmaTok.isNot(tok::eod)) {
  550. if (PragmaTok.hasLeadingSpace() ||
  551. Callbacks->AvoidConcat(PrevPrevToken, PrevToken, PragmaTok))
  552. Callbacks->OS << ' ';
  553. std::string TokSpell = PP.getSpelling(PragmaTok);
  554. Callbacks->OS.write(&TokSpell[0], TokSpell.size());
  555. PrevPrevToken = PrevToken;
  556. PrevToken = PragmaTok;
  557. if (ShouldExpandTokens)
  558. PP.Lex(PragmaTok);
  559. else
  560. PP.LexUnexpandedToken(PragmaTok);
  561. }
  562. Callbacks->setEmittedDirectiveOnThisLine();
  563. }
  564. };
  565. } // end anonymous namespace
  566. static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
  567. PrintPPOutputPPCallbacks *Callbacks,
  568. raw_ostream &OS) {
  569. bool DropComments = PP.getLangOpts().TraditionalCPP &&
  570. !PP.getCommentRetentionState();
  571. char Buffer[256];
  572. Token PrevPrevTok, PrevTok;
  573. PrevPrevTok.startToken();
  574. PrevTok.startToken();
  575. while (1) {
  576. if (Callbacks->hasEmittedDirectiveOnThisLine()) {
  577. Callbacks->startNewLineIfNeeded();
  578. Callbacks->MoveToLine(Tok.getLocation());
  579. }
  580. // If this token is at the start of a line, emit newlines if needed.
  581. if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
  582. // done.
  583. } else if (Tok.hasLeadingSpace() ||
  584. // If we haven't emitted a token on this line yet, PrevTok isn't
  585. // useful to look at and no concatenation could happen anyway.
  586. (Callbacks->hasEmittedTokensOnThisLine() &&
  587. // Don't print "-" next to "-", it would form "--".
  588. Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
  589. OS << ' ';
  590. }
  591. if (DropComments && Tok.is(tok::comment)) {
  592. // Skip comments. Normally the preprocessor does not generate
  593. // tok::comment nodes at all when not keeping comments, but under
  594. // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
  595. SourceLocation StartLoc = Tok.getLocation();
  596. Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
  597. } else if (Tok.is(tok::annot_module_include) ||
  598. Tok.is(tok::annot_module_begin) ||
  599. Tok.is(tok::annot_module_end)) {
  600. // PrintPPOutputPPCallbacks::InclusionDirective handles producing
  601. // appropriate output here. Ignore this token entirely.
  602. PP.Lex(Tok);
  603. continue;
  604. } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
  605. OS << II->getName();
  606. } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
  607. Tok.getLiteralData()) {
  608. OS.write(Tok.getLiteralData(), Tok.getLength());
  609. } else if (Tok.getLength() < 256) {
  610. const char *TokPtr = Buffer;
  611. unsigned Len = PP.getSpelling(Tok, TokPtr);
  612. OS.write(TokPtr, Len);
  613. // Tokens that can contain embedded newlines need to adjust our current
  614. // line number.
  615. if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
  616. Callbacks->HandleNewlinesInToken(TokPtr, Len);
  617. } else {
  618. std::string S = PP.getSpelling(Tok);
  619. OS.write(&S[0], S.size());
  620. // Tokens that can contain embedded newlines need to adjust our current
  621. // line number.
  622. if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
  623. Callbacks->HandleNewlinesInToken(&S[0], S.size());
  624. }
  625. Callbacks->setEmittedTokensOnThisLine();
  626. if (Tok.is(tok::eof)) break;
  627. PrevPrevTok = PrevTok;
  628. PrevTok = Tok;
  629. PP.Lex(Tok);
  630. }
  631. }
  632. typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
  633. static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
  634. return LHS->first->getName().compare(RHS->first->getName());
  635. }
  636. static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
  637. // Ignore unknown pragmas.
  638. PP.IgnorePragmas();
  639. // -dM mode just scans and ignores all tokens in the files, then dumps out
  640. // the macro table at the end.
  641. PP.EnterMainSourceFile();
  642. Token Tok;
  643. do PP.Lex(Tok);
  644. while (Tok.isNot(tok::eof));
  645. SmallVector<id_macro_pair, 128> MacrosByID;
  646. for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
  647. I != E; ++I) {
  648. auto *MD = I->second.getLatest();
  649. if (MD && MD->isDefined())
  650. MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
  651. }
  652. llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
  653. for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
  654. MacroInfo &MI = *MacrosByID[i].second;
  655. // Ignore computed macros like __LINE__ and friends.
  656. if (MI.isBuiltinMacro()) continue;
  657. PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
  658. *OS << '\n';
  659. }
  660. }
  661. /// DoPrintPreprocessedInput - This implements -E mode.
  662. ///
  663. void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
  664. const PreprocessorOutputOptions &Opts) {
  665. // Show macros with no output is handled specially.
  666. if (!Opts.ShowCPP) {
  667. assert(Opts.ShowMacros && "Not yet implemented!");
  668. DoPrintMacros(PP, OS);
  669. return;
  670. }
  671. // Inform the preprocessor whether we want it to retain comments or not, due
  672. // to -C or -CC.
  673. PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
  674. PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
  675. PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
  676. Opts.ShowIncludeDirectives, Opts.UseLineDirectives);
  677. // Expand macros in pragmas with -fms-extensions. The assumption is that
  678. // the majority of pragmas in such a file will be Microsoft pragmas.
  679. PP.AddPragmaHandler(new UnknownPragmaHandler(
  680. "#pragma", Callbacks,
  681. /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
  682. PP.AddPragmaHandler(
  683. "GCC", new UnknownPragmaHandler(
  684. "#pragma GCC", Callbacks,
  685. /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
  686. PP.AddPragmaHandler(
  687. "clang", new UnknownPragmaHandler(
  688. "#pragma clang", Callbacks,
  689. /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
  690. // The tokens after pragma omp need to be expanded.
  691. //
  692. // OpenMP [2.1, Directive format]
  693. // Preprocessing tokens following the #pragma omp are subject to macro
  694. // replacement.
  695. PP.AddPragmaHandler("omp",
  696. new UnknownPragmaHandler("#pragma omp", Callbacks,
  697. /*RequireTokenExpansion=*/true));
  698. PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
  699. // After we have configured the preprocessor, enter the main file.
  700. PP.EnterMainSourceFile();
  701. // Consume all of the tokens that come from the predefines buffer. Those
  702. // should not be emitted into the output and are guaranteed to be at the
  703. // start.
  704. const SourceManager &SourceMgr = PP.getSourceManager();
  705. Token Tok;
  706. do {
  707. PP.Lex(Tok);
  708. if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
  709. break;
  710. PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
  711. if (PLoc.isInvalid())
  712. break;
  713. if (strcmp(PLoc.getFilename(), "<built-in>"))
  714. break;
  715. } while (true);
  716. // Read all the preprocessed tokens, printing them out to the stream.
  717. PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
  718. *OS << '\n';
  719. }