blob: d48b952ef20327b9bfd9ad9d14b3f205a14c0335 [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;
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +000096 bool DumpIncludeDirectives;
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,
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000101 bool defines, bool DumpIncludeDirectives,
102 bool UseLineDirectives)
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000103 : PP(pp), SM(PP.getSourceManager()), ConcatInfo(PP), OS(os),
104 DisableLineMarkers(lineMarkers), DumpDefines(defines),
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000105 DumpIncludeDirectives(DumpIncludeDirectives),
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000106 UseLineDirectives(UseLineDirectives) {
Daniel Dunbar27734fd2011-02-02 15:41:17 +0000107 CurLine = 0;
Chris Lattner4c4a2452007-07-24 06:57:14 +0000108 CurFilename += "<uninit>";
Chris Lattner87f267e2006-11-21 05:02:33 +0000109 EmittedTokensOnThisLine = false;
Jordan Rose127f6ee2012-06-15 23:33:51 +0000110 EmittedDirectiveOnThisLine = false;
Chris Lattnerb03dc762008-09-26 21:18:42 +0000111 FileType = SrcMgr::C_User;
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000112 Initialized = false;
Daniel Dunbar5d388752012-11-16 01:51:11 +0000113 IsFirstFileEntered = false;
Chris Lattner87f267e2006-11-21 05:02:33 +0000114 }
Mike Stump11289f42009-09-09 15:08:12 +0000115
Jordan Rose127f6ee2012-06-15 23:33:51 +0000116 void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattner4418ce12007-07-23 06:09:34 +0000117 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Mike Stump11289f42009-09-09 15:08:12 +0000118
Jordan Rose127f6ee2012-06-15 23:33:51 +0000119 void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
120 bool hasEmittedDirectiveOnThisLine() const {
121 return EmittedDirectiveOnThisLine;
122 }
123
124 bool startNewLineIfNeeded(bool ShouldUpdateCurrentLine = true);
Craig Topperafa7cb32014-03-13 06:07:04 +0000125
126 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
127 SrcMgr::CharacteristicKind FileType,
128 FileID PrevFID) override;
129 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
130 StringRef FileName, bool IsAngled,
131 CharSourceRange FilenameRange, const FileEntry *File,
132 StringRef SearchPath, StringRef RelativePath,
133 const Module *Imported) override;
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000134 void Ident(SourceLocation Loc, StringRef str) override;
Craig Topperafa7cb32014-03-13 06:07:04 +0000135 void PragmaMessage(SourceLocation Loc, StringRef Namespace,
136 PragmaMessageKind Kind, StringRef Str) override;
137 void PragmaDebug(SourceLocation Loc, StringRef DebugType) override;
138 void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override;
139 void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override;
140 void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
Alp Tokerc726c362014-06-10 09:31:37 +0000141 diag::Severity Map, StringRef Str) override;
Craig Topperafa7cb32014-03-13 06:07:04 +0000142 void PragmaWarning(SourceLocation Loc, StringRef WarningSpec,
143 ArrayRef<int> Ids) override;
144 void PragmaWarningPush(SourceLocation Loc, int Level) override;
145 void PragmaWarningPop(SourceLocation Loc) override;
Chris Lattner87f267e2006-11-21 05:02:33 +0000146
Chris Lattner3ed83c12007-12-09 21:11:08 +0000147 bool HandleFirstTokOnLine(Token &Tok);
Hal Finkel2109f232013-01-28 04:37:37 +0000148
149 /// Move to the line of the provided source location. This will
150 /// return true if the output stream required adjustment or if
151 /// the requested location is on the first line.
Chris Lattner5dbefc62010-04-13 00:01:41 +0000152 bool MoveToLine(SourceLocation Loc) {
Douglas Gregor453b0122010-11-12 07:15:47 +0000153 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
154 if (PLoc.isInvalid())
155 return false;
Hal Finkel2109f232013-01-28 04:37:37 +0000156 return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
Chris Lattner5dbefc62010-04-13 00:01:41 +0000157 }
158 bool MoveToLine(unsigned LineNo);
159
Chris Lattner0384e6352010-04-14 03:57:19 +0000160 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
161 const Token &Tok) {
162 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
Chris Lattner644d4522009-02-13 00:46:04 +0000163 }
Craig Topper49a27902014-05-22 04:46:25 +0000164 void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
165 unsigned ExtraLen=0);
Douglas Gregorc7d65762010-09-09 22:45:38 +0000166 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000167 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump11289f42009-09-09 15:08:12 +0000168
Chris Lattnercac63f32009-04-12 01:56:53 +0000169 /// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Topperafa7cb32014-03-13 06:07:04 +0000170 void MacroDefined(const Token &MacroNameTok,
171 const MacroDirective *MD) override;
Mike Stump11289f42009-09-09 15:08:12 +0000172
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000173 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
Craig Topperafa7cb32014-03-13 06:07:04 +0000174 void MacroUndefined(const Token &MacroNameTok,
Richard Smith36bd40d2015-05-04 03:15:40 +0000175 const MacroDefinition &MD) override;
Chris Lattner87f267e2006-11-21 05:02:33 +0000176};
Chris Lattner21632652008-04-08 04:16:20 +0000177} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000178
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000179void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
180 const char *Extra,
181 unsigned ExtraLen) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000182 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000183
Chris Lattner76b44452009-12-07 01:42:56 +0000184 // Emit #line directives or GNU line markers depending on what mode we're in.
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000185 if (UseLineDirectives) {
Chris Lattner76b44452009-12-07 01:42:56 +0000186 OS << "#line" << ' ' << LineNo << ' ' << '"';
Eli Friedman80e45b82013-08-29 01:42:42 +0000187 OS.write_escaped(CurFilename);
Chris Lattner76b44452009-12-07 01:42:56 +0000188 OS << '"';
189 } else {
190 OS << '#' << ' ' << LineNo << ' ' << '"';
Eli Friedman80e45b82013-08-29 01:42:42 +0000191 OS.write_escaped(CurFilename);
Chris Lattner76b44452009-12-07 01:42:56 +0000192 OS << '"';
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +0000193
Steve Naroff66aaa392009-12-06 01:02:14 +0000194 if (ExtraLen)
195 OS.write(Extra, ExtraLen);
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000196
Steve Naroff66aaa392009-12-06 01:02:14 +0000197 if (FileType == SrcMgr::C_System)
198 OS.write(" 3", 2);
199 else if (FileType == SrcMgr::C_ExternCSystem)
200 OS.write(" 3 4", 4);
201 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000202 OS << '\n';
203}
204
Chris Lattner728b4dc2006-07-04 21:28:37 +0000205/// MoveToLine - Move the output to the source line specified by the location
206/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner3ed83c12007-12-09 21:11:08 +0000207/// #line directive. This returns false if already at the specified line, true
208/// if some newlines were emitted.
Chris Lattner5dbefc62010-04-13 00:01:41 +0000209bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000210 // If this line is "close enough" to the original line, just print newlines,
211 // otherwise print a #line directive.
Daniel Dunbare7781312008-09-26 01:13:35 +0000212 if (LineNo-CurLine <= 8) {
Chris Lattner5f075822007-07-23 05:14:05 +0000213 if (LineNo-CurLine == 1)
Chris Lattner068529a2008-08-17 03:12:02 +0000214 OS << '\n';
Chris Lattner3ed83c12007-12-09 21:11:08 +0000215 else if (LineNo == CurLine)
Chandler Carruth46a32c22011-07-14 16:14:52 +0000216 return false; // Spelling line moved, but expansion line didn't.
Chris Lattner5f075822007-07-23 05:14:05 +0000217 else {
218 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattner068529a2008-08-17 03:12:02 +0000219 OS.write(NewLines, LineNo-CurLine);
Chris Lattner5f075822007-07-23 05:14:05 +0000220 }
Chris Lattnerbc6bcab2010-06-12 16:20:56 +0000221 } else if (!DisableLineMarkers) {
222 // Emit a #line or line marker.
Craig Topper49a27902014-05-22 04:46:25 +0000223 WriteLineInfo(LineNo, nullptr, 0);
Chris Lattnerbc6bcab2010-06-12 16:20:56 +0000224 } else {
225 // Okay, we're in -P mode, which turns off line markers. However, we still
226 // need to emit a newline between tokens on different lines.
Jordan Rose127f6ee2012-06-15 23:33:51 +0000227 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Mike Stump11289f42009-09-09 15:08:12 +0000228 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000229
Mike Stump11289f42009-09-09 15:08:12 +0000230 CurLine = LineNo;
Chris Lattner3ed83c12007-12-09 21:11:08 +0000231 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000232}
233
Jordan Rose127f6ee2012-06-15 23:33:51 +0000234bool
235PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
236 if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
Douglas Gregorc7d65762010-09-09 22:45:38 +0000237 OS << '\n';
238 EmittedTokensOnThisLine = false;
Jordan Rose127f6ee2012-06-15 23:33:51 +0000239 EmittedDirectiveOnThisLine = false;
240 if (ShouldUpdateCurrentLine)
241 ++CurLine;
Douglas Gregorc7d65762010-09-09 22:45:38 +0000242 return true;
243 }
244
245 return false;
246}
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000247
248/// FileChanged - Whenever the preprocessor enters or exits a #include file
249/// it invokes this handler. Update our conception of the current source
250/// position.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000251void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
252 FileChangeReason Reason,
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000253 SrcMgr::CharacteristicKind NewFileType,
254 FileID PrevFID) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000255 // Unless we are exiting a #include, make sure to skip ahead to the line the
256 // #include directive was at.
Chris Lattner9d94f042010-04-13 00:06:42 +0000257 SourceManager &SourceMgr = SM;
Chris Lattner5dbefc62010-04-13 00:01:41 +0000258
259 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Douglas Gregor453b0122010-11-12 07:15:47 +0000260 if (UserLoc.isInvalid())
261 return;
262
Chris Lattnerc745cec2010-04-14 04:28:50 +0000263 unsigned NewLine = UserLoc.getLine();
Daniel Dunbard4352752010-08-24 22:44:13 +0000264
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000265 if (Reason == PPCallbacks::EnterFile) {
Douglas Gregor453b0122010-11-12 07:15:47 +0000266 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
Chris Lattnerd8cc8842009-01-30 18:44:17 +0000267 if (IncludeLoc.isValid())
268 MoveToLine(IncludeLoc);
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000269 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
Jordan Rose111c4a62013-04-17 19:09:18 +0000270 // GCC emits the # directive for this directive on the line AFTER the
271 // directive and emits a bunch of spaces that aren't needed. This is because
272 // otherwise we will emit a line marker for THIS line, which requires an
273 // extra blank line after the directive to avoid making all following lines
274 // off by one. We can do better by simply incrementing NewLine here.
275 NewLine += 1;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000276 }
Chris Lattner5dbefc62010-04-13 00:01:41 +0000277
278 CurLine = NewLine;
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000279
Chris Lattner4c4a2452007-07-24 06:57:14 +0000280 CurFilename.clear();
Chris Lattner5dbefc62010-04-13 00:01:41 +0000281 CurFilename += UserLoc.getFilename();
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000282 FileType = NewFileType;
283
Eli Friedmanc52435b2013-01-09 03:16:42 +0000284 if (DisableLineMarkers) {
285 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
286 return;
287 }
Daniel Dunbard4352752010-08-24 22:44:13 +0000288
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000289 if (!Initialized) {
290 WriteLineInfo(CurLine);
291 Initialized = true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000292 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000293
Daniel Dunbar5d388752012-11-16 01:51:11 +0000294 // Do not emit an enter marker for the main file (which we expect is the first
295 // entered file). This matches gcc, and improves compatibility with some tools
296 // which track the # line markers as a way to determine when the preprocessed
297 // output is in the context of the main file.
298 if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
299 IsFirstFileEntered = true;
300 return;
301 }
302
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000303 switch (Reason) {
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000304 case PPCallbacks::EnterFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000305 WriteLineInfo(CurLine, " 1", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000306 break;
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000307 case PPCallbacks::ExitFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000308 WriteLineInfo(CurLine, " 2", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000309 break;
Mike Stump11289f42009-09-09 15:08:12 +0000310 case PPCallbacks::SystemHeaderPragma:
311 case PPCallbacks::RenameFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000312 WriteLineInfo(CurLine);
313 break;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000314 }
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000315}
316
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000317void PrintPPOutputPPCallbacks::InclusionDirective(SourceLocation HashLoc,
318 const Token &IncludeTok,
319 StringRef FileName,
320 bool IsAngled,
321 CharSourceRange FilenameRange,
322 const FileEntry *File,
323 StringRef SearchPath,
324 StringRef RelativePath,
325 const Module *Imported) {
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000326 if (Imported) {
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000327 // When preprocessing, turn implicit imports into @imports.
328 // FIXME: This is a stop-gap until a more comprehensive "preprocessing with
329 // modules" solution is introduced.
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000330 startNewLineIfNeeded();
331 MoveToLine(HashLoc);
Richard Smith466a15e2016-04-08 00:09:53 +0000332 if (PP.getLangOpts().ObjC2) {
333 OS << "@import " << Imported->getFullModuleName() << ";"
334 << " /* clang -E: implicit import for \"" << File->getName()
335 << "\" */";
336 } else {
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000337 const std::string TokenText = PP.getSpelling(IncludeTok);
338 assert(!TokenText.empty());
339 OS << "#" << TokenText << " "
Richard Smith466a15e2016-04-08 00:09:53 +0000340 << (IsAngled ? '<' : '"')
341 << FileName
Richard Smith6a6747d2016-04-08 01:23:59 +0000342 << (IsAngled ? '>' : '"')
343 << " /* clang -E: implicit import for module "
344 << Imported->getFullModuleName() << " */";
Richard Smith466a15e2016-04-08 00:09:53 +0000345 }
Ben Langmuir5418f402014-09-10 21:29:41 +0000346 // Since we want a newline after the @import, but not a #<line>, start a new
347 // line immediately.
Argyrios Kyrtzidisc3b4b792013-04-29 17:26:22 +0000348 EmittedTokensOnThisLine = true;
Ben Langmuir5418f402014-09-10 21:29:41 +0000349 startNewLineIfNeeded();
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000350 } else {
351 // Not a module import; it's a more vanilla inclusion of some file using one
352 // of: #include, #import, #include_next, #include_macros.
353 if (DumpIncludeDirectives) {
354 startNewLineIfNeeded();
355 MoveToLine(HashLoc);
356 const std::string TokenText = PP.getSpelling(IncludeTok);
357 assert(!TokenText.empty());
358 OS << "#" << TokenText << " "
359 << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
360 << " /* clang -E -dI */";
361 setEmittedDirectiveOnThisLine();
362 startNewLineIfNeeded();
363 }
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000364 }
365}
366
Chris Lattner5eef5072009-01-16 19:25:54 +0000367/// Ident - Handle #ident directives when read by the preprocessor.
Chris Lattner728b4dc2006-07-04 21:28:37 +0000368///
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000369void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
Chris Lattner3338ba82006-07-04 21:19:39 +0000370 MoveToLine(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000371
Chris Lattner068529a2008-08-17 03:12:02 +0000372 OS.write("#ident ", strlen("#ident "));
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000373 OS.write(S.begin(), S.size());
Chris Lattner87f267e2006-11-21 05:02:33 +0000374 EmittedTokensOnThisLine = true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000375}
376
Chris Lattnercac63f32009-04-12 01:56:53 +0000377/// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000378void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000379 const MacroDirective *MD) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000380 const MacroInfo *MI = MD->getMacroInfo();
Chris Lattnercac63f32009-04-12 01:56:53 +0000381 // Only print out macro definitions in -dD mode.
382 if (!DumpDefines ||
383 // Ignore __FILE__ etc.
384 MI->isBuiltinMacro()) return;
Mike Stump11289f42009-09-09 15:08:12 +0000385
Chris Lattnercac63f32009-04-12 01:56:53 +0000386 MoveToLine(MI->getDefinitionLoc());
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000387 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
Jordan Rose127f6ee2012-06-15 23:33:51 +0000388 setEmittedDirectiveOnThisLine();
Chris Lattnercac63f32009-04-12 01:56:53 +0000389}
390
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000391void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
Richard Smith36bd40d2015-05-04 03:15:40 +0000392 const MacroDefinition &MD) {
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000393 // Only print out macro definitions in -dD mode.
394 if (!DumpDefines) return;
395
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000396 MoveToLine(MacroNameTok.getLocation());
397 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
Jordan Rose127f6ee2012-06-15 23:33:51 +0000398 setEmittedDirectiveOnThisLine();
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000399}
Chris Lattnercac63f32009-04-12 01:56:53 +0000400
Benjamin Kramer0772c422016-02-13 13:42:54 +0000401static void outputPrintable(raw_ostream &OS, StringRef Str) {
402 for (unsigned char Char : Str) {
403 if (isPrintable(Char) && Char != '\\' && Char != '"')
404 OS << (char)Char;
405 else // Output anything hard as an octal escape.
406 OS << '\\'
407 << (char)('0' + ((Char >> 6) & 7))
408 << (char)('0' + ((Char >> 3) & 7))
409 << (char)('0' + ((Char >> 0) & 7));
410 }
Aaron Ballman5d041be2013-06-04 02:07:14 +0000411}
412
Chris Lattner30c924b2010-06-26 17:11:39 +0000413void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000414 StringRef Namespace,
415 PragmaMessageKind Kind,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000416 StringRef Str) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000417 startNewLineIfNeeded();
Chris Lattner30c924b2010-06-26 17:11:39 +0000418 MoveToLine(Loc);
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000419 OS << "#pragma ";
420 if (!Namespace.empty())
421 OS << Namespace << ' ';
422 switch (Kind) {
423 case PMK_Message:
Andy Gibbsaa0b94a2013-04-19 17:13:17 +0000424 OS << "message(\"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000425 break;
426 case PMK_Warning:
Andy Gibbs96d93902013-04-18 16:49:37 +0000427 OS << "warning \"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000428 break;
429 case PMK_Error:
Andy Gibbs96d93902013-04-18 16:49:37 +0000430 OS << "error \"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000431 break;
432 }
Chris Lattner30c924b2010-06-26 17:11:39 +0000433
Aaron Ballman5d041be2013-06-04 02:07:14 +0000434 outputPrintable(OS, Str);
Chris Lattner30c924b2010-06-26 17:11:39 +0000435 OS << '"';
Andy Gibbsaa0b94a2013-04-19 17:13:17 +0000436 if (Kind == PMK_Message)
437 OS << ')';
Jordan Rose127f6ee2012-06-15 23:33:51 +0000438 setEmittedDirectiveOnThisLine();
Chris Lattner30c924b2010-06-26 17:11:39 +0000439}
440
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000441void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
442 StringRef DebugType) {
443 startNewLineIfNeeded();
444 MoveToLine(Loc);
445
446 OS << "#pragma clang __debug ";
447 OS << DebugType;
448
449 setEmittedDirectiveOnThisLine();
450}
451
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000452void PrintPPOutputPPCallbacks::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000453PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000454 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000455 MoveToLine(Loc);
456 OS << "#pragma " << Namespace << " diagnostic push";
Jordan Rose127f6ee2012-06-15 23:33:51 +0000457 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000458}
459
460void PrintPPOutputPPCallbacks::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000461PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000462 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000463 MoveToLine(Loc);
464 OS << "#pragma " << Namespace << " diagnostic pop";
Jordan Rose127f6ee2012-06-15 23:33:51 +0000465 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000466}
467
Alp Tokerc726c362014-06-10 09:31:37 +0000468void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
469 StringRef Namespace,
470 diag::Severity Map,
471 StringRef Str) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000472 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000473 MoveToLine(Loc);
474 OS << "#pragma " << Namespace << " diagnostic ";
Benjamin Kramer7ec12c92012-02-07 22:29:24 +0000475 switch (Map) {
Alp Toker46df1c02014-06-12 10:15:20 +0000476 case diag::Severity::Remark:
Tobias Grosser74160242014-02-28 09:11:08 +0000477 OS << "remark";
478 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000479 case diag::Severity::Warning:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000480 OS << "warning";
481 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000482 case diag::Severity::Error:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000483 OS << "error";
484 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000485 case diag::Severity::Ignored:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000486 OS << "ignored";
487 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000488 case diag::Severity::Fatal:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000489 OS << "fatal";
490 break;
491 }
492 OS << " \"" << Str << '"';
Jordan Rose127f6ee2012-06-15 23:33:51 +0000493 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000494}
Chris Lattner5eef5072009-01-16 19:25:54 +0000495
Reid Kleckner881dff32013-09-13 22:00:30 +0000496void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
497 StringRef WarningSpec,
498 ArrayRef<int> Ids) {
499 startNewLineIfNeeded();
500 MoveToLine(Loc);
501 OS << "#pragma warning(" << WarningSpec << ':';
502 for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
503 OS << ' ' << *I;
504 OS << ')';
505 setEmittedDirectiveOnThisLine();
506}
507
508void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
509 int Level) {
510 startNewLineIfNeeded();
511 MoveToLine(Loc);
512 OS << "#pragma warning(push";
Reid Kleckner4d185102013-10-02 15:19:23 +0000513 if (Level >= 0)
Reid Kleckner881dff32013-09-13 22:00:30 +0000514 OS << ", " << Level;
515 OS << ')';
516 setEmittedDirectiveOnThisLine();
517}
518
519void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
520 startNewLineIfNeeded();
521 MoveToLine(Loc);
522 OS << "#pragma warning(pop)";
523 setEmittedDirectiveOnThisLine();
524}
525
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000526/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner3ed83c12007-12-09 21:11:08 +0000527/// is called for the first token on each new line. If this really is the start
528/// of a new logical line, handle it and return true, otherwise return false.
529/// This may not be the start of a logical line because the "start of line"
Chandler Carruth46a32c22011-07-14 16:14:52 +0000530/// marker is set for spelling lines, not expansion ones.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000531bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000532 // Figure out what line we went to and insert the appropriate number of
533 // newline characters.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000534 if (!MoveToLine(Tok.getLocation()))
535 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000536
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000537 // Print out space characters so that the first token on a line is
538 // indented for easy reading.
Chandler Carruth42f35f92011-07-25 20:57:57 +0000539 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000540
Richard Smith5b2f7c52014-02-24 20:50:36 +0000541 // The first token on a line can have a column number of 1, yet still expect
542 // leading white space, if a macro expansion in column 1 starts with an empty
543 // macro argument, or an empty nested macro expansion. In this case, move the
544 // token to column 2.
545 if (ColNo == 1 && Tok.hasLeadingSpace())
546 ColNo = 2;
547
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000548 // This hack prevents stuff like:
549 // #define HASH #
550 // HASH define foo bar
551 // From having the # character end up at column 1, which makes it so it
552 // is not handled as a #define next time through the preprocessor if in
553 // -fpreprocessed mode.
Chris Lattner3c69f122007-10-09 18:03:42 +0000554 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattner068529a2008-08-17 03:12:02 +0000555 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000556
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000557 // Otherwise, indent the appropriate number of spaces.
558 for (; ColNo > 1; --ColNo)
Chris Lattner068529a2008-08-17 03:12:02 +0000559 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000560
Chris Lattner3ed83c12007-12-09 21:11:08 +0000561 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000562}
563
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000564void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
565 unsigned Len) {
566 unsigned NumNewlines = 0;
567 for (; Len; --Len, ++TokStr) {
568 if (*TokStr != '\n' &&
569 *TokStr != '\r')
570 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000571
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000572 ++NumNewlines;
Mike Stump11289f42009-09-09 15:08:12 +0000573
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000574 // If we have \n\r or \r\n, skip both and count as one line.
575 if (Len != 1 &&
576 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
Richard Trieucc3949d2016-02-18 22:34:54 +0000577 TokStr[0] != TokStr[1]) {
578 ++TokStr;
579 --Len;
580 }
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000581 }
Mike Stump11289f42009-09-09 15:08:12 +0000582
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000583 if (NumNewlines == 0) return;
Mike Stump11289f42009-09-09 15:08:12 +0000584
Chris Lattnera5e67752009-06-15 04:08:28 +0000585 CurLine += NumNewlines;
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000586}
587
588
Chris Lattner5de858c2006-07-04 19:04:44 +0000589namespace {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000590struct UnknownPragmaHandler : public PragmaHandler {
591 const char *Prefix;
Chris Lattner87f267e2006-11-21 05:02:33 +0000592 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump11289f42009-09-09 15:08:12 +0000593
Samuel Antaoeab747b2015-06-15 23:44:27 +0000594 // Set to true if tokens should be expanded
595 bool ShouldExpandTokens;
596
597 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
598 bool RequireTokenExpansion)
599 : Prefix(prefix), Callbacks(callbacks),
600 ShouldExpandTokens(RequireTokenExpansion) {}
Craig Topperafa7cb32014-03-13 06:07:04 +0000601 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
602 Token &PragmaTok) override {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000603 // Figure out what line we went to and insert the appropriate number of
604 // newline characters.
Jordan Rose127f6ee2012-06-15 23:33:51 +0000605 Callbacks->startNewLineIfNeeded();
Chris Lattner87f267e2006-11-21 05:02:33 +0000606 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattner068529a2008-08-17 03:12:02 +0000607 Callbacks->OS.write(Prefix, strlen(Prefix));
Samuel Antaoeab747b2015-06-15 23:44:27 +0000608
Alexey Bataev56f5ad12016-02-09 11:01:58 +0000609 if (ShouldExpandTokens) {
610 // The first token does not have expanded macros. Expand them, if
611 // required.
David Blaikie2eabcc92016-02-09 18:52:09 +0000612 auto Toks = llvm::make_unique<Token[]>(1);
Alexey Bataev56f5ad12016-02-09 11:01:58 +0000613 Toks[0] = PragmaTok;
David Blaikie2eabcc92016-02-09 18:52:09 +0000614 PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
615 /*DisableMacroExpansion=*/false);
Alexey Bataev56f5ad12016-02-09 11:01:58 +0000616 PP.Lex(PragmaTok);
617 }
Samuel Antaoeab747b2015-06-15 23:44:27 +0000618 Token PrevToken;
619 Token PrevPrevToken;
620 PrevToken.startToken();
621 PrevPrevToken.startToken();
622
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000623 // Read and print all of the pragma tokens.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000624 while (PragmaTok.isNot(tok::eod)) {
Samuel Antaoeab747b2015-06-15 23:44:27 +0000625 if (PragmaTok.hasLeadingSpace() ||
626 Callbacks->AvoidConcat(PrevPrevToken, PrevToken, PragmaTok))
Chris Lattner068529a2008-08-17 03:12:02 +0000627 Callbacks->OS << ' ';
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000628 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattner068529a2008-08-17 03:12:02 +0000629 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Kleckner0e73ec42014-02-20 22:59:51 +0000630
Samuel Antaoeab747b2015-06-15 23:44:27 +0000631 PrevPrevToken = PrevToken;
632 PrevToken = PragmaTok;
633
634 if (ShouldExpandTokens)
Reid Kleckner0e73ec42014-02-20 22:59:51 +0000635 PP.Lex(PragmaTok);
636 else
637 PP.LexUnexpandedToken(PragmaTok);
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000638 }
Jordan Rose127f6ee2012-06-15 23:33:51 +0000639 Callbacks->setEmittedDirectiveOnThisLine();
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000640 }
641};
Chris Lattner5de858c2006-07-04 19:04:44 +0000642} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000643
Chris Lattner4418ce12007-07-23 06:09:34 +0000644
Chris Lattnerfc001b02009-02-06 05:56:11 +0000645static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
646 PrintPPOutputPPCallbacks *Callbacks,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000647 raw_ostream &OS) {
Jordan Rose67b66232013-03-05 23:54:55 +0000648 bool DropComments = PP.getLangOpts().TraditionalCPP &&
649 !PP.getCommentRetentionState();
650
Benjamin Kramer718f7222010-02-27 18:02:51 +0000651 char Buffer[256];
Chris Lattnerbba37f42010-06-15 21:06:38 +0000652 Token PrevPrevTok, PrevTok;
653 PrevPrevTok.startToken();
654 PrevTok.startToken();
Chris Lattner3ff2e692007-10-10 20:45:16 +0000655 while (1) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000656 if (Callbacks->hasEmittedDirectiveOnThisLine()) {
657 Callbacks->startNewLineIfNeeded();
658 Callbacks->MoveToLine(Tok.getLocation());
659 }
Mike Stump11289f42009-09-09 15:08:12 +0000660
Chris Lattner67c38482006-07-04 23:24:26 +0000661 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000662 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
663 // done.
Mike Stump11289f42009-09-09 15:08:12 +0000664 } else if (Tok.hasLeadingSpace() ||
Chris Lattner4418ce12007-07-23 06:09:34 +0000665 // If we haven't emitted a token on this line yet, PrevTok isn't
666 // useful to look at and no concatenation could happen anyway.
Chris Lattnerd63c8a52007-07-23 23:21:34 +0000667 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattner4418ce12007-07-23 06:09:34 +0000668 // Don't print "-" next to "-", it would form "--".
Chris Lattner0384e6352010-04-14 03:57:19 +0000669 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattner068529a2008-08-17 03:12:02 +0000670 OS << ' ';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000671 }
Mike Stump11289f42009-09-09 15:08:12 +0000672
Jordan Rose67b66232013-03-05 23:54:55 +0000673 if (DropComments && Tok.is(tok::comment)) {
674 // Skip comments. Normally the preprocessor does not generate
675 // tok::comment nodes at all when not keeping comments, but under
676 // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
677 SourceLocation StartLoc = Tok.getLocation();
678 Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
Ben Langmuir5eb7cb72014-01-30 21:50:18 +0000679 } else if (Tok.is(tok::annot_module_include) ||
680 Tok.is(tok::annot_module_begin) ||
681 Tok.is(tok::annot_module_end)) {
682 // PrintPPOutputPPCallbacks::InclusionDirective handles producing
683 // appropriate output here. Ignore this token entirely.
Richard Smithce587f52013-11-15 04:24:58 +0000684 PP.Lex(Tok);
685 continue;
Jordan Rose67b66232013-03-05 23:54:55 +0000686 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
Benjamin Kramer718f7222010-02-27 18:02:51 +0000687 OS << II->getName();
688 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
689 Tok.getLiteralData()) {
690 OS.write(Tok.getLiteralData(), Tok.getLength());
691 } else if (Tok.getLength() < 256) {
692 const char *TokPtr = Buffer;
693 unsigned Len = PP.getSpelling(Tok, TokPtr);
694 OS.write(TokPtr, Len);
Mike Stump11289f42009-09-09 15:08:12 +0000695
Benjamin Kramer718f7222010-02-27 18:02:51 +0000696 // Tokens that can contain embedded newlines need to adjust our current
697 // line number.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000698 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramer718f7222010-02-27 18:02:51 +0000699 Callbacks->HandleNewlinesInToken(TokPtr, Len);
700 } else {
701 std::string S = PP.getSpelling(Tok);
702 OS.write(&S[0], S.size());
703
704 // Tokens that can contain embedded newlines need to adjust our current
705 // line number.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000706 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramer718f7222010-02-27 18:02:51 +0000707 Callbacks->HandleNewlinesInToken(&S[0], S.size());
708 }
Jordan Rose127f6ee2012-06-15 23:33:51 +0000709 Callbacks->setEmittedTokensOnThisLine();
Mike Stump11289f42009-09-09 15:08:12 +0000710
Chris Lattner3ff2e692007-10-10 20:45:16 +0000711 if (Tok.is(tok::eof)) break;
Mike Stump11289f42009-09-09 15:08:12 +0000712
Chris Lattner0384e6352010-04-14 03:57:19 +0000713 PrevPrevTok = PrevTok;
Chris Lattner3ff2e692007-10-10 20:45:16 +0000714 PrevTok = Tok;
715 PP.Lex(Tok);
716 }
Chris Lattnerfc001b02009-02-06 05:56:11 +0000717}
718
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000719typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
720static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
721 return LHS->first->getName().compare(RHS->first->getName());
722}
723
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000724static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
Daniel Dunbard839e772010-06-11 20:10:12 +0000725 // Ignore unknown pragmas.
Lubos Lunak576a0412014-05-01 12:54:03 +0000726 PP.IgnorePragmas();
Daniel Dunbard839e772010-06-11 20:10:12 +0000727
Eli Friedman26c672b2009-05-19 01:32:34 +0000728 // -dM mode just scans and ignores all tokens in the files, then dumps out
729 // the macro table at the end.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000730 PP.EnterMainSourceFile();
Eli Friedman26c672b2009-05-19 01:32:34 +0000731
732 Token Tok;
733 do PP.Lex(Tok);
734 while (Tok.isNot(tok::eof));
735
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000736 SmallVector<id_macro_pair, 128> MacrosByID;
737 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
738 I != E; ++I) {
Richard Smith20e883e2015-04-29 23:20:19 +0000739 auto *MD = I->second.getLatest();
740 if (MD && MD->isDefined())
741 MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000742 }
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000743 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedman26c672b2009-05-19 01:32:34 +0000744
745 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
746 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000747 // Ignore computed macros like __LINE__ and friends.
Eli Friedman26c672b2009-05-19 01:32:34 +0000748 if (MI.isBuiltinMacro()) continue;
749
750 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +0000751 *OS << '\n';
Eli Friedman26c672b2009-05-19 01:32:34 +0000752 }
753}
754
Chris Lattnerfc001b02009-02-06 05:56:11 +0000755/// DoPrintPreprocessedInput - This implements -E mode.
756///
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000757void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
Daniel Dunbar22bdabf2009-11-11 10:07:44 +0000758 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000759 // Show macros with no output is handled specially.
760 if (!Opts.ShowCPP) {
761 assert(Opts.ShowMacros && "Not yet implemented!");
762 DoPrintMacros(PP, OS);
763 return;
764 }
765
Chris Lattnerfc001b02009-02-06 05:56:11 +0000766 // Inform the preprocessor whether we want it to retain comments or not, due
767 // to -C or -CC.
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000768 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanfcb57d52009-05-19 01:02:07 +0000769
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000770 PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000771 PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
772 Opts.ShowIncludeDirectives, Opts.UseLineDirectives);
Samuel Antaoeab747b2015-06-15 23:44:27 +0000773
774 // Expand macros in pragmas with -fms-extensions. The assumption is that
775 // the majority of pragmas in such a file will be Microsoft pragmas.
776 PP.AddPragmaHandler(new UnknownPragmaHandler(
777 "#pragma", Callbacks,
778 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
779 PP.AddPragmaHandler(
780 "GCC", new UnknownPragmaHandler(
781 "#pragma GCC", Callbacks,
782 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
783 PP.AddPragmaHandler(
784 "clang", new UnknownPragmaHandler(
785 "#pragma clang", Callbacks,
786 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
787
788 // The tokens after pragma omp need to be expanded.
789 //
790 // OpenMP [2.1, Directive format]
791 // Preprocessing tokens following the #pragma omp are subject to macro
792 // replacement.
793 PP.AddPragmaHandler("omp",
794 new UnknownPragmaHandler("#pragma omp", Callbacks,
795 /*RequireTokenExpansion=*/true));
Chris Lattnerfc001b02009-02-06 05:56:11 +0000796
Craig Topperb8a70532014-09-10 04:53:53 +0000797 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
Chris Lattnerfc001b02009-02-06 05:56:11 +0000798
Eli Friedman26c672b2009-05-19 01:32:34 +0000799 // After we have configured the preprocessor, enter the main file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000800 PP.EnterMainSourceFile();
Chris Lattnerfc001b02009-02-06 05:56:11 +0000801
Eli Friedman26c672b2009-05-19 01:32:34 +0000802 // Consume all of the tokens that come from the predefines buffer. Those
803 // should not be emitted into the output and are guaranteed to be at the
804 // start.
805 const SourceManager &SourceMgr = PP.getSourceManager();
806 Token Tok;
Douglas Gregor453b0122010-11-12 07:15:47 +0000807 do {
808 PP.Lex(Tok);
809 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
810 break;
811
812 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
813 if (PLoc.isInvalid())
814 break;
815
816 if (strcmp(PLoc.getFilename(), "<built-in>"))
817 break;
818 } while (true);
Chris Lattnerfc001b02009-02-06 05:56:11 +0000819
Eli Friedman26c672b2009-05-19 01:32:34 +0000820 // Read all the preprocessed tokens, printing them out to the stream.
821 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
822 *OS << '\n';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000823}