PrintPreprocessedOutput.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. //===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This code simply runs the preprocessor on the input file and prints out the
  11. // result. This is the traditional behavior of the -E option.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Frontend/Utils.h"
  15. #include "clang/Basic/CharInfo.h"
  16. #include "clang/Basic/Diagnostic.h"
  17. #include "clang/Basic/SourceManager.h"
  18. #include "clang/Frontend/PreprocessorOutputOptions.h"
  19. #include "clang/Lex/MacroInfo.h"
  20. #include "clang/Lex/PPCallbacks.h"
  21. #include "clang/Lex/Pragma.h"
  22. #include "clang/Lex/Preprocessor.h"
  23. #include "clang/Lex/TokenConcatenation.h"
  24. #include "llvm/ADT/STLExtras.h"
  25. #include "llvm/ADT/SmallString.h"
  26. #include "llvm/ADT/StringRef.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include <cstdio>
  30. using namespace clang;
  31. /// PrintMacroDefinition - Print a macro definition in a form that will be
  32. /// properly accepted back as a definition.
  33. static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
  34. Preprocessor &PP, raw_ostream &OS) {
  35. OS << "#define " << II.getName();
  36. if (MI.isFunctionLike()) {
  37. OS << '(';
  38. if (!MI.arg_empty()) {
  39. MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
  40. for (; AI+1 != E; ++AI) {
  41. OS << (*AI)->getName();
  42. OS << ',';
  43. }
  44. // Last argument.
  45. if ((*AI)->getName() == "__VA_ARGS__")
  46. OS << "...";
  47. else
  48. OS << (*AI)->getName();
  49. }
  50. if (MI.isGNUVarargs())
  51. OS << "..."; // #define foo(x...)
  52. OS << ')';
  53. }
  54. // GCC always emits a space, even if the macro body is empty. However, do not
  55. // want to emit two spaces if the first token has a leading space.
  56. if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
  57. OS << ' ';
  58. SmallString<128> SpellingBuffer;
  59. for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end();
  60. I != E; ++I) {
  61. if (I->hasLeadingSpace())
  62. OS << ' ';
  63. OS << PP.getSpelling(*I, SpellingBuffer);
  64. }
  65. }
  66. //===----------------------------------------------------------------------===//
  67. // Preprocessed token printer
  68. //===----------------------------------------------------------------------===//
  69. namespace {
  70. class PrintPPOutputPPCallbacks : public PPCallbacks {
  71. Preprocessor &PP;
  72. SourceManager &SM;
  73. TokenConcatenation ConcatInfo;
  74. public:
  75. raw_ostream &OS;
  76. private:
  77. unsigned CurLine;
  78. bool EmittedTokensOnThisLine;
  79. bool EmittedDirectiveOnThisLine;
  80. SrcMgr::CharacteristicKind FileType;
  81. SmallString<512> CurFilename;
  82. bool Initialized;
  83. bool DisableLineMarkers;
  84. bool DumpDefines;
  85. bool UseLineDirective;
  86. bool IsFirstFileEntered;
  87. public:
  88. PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os,
  89. bool lineMarkers, bool defines)
  90. : PP(pp), SM(PP.getSourceManager()),
  91. ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
  92. DumpDefines(defines) {
  93. CurLine = 0;
  94. CurFilename += "<uninit>";
  95. EmittedTokensOnThisLine = false;
  96. EmittedDirectiveOnThisLine = false;
  97. FileType = SrcMgr::C_User;
  98. Initialized = false;
  99. IsFirstFileEntered = false;
  100. // If we're in microsoft mode, use normal #line instead of line markers.
  101. UseLineDirective = PP.getLangOpts().MicrosoftExt;
  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. virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  111. SrcMgr::CharacteristicKind FileType,
  112. FileID PrevFID);
  113. virtual void InclusionDirective(SourceLocation HashLoc,
  114. const Token &IncludeTok,
  115. StringRef FileName,
  116. bool IsAngled,
  117. CharSourceRange FilenameRange,
  118. const FileEntry *File,
  119. StringRef SearchPath,
  120. StringRef RelativePath,
  121. const Module *Imported);
  122. virtual void Ident(SourceLocation Loc, const std::string &str);
  123. virtual void PragmaCaptured(SourceLocation Loc, StringRef Str);
  124. virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
  125. const std::string &Str);
  126. virtual void PragmaDetectMismatch(SourceLocation Loc,
  127. const std::string &Name,
  128. const std::string &Value);
  129. virtual void PragmaMessage(SourceLocation Loc, StringRef Namespace,
  130. PragmaMessageKind Kind, StringRef Str);
  131. virtual void PragmaDebug(SourceLocation Loc, StringRef DebugType);
  132. virtual void PragmaDiagnosticPush(SourceLocation Loc,
  133. StringRef Namespace);
  134. virtual void PragmaDiagnosticPop(SourceLocation Loc,
  135. StringRef Namespace);
  136. virtual void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
  137. diag::Mapping Map, StringRef Str);
  138. virtual void PragmaWarning(SourceLocation Loc, StringRef WarningSpec,
  139. ArrayRef<int> Ids);
  140. virtual void PragmaWarningPush(SourceLocation Loc, int Level);
  141. virtual void PragmaWarningPop(SourceLocation Loc);
  142. bool HandleFirstTokOnLine(Token &Tok);
  143. /// Move to the line of the provided source location. This will
  144. /// return true if the output stream required adjustment or if
  145. /// the requested location is on the first line.
  146. bool MoveToLine(SourceLocation Loc) {
  147. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  148. if (PLoc.isInvalid())
  149. return false;
  150. return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
  151. }
  152. bool MoveToLine(unsigned LineNo);
  153. bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
  154. const Token &Tok) {
  155. return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
  156. }
  157. void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
  158. bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
  159. void HandleNewlinesInToken(const char *TokStr, unsigned Len);
  160. /// MacroDefined - This hook is called whenever a macro definition is seen.
  161. void MacroDefined(const Token &MacroNameTok, const MacroDirective *MD);
  162. /// MacroUndefined - This hook is called whenever a macro #undef is seen.
  163. void MacroUndefined(const Token &MacroNameTok, const MacroDirective *MD);
  164. };
  165. } // end anonymous namespace
  166. void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
  167. const char *Extra,
  168. unsigned ExtraLen) {
  169. startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
  170. // Emit #line directives or GNU line markers depending on what mode we're in.
  171. if (UseLineDirective) {
  172. OS << "#line" << ' ' << LineNo << ' ' << '"';
  173. OS.write_escaped(CurFilename);
  174. OS << '"';
  175. } else {
  176. OS << '#' << ' ' << LineNo << ' ' << '"';
  177. OS.write_escaped(CurFilename);
  178. OS << '"';
  179. if (ExtraLen)
  180. OS.write(Extra, ExtraLen);
  181. if (FileType == SrcMgr::C_System)
  182. OS.write(" 3", 2);
  183. else if (FileType == SrcMgr::C_ExternCSystem)
  184. OS.write(" 3 4", 4);
  185. }
  186. OS << '\n';
  187. }
  188. /// MoveToLine - Move the output to the source line specified by the location
  189. /// object. We can do this by emitting some number of \n's, or be emitting a
  190. /// #line directive. This returns false if already at the specified line, true
  191. /// if some newlines were emitted.
  192. bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
  193. // If this line is "close enough" to the original line, just print newlines,
  194. // otherwise print a #line directive.
  195. if (LineNo-CurLine <= 8) {
  196. if (LineNo-CurLine == 1)
  197. OS << '\n';
  198. else if (LineNo == CurLine)
  199. return false; // Spelling line moved, but expansion line didn't.
  200. else {
  201. const char *NewLines = "\n\n\n\n\n\n\n\n";
  202. OS.write(NewLines, LineNo-CurLine);
  203. }
  204. } else if (!DisableLineMarkers) {
  205. // Emit a #line or line marker.
  206. WriteLineInfo(LineNo, 0, 0);
  207. } else {
  208. // Okay, we're in -P mode, which turns off line markers. However, we still
  209. // need to emit a newline between tokens on different lines.
  210. startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
  211. }
  212. CurLine = LineNo;
  213. return true;
  214. }
  215. bool
  216. PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
  217. if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
  218. OS << '\n';
  219. EmittedTokensOnThisLine = false;
  220. EmittedDirectiveOnThisLine = false;
  221. if (ShouldUpdateCurrentLine)
  222. ++CurLine;
  223. return true;
  224. }
  225. return false;
  226. }
  227. /// FileChanged - Whenever the preprocessor enters or exits a #include file
  228. /// it invokes this handler. Update our conception of the current source
  229. /// position.
  230. void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
  231. FileChangeReason Reason,
  232. SrcMgr::CharacteristicKind NewFileType,
  233. FileID PrevFID) {
  234. // Unless we are exiting a #include, make sure to skip ahead to the line the
  235. // #include directive was at.
  236. SourceManager &SourceMgr = SM;
  237. PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
  238. if (UserLoc.isInvalid())
  239. return;
  240. unsigned NewLine = UserLoc.getLine();
  241. if (Reason == PPCallbacks::EnterFile) {
  242. SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
  243. if (IncludeLoc.isValid())
  244. MoveToLine(IncludeLoc);
  245. } else if (Reason == PPCallbacks::SystemHeaderPragma) {
  246. // GCC emits the # directive for this directive on the line AFTER the
  247. // directive and emits a bunch of spaces that aren't needed. This is because
  248. // otherwise we will emit a line marker for THIS line, which requires an
  249. // extra blank line after the directive to avoid making all following lines
  250. // off by one. We can do better by simply incrementing NewLine here.
  251. NewLine += 1;
  252. }
  253. CurLine = NewLine;
  254. CurFilename.clear();
  255. CurFilename += UserLoc.getFilename();
  256. FileType = NewFileType;
  257. if (DisableLineMarkers) {
  258. startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
  259. return;
  260. }
  261. if (!Initialized) {
  262. WriteLineInfo(CurLine);
  263. Initialized = true;
  264. }
  265. // Do not emit an enter marker for the main file (which we expect is the first
  266. // entered file). This matches gcc, and improves compatibility with some tools
  267. // which track the # line markers as a way to determine when the preprocessed
  268. // output is in the context of the main file.
  269. if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
  270. IsFirstFileEntered = true;
  271. return;
  272. }
  273. switch (Reason) {
  274. case PPCallbacks::EnterFile:
  275. WriteLineInfo(CurLine, " 1", 2);
  276. break;
  277. case PPCallbacks::ExitFile:
  278. WriteLineInfo(CurLine, " 2", 2);
  279. break;
  280. case PPCallbacks::SystemHeaderPragma:
  281. case PPCallbacks::RenameFile:
  282. WriteLineInfo(CurLine);
  283. break;
  284. }
  285. }
  286. void PrintPPOutputPPCallbacks::InclusionDirective(SourceLocation HashLoc,
  287. const Token &IncludeTok,
  288. StringRef FileName,
  289. bool IsAngled,
  290. CharSourceRange FilenameRange,
  291. const FileEntry *File,
  292. StringRef SearchPath,
  293. StringRef RelativePath,
  294. const Module *Imported) {
  295. // When preprocessing, turn implicit imports into @imports.
  296. // FIXME: This is a stop-gap until a more comprehensive "preprocessing with
  297. // modules" solution is introduced.
  298. if (Imported) {
  299. startNewLineIfNeeded();
  300. MoveToLine(HashLoc);
  301. OS << "@import " << Imported->getFullModuleName() << ";"
  302. << " /* clang -E: implicit import for \"" << File->getName() << "\" */";
  303. EmittedTokensOnThisLine = true;
  304. setEmittedDirectiveOnThisLine();
  305. }
  306. }
  307. /// Ident - Handle #ident directives when read by the preprocessor.
  308. ///
  309. void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
  310. MoveToLine(Loc);
  311. OS.write("#ident ", strlen("#ident "));
  312. OS.write(&S[0], S.size());
  313. EmittedTokensOnThisLine = true;
  314. }
  315. void PrintPPOutputPPCallbacks::PragmaCaptured(SourceLocation Loc,
  316. StringRef Str) {
  317. startNewLineIfNeeded();
  318. MoveToLine(Loc);
  319. OS << "#pragma captured";
  320. setEmittedDirectiveOnThisLine();
  321. }
  322. /// MacroDefined - This hook is called whenever a macro definition is seen.
  323. void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
  324. const MacroDirective *MD) {
  325. const MacroInfo *MI = MD->getMacroInfo();
  326. // Only print out macro definitions in -dD mode.
  327. if (!DumpDefines ||
  328. // Ignore __FILE__ etc.
  329. MI->isBuiltinMacro()) return;
  330. MoveToLine(MI->getDefinitionLoc());
  331. PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
  332. setEmittedDirectiveOnThisLine();
  333. }
  334. void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
  335. const MacroDirective *MD) {
  336. // Only print out macro definitions in -dD mode.
  337. if (!DumpDefines) return;
  338. MoveToLine(MacroNameTok.getLocation());
  339. OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
  340. setEmittedDirectiveOnThisLine();
  341. }
  342. static void outputPrintable(llvm::raw_ostream& OS,
  343. const std::string &Str) {
  344. for (unsigned i = 0, e = Str.size(); i != e; ++i) {
  345. unsigned char Char = Str[i];
  346. if (isPrintable(Char) && Char != '\\' && Char != '"')
  347. OS << (char)Char;
  348. else // Output anything hard as an octal escape.
  349. OS << '\\'
  350. << (char)('0'+ ((Char >> 6) & 7))
  351. << (char)('0'+ ((Char >> 3) & 7))
  352. << (char)('0'+ ((Char >> 0) & 7));
  353. }
  354. }
  355. void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
  356. const IdentifierInfo *Kind,
  357. const std::string &Str) {
  358. startNewLineIfNeeded();
  359. MoveToLine(Loc);
  360. OS << "#pragma comment(" << Kind->getName();
  361. if (!Str.empty()) {
  362. OS << ", \"";
  363. outputPrintable(OS, Str);
  364. OS << '"';
  365. }
  366. OS << ')';
  367. setEmittedDirectiveOnThisLine();
  368. }
  369. void PrintPPOutputPPCallbacks::PragmaDetectMismatch(SourceLocation Loc,
  370. const std::string &Name,
  371. const std::string &Value) {
  372. startNewLineIfNeeded();
  373. MoveToLine(Loc);
  374. OS << "#pragma detect_mismatch(\"" << Name << '"';
  375. outputPrintable(OS, Name);
  376. OS << "\", \"";
  377. outputPrintable(OS, Value);
  378. OS << "\")";
  379. setEmittedDirectiveOnThisLine();
  380. }
  381. void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
  382. StringRef Namespace,
  383. PragmaMessageKind Kind,
  384. StringRef Str) {
  385. startNewLineIfNeeded();
  386. MoveToLine(Loc);
  387. OS << "#pragma ";
  388. if (!Namespace.empty())
  389. OS << Namespace << ' ';
  390. switch (Kind) {
  391. case PMK_Message:
  392. OS << "message(\"";
  393. break;
  394. case PMK_Warning:
  395. OS << "warning \"";
  396. break;
  397. case PMK_Error:
  398. OS << "error \"";
  399. break;
  400. }
  401. outputPrintable(OS, Str);
  402. OS << '"';
  403. if (Kind == PMK_Message)
  404. OS << ')';
  405. setEmittedDirectiveOnThisLine();
  406. }
  407. void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
  408. StringRef DebugType) {
  409. startNewLineIfNeeded();
  410. MoveToLine(Loc);
  411. OS << "#pragma clang __debug ";
  412. OS << DebugType;
  413. setEmittedDirectiveOnThisLine();
  414. }
  415. void PrintPPOutputPPCallbacks::
  416. PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
  417. startNewLineIfNeeded();
  418. MoveToLine(Loc);
  419. OS << "#pragma " << Namespace << " diagnostic push";
  420. setEmittedDirectiveOnThisLine();
  421. }
  422. void PrintPPOutputPPCallbacks::
  423. PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
  424. startNewLineIfNeeded();
  425. MoveToLine(Loc);
  426. OS << "#pragma " << Namespace << " diagnostic pop";
  427. setEmittedDirectiveOnThisLine();
  428. }
  429. void PrintPPOutputPPCallbacks::
  430. PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
  431. diag::Mapping Map, StringRef Str) {
  432. startNewLineIfNeeded();
  433. MoveToLine(Loc);
  434. OS << "#pragma " << Namespace << " diagnostic ";
  435. switch (Map) {
  436. case diag::MAP_WARNING:
  437. OS << "warning";
  438. break;
  439. case diag::MAP_ERROR:
  440. OS << "error";
  441. break;
  442. case diag::MAP_IGNORE:
  443. OS << "ignored";
  444. break;
  445. case diag::MAP_FATAL:
  446. OS << "fatal";
  447. break;
  448. }
  449. OS << " \"" << Str << '"';
  450. setEmittedDirectiveOnThisLine();
  451. }
  452. void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
  453. StringRef WarningSpec,
  454. ArrayRef<int> Ids) {
  455. startNewLineIfNeeded();
  456. MoveToLine(Loc);
  457. OS << "#pragma warning(" << WarningSpec << ':';
  458. for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
  459. OS << ' ' << *I;
  460. OS << ')';
  461. setEmittedDirectiveOnThisLine();
  462. }
  463. void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
  464. int Level) {
  465. startNewLineIfNeeded();
  466. MoveToLine(Loc);
  467. OS << "#pragma warning(push";
  468. if (Level >= 0)
  469. OS << ", " << Level;
  470. OS << ')';
  471. setEmittedDirectiveOnThisLine();
  472. }
  473. void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
  474. startNewLineIfNeeded();
  475. MoveToLine(Loc);
  476. OS << "#pragma warning(pop)";
  477. setEmittedDirectiveOnThisLine();
  478. }
  479. /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
  480. /// is called for the first token on each new line. If this really is the start
  481. /// of a new logical line, handle it and return true, otherwise return false.
  482. /// This may not be the start of a logical line because the "start of line"
  483. /// marker is set for spelling lines, not expansion ones.
  484. bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
  485. // Figure out what line we went to and insert the appropriate number of
  486. // newline characters.
  487. if (!MoveToLine(Tok.getLocation()))
  488. return false;
  489. // Print out space characters so that the first token on a line is
  490. // indented for easy reading.
  491. unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
  492. // This hack prevents stuff like:
  493. // #define HASH #
  494. // HASH define foo bar
  495. // From having the # character end up at column 1, which makes it so it
  496. // is not handled as a #define next time through the preprocessor if in
  497. // -fpreprocessed mode.
  498. if (ColNo <= 1 && Tok.is(tok::hash))
  499. OS << ' ';
  500. // Otherwise, indent the appropriate number of spaces.
  501. for (; ColNo > 1; --ColNo)
  502. OS << ' ';
  503. return true;
  504. }
  505. void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
  506. unsigned Len) {
  507. unsigned NumNewlines = 0;
  508. for (; Len; --Len, ++TokStr) {
  509. if (*TokStr != '\n' &&
  510. *TokStr != '\r')
  511. continue;
  512. ++NumNewlines;
  513. // If we have \n\r or \r\n, skip both and count as one line.
  514. if (Len != 1 &&
  515. (TokStr[1] == '\n' || TokStr[1] == '\r') &&
  516. TokStr[0] != TokStr[1])
  517. ++TokStr, --Len;
  518. }
  519. if (NumNewlines == 0) return;
  520. CurLine += NumNewlines;
  521. }
  522. namespace {
  523. struct UnknownPragmaHandler : public PragmaHandler {
  524. const char *Prefix;
  525. PrintPPOutputPPCallbacks *Callbacks;
  526. UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
  527. : Prefix(prefix), Callbacks(callbacks) {}
  528. virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
  529. Token &PragmaTok) {
  530. // Figure out what line we went to and insert the appropriate number of
  531. // newline characters.
  532. Callbacks->startNewLineIfNeeded();
  533. Callbacks->MoveToLine(PragmaTok.getLocation());
  534. Callbacks->OS.write(Prefix, strlen(Prefix));
  535. // Read and print all of the pragma tokens.
  536. while (PragmaTok.isNot(tok::eod)) {
  537. if (PragmaTok.hasLeadingSpace())
  538. Callbacks->OS << ' ';
  539. std::string TokSpell = PP.getSpelling(PragmaTok);
  540. Callbacks->OS.write(&TokSpell[0], TokSpell.size());
  541. PP.LexUnexpandedToken(PragmaTok);
  542. }
  543. Callbacks->setEmittedDirectiveOnThisLine();
  544. }
  545. };
  546. } // end anonymous namespace
  547. static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
  548. PrintPPOutputPPCallbacks *Callbacks,
  549. raw_ostream &OS) {
  550. bool DropComments = PP.getLangOpts().TraditionalCPP &&
  551. !PP.getCommentRetentionState();
  552. char Buffer[256];
  553. Token PrevPrevTok, PrevTok;
  554. PrevPrevTok.startToken();
  555. PrevTok.startToken();
  556. while (1) {
  557. if (Callbacks->hasEmittedDirectiveOnThisLine()) {
  558. Callbacks->startNewLineIfNeeded();
  559. Callbacks->MoveToLine(Tok.getLocation());
  560. }
  561. // If this token is at the start of a line, emit newlines if needed.
  562. if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
  563. // done.
  564. } else if (Tok.hasLeadingSpace() ||
  565. // If we haven't emitted a token on this line yet, PrevTok isn't
  566. // useful to look at and no concatenation could happen anyway.
  567. (Callbacks->hasEmittedTokensOnThisLine() &&
  568. // Don't print "-" next to "-", it would form "--".
  569. Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
  570. OS << ' ';
  571. }
  572. if (DropComments && Tok.is(tok::comment)) {
  573. // Skip comments. Normally the preprocessor does not generate
  574. // tok::comment nodes at all when not keeping comments, but under
  575. // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
  576. SourceLocation StartLoc = Tok.getLocation();
  577. Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
  578. } else if (Tok.isAnnotation()) {
  579. // PrintPPOutputPPCallbacks handles producing appropriate output here.
  580. // Ignore this token entirely.
  581. PP.Lex(Tok);
  582. continue;
  583. } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
  584. OS << II->getName();
  585. } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
  586. Tok.getLiteralData()) {
  587. OS.write(Tok.getLiteralData(), Tok.getLength());
  588. } else if (Tok.getLength() < 256) {
  589. const char *TokPtr = Buffer;
  590. unsigned Len = PP.getSpelling(Tok, TokPtr);
  591. OS.write(TokPtr, Len);
  592. // Tokens that can contain embedded newlines need to adjust our current
  593. // line number.
  594. if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
  595. Callbacks->HandleNewlinesInToken(TokPtr, Len);
  596. } else {
  597. std::string S = PP.getSpelling(Tok);
  598. OS.write(&S[0], S.size());
  599. // Tokens that can contain embedded newlines need to adjust our current
  600. // line number.
  601. if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
  602. Callbacks->HandleNewlinesInToken(&S[0], S.size());
  603. }
  604. Callbacks->setEmittedTokensOnThisLine();
  605. if (Tok.is(tok::eof)) break;
  606. PrevPrevTok = PrevTok;
  607. PrevTok = Tok;
  608. PP.Lex(Tok);
  609. }
  610. }
  611. typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
  612. static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
  613. return LHS->first->getName().compare(RHS->first->getName());
  614. }
  615. static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
  616. // Ignore unknown pragmas.
  617. PP.AddPragmaHandler(new EmptyPragmaHandler());
  618. // -dM mode just scans and ignores all tokens in the files, then dumps out
  619. // the macro table at the end.
  620. PP.EnterMainSourceFile();
  621. Token Tok;
  622. do PP.Lex(Tok);
  623. while (Tok.isNot(tok::eof));
  624. SmallVector<id_macro_pair, 128> MacrosByID;
  625. for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
  626. I != E; ++I) {
  627. if (I->first->hasMacroDefinition())
  628. MacrosByID.push_back(id_macro_pair(I->first, I->second->getMacroInfo()));
  629. }
  630. llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
  631. for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
  632. MacroInfo &MI = *MacrosByID[i].second;
  633. // Ignore computed macros like __LINE__ and friends.
  634. if (MI.isBuiltinMacro()) continue;
  635. PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
  636. *OS << '\n';
  637. }
  638. }
  639. /// DoPrintPreprocessedInput - This implements -E mode.
  640. ///
  641. void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
  642. const PreprocessorOutputOptions &Opts) {
  643. // Show macros with no output is handled specially.
  644. if (!Opts.ShowCPP) {
  645. assert(Opts.ShowMacros && "Not yet implemented!");
  646. DoPrintMacros(PP, OS);
  647. return;
  648. }
  649. // Inform the preprocessor whether we want it to retain comments or not, due
  650. // to -C or -CC.
  651. PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
  652. PrintPPOutputPPCallbacks *Callbacks =
  653. new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
  654. Opts.ShowMacros);
  655. PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
  656. PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
  657. PP.AddPragmaHandler("clang",
  658. new UnknownPragmaHandler("#pragma clang", Callbacks));
  659. PP.addPPCallbacks(Callbacks);
  660. // After we have configured the preprocessor, enter the main file.
  661. PP.EnterMainSourceFile();
  662. // Consume all of the tokens that come from the predefines buffer. Those
  663. // should not be emitted into the output and are guaranteed to be at the
  664. // start.
  665. const SourceManager &SourceMgr = PP.getSourceManager();
  666. Token Tok;
  667. do {
  668. PP.Lex(Tok);
  669. if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
  670. break;
  671. PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
  672. if (PLoc.isInvalid())
  673. break;
  674. if (strcmp(PLoc.getFilename(), "<built-in>"))
  675. break;
  676. } while (true);
  677. // Read all the preprocessed tokens, printing them out to the stream.
  678. PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
  679. *OS << '\n';
  680. }