PrintPreprocessedOutput.cpp 31 KB

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