PrintPreprocessedOutput.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  1. //===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This code simply runs the preprocessor on the input file and prints out the
  10. // result. This is the traditional behavior of the -E option.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Frontend/Utils.h"
  14. #include "clang/Basic/CharInfo.h"
  15. #include "clang/Basic/Diagnostic.h"
  16. #include "clang/Basic/SourceManager.h"
  17. #include "clang/Frontend/PreprocessorOutputOptions.h"
  18. #include "clang/Lex/MacroInfo.h"
  19. #include "clang/Lex/PPCallbacks.h"
  20. #include "clang/Lex/Pragma.h"
  21. #include "clang/Lex/Preprocessor.h"
  22. #include "clang/Lex/TokenConcatenation.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/SmallString.h"
  25. #include "llvm/ADT/StringRef.h"
  26. #include "llvm/Support/ErrorHandling.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <cstdio>
  29. using namespace clang;
  30. /// PrintMacroDefinition - Print a macro definition in a form that will be
  31. /// properly accepted back as a definition.
  32. static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
  33. Preprocessor &PP, raw_ostream &OS) {
  34. OS << "#define " << II.getName();
  35. if (MI.isFunctionLike()) {
  36. OS << '(';
  37. if (!MI.param_empty()) {
  38. MacroInfo::param_iterator AI = MI.param_begin(), E = MI.param_end();
  39. for (; AI+1 != E; ++AI) {
  40. OS << (*AI)->getName();
  41. OS << ',';
  42. }
  43. // Last argument.
  44. if ((*AI)->getName() == "__VA_ARGS__")
  45. OS << "...";
  46. else
  47. OS << (*AI)->getName();
  48. }
  49. if (MI.isGNUVarargs())
  50. OS << "..."; // #define foo(x...)
  51. OS << ')';
  52. }
  53. // GCC always emits a space, even if the macro body is empty. However, do not
  54. // want to emit two spaces if the first token has a leading space.
  55. if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
  56. OS << ' ';
  57. SmallString<128> SpellingBuffer;
  58. for (const auto &T : MI.tokens()) {
  59. if (T.hasLeadingSpace())
  60. OS << ' ';
  61. OS << PP.getSpelling(T, SpellingBuffer);
  62. }
  63. }
  64. //===----------------------------------------------------------------------===//
  65. // Preprocessed token printer
  66. //===----------------------------------------------------------------------===//
  67. namespace {
  68. class PrintPPOutputPPCallbacks : public PPCallbacks {
  69. Preprocessor &PP;
  70. SourceManager &SM;
  71. TokenConcatenation ConcatInfo;
  72. public:
  73. raw_ostream &OS;
  74. private:
  75. unsigned CurLine;
  76. bool EmittedTokensOnThisLine;
  77. bool EmittedDirectiveOnThisLine;
  78. SrcMgr::CharacteristicKind FileType;
  79. SmallString<512> CurFilename;
  80. bool Initialized;
  81. bool DisableLineMarkers;
  82. bool DumpDefines;
  83. bool DumpIncludeDirectives;
  84. bool UseLineDirectives;
  85. bool IsFirstFileEntered;
  86. public:
  87. PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os, bool lineMarkers,
  88. bool defines, bool DumpIncludeDirectives,
  89. bool UseLineDirectives)
  90. : PP(pp), SM(PP.getSourceManager()), ConcatInfo(PP), OS(os),
  91. DisableLineMarkers(lineMarkers), DumpDefines(defines),
  92. DumpIncludeDirectives(DumpIncludeDirectives),
  93. UseLineDirectives(UseLineDirectives) {
  94. CurLine = 0;
  95. CurFilename += "<uninit>";
  96. EmittedTokensOnThisLine = false;
  97. EmittedDirectiveOnThisLine = false;
  98. FileType = SrcMgr::C_User;
  99. Initialized = false;
  100. IsFirstFileEntered = false;
  101. }
  102. void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
  103. bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
  104. void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
  105. bool hasEmittedDirectiveOnThisLine() const {
  106. return EmittedDirectiveOnThisLine;
  107. }
  108. bool startNewLineIfNeeded(bool ShouldUpdateCurrentLine = true);
  109. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  110. SrcMgr::CharacteristicKind FileType,
  111. FileID PrevFID) override;
  112. void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
  113. StringRef FileName, bool IsAngled,
  114. CharSourceRange FilenameRange, const FileEntry *File,
  115. StringRef SearchPath, StringRef RelativePath,
  116. const Module *Imported,
  117. SrcMgr::CharacteristicKind FileType) 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. void PragmaExecCharsetPush(SourceLocation Loc, StringRef Str) override;
  131. void PragmaExecCharsetPop(SourceLocation Loc) override;
  132. void PragmaAssumeNonNullBegin(SourceLocation Loc) override;
  133. void PragmaAssumeNonNullEnd(SourceLocation Loc) override;
  134. bool HandleFirstTokOnLine(Token &Tok);
  135. /// Move to the line of the provided source location. This will
  136. /// return true if the output stream required adjustment or if
  137. /// the requested location is on the first line.
  138. bool MoveToLine(SourceLocation Loc) {
  139. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  140. if (PLoc.isInvalid())
  141. return false;
  142. return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
  143. }
  144. bool MoveToLine(unsigned LineNo);
  145. bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
  146. const Token &Tok) {
  147. return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
  148. }
  149. void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
  150. unsigned ExtraLen=0);
  151. bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
  152. void HandleNewlinesInToken(const char *TokStr, unsigned Len);
  153. /// MacroDefined - This hook is called whenever a macro definition is seen.
  154. void MacroDefined(const Token &MacroNameTok,
  155. const MacroDirective *MD) override;
  156. /// MacroUndefined - This hook is called whenever a macro #undef is seen.
  157. void MacroUndefined(const Token &MacroNameTok,
  158. const MacroDefinition &MD,
  159. const MacroDirective *Undef) override;
  160. void BeginModule(const Module *M);
  161. void EndModule(const Module *M);
  162. };
  163. } // end anonymous namespace
  164. void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
  165. const char *Extra,
  166. unsigned ExtraLen) {
  167. startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
  168. // Emit #line directives or GNU line markers depending on what mode we're in.
  169. if (UseLineDirectives) {
  170. OS << "#line" << ' ' << LineNo << ' ' << '"';
  171. OS.write_escaped(CurFilename);
  172. OS << '"';
  173. } else {
  174. OS << '#' << ' ' << LineNo << ' ' << '"';
  175. OS.write_escaped(CurFilename);
  176. OS << '"';
  177. if (ExtraLen)
  178. OS.write(Extra, ExtraLen);
  179. if (FileType == SrcMgr::C_System)
  180. OS.write(" 3", 2);
  181. else if (FileType == SrcMgr::C_ExternCSystem)
  182. OS.write(" 3 4", 4);
  183. }
  184. OS << '\n';
  185. }
  186. /// MoveToLine - Move the output to the source line specified by the location
  187. /// object. We can do this by emitting some number of \n's, or be emitting a
  188. /// #line directive. This returns false if already at the specified line, true
  189. /// if some newlines were emitted.
  190. bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
  191. // If this line is "close enough" to the original line, just print newlines,
  192. // otherwise print a #line directive.
  193. if (LineNo-CurLine <= 8) {
  194. if (LineNo-CurLine == 1)
  195. OS << '\n';
  196. else if (LineNo == CurLine)
  197. return false; // Spelling line moved, but expansion line didn't.
  198. else {
  199. const char *NewLines = "\n\n\n\n\n\n\n\n";
  200. OS.write(NewLines, LineNo-CurLine);
  201. }
  202. } else if (!DisableLineMarkers) {
  203. // Emit a #line or line marker.
  204. WriteLineInfo(LineNo, nullptr, 0);
  205. } else {
  206. // Okay, we're in -P mode, which turns off line markers. However, we still
  207. // need to emit a newline between tokens on different lines.
  208. startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
  209. }
  210. CurLine = LineNo;
  211. return true;
  212. }
  213. bool
  214. PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
  215. if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
  216. OS << '\n';
  217. EmittedTokensOnThisLine = false;
  218. EmittedDirectiveOnThisLine = false;
  219. if (ShouldUpdateCurrentLine)
  220. ++CurLine;
  221. return true;
  222. }
  223. return false;
  224. }
  225. /// FileChanged - Whenever the preprocessor enters or exits a #include file
  226. /// it invokes this handler. Update our conception of the current source
  227. /// position.
  228. void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
  229. FileChangeReason Reason,
  230. SrcMgr::CharacteristicKind NewFileType,
  231. FileID PrevFID) {
  232. // Unless we are exiting a #include, make sure to skip ahead to the line the
  233. // #include directive was at.
  234. SourceManager &SourceMgr = SM;
  235. PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
  236. if (UserLoc.isInvalid())
  237. return;
  238. unsigned NewLine = UserLoc.getLine();
  239. if (Reason == PPCallbacks::EnterFile) {
  240. SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
  241. if (IncludeLoc.isValid())
  242. MoveToLine(IncludeLoc);
  243. } else if (Reason == PPCallbacks::SystemHeaderPragma) {
  244. // GCC emits the # directive for this directive on the line AFTER the
  245. // directive and emits a bunch of spaces that aren't needed. This is because
  246. // otherwise we will emit a line marker for THIS line, which requires an
  247. // extra blank line after the directive to avoid making all following lines
  248. // off by one. We can do better by simply incrementing NewLine here.
  249. NewLine += 1;
  250. }
  251. CurLine = NewLine;
  252. CurFilename.clear();
  253. CurFilename += UserLoc.getFilename();
  254. FileType = NewFileType;
  255. if (DisableLineMarkers) {
  256. startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
  257. return;
  258. }
  259. if (!Initialized) {
  260. WriteLineInfo(CurLine);
  261. Initialized = true;
  262. }
  263. // Do not emit an enter marker for the main file (which we expect is the first
  264. // entered file). This matches gcc, and improves compatibility with some tools
  265. // which track the # line markers as a way to determine when the preprocessed
  266. // output is in the context of the main file.
  267. if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
  268. IsFirstFileEntered = true;
  269. return;
  270. }
  271. switch (Reason) {
  272. case PPCallbacks::EnterFile:
  273. WriteLineInfo(CurLine, " 1", 2);
  274. break;
  275. case PPCallbacks::ExitFile:
  276. WriteLineInfo(CurLine, " 2", 2);
  277. break;
  278. case PPCallbacks::SystemHeaderPragma:
  279. case PPCallbacks::RenameFile:
  280. WriteLineInfo(CurLine);
  281. break;
  282. }
  283. }
  284. void PrintPPOutputPPCallbacks::InclusionDirective(
  285. SourceLocation HashLoc,
  286. const Token &IncludeTok,
  287. StringRef FileName,
  288. bool IsAngled,
  289. CharSourceRange FilenameRange,
  290. const FileEntry *File,
  291. StringRef SearchPath,
  292. StringRef RelativePath,
  293. const Module *Imported,
  294. SrcMgr::CharacteristicKind FileType) {
  295. // In -dI mode, dump #include directives prior to dumping their content or
  296. // interpretation.
  297. if (DumpIncludeDirectives) {
  298. startNewLineIfNeeded();
  299. MoveToLine(HashLoc);
  300. const std::string TokenText = PP.getSpelling(IncludeTok);
  301. assert(!TokenText.empty());
  302. OS << "#" << TokenText << " "
  303. << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
  304. << " /* clang -E -dI */";
  305. setEmittedDirectiveOnThisLine();
  306. startNewLineIfNeeded();
  307. }
  308. // When preprocessing, turn implicit imports into module import pragmas.
  309. if (Imported) {
  310. switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
  311. case tok::pp_include:
  312. case tok::pp_import:
  313. case tok::pp_include_next:
  314. startNewLineIfNeeded();
  315. MoveToLine(HashLoc);
  316. OS << "#pragma clang module import " << Imported->getFullModuleName(true)
  317. << " /* clang -E: implicit import for "
  318. << "#" << PP.getSpelling(IncludeTok) << " "
  319. << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
  320. << " */";
  321. // Since we want a newline after the pragma, but not a #<line>, start a
  322. // new line immediately.
  323. EmittedTokensOnThisLine = true;
  324. startNewLineIfNeeded();
  325. break;
  326. case tok::pp___include_macros:
  327. // #__include_macros has no effect on a user of a preprocessed source
  328. // file; the only effect is on preprocessing.
  329. //
  330. // FIXME: That's not *quite* true: it causes the module in question to
  331. // be loaded, which can affect downstream diagnostics.
  332. break;
  333. default:
  334. llvm_unreachable("unknown include directive kind");
  335. break;
  336. }
  337. }
  338. }
  339. /// Handle entering the scope of a module during a module compilation.
  340. void PrintPPOutputPPCallbacks::BeginModule(const Module *M) {
  341. startNewLineIfNeeded();
  342. OS << "#pragma clang module begin " << M->getFullModuleName(true);
  343. setEmittedDirectiveOnThisLine();
  344. }
  345. /// Handle leaving the scope of a module during a module compilation.
  346. void PrintPPOutputPPCallbacks::EndModule(const Module *M) {
  347. startNewLineIfNeeded();
  348. OS << "#pragma clang module end /*" << M->getFullModuleName(true) << "*/";
  349. setEmittedDirectiveOnThisLine();
  350. }
  351. /// Ident - Handle #ident directives when read by the preprocessor.
  352. ///
  353. void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
  354. MoveToLine(Loc);
  355. OS.write("#ident ", strlen("#ident "));
  356. OS.write(S.begin(), S.size());
  357. EmittedTokensOnThisLine = true;
  358. }
  359. /// MacroDefined - This hook is called whenever a macro definition is seen.
  360. void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
  361. const MacroDirective *MD) {
  362. const MacroInfo *MI = MD->getMacroInfo();
  363. // Only print out macro definitions in -dD mode.
  364. if (!DumpDefines ||
  365. // Ignore __FILE__ etc.
  366. MI->isBuiltinMacro()) return;
  367. MoveToLine(MI->getDefinitionLoc());
  368. PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
  369. setEmittedDirectiveOnThisLine();
  370. }
  371. void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
  372. const MacroDefinition &MD,
  373. const MacroDirective *Undef) {
  374. // Only print out macro definitions in -dD mode.
  375. if (!DumpDefines) return;
  376. MoveToLine(MacroNameTok.getLocation());
  377. OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
  378. setEmittedDirectiveOnThisLine();
  379. }
  380. static void outputPrintable(raw_ostream &OS, StringRef Str) {
  381. for (unsigned char Char : Str) {
  382. if (isPrintable(Char) && Char != '\\' && Char != '"')
  383. OS << (char)Char;
  384. else // Output anything hard as an octal escape.
  385. OS << '\\'
  386. << (char)('0' + ((Char >> 6) & 7))
  387. << (char)('0' + ((Char >> 3) & 7))
  388. << (char)('0' + ((Char >> 0) & 7));
  389. }
  390. }
  391. void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
  392. StringRef Namespace,
  393. PragmaMessageKind Kind,
  394. StringRef Str) {
  395. startNewLineIfNeeded();
  396. MoveToLine(Loc);
  397. OS << "#pragma ";
  398. if (!Namespace.empty())
  399. OS << Namespace << ' ';
  400. switch (Kind) {
  401. case PMK_Message:
  402. OS << "message(\"";
  403. break;
  404. case PMK_Warning:
  405. OS << "warning \"";
  406. break;
  407. case PMK_Error:
  408. OS << "error \"";
  409. break;
  410. }
  411. outputPrintable(OS, Str);
  412. OS << '"';
  413. if (Kind == PMK_Message)
  414. OS << ')';
  415. setEmittedDirectiveOnThisLine();
  416. }
  417. void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
  418. StringRef DebugType) {
  419. startNewLineIfNeeded();
  420. MoveToLine(Loc);
  421. OS << "#pragma clang __debug ";
  422. OS << DebugType;
  423. setEmittedDirectiveOnThisLine();
  424. }
  425. void PrintPPOutputPPCallbacks::
  426. PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
  427. startNewLineIfNeeded();
  428. MoveToLine(Loc);
  429. OS << "#pragma " << Namespace << " diagnostic push";
  430. setEmittedDirectiveOnThisLine();
  431. }
  432. void PrintPPOutputPPCallbacks::
  433. PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
  434. startNewLineIfNeeded();
  435. MoveToLine(Loc);
  436. OS << "#pragma " << Namespace << " diagnostic pop";
  437. setEmittedDirectiveOnThisLine();
  438. }
  439. void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
  440. StringRef Namespace,
  441. diag::Severity Map,
  442. StringRef Str) {
  443. startNewLineIfNeeded();
  444. MoveToLine(Loc);
  445. OS << "#pragma " << Namespace << " diagnostic ";
  446. switch (Map) {
  447. case diag::Severity::Remark:
  448. OS << "remark";
  449. break;
  450. case diag::Severity::Warning:
  451. OS << "warning";
  452. break;
  453. case diag::Severity::Error:
  454. OS << "error";
  455. break;
  456. case diag::Severity::Ignored:
  457. OS << "ignored";
  458. break;
  459. case diag::Severity::Fatal:
  460. OS << "fatal";
  461. break;
  462. }
  463. OS << " \"" << Str << '"';
  464. setEmittedDirectiveOnThisLine();
  465. }
  466. void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
  467. StringRef WarningSpec,
  468. ArrayRef<int> Ids) {
  469. startNewLineIfNeeded();
  470. MoveToLine(Loc);
  471. OS << "#pragma warning(" << WarningSpec << ':';
  472. for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
  473. OS << ' ' << *I;
  474. OS << ')';
  475. setEmittedDirectiveOnThisLine();
  476. }
  477. void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
  478. int Level) {
  479. startNewLineIfNeeded();
  480. MoveToLine(Loc);
  481. OS << "#pragma warning(push";
  482. if (Level >= 0)
  483. OS << ", " << Level;
  484. OS << ')';
  485. setEmittedDirectiveOnThisLine();
  486. }
  487. void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
  488. startNewLineIfNeeded();
  489. MoveToLine(Loc);
  490. OS << "#pragma warning(pop)";
  491. setEmittedDirectiveOnThisLine();
  492. }
  493. void PrintPPOutputPPCallbacks::PragmaExecCharsetPush(SourceLocation Loc,
  494. StringRef Str) {
  495. startNewLineIfNeeded();
  496. MoveToLine(Loc);
  497. OS << "#pragma character_execution_set(push";
  498. if (!Str.empty())
  499. OS << ", " << Str;
  500. OS << ')';
  501. setEmittedDirectiveOnThisLine();
  502. }
  503. void PrintPPOutputPPCallbacks::PragmaExecCharsetPop(SourceLocation Loc) {
  504. startNewLineIfNeeded();
  505. MoveToLine(Loc);
  506. OS << "#pragma character_execution_set(pop)";
  507. setEmittedDirectiveOnThisLine();
  508. }
  509. void PrintPPOutputPPCallbacks::
  510. PragmaAssumeNonNullBegin(SourceLocation Loc) {
  511. startNewLineIfNeeded();
  512. MoveToLine(Loc);
  513. OS << "#pragma clang assume_nonnull begin";
  514. setEmittedDirectiveOnThisLine();
  515. }
  516. void PrintPPOutputPPCallbacks::
  517. PragmaAssumeNonNullEnd(SourceLocation Loc) {
  518. startNewLineIfNeeded();
  519. MoveToLine(Loc);
  520. OS << "#pragma clang assume_nonnull end";
  521. setEmittedDirectiveOnThisLine();
  522. }
  523. /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
  524. /// is called for the first token on each new line. If this really is the start
  525. /// of a new logical line, handle it and return true, otherwise return false.
  526. /// This may not be the start of a logical line because the "start of line"
  527. /// marker is set for spelling lines, not expansion ones.
  528. bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
  529. // Figure out what line we went to and insert the appropriate number of
  530. // newline characters.
  531. if (!MoveToLine(Tok.getLocation()))
  532. return false;
  533. // Print out space characters so that the first token on a line is
  534. // indented for easy reading.
  535. unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
  536. // The first token on a line can have a column number of 1, yet still expect
  537. // leading white space, if a macro expansion in column 1 starts with an empty
  538. // macro argument, or an empty nested macro expansion. In this case, move the
  539. // token to column 2.
  540. if (ColNo == 1 && Tok.hasLeadingSpace())
  541. ColNo = 2;
  542. // This hack prevents stuff like:
  543. // #define HASH #
  544. // HASH define foo bar
  545. // From having the # character end up at column 1, which makes it so it
  546. // is not handled as a #define next time through the preprocessor if in
  547. // -fpreprocessed mode.
  548. if (ColNo <= 1 && Tok.is(tok::hash))
  549. OS << ' ';
  550. // Otherwise, indent the appropriate number of spaces.
  551. for (; ColNo > 1; --ColNo)
  552. OS << ' ';
  553. return true;
  554. }
  555. void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
  556. unsigned Len) {
  557. unsigned NumNewlines = 0;
  558. for (; Len; --Len, ++TokStr) {
  559. if (*TokStr != '\n' &&
  560. *TokStr != '\r')
  561. continue;
  562. ++NumNewlines;
  563. // If we have \n\r or \r\n, skip both and count as one line.
  564. if (Len != 1 &&
  565. (TokStr[1] == '\n' || TokStr[1] == '\r') &&
  566. TokStr[0] != TokStr[1]) {
  567. ++TokStr;
  568. --Len;
  569. }
  570. }
  571. if (NumNewlines == 0) return;
  572. CurLine += NumNewlines;
  573. }
  574. namespace {
  575. struct UnknownPragmaHandler : public PragmaHandler {
  576. const char *Prefix;
  577. PrintPPOutputPPCallbacks *Callbacks;
  578. // Set to true if tokens should be expanded
  579. bool ShouldExpandTokens;
  580. UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
  581. bool RequireTokenExpansion)
  582. : Prefix(prefix), Callbacks(callbacks),
  583. ShouldExpandTokens(RequireTokenExpansion) {}
  584. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  585. Token &PragmaTok) override {
  586. // Figure out what line we went to and insert the appropriate number of
  587. // newline characters.
  588. Callbacks->startNewLineIfNeeded();
  589. Callbacks->MoveToLine(PragmaTok.getLocation());
  590. Callbacks->OS.write(Prefix, strlen(Prefix));
  591. if (ShouldExpandTokens) {
  592. // The first token does not have expanded macros. Expand them, if
  593. // required.
  594. auto Toks = std::make_unique<Token[]>(1);
  595. Toks[0] = PragmaTok;
  596. PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
  597. /*DisableMacroExpansion=*/false,
  598. /*IsReinject=*/false);
  599. PP.Lex(PragmaTok);
  600. }
  601. Token PrevToken;
  602. Token PrevPrevToken;
  603. PrevToken.startToken();
  604. PrevPrevToken.startToken();
  605. // Read and print all of the pragma tokens.
  606. while (PragmaTok.isNot(tok::eod)) {
  607. if (PragmaTok.hasLeadingSpace() ||
  608. Callbacks->AvoidConcat(PrevPrevToken, PrevToken, PragmaTok))
  609. Callbacks->OS << ' ';
  610. std::string TokSpell = PP.getSpelling(PragmaTok);
  611. Callbacks->OS.write(&TokSpell[0], TokSpell.size());
  612. PrevPrevToken = PrevToken;
  613. PrevToken = PragmaTok;
  614. if (ShouldExpandTokens)
  615. PP.Lex(PragmaTok);
  616. else
  617. PP.LexUnexpandedToken(PragmaTok);
  618. }
  619. Callbacks->setEmittedDirectiveOnThisLine();
  620. }
  621. };
  622. } // end anonymous namespace
  623. static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
  624. PrintPPOutputPPCallbacks *Callbacks,
  625. raw_ostream &OS) {
  626. bool DropComments = PP.getLangOpts().TraditionalCPP &&
  627. !PP.getCommentRetentionState();
  628. char Buffer[256];
  629. Token PrevPrevTok, PrevTok;
  630. PrevPrevTok.startToken();
  631. PrevTok.startToken();
  632. while (1) {
  633. if (Callbacks->hasEmittedDirectiveOnThisLine()) {
  634. Callbacks->startNewLineIfNeeded();
  635. Callbacks->MoveToLine(Tok.getLocation());
  636. }
  637. // If this token is at the start of a line, emit newlines if needed.
  638. if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
  639. // done.
  640. } else if (Tok.hasLeadingSpace() ||
  641. // If we haven't emitted a token on this line yet, PrevTok isn't
  642. // useful to look at and no concatenation could happen anyway.
  643. (Callbacks->hasEmittedTokensOnThisLine() &&
  644. // Don't print "-" next to "-", it would form "--".
  645. Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
  646. OS << ' ';
  647. }
  648. if (DropComments && Tok.is(tok::comment)) {
  649. // Skip comments. Normally the preprocessor does not generate
  650. // tok::comment nodes at all when not keeping comments, but under
  651. // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
  652. SourceLocation StartLoc = Tok.getLocation();
  653. Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
  654. } else if (Tok.is(tok::eod)) {
  655. // Don't print end of directive tokens, since they are typically newlines
  656. // that mess up our line tracking. These come from unknown pre-processor
  657. // directives or hash-prefixed comments in standalone assembly files.
  658. PP.Lex(Tok);
  659. continue;
  660. } else if (Tok.is(tok::annot_module_include)) {
  661. // PrintPPOutputPPCallbacks::InclusionDirective handles producing
  662. // appropriate output here. Ignore this token entirely.
  663. PP.Lex(Tok);
  664. continue;
  665. } else if (Tok.is(tok::annot_module_begin)) {
  666. // FIXME: We retrieve this token after the FileChanged callback, and
  667. // retrieve the module_end token before the FileChanged callback, so
  668. // we render this within the file and render the module end outside the
  669. // file, but this is backwards from the token locations: the module_begin
  670. // token is at the include location (outside the file) and the module_end
  671. // token is at the EOF location (within the file).
  672. Callbacks->BeginModule(
  673. reinterpret_cast<Module *>(Tok.getAnnotationValue()));
  674. PP.Lex(Tok);
  675. continue;
  676. } else if (Tok.is(tok::annot_module_end)) {
  677. Callbacks->EndModule(
  678. reinterpret_cast<Module *>(Tok.getAnnotationValue()));
  679. PP.Lex(Tok);
  680. continue;
  681. } else if (Tok.is(tok::annot_header_unit)) {
  682. // This is a header-name that has been (effectively) converted into a
  683. // module-name.
  684. // FIXME: The module name could contain non-identifier module name
  685. // components. We don't have a good way to round-trip those.
  686. Module *M = reinterpret_cast<Module *>(Tok.getAnnotationValue());
  687. std::string Name = M->getFullModuleName();
  688. OS.write(Name.data(), Name.size());
  689. Callbacks->HandleNewlinesInToken(Name.data(), Name.size());
  690. } else if (Tok.isAnnotation()) {
  691. // Ignore annotation tokens created by pragmas - the pragmas themselves
  692. // will be reproduced in the preprocessed output.
  693. PP.Lex(Tok);
  694. continue;
  695. } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
  696. OS << II->getName();
  697. } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
  698. Tok.getLiteralData()) {
  699. OS.write(Tok.getLiteralData(), Tok.getLength());
  700. } else if (Tok.getLength() < llvm::array_lengthof(Buffer)) {
  701. const char *TokPtr = Buffer;
  702. unsigned Len = PP.getSpelling(Tok, TokPtr);
  703. OS.write(TokPtr, Len);
  704. // Tokens that can contain embedded newlines need to adjust our current
  705. // line number.
  706. if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
  707. Callbacks->HandleNewlinesInToken(TokPtr, Len);
  708. } else {
  709. std::string S = PP.getSpelling(Tok);
  710. OS.write(S.data(), S.size());
  711. // Tokens that can contain embedded newlines need to adjust our current
  712. // line number.
  713. if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
  714. Callbacks->HandleNewlinesInToken(S.data(), S.size());
  715. }
  716. Callbacks->setEmittedTokensOnThisLine();
  717. if (Tok.is(tok::eof)) break;
  718. PrevPrevTok = PrevTok;
  719. PrevTok = Tok;
  720. PP.Lex(Tok);
  721. }
  722. }
  723. typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
  724. static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
  725. return LHS->first->getName().compare(RHS->first->getName());
  726. }
  727. static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
  728. // Ignore unknown pragmas.
  729. PP.IgnorePragmas();
  730. // -dM mode just scans and ignores all tokens in the files, then dumps out
  731. // the macro table at the end.
  732. PP.EnterMainSourceFile();
  733. Token Tok;
  734. do PP.Lex(Tok);
  735. while (Tok.isNot(tok::eof));
  736. SmallVector<id_macro_pair, 128> MacrosByID;
  737. for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
  738. I != E; ++I) {
  739. auto *MD = I->second.getLatest();
  740. if (MD && MD->isDefined())
  741. MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
  742. }
  743. llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
  744. for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
  745. MacroInfo &MI = *MacrosByID[i].second;
  746. // Ignore computed macros like __LINE__ and friends.
  747. if (MI.isBuiltinMacro()) continue;
  748. PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
  749. *OS << '\n';
  750. }
  751. }
  752. /// DoPrintPreprocessedInput - This implements -E mode.
  753. ///
  754. void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
  755. const PreprocessorOutputOptions &Opts) {
  756. // Show macros with no output is handled specially.
  757. if (!Opts.ShowCPP) {
  758. assert(Opts.ShowMacros && "Not yet implemented!");
  759. DoPrintMacros(PP, OS);
  760. return;
  761. }
  762. // Inform the preprocessor whether we want it to retain comments or not, due
  763. // to -C or -CC.
  764. PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
  765. PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
  766. PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
  767. Opts.ShowIncludeDirectives, Opts.UseLineDirectives);
  768. // Expand macros in pragmas with -fms-extensions. The assumption is that
  769. // the majority of pragmas in such a file will be Microsoft pragmas.
  770. // Remember the handlers we will add so that we can remove them later.
  771. std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(
  772. new UnknownPragmaHandler(
  773. "#pragma", Callbacks,
  774. /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
  775. std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(
  776. "#pragma GCC", Callbacks,
  777. /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
  778. std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(
  779. "#pragma clang", Callbacks,
  780. /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
  781. PP.AddPragmaHandler(MicrosoftExtHandler.get());
  782. PP.AddPragmaHandler("GCC", GCCHandler.get());
  783. PP.AddPragmaHandler("clang", ClangHandler.get());
  784. // The tokens after pragma omp need to be expanded.
  785. //
  786. // OpenMP [2.1, Directive format]
  787. // Preprocessing tokens following the #pragma omp are subject to macro
  788. // replacement.
  789. std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(
  790. new UnknownPragmaHandler("#pragma omp", Callbacks,
  791. /*RequireTokenExpansion=*/true));
  792. PP.AddPragmaHandler("omp", OpenMPHandler.get());
  793. PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
  794. // After we have configured the preprocessor, enter the main file.
  795. PP.EnterMainSourceFile();
  796. // Consume all of the tokens that come from the predefines buffer. Those
  797. // should not be emitted into the output and are guaranteed to be at the
  798. // start.
  799. const SourceManager &SourceMgr = PP.getSourceManager();
  800. Token Tok;
  801. do {
  802. PP.Lex(Tok);
  803. if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
  804. break;
  805. PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
  806. if (PLoc.isInvalid())
  807. break;
  808. if (strcmp(PLoc.getFilename(), "<built-in>"))
  809. break;
  810. } while (true);
  811. // Read all the preprocessed tokens, printing them out to the stream.
  812. PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
  813. *OS << '\n';
  814. // Remove the handlers we just added to leave the preprocessor in a sane state
  815. // so that it can be reused (for example by a clang::Parser instance).
  816. PP.RemovePragmaHandler(MicrosoftExtHandler.get());
  817. PP.RemovePragmaHandler("GCC", GCCHandler.get());
  818. PP.RemovePragmaHandler("clang", ClangHandler.get());
  819. PP.RemovePragmaHandler("omp", OpenMPHandler.get());
  820. }