blob: 037a6a525e2fce5611d237e01e6a518135932a45 [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;
Daniel Marjamakiecb0e1b2015-05-11 08:25:54 +000067 for (const auto &T : MI.tokens()) {
68 if (T.hasLeadingSpace())
Chris Lattnercac63f32009-04-12 01:56:53 +000069 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +000070
Daniel Marjamakiecb0e1b2015-05-11 08:25:54 +000071 OS << PP.getSpelling(T, SpellingBuffer);
Chris Lattnercac63f32009-04-12 01:56:53 +000072 }
73}
74
Chris Lattnerf46be6c2006-07-04 22:19:33 +000075//===----------------------------------------------------------------------===//
76// Preprocessed token printer
77//===----------------------------------------------------------------------===//
78
Chris Lattner87f267e2006-11-21 05:02:33 +000079namespace {
80class PrintPPOutputPPCallbacks : public PPCallbacks {
81 Preprocessor &PP;
Chris Lattner9d94f042010-04-13 00:06:42 +000082 SourceManager &SM;
Chris Lattner644d4522009-02-13 00:46:04 +000083 TokenConcatenation ConcatInfo;
Chris Lattner068529a2008-08-17 03:12:02 +000084public:
Chris Lattner0e62c1c2011-07-23 10:55:15 +000085 raw_ostream &OS;
Chris Lattner068529a2008-08-17 03:12:02 +000086private:
Chris Lattner87f267e2006-11-21 05:02:33 +000087 unsigned CurLine;
Daniel Dunbard4352752010-08-24 22:44:13 +000088
Chris Lattner87f267e2006-11-21 05:02:33 +000089 bool EmittedTokensOnThisLine;
Jordan Rose127f6ee2012-06-15 23:33:51 +000090 bool EmittedDirectiveOnThisLine;
Chris Lattner66a740e2008-10-27 01:19:25 +000091 SrcMgr::CharacteristicKind FileType;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000092 SmallString<512> CurFilename;
Daniel Dunbar98e0e532008-09-05 03:22:57 +000093 bool Initialized;
Eli Friedman6af494b2009-05-19 03:06:47 +000094 bool DisableLineMarkers;
95 bool DumpDefines;
Reid Kleckner1df0fea2015-02-26 00:17:25 +000096 bool UseLineDirectives;
Daniel Dunbar5d388752012-11-16 01:51:11 +000097 bool IsFirstFileEntered;
Chris Lattner87f267e2006-11-21 05:02:33 +000098public:
Reid Kleckner1df0fea2015-02-26 00:17:25 +000099 PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os, bool lineMarkers,
100 bool defines, bool UseLineDirectives)
101 : PP(pp), SM(PP.getSourceManager()), ConcatInfo(PP), OS(os),
102 DisableLineMarkers(lineMarkers), DumpDefines(defines),
103 UseLineDirectives(UseLineDirectives) {
Daniel Dunbar27734fd2011-02-02 15:41:17 +0000104 CurLine = 0;
Chris Lattner4c4a2452007-07-24 06:57:14 +0000105 CurFilename += "<uninit>";
Chris Lattner87f267e2006-11-21 05:02:33 +0000106 EmittedTokensOnThisLine = false;
Jordan Rose127f6ee2012-06-15 23:33:51 +0000107 EmittedDirectiveOnThisLine = false;
Chris Lattnerb03dc762008-09-26 21:18:42 +0000108 FileType = SrcMgr::C_User;
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000109 Initialized = false;
Daniel Dunbar5d388752012-11-16 01:51:11 +0000110 IsFirstFileEntered = false;
Chris Lattner87f267e2006-11-21 05:02:33 +0000111 }
Mike Stump11289f42009-09-09 15:08:12 +0000112
Jordan Rose127f6ee2012-06-15 23:33:51 +0000113 void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattner4418ce12007-07-23 06:09:34 +0000114 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Mike Stump11289f42009-09-09 15:08:12 +0000115
Jordan Rose127f6ee2012-06-15 23:33:51 +0000116 void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
117 bool hasEmittedDirectiveOnThisLine() const {
118 return EmittedDirectiveOnThisLine;
119 }
120
121 bool startNewLineIfNeeded(bool ShouldUpdateCurrentLine = true);
Craig Topperafa7cb32014-03-13 06:07:04 +0000122
123 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
124 SrcMgr::CharacteristicKind FileType,
125 FileID PrevFID) override;
126 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
127 StringRef FileName, bool IsAngled,
128 CharSourceRange FilenameRange, const FileEntry *File,
129 StringRef SearchPath, StringRef RelativePath,
130 const Module *Imported) override;
131 void Ident(SourceLocation Loc, const std::string &str) override;
Craig Topperafa7cb32014-03-13 06:07:04 +0000132 void PragmaMessage(SourceLocation Loc, StringRef Namespace,
133 PragmaMessageKind Kind, StringRef Str) override;
134 void PragmaDebug(SourceLocation Loc, StringRef DebugType) override;
135 void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override;
136 void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override;
137 void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
Alp Tokerc726c362014-06-10 09:31:37 +0000138 diag::Severity Map, StringRef Str) override;
Craig Topperafa7cb32014-03-13 06:07:04 +0000139 void PragmaWarning(SourceLocation Loc, StringRef WarningSpec,
140 ArrayRef<int> Ids) override;
141 void PragmaWarningPush(SourceLocation Loc, int Level) override;
142 void PragmaWarningPop(SourceLocation Loc) override;
Chris Lattner87f267e2006-11-21 05:02:33 +0000143
Chris Lattner3ed83c12007-12-09 21:11:08 +0000144 bool HandleFirstTokOnLine(Token &Tok);
Hal Finkel2109f232013-01-28 04:37:37 +0000145
146 /// Move to the line of the provided source location. This will
147 /// return true if the output stream required adjustment or if
148 /// the requested location is on the first line.
Chris Lattner5dbefc62010-04-13 00:01:41 +0000149 bool MoveToLine(SourceLocation Loc) {
Douglas Gregor453b0122010-11-12 07:15:47 +0000150 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
151 if (PLoc.isInvalid())
152 return false;
Hal Finkel2109f232013-01-28 04:37:37 +0000153 return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
Chris Lattner5dbefc62010-04-13 00:01:41 +0000154 }
155 bool MoveToLine(unsigned LineNo);
156
Chris Lattner0384e6352010-04-14 03:57:19 +0000157 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
158 const Token &Tok) {
159 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
Chris Lattner644d4522009-02-13 00:46:04 +0000160 }
Craig Topper49a27902014-05-22 04:46:25 +0000161 void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
162 unsigned ExtraLen=0);
Douglas Gregorc7d65762010-09-09 22:45:38 +0000163 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000164 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump11289f42009-09-09 15:08:12 +0000165
Chris Lattnercac63f32009-04-12 01:56:53 +0000166 /// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Topperafa7cb32014-03-13 06:07:04 +0000167 void MacroDefined(const Token &MacroNameTok,
168 const MacroDirective *MD) override;
Mike Stump11289f42009-09-09 15:08:12 +0000169
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000170 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
Craig Topperafa7cb32014-03-13 06:07:04 +0000171 void MacroUndefined(const Token &MacroNameTok,
Richard Smith36bd40d2015-05-04 03:15:40 +0000172 const MacroDefinition &MD) override;
Chris Lattner87f267e2006-11-21 05:02:33 +0000173};
Chris Lattner21632652008-04-08 04:16:20 +0000174} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000175
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000176void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
177 const char *Extra,
178 unsigned ExtraLen) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000179 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000180
Chris Lattner76b44452009-12-07 01:42:56 +0000181 // Emit #line directives or GNU line markers depending on what mode we're in.
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000182 if (UseLineDirectives) {
Chris Lattner76b44452009-12-07 01:42:56 +0000183 OS << "#line" << ' ' << LineNo << ' ' << '"';
Eli Friedman80e45b82013-08-29 01:42:42 +0000184 OS.write_escaped(CurFilename);
Chris Lattner76b44452009-12-07 01:42:56 +0000185 OS << '"';
186 } else {
187 OS << '#' << ' ' << LineNo << ' ' << '"';
Eli Friedman80e45b82013-08-29 01:42:42 +0000188 OS.write_escaped(CurFilename);
Chris Lattner76b44452009-12-07 01:42:56 +0000189 OS << '"';
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +0000190
Steve Naroff66aaa392009-12-06 01:02:14 +0000191 if (ExtraLen)
192 OS.write(Extra, ExtraLen);
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000193
Steve Naroff66aaa392009-12-06 01:02:14 +0000194 if (FileType == SrcMgr::C_System)
195 OS.write(" 3", 2);
196 else if (FileType == SrcMgr::C_ExternCSystem)
197 OS.write(" 3 4", 4);
198 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000199 OS << '\n';
200}
201
Chris Lattner728b4dc2006-07-04 21:28:37 +0000202/// MoveToLine - Move the output to the source line specified by the location
203/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner3ed83c12007-12-09 21:11:08 +0000204/// #line directive. This returns false if already at the specified line, true
205/// if some newlines were emitted.
Chris Lattner5dbefc62010-04-13 00:01:41 +0000206bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000207 // If this line is "close enough" to the original line, just print newlines,
208 // otherwise print a #line directive.
Daniel Dunbare7781312008-09-26 01:13:35 +0000209 if (LineNo-CurLine <= 8) {
Chris Lattner5f075822007-07-23 05:14:05 +0000210 if (LineNo-CurLine == 1)
Chris Lattner068529a2008-08-17 03:12:02 +0000211 OS << '\n';
Chris Lattner3ed83c12007-12-09 21:11:08 +0000212 else if (LineNo == CurLine)
Chandler Carruth46a32c22011-07-14 16:14:52 +0000213 return false; // Spelling line moved, but expansion line didn't.
Chris Lattner5f075822007-07-23 05:14:05 +0000214 else {
215 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattner068529a2008-08-17 03:12:02 +0000216 OS.write(NewLines, LineNo-CurLine);
Chris Lattner5f075822007-07-23 05:14:05 +0000217 }
Chris Lattnerbc6bcab2010-06-12 16:20:56 +0000218 } else if (!DisableLineMarkers) {
219 // Emit a #line or line marker.
Craig Topper49a27902014-05-22 04:46:25 +0000220 WriteLineInfo(LineNo, nullptr, 0);
Chris Lattnerbc6bcab2010-06-12 16:20:56 +0000221 } else {
222 // Okay, we're in -P mode, which turns off line markers. However, we still
223 // need to emit a newline between tokens on different lines.
Jordan Rose127f6ee2012-06-15 23:33:51 +0000224 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Mike Stump11289f42009-09-09 15:08:12 +0000225 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000226
Mike Stump11289f42009-09-09 15:08:12 +0000227 CurLine = LineNo;
Chris Lattner3ed83c12007-12-09 21:11:08 +0000228 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000229}
230
Jordan Rose127f6ee2012-06-15 23:33:51 +0000231bool
232PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
233 if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
Douglas Gregorc7d65762010-09-09 22:45:38 +0000234 OS << '\n';
235 EmittedTokensOnThisLine = false;
Jordan Rose127f6ee2012-06-15 23:33:51 +0000236 EmittedDirectiveOnThisLine = false;
237 if (ShouldUpdateCurrentLine)
238 ++CurLine;
Douglas Gregorc7d65762010-09-09 22:45:38 +0000239 return true;
240 }
241
242 return false;
243}
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000244
245/// FileChanged - Whenever the preprocessor enters or exits a #include file
246/// it invokes this handler. Update our conception of the current source
247/// position.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000248void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
249 FileChangeReason Reason,
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000250 SrcMgr::CharacteristicKind NewFileType,
251 FileID PrevFID) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000252 // Unless we are exiting a #include, make sure to skip ahead to the line the
253 // #include directive was at.
Chris Lattner9d94f042010-04-13 00:06:42 +0000254 SourceManager &SourceMgr = SM;
Chris Lattner5dbefc62010-04-13 00:01:41 +0000255
256 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Douglas Gregor453b0122010-11-12 07:15:47 +0000257 if (UserLoc.isInvalid())
258 return;
259
Chris Lattnerc745cec2010-04-14 04:28:50 +0000260 unsigned NewLine = UserLoc.getLine();
Daniel Dunbard4352752010-08-24 22:44:13 +0000261
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000262 if (Reason == PPCallbacks::EnterFile) {
Douglas Gregor453b0122010-11-12 07:15:47 +0000263 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
Chris Lattnerd8cc8842009-01-30 18:44:17 +0000264 if (IncludeLoc.isValid())
265 MoveToLine(IncludeLoc);
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000266 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
Jordan Rose111c4a62013-04-17 19:09:18 +0000267 // GCC emits the # directive for this directive on the line AFTER the
268 // directive and emits a bunch of spaces that aren't needed. This is because
269 // otherwise we will emit a line marker for THIS line, which requires an
270 // extra blank line after the directive to avoid making all following lines
271 // off by one. We can do better by simply incrementing NewLine here.
272 NewLine += 1;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000273 }
Chris Lattner5dbefc62010-04-13 00:01:41 +0000274
275 CurLine = NewLine;
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000276
Chris Lattner4c4a2452007-07-24 06:57:14 +0000277 CurFilename.clear();
Chris Lattner5dbefc62010-04-13 00:01:41 +0000278 CurFilename += UserLoc.getFilename();
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000279 FileType = NewFileType;
280
Eli Friedmanc52435b2013-01-09 03:16:42 +0000281 if (DisableLineMarkers) {
282 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
283 return;
284 }
Daniel Dunbard4352752010-08-24 22:44:13 +0000285
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000286 if (!Initialized) {
287 WriteLineInfo(CurLine);
288 Initialized = true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000289 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000290
Daniel Dunbar5d388752012-11-16 01:51:11 +0000291 // Do not emit an enter marker for the main file (which we expect is the first
292 // entered file). This matches gcc, and improves compatibility with some tools
293 // which track the # line markers as a way to determine when the preprocessed
294 // output is in the context of the main file.
295 if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
296 IsFirstFileEntered = true;
297 return;
298 }
299
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000300 switch (Reason) {
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000301 case PPCallbacks::EnterFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000302 WriteLineInfo(CurLine, " 1", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000303 break;
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000304 case PPCallbacks::ExitFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000305 WriteLineInfo(CurLine, " 2", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000306 break;
Mike Stump11289f42009-09-09 15:08:12 +0000307 case PPCallbacks::SystemHeaderPragma:
308 case PPCallbacks::RenameFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000309 WriteLineInfo(CurLine);
310 break;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000311 }
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000312}
313
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000314void PrintPPOutputPPCallbacks::InclusionDirective(SourceLocation HashLoc,
315 const Token &IncludeTok,
316 StringRef FileName,
317 bool IsAngled,
318 CharSourceRange FilenameRange,
319 const FileEntry *File,
320 StringRef SearchPath,
321 StringRef RelativePath,
322 const Module *Imported) {
323 // When preprocessing, turn implicit imports into @imports.
324 // FIXME: This is a stop-gap until a more comprehensive "preprocessing with
325 // modules" solution is introduced.
326 if (Imported) {
327 startNewLineIfNeeded();
328 MoveToLine(HashLoc);
329 OS << "@import " << Imported->getFullModuleName() << ";"
330 << " /* clang -E: implicit import for \"" << File->getName() << "\" */";
Ben Langmuir5418f402014-09-10 21:29:41 +0000331 // Since we want a newline after the @import, but not a #<line>, start a new
332 // line immediately.
Argyrios Kyrtzidisc3b4b792013-04-29 17:26:22 +0000333 EmittedTokensOnThisLine = true;
Ben Langmuir5418f402014-09-10 21:29:41 +0000334 startNewLineIfNeeded();
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000335 }
336}
337
Chris Lattner5eef5072009-01-16 19:25:54 +0000338/// Ident - Handle #ident directives when read by the preprocessor.
Chris Lattner728b4dc2006-07-04 21:28:37 +0000339///
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000340void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
Chris Lattner3338ba82006-07-04 21:19:39 +0000341 MoveToLine(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000342
Chris Lattner068529a2008-08-17 03:12:02 +0000343 OS.write("#ident ", strlen("#ident "));
344 OS.write(&S[0], S.size());
Chris Lattner87f267e2006-11-21 05:02:33 +0000345 EmittedTokensOnThisLine = true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000346}
347
Chris Lattnercac63f32009-04-12 01:56:53 +0000348/// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000349void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000350 const MacroDirective *MD) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000351 const MacroInfo *MI = MD->getMacroInfo();
Chris Lattnercac63f32009-04-12 01:56:53 +0000352 // Only print out macro definitions in -dD mode.
353 if (!DumpDefines ||
354 // Ignore __FILE__ etc.
355 MI->isBuiltinMacro()) return;
Mike Stump11289f42009-09-09 15:08:12 +0000356
Chris Lattnercac63f32009-04-12 01:56:53 +0000357 MoveToLine(MI->getDefinitionLoc());
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000358 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
Jordan Rose127f6ee2012-06-15 23:33:51 +0000359 setEmittedDirectiveOnThisLine();
Chris Lattnercac63f32009-04-12 01:56:53 +0000360}
361
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000362void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
Richard Smith36bd40d2015-05-04 03:15:40 +0000363 const MacroDefinition &MD) {
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000364 // Only print out macro definitions in -dD mode.
365 if (!DumpDefines) return;
366
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000367 MoveToLine(MacroNameTok.getLocation());
368 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
Jordan Rose127f6ee2012-06-15 23:33:51 +0000369 setEmittedDirectiveOnThisLine();
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000370}
Chris Lattnercac63f32009-04-12 01:56:53 +0000371
Aaron Ballman5d041be2013-06-04 02:07:14 +0000372static void outputPrintable(llvm::raw_ostream& OS,
Chris Lattner5eef5072009-01-16 19:25:54 +0000373 const std::string &Str) {
Chris Lattner5eef5072009-01-16 19:25:54 +0000374 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
375 unsigned char Char = Str[i];
Jordan Rosea7d03842013-02-08 22:30:41 +0000376 if (isPrintable(Char) && Char != '\\' && Char != '"')
Chris Lattner5eef5072009-01-16 19:25:54 +0000377 OS << (char)Char;
378 else // Output anything hard as an octal escape.
379 OS << '\\'
380 << (char)('0'+ ((Char >> 6) & 7))
381 << (char)('0'+ ((Char >> 3) & 7))
382 << (char)('0'+ ((Char >> 0) & 7));
383 }
Aaron Ballman5d041be2013-06-04 02:07:14 +0000384}
385
Chris Lattner30c924b2010-06-26 17:11:39 +0000386void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000387 StringRef Namespace,
388 PragmaMessageKind Kind,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000389 StringRef Str) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000390 startNewLineIfNeeded();
Chris Lattner30c924b2010-06-26 17:11:39 +0000391 MoveToLine(Loc);
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000392 OS << "#pragma ";
393 if (!Namespace.empty())
394 OS << Namespace << ' ';
395 switch (Kind) {
396 case PMK_Message:
Andy Gibbsaa0b94a2013-04-19 17:13:17 +0000397 OS << "message(\"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000398 break;
399 case PMK_Warning:
Andy Gibbs96d93902013-04-18 16:49:37 +0000400 OS << "warning \"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000401 break;
402 case PMK_Error:
Andy Gibbs96d93902013-04-18 16:49:37 +0000403 OS << "error \"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000404 break;
405 }
Chris Lattner30c924b2010-06-26 17:11:39 +0000406
Aaron Ballman5d041be2013-06-04 02:07:14 +0000407 outputPrintable(OS, Str);
Chris Lattner30c924b2010-06-26 17:11:39 +0000408 OS << '"';
Andy Gibbsaa0b94a2013-04-19 17:13:17 +0000409 if (Kind == PMK_Message)
410 OS << ')';
Jordan Rose127f6ee2012-06-15 23:33:51 +0000411 setEmittedDirectiveOnThisLine();
Chris Lattner30c924b2010-06-26 17:11:39 +0000412}
413
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000414void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
415 StringRef DebugType) {
416 startNewLineIfNeeded();
417 MoveToLine(Loc);
418
419 OS << "#pragma clang __debug ";
420 OS << DebugType;
421
422 setEmittedDirectiveOnThisLine();
423}
424
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000425void PrintPPOutputPPCallbacks::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000426PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000427 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000428 MoveToLine(Loc);
429 OS << "#pragma " << Namespace << " diagnostic push";
Jordan Rose127f6ee2012-06-15 23:33:51 +0000430 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000431}
432
433void PrintPPOutputPPCallbacks::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000434PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000435 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000436 MoveToLine(Loc);
437 OS << "#pragma " << Namespace << " diagnostic pop";
Jordan Rose127f6ee2012-06-15 23:33:51 +0000438 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000439}
440
Alp Tokerc726c362014-06-10 09:31:37 +0000441void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
442 StringRef Namespace,
443 diag::Severity Map,
444 StringRef Str) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000445 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000446 MoveToLine(Loc);
447 OS << "#pragma " << Namespace << " diagnostic ";
Benjamin Kramer7ec12c92012-02-07 22:29:24 +0000448 switch (Map) {
Alp Toker46df1c02014-06-12 10:15:20 +0000449 case diag::Severity::Remark:
Tobias Grosser74160242014-02-28 09:11:08 +0000450 OS << "remark";
451 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000452 case diag::Severity::Warning:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000453 OS << "warning";
454 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000455 case diag::Severity::Error:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000456 OS << "error";
457 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000458 case diag::Severity::Ignored:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000459 OS << "ignored";
460 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000461 case diag::Severity::Fatal:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000462 OS << "fatal";
463 break;
464 }
465 OS << " \"" << Str << '"';
Jordan Rose127f6ee2012-06-15 23:33:51 +0000466 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000467}
Chris Lattner5eef5072009-01-16 19:25:54 +0000468
Reid Kleckner881dff32013-09-13 22:00:30 +0000469void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
470 StringRef WarningSpec,
471 ArrayRef<int> Ids) {
472 startNewLineIfNeeded();
473 MoveToLine(Loc);
474 OS << "#pragma warning(" << WarningSpec << ':';
475 for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
476 OS << ' ' << *I;
477 OS << ')';
478 setEmittedDirectiveOnThisLine();
479}
480
481void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
482 int Level) {
483 startNewLineIfNeeded();
484 MoveToLine(Loc);
485 OS << "#pragma warning(push";
Reid Kleckner4d185102013-10-02 15:19:23 +0000486 if (Level >= 0)
Reid Kleckner881dff32013-09-13 22:00:30 +0000487 OS << ", " << Level;
488 OS << ')';
489 setEmittedDirectiveOnThisLine();
490}
491
492void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
493 startNewLineIfNeeded();
494 MoveToLine(Loc);
495 OS << "#pragma warning(pop)";
496 setEmittedDirectiveOnThisLine();
497}
498
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000499/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner3ed83c12007-12-09 21:11:08 +0000500/// is called for the first token on each new line. If this really is the start
501/// of a new logical line, handle it and return true, otherwise return false.
502/// This may not be the start of a logical line because the "start of line"
Chandler Carruth46a32c22011-07-14 16:14:52 +0000503/// marker is set for spelling lines, not expansion ones.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000504bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000505 // Figure out what line we went to and insert the appropriate number of
506 // newline characters.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000507 if (!MoveToLine(Tok.getLocation()))
508 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000509
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000510 // Print out space characters so that the first token on a line is
511 // indented for easy reading.
Chandler Carruth42f35f92011-07-25 20:57:57 +0000512 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000513
Richard Smith5b2f7c52014-02-24 20:50:36 +0000514 // The first token on a line can have a column number of 1, yet still expect
515 // leading white space, if a macro expansion in column 1 starts with an empty
516 // macro argument, or an empty nested macro expansion. In this case, move the
517 // token to column 2.
518 if (ColNo == 1 && Tok.hasLeadingSpace())
519 ColNo = 2;
520
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000521 // This hack prevents stuff like:
522 // #define HASH #
523 // HASH define foo bar
524 // From having the # character end up at column 1, which makes it so it
525 // is not handled as a #define next time through the preprocessor if in
526 // -fpreprocessed mode.
Chris Lattner3c69f122007-10-09 18:03:42 +0000527 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattner068529a2008-08-17 03:12:02 +0000528 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000529
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000530 // Otherwise, indent the appropriate number of spaces.
531 for (; ColNo > 1; --ColNo)
Chris Lattner068529a2008-08-17 03:12:02 +0000532 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000533
Chris Lattner3ed83c12007-12-09 21:11:08 +0000534 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000535}
536
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000537void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
538 unsigned Len) {
539 unsigned NumNewlines = 0;
540 for (; Len; --Len, ++TokStr) {
541 if (*TokStr != '\n' &&
542 *TokStr != '\r')
543 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000544
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000545 ++NumNewlines;
Mike Stump11289f42009-09-09 15:08:12 +0000546
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000547 // If we have \n\r or \r\n, skip both and count as one line.
548 if (Len != 1 &&
549 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
550 TokStr[0] != TokStr[1])
551 ++TokStr, --Len;
552 }
Mike Stump11289f42009-09-09 15:08:12 +0000553
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000554 if (NumNewlines == 0) return;
Mike Stump11289f42009-09-09 15:08:12 +0000555
Chris Lattnera5e67752009-06-15 04:08:28 +0000556 CurLine += NumNewlines;
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000557}
558
559
Chris Lattner5de858c2006-07-04 19:04:44 +0000560namespace {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000561struct UnknownPragmaHandler : public PragmaHandler {
562 const char *Prefix;
Chris Lattner87f267e2006-11-21 05:02:33 +0000563 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump11289f42009-09-09 15:08:12 +0000564
Chris Lattner87f267e2006-11-21 05:02:33 +0000565 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000566 : Prefix(prefix), Callbacks(callbacks) {}
Craig Topperafa7cb32014-03-13 06:07:04 +0000567 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
568 Token &PragmaTok) override {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000569 // Figure out what line we went to and insert the appropriate number of
570 // newline characters.
Jordan Rose127f6ee2012-06-15 23:33:51 +0000571 Callbacks->startNewLineIfNeeded();
Chris Lattner87f267e2006-11-21 05:02:33 +0000572 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattner068529a2008-08-17 03:12:02 +0000573 Callbacks->OS.write(Prefix, strlen(Prefix));
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000574 // Read and print all of the pragma tokens.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000575 while (PragmaTok.isNot(tok::eod)) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000576 if (PragmaTok.hasLeadingSpace())
Chris Lattner068529a2008-08-17 03:12:02 +0000577 Callbacks->OS << ' ';
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000578 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattner068529a2008-08-17 03:12:02 +0000579 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Kleckner0e73ec42014-02-20 22:59:51 +0000580
581 // Expand macros in pragmas with -fms-extensions. The assumption is that
582 // the majority of pragmas in such a file will be Microsoft pragmas.
583 if (PP.getLangOpts().MicrosoftExt)
584 PP.Lex(PragmaTok);
585 else
586 PP.LexUnexpandedToken(PragmaTok);
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000587 }
Jordan Rose127f6ee2012-06-15 23:33:51 +0000588 Callbacks->setEmittedDirectiveOnThisLine();
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000589 }
590};
Chris Lattner5de858c2006-07-04 19:04:44 +0000591} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000592
Chris Lattner4418ce12007-07-23 06:09:34 +0000593
Chris Lattnerfc001b02009-02-06 05:56:11 +0000594static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
595 PrintPPOutputPPCallbacks *Callbacks,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000596 raw_ostream &OS) {
Jordan Rose67b66232013-03-05 23:54:55 +0000597 bool DropComments = PP.getLangOpts().TraditionalCPP &&
598 !PP.getCommentRetentionState();
599
Benjamin Kramer718f7222010-02-27 18:02:51 +0000600 char Buffer[256];
Chris Lattnerbba37f42010-06-15 21:06:38 +0000601 Token PrevPrevTok, PrevTok;
602 PrevPrevTok.startToken();
603 PrevTok.startToken();
Chris Lattner3ff2e692007-10-10 20:45:16 +0000604 while (1) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000605 if (Callbacks->hasEmittedDirectiveOnThisLine()) {
606 Callbacks->startNewLineIfNeeded();
607 Callbacks->MoveToLine(Tok.getLocation());
608 }
Mike Stump11289f42009-09-09 15:08:12 +0000609
Chris Lattner67c38482006-07-04 23:24:26 +0000610 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000611 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
612 // done.
Mike Stump11289f42009-09-09 15:08:12 +0000613 } else if (Tok.hasLeadingSpace() ||
Chris Lattner4418ce12007-07-23 06:09:34 +0000614 // If we haven't emitted a token on this line yet, PrevTok isn't
615 // useful to look at and no concatenation could happen anyway.
Chris Lattnerd63c8a52007-07-23 23:21:34 +0000616 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattner4418ce12007-07-23 06:09:34 +0000617 // Don't print "-" next to "-", it would form "--".
Chris Lattner0384e6352010-04-14 03:57:19 +0000618 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattner068529a2008-08-17 03:12:02 +0000619 OS << ' ';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000620 }
Mike Stump11289f42009-09-09 15:08:12 +0000621
Jordan Rose67b66232013-03-05 23:54:55 +0000622 if (DropComments && Tok.is(tok::comment)) {
623 // Skip comments. Normally the preprocessor does not generate
624 // tok::comment nodes at all when not keeping comments, but under
625 // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
626 SourceLocation StartLoc = Tok.getLocation();
627 Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
Ben Langmuir5eb7cb72014-01-30 21:50:18 +0000628 } else if (Tok.is(tok::annot_module_include) ||
629 Tok.is(tok::annot_module_begin) ||
630 Tok.is(tok::annot_module_end)) {
631 // PrintPPOutputPPCallbacks::InclusionDirective handles producing
632 // appropriate output here. Ignore this token entirely.
Richard Smithce587f52013-11-15 04:24:58 +0000633 PP.Lex(Tok);
634 continue;
Jordan Rose67b66232013-03-05 23:54:55 +0000635 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
Benjamin Kramer718f7222010-02-27 18:02:51 +0000636 OS << II->getName();
637 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
638 Tok.getLiteralData()) {
639 OS.write(Tok.getLiteralData(), Tok.getLength());
640 } else if (Tok.getLength() < 256) {
641 const char *TokPtr = Buffer;
642 unsigned Len = PP.getSpelling(Tok, TokPtr);
643 OS.write(TokPtr, Len);
Mike Stump11289f42009-09-09 15:08:12 +0000644
Benjamin Kramer718f7222010-02-27 18:02:51 +0000645 // Tokens that can contain embedded newlines need to adjust our current
646 // line number.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000647 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramer718f7222010-02-27 18:02:51 +0000648 Callbacks->HandleNewlinesInToken(TokPtr, Len);
649 } else {
650 std::string S = PP.getSpelling(Tok);
651 OS.write(&S[0], S.size());
652
653 // Tokens that can contain embedded newlines need to adjust our current
654 // line number.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000655 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramer718f7222010-02-27 18:02:51 +0000656 Callbacks->HandleNewlinesInToken(&S[0], S.size());
657 }
Jordan Rose127f6ee2012-06-15 23:33:51 +0000658 Callbacks->setEmittedTokensOnThisLine();
Mike Stump11289f42009-09-09 15:08:12 +0000659
Chris Lattner3ff2e692007-10-10 20:45:16 +0000660 if (Tok.is(tok::eof)) break;
Mike Stump11289f42009-09-09 15:08:12 +0000661
Chris Lattner0384e6352010-04-14 03:57:19 +0000662 PrevPrevTok = PrevTok;
Chris Lattner3ff2e692007-10-10 20:45:16 +0000663 PrevTok = Tok;
664 PP.Lex(Tok);
665 }
Chris Lattnerfc001b02009-02-06 05:56:11 +0000666}
667
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000668typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
669static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
670 return LHS->first->getName().compare(RHS->first->getName());
671}
672
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000673static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
Daniel Dunbard839e772010-06-11 20:10:12 +0000674 // Ignore unknown pragmas.
Lubos Lunak576a0412014-05-01 12:54:03 +0000675 PP.IgnorePragmas();
Daniel Dunbard839e772010-06-11 20:10:12 +0000676
Eli Friedman26c672b2009-05-19 01:32:34 +0000677 // -dM mode just scans and ignores all tokens in the files, then dumps out
678 // the macro table at the end.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000679 PP.EnterMainSourceFile();
Eli Friedman26c672b2009-05-19 01:32:34 +0000680
681 Token Tok;
682 do PP.Lex(Tok);
683 while (Tok.isNot(tok::eof));
684
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000685 SmallVector<id_macro_pair, 128> MacrosByID;
686 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
687 I != E; ++I) {
Richard Smith20e883e2015-04-29 23:20:19 +0000688 auto *MD = I->second.getLatest();
689 if (MD && MD->isDefined())
690 MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000691 }
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000692 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedman26c672b2009-05-19 01:32:34 +0000693
694 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
695 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000696 // Ignore computed macros like __LINE__ and friends.
Eli Friedman26c672b2009-05-19 01:32:34 +0000697 if (MI.isBuiltinMacro()) continue;
698
699 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +0000700 *OS << '\n';
Eli Friedman26c672b2009-05-19 01:32:34 +0000701 }
702}
703
Chris Lattnerfc001b02009-02-06 05:56:11 +0000704/// DoPrintPreprocessedInput - This implements -E mode.
705///
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000706void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
Daniel Dunbar22bdabf2009-11-11 10:07:44 +0000707 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000708 // Show macros with no output is handled specially.
709 if (!Opts.ShowCPP) {
710 assert(Opts.ShowMacros && "Not yet implemented!");
711 DoPrintMacros(PP, OS);
712 return;
713 }
714
Chris Lattnerfc001b02009-02-06 05:56:11 +0000715 // Inform the preprocessor whether we want it to retain comments or not, due
716 // to -C or -CC.
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000717 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanfcb57d52009-05-19 01:02:07 +0000718
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000719 PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
720 PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros, Opts.UseLineDirectives);
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000721 PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
Chris Lattner49609d52010-11-10 01:00:49 +0000722 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
723 PP.AddPragmaHandler("clang",
724 new UnknownPragmaHandler("#pragma clang", Callbacks));
Chris Lattnerfc001b02009-02-06 05:56:11 +0000725
Craig Topperb8a70532014-09-10 04:53:53 +0000726 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
Chris Lattnerfc001b02009-02-06 05:56:11 +0000727
Eli Friedman26c672b2009-05-19 01:32:34 +0000728 // After we have configured the preprocessor, enter the main file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000729 PP.EnterMainSourceFile();
Chris Lattnerfc001b02009-02-06 05:56:11 +0000730
Eli Friedman26c672b2009-05-19 01:32:34 +0000731 // Consume all of the tokens that come from the predefines buffer. Those
732 // should not be emitted into the output and are guaranteed to be at the
733 // start.
734 const SourceManager &SourceMgr = PP.getSourceManager();
735 Token Tok;
Douglas Gregor453b0122010-11-12 07:15:47 +0000736 do {
737 PP.Lex(Tok);
738 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
739 break;
740
741 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
742 if (PLoc.isInvalid())
743 break;
744
745 if (strcmp(PLoc.getFilename(), "<built-in>"))
746 break;
747 } while (true);
Chris Lattnerfc001b02009-02-06 05:56:11 +0000748
Eli Friedman26c672b2009-05-19 01:32:34 +0000749 // Read all the preprocessed tokens, printing them out to the stream.
750 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
751 *OS << '\n';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000752}