PrintPreprocessedOutput.cpp 31 KB

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