blob: 3b835985a54c056a7cabb598cfa3dbd197d36fc8 [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,
Julie Hockett96fbe582018-05-10 19:05:36 +0000133 const Module *Imported,
134 SrcMgr::CharacteristicKind FileType) override;
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000135 void Ident(SourceLocation Loc, StringRef str) override;
Craig Topperafa7cb32014-03-13 06:07:04 +0000136 void PragmaMessage(SourceLocation Loc, StringRef Namespace,
137 PragmaMessageKind Kind, StringRef Str) override;
138 void PragmaDebug(SourceLocation Loc, StringRef DebugType) override;
139 void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override;
140 void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override;
141 void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
Alp Tokerc726c362014-06-10 09:31:37 +0000142 diag::Severity Map, StringRef Str) override;
Craig Topperafa7cb32014-03-13 06:07:04 +0000143 void PragmaWarning(SourceLocation Loc, StringRef WarningSpec,
144 ArrayRef<int> Ids) override;
145 void PragmaWarningPush(SourceLocation Loc, int Level) override;
146 void PragmaWarningPop(SourceLocation Loc) override;
Eli Friedman16fee082017-09-27 23:29:37 +0000147 void PragmaAssumeNonNullBegin(SourceLocation Loc) override;
148 void PragmaAssumeNonNullEnd(SourceLocation Loc) override;
Chris Lattner87f267e2006-11-21 05:02:33 +0000149
Chris Lattner3ed83c12007-12-09 21:11:08 +0000150 bool HandleFirstTokOnLine(Token &Tok);
Hal Finkel2109f232013-01-28 04:37:37 +0000151
152 /// Move to the line of the provided source location. This will
153 /// return true if the output stream required adjustment or if
154 /// the requested location is on the first line.
Chris Lattner5dbefc62010-04-13 00:01:41 +0000155 bool MoveToLine(SourceLocation Loc) {
Douglas Gregor453b0122010-11-12 07:15:47 +0000156 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
157 if (PLoc.isInvalid())
158 return false;
Hal Finkel2109f232013-01-28 04:37:37 +0000159 return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
Chris Lattner5dbefc62010-04-13 00:01:41 +0000160 }
161 bool MoveToLine(unsigned LineNo);
162
Fangrui Song6907ce22018-07-30 19:24:48 +0000163 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
Chris Lattner0384e6352010-04-14 03:57:19 +0000164 const Token &Tok) {
165 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
Chris Lattner644d4522009-02-13 00:46:04 +0000166 }
Craig Topper49a27902014-05-22 04:46:25 +0000167 void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
168 unsigned ExtraLen=0);
Douglas Gregorc7d65762010-09-09 22:45:38 +0000169 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000170 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump11289f42009-09-09 15:08:12 +0000171
Chris Lattnercac63f32009-04-12 01:56:53 +0000172 /// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Topperafa7cb32014-03-13 06:07:04 +0000173 void MacroDefined(const Token &MacroNameTok,
174 const MacroDirective *MD) override;
Mike Stump11289f42009-09-09 15:08:12 +0000175
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000176 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
Craig Topperafa7cb32014-03-13 06:07:04 +0000177 void MacroUndefined(const Token &MacroNameTok,
Vedant Kumar349a6242017-04-26 21:05:44 +0000178 const MacroDefinition &MD,
179 const MacroDirective *Undef) override;
Richard Smithd1386302017-05-04 00:29:54 +0000180
181 void BeginModule(const Module *M);
182 void EndModule(const Module *M);
Chris Lattner87f267e2006-11-21 05:02:33 +0000183};
Chris Lattner21632652008-04-08 04:16:20 +0000184} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000185
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000186void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
187 const char *Extra,
188 unsigned ExtraLen) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000189 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000190
Chris Lattner76b44452009-12-07 01:42:56 +0000191 // Emit #line directives or GNU line markers depending on what mode we're in.
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000192 if (UseLineDirectives) {
Chris Lattner76b44452009-12-07 01:42:56 +0000193 OS << "#line" << ' ' << LineNo << ' ' << '"';
Eli Friedman80e45b82013-08-29 01:42:42 +0000194 OS.write_escaped(CurFilename);
Chris Lattner76b44452009-12-07 01:42:56 +0000195 OS << '"';
196 } else {
197 OS << '#' << ' ' << LineNo << ' ' << '"';
Eli Friedman80e45b82013-08-29 01:42:42 +0000198 OS.write_escaped(CurFilename);
Chris Lattner76b44452009-12-07 01:42:56 +0000199 OS << '"';
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +0000200
Steve Naroff66aaa392009-12-06 01:02:14 +0000201 if (ExtraLen)
202 OS.write(Extra, ExtraLen);
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000203
Steve Naroff66aaa392009-12-06 01:02:14 +0000204 if (FileType == SrcMgr::C_System)
205 OS.write(" 3", 2);
206 else if (FileType == SrcMgr::C_ExternCSystem)
207 OS.write(" 3 4", 4);
208 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000209 OS << '\n';
210}
211
Chris Lattner728b4dc2006-07-04 21:28:37 +0000212/// MoveToLine - Move the output to the source line specified by the location
213/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner3ed83c12007-12-09 21:11:08 +0000214/// #line directive. This returns false if already at the specified line, true
215/// if some newlines were emitted.
Chris Lattner5dbefc62010-04-13 00:01:41 +0000216bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000217 // If this line is "close enough" to the original line, just print newlines,
218 // otherwise print a #line directive.
Daniel Dunbare7781312008-09-26 01:13:35 +0000219 if (LineNo-CurLine <= 8) {
Chris Lattner5f075822007-07-23 05:14:05 +0000220 if (LineNo-CurLine == 1)
Chris Lattner068529a2008-08-17 03:12:02 +0000221 OS << '\n';
Chris Lattner3ed83c12007-12-09 21:11:08 +0000222 else if (LineNo == CurLine)
Chandler Carruth46a32c22011-07-14 16:14:52 +0000223 return false; // Spelling line moved, but expansion line didn't.
Chris Lattner5f075822007-07-23 05:14:05 +0000224 else {
225 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattner068529a2008-08-17 03:12:02 +0000226 OS.write(NewLines, LineNo-CurLine);
Chris Lattner5f075822007-07-23 05:14:05 +0000227 }
Chris Lattnerbc6bcab2010-06-12 16:20:56 +0000228 } else if (!DisableLineMarkers) {
229 // Emit a #line or line marker.
Craig Topper49a27902014-05-22 04:46:25 +0000230 WriteLineInfo(LineNo, nullptr, 0);
Chris Lattnerbc6bcab2010-06-12 16:20:56 +0000231 } else {
232 // Okay, we're in -P mode, which turns off line markers. However, we still
233 // need to emit a newline between tokens on different lines.
Jordan Rose127f6ee2012-06-15 23:33:51 +0000234 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Mike Stump11289f42009-09-09 15:08:12 +0000235 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000236
Mike Stump11289f42009-09-09 15:08:12 +0000237 CurLine = LineNo;
Chris Lattner3ed83c12007-12-09 21:11:08 +0000238 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000239}
240
Jordan Rose127f6ee2012-06-15 23:33:51 +0000241bool
242PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
243 if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
Douglas Gregorc7d65762010-09-09 22:45:38 +0000244 OS << '\n';
245 EmittedTokensOnThisLine = false;
Jordan Rose127f6ee2012-06-15 23:33:51 +0000246 EmittedDirectiveOnThisLine = false;
247 if (ShouldUpdateCurrentLine)
248 ++CurLine;
Douglas Gregorc7d65762010-09-09 22:45:38 +0000249 return true;
250 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000251
Douglas Gregorc7d65762010-09-09 22:45:38 +0000252 return false;
253}
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000254
255/// FileChanged - Whenever the preprocessor enters or exits a #include file
256/// it invokes this handler. Update our conception of the current source
257/// position.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000258void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
259 FileChangeReason Reason,
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000260 SrcMgr::CharacteristicKind NewFileType,
261 FileID PrevFID) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000262 // Unless we are exiting a #include, make sure to skip ahead to the line the
263 // #include directive was at.
Chris Lattner9d94f042010-04-13 00:06:42 +0000264 SourceManager &SourceMgr = SM;
Fangrui Song6907ce22018-07-30 19:24:48 +0000265
Chris Lattner5dbefc62010-04-13 00:01:41 +0000266 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Douglas Gregor453b0122010-11-12 07:15:47 +0000267 if (UserLoc.isInvalid())
268 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000269
Chris Lattnerc745cec2010-04-14 04:28:50 +0000270 unsigned NewLine = UserLoc.getLine();
Daniel Dunbard4352752010-08-24 22:44:13 +0000271
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000272 if (Reason == PPCallbacks::EnterFile) {
Douglas Gregor453b0122010-11-12 07:15:47 +0000273 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
Chris Lattnerd8cc8842009-01-30 18:44:17 +0000274 if (IncludeLoc.isValid())
275 MoveToLine(IncludeLoc);
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000276 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
Jordan Rose111c4a62013-04-17 19:09:18 +0000277 // GCC emits the # directive for this directive on the line AFTER the
278 // directive and emits a bunch of spaces that aren't needed. This is because
279 // otherwise we will emit a line marker for THIS line, which requires an
280 // extra blank line after the directive to avoid making all following lines
281 // off by one. We can do better by simply incrementing NewLine here.
282 NewLine += 1;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000283 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000284
Chris Lattner5dbefc62010-04-13 00:01:41 +0000285 CurLine = NewLine;
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000286
Chris Lattner4c4a2452007-07-24 06:57:14 +0000287 CurFilename.clear();
Chris Lattner5dbefc62010-04-13 00:01:41 +0000288 CurFilename += UserLoc.getFilename();
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000289 FileType = NewFileType;
290
Eli Friedmanc52435b2013-01-09 03:16:42 +0000291 if (DisableLineMarkers) {
292 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
293 return;
294 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000295
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000296 if (!Initialized) {
297 WriteLineInfo(CurLine);
298 Initialized = true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000299 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000300
Daniel Dunbar5d388752012-11-16 01:51:11 +0000301 // Do not emit an enter marker for the main file (which we expect is the first
302 // entered file). This matches gcc, and improves compatibility with some tools
303 // which track the # line markers as a way to determine when the preprocessed
304 // output is in the context of the main file.
305 if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
306 IsFirstFileEntered = true;
307 return;
308 }
309
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000310 switch (Reason) {
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000311 case PPCallbacks::EnterFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000312 WriteLineInfo(CurLine, " 1", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000313 break;
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000314 case PPCallbacks::ExitFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000315 WriteLineInfo(CurLine, " 2", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000316 break;
Mike Stump11289f42009-09-09 15:08:12 +0000317 case PPCallbacks::SystemHeaderPragma:
318 case PPCallbacks::RenameFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000319 WriteLineInfo(CurLine);
320 break;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000321 }
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000322}
323
Julie Hockett96fbe582018-05-10 19:05:36 +0000324void PrintPPOutputPPCallbacks::InclusionDirective(
325 SourceLocation HashLoc,
326 const Token &IncludeTok,
327 StringRef FileName,
328 bool IsAngled,
329 CharSourceRange FilenameRange,
330 const FileEntry *File,
331 StringRef SearchPath,
332 StringRef RelativePath,
333 const Module *Imported,
334 SrcMgr::CharacteristicKind FileType) {
Richard Smithc51c38b2017-04-29 00:34:47 +0000335 // In -dI mode, dump #include directives prior to dumping their content or
336 // interpretation.
337 if (DumpIncludeDirectives) {
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000338 startNewLineIfNeeded();
339 MoveToLine(HashLoc);
Richard Smithc51c38b2017-04-29 00:34:47 +0000340 const std::string TokenText = PP.getSpelling(IncludeTok);
341 assert(!TokenText.empty());
342 OS << "#" << TokenText << " "
343 << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
344 << " /* clang -E -dI */";
345 setEmittedDirectiveOnThisLine();
Ben Langmuir5418f402014-09-10 21:29:41 +0000346 startNewLineIfNeeded();
Richard Smithc51c38b2017-04-29 00:34:47 +0000347 }
348
349 // When preprocessing, turn implicit imports into module import pragmas.
350 if (Imported) {
351 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
352 case tok::pp_include:
353 case tok::pp_import:
354 case tok::pp_include_next:
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000355 startNewLineIfNeeded();
356 MoveToLine(HashLoc);
Richard Smith9565c75b2017-06-19 23:09:36 +0000357 OS << "#pragma clang module import " << Imported->getFullModuleName(true)
Richard Smithc51c38b2017-04-29 00:34:47 +0000358 << " /* clang -E: implicit import for "
359 << "#" << PP.getSpelling(IncludeTok) << " "
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000360 << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
Richard Smithc51c38b2017-04-29 00:34:47 +0000361 << " */";
362 // Since we want a newline after the pragma, but not a #<line>, start a
363 // new line immediately.
364 EmittedTokensOnThisLine = true;
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000365 startNewLineIfNeeded();
Richard Smithc51c38b2017-04-29 00:34:47 +0000366 break;
367
368 case tok::pp___include_macros:
369 // #__include_macros has no effect on a user of a preprocessed source
370 // file; the only effect is on preprocessing.
371 //
372 // FIXME: That's not *quite* true: it causes the module in question to
373 // be loaded, which can affect downstream diagnostics.
374 break;
375
376 default:
377 llvm_unreachable("unknown include directive kind");
378 break;
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000379 }
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000380 }
381}
382
Richard Smithd1386302017-05-04 00:29:54 +0000383/// Handle entering the scope of a module during a module compilation.
384void PrintPPOutputPPCallbacks::BeginModule(const Module *M) {
385 startNewLineIfNeeded();
Richard Smith9565c75b2017-06-19 23:09:36 +0000386 OS << "#pragma clang module begin " << M->getFullModuleName(true);
Richard Smithd1386302017-05-04 00:29:54 +0000387 setEmittedDirectiveOnThisLine();
388}
389
390/// Handle leaving the scope of a module during a module compilation.
391void PrintPPOutputPPCallbacks::EndModule(const Module *M) {
392 startNewLineIfNeeded();
Richard Smith9565c75b2017-06-19 23:09:36 +0000393 OS << "#pragma clang module end /*" << M->getFullModuleName(true) << "*/";
Richard Smithd1386302017-05-04 00:29:54 +0000394 setEmittedDirectiveOnThisLine();
395}
396
Chris Lattner5eef5072009-01-16 19:25:54 +0000397/// Ident - Handle #ident directives when read by the preprocessor.
Chris Lattner728b4dc2006-07-04 21:28:37 +0000398///
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000399void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
Chris Lattner3338ba82006-07-04 21:19:39 +0000400 MoveToLine(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000401
Chris Lattner068529a2008-08-17 03:12:02 +0000402 OS.write("#ident ", strlen("#ident "));
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000403 OS.write(S.begin(), S.size());
Chris Lattner87f267e2006-11-21 05:02:33 +0000404 EmittedTokensOnThisLine = true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000405}
406
Chris Lattnercac63f32009-04-12 01:56:53 +0000407/// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000408void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000409 const MacroDirective *MD) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000410 const MacroInfo *MI = MD->getMacroInfo();
Chris Lattnercac63f32009-04-12 01:56:53 +0000411 // Only print out macro definitions in -dD mode.
412 if (!DumpDefines ||
413 // Ignore __FILE__ etc.
414 MI->isBuiltinMacro()) return;
Mike Stump11289f42009-09-09 15:08:12 +0000415
Chris Lattnercac63f32009-04-12 01:56:53 +0000416 MoveToLine(MI->getDefinitionLoc());
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000417 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
Jordan Rose127f6ee2012-06-15 23:33:51 +0000418 setEmittedDirectiveOnThisLine();
Chris Lattnercac63f32009-04-12 01:56:53 +0000419}
420
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000421void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
Vedant Kumar349a6242017-04-26 21:05:44 +0000422 const MacroDefinition &MD,
423 const MacroDirective *Undef) {
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000424 // Only print out macro definitions in -dD mode.
425 if (!DumpDefines) return;
426
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000427 MoveToLine(MacroNameTok.getLocation());
428 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
Jordan Rose127f6ee2012-06-15 23:33:51 +0000429 setEmittedDirectiveOnThisLine();
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000430}
Chris Lattnercac63f32009-04-12 01:56:53 +0000431
Benjamin Kramer0772c422016-02-13 13:42:54 +0000432static void outputPrintable(raw_ostream &OS, StringRef Str) {
433 for (unsigned char Char : Str) {
434 if (isPrintable(Char) && Char != '\\' && Char != '"')
435 OS << (char)Char;
436 else // Output anything hard as an octal escape.
437 OS << '\\'
438 << (char)('0' + ((Char >> 6) & 7))
439 << (char)('0' + ((Char >> 3) & 7))
440 << (char)('0' + ((Char >> 0) & 7));
441 }
Aaron Ballman5d041be2013-06-04 02:07:14 +0000442}
443
Chris Lattner30c924b2010-06-26 17:11:39 +0000444void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000445 StringRef Namespace,
446 PragmaMessageKind Kind,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000447 StringRef Str) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000448 startNewLineIfNeeded();
Chris Lattner30c924b2010-06-26 17:11:39 +0000449 MoveToLine(Loc);
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000450 OS << "#pragma ";
451 if (!Namespace.empty())
452 OS << Namespace << ' ';
453 switch (Kind) {
454 case PMK_Message:
Andy Gibbsaa0b94a2013-04-19 17:13:17 +0000455 OS << "message(\"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000456 break;
457 case PMK_Warning:
Andy Gibbs96d93902013-04-18 16:49:37 +0000458 OS << "warning \"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000459 break;
460 case PMK_Error:
Andy Gibbs96d93902013-04-18 16:49:37 +0000461 OS << "error \"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000462 break;
463 }
Chris Lattner30c924b2010-06-26 17:11:39 +0000464
Aaron Ballman5d041be2013-06-04 02:07:14 +0000465 outputPrintable(OS, Str);
Chris Lattner30c924b2010-06-26 17:11:39 +0000466 OS << '"';
Andy Gibbsaa0b94a2013-04-19 17:13:17 +0000467 if (Kind == PMK_Message)
468 OS << ')';
Jordan Rose127f6ee2012-06-15 23:33:51 +0000469 setEmittedDirectiveOnThisLine();
Chris Lattner30c924b2010-06-26 17:11:39 +0000470}
471
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000472void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
473 StringRef DebugType) {
474 startNewLineIfNeeded();
475 MoveToLine(Loc);
476
477 OS << "#pragma clang __debug ";
478 OS << DebugType;
479
480 setEmittedDirectiveOnThisLine();
481}
482
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000483void PrintPPOutputPPCallbacks::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000484PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000485 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000486 MoveToLine(Loc);
487 OS << "#pragma " << Namespace << " diagnostic push";
Jordan Rose127f6ee2012-06-15 23:33:51 +0000488 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000489}
490
491void PrintPPOutputPPCallbacks::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000492PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000493 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000494 MoveToLine(Loc);
495 OS << "#pragma " << Namespace << " diagnostic pop";
Jordan Rose127f6ee2012-06-15 23:33:51 +0000496 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000497}
498
Alp Tokerc726c362014-06-10 09:31:37 +0000499void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
500 StringRef Namespace,
501 diag::Severity Map,
502 StringRef Str) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000503 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000504 MoveToLine(Loc);
505 OS << "#pragma " << Namespace << " diagnostic ";
Benjamin Kramer7ec12c92012-02-07 22:29:24 +0000506 switch (Map) {
Alp Toker46df1c02014-06-12 10:15:20 +0000507 case diag::Severity::Remark:
Tobias Grosser74160242014-02-28 09:11:08 +0000508 OS << "remark";
509 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000510 case diag::Severity::Warning:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000511 OS << "warning";
512 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000513 case diag::Severity::Error:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000514 OS << "error";
515 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000516 case diag::Severity::Ignored:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000517 OS << "ignored";
518 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000519 case diag::Severity::Fatal:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000520 OS << "fatal";
521 break;
522 }
523 OS << " \"" << Str << '"';
Jordan Rose127f6ee2012-06-15 23:33:51 +0000524 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000525}
Chris Lattner5eef5072009-01-16 19:25:54 +0000526
Reid Kleckner881dff32013-09-13 22:00:30 +0000527void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
528 StringRef WarningSpec,
529 ArrayRef<int> Ids) {
530 startNewLineIfNeeded();
531 MoveToLine(Loc);
532 OS << "#pragma warning(" << WarningSpec << ':';
533 for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
534 OS << ' ' << *I;
535 OS << ')';
536 setEmittedDirectiveOnThisLine();
537}
538
539void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
540 int Level) {
541 startNewLineIfNeeded();
542 MoveToLine(Loc);
543 OS << "#pragma warning(push";
Reid Kleckner4d185102013-10-02 15:19:23 +0000544 if (Level >= 0)
Reid Kleckner881dff32013-09-13 22:00:30 +0000545 OS << ", " << Level;
546 OS << ')';
547 setEmittedDirectiveOnThisLine();
548}
549
550void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
551 startNewLineIfNeeded();
552 MoveToLine(Loc);
553 OS << "#pragma warning(pop)";
554 setEmittedDirectiveOnThisLine();
555}
556
Eli Friedman16fee082017-09-27 23:29:37 +0000557void PrintPPOutputPPCallbacks::
558PragmaAssumeNonNullBegin(SourceLocation Loc) {
559 startNewLineIfNeeded();
560 MoveToLine(Loc);
561 OS << "#pragma clang assume_nonnull begin";
562 setEmittedDirectiveOnThisLine();
563}
564
565void PrintPPOutputPPCallbacks::
566PragmaAssumeNonNullEnd(SourceLocation Loc) {
567 startNewLineIfNeeded();
568 MoveToLine(Loc);
569 OS << "#pragma clang assume_nonnull end";
570 setEmittedDirectiveOnThisLine();
571}
572
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000573/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner3ed83c12007-12-09 21:11:08 +0000574/// is called for the first token on each new line. If this really is the start
575/// of a new logical line, handle it and return true, otherwise return false.
576/// This may not be the start of a logical line because the "start of line"
Chandler Carruth46a32c22011-07-14 16:14:52 +0000577/// marker is set for spelling lines, not expansion ones.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000578bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000579 // Figure out what line we went to and insert the appropriate number of
580 // newline characters.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000581 if (!MoveToLine(Tok.getLocation()))
582 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000583
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000584 // Print out space characters so that the first token on a line is
585 // indented for easy reading.
Chandler Carruth42f35f92011-07-25 20:57:57 +0000586 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000587
Richard Smith5b2f7c52014-02-24 20:50:36 +0000588 // The first token on a line can have a column number of 1, yet still expect
589 // leading white space, if a macro expansion in column 1 starts with an empty
590 // macro argument, or an empty nested macro expansion. In this case, move the
591 // token to column 2.
592 if (ColNo == 1 && Tok.hasLeadingSpace())
593 ColNo = 2;
594
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000595 // This hack prevents stuff like:
596 // #define HASH #
597 // HASH define foo bar
598 // From having the # character end up at column 1, which makes it so it
599 // is not handled as a #define next time through the preprocessor if in
600 // -fpreprocessed mode.
Chris Lattner3c69f122007-10-09 18:03:42 +0000601 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattner068529a2008-08-17 03:12:02 +0000602 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000603
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000604 // Otherwise, indent the appropriate number of spaces.
605 for (; ColNo > 1; --ColNo)
Chris Lattner068529a2008-08-17 03:12:02 +0000606 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000607
Chris Lattner3ed83c12007-12-09 21:11:08 +0000608 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000609}
610
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000611void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
612 unsigned Len) {
613 unsigned NumNewlines = 0;
614 for (; Len; --Len, ++TokStr) {
615 if (*TokStr != '\n' &&
616 *TokStr != '\r')
617 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000618
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000619 ++NumNewlines;
Mike Stump11289f42009-09-09 15:08:12 +0000620
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000621 // If we have \n\r or \r\n, skip both and count as one line.
622 if (Len != 1 &&
623 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
Richard Trieucc3949d2016-02-18 22:34:54 +0000624 TokStr[0] != TokStr[1]) {
625 ++TokStr;
626 --Len;
627 }
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000628 }
Mike Stump11289f42009-09-09 15:08:12 +0000629
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000630 if (NumNewlines == 0) return;
Mike Stump11289f42009-09-09 15:08:12 +0000631
Chris Lattnera5e67752009-06-15 04:08:28 +0000632 CurLine += NumNewlines;
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000633}
634
635
Chris Lattner5de858c2006-07-04 19:04:44 +0000636namespace {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000637struct UnknownPragmaHandler : public PragmaHandler {
638 const char *Prefix;
Chris Lattner87f267e2006-11-21 05:02:33 +0000639 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump11289f42009-09-09 15:08:12 +0000640
Samuel Antaoeab747b2015-06-15 23:44:27 +0000641 // Set to true if tokens should be expanded
642 bool ShouldExpandTokens;
643
644 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
645 bool RequireTokenExpansion)
646 : Prefix(prefix), Callbacks(callbacks),
647 ShouldExpandTokens(RequireTokenExpansion) {}
Craig Topperafa7cb32014-03-13 06:07:04 +0000648 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
649 Token &PragmaTok) override {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000650 // Figure out what line we went to and insert the appropriate number of
651 // newline characters.
Jordan Rose127f6ee2012-06-15 23:33:51 +0000652 Callbacks->startNewLineIfNeeded();
Chris Lattner87f267e2006-11-21 05:02:33 +0000653 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattner068529a2008-08-17 03:12:02 +0000654 Callbacks->OS.write(Prefix, strlen(Prefix));
Samuel Antaoeab747b2015-06-15 23:44:27 +0000655
Alexey Bataev56f5ad12016-02-09 11:01:58 +0000656 if (ShouldExpandTokens) {
657 // The first token does not have expanded macros. Expand them, if
658 // required.
David Blaikie2eabcc92016-02-09 18:52:09 +0000659 auto Toks = llvm::make_unique<Token[]>(1);
Alexey Bataev56f5ad12016-02-09 11:01:58 +0000660 Toks[0] = PragmaTok;
David Blaikie2eabcc92016-02-09 18:52:09 +0000661 PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
662 /*DisableMacroExpansion=*/false);
Alexey Bataev56f5ad12016-02-09 11:01:58 +0000663 PP.Lex(PragmaTok);
664 }
Samuel Antaoeab747b2015-06-15 23:44:27 +0000665 Token PrevToken;
666 Token PrevPrevToken;
667 PrevToken.startToken();
668 PrevPrevToken.startToken();
669
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000670 // Read and print all of the pragma tokens.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000671 while (PragmaTok.isNot(tok::eod)) {
Samuel Antaoeab747b2015-06-15 23:44:27 +0000672 if (PragmaTok.hasLeadingSpace() ||
673 Callbacks->AvoidConcat(PrevPrevToken, PrevToken, PragmaTok))
Chris Lattner068529a2008-08-17 03:12:02 +0000674 Callbacks->OS << ' ';
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000675 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattner068529a2008-08-17 03:12:02 +0000676 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Kleckner0e73ec42014-02-20 22:59:51 +0000677
Samuel Antaoeab747b2015-06-15 23:44:27 +0000678 PrevPrevToken = PrevToken;
679 PrevToken = PragmaTok;
680
681 if (ShouldExpandTokens)
Reid Kleckner0e73ec42014-02-20 22:59:51 +0000682 PP.Lex(PragmaTok);
683 else
684 PP.LexUnexpandedToken(PragmaTok);
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000685 }
Jordan Rose127f6ee2012-06-15 23:33:51 +0000686 Callbacks->setEmittedDirectiveOnThisLine();
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000687 }
688};
Chris Lattner5de858c2006-07-04 19:04:44 +0000689} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000690
Chris Lattner4418ce12007-07-23 06:09:34 +0000691
Chris Lattnerfc001b02009-02-06 05:56:11 +0000692static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
693 PrintPPOutputPPCallbacks *Callbacks,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000694 raw_ostream &OS) {
Jordan Rose67b66232013-03-05 23:54:55 +0000695 bool DropComments = PP.getLangOpts().TraditionalCPP &&
696 !PP.getCommentRetentionState();
697
Benjamin Kramer718f7222010-02-27 18:02:51 +0000698 char Buffer[256];
Chris Lattnerbba37f42010-06-15 21:06:38 +0000699 Token PrevPrevTok, PrevTok;
700 PrevPrevTok.startToken();
701 PrevTok.startToken();
Chris Lattner3ff2e692007-10-10 20:45:16 +0000702 while (1) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000703 if (Callbacks->hasEmittedDirectiveOnThisLine()) {
704 Callbacks->startNewLineIfNeeded();
705 Callbacks->MoveToLine(Tok.getLocation());
706 }
Mike Stump11289f42009-09-09 15:08:12 +0000707
Chris Lattner67c38482006-07-04 23:24:26 +0000708 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000709 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
710 // done.
Mike Stump11289f42009-09-09 15:08:12 +0000711 } else if (Tok.hasLeadingSpace() ||
Chris Lattner4418ce12007-07-23 06:09:34 +0000712 // If we haven't emitted a token on this line yet, PrevTok isn't
713 // useful to look at and no concatenation could happen anyway.
Chris Lattnerd63c8a52007-07-23 23:21:34 +0000714 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattner4418ce12007-07-23 06:09:34 +0000715 // Don't print "-" next to "-", it would form "--".
Chris Lattner0384e6352010-04-14 03:57:19 +0000716 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattner068529a2008-08-17 03:12:02 +0000717 OS << ' ';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000718 }
Mike Stump11289f42009-09-09 15:08:12 +0000719
Jordan Rose67b66232013-03-05 23:54:55 +0000720 if (DropComments && Tok.is(tok::comment)) {
721 // Skip comments. Normally the preprocessor does not generate
722 // tok::comment nodes at all when not keeping comments, but under
723 // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
724 SourceLocation StartLoc = Tok.getLocation();
725 Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
Reid Kleckner400a64e2017-10-16 23:07:15 +0000726 } else if (Tok.is(tok::eod)) {
727 // Don't print end of directive tokens, since they are typically newlines
728 // that mess up our line tracking. These come from unknown pre-processor
729 // directives or hash-prefixed comments in standalone assembly files.
730 PP.Lex(Tok);
731 continue;
Richard Smithd1386302017-05-04 00:29:54 +0000732 } else if (Tok.is(tok::annot_module_include)) {
Ben Langmuir5eb7cb72014-01-30 21:50:18 +0000733 // PrintPPOutputPPCallbacks::InclusionDirective handles producing
734 // appropriate output here. Ignore this token entirely.
Richard Smithce587f52013-11-15 04:24:58 +0000735 PP.Lex(Tok);
736 continue;
Richard Smithd1386302017-05-04 00:29:54 +0000737 } else if (Tok.is(tok::annot_module_begin)) {
738 // FIXME: We retrieve this token after the FileChanged callback, and
739 // retrieve the module_end token before the FileChanged callback, so
740 // we render this within the file and render the module end outside the
741 // file, but this is backwards from the token locations: the module_begin
742 // token is at the include location (outside the file) and the module_end
743 // token is at the EOF location (within the file).
744 Callbacks->BeginModule(
745 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
746 PP.Lex(Tok);
747 continue;
748 } else if (Tok.is(tok::annot_module_end)) {
749 Callbacks->EndModule(
750 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
751 PP.Lex(Tok);
752 continue;
David Blaikie1013fe72018-11-15 03:04:21 +0000753 } else if (Tok.isAnnotation()) {
754 // Ignore annotation tokens created by pragmas - the pragmas themselves
755 // will be reproduced in the preprocessed output.
756 PP.Lex(Tok);
757 continue;
Jordan Rose67b66232013-03-05 23:54:55 +0000758 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
Benjamin Kramer718f7222010-02-27 18:02:51 +0000759 OS << II->getName();
760 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
761 Tok.getLiteralData()) {
762 OS.write(Tok.getLiteralData(), Tok.getLength());
Paul Robinson4bb85ac2018-01-03 20:29:49 +0000763 } else if (Tok.getLength() < llvm::array_lengthof(Buffer)) {
Benjamin Kramer718f7222010-02-27 18:02:51 +0000764 const char *TokPtr = Buffer;
765 unsigned Len = PP.getSpelling(Tok, TokPtr);
766 OS.write(TokPtr, Len);
Mike Stump11289f42009-09-09 15:08:12 +0000767
Benjamin Kramer718f7222010-02-27 18:02:51 +0000768 // Tokens that can contain embedded newlines need to adjust our current
769 // line number.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000770 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramer718f7222010-02-27 18:02:51 +0000771 Callbacks->HandleNewlinesInToken(TokPtr, Len);
772 } else {
773 std::string S = PP.getSpelling(Tok);
774 OS.write(&S[0], S.size());
775
776 // Tokens that can contain embedded newlines need to adjust our current
777 // line number.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000778 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramer718f7222010-02-27 18:02:51 +0000779 Callbacks->HandleNewlinesInToken(&S[0], S.size());
780 }
Jordan Rose127f6ee2012-06-15 23:33:51 +0000781 Callbacks->setEmittedTokensOnThisLine();
Mike Stump11289f42009-09-09 15:08:12 +0000782
Chris Lattner3ff2e692007-10-10 20:45:16 +0000783 if (Tok.is(tok::eof)) break;
Mike Stump11289f42009-09-09 15:08:12 +0000784
Chris Lattner0384e6352010-04-14 03:57:19 +0000785 PrevPrevTok = PrevTok;
Chris Lattner3ff2e692007-10-10 20:45:16 +0000786 PrevTok = Tok;
787 PP.Lex(Tok);
788 }
Chris Lattnerfc001b02009-02-06 05:56:11 +0000789}
790
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000791typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
792static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
793 return LHS->first->getName().compare(RHS->first->getName());
794}
795
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000796static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
Daniel Dunbard839e772010-06-11 20:10:12 +0000797 // Ignore unknown pragmas.
Lubos Lunak576a0412014-05-01 12:54:03 +0000798 PP.IgnorePragmas();
Daniel Dunbard839e772010-06-11 20:10:12 +0000799
Eli Friedman26c672b2009-05-19 01:32:34 +0000800 // -dM mode just scans and ignores all tokens in the files, then dumps out
801 // the macro table at the end.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000802 PP.EnterMainSourceFile();
Eli Friedman26c672b2009-05-19 01:32:34 +0000803
804 Token Tok;
805 do PP.Lex(Tok);
806 while (Tok.isNot(tok::eof));
807
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000808 SmallVector<id_macro_pair, 128> MacrosByID;
809 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
810 I != E; ++I) {
Richard Smith20e883e2015-04-29 23:20:19 +0000811 auto *MD = I->second.getLatest();
812 if (MD && MD->isDefined())
813 MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000814 }
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000815 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedman26c672b2009-05-19 01:32:34 +0000816
817 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
818 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000819 // Ignore computed macros like __LINE__ and friends.
Eli Friedman26c672b2009-05-19 01:32:34 +0000820 if (MI.isBuiltinMacro()) continue;
821
822 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +0000823 *OS << '\n';
Eli Friedman26c672b2009-05-19 01:32:34 +0000824 }
825}
826
Chris Lattnerfc001b02009-02-06 05:56:11 +0000827/// DoPrintPreprocessedInput - This implements -E mode.
828///
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000829void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
Daniel Dunbar22bdabf2009-11-11 10:07:44 +0000830 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000831 // Show macros with no output is handled specially.
832 if (!Opts.ShowCPP) {
833 assert(Opts.ShowMacros && "Not yet implemented!");
834 DoPrintMacros(PP, OS);
835 return;
836 }
837
Chris Lattnerfc001b02009-02-06 05:56:11 +0000838 // Inform the preprocessor whether we want it to retain comments or not, due
839 // to -C or -CC.
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000840 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanfcb57d52009-05-19 01:02:07 +0000841
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000842 PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000843 PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
844 Opts.ShowIncludeDirectives, Opts.UseLineDirectives);
Samuel Antaoeab747b2015-06-15 23:44:27 +0000845
846 // Expand macros in pragmas with -fms-extensions. The assumption is that
847 // the majority of pragmas in such a file will be Microsoft pragmas.
Vassil Vassilev2b676cf2017-04-27 16:58:33 +0000848 // Remember the handlers we will add so that we can remove them later.
849 std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(
850 new UnknownPragmaHandler(
851 "#pragma", Callbacks,
852 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
853
854 std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(
855 "#pragma GCC", Callbacks,
Samuel Antaoeab747b2015-06-15 23:44:27 +0000856 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
Vassil Vassilev2b676cf2017-04-27 16:58:33 +0000857
858 std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(
859 "#pragma clang", Callbacks,
860 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
861
862 PP.AddPragmaHandler(MicrosoftExtHandler.get());
863 PP.AddPragmaHandler("GCC", GCCHandler.get());
864 PP.AddPragmaHandler("clang", ClangHandler.get());
Samuel Antaoeab747b2015-06-15 23:44:27 +0000865
866 // The tokens after pragma omp need to be expanded.
867 //
868 // OpenMP [2.1, Directive format]
869 // Preprocessing tokens following the #pragma omp are subject to macro
870 // replacement.
Vassil Vassilev2b676cf2017-04-27 16:58:33 +0000871 std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(
872 new UnknownPragmaHandler("#pragma omp", Callbacks,
873 /*RequireTokenExpansion=*/true));
874 PP.AddPragmaHandler("omp", OpenMPHandler.get());
Chris Lattnerfc001b02009-02-06 05:56:11 +0000875
Craig Topperb8a70532014-09-10 04:53:53 +0000876 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
Chris Lattnerfc001b02009-02-06 05:56:11 +0000877
Eli Friedman26c672b2009-05-19 01:32:34 +0000878 // After we have configured the preprocessor, enter the main file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000879 PP.EnterMainSourceFile();
Chris Lattnerfc001b02009-02-06 05:56:11 +0000880
Eli Friedman26c672b2009-05-19 01:32:34 +0000881 // Consume all of the tokens that come from the predefines buffer. Those
882 // should not be emitted into the output and are guaranteed to be at the
883 // start.
884 const SourceManager &SourceMgr = PP.getSourceManager();
885 Token Tok;
Douglas Gregor453b0122010-11-12 07:15:47 +0000886 do {
887 PP.Lex(Tok);
888 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
889 break;
890
891 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
892 if (PLoc.isInvalid())
893 break;
894
895 if (strcmp(PLoc.getFilename(), "<built-in>"))
896 break;
897 } while (true);
Chris Lattnerfc001b02009-02-06 05:56:11 +0000898
Eli Friedman26c672b2009-05-19 01:32:34 +0000899 // Read all the preprocessed tokens, printing them out to the stream.
900 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
901 *OS << '\n';
Vassil Vassilev2b676cf2017-04-27 16:58:33 +0000902
903 // Remove the handlers we just added to leave the preprocessor in a sane state
904 // so that it can be reused (for example by a clang::Parser instance).
905 PP.RemovePragmaHandler(MicrosoftExtHandler.get());
906 PP.RemovePragmaHandler("GCC", GCCHandler.get());
907 PP.RemovePragmaHandler("clang", ClangHandler.get());
908 PP.RemovePragmaHandler("omp", OpenMPHandler.get());
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000909}