blob: 8ca36489ee465e730db11a5c4a614c33661b4a67 [file] [log] [blame]
Chris Lattner09e3cdf2006-07-04 19:04:05 +00001//===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner09e3cdf2006-07-04 19:04:05 +00007//
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
Eli Friedman16b7b6f2009-05-19 04:14:29 +000015#include "clang/Frontend/Utils.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000016#include "clang/Basic/CharInfo.h"
Daniel Dunbar531f6c62009-11-11 10:07:22 +000017#include "clang/Basic/Diagnostic.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Frontend/PreprocessorOutputOptions.h"
Chris Lattner1630c3c2009-02-06 06:45:26 +000020#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000021#include "clang/Lex/PPCallbacks.h"
Chris Lattner09e3cdf2006-07-04 19:04:05 +000022#include "clang/Lex/Pragma.h"
Daniel Dunbar531f6c62009-11-11 10:07:22 +000023#include "clang/Lex/Preprocessor.h"
Chris Lattner644d4522009-02-13 00:46:04 +000024#include "clang/Lex/TokenConcatenation.h"
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +000025#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "llvm/ADT/SmallString.h"
Chris Lattner30c924b2010-06-26 17:11:39 +000027#include "llvm/ADT/StringRef.h"
Douglas Gregor3bde9b12011-06-22 19:41:48 +000028#include "llvm/Support/ErrorHandling.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerdeb37012006-07-04 19:24:06 +000030#include <cstdio>
Chris Lattner09e3cdf2006-07-04 19:04:05 +000031using namespace clang;
32
Chris Lattnercac63f32009-04-12 01:56:53 +000033/// PrintMacroDefinition - Print a macro definition in a form that will be
34/// properly accepted back as a definition.
35static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000036 Preprocessor &PP, raw_ostream &OS) {
Chris Lattnercac63f32009-04-12 01:56:53 +000037 OS << "#define " << II.getName();
Mike Stump11289f42009-09-09 15:08:12 +000038
Chris Lattnercac63f32009-04-12 01:56:53 +000039 if (MI.isFunctionLike()) {
40 OS << '(';
Chris Lattner53d80e22009-12-09 02:08:14 +000041 if (!MI.arg_empty()) {
Chris Lattnercac63f32009-04-12 01:56:53 +000042 MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
Chris Lattner53d80e22009-12-09 02:08:14 +000043 for (; AI+1 != E; ++AI) {
44 OS << (*AI)->getName();
Chris Lattner9dfed9f2009-12-07 01:58:34 +000045 OS << ',';
Chris Lattner9dfed9f2009-12-07 01:58:34 +000046 }
Chris Lattner53d80e22009-12-09 02:08:14 +000047
48 // Last argument.
49 if ((*AI)->getName() == "__VA_ARGS__")
50 OS << "...";
51 else
52 OS << (*AI)->getName();
Chris Lattnercac63f32009-04-12 01:56:53 +000053 }
Mike Stump11289f42009-09-09 15:08:12 +000054
Chris Lattner9dfed9f2009-12-07 01:58:34 +000055 if (MI.isGNUVarargs())
56 OS << "..."; // #define foo(x...)
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +000057
Chris Lattnercac63f32009-04-12 01:56:53 +000058 OS << ')';
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Chris Lattnercac63f32009-04-12 01:56:53 +000061 // GCC always emits a space, even if the macro body is empty. However, do not
62 // want to emit two spaces if the first token has a leading space.
63 if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
64 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +000065
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000066 SmallString<128> SpellingBuffer;
Chris Lattnercac63f32009-04-12 01:56:53 +000067 for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end();
68 I != E; ++I) {
69 if (I->hasLeadingSpace())
70 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +000071
Benjamin Kramer0a1abd42010-02-27 13:44:12 +000072 OS << PP.getSpelling(*I, SpellingBuffer);
Chris Lattnercac63f32009-04-12 01:56:53 +000073 }
74}
75
Chris Lattnerf46be6c2006-07-04 22:19:33 +000076//===----------------------------------------------------------------------===//
77// Preprocessed token printer
78//===----------------------------------------------------------------------===//
79
Chris Lattner87f267e2006-11-21 05:02:33 +000080namespace {
81class PrintPPOutputPPCallbacks : public PPCallbacks {
82 Preprocessor &PP;
Chris Lattner9d94f042010-04-13 00:06:42 +000083 SourceManager &SM;
Chris Lattner644d4522009-02-13 00:46:04 +000084 TokenConcatenation ConcatInfo;
Chris Lattner068529a2008-08-17 03:12:02 +000085public:
Chris Lattner0e62c1c2011-07-23 10:55:15 +000086 raw_ostream &OS;
Chris Lattner068529a2008-08-17 03:12:02 +000087private:
Chris Lattner87f267e2006-11-21 05:02:33 +000088 unsigned CurLine;
Daniel Dunbard4352752010-08-24 22:44:13 +000089
Chris Lattner87f267e2006-11-21 05:02:33 +000090 bool EmittedTokensOnThisLine;
Jordan Rose127f6ee2012-06-15 23:33:51 +000091 bool EmittedDirectiveOnThisLine;
Chris Lattner66a740e2008-10-27 01:19:25 +000092 SrcMgr::CharacteristicKind FileType;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000093 SmallString<512> CurFilename;
Daniel Dunbar98e0e532008-09-05 03:22:57 +000094 bool Initialized;
Eli Friedman6af494b2009-05-19 03:06:47 +000095 bool DisableLineMarkers;
96 bool DumpDefines;
Reid Kleckner1df0fea2015-02-26 00:17:25 +000097 bool UseLineDirectives;
Daniel Dunbar5d388752012-11-16 01:51:11 +000098 bool IsFirstFileEntered;
Chris Lattner87f267e2006-11-21 05:02:33 +000099public:
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000100 PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os, bool lineMarkers,
101 bool defines, bool UseLineDirectives)
102 : PP(pp), SM(PP.getSourceManager()), ConcatInfo(PP), OS(os),
103 DisableLineMarkers(lineMarkers), DumpDefines(defines),
104 UseLineDirectives(UseLineDirectives) {
Daniel Dunbar27734fd2011-02-02 15:41:17 +0000105 CurLine = 0;
Chris Lattner4c4a2452007-07-24 06:57:14 +0000106 CurFilename += "<uninit>";
Chris Lattner87f267e2006-11-21 05:02:33 +0000107 EmittedTokensOnThisLine = false;
Jordan Rose127f6ee2012-06-15 23:33:51 +0000108 EmittedDirectiveOnThisLine = false;
Chris Lattnerb03dc762008-09-26 21:18:42 +0000109 FileType = SrcMgr::C_User;
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000110 Initialized = false;
Daniel Dunbar5d388752012-11-16 01:51:11 +0000111 IsFirstFileEntered = false;
Chris Lattner87f267e2006-11-21 05:02:33 +0000112 }
Mike Stump11289f42009-09-09 15:08:12 +0000113
Jordan Rose127f6ee2012-06-15 23:33:51 +0000114 void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattner4418ce12007-07-23 06:09:34 +0000115 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Mike Stump11289f42009-09-09 15:08:12 +0000116
Jordan Rose127f6ee2012-06-15 23:33:51 +0000117 void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
118 bool hasEmittedDirectiveOnThisLine() const {
119 return EmittedDirectiveOnThisLine;
120 }
121
122 bool startNewLineIfNeeded(bool ShouldUpdateCurrentLine = true);
Craig Topperafa7cb32014-03-13 06:07:04 +0000123
124 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
125 SrcMgr::CharacteristicKind FileType,
126 FileID PrevFID) override;
127 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
128 StringRef FileName, bool IsAngled,
129 CharSourceRange FilenameRange, const FileEntry *File,
130 StringRef SearchPath, StringRef RelativePath,
131 const Module *Imported) override;
132 void Ident(SourceLocation Loc, const std::string &str) override;
Craig Topperafa7cb32014-03-13 06:07:04 +0000133 void PragmaMessage(SourceLocation Loc, StringRef Namespace,
134 PragmaMessageKind Kind, StringRef Str) override;
135 void PragmaDebug(SourceLocation Loc, StringRef DebugType) override;
136 void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override;
137 void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override;
138 void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
Alp Tokerc726c362014-06-10 09:31:37 +0000139 diag::Severity Map, StringRef Str) override;
Craig Topperafa7cb32014-03-13 06:07:04 +0000140 void PragmaWarning(SourceLocation Loc, StringRef WarningSpec,
141 ArrayRef<int> Ids) override;
142 void PragmaWarningPush(SourceLocation Loc, int Level) override;
143 void PragmaWarningPop(SourceLocation Loc) override;
Chris Lattner87f267e2006-11-21 05:02:33 +0000144
Chris Lattner3ed83c12007-12-09 21:11:08 +0000145 bool HandleFirstTokOnLine(Token &Tok);
Hal Finkel2109f232013-01-28 04:37:37 +0000146
147 /// Move to the line of the provided source location. This will
148 /// return true if the output stream required adjustment or if
149 /// the requested location is on the first line.
Chris Lattner5dbefc62010-04-13 00:01:41 +0000150 bool MoveToLine(SourceLocation Loc) {
Douglas Gregor453b0122010-11-12 07:15:47 +0000151 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
152 if (PLoc.isInvalid())
153 return false;
Hal Finkel2109f232013-01-28 04:37:37 +0000154 return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
Chris Lattner5dbefc62010-04-13 00:01:41 +0000155 }
156 bool MoveToLine(unsigned LineNo);
157
Chris Lattner0384e6352010-04-14 03:57:19 +0000158 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
159 const Token &Tok) {
160 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
Chris Lattner644d4522009-02-13 00:46:04 +0000161 }
Craig Topper49a27902014-05-22 04:46:25 +0000162 void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
163 unsigned ExtraLen=0);
Douglas Gregorc7d65762010-09-09 22:45:38 +0000164 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000165 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump11289f42009-09-09 15:08:12 +0000166
Chris Lattnercac63f32009-04-12 01:56:53 +0000167 /// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Topperafa7cb32014-03-13 06:07:04 +0000168 void MacroDefined(const Token &MacroNameTok,
169 const MacroDirective *MD) override;
Mike Stump11289f42009-09-09 15:08:12 +0000170
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000171 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
Craig Topperafa7cb32014-03-13 06:07:04 +0000172 void MacroUndefined(const Token &MacroNameTok,
Richard Smith36bd40d2015-05-04 03:15:40 +0000173 const MacroDefinition &MD) override;
Chris Lattner87f267e2006-11-21 05:02:33 +0000174};
Chris Lattner21632652008-04-08 04:16:20 +0000175} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000176
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000177void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
178 const char *Extra,
179 unsigned ExtraLen) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000180 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000181
Chris Lattner76b44452009-12-07 01:42:56 +0000182 // Emit #line directives or GNU line markers depending on what mode we're in.
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000183 if (UseLineDirectives) {
Chris Lattner76b44452009-12-07 01:42:56 +0000184 OS << "#line" << ' ' << LineNo << ' ' << '"';
Eli Friedman80e45b82013-08-29 01:42:42 +0000185 OS.write_escaped(CurFilename);
Chris Lattner76b44452009-12-07 01:42:56 +0000186 OS << '"';
187 } else {
188 OS << '#' << ' ' << LineNo << ' ' << '"';
Eli Friedman80e45b82013-08-29 01:42:42 +0000189 OS.write_escaped(CurFilename);
Chris Lattner76b44452009-12-07 01:42:56 +0000190 OS << '"';
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +0000191
Steve Naroff66aaa392009-12-06 01:02:14 +0000192 if (ExtraLen)
193 OS.write(Extra, ExtraLen);
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000194
Steve Naroff66aaa392009-12-06 01:02:14 +0000195 if (FileType == SrcMgr::C_System)
196 OS.write(" 3", 2);
197 else if (FileType == SrcMgr::C_ExternCSystem)
198 OS.write(" 3 4", 4);
199 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000200 OS << '\n';
201}
202
Chris Lattner728b4dc2006-07-04 21:28:37 +0000203/// MoveToLine - Move the output to the source line specified by the location
204/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner3ed83c12007-12-09 21:11:08 +0000205/// #line directive. This returns false if already at the specified line, true
206/// if some newlines were emitted.
Chris Lattner5dbefc62010-04-13 00:01:41 +0000207bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000208 // If this line is "close enough" to the original line, just print newlines,
209 // otherwise print a #line directive.
Daniel Dunbare7781312008-09-26 01:13:35 +0000210 if (LineNo-CurLine <= 8) {
Chris Lattner5f075822007-07-23 05:14:05 +0000211 if (LineNo-CurLine == 1)
Chris Lattner068529a2008-08-17 03:12:02 +0000212 OS << '\n';
Chris Lattner3ed83c12007-12-09 21:11:08 +0000213 else if (LineNo == CurLine)
Chandler Carruth46a32c22011-07-14 16:14:52 +0000214 return false; // Spelling line moved, but expansion line didn't.
Chris Lattner5f075822007-07-23 05:14:05 +0000215 else {
216 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattner068529a2008-08-17 03:12:02 +0000217 OS.write(NewLines, LineNo-CurLine);
Chris Lattner5f075822007-07-23 05:14:05 +0000218 }
Chris Lattnerbc6bcab2010-06-12 16:20:56 +0000219 } else if (!DisableLineMarkers) {
220 // Emit a #line or line marker.
Craig Topper49a27902014-05-22 04:46:25 +0000221 WriteLineInfo(LineNo, nullptr, 0);
Chris Lattnerbc6bcab2010-06-12 16:20:56 +0000222 } else {
223 // Okay, we're in -P mode, which turns off line markers. However, we still
224 // need to emit a newline between tokens on different lines.
Jordan Rose127f6ee2012-06-15 23:33:51 +0000225 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Mike Stump11289f42009-09-09 15:08:12 +0000226 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000227
Mike Stump11289f42009-09-09 15:08:12 +0000228 CurLine = LineNo;
Chris Lattner3ed83c12007-12-09 21:11:08 +0000229 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000230}
231
Jordan Rose127f6ee2012-06-15 23:33:51 +0000232bool
233PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
234 if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
Douglas Gregorc7d65762010-09-09 22:45:38 +0000235 OS << '\n';
236 EmittedTokensOnThisLine = false;
Jordan Rose127f6ee2012-06-15 23:33:51 +0000237 EmittedDirectiveOnThisLine = false;
238 if (ShouldUpdateCurrentLine)
239 ++CurLine;
Douglas Gregorc7d65762010-09-09 22:45:38 +0000240 return true;
241 }
242
243 return false;
244}
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000245
246/// FileChanged - Whenever the preprocessor enters or exits a #include file
247/// it invokes this handler. Update our conception of the current source
248/// position.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000249void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
250 FileChangeReason Reason,
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000251 SrcMgr::CharacteristicKind NewFileType,
252 FileID PrevFID) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000253 // Unless we are exiting a #include, make sure to skip ahead to the line the
254 // #include directive was at.
Chris Lattner9d94f042010-04-13 00:06:42 +0000255 SourceManager &SourceMgr = SM;
Chris Lattner5dbefc62010-04-13 00:01:41 +0000256
257 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Douglas Gregor453b0122010-11-12 07:15:47 +0000258 if (UserLoc.isInvalid())
259 return;
260
Chris Lattnerc745cec2010-04-14 04:28:50 +0000261 unsigned NewLine = UserLoc.getLine();
Daniel Dunbard4352752010-08-24 22:44:13 +0000262
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000263 if (Reason == PPCallbacks::EnterFile) {
Douglas Gregor453b0122010-11-12 07:15:47 +0000264 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
Chris Lattnerd8cc8842009-01-30 18:44:17 +0000265 if (IncludeLoc.isValid())
266 MoveToLine(IncludeLoc);
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000267 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
Jordan Rose111c4a62013-04-17 19:09:18 +0000268 // GCC emits the # directive for this directive on the line AFTER the
269 // directive and emits a bunch of spaces that aren't needed. This is because
270 // otherwise we will emit a line marker for THIS line, which requires an
271 // extra blank line after the directive to avoid making all following lines
272 // off by one. We can do better by simply incrementing NewLine here.
273 NewLine += 1;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000274 }
Chris Lattner5dbefc62010-04-13 00:01:41 +0000275
276 CurLine = NewLine;
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000277
Chris Lattner4c4a2452007-07-24 06:57:14 +0000278 CurFilename.clear();
Chris Lattner5dbefc62010-04-13 00:01:41 +0000279 CurFilename += UserLoc.getFilename();
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000280 FileType = NewFileType;
281
Eli Friedmanc52435b2013-01-09 03:16:42 +0000282 if (DisableLineMarkers) {
283 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
284 return;
285 }
Daniel Dunbard4352752010-08-24 22:44:13 +0000286
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000287 if (!Initialized) {
288 WriteLineInfo(CurLine);
289 Initialized = true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000290 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000291
Daniel Dunbar5d388752012-11-16 01:51:11 +0000292 // Do not emit an enter marker for the main file (which we expect is the first
293 // entered file). This matches gcc, and improves compatibility with some tools
294 // which track the # line markers as a way to determine when the preprocessed
295 // output is in the context of the main file.
296 if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
297 IsFirstFileEntered = true;
298 return;
299 }
300
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000301 switch (Reason) {
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000302 case PPCallbacks::EnterFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000303 WriteLineInfo(CurLine, " 1", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000304 break;
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000305 case PPCallbacks::ExitFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000306 WriteLineInfo(CurLine, " 2", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000307 break;
Mike Stump11289f42009-09-09 15:08:12 +0000308 case PPCallbacks::SystemHeaderPragma:
309 case PPCallbacks::RenameFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000310 WriteLineInfo(CurLine);
311 break;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000312 }
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000313}
314
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000315void PrintPPOutputPPCallbacks::InclusionDirective(SourceLocation HashLoc,
316 const Token &IncludeTok,
317 StringRef FileName,
318 bool IsAngled,
319 CharSourceRange FilenameRange,
320 const FileEntry *File,
321 StringRef SearchPath,
322 StringRef RelativePath,
323 const Module *Imported) {
324 // When preprocessing, turn implicit imports into @imports.
325 // FIXME: This is a stop-gap until a more comprehensive "preprocessing with
326 // modules" solution is introduced.
327 if (Imported) {
328 startNewLineIfNeeded();
329 MoveToLine(HashLoc);
330 OS << "@import " << Imported->getFullModuleName() << ";"
331 << " /* clang -E: implicit import for \"" << File->getName() << "\" */";
Ben Langmuir5418f402014-09-10 21:29:41 +0000332 // Since we want a newline after the @import, but not a #<line>, start a new
333 // line immediately.
Argyrios Kyrtzidisc3b4b792013-04-29 17:26:22 +0000334 EmittedTokensOnThisLine = true;
Ben Langmuir5418f402014-09-10 21:29:41 +0000335 startNewLineIfNeeded();
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000336 }
337}
338
Chris Lattner5eef5072009-01-16 19:25:54 +0000339/// Ident - Handle #ident directives when read by the preprocessor.
Chris Lattner728b4dc2006-07-04 21:28:37 +0000340///
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000341void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
Chris Lattner3338ba82006-07-04 21:19:39 +0000342 MoveToLine(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000343
Chris Lattner068529a2008-08-17 03:12:02 +0000344 OS.write("#ident ", strlen("#ident "));
345 OS.write(&S[0], S.size());
Chris Lattner87f267e2006-11-21 05:02:33 +0000346 EmittedTokensOnThisLine = true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000347}
348
Chris Lattnercac63f32009-04-12 01:56:53 +0000349/// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000350void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000351 const MacroDirective *MD) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000352 const MacroInfo *MI = MD->getMacroInfo();
Chris Lattnercac63f32009-04-12 01:56:53 +0000353 // Only print out macro definitions in -dD mode.
354 if (!DumpDefines ||
355 // Ignore __FILE__ etc.
356 MI->isBuiltinMacro()) return;
Mike Stump11289f42009-09-09 15:08:12 +0000357
Chris Lattnercac63f32009-04-12 01:56:53 +0000358 MoveToLine(MI->getDefinitionLoc());
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000359 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
Jordan Rose127f6ee2012-06-15 23:33:51 +0000360 setEmittedDirectiveOnThisLine();
Chris Lattnercac63f32009-04-12 01:56:53 +0000361}
362
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000363void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
Richard Smith36bd40d2015-05-04 03:15:40 +0000364 const MacroDefinition &MD) {
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000365 // Only print out macro definitions in -dD mode.
366 if (!DumpDefines) return;
367
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000368 MoveToLine(MacroNameTok.getLocation());
369 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
Jordan Rose127f6ee2012-06-15 23:33:51 +0000370 setEmittedDirectiveOnThisLine();
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000371}
Chris Lattnercac63f32009-04-12 01:56:53 +0000372
Aaron Ballman5d041be2013-06-04 02:07:14 +0000373static void outputPrintable(llvm::raw_ostream& OS,
Chris Lattner5eef5072009-01-16 19:25:54 +0000374 const std::string &Str) {
Chris Lattner5eef5072009-01-16 19:25:54 +0000375 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
376 unsigned char Char = Str[i];
Jordan Rosea7d03842013-02-08 22:30:41 +0000377 if (isPrintable(Char) && Char != '\\' && Char != '"')
Chris Lattner5eef5072009-01-16 19:25:54 +0000378 OS << (char)Char;
379 else // Output anything hard as an octal escape.
380 OS << '\\'
381 << (char)('0'+ ((Char >> 6) & 7))
382 << (char)('0'+ ((Char >> 3) & 7))
383 << (char)('0'+ ((Char >> 0) & 7));
384 }
Aaron Ballman5d041be2013-06-04 02:07:14 +0000385}
386
Chris Lattner30c924b2010-06-26 17:11:39 +0000387void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000388 StringRef Namespace,
389 PragmaMessageKind Kind,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000390 StringRef Str) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000391 startNewLineIfNeeded();
Chris Lattner30c924b2010-06-26 17:11:39 +0000392 MoveToLine(Loc);
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000393 OS << "#pragma ";
394 if (!Namespace.empty())
395 OS << Namespace << ' ';
396 switch (Kind) {
397 case PMK_Message:
Andy Gibbsaa0b94a2013-04-19 17:13:17 +0000398 OS << "message(\"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000399 break;
400 case PMK_Warning:
Andy Gibbs96d93902013-04-18 16:49:37 +0000401 OS << "warning \"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000402 break;
403 case PMK_Error:
Andy Gibbs96d93902013-04-18 16:49:37 +0000404 OS << "error \"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000405 break;
406 }
Chris Lattner30c924b2010-06-26 17:11:39 +0000407
Aaron Ballman5d041be2013-06-04 02:07:14 +0000408 outputPrintable(OS, Str);
Chris Lattner30c924b2010-06-26 17:11:39 +0000409 OS << '"';
Andy Gibbsaa0b94a2013-04-19 17:13:17 +0000410 if (Kind == PMK_Message)
411 OS << ')';
Jordan Rose127f6ee2012-06-15 23:33:51 +0000412 setEmittedDirectiveOnThisLine();
Chris Lattner30c924b2010-06-26 17:11:39 +0000413}
414
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000415void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
416 StringRef DebugType) {
417 startNewLineIfNeeded();
418 MoveToLine(Loc);
419
420 OS << "#pragma clang __debug ";
421 OS << DebugType;
422
423 setEmittedDirectiveOnThisLine();
424}
425
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000426void PrintPPOutputPPCallbacks::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000427PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000428 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000429 MoveToLine(Loc);
430 OS << "#pragma " << Namespace << " diagnostic push";
Jordan Rose127f6ee2012-06-15 23:33:51 +0000431 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000432}
433
434void PrintPPOutputPPCallbacks::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000435PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000436 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000437 MoveToLine(Loc);
438 OS << "#pragma " << Namespace << " diagnostic pop";
Jordan Rose127f6ee2012-06-15 23:33:51 +0000439 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000440}
441
Alp Tokerc726c362014-06-10 09:31:37 +0000442void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
443 StringRef Namespace,
444 diag::Severity Map,
445 StringRef Str) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000446 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000447 MoveToLine(Loc);
448 OS << "#pragma " << Namespace << " diagnostic ";
Benjamin Kramer7ec12c92012-02-07 22:29:24 +0000449 switch (Map) {
Alp Toker46df1c02014-06-12 10:15:20 +0000450 case diag::Severity::Remark:
Tobias Grosser74160242014-02-28 09:11:08 +0000451 OS << "remark";
452 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000453 case diag::Severity::Warning:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000454 OS << "warning";
455 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000456 case diag::Severity::Error:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000457 OS << "error";
458 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000459 case diag::Severity::Ignored:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000460 OS << "ignored";
461 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000462 case diag::Severity::Fatal:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000463 OS << "fatal";
464 break;
465 }
466 OS << " \"" << Str << '"';
Jordan Rose127f6ee2012-06-15 23:33:51 +0000467 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000468}
Chris Lattner5eef5072009-01-16 19:25:54 +0000469
Reid Kleckner881dff32013-09-13 22:00:30 +0000470void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
471 StringRef WarningSpec,
472 ArrayRef<int> Ids) {
473 startNewLineIfNeeded();
474 MoveToLine(Loc);
475 OS << "#pragma warning(" << WarningSpec << ':';
476 for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
477 OS << ' ' << *I;
478 OS << ')';
479 setEmittedDirectiveOnThisLine();
480}
481
482void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
483 int Level) {
484 startNewLineIfNeeded();
485 MoveToLine(Loc);
486 OS << "#pragma warning(push";
Reid Kleckner4d185102013-10-02 15:19:23 +0000487 if (Level >= 0)
Reid Kleckner881dff32013-09-13 22:00:30 +0000488 OS << ", " << Level;
489 OS << ')';
490 setEmittedDirectiveOnThisLine();
491}
492
493void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
494 startNewLineIfNeeded();
495 MoveToLine(Loc);
496 OS << "#pragma warning(pop)";
497 setEmittedDirectiveOnThisLine();
498}
499
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000500/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner3ed83c12007-12-09 21:11:08 +0000501/// is called for the first token on each new line. If this really is the start
502/// of a new logical line, handle it and return true, otherwise return false.
503/// This may not be the start of a logical line because the "start of line"
Chandler Carruth46a32c22011-07-14 16:14:52 +0000504/// marker is set for spelling lines, not expansion ones.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000505bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000506 // Figure out what line we went to and insert the appropriate number of
507 // newline characters.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000508 if (!MoveToLine(Tok.getLocation()))
509 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000510
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000511 // Print out space characters so that the first token on a line is
512 // indented for easy reading.
Chandler Carruth42f35f92011-07-25 20:57:57 +0000513 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000514
Richard Smith5b2f7c52014-02-24 20:50:36 +0000515 // The first token on a line can have a column number of 1, yet still expect
516 // leading white space, if a macro expansion in column 1 starts with an empty
517 // macro argument, or an empty nested macro expansion. In this case, move the
518 // token to column 2.
519 if (ColNo == 1 && Tok.hasLeadingSpace())
520 ColNo = 2;
521
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000522 // 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.
Chris Lattner3c69f122007-10-09 18:03:42 +0000528 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattner068529a2008-08-17 03:12:02 +0000529 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000530
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000531 // Otherwise, indent the appropriate number of spaces.
532 for (; ColNo > 1; --ColNo)
Chris Lattner068529a2008-08-17 03:12:02 +0000533 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000534
Chris Lattner3ed83c12007-12-09 21:11:08 +0000535 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000536}
537
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000538void 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;
Mike Stump11289f42009-09-09 15:08:12 +0000545
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000546 ++NumNewlines;
Mike Stump11289f42009-09-09 15:08:12 +0000547
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000548 // If we have \n\r or \r\n, skip both and count as one line.
549 if (Len != 1 &&
550 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
551 TokStr[0] != TokStr[1])
552 ++TokStr, --Len;
553 }
Mike Stump11289f42009-09-09 15:08:12 +0000554
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000555 if (NumNewlines == 0) return;
Mike Stump11289f42009-09-09 15:08:12 +0000556
Chris Lattnera5e67752009-06-15 04:08:28 +0000557 CurLine += NumNewlines;
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000558}
559
560
Chris Lattner5de858c2006-07-04 19:04:44 +0000561namespace {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000562struct UnknownPragmaHandler : public PragmaHandler {
563 const char *Prefix;
Chris Lattner87f267e2006-11-21 05:02:33 +0000564 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump11289f42009-09-09 15:08:12 +0000565
Chris Lattner87f267e2006-11-21 05:02:33 +0000566 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000567 : Prefix(prefix), Callbacks(callbacks) {}
Craig Topperafa7cb32014-03-13 06:07:04 +0000568 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
569 Token &PragmaTok) override {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000570 // Figure out what line we went to and insert the appropriate number of
571 // newline characters.
Jordan Rose127f6ee2012-06-15 23:33:51 +0000572 Callbacks->startNewLineIfNeeded();
Chris Lattner87f267e2006-11-21 05:02:33 +0000573 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattner068529a2008-08-17 03:12:02 +0000574 Callbacks->OS.write(Prefix, strlen(Prefix));
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000575 // Read and print all of the pragma tokens.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000576 while (PragmaTok.isNot(tok::eod)) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000577 if (PragmaTok.hasLeadingSpace())
Chris Lattner068529a2008-08-17 03:12:02 +0000578 Callbacks->OS << ' ';
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000579 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattner068529a2008-08-17 03:12:02 +0000580 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Kleckner0e73ec42014-02-20 22:59:51 +0000581
582 // Expand macros in pragmas with -fms-extensions. The assumption is that
583 // the majority of pragmas in such a file will be Microsoft pragmas.
584 if (PP.getLangOpts().MicrosoftExt)
585 PP.Lex(PragmaTok);
586 else
587 PP.LexUnexpandedToken(PragmaTok);
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000588 }
Jordan Rose127f6ee2012-06-15 23:33:51 +0000589 Callbacks->setEmittedDirectiveOnThisLine();
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000590 }
591};
Chris Lattner5de858c2006-07-04 19:04:44 +0000592} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000593
Chris Lattner4418ce12007-07-23 06:09:34 +0000594
Chris Lattnerfc001b02009-02-06 05:56:11 +0000595static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
596 PrintPPOutputPPCallbacks *Callbacks,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000597 raw_ostream &OS) {
Jordan Rose67b66232013-03-05 23:54:55 +0000598 bool DropComments = PP.getLangOpts().TraditionalCPP &&
599 !PP.getCommentRetentionState();
600
Benjamin Kramer718f7222010-02-27 18:02:51 +0000601 char Buffer[256];
Chris Lattnerbba37f42010-06-15 21:06:38 +0000602 Token PrevPrevTok, PrevTok;
603 PrevPrevTok.startToken();
604 PrevTok.startToken();
Chris Lattner3ff2e692007-10-10 20:45:16 +0000605 while (1) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000606 if (Callbacks->hasEmittedDirectiveOnThisLine()) {
607 Callbacks->startNewLineIfNeeded();
608 Callbacks->MoveToLine(Tok.getLocation());
609 }
Mike Stump11289f42009-09-09 15:08:12 +0000610
Chris Lattner67c38482006-07-04 23:24:26 +0000611 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000612 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
613 // done.
Mike Stump11289f42009-09-09 15:08:12 +0000614 } else if (Tok.hasLeadingSpace() ||
Chris Lattner4418ce12007-07-23 06:09:34 +0000615 // If we haven't emitted a token on this line yet, PrevTok isn't
616 // useful to look at and no concatenation could happen anyway.
Chris Lattnerd63c8a52007-07-23 23:21:34 +0000617 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattner4418ce12007-07-23 06:09:34 +0000618 // Don't print "-" next to "-", it would form "--".
Chris Lattner0384e6352010-04-14 03:57:19 +0000619 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattner068529a2008-08-17 03:12:02 +0000620 OS << ' ';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000621 }
Mike Stump11289f42009-09-09 15:08:12 +0000622
Jordan Rose67b66232013-03-05 23:54:55 +0000623 if (DropComments && Tok.is(tok::comment)) {
624 // Skip comments. Normally the preprocessor does not generate
625 // tok::comment nodes at all when not keeping comments, but under
626 // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
627 SourceLocation StartLoc = Tok.getLocation();
628 Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
Ben Langmuir5eb7cb72014-01-30 21:50:18 +0000629 } else if (Tok.is(tok::annot_module_include) ||
630 Tok.is(tok::annot_module_begin) ||
631 Tok.is(tok::annot_module_end)) {
632 // PrintPPOutputPPCallbacks::InclusionDirective handles producing
633 // appropriate output here. Ignore this token entirely.
Richard Smithce587f52013-11-15 04:24:58 +0000634 PP.Lex(Tok);
635 continue;
Jordan Rose67b66232013-03-05 23:54:55 +0000636 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
Benjamin Kramer718f7222010-02-27 18:02:51 +0000637 OS << II->getName();
638 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
639 Tok.getLiteralData()) {
640 OS.write(Tok.getLiteralData(), Tok.getLength());
641 } else if (Tok.getLength() < 256) {
642 const char *TokPtr = Buffer;
643 unsigned Len = PP.getSpelling(Tok, TokPtr);
644 OS.write(TokPtr, Len);
Mike Stump11289f42009-09-09 15:08:12 +0000645
Benjamin Kramer718f7222010-02-27 18:02:51 +0000646 // Tokens that can contain embedded newlines need to adjust our current
647 // line number.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000648 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramer718f7222010-02-27 18:02:51 +0000649 Callbacks->HandleNewlinesInToken(TokPtr, Len);
650 } else {
651 std::string S = PP.getSpelling(Tok);
652 OS.write(&S[0], S.size());
653
654 // Tokens that can contain embedded newlines need to adjust our current
655 // line number.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000656 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramer718f7222010-02-27 18:02:51 +0000657 Callbacks->HandleNewlinesInToken(&S[0], S.size());
658 }
Jordan Rose127f6ee2012-06-15 23:33:51 +0000659 Callbacks->setEmittedTokensOnThisLine();
Mike Stump11289f42009-09-09 15:08:12 +0000660
Chris Lattner3ff2e692007-10-10 20:45:16 +0000661 if (Tok.is(tok::eof)) break;
Mike Stump11289f42009-09-09 15:08:12 +0000662
Chris Lattner0384e6352010-04-14 03:57:19 +0000663 PrevPrevTok = PrevTok;
Chris Lattner3ff2e692007-10-10 20:45:16 +0000664 PrevTok = Tok;
665 PP.Lex(Tok);
666 }
Chris Lattnerfc001b02009-02-06 05:56:11 +0000667}
668
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000669typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
670static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
671 return LHS->first->getName().compare(RHS->first->getName());
672}
673
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000674static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
Daniel Dunbard839e772010-06-11 20:10:12 +0000675 // Ignore unknown pragmas.
Lubos Lunak576a0412014-05-01 12:54:03 +0000676 PP.IgnorePragmas();
Daniel Dunbard839e772010-06-11 20:10:12 +0000677
Eli Friedman26c672b2009-05-19 01:32:34 +0000678 // -dM mode just scans and ignores all tokens in the files, then dumps out
679 // the macro table at the end.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000680 PP.EnterMainSourceFile();
Eli Friedman26c672b2009-05-19 01:32:34 +0000681
682 Token Tok;
683 do PP.Lex(Tok);
684 while (Tok.isNot(tok::eof));
685
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000686 SmallVector<id_macro_pair, 128> MacrosByID;
687 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
688 I != E; ++I) {
Richard Smith20e883e2015-04-29 23:20:19 +0000689 auto *MD = I->second.getLatest();
690 if (MD && MD->isDefined())
691 MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000692 }
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000693 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedman26c672b2009-05-19 01:32:34 +0000694
695 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
696 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000697 // Ignore computed macros like __LINE__ and friends.
Eli Friedman26c672b2009-05-19 01:32:34 +0000698 if (MI.isBuiltinMacro()) continue;
699
700 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +0000701 *OS << '\n';
Eli Friedman26c672b2009-05-19 01:32:34 +0000702 }
703}
704
Chris Lattnerfc001b02009-02-06 05:56:11 +0000705/// DoPrintPreprocessedInput - This implements -E mode.
706///
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000707void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
Daniel Dunbar22bdabf2009-11-11 10:07:44 +0000708 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000709 // Show macros with no output is handled specially.
710 if (!Opts.ShowCPP) {
711 assert(Opts.ShowMacros && "Not yet implemented!");
712 DoPrintMacros(PP, OS);
713 return;
714 }
715
Chris Lattnerfc001b02009-02-06 05:56:11 +0000716 // Inform the preprocessor whether we want it to retain comments or not, due
717 // to -C or -CC.
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000718 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanfcb57d52009-05-19 01:02:07 +0000719
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000720 PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
721 PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros, Opts.UseLineDirectives);
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000722 PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
Chris Lattner49609d52010-11-10 01:00:49 +0000723 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
724 PP.AddPragmaHandler("clang",
725 new UnknownPragmaHandler("#pragma clang", Callbacks));
Chris Lattnerfc001b02009-02-06 05:56:11 +0000726
Craig Topperb8a70532014-09-10 04:53:53 +0000727 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
Chris Lattnerfc001b02009-02-06 05:56:11 +0000728
Eli Friedman26c672b2009-05-19 01:32:34 +0000729 // After we have configured the preprocessor, enter the main file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000730 PP.EnterMainSourceFile();
Chris Lattnerfc001b02009-02-06 05:56:11 +0000731
Eli Friedman26c672b2009-05-19 01:32:34 +0000732 // Consume all of the tokens that come from the predefines buffer. Those
733 // should not be emitted into the output and are guaranteed to be at the
734 // start.
735 const SourceManager &SourceMgr = PP.getSourceManager();
736 Token Tok;
Douglas Gregor453b0122010-11-12 07:15:47 +0000737 do {
738 PP.Lex(Tok);
739 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
740 break;
741
742 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
743 if (PLoc.isInvalid())
744 break;
745
746 if (strcmp(PLoc.getFilename(), "<built-in>"))
747 break;
748 } while (true);
Chris Lattnerfc001b02009-02-06 05:56:11 +0000749
Eli Friedman26c672b2009-05-19 01:32:34 +0000750 // Read all the preprocessed tokens, printing them out to the stream.
751 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
752 *OS << '\n';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000753}