blob: 8ae9038316c2c8da1a7daefcb02ca4516bf574f1 [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 << '(';
Faisal Valiac506d72017-07-17 17:18:43 +000041 if (!MI.param_empty()) {
42 MacroInfo::param_iterator AI = MI.param_begin(), E = MI.param_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;
Eli Friedman16fee082017-09-27 23:29:37 +0000146 void PragmaAssumeNonNullBegin(SourceLocation Loc) override;
147 void PragmaAssumeNonNullEnd(SourceLocation Loc) override;
Chris Lattner87f267e2006-11-21 05:02:33 +0000148
Chris Lattner3ed83c12007-12-09 21:11:08 +0000149 bool HandleFirstTokOnLine(Token &Tok);
Hal Finkel2109f232013-01-28 04:37:37 +0000150
151 /// Move to the line of the provided source location. This will
152 /// return true if the output stream required adjustment or if
153 /// the requested location is on the first line.
Chris Lattner5dbefc62010-04-13 00:01:41 +0000154 bool MoveToLine(SourceLocation Loc) {
Douglas Gregor453b0122010-11-12 07:15:47 +0000155 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
156 if (PLoc.isInvalid())
157 return false;
Hal Finkel2109f232013-01-28 04:37:37 +0000158 return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
Chris Lattner5dbefc62010-04-13 00:01:41 +0000159 }
160 bool MoveToLine(unsigned LineNo);
161
Chris Lattner0384e6352010-04-14 03:57:19 +0000162 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
163 const Token &Tok) {
164 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
Chris Lattner644d4522009-02-13 00:46:04 +0000165 }
Craig Topper49a27902014-05-22 04:46:25 +0000166 void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
167 unsigned ExtraLen=0);
Douglas Gregorc7d65762010-09-09 22:45:38 +0000168 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000169 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump11289f42009-09-09 15:08:12 +0000170
Chris Lattnercac63f32009-04-12 01:56:53 +0000171 /// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Topperafa7cb32014-03-13 06:07:04 +0000172 void MacroDefined(const Token &MacroNameTok,
173 const MacroDirective *MD) override;
Mike Stump11289f42009-09-09 15:08:12 +0000174
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000175 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
Craig Topperafa7cb32014-03-13 06:07:04 +0000176 void MacroUndefined(const Token &MacroNameTok,
Vedant Kumar349a6242017-04-26 21:05:44 +0000177 const MacroDefinition &MD,
178 const MacroDirective *Undef) override;
Richard Smithd1386302017-05-04 00:29:54 +0000179
180 void BeginModule(const Module *M);
181 void EndModule(const Module *M);
Chris Lattner87f267e2006-11-21 05:02:33 +0000182};
Chris Lattner21632652008-04-08 04:16:20 +0000183} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000184
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000185void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
186 const char *Extra,
187 unsigned ExtraLen) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000188 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000189
Chris Lattner76b44452009-12-07 01:42:56 +0000190 // Emit #line directives or GNU line markers depending on what mode we're in.
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000191 if (UseLineDirectives) {
Chris Lattner76b44452009-12-07 01:42:56 +0000192 OS << "#line" << ' ' << LineNo << ' ' << '"';
Eli Friedman80e45b82013-08-29 01:42:42 +0000193 OS.write_escaped(CurFilename);
Chris Lattner76b44452009-12-07 01:42:56 +0000194 OS << '"';
195 } else {
196 OS << '#' << ' ' << LineNo << ' ' << '"';
Eli Friedman80e45b82013-08-29 01:42:42 +0000197 OS.write_escaped(CurFilename);
Chris Lattner76b44452009-12-07 01:42:56 +0000198 OS << '"';
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +0000199
Steve Naroff66aaa392009-12-06 01:02:14 +0000200 if (ExtraLen)
201 OS.write(Extra, ExtraLen);
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000202
Steve Naroff66aaa392009-12-06 01:02:14 +0000203 if (FileType == SrcMgr::C_System)
204 OS.write(" 3", 2);
205 else if (FileType == SrcMgr::C_ExternCSystem)
206 OS.write(" 3 4", 4);
207 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000208 OS << '\n';
209}
210
Chris Lattner728b4dc2006-07-04 21:28:37 +0000211/// MoveToLine - Move the output to the source line specified by the location
212/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner3ed83c12007-12-09 21:11:08 +0000213/// #line directive. This returns false if already at the specified line, true
214/// if some newlines were emitted.
Chris Lattner5dbefc62010-04-13 00:01:41 +0000215bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000216 // If this line is "close enough" to the original line, just print newlines,
217 // otherwise print a #line directive.
Daniel Dunbare7781312008-09-26 01:13:35 +0000218 if (LineNo-CurLine <= 8) {
Chris Lattner5f075822007-07-23 05:14:05 +0000219 if (LineNo-CurLine == 1)
Chris Lattner068529a2008-08-17 03:12:02 +0000220 OS << '\n';
Chris Lattner3ed83c12007-12-09 21:11:08 +0000221 else if (LineNo == CurLine)
Chandler Carruth46a32c22011-07-14 16:14:52 +0000222 return false; // Spelling line moved, but expansion line didn't.
Chris Lattner5f075822007-07-23 05:14:05 +0000223 else {
224 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattner068529a2008-08-17 03:12:02 +0000225 OS.write(NewLines, LineNo-CurLine);
Chris Lattner5f075822007-07-23 05:14:05 +0000226 }
Chris Lattnerbc6bcab2010-06-12 16:20:56 +0000227 } else if (!DisableLineMarkers) {
228 // Emit a #line or line marker.
Craig Topper49a27902014-05-22 04:46:25 +0000229 WriteLineInfo(LineNo, nullptr, 0);
Chris Lattnerbc6bcab2010-06-12 16:20:56 +0000230 } else {
231 // Okay, we're in -P mode, which turns off line markers. However, we still
232 // need to emit a newline between tokens on different lines.
Jordan Rose127f6ee2012-06-15 23:33:51 +0000233 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Mike Stump11289f42009-09-09 15:08:12 +0000234 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000235
Mike Stump11289f42009-09-09 15:08:12 +0000236 CurLine = LineNo;
Chris Lattner3ed83c12007-12-09 21:11:08 +0000237 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000238}
239
Jordan Rose127f6ee2012-06-15 23:33:51 +0000240bool
241PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
242 if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
Douglas Gregorc7d65762010-09-09 22:45:38 +0000243 OS << '\n';
244 EmittedTokensOnThisLine = false;
Jordan Rose127f6ee2012-06-15 23:33:51 +0000245 EmittedDirectiveOnThisLine = false;
246 if (ShouldUpdateCurrentLine)
247 ++CurLine;
Douglas Gregorc7d65762010-09-09 22:45:38 +0000248 return true;
249 }
250
251 return false;
252}
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000253
254/// FileChanged - Whenever the preprocessor enters or exits a #include file
255/// it invokes this handler. Update our conception of the current source
256/// position.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000257void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
258 FileChangeReason Reason,
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000259 SrcMgr::CharacteristicKind NewFileType,
260 FileID PrevFID) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000261 // Unless we are exiting a #include, make sure to skip ahead to the line the
262 // #include directive was at.
Chris Lattner9d94f042010-04-13 00:06:42 +0000263 SourceManager &SourceMgr = SM;
Chris Lattner5dbefc62010-04-13 00:01:41 +0000264
265 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Douglas Gregor453b0122010-11-12 07:15:47 +0000266 if (UserLoc.isInvalid())
267 return;
268
Chris Lattnerc745cec2010-04-14 04:28:50 +0000269 unsigned NewLine = UserLoc.getLine();
Daniel Dunbard4352752010-08-24 22:44:13 +0000270
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000271 if (Reason == PPCallbacks::EnterFile) {
Douglas Gregor453b0122010-11-12 07:15:47 +0000272 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
Chris Lattnerd8cc8842009-01-30 18:44:17 +0000273 if (IncludeLoc.isValid())
274 MoveToLine(IncludeLoc);
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000275 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
Jordan Rose111c4a62013-04-17 19:09:18 +0000276 // GCC emits the # directive for this directive on the line AFTER the
277 // directive and emits a bunch of spaces that aren't needed. This is because
278 // otherwise we will emit a line marker for THIS line, which requires an
279 // extra blank line after the directive to avoid making all following lines
280 // off by one. We can do better by simply incrementing NewLine here.
281 NewLine += 1;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000282 }
Chris Lattner5dbefc62010-04-13 00:01:41 +0000283
284 CurLine = NewLine;
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000285
Chris Lattner4c4a2452007-07-24 06:57:14 +0000286 CurFilename.clear();
Chris Lattner5dbefc62010-04-13 00:01:41 +0000287 CurFilename += UserLoc.getFilename();
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000288 FileType = NewFileType;
289
Eli Friedmanc52435b2013-01-09 03:16:42 +0000290 if (DisableLineMarkers) {
291 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
292 return;
293 }
Daniel Dunbard4352752010-08-24 22:44:13 +0000294
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000295 if (!Initialized) {
296 WriteLineInfo(CurLine);
297 Initialized = true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000298 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000299
Daniel Dunbar5d388752012-11-16 01:51:11 +0000300 // Do not emit an enter marker for the main file (which we expect is the first
301 // entered file). This matches gcc, and improves compatibility with some tools
302 // which track the # line markers as a way to determine when the preprocessed
303 // output is in the context of the main file.
304 if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
305 IsFirstFileEntered = true;
306 return;
307 }
308
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000309 switch (Reason) {
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000310 case PPCallbacks::EnterFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000311 WriteLineInfo(CurLine, " 1", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000312 break;
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000313 case PPCallbacks::ExitFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000314 WriteLineInfo(CurLine, " 2", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000315 break;
Mike Stump11289f42009-09-09 15:08:12 +0000316 case PPCallbacks::SystemHeaderPragma:
317 case PPCallbacks::RenameFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000318 WriteLineInfo(CurLine);
319 break;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000320 }
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000321}
322
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000323void PrintPPOutputPPCallbacks::InclusionDirective(SourceLocation HashLoc,
324 const Token &IncludeTok,
325 StringRef FileName,
326 bool IsAngled,
327 CharSourceRange FilenameRange,
328 const FileEntry *File,
329 StringRef SearchPath,
330 StringRef RelativePath,
331 const Module *Imported) {
Richard Smithc51c38b2017-04-29 00:34:47 +0000332 // In -dI mode, dump #include directives prior to dumping their content or
333 // interpretation.
334 if (DumpIncludeDirectives) {
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000335 startNewLineIfNeeded();
336 MoveToLine(HashLoc);
Richard Smithc51c38b2017-04-29 00:34:47 +0000337 const std::string TokenText = PP.getSpelling(IncludeTok);
338 assert(!TokenText.empty());
339 OS << "#" << TokenText << " "
340 << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
341 << " /* clang -E -dI */";
342 setEmittedDirectiveOnThisLine();
Ben Langmuir5418f402014-09-10 21:29:41 +0000343 startNewLineIfNeeded();
Richard Smithc51c38b2017-04-29 00:34:47 +0000344 }
345
346 // When preprocessing, turn implicit imports into module import pragmas.
347 if (Imported) {
348 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
349 case tok::pp_include:
350 case tok::pp_import:
351 case tok::pp_include_next:
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000352 startNewLineIfNeeded();
353 MoveToLine(HashLoc);
Richard Smith9565c75b2017-06-19 23:09:36 +0000354 OS << "#pragma clang module import " << Imported->getFullModuleName(true)
Richard Smithc51c38b2017-04-29 00:34:47 +0000355 << " /* clang -E: implicit import for "
356 << "#" << PP.getSpelling(IncludeTok) << " "
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000357 << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
Richard Smithc51c38b2017-04-29 00:34:47 +0000358 << " */";
359 // Since we want a newline after the pragma, but not a #<line>, start a
360 // new line immediately.
361 EmittedTokensOnThisLine = true;
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000362 startNewLineIfNeeded();
Richard Smithc51c38b2017-04-29 00:34:47 +0000363 break;
364
365 case tok::pp___include_macros:
366 // #__include_macros has no effect on a user of a preprocessed source
367 // file; the only effect is on preprocessing.
368 //
369 // FIXME: That's not *quite* true: it causes the module in question to
370 // be loaded, which can affect downstream diagnostics.
371 break;
372
373 default:
374 llvm_unreachable("unknown include directive kind");
375 break;
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000376 }
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000377 }
378}
379
Richard Smithd1386302017-05-04 00:29:54 +0000380/// Handle entering the scope of a module during a module compilation.
381void PrintPPOutputPPCallbacks::BeginModule(const Module *M) {
382 startNewLineIfNeeded();
Richard Smith9565c75b2017-06-19 23:09:36 +0000383 OS << "#pragma clang module begin " << M->getFullModuleName(true);
Richard Smithd1386302017-05-04 00:29:54 +0000384 setEmittedDirectiveOnThisLine();
385}
386
387/// Handle leaving the scope of a module during a module compilation.
388void PrintPPOutputPPCallbacks::EndModule(const Module *M) {
389 startNewLineIfNeeded();
Richard Smith9565c75b2017-06-19 23:09:36 +0000390 OS << "#pragma clang module end /*" << M->getFullModuleName(true) << "*/";
Richard Smithd1386302017-05-04 00:29:54 +0000391 setEmittedDirectiveOnThisLine();
392}
393
Chris Lattner5eef5072009-01-16 19:25:54 +0000394/// Ident - Handle #ident directives when read by the preprocessor.
Chris Lattner728b4dc2006-07-04 21:28:37 +0000395///
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000396void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
Chris Lattner3338ba82006-07-04 21:19:39 +0000397 MoveToLine(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000398
Chris Lattner068529a2008-08-17 03:12:02 +0000399 OS.write("#ident ", strlen("#ident "));
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000400 OS.write(S.begin(), S.size());
Chris Lattner87f267e2006-11-21 05:02:33 +0000401 EmittedTokensOnThisLine = true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000402}
403
Chris Lattnercac63f32009-04-12 01:56:53 +0000404/// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000405void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000406 const MacroDirective *MD) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000407 const MacroInfo *MI = MD->getMacroInfo();
Chris Lattnercac63f32009-04-12 01:56:53 +0000408 // Only print out macro definitions in -dD mode.
409 if (!DumpDefines ||
410 // Ignore __FILE__ etc.
411 MI->isBuiltinMacro()) return;
Mike Stump11289f42009-09-09 15:08:12 +0000412
Chris Lattnercac63f32009-04-12 01:56:53 +0000413 MoveToLine(MI->getDefinitionLoc());
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000414 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
Jordan Rose127f6ee2012-06-15 23:33:51 +0000415 setEmittedDirectiveOnThisLine();
Chris Lattnercac63f32009-04-12 01:56:53 +0000416}
417
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000418void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
Vedant Kumar349a6242017-04-26 21:05:44 +0000419 const MacroDefinition &MD,
420 const MacroDirective *Undef) {
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000421 // Only print out macro definitions in -dD mode.
422 if (!DumpDefines) return;
423
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000424 MoveToLine(MacroNameTok.getLocation());
425 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
Jordan Rose127f6ee2012-06-15 23:33:51 +0000426 setEmittedDirectiveOnThisLine();
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000427}
Chris Lattnercac63f32009-04-12 01:56:53 +0000428
Benjamin Kramer0772c422016-02-13 13:42:54 +0000429static void outputPrintable(raw_ostream &OS, StringRef Str) {
430 for (unsigned char Char : Str) {
431 if (isPrintable(Char) && Char != '\\' && Char != '"')
432 OS << (char)Char;
433 else // Output anything hard as an octal escape.
434 OS << '\\'
435 << (char)('0' + ((Char >> 6) & 7))
436 << (char)('0' + ((Char >> 3) & 7))
437 << (char)('0' + ((Char >> 0) & 7));
438 }
Aaron Ballman5d041be2013-06-04 02:07:14 +0000439}
440
Chris Lattner30c924b2010-06-26 17:11:39 +0000441void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000442 StringRef Namespace,
443 PragmaMessageKind Kind,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000444 StringRef Str) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000445 startNewLineIfNeeded();
Chris Lattner30c924b2010-06-26 17:11:39 +0000446 MoveToLine(Loc);
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000447 OS << "#pragma ";
448 if (!Namespace.empty())
449 OS << Namespace << ' ';
450 switch (Kind) {
451 case PMK_Message:
Andy Gibbsaa0b94a2013-04-19 17:13:17 +0000452 OS << "message(\"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000453 break;
454 case PMK_Warning:
Andy Gibbs96d93902013-04-18 16:49:37 +0000455 OS << "warning \"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000456 break;
457 case PMK_Error:
Andy Gibbs96d93902013-04-18 16:49:37 +0000458 OS << "error \"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000459 break;
460 }
Chris Lattner30c924b2010-06-26 17:11:39 +0000461
Aaron Ballman5d041be2013-06-04 02:07:14 +0000462 outputPrintable(OS, Str);
Chris Lattner30c924b2010-06-26 17:11:39 +0000463 OS << '"';
Andy Gibbsaa0b94a2013-04-19 17:13:17 +0000464 if (Kind == PMK_Message)
465 OS << ')';
Jordan Rose127f6ee2012-06-15 23:33:51 +0000466 setEmittedDirectiveOnThisLine();
Chris Lattner30c924b2010-06-26 17:11:39 +0000467}
468
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000469void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
470 StringRef DebugType) {
471 startNewLineIfNeeded();
472 MoveToLine(Loc);
473
474 OS << "#pragma clang __debug ";
475 OS << DebugType;
476
477 setEmittedDirectiveOnThisLine();
478}
479
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000480void PrintPPOutputPPCallbacks::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000481PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000482 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000483 MoveToLine(Loc);
484 OS << "#pragma " << Namespace << " diagnostic push";
Jordan Rose127f6ee2012-06-15 23:33:51 +0000485 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000486}
487
488void PrintPPOutputPPCallbacks::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000489PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000490 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000491 MoveToLine(Loc);
492 OS << "#pragma " << Namespace << " diagnostic pop";
Jordan Rose127f6ee2012-06-15 23:33:51 +0000493 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000494}
495
Alp Tokerc726c362014-06-10 09:31:37 +0000496void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
497 StringRef Namespace,
498 diag::Severity Map,
499 StringRef Str) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000500 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000501 MoveToLine(Loc);
502 OS << "#pragma " << Namespace << " diagnostic ";
Benjamin Kramer7ec12c92012-02-07 22:29:24 +0000503 switch (Map) {
Alp Toker46df1c02014-06-12 10:15:20 +0000504 case diag::Severity::Remark:
Tobias Grosser74160242014-02-28 09:11:08 +0000505 OS << "remark";
506 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000507 case diag::Severity::Warning:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000508 OS << "warning";
509 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000510 case diag::Severity::Error:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000511 OS << "error";
512 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000513 case diag::Severity::Ignored:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000514 OS << "ignored";
515 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000516 case diag::Severity::Fatal:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000517 OS << "fatal";
518 break;
519 }
520 OS << " \"" << Str << '"';
Jordan Rose127f6ee2012-06-15 23:33:51 +0000521 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000522}
Chris Lattner5eef5072009-01-16 19:25:54 +0000523
Reid Kleckner881dff32013-09-13 22:00:30 +0000524void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
525 StringRef WarningSpec,
526 ArrayRef<int> Ids) {
527 startNewLineIfNeeded();
528 MoveToLine(Loc);
529 OS << "#pragma warning(" << WarningSpec << ':';
530 for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
531 OS << ' ' << *I;
532 OS << ')';
533 setEmittedDirectiveOnThisLine();
534}
535
536void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
537 int Level) {
538 startNewLineIfNeeded();
539 MoveToLine(Loc);
540 OS << "#pragma warning(push";
Reid Kleckner4d185102013-10-02 15:19:23 +0000541 if (Level >= 0)
Reid Kleckner881dff32013-09-13 22:00:30 +0000542 OS << ", " << Level;
543 OS << ')';
544 setEmittedDirectiveOnThisLine();
545}
546
547void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
548 startNewLineIfNeeded();
549 MoveToLine(Loc);
550 OS << "#pragma warning(pop)";
551 setEmittedDirectiveOnThisLine();
552}
553
Eli Friedman16fee082017-09-27 23:29:37 +0000554void PrintPPOutputPPCallbacks::
555PragmaAssumeNonNullBegin(SourceLocation Loc) {
556 startNewLineIfNeeded();
557 MoveToLine(Loc);
558 OS << "#pragma clang assume_nonnull begin";
559 setEmittedDirectiveOnThisLine();
560}
561
562void PrintPPOutputPPCallbacks::
563PragmaAssumeNonNullEnd(SourceLocation Loc) {
564 startNewLineIfNeeded();
565 MoveToLine(Loc);
566 OS << "#pragma clang assume_nonnull end";
567 setEmittedDirectiveOnThisLine();
568}
569
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000570/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner3ed83c12007-12-09 21:11:08 +0000571/// is called for the first token on each new line. If this really is the start
572/// of a new logical line, handle it and return true, otherwise return false.
573/// This may not be the start of a logical line because the "start of line"
Chandler Carruth46a32c22011-07-14 16:14:52 +0000574/// marker is set for spelling lines, not expansion ones.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000575bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000576 // Figure out what line we went to and insert the appropriate number of
577 // newline characters.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000578 if (!MoveToLine(Tok.getLocation()))
579 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000580
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000581 // Print out space characters so that the first token on a line is
582 // indented for easy reading.
Chandler Carruth42f35f92011-07-25 20:57:57 +0000583 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000584
Richard Smith5b2f7c52014-02-24 20:50:36 +0000585 // The first token on a line can have a column number of 1, yet still expect
586 // leading white space, if a macro expansion in column 1 starts with an empty
587 // macro argument, or an empty nested macro expansion. In this case, move the
588 // token to column 2.
589 if (ColNo == 1 && Tok.hasLeadingSpace())
590 ColNo = 2;
591
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000592 // This hack prevents stuff like:
593 // #define HASH #
594 // HASH define foo bar
595 // From having the # character end up at column 1, which makes it so it
596 // is not handled as a #define next time through the preprocessor if in
597 // -fpreprocessed mode.
Chris Lattner3c69f122007-10-09 18:03:42 +0000598 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattner068529a2008-08-17 03:12:02 +0000599 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000600
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000601 // Otherwise, indent the appropriate number of spaces.
602 for (; ColNo > 1; --ColNo)
Chris Lattner068529a2008-08-17 03:12:02 +0000603 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000604
Chris Lattner3ed83c12007-12-09 21:11:08 +0000605 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000606}
607
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000608void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
609 unsigned Len) {
610 unsigned NumNewlines = 0;
611 for (; Len; --Len, ++TokStr) {
612 if (*TokStr != '\n' &&
613 *TokStr != '\r')
614 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000615
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000616 ++NumNewlines;
Mike Stump11289f42009-09-09 15:08:12 +0000617
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000618 // If we have \n\r or \r\n, skip both and count as one line.
619 if (Len != 1 &&
620 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
Richard Trieucc3949d2016-02-18 22:34:54 +0000621 TokStr[0] != TokStr[1]) {
622 ++TokStr;
623 --Len;
624 }
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000625 }
Mike Stump11289f42009-09-09 15:08:12 +0000626
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000627 if (NumNewlines == 0) return;
Mike Stump11289f42009-09-09 15:08:12 +0000628
Chris Lattnera5e67752009-06-15 04:08:28 +0000629 CurLine += NumNewlines;
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000630}
631
632
Chris Lattner5de858c2006-07-04 19:04:44 +0000633namespace {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000634struct UnknownPragmaHandler : public PragmaHandler {
635 const char *Prefix;
Chris Lattner87f267e2006-11-21 05:02:33 +0000636 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump11289f42009-09-09 15:08:12 +0000637
Samuel Antaoeab747b2015-06-15 23:44:27 +0000638 // Set to true if tokens should be expanded
639 bool ShouldExpandTokens;
640
641 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
642 bool RequireTokenExpansion)
643 : Prefix(prefix), Callbacks(callbacks),
644 ShouldExpandTokens(RequireTokenExpansion) {}
Craig Topperafa7cb32014-03-13 06:07:04 +0000645 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
646 Token &PragmaTok) override {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000647 // Figure out what line we went to and insert the appropriate number of
648 // newline characters.
Jordan Rose127f6ee2012-06-15 23:33:51 +0000649 Callbacks->startNewLineIfNeeded();
Chris Lattner87f267e2006-11-21 05:02:33 +0000650 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattner068529a2008-08-17 03:12:02 +0000651 Callbacks->OS.write(Prefix, strlen(Prefix));
Samuel Antaoeab747b2015-06-15 23:44:27 +0000652
Alexey Bataev56f5ad12016-02-09 11:01:58 +0000653 if (ShouldExpandTokens) {
654 // The first token does not have expanded macros. Expand them, if
655 // required.
David Blaikie2eabcc92016-02-09 18:52:09 +0000656 auto Toks = llvm::make_unique<Token[]>(1);
Alexey Bataev56f5ad12016-02-09 11:01:58 +0000657 Toks[0] = PragmaTok;
David Blaikie2eabcc92016-02-09 18:52:09 +0000658 PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
659 /*DisableMacroExpansion=*/false);
Alexey Bataev56f5ad12016-02-09 11:01:58 +0000660 PP.Lex(PragmaTok);
661 }
Samuel Antaoeab747b2015-06-15 23:44:27 +0000662 Token PrevToken;
663 Token PrevPrevToken;
664 PrevToken.startToken();
665 PrevPrevToken.startToken();
666
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000667 // Read and print all of the pragma tokens.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000668 while (PragmaTok.isNot(tok::eod)) {
Samuel Antaoeab747b2015-06-15 23:44:27 +0000669 if (PragmaTok.hasLeadingSpace() ||
670 Callbacks->AvoidConcat(PrevPrevToken, PrevToken, PragmaTok))
Chris Lattner068529a2008-08-17 03:12:02 +0000671 Callbacks->OS << ' ';
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000672 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattner068529a2008-08-17 03:12:02 +0000673 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Kleckner0e73ec42014-02-20 22:59:51 +0000674
Samuel Antaoeab747b2015-06-15 23:44:27 +0000675 PrevPrevToken = PrevToken;
676 PrevToken = PragmaTok;
677
678 if (ShouldExpandTokens)
Reid Kleckner0e73ec42014-02-20 22:59:51 +0000679 PP.Lex(PragmaTok);
680 else
681 PP.LexUnexpandedToken(PragmaTok);
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000682 }
Jordan Rose127f6ee2012-06-15 23:33:51 +0000683 Callbacks->setEmittedDirectiveOnThisLine();
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000684 }
685};
Chris Lattner5de858c2006-07-04 19:04:44 +0000686} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000687
Chris Lattner4418ce12007-07-23 06:09:34 +0000688
Chris Lattnerfc001b02009-02-06 05:56:11 +0000689static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
690 PrintPPOutputPPCallbacks *Callbacks,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000691 raw_ostream &OS) {
Jordan Rose67b66232013-03-05 23:54:55 +0000692 bool DropComments = PP.getLangOpts().TraditionalCPP &&
693 !PP.getCommentRetentionState();
694
Benjamin Kramer718f7222010-02-27 18:02:51 +0000695 char Buffer[256];
Chris Lattnerbba37f42010-06-15 21:06:38 +0000696 Token PrevPrevTok, PrevTok;
697 PrevPrevTok.startToken();
698 PrevTok.startToken();
Chris Lattner3ff2e692007-10-10 20:45:16 +0000699 while (1) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000700 if (Callbacks->hasEmittedDirectiveOnThisLine()) {
701 Callbacks->startNewLineIfNeeded();
702 Callbacks->MoveToLine(Tok.getLocation());
703 }
Mike Stump11289f42009-09-09 15:08:12 +0000704
Chris Lattner67c38482006-07-04 23:24:26 +0000705 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000706 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
707 // done.
Mike Stump11289f42009-09-09 15:08:12 +0000708 } else if (Tok.hasLeadingSpace() ||
Chris Lattner4418ce12007-07-23 06:09:34 +0000709 // If we haven't emitted a token on this line yet, PrevTok isn't
710 // useful to look at and no concatenation could happen anyway.
Chris Lattnerd63c8a52007-07-23 23:21:34 +0000711 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattner4418ce12007-07-23 06:09:34 +0000712 // Don't print "-" next to "-", it would form "--".
Chris Lattner0384e6352010-04-14 03:57:19 +0000713 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattner068529a2008-08-17 03:12:02 +0000714 OS << ' ';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000715 }
Mike Stump11289f42009-09-09 15:08:12 +0000716
Jordan Rose67b66232013-03-05 23:54:55 +0000717 if (DropComments && Tok.is(tok::comment)) {
718 // Skip comments. Normally the preprocessor does not generate
719 // tok::comment nodes at all when not keeping comments, but under
720 // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
721 SourceLocation StartLoc = Tok.getLocation();
722 Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
Richard Smithd1386302017-05-04 00:29:54 +0000723 } else if (Tok.is(tok::annot_module_include)) {
Ben Langmuir5eb7cb72014-01-30 21:50:18 +0000724 // PrintPPOutputPPCallbacks::InclusionDirective handles producing
725 // appropriate output here. Ignore this token entirely.
Richard Smithce587f52013-11-15 04:24:58 +0000726 PP.Lex(Tok);
727 continue;
Richard Smithd1386302017-05-04 00:29:54 +0000728 } else if (Tok.is(tok::annot_module_begin)) {
729 // FIXME: We retrieve this token after the FileChanged callback, and
730 // retrieve the module_end token before the FileChanged callback, so
731 // we render this within the file and render the module end outside the
732 // file, but this is backwards from the token locations: the module_begin
733 // token is at the include location (outside the file) and the module_end
734 // token is at the EOF location (within the file).
735 Callbacks->BeginModule(
736 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
737 PP.Lex(Tok);
738 continue;
739 } else if (Tok.is(tok::annot_module_end)) {
740 Callbacks->EndModule(
741 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
742 PP.Lex(Tok);
743 continue;
Jordan Rose67b66232013-03-05 23:54:55 +0000744 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
Benjamin Kramer718f7222010-02-27 18:02:51 +0000745 OS << II->getName();
746 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
747 Tok.getLiteralData()) {
748 OS.write(Tok.getLiteralData(), Tok.getLength());
749 } else if (Tok.getLength() < 256) {
750 const char *TokPtr = Buffer;
751 unsigned Len = PP.getSpelling(Tok, TokPtr);
752 OS.write(TokPtr, Len);
Mike Stump11289f42009-09-09 15:08:12 +0000753
Benjamin Kramer718f7222010-02-27 18:02:51 +0000754 // Tokens that can contain embedded newlines need to adjust our current
755 // line number.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000756 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramer718f7222010-02-27 18:02:51 +0000757 Callbacks->HandleNewlinesInToken(TokPtr, Len);
758 } else {
759 std::string S = PP.getSpelling(Tok);
760 OS.write(&S[0], S.size());
761
762 // Tokens that can contain embedded newlines need to adjust our current
763 // line number.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000764 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramer718f7222010-02-27 18:02:51 +0000765 Callbacks->HandleNewlinesInToken(&S[0], S.size());
766 }
Jordan Rose127f6ee2012-06-15 23:33:51 +0000767 Callbacks->setEmittedTokensOnThisLine();
Mike Stump11289f42009-09-09 15:08:12 +0000768
Chris Lattner3ff2e692007-10-10 20:45:16 +0000769 if (Tok.is(tok::eof)) break;
Mike Stump11289f42009-09-09 15:08:12 +0000770
Chris Lattner0384e6352010-04-14 03:57:19 +0000771 PrevPrevTok = PrevTok;
Chris Lattner3ff2e692007-10-10 20:45:16 +0000772 PrevTok = Tok;
773 PP.Lex(Tok);
774 }
Chris Lattnerfc001b02009-02-06 05:56:11 +0000775}
776
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000777typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
778static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
779 return LHS->first->getName().compare(RHS->first->getName());
780}
781
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000782static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
Daniel Dunbard839e772010-06-11 20:10:12 +0000783 // Ignore unknown pragmas.
Lubos Lunak576a0412014-05-01 12:54:03 +0000784 PP.IgnorePragmas();
Daniel Dunbard839e772010-06-11 20:10:12 +0000785
Eli Friedman26c672b2009-05-19 01:32:34 +0000786 // -dM mode just scans and ignores all tokens in the files, then dumps out
787 // the macro table at the end.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000788 PP.EnterMainSourceFile();
Eli Friedman26c672b2009-05-19 01:32:34 +0000789
790 Token Tok;
791 do PP.Lex(Tok);
792 while (Tok.isNot(tok::eof));
793
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000794 SmallVector<id_macro_pair, 128> MacrosByID;
795 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
796 I != E; ++I) {
Richard Smith20e883e2015-04-29 23:20:19 +0000797 auto *MD = I->second.getLatest();
798 if (MD && MD->isDefined())
799 MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000800 }
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000801 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedman26c672b2009-05-19 01:32:34 +0000802
803 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
804 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000805 // Ignore computed macros like __LINE__ and friends.
Eli Friedman26c672b2009-05-19 01:32:34 +0000806 if (MI.isBuiltinMacro()) continue;
807
808 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +0000809 *OS << '\n';
Eli Friedman26c672b2009-05-19 01:32:34 +0000810 }
811}
812
Chris Lattnerfc001b02009-02-06 05:56:11 +0000813/// DoPrintPreprocessedInput - This implements -E mode.
814///
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000815void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
Daniel Dunbar22bdabf2009-11-11 10:07:44 +0000816 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000817 // Show macros with no output is handled specially.
818 if (!Opts.ShowCPP) {
819 assert(Opts.ShowMacros && "Not yet implemented!");
820 DoPrintMacros(PP, OS);
821 return;
822 }
823
Chris Lattnerfc001b02009-02-06 05:56:11 +0000824 // Inform the preprocessor whether we want it to retain comments or not, due
825 // to -C or -CC.
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000826 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanfcb57d52009-05-19 01:02:07 +0000827
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000828 PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000829 PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
830 Opts.ShowIncludeDirectives, Opts.UseLineDirectives);
Samuel Antaoeab747b2015-06-15 23:44:27 +0000831
832 // Expand macros in pragmas with -fms-extensions. The assumption is that
833 // the majority of pragmas in such a file will be Microsoft pragmas.
Vassil Vassilev2b676cf2017-04-27 16:58:33 +0000834 // Remember the handlers we will add so that we can remove them later.
835 std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(
836 new UnknownPragmaHandler(
837 "#pragma", Callbacks,
838 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
839
840 std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(
841 "#pragma GCC", Callbacks,
Samuel Antaoeab747b2015-06-15 23:44:27 +0000842 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
Vassil Vassilev2b676cf2017-04-27 16:58:33 +0000843
844 std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(
845 "#pragma clang", Callbacks,
846 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
847
848 PP.AddPragmaHandler(MicrosoftExtHandler.get());
849 PP.AddPragmaHandler("GCC", GCCHandler.get());
850 PP.AddPragmaHandler("clang", ClangHandler.get());
Samuel Antaoeab747b2015-06-15 23:44:27 +0000851
852 // The tokens after pragma omp need to be expanded.
853 //
854 // OpenMP [2.1, Directive format]
855 // Preprocessing tokens following the #pragma omp are subject to macro
856 // replacement.
Vassil Vassilev2b676cf2017-04-27 16:58:33 +0000857 std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(
858 new UnknownPragmaHandler("#pragma omp", Callbacks,
859 /*RequireTokenExpansion=*/true));
860 PP.AddPragmaHandler("omp", OpenMPHandler.get());
Chris Lattnerfc001b02009-02-06 05:56:11 +0000861
Craig Topperb8a70532014-09-10 04:53:53 +0000862 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
Chris Lattnerfc001b02009-02-06 05:56:11 +0000863
Eli Friedman26c672b2009-05-19 01:32:34 +0000864 // After we have configured the preprocessor, enter the main file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000865 PP.EnterMainSourceFile();
Chris Lattnerfc001b02009-02-06 05:56:11 +0000866
Eli Friedman26c672b2009-05-19 01:32:34 +0000867 // Consume all of the tokens that come from the predefines buffer. Those
868 // should not be emitted into the output and are guaranteed to be at the
869 // start.
870 const SourceManager &SourceMgr = PP.getSourceManager();
871 Token Tok;
Douglas Gregor453b0122010-11-12 07:15:47 +0000872 do {
873 PP.Lex(Tok);
874 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
875 break;
876
877 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
878 if (PLoc.isInvalid())
879 break;
880
881 if (strcmp(PLoc.getFilename(), "<built-in>"))
882 break;
883 } while (true);
Chris Lattnerfc001b02009-02-06 05:56:11 +0000884
Eli Friedman26c672b2009-05-19 01:32:34 +0000885 // Read all the preprocessed tokens, printing them out to the stream.
886 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
887 *OS << '\n';
Vassil Vassilev2b676cf2017-04-27 16:58:33 +0000888
889 // Remove the handlers we just added to leave the preprocessor in a sane state
890 // so that it can be reused (for example by a clang::Parser instance).
891 PP.RemovePragmaHandler(MicrosoftExtHandler.get());
892 PP.RemovePragmaHandler("GCC", GCCHandler.get());
893 PP.RemovePragmaHandler("clang", ClangHandler.get());
894 PP.RemovePragmaHandler("omp", OpenMPHandler.get());
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000895}