PrintPreprocessedOutput.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  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. bool MinimizeWhitespace;
  87. Token PrevTok;
  88. Token PrevPrevTok;
  89. public:
  90. PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os, bool lineMarkers,
  91. bool defines, bool DumpIncludeDirectives,
  92. bool UseLineDirectives, bool MinimizeWhitespace)
  93. : PP(pp), SM(PP.getSourceManager()), ConcatInfo(PP), OS(os),
  94. DisableLineMarkers(lineMarkers), DumpDefines(defines),
  95. DumpIncludeDirectives(DumpIncludeDirectives),
  96. UseLineDirectives(UseLineDirectives),
  97. MinimizeWhitespace(MinimizeWhitespace) {
  98. CurLine = 0;
  99. CurFilename += "<uninit>";
  100. EmittedTokensOnThisLine = false;
  101. EmittedDirectiveOnThisLine = false;
  102. FileType = SrcMgr::C_User;
  103. Initialized = false;
  104. IsFirstFileEntered = false;
  105. PrevTok.startToken();
  106. PrevPrevTok.startToken();
  107. }
  108. bool isMinimizeWhitespace() const { return MinimizeWhitespace; }
  109. void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
  110. bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
  111. void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
  112. bool hasEmittedDirectiveOnThisLine() const {
  113. return EmittedDirectiveOnThisLine;
  114. }
  115. /// Ensure that the output stream position is at the beginning of a new line
  116. /// and inserts one if it does not. It is intended to ensure that directives
  117. /// inserted by the directives not from the input source (such as #line) are
  118. /// in the first column. To insert newlines that represent the input, use
  119. /// MoveToLine(/*...*/, /*RequireStartOfLine=*/true).
  120. void startNewLineIfNeeded();
  121. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  122. SrcMgr::CharacteristicKind FileType,
  123. FileID PrevFID) override;
  124. void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
  125. StringRef FileName, bool IsAngled,
  126. CharSourceRange FilenameRange, const FileEntry *File,
  127. StringRef SearchPath, StringRef RelativePath,
  128. const Module *Imported,
  129. SrcMgr::CharacteristicKind FileType) override;
  130. void Ident(SourceLocation Loc, StringRef str) override;
  131. void PragmaMessage(SourceLocation Loc, StringRef Namespace,
  132. PragmaMessageKind Kind, StringRef Str) override;
  133. void PragmaDebug(SourceLocation Loc, StringRef DebugType) override;
  134. void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override;
  135. void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override;
  136. void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
  137. diag::Severity Map, StringRef Str) override;
  138. void PragmaWarning(SourceLocation Loc, PragmaWarningSpecifier WarningSpec,
  139. ArrayRef<int> Ids) override;
  140. void PragmaWarningPush(SourceLocation Loc, int Level) override;
  141. void PragmaWarningPop(SourceLocation Loc) override;
  142. void PragmaExecCharsetPush(SourceLocation Loc, StringRef Str) override;
  143. void PragmaExecCharsetPop(SourceLocation Loc) override;
  144. void PragmaAssumeNonNullBegin(SourceLocation Loc) override;
  145. void PragmaAssumeNonNullEnd(SourceLocation Loc) override;
  146. /// Insert whitespace before emitting the next token.
  147. ///
  148. /// @param Tok Next token to be emitted.
  149. /// @param RequireSpace Ensure at least one whitespace is emitted. Useful
  150. /// if non-tokens have been emitted to the stream.
  151. /// @param RequireSameLine Never emit newlines. Useful when semantics depend
  152. /// on being on the same line, such as directives.
  153. void HandleWhitespaceBeforeTok(const Token &Tok, bool RequireSpace,
  154. bool RequireSameLine);
  155. /// Move to the line of the provided source location. This will
  156. /// return true if a newline was inserted or if
  157. /// the requested location is the first token on the first line.
  158. /// In these cases the next output will be the first column on the line and
  159. /// make it possible to insert indention. The newline was inserted
  160. /// implicitly when at the beginning of the file.
  161. ///
  162. /// @param Tok Token where to move to.
  163. /// @param RequireStartOfLine Whether the next line depends on being in the
  164. /// first column, such as a directive.
  165. ///
  166. /// @return Whether column adjustments are necessary.
  167. bool MoveToLine(const Token &Tok, bool RequireStartOfLine) {
  168. PresumedLoc PLoc = SM.getPresumedLoc(Tok.getLocation());
  169. unsigned TargetLine = PLoc.isValid() ? PLoc.getLine() : CurLine;
  170. bool IsFirstInFile = Tok.isAtStartOfLine() && PLoc.getLine() == 1;
  171. return MoveToLine(TargetLine, RequireStartOfLine) || IsFirstInFile;
  172. }
  173. /// Move to the line of the provided source location. Returns true if a new
  174. /// line was inserted.
  175. bool MoveToLine(SourceLocation Loc, bool RequireStartOfLine) {
  176. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  177. unsigned TargetLine = PLoc.isValid() ? PLoc.getLine() : CurLine;
  178. return MoveToLine(TargetLine, RequireStartOfLine);
  179. }
  180. bool MoveToLine(unsigned LineNo, bool RequireStartOfLine);
  181. bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
  182. const Token &Tok) {
  183. return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
  184. }
  185. void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
  186. unsigned ExtraLen=0);
  187. bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
  188. void HandleNewlinesInToken(const char *TokStr, unsigned Len);
  189. /// MacroDefined - This hook is called whenever a macro definition is seen.
  190. void MacroDefined(const Token &MacroNameTok,
  191. const MacroDirective *MD) override;
  192. /// MacroUndefined - This hook is called whenever a macro #undef is seen.
  193. void MacroUndefined(const Token &MacroNameTok,
  194. const MacroDefinition &MD,
  195. const MacroDirective *Undef) override;
  196. void BeginModule(const Module *M);
  197. void EndModule(const Module *M);
  198. };
  199. } // end anonymous namespace
  200. void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
  201. const char *Extra,
  202. unsigned ExtraLen) {
  203. startNewLineIfNeeded();
  204. // Emit #line directives or GNU line markers depending on what mode we're in.
  205. if (UseLineDirectives) {
  206. OS << "#line" << ' ' << LineNo << ' ' << '"';
  207. OS.write_escaped(CurFilename);
  208. OS << '"';
  209. } else {
  210. OS << '#' << ' ' << LineNo << ' ' << '"';
  211. OS.write_escaped(CurFilename);
  212. OS << '"';
  213. if (ExtraLen)
  214. OS.write(Extra, ExtraLen);
  215. if (FileType == SrcMgr::C_System)
  216. OS.write(" 3", 2);
  217. else if (FileType == SrcMgr::C_ExternCSystem)
  218. OS.write(" 3 4", 4);
  219. }
  220. OS << '\n';
  221. }
  222. /// MoveToLine - Move the output to the source line specified by the location
  223. /// object. We can do this by emitting some number of \n's, or be emitting a
  224. /// #line directive. This returns false if already at the specified line, true
  225. /// if some newlines were emitted.
  226. bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo,
  227. bool RequireStartOfLine) {
  228. // If it is required to start a new line or finish the current, insert
  229. // vertical whitespace now and take it into account when moving to the
  230. // expected line.
  231. bool StartedNewLine = false;
  232. if ((RequireStartOfLine && EmittedTokensOnThisLine) ||
  233. EmittedDirectiveOnThisLine) {
  234. OS << '\n';
  235. StartedNewLine = true;
  236. CurLine += 1;
  237. EmittedTokensOnThisLine = false;
  238. EmittedDirectiveOnThisLine = false;
  239. }
  240. // If this line is "close enough" to the original line, just print newlines,
  241. // otherwise print a #line directive.
  242. if (CurLine == LineNo) {
  243. // Nothing to do if we are already on the correct line.
  244. } else if (MinimizeWhitespace && DisableLineMarkers) {
  245. // With -E -P -fminimize-whitespace, don't emit anything if not necessary.
  246. } else if (!StartedNewLine && LineNo - CurLine == 1) {
  247. // Printing a single line has priority over printing a #line directive, even
  248. // when minimizing whitespace which otherwise would print #line directives
  249. // for every single line.
  250. OS << '\n';
  251. StartedNewLine = true;
  252. } else if (!DisableLineMarkers) {
  253. if (LineNo - CurLine <= 8) {
  254. const char *NewLines = "\n\n\n\n\n\n\n\n";
  255. OS.write(NewLines, LineNo - CurLine);
  256. } else {
  257. // Emit a #line or line marker.
  258. WriteLineInfo(LineNo, nullptr, 0);
  259. }
  260. StartedNewLine = true;
  261. } else if (EmittedTokensOnThisLine) {
  262. // If we are not on the correct line and don't need to be line-correct,
  263. // at least ensure we start on a new line.
  264. OS << '\n';
  265. StartedNewLine = true;
  266. }
  267. if (StartedNewLine) {
  268. EmittedTokensOnThisLine = false;
  269. EmittedDirectiveOnThisLine = false;
  270. }
  271. CurLine = LineNo;
  272. return StartedNewLine;
  273. }
  274. void PrintPPOutputPPCallbacks::startNewLineIfNeeded() {
  275. if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
  276. OS << '\n';
  277. EmittedTokensOnThisLine = false;
  278. EmittedDirectiveOnThisLine = false;
  279. }
  280. }
  281. /// FileChanged - Whenever the preprocessor enters or exits a #include file
  282. /// it invokes this handler. Update our conception of the current source
  283. /// position.
  284. void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
  285. FileChangeReason Reason,
  286. SrcMgr::CharacteristicKind NewFileType,
  287. FileID PrevFID) {
  288. // Unless we are exiting a #include, make sure to skip ahead to the line the
  289. // #include directive was at.
  290. SourceManager &SourceMgr = SM;
  291. PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
  292. if (UserLoc.isInvalid())
  293. return;
  294. unsigned NewLine = UserLoc.getLine();
  295. if (Reason == PPCallbacks::EnterFile) {
  296. SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
  297. if (IncludeLoc.isValid())
  298. MoveToLine(IncludeLoc, /*RequireStartOfLine=*/false);
  299. } else if (Reason == PPCallbacks::SystemHeaderPragma) {
  300. // GCC emits the # directive for this directive on the line AFTER the
  301. // directive and emits a bunch of spaces that aren't needed. This is because
  302. // otherwise we will emit a line marker for THIS line, which requires an
  303. // extra blank line after the directive to avoid making all following lines
  304. // off by one. We can do better by simply incrementing NewLine here.
  305. NewLine += 1;
  306. }
  307. CurLine = NewLine;
  308. CurFilename.clear();
  309. CurFilename += UserLoc.getFilename();
  310. FileType = NewFileType;
  311. if (DisableLineMarkers) {
  312. if (!MinimizeWhitespace)
  313. startNewLineIfNeeded();
  314. return;
  315. }
  316. if (!Initialized) {
  317. WriteLineInfo(CurLine);
  318. Initialized = true;
  319. }
  320. // Do not emit an enter marker for the main file (which we expect is the first
  321. // entered file). This matches gcc, and improves compatibility with some tools
  322. // which track the # line markers as a way to determine when the preprocessed
  323. // output is in the context of the main file.
  324. if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
  325. IsFirstFileEntered = true;
  326. return;
  327. }
  328. switch (Reason) {
  329. case PPCallbacks::EnterFile:
  330. WriteLineInfo(CurLine, " 1", 2);
  331. break;
  332. case PPCallbacks::ExitFile:
  333. WriteLineInfo(CurLine, " 2", 2);
  334. break;
  335. case PPCallbacks::SystemHeaderPragma:
  336. case PPCallbacks::RenameFile:
  337. WriteLineInfo(CurLine);
  338. break;
  339. }
  340. }
  341. void PrintPPOutputPPCallbacks::InclusionDirective(
  342. SourceLocation HashLoc,
  343. const Token &IncludeTok,
  344. StringRef FileName,
  345. bool IsAngled,
  346. CharSourceRange FilenameRange,
  347. const FileEntry *File,
  348. StringRef SearchPath,
  349. StringRef RelativePath,
  350. const Module *Imported,
  351. SrcMgr::CharacteristicKind FileType) {
  352. // In -dI mode, dump #include directives prior to dumping their content or
  353. // interpretation.
  354. if (DumpIncludeDirectives) {
  355. MoveToLine(HashLoc, /*RequireStartOfLine=*/true);
  356. const std::string TokenText = PP.getSpelling(IncludeTok);
  357. assert(!TokenText.empty());
  358. OS << "#" << TokenText << " "
  359. << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
  360. << " /* clang -E -dI */";
  361. setEmittedDirectiveOnThisLine();
  362. }
  363. // When preprocessing, turn implicit imports into module import pragmas.
  364. if (Imported) {
  365. switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
  366. case tok::pp_include:
  367. case tok::pp_import:
  368. case tok::pp_include_next:
  369. MoveToLine(HashLoc, /*RequireStartOfLine=*/true);
  370. OS << "#pragma clang module import " << Imported->getFullModuleName(true)
  371. << " /* clang -E: implicit import for "
  372. << "#" << PP.getSpelling(IncludeTok) << " "
  373. << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
  374. << " */";
  375. setEmittedDirectiveOnThisLine();
  376. break;
  377. case tok::pp___include_macros:
  378. // #__include_macros has no effect on a user of a preprocessed source
  379. // file; the only effect is on preprocessing.
  380. //
  381. // FIXME: That's not *quite* true: it causes the module in question to
  382. // be loaded, which can affect downstream diagnostics.
  383. break;
  384. default:
  385. llvm_unreachable("unknown include directive kind");
  386. break;
  387. }
  388. }
  389. }
  390. /// Handle entering the scope of a module during a module compilation.
  391. void PrintPPOutputPPCallbacks::BeginModule(const Module *M) {
  392. startNewLineIfNeeded();
  393. OS << "#pragma clang module begin " << M->getFullModuleName(true);
  394. setEmittedDirectiveOnThisLine();
  395. }
  396. /// Handle leaving the scope of a module during a module compilation.
  397. void PrintPPOutputPPCallbacks::EndModule(const Module *M) {
  398. startNewLineIfNeeded();
  399. OS << "#pragma clang module end /*" << M->getFullModuleName(true) << "*/";
  400. setEmittedDirectiveOnThisLine();
  401. }
  402. /// Ident - Handle #ident directives when read by the preprocessor.
  403. ///
  404. void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
  405. MoveToLine(Loc, /*RequireStartOfLine=*/true);
  406. OS.write("#ident ", strlen("#ident "));
  407. OS.write(S.begin(), S.size());
  408. setEmittedTokensOnThisLine();
  409. }
  410. /// MacroDefined - This hook is called whenever a macro definition is seen.
  411. void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
  412. const MacroDirective *MD) {
  413. const MacroInfo *MI = MD->getMacroInfo();
  414. // Only print out macro definitions in -dD mode.
  415. if (!DumpDefines ||
  416. // Ignore __FILE__ etc.
  417. MI->isBuiltinMacro()) return;
  418. MoveToLine(MI->getDefinitionLoc(), /*RequireStartOfLine=*/true);
  419. PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
  420. setEmittedDirectiveOnThisLine();
  421. }
  422. void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
  423. const MacroDefinition &MD,
  424. const MacroDirective *Undef) {
  425. // Only print out macro definitions in -dD mode.
  426. if (!DumpDefines) return;
  427. MoveToLine(MacroNameTok.getLocation(), /*RequireStartOfLine=*/true);
  428. OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
  429. setEmittedDirectiveOnThisLine();
  430. }
  431. static void outputPrintable(raw_ostream &OS, StringRef Str) {
  432. for (unsigned char Char : Str) {
  433. if (isPrintable(Char) && Char != '\\' && Char != '"')
  434. OS << (char)Char;
  435. else // Output anything hard as an octal escape.
  436. OS << '\\'
  437. << (char)('0' + ((Char >> 6) & 7))
  438. << (char)('0' + ((Char >> 3) & 7))
  439. << (char)('0' + ((Char >> 0) & 7));
  440. }
  441. }
  442. void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
  443. StringRef Namespace,
  444. PragmaMessageKind Kind,
  445. StringRef Str) {
  446. MoveToLine(Loc, /*RequireStartOfLine=*/true);
  447. OS << "#pragma ";
  448. if (!Namespace.empty())
  449. OS << Namespace << ' ';
  450. switch (Kind) {
  451. case PMK_Message:
  452. OS << "message(\"";
  453. break;
  454. case PMK_Warning:
  455. OS << "warning \"";
  456. break;
  457. case PMK_Error:
  458. OS << "error \"";
  459. break;
  460. }
  461. outputPrintable(OS, Str);
  462. OS << '"';
  463. if (Kind == PMK_Message)
  464. OS << ')';
  465. setEmittedDirectiveOnThisLine();
  466. }
  467. void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
  468. StringRef DebugType) {
  469. MoveToLine(Loc, /*RequireStartOfLine=*/true);
  470. OS << "#pragma clang __debug ";
  471. OS << DebugType;
  472. setEmittedDirectiveOnThisLine();
  473. }
  474. void PrintPPOutputPPCallbacks::
  475. PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
  476. MoveToLine(Loc, /*RequireStartOfLine=*/true);
  477. OS << "#pragma " << Namespace << " diagnostic push";
  478. setEmittedDirectiveOnThisLine();
  479. }
  480. void PrintPPOutputPPCallbacks::
  481. PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
  482. MoveToLine(Loc, /*RequireStartOfLine=*/true);
  483. OS << "#pragma " << Namespace << " diagnostic pop";
  484. setEmittedDirectiveOnThisLine();
  485. }
  486. void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
  487. StringRef Namespace,
  488. diag::Severity Map,
  489. StringRef Str) {
  490. MoveToLine(Loc, /*RequireStartOfLine=*/true);
  491. OS << "#pragma " << Namespace << " diagnostic ";
  492. switch (Map) {
  493. case diag::Severity::Remark:
  494. OS << "remark";
  495. break;
  496. case diag::Severity::Warning:
  497. OS << "warning";
  498. break;
  499. case diag::Severity::Error:
  500. OS << "error";
  501. break;
  502. case diag::Severity::Ignored:
  503. OS << "ignored";
  504. break;
  505. case diag::Severity::Fatal:
  506. OS << "fatal";
  507. break;
  508. }
  509. OS << " \"" << Str << '"';
  510. setEmittedDirectiveOnThisLine();
  511. }
  512. void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
  513. PragmaWarningSpecifier WarningSpec,
  514. ArrayRef<int> Ids) {
  515. MoveToLine(Loc, /*RequireStartOfLine=*/true);
  516. OS << "#pragma warning(";
  517. switch(WarningSpec) {
  518. case PWS_Default: OS << "default"; break;
  519. case PWS_Disable: OS << "disable"; break;
  520. case PWS_Error: OS << "error"; break;
  521. case PWS_Once: OS << "once"; break;
  522. case PWS_Suppress: OS << "suppress"; break;
  523. case PWS_Level1: OS << '1'; break;
  524. case PWS_Level2: OS << '2'; break;
  525. case PWS_Level3: OS << '3'; break;
  526. case PWS_Level4: OS << '4'; break;
  527. }
  528. OS << ':';
  529. for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
  530. OS << ' ' << *I;
  531. OS << ')';
  532. setEmittedDirectiveOnThisLine();
  533. }
  534. void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
  535. int Level) {
  536. MoveToLine(Loc, /*RequireStartOfLine=*/true);
  537. OS << "#pragma warning(push";
  538. if (Level >= 0)
  539. OS << ", " << Level;
  540. OS << ')';
  541. setEmittedDirectiveOnThisLine();
  542. }
  543. void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
  544. MoveToLine(Loc, /*RequireStartOfLine=*/true);
  545. OS << "#pragma warning(pop)";
  546. setEmittedDirectiveOnThisLine();
  547. }
  548. void PrintPPOutputPPCallbacks::PragmaExecCharsetPush(SourceLocation Loc,
  549. StringRef Str) {
  550. MoveToLine(Loc, /*RequireStartOfLine=*/true);
  551. OS << "#pragma character_execution_set(push";
  552. if (!Str.empty())
  553. OS << ", " << Str;
  554. OS << ')';
  555. setEmittedDirectiveOnThisLine();
  556. }
  557. void PrintPPOutputPPCallbacks::PragmaExecCharsetPop(SourceLocation Loc) {
  558. MoveToLine(Loc, /*RequireStartOfLine=*/true);
  559. OS << "#pragma character_execution_set(pop)";
  560. setEmittedDirectiveOnThisLine();
  561. }
  562. void PrintPPOutputPPCallbacks::
  563. PragmaAssumeNonNullBegin(SourceLocation Loc) {
  564. MoveToLine(Loc, /*RequireStartOfLine=*/true);
  565. OS << "#pragma clang assume_nonnull begin";
  566. setEmittedDirectiveOnThisLine();
  567. }
  568. void PrintPPOutputPPCallbacks::
  569. PragmaAssumeNonNullEnd(SourceLocation Loc) {
  570. MoveToLine(Loc, /*RequireStartOfLine=*/true);
  571. OS << "#pragma clang assume_nonnull end";
  572. setEmittedDirectiveOnThisLine();
  573. }
  574. void PrintPPOutputPPCallbacks::HandleWhitespaceBeforeTok(const Token &Tok,
  575. bool RequireSpace,
  576. bool RequireSameLine) {
  577. // These tokens are not expanded to anything and don't need whitespace before
  578. // them.
  579. if (Tok.is(tok::eof) ||
  580. (Tok.isAnnotation() && !Tok.is(tok::annot_header_unit) &&
  581. !Tok.is(tok::annot_module_begin) && !Tok.is(tok::annot_module_end)))
  582. return;
  583. // EmittedDirectiveOnThisLine takes priority over RequireSameLine.
  584. if ((!RequireSameLine || EmittedDirectiveOnThisLine) &&
  585. MoveToLine(Tok, /*RequireStartOfLine=*/EmittedDirectiveOnThisLine)) {
  586. if (MinimizeWhitespace) {
  587. // Avoid interpreting hash as a directive under -fpreprocessed.
  588. if (Tok.is(tok::hash))
  589. OS << ' ';
  590. } else {
  591. // Print out space characters so that the first token on a line is
  592. // indented for easy reading.
  593. unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
  594. // The first token on a line can have a column number of 1, yet still
  595. // expect leading white space, if a macro expansion in column 1 starts
  596. // with an empty macro argument, or an empty nested macro expansion. In
  597. // this case, move the token to column 2.
  598. if (ColNo == 1 && Tok.hasLeadingSpace())
  599. ColNo = 2;
  600. // This hack prevents stuff like:
  601. // #define HASH #
  602. // HASH define foo bar
  603. // From having the # character end up at column 1, which makes it so it
  604. // is not handled as a #define next time through the preprocessor if in
  605. // -fpreprocessed mode.
  606. if (ColNo <= 1 && Tok.is(tok::hash))
  607. OS << ' ';
  608. // Otherwise, indent the appropriate number of spaces.
  609. for (; ColNo > 1; --ColNo)
  610. OS << ' ';
  611. }
  612. } else {
  613. // Insert whitespace between the previous and next token if either
  614. // - The caller requires it
  615. // - The input had whitespace between them and we are not in
  616. // whitespace-minimization mode
  617. // - The whitespace is necessary to keep the tokens apart and there is not
  618. // already a newline between them
  619. if (RequireSpace || (!MinimizeWhitespace && Tok.hasLeadingSpace()) ||
  620. ((EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) &&
  621. AvoidConcat(PrevPrevTok, PrevTok, Tok)))
  622. OS << ' ';
  623. }
  624. PrevPrevTok = PrevTok;
  625. PrevTok = Tok;
  626. }
  627. void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
  628. unsigned Len) {
  629. unsigned NumNewlines = 0;
  630. for (; Len; --Len, ++TokStr) {
  631. if (*TokStr != '\n' &&
  632. *TokStr != '\r')
  633. continue;
  634. ++NumNewlines;
  635. // If we have \n\r or \r\n, skip both and count as one line.
  636. if (Len != 1 &&
  637. (TokStr[1] == '\n' || TokStr[1] == '\r') &&
  638. TokStr[0] != TokStr[1]) {
  639. ++TokStr;
  640. --Len;
  641. }
  642. }
  643. if (NumNewlines == 0) return;
  644. CurLine += NumNewlines;
  645. }
  646. namespace {
  647. struct UnknownPragmaHandler : public PragmaHandler {
  648. const char *Prefix;
  649. PrintPPOutputPPCallbacks *Callbacks;
  650. // Set to true if tokens should be expanded
  651. bool ShouldExpandTokens;
  652. UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
  653. bool RequireTokenExpansion)
  654. : Prefix(prefix), Callbacks(callbacks),
  655. ShouldExpandTokens(RequireTokenExpansion) {}
  656. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  657. Token &PragmaTok) override {
  658. // Figure out what line we went to and insert the appropriate number of
  659. // newline characters.
  660. Callbacks->MoveToLine(PragmaTok.getLocation(), /*RequireStartOfLine=*/true);
  661. Callbacks->OS.write(Prefix, strlen(Prefix));
  662. Callbacks->setEmittedTokensOnThisLine();
  663. if (ShouldExpandTokens) {
  664. // The first token does not have expanded macros. Expand them, if
  665. // required.
  666. auto Toks = std::make_unique<Token[]>(1);
  667. Toks[0] = PragmaTok;
  668. PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
  669. /*DisableMacroExpansion=*/false,
  670. /*IsReinject=*/false);
  671. PP.Lex(PragmaTok);
  672. }
  673. // Read and print all of the pragma tokens.
  674. bool IsFirst = true;
  675. while (PragmaTok.isNot(tok::eod)) {
  676. Callbacks->HandleWhitespaceBeforeTok(PragmaTok, /*RequireSpace=*/IsFirst,
  677. /*RequireSameLine=*/true);
  678. IsFirst = false;
  679. std::string TokSpell = PP.getSpelling(PragmaTok);
  680. Callbacks->OS.write(&TokSpell[0], TokSpell.size());
  681. Callbacks->setEmittedTokensOnThisLine();
  682. if (ShouldExpandTokens)
  683. PP.Lex(PragmaTok);
  684. else
  685. PP.LexUnexpandedToken(PragmaTok);
  686. }
  687. Callbacks->setEmittedDirectiveOnThisLine();
  688. }
  689. };
  690. } // end anonymous namespace
  691. static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
  692. PrintPPOutputPPCallbacks *Callbacks,
  693. raw_ostream &OS) {
  694. bool DropComments = PP.getLangOpts().TraditionalCPP &&
  695. !PP.getCommentRetentionState();
  696. bool IsStartOfLine = false;
  697. char Buffer[256];
  698. while (true) {
  699. // Two lines joined with line continuation ('\' as last character on the
  700. // line) must be emitted as one line even though Tok.getLine() returns two
  701. // different values. In this situation Tok.isAtStartOfLine() is false even
  702. // though it may be the first token on the lexical line. When
  703. // dropping/skipping a token that is at the start of a line, propagate the
  704. // start-of-line-ness to the next token to not append it to the previous
  705. // line.
  706. IsStartOfLine = IsStartOfLine || Tok.isAtStartOfLine();
  707. Callbacks->HandleWhitespaceBeforeTok(Tok, /*RequireSpace=*/false,
  708. /*RequireSameLine=*/!IsStartOfLine);
  709. if (DropComments && Tok.is(tok::comment)) {
  710. // Skip comments. Normally the preprocessor does not generate
  711. // tok::comment nodes at all when not keeping comments, but under
  712. // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
  713. PP.Lex(Tok);
  714. continue;
  715. } else if (Tok.is(tok::eod)) {
  716. // Don't print end of directive tokens, since they are typically newlines
  717. // that mess up our line tracking. These come from unknown pre-processor
  718. // directives or hash-prefixed comments in standalone assembly files.
  719. PP.Lex(Tok);
  720. // FIXME: The token on the next line after #include should have
  721. // Tok.isAtStartOfLine() set.
  722. IsStartOfLine = true;
  723. continue;
  724. } else if (Tok.is(tok::annot_module_include)) {
  725. // PrintPPOutputPPCallbacks::InclusionDirective handles producing
  726. // appropriate output here. Ignore this token entirely.
  727. PP.Lex(Tok);
  728. IsStartOfLine = true;
  729. continue;
  730. } else if (Tok.is(tok::annot_module_begin)) {
  731. // FIXME: We retrieve this token after the FileChanged callback, and
  732. // retrieve the module_end token before the FileChanged callback, so
  733. // we render this within the file and render the module end outside the
  734. // file, but this is backwards from the token locations: the module_begin
  735. // token is at the include location (outside the file) and the module_end
  736. // token is at the EOF location (within the file).
  737. Callbacks->BeginModule(
  738. reinterpret_cast<Module *>(Tok.getAnnotationValue()));
  739. PP.Lex(Tok);
  740. IsStartOfLine = true;
  741. continue;
  742. } else if (Tok.is(tok::annot_module_end)) {
  743. Callbacks->EndModule(
  744. reinterpret_cast<Module *>(Tok.getAnnotationValue()));
  745. PP.Lex(Tok);
  746. IsStartOfLine = true;
  747. continue;
  748. } else if (Tok.is(tok::annot_header_unit)) {
  749. // This is a header-name that has been (effectively) converted into a
  750. // module-name.
  751. // FIXME: The module name could contain non-identifier module name
  752. // components. We don't have a good way to round-trip those.
  753. Module *M = reinterpret_cast<Module *>(Tok.getAnnotationValue());
  754. std::string Name = M->getFullModuleName();
  755. OS.write(Name.data(), Name.size());
  756. Callbacks->HandleNewlinesInToken(Name.data(), Name.size());
  757. } else if (Tok.isAnnotation()) {
  758. // Ignore annotation tokens created by pragmas - the pragmas themselves
  759. // will be reproduced in the preprocessed output.
  760. PP.Lex(Tok);
  761. continue;
  762. } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
  763. OS << II->getName();
  764. } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
  765. Tok.getLiteralData()) {
  766. OS.write(Tok.getLiteralData(), Tok.getLength());
  767. } else if (Tok.getLength() < llvm::array_lengthof(Buffer)) {
  768. const char *TokPtr = Buffer;
  769. unsigned Len = PP.getSpelling(Tok, TokPtr);
  770. OS.write(TokPtr, Len);
  771. // Tokens that can contain embedded newlines need to adjust our current
  772. // line number.
  773. // FIXME: The token may end with a newline in which case
  774. // setEmittedDirectiveOnThisLine/setEmittedTokensOnThisLine afterwards is
  775. // wrong.
  776. if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
  777. Callbacks->HandleNewlinesInToken(TokPtr, Len);
  778. if (Tok.is(tok::comment) && Len >= 2 && TokPtr[0] == '/' &&
  779. TokPtr[1] == '/') {
  780. // It's a line comment;
  781. // Ensure that we don't concatenate anything behind it.
  782. Callbacks->setEmittedDirectiveOnThisLine();
  783. }
  784. } else {
  785. std::string S = PP.getSpelling(Tok);
  786. OS.write(S.data(), S.size());
  787. // Tokens that can contain embedded newlines need to adjust our current
  788. // line number.
  789. if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
  790. Callbacks->HandleNewlinesInToken(S.data(), S.size());
  791. if (Tok.is(tok::comment) && S.size() >= 2 && S[0] == '/' && S[1] == '/') {
  792. // It's a line comment;
  793. // Ensure that we don't concatenate anything behind it.
  794. Callbacks->setEmittedDirectiveOnThisLine();
  795. }
  796. }
  797. Callbacks->setEmittedTokensOnThisLine();
  798. IsStartOfLine = false;
  799. if (Tok.is(tok::eof)) break;
  800. PP.Lex(Tok);
  801. }
  802. }
  803. typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
  804. static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
  805. return LHS->first->getName().compare(RHS->first->getName());
  806. }
  807. static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
  808. // Ignore unknown pragmas.
  809. PP.IgnorePragmas();
  810. // -dM mode just scans and ignores all tokens in the files, then dumps out
  811. // the macro table at the end.
  812. PP.EnterMainSourceFile();
  813. Token Tok;
  814. do PP.Lex(Tok);
  815. while (Tok.isNot(tok::eof));
  816. SmallVector<id_macro_pair, 128> MacrosByID;
  817. for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
  818. I != E; ++I) {
  819. auto *MD = I->second.getLatest();
  820. if (MD && MD->isDefined())
  821. MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
  822. }
  823. llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
  824. for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
  825. MacroInfo &MI = *MacrosByID[i].second;
  826. // Ignore computed macros like __LINE__ and friends.
  827. if (MI.isBuiltinMacro()) continue;
  828. PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
  829. *OS << '\n';
  830. }
  831. }
  832. /// DoPrintPreprocessedInput - This implements -E mode.
  833. ///
  834. void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
  835. const PreprocessorOutputOptions &Opts) {
  836. // Show macros with no output is handled specially.
  837. if (!Opts.ShowCPP) {
  838. assert(Opts.ShowMacros && "Not yet implemented!");
  839. DoPrintMacros(PP, OS);
  840. return;
  841. }
  842. // Inform the preprocessor whether we want it to retain comments or not, due
  843. // to -C or -CC.
  844. PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
  845. PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
  846. PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
  847. Opts.ShowIncludeDirectives, Opts.UseLineDirectives,
  848. Opts.MinimizeWhitespace);
  849. // Expand macros in pragmas with -fms-extensions. The assumption is that
  850. // the majority of pragmas in such a file will be Microsoft pragmas.
  851. // Remember the handlers we will add so that we can remove them later.
  852. std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(
  853. new UnknownPragmaHandler(
  854. "#pragma", Callbacks,
  855. /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
  856. std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(
  857. "#pragma GCC", Callbacks,
  858. /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
  859. std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(
  860. "#pragma clang", Callbacks,
  861. /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
  862. PP.AddPragmaHandler(MicrosoftExtHandler.get());
  863. PP.AddPragmaHandler("GCC", GCCHandler.get());
  864. PP.AddPragmaHandler("clang", ClangHandler.get());
  865. // The tokens after pragma omp need to be expanded.
  866. //
  867. // OpenMP [2.1, Directive format]
  868. // Preprocessing tokens following the #pragma omp are subject to macro
  869. // replacement.
  870. std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(
  871. new UnknownPragmaHandler("#pragma omp", Callbacks,
  872. /*RequireTokenExpansion=*/true));
  873. PP.AddPragmaHandler("omp", OpenMPHandler.get());
  874. PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
  875. // After we have configured the preprocessor, enter the main file.
  876. PP.EnterMainSourceFile();
  877. // Consume all of the tokens that come from the predefines buffer. Those
  878. // should not be emitted into the output and are guaranteed to be at the
  879. // start.
  880. const SourceManager &SourceMgr = PP.getSourceManager();
  881. Token Tok;
  882. do {
  883. PP.Lex(Tok);
  884. if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
  885. break;
  886. PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
  887. if (PLoc.isInvalid())
  888. break;
  889. if (strcmp(PLoc.getFilename(), "<built-in>"))
  890. break;
  891. } while (true);
  892. // Read all the preprocessed tokens, printing them out to the stream.
  893. PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
  894. *OS << '\n';
  895. // Remove the handlers we just added to leave the preprocessor in a sane state
  896. // so that it can be reused (for example by a clang::Parser instance).
  897. PP.RemovePragmaHandler(MicrosoftExtHandler.get());
  898. PP.RemovePragmaHandler("GCC", GCCHandler.get());
  899. PP.RemovePragmaHandler("clang", ClangHandler.get());
  900. PP.RemovePragmaHandler("omp", OpenMPHandler.get());
  901. }