blob: 20d7cd3a8c011cda1f57865fb7515beca8626d0b [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;
Chris Lattner76b44452009-12-07 01:42:56 +000097 bool UseLineDirective;
Daniel Dunbar5d388752012-11-16 01:51:11 +000098 bool IsFirstFileEntered;
Chris Lattner87f267e2006-11-21 05:02:33 +000099public:
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000100 PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os,
Daniel Dunbar27734fd2011-02-02 15:41:17 +0000101 bool lineMarkers, bool defines)
Chris Lattner9d94f042010-04-13 00:06:42 +0000102 : PP(pp), SM(PP.getSourceManager()),
103 ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
Daniel Dunbar27734fd2011-02-02 15:41:17 +0000104 DumpDefines(defines) {
105 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;
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +0000112
Chris Lattner76b44452009-12-07 01:42:56 +0000113 // If we're in microsoft mode, use normal #line instead of line markers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000114 UseLineDirective = PP.getLangOpts().MicrosoftExt;
Chris Lattner87f267e2006-11-21 05:02:33 +0000115 }
Mike Stump11289f42009-09-09 15:08:12 +0000116
Jordan Rose127f6ee2012-06-15 23:33:51 +0000117 void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattner4418ce12007-07-23 06:09:34 +0000118 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Mike Stump11289f42009-09-09 15:08:12 +0000119
Jordan Rose127f6ee2012-06-15 23:33:51 +0000120 void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
121 bool hasEmittedDirectiveOnThisLine() const {
122 return EmittedDirectiveOnThisLine;
123 }
124
125 bool startNewLineIfNeeded(bool ShouldUpdateCurrentLine = true);
Douglas Gregorc7d65762010-09-09 22:45:38 +0000126
Chris Lattner87f267e2006-11-21 05:02:33 +0000127 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000128 SrcMgr::CharacteristicKind FileType,
129 FileID PrevFID);
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000130 virtual void InclusionDirective(SourceLocation HashLoc,
131 const Token &IncludeTok,
132 StringRef FileName,
133 bool IsAngled,
134 CharSourceRange FilenameRange,
135 const FileEntry *File,
136 StringRef SearchPath,
137 StringRef RelativePath,
138 const Module *Imported);
Chris Lattner87f267e2006-11-21 05:02:33 +0000139 virtual void Ident(SourceLocation Loc, const std::string &str);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000140 virtual void PragmaCaptured(SourceLocation Loc, StringRef Str);
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000141 virtual void PragmaMessage(SourceLocation Loc, StringRef Namespace,
142 PragmaMessageKind Kind, StringRef Str);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000143 virtual void PragmaDebug(SourceLocation Loc, StringRef DebugType);
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000144 virtual void PragmaDiagnosticPush(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000145 StringRef Namespace);
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000146 virtual void PragmaDiagnosticPop(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000147 StringRef Namespace);
148 virtual void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
Benjamin Kramer7ec12c92012-02-07 22:29:24 +0000149 diag::Mapping Map, StringRef Str);
Reid Kleckner881dff32013-09-13 22:00:30 +0000150 virtual void PragmaWarning(SourceLocation Loc, StringRef WarningSpec,
151 ArrayRef<int> Ids);
152 virtual void PragmaWarningPush(SourceLocation Loc, int Level);
153 virtual void PragmaWarningPop(SourceLocation Loc);
Chris Lattner87f267e2006-11-21 05:02:33 +0000154
Chris Lattner3ed83c12007-12-09 21:11:08 +0000155 bool HandleFirstTokOnLine(Token &Tok);
Hal Finkel2109f232013-01-28 04:37:37 +0000156
157 /// Move to the line of the provided source location. This will
158 /// return true if the output stream required adjustment or if
159 /// the requested location is on the first line.
Chris Lattner5dbefc62010-04-13 00:01:41 +0000160 bool MoveToLine(SourceLocation Loc) {
Douglas Gregor453b0122010-11-12 07:15:47 +0000161 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
162 if (PLoc.isInvalid())
163 return false;
Hal Finkel2109f232013-01-28 04:37:37 +0000164 return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
Chris Lattner5dbefc62010-04-13 00:01:41 +0000165 }
166 bool MoveToLine(unsigned LineNo);
167
Chris Lattner0384e6352010-04-14 03:57:19 +0000168 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
169 const Token &Tok) {
170 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
Chris Lattner644d4522009-02-13 00:46:04 +0000171 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000172 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
Douglas Gregorc7d65762010-09-09 22:45:38 +0000173 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000174 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump11289f42009-09-09 15:08:12 +0000175
Chris Lattnercac63f32009-04-12 01:56:53 +0000176 /// MacroDefined - This hook is called whenever a macro definition is seen.
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000177 void MacroDefined(const Token &MacroNameTok, const MacroDirective *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000178
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000179 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000180 void MacroUndefined(const Token &MacroNameTok, const MacroDirective *MD);
Chris Lattner87f267e2006-11-21 05:02:33 +0000181};
Chris Lattner21632652008-04-08 04:16:20 +0000182} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000183
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000184void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
185 const char *Extra,
186 unsigned ExtraLen) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000187 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000188
Chris Lattner76b44452009-12-07 01:42:56 +0000189 // Emit #line directives or GNU line markers depending on what mode we're in.
190 if (UseLineDirective) {
191 OS << "#line" << ' ' << LineNo << ' ' << '"';
Eli Friedman80e45b82013-08-29 01:42:42 +0000192 OS.write_escaped(CurFilename);
Chris Lattner76b44452009-12-07 01:42:56 +0000193 OS << '"';
194 } else {
195 OS << '#' << ' ' << LineNo << ' ' << '"';
Eli Friedman80e45b82013-08-29 01:42:42 +0000196 OS.write_escaped(CurFilename);
Chris Lattner76b44452009-12-07 01:42:56 +0000197 OS << '"';
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +0000198
Steve Naroff66aaa392009-12-06 01:02:14 +0000199 if (ExtraLen)
200 OS.write(Extra, ExtraLen);
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000201
Steve Naroff66aaa392009-12-06 01:02:14 +0000202 if (FileType == SrcMgr::C_System)
203 OS.write(" 3", 2);
204 else if (FileType == SrcMgr::C_ExternCSystem)
205 OS.write(" 3 4", 4);
206 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000207 OS << '\n';
208}
209
Chris Lattner728b4dc2006-07-04 21:28:37 +0000210/// MoveToLine - Move the output to the source line specified by the location
211/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner3ed83c12007-12-09 21:11:08 +0000212/// #line directive. This returns false if already at the specified line, true
213/// if some newlines were emitted.
Chris Lattner5dbefc62010-04-13 00:01:41 +0000214bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000215 // If this line is "close enough" to the original line, just print newlines,
216 // otherwise print a #line directive.
Daniel Dunbare7781312008-09-26 01:13:35 +0000217 if (LineNo-CurLine <= 8) {
Chris Lattner5f075822007-07-23 05:14:05 +0000218 if (LineNo-CurLine == 1)
Chris Lattner068529a2008-08-17 03:12:02 +0000219 OS << '\n';
Chris Lattner3ed83c12007-12-09 21:11:08 +0000220 else if (LineNo == CurLine)
Chandler Carruth46a32c22011-07-14 16:14:52 +0000221 return false; // Spelling line moved, but expansion line didn't.
Chris Lattner5f075822007-07-23 05:14:05 +0000222 else {
223 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattner068529a2008-08-17 03:12:02 +0000224 OS.write(NewLines, LineNo-CurLine);
Chris Lattner5f075822007-07-23 05:14:05 +0000225 }
Chris Lattnerbc6bcab2010-06-12 16:20:56 +0000226 } else if (!DisableLineMarkers) {
227 // Emit a #line or line marker.
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000228 WriteLineInfo(LineNo, 0, 0);
Chris Lattnerbc6bcab2010-06-12 16:20:56 +0000229 } else {
230 // Okay, we're in -P mode, which turns off line markers. However, we still
231 // need to emit a newline between tokens on different lines.
Jordan Rose127f6ee2012-06-15 23:33:51 +0000232 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Mike Stump11289f42009-09-09 15:08:12 +0000233 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000234
Mike Stump11289f42009-09-09 15:08:12 +0000235 CurLine = LineNo;
Chris Lattner3ed83c12007-12-09 21:11:08 +0000236 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000237}
238
Jordan Rose127f6ee2012-06-15 23:33:51 +0000239bool
240PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
241 if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
Douglas Gregorc7d65762010-09-09 22:45:38 +0000242 OS << '\n';
243 EmittedTokensOnThisLine = false;
Jordan Rose127f6ee2012-06-15 23:33:51 +0000244 EmittedDirectiveOnThisLine = false;
245 if (ShouldUpdateCurrentLine)
246 ++CurLine;
Douglas Gregorc7d65762010-09-09 22:45:38 +0000247 return true;
248 }
249
250 return false;
251}
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000252
253/// FileChanged - Whenever the preprocessor enters or exits a #include file
254/// it invokes this handler. Update our conception of the current source
255/// position.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000256void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
257 FileChangeReason Reason,
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000258 SrcMgr::CharacteristicKind NewFileType,
259 FileID PrevFID) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000260 // Unless we are exiting a #include, make sure to skip ahead to the line the
261 // #include directive was at.
Chris Lattner9d94f042010-04-13 00:06:42 +0000262 SourceManager &SourceMgr = SM;
Chris Lattner5dbefc62010-04-13 00:01:41 +0000263
264 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Douglas Gregor453b0122010-11-12 07:15:47 +0000265 if (UserLoc.isInvalid())
266 return;
267
Chris Lattnerc745cec2010-04-14 04:28:50 +0000268 unsigned NewLine = UserLoc.getLine();
Daniel Dunbard4352752010-08-24 22:44:13 +0000269
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000270 if (Reason == PPCallbacks::EnterFile) {
Douglas Gregor453b0122010-11-12 07:15:47 +0000271 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
Chris Lattnerd8cc8842009-01-30 18:44:17 +0000272 if (IncludeLoc.isValid())
273 MoveToLine(IncludeLoc);
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000274 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
Jordan Rose111c4a62013-04-17 19:09:18 +0000275 // GCC emits the # directive for this directive on the line AFTER the
276 // directive and emits a bunch of spaces that aren't needed. This is because
277 // otherwise we will emit a line marker for THIS line, which requires an
278 // extra blank line after the directive to avoid making all following lines
279 // off by one. We can do better by simply incrementing NewLine here.
280 NewLine += 1;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000281 }
Chris Lattner5dbefc62010-04-13 00:01:41 +0000282
283 CurLine = NewLine;
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000284
Chris Lattner4c4a2452007-07-24 06:57:14 +0000285 CurFilename.clear();
Chris Lattner5dbefc62010-04-13 00:01:41 +0000286 CurFilename += UserLoc.getFilename();
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000287 FileType = NewFileType;
288
Eli Friedmanc52435b2013-01-09 03:16:42 +0000289 if (DisableLineMarkers) {
290 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
291 return;
292 }
Daniel Dunbard4352752010-08-24 22:44:13 +0000293
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000294 if (!Initialized) {
295 WriteLineInfo(CurLine);
296 Initialized = true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000297 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000298
Daniel Dunbar5d388752012-11-16 01:51:11 +0000299 // Do not emit an enter marker for the main file (which we expect is the first
300 // entered file). This matches gcc, and improves compatibility with some tools
301 // which track the # line markers as a way to determine when the preprocessed
302 // output is in the context of the main file.
303 if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
304 IsFirstFileEntered = true;
305 return;
306 }
307
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000308 switch (Reason) {
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000309 case PPCallbacks::EnterFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000310 WriteLineInfo(CurLine, " 1", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000311 break;
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000312 case PPCallbacks::ExitFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000313 WriteLineInfo(CurLine, " 2", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000314 break;
Mike Stump11289f42009-09-09 15:08:12 +0000315 case PPCallbacks::SystemHeaderPragma:
316 case PPCallbacks::RenameFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000317 WriteLineInfo(CurLine);
318 break;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000319 }
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000320}
321
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000322void PrintPPOutputPPCallbacks::InclusionDirective(SourceLocation HashLoc,
323 const Token &IncludeTok,
324 StringRef FileName,
325 bool IsAngled,
326 CharSourceRange FilenameRange,
327 const FileEntry *File,
328 StringRef SearchPath,
329 StringRef RelativePath,
330 const Module *Imported) {
331 // When preprocessing, turn implicit imports into @imports.
332 // FIXME: This is a stop-gap until a more comprehensive "preprocessing with
333 // modules" solution is introduced.
334 if (Imported) {
335 startNewLineIfNeeded();
336 MoveToLine(HashLoc);
337 OS << "@import " << Imported->getFullModuleName() << ";"
338 << " /* clang -E: implicit import for \"" << File->getName() << "\" */";
Argyrios Kyrtzidisc3b4b792013-04-29 17:26:22 +0000339 EmittedTokensOnThisLine = true;
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000340 }
341}
342
Chris Lattner5eef5072009-01-16 19:25:54 +0000343/// Ident - Handle #ident directives when read by the preprocessor.
Chris Lattner728b4dc2006-07-04 21:28:37 +0000344///
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000345void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
Chris Lattner3338ba82006-07-04 21:19:39 +0000346 MoveToLine(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000347
Chris Lattner068529a2008-08-17 03:12:02 +0000348 OS.write("#ident ", strlen("#ident "));
349 OS.write(&S[0], S.size());
Chris Lattner87f267e2006-11-21 05:02:33 +0000350 EmittedTokensOnThisLine = true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000351}
352
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000353void PrintPPOutputPPCallbacks::PragmaCaptured(SourceLocation Loc,
354 StringRef Str) {
355 startNewLineIfNeeded();
356 MoveToLine(Loc);
357 OS << "#pragma captured";
358
359 setEmittedDirectiveOnThisLine();
360}
361
Chris Lattnercac63f32009-04-12 01:56:53 +0000362/// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000363void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000364 const MacroDirective *MD) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000365 const MacroInfo *MI = MD->getMacroInfo();
Chris Lattnercac63f32009-04-12 01:56:53 +0000366 // Only print out macro definitions in -dD mode.
367 if (!DumpDefines ||
368 // Ignore __FILE__ etc.
369 MI->isBuiltinMacro()) return;
Mike Stump11289f42009-09-09 15:08:12 +0000370
Chris Lattnercac63f32009-04-12 01:56:53 +0000371 MoveToLine(MI->getDefinitionLoc());
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000372 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
Jordan Rose127f6ee2012-06-15 23:33:51 +0000373 setEmittedDirectiveOnThisLine();
Chris Lattnercac63f32009-04-12 01:56:53 +0000374}
375
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000376void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000377 const MacroDirective *MD) {
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000378 // Only print out macro definitions in -dD mode.
379 if (!DumpDefines) return;
380
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000381 MoveToLine(MacroNameTok.getLocation());
382 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
Jordan Rose127f6ee2012-06-15 23:33:51 +0000383 setEmittedDirectiveOnThisLine();
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000384}
Chris Lattnercac63f32009-04-12 01:56:53 +0000385
Aaron Ballman5d041be2013-06-04 02:07:14 +0000386static void outputPrintable(llvm::raw_ostream& OS,
Chris Lattner5eef5072009-01-16 19:25:54 +0000387 const std::string &Str) {
Chris Lattner5eef5072009-01-16 19:25:54 +0000388 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
389 unsigned char Char = Str[i];
Jordan Rosea7d03842013-02-08 22:30:41 +0000390 if (isPrintable(Char) && Char != '\\' && Char != '"')
Chris Lattner5eef5072009-01-16 19:25:54 +0000391 OS << (char)Char;
392 else // Output anything hard as an octal escape.
393 OS << '\\'
394 << (char)('0'+ ((Char >> 6) & 7))
395 << (char)('0'+ ((Char >> 3) & 7))
396 << (char)('0'+ ((Char >> 0) & 7));
397 }
Aaron Ballman5d041be2013-06-04 02:07:14 +0000398}
399
Chris Lattner30c924b2010-06-26 17:11:39 +0000400void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000401 StringRef Namespace,
402 PragmaMessageKind Kind,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000403 StringRef Str) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000404 startNewLineIfNeeded();
Chris Lattner30c924b2010-06-26 17:11:39 +0000405 MoveToLine(Loc);
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000406 OS << "#pragma ";
407 if (!Namespace.empty())
408 OS << Namespace << ' ';
409 switch (Kind) {
410 case PMK_Message:
Andy Gibbsaa0b94a2013-04-19 17:13:17 +0000411 OS << "message(\"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000412 break;
413 case PMK_Warning:
Andy Gibbs96d93902013-04-18 16:49:37 +0000414 OS << "warning \"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000415 break;
416 case PMK_Error:
Andy Gibbs96d93902013-04-18 16:49:37 +0000417 OS << "error \"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000418 break;
419 }
Chris Lattner30c924b2010-06-26 17:11:39 +0000420
Aaron Ballman5d041be2013-06-04 02:07:14 +0000421 outputPrintable(OS, Str);
Chris Lattner30c924b2010-06-26 17:11:39 +0000422 OS << '"';
Andy Gibbsaa0b94a2013-04-19 17:13:17 +0000423 if (Kind == PMK_Message)
424 OS << ')';
Jordan Rose127f6ee2012-06-15 23:33:51 +0000425 setEmittedDirectiveOnThisLine();
Chris Lattner30c924b2010-06-26 17:11:39 +0000426}
427
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000428void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
429 StringRef DebugType) {
430 startNewLineIfNeeded();
431 MoveToLine(Loc);
432
433 OS << "#pragma clang __debug ";
434 OS << DebugType;
435
436 setEmittedDirectiveOnThisLine();
437}
438
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000439void PrintPPOutputPPCallbacks::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000440PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000441 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000442 MoveToLine(Loc);
443 OS << "#pragma " << Namespace << " diagnostic push";
Jordan Rose127f6ee2012-06-15 23:33:51 +0000444 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000445}
446
447void PrintPPOutputPPCallbacks::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000448PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000449 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000450 MoveToLine(Loc);
451 OS << "#pragma " << Namespace << " diagnostic pop";
Jordan Rose127f6ee2012-06-15 23:33:51 +0000452 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000453}
454
455void PrintPPOutputPPCallbacks::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000456PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
Benjamin Kramer7ec12c92012-02-07 22:29:24 +0000457 diag::Mapping Map, StringRef Str) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000458 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000459 MoveToLine(Loc);
460 OS << "#pragma " << Namespace << " diagnostic ";
Benjamin Kramer7ec12c92012-02-07 22:29:24 +0000461 switch (Map) {
Tobias Grosser74160242014-02-28 09:11:08 +0000462 case diag::MAP_REMARK:
463 OS << "remark";
464 break;
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000465 case diag::MAP_WARNING:
466 OS << "warning";
467 break;
468 case diag::MAP_ERROR:
469 OS << "error";
470 break;
471 case diag::MAP_IGNORE:
472 OS << "ignored";
473 break;
474 case diag::MAP_FATAL:
475 OS << "fatal";
476 break;
477 }
478 OS << " \"" << Str << '"';
Jordan Rose127f6ee2012-06-15 23:33:51 +0000479 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000480}
Chris Lattner5eef5072009-01-16 19:25:54 +0000481
Reid Kleckner881dff32013-09-13 22:00:30 +0000482void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
483 StringRef WarningSpec,
484 ArrayRef<int> Ids) {
485 startNewLineIfNeeded();
486 MoveToLine(Loc);
487 OS << "#pragma warning(" << WarningSpec << ':';
488 for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
489 OS << ' ' << *I;
490 OS << ')';
491 setEmittedDirectiveOnThisLine();
492}
493
494void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
495 int Level) {
496 startNewLineIfNeeded();
497 MoveToLine(Loc);
498 OS << "#pragma warning(push";
Reid Kleckner4d185102013-10-02 15:19:23 +0000499 if (Level >= 0)
Reid Kleckner881dff32013-09-13 22:00:30 +0000500 OS << ", " << Level;
501 OS << ')';
502 setEmittedDirectiveOnThisLine();
503}
504
505void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
506 startNewLineIfNeeded();
507 MoveToLine(Loc);
508 OS << "#pragma warning(pop)";
509 setEmittedDirectiveOnThisLine();
510}
511
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000512/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner3ed83c12007-12-09 21:11:08 +0000513/// is called for the first token on each new line. If this really is the start
514/// of a new logical line, handle it and return true, otherwise return false.
515/// This may not be the start of a logical line because the "start of line"
Chandler Carruth46a32c22011-07-14 16:14:52 +0000516/// marker is set for spelling lines, not expansion ones.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000517bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000518 // Figure out what line we went to and insert the appropriate number of
519 // newline characters.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000520 if (!MoveToLine(Tok.getLocation()))
521 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000522
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000523 // Print out space characters so that the first token on a line is
524 // indented for easy reading.
Chandler Carruth42f35f92011-07-25 20:57:57 +0000525 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000526
Richard Smith5b2f7c52014-02-24 20:50:36 +0000527 // The first token on a line can have a column number of 1, yet still expect
528 // leading white space, if a macro expansion in column 1 starts with an empty
529 // macro argument, or an empty nested macro expansion. In this case, move the
530 // token to column 2.
531 if (ColNo == 1 && Tok.hasLeadingSpace())
532 ColNo = 2;
533
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000534 // This hack prevents stuff like:
535 // #define HASH #
536 // HASH define foo bar
537 // From having the # character end up at column 1, which makes it so it
538 // is not handled as a #define next time through the preprocessor if in
539 // -fpreprocessed mode.
Chris Lattner3c69f122007-10-09 18:03:42 +0000540 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattner068529a2008-08-17 03:12:02 +0000541 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000542
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000543 // Otherwise, indent the appropriate number of spaces.
544 for (; ColNo > 1; --ColNo)
Chris Lattner068529a2008-08-17 03:12:02 +0000545 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000546
Chris Lattner3ed83c12007-12-09 21:11:08 +0000547 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000548}
549
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000550void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
551 unsigned Len) {
552 unsigned NumNewlines = 0;
553 for (; Len; --Len, ++TokStr) {
554 if (*TokStr != '\n' &&
555 *TokStr != '\r')
556 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000557
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000558 ++NumNewlines;
Mike Stump11289f42009-09-09 15:08:12 +0000559
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000560 // If we have \n\r or \r\n, skip both and count as one line.
561 if (Len != 1 &&
562 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
563 TokStr[0] != TokStr[1])
564 ++TokStr, --Len;
565 }
Mike Stump11289f42009-09-09 15:08:12 +0000566
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000567 if (NumNewlines == 0) return;
Mike Stump11289f42009-09-09 15:08:12 +0000568
Chris Lattnera5e67752009-06-15 04:08:28 +0000569 CurLine += NumNewlines;
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000570}
571
572
Chris Lattner5de858c2006-07-04 19:04:44 +0000573namespace {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000574struct UnknownPragmaHandler : public PragmaHandler {
575 const char *Prefix;
Chris Lattner87f267e2006-11-21 05:02:33 +0000576 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump11289f42009-09-09 15:08:12 +0000577
Chris Lattner87f267e2006-11-21 05:02:33 +0000578 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000579 : Prefix(prefix), Callbacks(callbacks) {}
Douglas Gregorc7d65762010-09-09 22:45:38 +0000580 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
581 Token &PragmaTok) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000582 // Figure out what line we went to and insert the appropriate number of
583 // newline characters.
Jordan Rose127f6ee2012-06-15 23:33:51 +0000584 Callbacks->startNewLineIfNeeded();
Chris Lattner87f267e2006-11-21 05:02:33 +0000585 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattner068529a2008-08-17 03:12:02 +0000586 Callbacks->OS.write(Prefix, strlen(Prefix));
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000587 // Read and print all of the pragma tokens.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000588 while (PragmaTok.isNot(tok::eod)) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000589 if (PragmaTok.hasLeadingSpace())
Chris Lattner068529a2008-08-17 03:12:02 +0000590 Callbacks->OS << ' ';
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000591 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattner068529a2008-08-17 03:12:02 +0000592 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Kleckner0e73ec42014-02-20 22:59:51 +0000593
594 // Expand macros in pragmas with -fms-extensions. The assumption is that
595 // the majority of pragmas in such a file will be Microsoft pragmas.
596 if (PP.getLangOpts().MicrosoftExt)
597 PP.Lex(PragmaTok);
598 else
599 PP.LexUnexpandedToken(PragmaTok);
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000600 }
Jordan Rose127f6ee2012-06-15 23:33:51 +0000601 Callbacks->setEmittedDirectiveOnThisLine();
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000602 }
603};
Chris Lattner5de858c2006-07-04 19:04:44 +0000604} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000605
Chris Lattner4418ce12007-07-23 06:09:34 +0000606
Chris Lattnerfc001b02009-02-06 05:56:11 +0000607static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
608 PrintPPOutputPPCallbacks *Callbacks,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000609 raw_ostream &OS) {
Jordan Rose67b66232013-03-05 23:54:55 +0000610 bool DropComments = PP.getLangOpts().TraditionalCPP &&
611 !PP.getCommentRetentionState();
612
Benjamin Kramer718f7222010-02-27 18:02:51 +0000613 char Buffer[256];
Chris Lattnerbba37f42010-06-15 21:06:38 +0000614 Token PrevPrevTok, PrevTok;
615 PrevPrevTok.startToken();
616 PrevTok.startToken();
Chris Lattner3ff2e692007-10-10 20:45:16 +0000617 while (1) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000618 if (Callbacks->hasEmittedDirectiveOnThisLine()) {
619 Callbacks->startNewLineIfNeeded();
620 Callbacks->MoveToLine(Tok.getLocation());
621 }
Mike Stump11289f42009-09-09 15:08:12 +0000622
Chris Lattner67c38482006-07-04 23:24:26 +0000623 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000624 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
625 // done.
Mike Stump11289f42009-09-09 15:08:12 +0000626 } else if (Tok.hasLeadingSpace() ||
Chris Lattner4418ce12007-07-23 06:09:34 +0000627 // If we haven't emitted a token on this line yet, PrevTok isn't
628 // useful to look at and no concatenation could happen anyway.
Chris Lattnerd63c8a52007-07-23 23:21:34 +0000629 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattner4418ce12007-07-23 06:09:34 +0000630 // Don't print "-" next to "-", it would form "--".
Chris Lattner0384e6352010-04-14 03:57:19 +0000631 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattner068529a2008-08-17 03:12:02 +0000632 OS << ' ';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000633 }
Mike Stump11289f42009-09-09 15:08:12 +0000634
Jordan Rose67b66232013-03-05 23:54:55 +0000635 if (DropComments && Tok.is(tok::comment)) {
636 // Skip comments. Normally the preprocessor does not generate
637 // tok::comment nodes at all when not keeping comments, but under
638 // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
639 SourceLocation StartLoc = Tok.getLocation();
640 Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
Ben Langmuir5eb7cb72014-01-30 21:50:18 +0000641 } else if (Tok.is(tok::annot_module_include) ||
642 Tok.is(tok::annot_module_begin) ||
643 Tok.is(tok::annot_module_end)) {
644 // PrintPPOutputPPCallbacks::InclusionDirective handles producing
645 // appropriate output here. Ignore this token entirely.
Richard Smithce587f52013-11-15 04:24:58 +0000646 PP.Lex(Tok);
647 continue;
Jordan Rose67b66232013-03-05 23:54:55 +0000648 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
Benjamin Kramer718f7222010-02-27 18:02:51 +0000649 OS << II->getName();
650 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
651 Tok.getLiteralData()) {
652 OS.write(Tok.getLiteralData(), Tok.getLength());
653 } else if (Tok.getLength() < 256) {
654 const char *TokPtr = Buffer;
655 unsigned Len = PP.getSpelling(Tok, TokPtr);
656 OS.write(TokPtr, Len);
Mike Stump11289f42009-09-09 15:08:12 +0000657
Benjamin Kramer718f7222010-02-27 18:02:51 +0000658 // Tokens that can contain embedded newlines need to adjust our current
659 // line number.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000660 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramer718f7222010-02-27 18:02:51 +0000661 Callbacks->HandleNewlinesInToken(TokPtr, Len);
662 } else {
663 std::string S = PP.getSpelling(Tok);
664 OS.write(&S[0], S.size());
665
666 // Tokens that can contain embedded newlines need to adjust our current
667 // line number.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000668 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramer718f7222010-02-27 18:02:51 +0000669 Callbacks->HandleNewlinesInToken(&S[0], S.size());
670 }
Jordan Rose127f6ee2012-06-15 23:33:51 +0000671 Callbacks->setEmittedTokensOnThisLine();
Mike Stump11289f42009-09-09 15:08:12 +0000672
Chris Lattner3ff2e692007-10-10 20:45:16 +0000673 if (Tok.is(tok::eof)) break;
Mike Stump11289f42009-09-09 15:08:12 +0000674
Chris Lattner0384e6352010-04-14 03:57:19 +0000675 PrevPrevTok = PrevTok;
Chris Lattner3ff2e692007-10-10 20:45:16 +0000676 PrevTok = Tok;
677 PP.Lex(Tok);
678 }
Chris Lattnerfc001b02009-02-06 05:56:11 +0000679}
680
Dmitri Gribenko049a4ff2013-01-14 00:36:42 +0000681typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
Benjamin Kramer04bf1872013-09-22 14:10:29 +0000682static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +0000683 return LHS->first->getName().compare(RHS->first->getName());
Chris Lattner1ec246d2009-02-10 22:28:19 +0000684}
Chris Lattnerfc001b02009-02-06 05:56:11 +0000685
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000686static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
Daniel Dunbard839e772010-06-11 20:10:12 +0000687 // Ignore unknown pragmas.
NAKAMURA Takumiddc86792013-12-04 11:12:26 +0000688 PP.AddPragmaHandler(new EmptyPragmaHandler());
Daniel Dunbard839e772010-06-11 20:10:12 +0000689
Eli Friedman26c672b2009-05-19 01:32:34 +0000690 // -dM mode just scans and ignores all tokens in the files, then dumps out
691 // the macro table at the end.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000692 PP.EnterMainSourceFile();
Eli Friedman26c672b2009-05-19 01:32:34 +0000693
694 Token Tok;
695 do PP.Lex(Tok);
696 while (Tok.isNot(tok::eof));
697
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000698 SmallVector<id_macro_pair, 128> MacrosByID;
699 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
700 I != E; ++I) {
701 if (I->first->hasMacroDefinition())
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000702 MacrosByID.push_back(id_macro_pair(I->first, I->second->getMacroInfo()));
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000703 }
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +0000704 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedman26c672b2009-05-19 01:32:34 +0000705
706 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
707 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000708 // Ignore computed macros like __LINE__ and friends.
Eli Friedman26c672b2009-05-19 01:32:34 +0000709 if (MI.isBuiltinMacro()) continue;
710
711 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +0000712 *OS << '\n';
Eli Friedman26c672b2009-05-19 01:32:34 +0000713 }
714}
715
Chris Lattnerfc001b02009-02-06 05:56:11 +0000716/// DoPrintPreprocessedInput - This implements -E mode.
717///
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000718void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
Daniel Dunbar22bdabf2009-11-11 10:07:44 +0000719 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000720 // Show macros with no output is handled specially.
721 if (!Opts.ShowCPP) {
722 assert(Opts.ShowMacros && "Not yet implemented!");
723 DoPrintMacros(PP, OS);
724 return;
725 }
726
Chris Lattnerfc001b02009-02-06 05:56:11 +0000727 // Inform the preprocessor whether we want it to retain comments or not, due
728 // to -C or -CC.
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000729 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanfcb57d52009-05-19 01:02:07 +0000730
Eli Friedman6af494b2009-05-19 03:06:47 +0000731 PrintPPOutputPPCallbacks *Callbacks =
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000732 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
Daniel Dunbar27734fd2011-02-02 15:41:17 +0000733 Opts.ShowMacros);
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000734 PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
Chris Lattner49609d52010-11-10 01:00:49 +0000735 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
736 PP.AddPragmaHandler("clang",
737 new UnknownPragmaHandler("#pragma clang", Callbacks));
Chris Lattnerfc001b02009-02-06 05:56:11 +0000738
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +0000739 PP.addPPCallbacks(Callbacks);
Chris Lattnerfc001b02009-02-06 05:56:11 +0000740
Eli Friedman26c672b2009-05-19 01:32:34 +0000741 // After we have configured the preprocessor, enter the main file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000742 PP.EnterMainSourceFile();
Chris Lattnerfc001b02009-02-06 05:56:11 +0000743
Eli Friedman26c672b2009-05-19 01:32:34 +0000744 // Consume all of the tokens that come from the predefines buffer. Those
745 // should not be emitted into the output and are guaranteed to be at the
746 // start.
747 const SourceManager &SourceMgr = PP.getSourceManager();
748 Token Tok;
Douglas Gregor453b0122010-11-12 07:15:47 +0000749 do {
750 PP.Lex(Tok);
751 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
752 break;
753
754 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
755 if (PLoc.isInvalid())
756 break;
757
758 if (strcmp(PLoc.getFilename(), "<built-in>"))
759 break;
760 } while (true);
Chris Lattnerfc001b02009-02-06 05:56:11 +0000761
Eli Friedman26c672b2009-05-19 01:32:34 +0000762 // Read all the preprocessed tokens, printing them out to the stream.
763 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
764 *OS << '\n';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000765}