blob: 490830c52415eecd26c2ef8ee5f3760cd679645f [file] [log] [blame]
Chris Lattner09e3cdf2006-07-04 19:04:05 +00001//===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner09e3cdf2006-07-04 19:04:05 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This code simply runs the preprocessor on the input file and prints out the
10// result. This is the traditional behavior of the -E option.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman16b7b6f2009-05-19 04:14:29 +000014#include "clang/Frontend/Utils.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000015#include "clang/Basic/CharInfo.h"
Daniel Dunbar531f6c62009-11-11 10:07:22 +000016#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/SourceManager.h"
18#include "clang/Frontend/PreprocessorOutputOptions.h"
Chris Lattner1630c3c2009-02-06 06:45:26 +000019#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000020#include "clang/Lex/PPCallbacks.h"
Chris Lattner09e3cdf2006-07-04 19:04:05 +000021#include "clang/Lex/Pragma.h"
Daniel Dunbar531f6c62009-11-11 10:07:22 +000022#include "clang/Lex/Preprocessor.h"
Chris Lattner644d4522009-02-13 00:46:04 +000023#include "clang/Lex/TokenConcatenation.h"
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +000024#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "llvm/ADT/SmallString.h"
Chris Lattner30c924b2010-06-26 17:11:39 +000026#include "llvm/ADT/StringRef.h"
Douglas Gregor3bde9b12011-06-22 19:41:48 +000027#include "llvm/Support/ErrorHandling.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "llvm/Support/raw_ostream.h"
Chris Lattnerdeb37012006-07-04 19:24:06 +000029#include <cstdio>
Chris Lattner09e3cdf2006-07-04 19:04:05 +000030using namespace clang;
31
Chris Lattnercac63f32009-04-12 01:56:53 +000032/// PrintMacroDefinition - Print a macro definition in a form that will be
33/// properly accepted back as a definition.
34static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000035 Preprocessor &PP, raw_ostream &OS) {
Chris Lattnercac63f32009-04-12 01:56:53 +000036 OS << "#define " << II.getName();
Mike Stump11289f42009-09-09 15:08:12 +000037
Chris Lattnercac63f32009-04-12 01:56:53 +000038 if (MI.isFunctionLike()) {
39 OS << '(';
Faisal Valiac506d72017-07-17 17:18:43 +000040 if (!MI.param_empty()) {
41 MacroInfo::param_iterator AI = MI.param_begin(), E = MI.param_end();
Chris Lattner53d80e22009-12-09 02:08:14 +000042 for (; AI+1 != E; ++AI) {
43 OS << (*AI)->getName();
Chris Lattner9dfed9f2009-12-07 01:58:34 +000044 OS << ',';
Chris Lattner9dfed9f2009-12-07 01:58:34 +000045 }
Chris Lattner53d80e22009-12-09 02:08:14 +000046
47 // Last argument.
48 if ((*AI)->getName() == "__VA_ARGS__")
49 OS << "...";
50 else
51 OS << (*AI)->getName();
Chris Lattnercac63f32009-04-12 01:56:53 +000052 }
Mike Stump11289f42009-09-09 15:08:12 +000053
Chris Lattner9dfed9f2009-12-07 01:58:34 +000054 if (MI.isGNUVarargs())
55 OS << "..."; // #define foo(x...)
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +000056
Chris Lattnercac63f32009-04-12 01:56:53 +000057 OS << ')';
58 }
Mike Stump11289f42009-09-09 15:08:12 +000059
Chris Lattnercac63f32009-04-12 01:56:53 +000060 // GCC always emits a space, even if the macro body is empty. However, do not
61 // want to emit two spaces if the first token has a leading space.
62 if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
63 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +000064
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000065 SmallString<128> SpellingBuffer;
Daniel Marjamakiecb0e1b2015-05-11 08:25:54 +000066 for (const auto &T : MI.tokens()) {
67 if (T.hasLeadingSpace())
Chris Lattnercac63f32009-04-12 01:56:53 +000068 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +000069
Daniel Marjamakiecb0e1b2015-05-11 08:25:54 +000070 OS << PP.getSpelling(T, SpellingBuffer);
Chris Lattnercac63f32009-04-12 01:56:53 +000071 }
72}
73
Chris Lattnerf46be6c2006-07-04 22:19:33 +000074//===----------------------------------------------------------------------===//
75// Preprocessed token printer
76//===----------------------------------------------------------------------===//
77
Chris Lattner87f267e2006-11-21 05:02:33 +000078namespace {
79class PrintPPOutputPPCallbacks : public PPCallbacks {
80 Preprocessor &PP;
Chris Lattner9d94f042010-04-13 00:06:42 +000081 SourceManager &SM;
Chris Lattner644d4522009-02-13 00:46:04 +000082 TokenConcatenation ConcatInfo;
Chris Lattner068529a2008-08-17 03:12:02 +000083public:
Chris Lattner0e62c1c2011-07-23 10:55:15 +000084 raw_ostream &OS;
Chris Lattner068529a2008-08-17 03:12:02 +000085private:
Chris Lattner87f267e2006-11-21 05:02:33 +000086 unsigned CurLine;
Daniel Dunbard4352752010-08-24 22:44:13 +000087
Chris Lattner87f267e2006-11-21 05:02:33 +000088 bool EmittedTokensOnThisLine;
Jordan Rose127f6ee2012-06-15 23:33:51 +000089 bool EmittedDirectiveOnThisLine;
Chris Lattner66a740e2008-10-27 01:19:25 +000090 SrcMgr::CharacteristicKind FileType;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000091 SmallString<512> CurFilename;
Daniel Dunbar98e0e532008-09-05 03:22:57 +000092 bool Initialized;
Eli Friedman6af494b2009-05-19 03:06:47 +000093 bool DisableLineMarkers;
94 bool DumpDefines;
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +000095 bool DumpIncludeDirectives;
Reid Kleckner1df0fea2015-02-26 00:17:25 +000096 bool UseLineDirectives;
Daniel Dunbar5d388752012-11-16 01:51:11 +000097 bool IsFirstFileEntered;
Chris Lattner87f267e2006-11-21 05:02:33 +000098public:
Reid Kleckner1df0fea2015-02-26 00:17:25 +000099 PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os, bool lineMarkers,
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000100 bool defines, bool DumpIncludeDirectives,
101 bool UseLineDirectives)
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000102 : PP(pp), SM(PP.getSourceManager()), ConcatInfo(PP), OS(os),
103 DisableLineMarkers(lineMarkers), DumpDefines(defines),
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000104 DumpIncludeDirectives(DumpIncludeDirectives),
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000105 UseLineDirectives(UseLineDirectives) {
Daniel Dunbar27734fd2011-02-02 15:41:17 +0000106 CurLine = 0;
Chris Lattner4c4a2452007-07-24 06:57:14 +0000107 CurFilename += "<uninit>";
Chris Lattner87f267e2006-11-21 05:02:33 +0000108 EmittedTokensOnThisLine = false;
Jordan Rose127f6ee2012-06-15 23:33:51 +0000109 EmittedDirectiveOnThisLine = false;
Chris Lattnerb03dc762008-09-26 21:18:42 +0000110 FileType = SrcMgr::C_User;
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000111 Initialized = false;
Daniel Dunbar5d388752012-11-16 01:51:11 +0000112 IsFirstFileEntered = false;
Chris Lattner87f267e2006-11-21 05:02:33 +0000113 }
Mike Stump11289f42009-09-09 15:08:12 +0000114
Jordan Rose127f6ee2012-06-15 23:33:51 +0000115 void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattner4418ce12007-07-23 06:09:34 +0000116 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Mike Stump11289f42009-09-09 15:08:12 +0000117
Jordan Rose127f6ee2012-06-15 23:33:51 +0000118 void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
119 bool hasEmittedDirectiveOnThisLine() const {
120 return EmittedDirectiveOnThisLine;
121 }
122
123 bool startNewLineIfNeeded(bool ShouldUpdateCurrentLine = true);
Craig Topperafa7cb32014-03-13 06:07:04 +0000124
125 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
126 SrcMgr::CharacteristicKind FileType,
127 FileID PrevFID) override;
128 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
129 StringRef FileName, bool IsAngled,
130 CharSourceRange FilenameRange, const FileEntry *File,
131 StringRef SearchPath, StringRef RelativePath,
Julie Hockett96fbe582018-05-10 19:05:36 +0000132 const Module *Imported,
133 SrcMgr::CharacteristicKind FileType) 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
Fangrui Song6907ce22018-07-30 19:24:48 +0000162 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
Chris Lattner0384e6352010-04-14 03:57:19 +0000163 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 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000250
Douglas Gregorc7d65762010-09-09 22:45:38 +0000251 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;
Fangrui Song6907ce22018-07-30 19:24:48 +0000264
Chris Lattner5dbefc62010-04-13 00:01:41 +0000265 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Douglas Gregor453b0122010-11-12 07:15:47 +0000266 if (UserLoc.isInvalid())
267 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000268
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 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000283
Chris Lattner5dbefc62010-04-13 00:01:41 +0000284 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 }
Fangrui Song6907ce22018-07-30 19:24:48 +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
Julie Hockett96fbe582018-05-10 19:05:36 +0000323void PrintPPOutputPPCallbacks::InclusionDirective(
324 SourceLocation HashLoc,
325 const Token &IncludeTok,
326 StringRef FileName,
327 bool IsAngled,
328 CharSourceRange FilenameRange,
329 const FileEntry *File,
330 StringRef SearchPath,
331 StringRef RelativePath,
332 const Module *Imported,
333 SrcMgr::CharacteristicKind FileType) {
Richard Smithc51c38b2017-04-29 00:34:47 +0000334 // In -dI mode, dump #include directives prior to dumping their content or
335 // interpretation.
336 if (DumpIncludeDirectives) {
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000337 startNewLineIfNeeded();
338 MoveToLine(HashLoc);
Richard Smithc51c38b2017-04-29 00:34:47 +0000339 const std::string TokenText = PP.getSpelling(IncludeTok);
340 assert(!TokenText.empty());
341 OS << "#" << TokenText << " "
342 << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
343 << " /* clang -E -dI */";
344 setEmittedDirectiveOnThisLine();
Ben Langmuir5418f402014-09-10 21:29:41 +0000345 startNewLineIfNeeded();
Richard Smithc51c38b2017-04-29 00:34:47 +0000346 }
347
348 // When preprocessing, turn implicit imports into module import pragmas.
349 if (Imported) {
350 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
351 case tok::pp_include:
352 case tok::pp_import:
353 case tok::pp_include_next:
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000354 startNewLineIfNeeded();
355 MoveToLine(HashLoc);
Richard Smith9565c75b2017-06-19 23:09:36 +0000356 OS << "#pragma clang module import " << Imported->getFullModuleName(true)
Richard Smithc51c38b2017-04-29 00:34:47 +0000357 << " /* clang -E: implicit import for "
358 << "#" << PP.getSpelling(IncludeTok) << " "
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000359 << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
Richard Smithc51c38b2017-04-29 00:34:47 +0000360 << " */";
361 // Since we want a newline after the pragma, but not a #<line>, start a
362 // new line immediately.
363 EmittedTokensOnThisLine = true;
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000364 startNewLineIfNeeded();
Richard Smithc51c38b2017-04-29 00:34:47 +0000365 break;
366
367 case tok::pp___include_macros:
368 // #__include_macros has no effect on a user of a preprocessed source
369 // file; the only effect is on preprocessing.
370 //
371 // FIXME: That's not *quite* true: it causes the module in question to
372 // be loaded, which can affect downstream diagnostics.
373 break;
374
375 default:
376 llvm_unreachable("unknown include directive kind");
377 break;
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000378 }
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000379 }
380}
381
Richard Smithd1386302017-05-04 00:29:54 +0000382/// Handle entering the scope of a module during a module compilation.
383void PrintPPOutputPPCallbacks::BeginModule(const Module *M) {
384 startNewLineIfNeeded();
Richard Smith9565c75b2017-06-19 23:09:36 +0000385 OS << "#pragma clang module begin " << M->getFullModuleName(true);
Richard Smithd1386302017-05-04 00:29:54 +0000386 setEmittedDirectiveOnThisLine();
387}
388
389/// Handle leaving the scope of a module during a module compilation.
390void PrintPPOutputPPCallbacks::EndModule(const Module *M) {
391 startNewLineIfNeeded();
Richard Smith9565c75b2017-06-19 23:09:36 +0000392 OS << "#pragma clang module end /*" << M->getFullModuleName(true) << "*/";
Richard Smithd1386302017-05-04 00:29:54 +0000393 setEmittedDirectiveOnThisLine();
394}
395
Chris Lattner5eef5072009-01-16 19:25:54 +0000396/// Ident - Handle #ident directives when read by the preprocessor.
Chris Lattner728b4dc2006-07-04 21:28:37 +0000397///
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000398void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
Chris Lattner3338ba82006-07-04 21:19:39 +0000399 MoveToLine(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000400
Chris Lattner068529a2008-08-17 03:12:02 +0000401 OS.write("#ident ", strlen("#ident "));
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000402 OS.write(S.begin(), S.size());
Chris Lattner87f267e2006-11-21 05:02:33 +0000403 EmittedTokensOnThisLine = true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000404}
405
Chris Lattnercac63f32009-04-12 01:56:53 +0000406/// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000407void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000408 const MacroDirective *MD) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000409 const MacroInfo *MI = MD->getMacroInfo();
Chris Lattnercac63f32009-04-12 01:56:53 +0000410 // Only print out macro definitions in -dD mode.
411 if (!DumpDefines ||
412 // Ignore __FILE__ etc.
413 MI->isBuiltinMacro()) return;
Mike Stump11289f42009-09-09 15:08:12 +0000414
Chris Lattnercac63f32009-04-12 01:56:53 +0000415 MoveToLine(MI->getDefinitionLoc());
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000416 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
Jordan Rose127f6ee2012-06-15 23:33:51 +0000417 setEmittedDirectiveOnThisLine();
Chris Lattnercac63f32009-04-12 01:56:53 +0000418}
419
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000420void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
Vedant Kumar349a6242017-04-26 21:05:44 +0000421 const MacroDefinition &MD,
422 const MacroDirective *Undef) {
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000423 // Only print out macro definitions in -dD mode.
424 if (!DumpDefines) return;
425
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000426 MoveToLine(MacroNameTok.getLocation());
427 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
Jordan Rose127f6ee2012-06-15 23:33:51 +0000428 setEmittedDirectiveOnThisLine();
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000429}
Chris Lattnercac63f32009-04-12 01:56:53 +0000430
Benjamin Kramer0772c422016-02-13 13:42:54 +0000431static void outputPrintable(raw_ostream &OS, StringRef Str) {
432 for (unsigned char Char : Str) {
433 if (isPrintable(Char) && Char != '\\' && Char != '"')
434 OS << (char)Char;
435 else // Output anything hard as an octal escape.
436 OS << '\\'
437 << (char)('0' + ((Char >> 6) & 7))
438 << (char)('0' + ((Char >> 3) & 7))
439 << (char)('0' + ((Char >> 0) & 7));
440 }
Aaron Ballman5d041be2013-06-04 02:07:14 +0000441}
442
Chris Lattner30c924b2010-06-26 17:11:39 +0000443void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000444 StringRef Namespace,
445 PragmaMessageKind Kind,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000446 StringRef Str) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000447 startNewLineIfNeeded();
Chris Lattner30c924b2010-06-26 17:11:39 +0000448 MoveToLine(Loc);
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000449 OS << "#pragma ";
450 if (!Namespace.empty())
451 OS << Namespace << ' ';
452 switch (Kind) {
453 case PMK_Message:
Andy Gibbsaa0b94a2013-04-19 17:13:17 +0000454 OS << "message(\"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000455 break;
456 case PMK_Warning:
Andy Gibbs96d93902013-04-18 16:49:37 +0000457 OS << "warning \"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000458 break;
459 case PMK_Error:
Andy Gibbs96d93902013-04-18 16:49:37 +0000460 OS << "error \"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000461 break;
462 }
Chris Lattner30c924b2010-06-26 17:11:39 +0000463
Aaron Ballman5d041be2013-06-04 02:07:14 +0000464 outputPrintable(OS, Str);
Chris Lattner30c924b2010-06-26 17:11:39 +0000465 OS << '"';
Andy Gibbsaa0b94a2013-04-19 17:13:17 +0000466 if (Kind == PMK_Message)
467 OS << ')';
Jordan Rose127f6ee2012-06-15 23:33:51 +0000468 setEmittedDirectiveOnThisLine();
Chris Lattner30c924b2010-06-26 17:11:39 +0000469}
470
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000471void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
472 StringRef DebugType) {
473 startNewLineIfNeeded();
474 MoveToLine(Loc);
475
476 OS << "#pragma clang __debug ";
477 OS << DebugType;
478
479 setEmittedDirectiveOnThisLine();
480}
481
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000482void PrintPPOutputPPCallbacks::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000483PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000484 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000485 MoveToLine(Loc);
486 OS << "#pragma " << Namespace << " diagnostic push";
Jordan Rose127f6ee2012-06-15 23:33:51 +0000487 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000488}
489
490void PrintPPOutputPPCallbacks::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000491PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000492 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000493 MoveToLine(Loc);
494 OS << "#pragma " << Namespace << " diagnostic pop";
Jordan Rose127f6ee2012-06-15 23:33:51 +0000495 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000496}
497
Alp Tokerc726c362014-06-10 09:31:37 +0000498void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
499 StringRef Namespace,
500 diag::Severity Map,
501 StringRef Str) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000502 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000503 MoveToLine(Loc);
504 OS << "#pragma " << Namespace << " diagnostic ";
Benjamin Kramer7ec12c92012-02-07 22:29:24 +0000505 switch (Map) {
Alp Toker46df1c02014-06-12 10:15:20 +0000506 case diag::Severity::Remark:
Tobias Grosser74160242014-02-28 09:11:08 +0000507 OS << "remark";
508 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000509 case diag::Severity::Warning:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000510 OS << "warning";
511 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000512 case diag::Severity::Error:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000513 OS << "error";
514 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000515 case diag::Severity::Ignored:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000516 OS << "ignored";
517 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000518 case diag::Severity::Fatal:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000519 OS << "fatal";
520 break;
521 }
522 OS << " \"" << Str << '"';
Jordan Rose127f6ee2012-06-15 23:33:51 +0000523 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000524}
Chris Lattner5eef5072009-01-16 19:25:54 +0000525
Reid Kleckner881dff32013-09-13 22:00:30 +0000526void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
527 StringRef WarningSpec,
528 ArrayRef<int> Ids) {
529 startNewLineIfNeeded();
530 MoveToLine(Loc);
531 OS << "#pragma warning(" << WarningSpec << ':';
532 for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
533 OS << ' ' << *I;
534 OS << ')';
535 setEmittedDirectiveOnThisLine();
536}
537
538void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
539 int Level) {
540 startNewLineIfNeeded();
541 MoveToLine(Loc);
542 OS << "#pragma warning(push";
Reid Kleckner4d185102013-10-02 15:19:23 +0000543 if (Level >= 0)
Reid Kleckner881dff32013-09-13 22:00:30 +0000544 OS << ", " << Level;
545 OS << ')';
546 setEmittedDirectiveOnThisLine();
547}
548
549void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
550 startNewLineIfNeeded();
551 MoveToLine(Loc);
552 OS << "#pragma warning(pop)";
553 setEmittedDirectiveOnThisLine();
554}
555
Eli Friedman16fee082017-09-27 23:29:37 +0000556void PrintPPOutputPPCallbacks::
557PragmaAssumeNonNullBegin(SourceLocation Loc) {
558 startNewLineIfNeeded();
559 MoveToLine(Loc);
560 OS << "#pragma clang assume_nonnull begin";
561 setEmittedDirectiveOnThisLine();
562}
563
564void PrintPPOutputPPCallbacks::
565PragmaAssumeNonNullEnd(SourceLocation Loc) {
566 startNewLineIfNeeded();
567 MoveToLine(Loc);
568 OS << "#pragma clang assume_nonnull end";
569 setEmittedDirectiveOnThisLine();
570}
571
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000572/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner3ed83c12007-12-09 21:11:08 +0000573/// is called for the first token on each new line. If this really is the start
574/// of a new logical line, handle it and return true, otherwise return false.
575/// This may not be the start of a logical line because the "start of line"
Chandler Carruth46a32c22011-07-14 16:14:52 +0000576/// marker is set for spelling lines, not expansion ones.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000577bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000578 // Figure out what line we went to and insert the appropriate number of
579 // newline characters.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000580 if (!MoveToLine(Tok.getLocation()))
581 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000582
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000583 // Print out space characters so that the first token on a line is
584 // indented for easy reading.
Chandler Carruth42f35f92011-07-25 20:57:57 +0000585 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000586
Richard Smith5b2f7c52014-02-24 20:50:36 +0000587 // The first token on a line can have a column number of 1, yet still expect
588 // leading white space, if a macro expansion in column 1 starts with an empty
589 // macro argument, or an empty nested macro expansion. In this case, move the
590 // token to column 2.
591 if (ColNo == 1 && Tok.hasLeadingSpace())
592 ColNo = 2;
593
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000594 // This hack prevents stuff like:
595 // #define HASH #
596 // HASH define foo bar
597 // From having the # character end up at column 1, which makes it so it
598 // is not handled as a #define next time through the preprocessor if in
599 // -fpreprocessed mode.
Chris Lattner3c69f122007-10-09 18:03:42 +0000600 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattner068529a2008-08-17 03:12:02 +0000601 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000602
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000603 // Otherwise, indent the appropriate number of spaces.
604 for (; ColNo > 1; --ColNo)
Chris Lattner068529a2008-08-17 03:12:02 +0000605 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000606
Chris Lattner3ed83c12007-12-09 21:11:08 +0000607 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000608}
609
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000610void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
611 unsigned Len) {
612 unsigned NumNewlines = 0;
613 for (; Len; --Len, ++TokStr) {
614 if (*TokStr != '\n' &&
615 *TokStr != '\r')
616 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000617
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000618 ++NumNewlines;
Mike Stump11289f42009-09-09 15:08:12 +0000619
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000620 // If we have \n\r or \r\n, skip both and count as one line.
621 if (Len != 1 &&
622 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
Richard Trieucc3949d2016-02-18 22:34:54 +0000623 TokStr[0] != TokStr[1]) {
624 ++TokStr;
625 --Len;
626 }
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000627 }
Mike Stump11289f42009-09-09 15:08:12 +0000628
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000629 if (NumNewlines == 0) return;
Mike Stump11289f42009-09-09 15:08:12 +0000630
Chris Lattnera5e67752009-06-15 04:08:28 +0000631 CurLine += NumNewlines;
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000632}
633
634
Chris Lattner5de858c2006-07-04 19:04:44 +0000635namespace {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000636struct UnknownPragmaHandler : public PragmaHandler {
637 const char *Prefix;
Chris Lattner87f267e2006-11-21 05:02:33 +0000638 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump11289f42009-09-09 15:08:12 +0000639
Samuel Antaoeab747b2015-06-15 23:44:27 +0000640 // Set to true if tokens should be expanded
641 bool ShouldExpandTokens;
642
643 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
644 bool RequireTokenExpansion)
645 : Prefix(prefix), Callbacks(callbacks),
646 ShouldExpandTokens(RequireTokenExpansion) {}
Craig Topperafa7cb32014-03-13 06:07:04 +0000647 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
648 Token &PragmaTok) override {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000649 // Figure out what line we went to and insert the appropriate number of
650 // newline characters.
Jordan Rose127f6ee2012-06-15 23:33:51 +0000651 Callbacks->startNewLineIfNeeded();
Chris Lattner87f267e2006-11-21 05:02:33 +0000652 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattner068529a2008-08-17 03:12:02 +0000653 Callbacks->OS.write(Prefix, strlen(Prefix));
Samuel Antaoeab747b2015-06-15 23:44:27 +0000654
Alexey Bataev56f5ad12016-02-09 11:01:58 +0000655 if (ShouldExpandTokens) {
656 // The first token does not have expanded macros. Expand them, if
657 // required.
David Blaikie2eabcc92016-02-09 18:52:09 +0000658 auto Toks = llvm::make_unique<Token[]>(1);
Alexey Bataev56f5ad12016-02-09 11:01:58 +0000659 Toks[0] = PragmaTok;
David Blaikie2eabcc92016-02-09 18:52:09 +0000660 PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
661 /*DisableMacroExpansion=*/false);
Alexey Bataev56f5ad12016-02-09 11:01:58 +0000662 PP.Lex(PragmaTok);
663 }
Samuel Antaoeab747b2015-06-15 23:44:27 +0000664 Token PrevToken;
665 Token PrevPrevToken;
666 PrevToken.startToken();
667 PrevPrevToken.startToken();
668
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000669 // Read and print all of the pragma tokens.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000670 while (PragmaTok.isNot(tok::eod)) {
Samuel Antaoeab747b2015-06-15 23:44:27 +0000671 if (PragmaTok.hasLeadingSpace() ||
672 Callbacks->AvoidConcat(PrevPrevToken, PrevToken, PragmaTok))
Chris Lattner068529a2008-08-17 03:12:02 +0000673 Callbacks->OS << ' ';
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000674 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattner068529a2008-08-17 03:12:02 +0000675 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Kleckner0e73ec42014-02-20 22:59:51 +0000676
Samuel Antaoeab747b2015-06-15 23:44:27 +0000677 PrevPrevToken = PrevToken;
678 PrevToken = PragmaTok;
679
680 if (ShouldExpandTokens)
Reid Kleckner0e73ec42014-02-20 22:59:51 +0000681 PP.Lex(PragmaTok);
682 else
683 PP.LexUnexpandedToken(PragmaTok);
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000684 }
Jordan Rose127f6ee2012-06-15 23:33:51 +0000685 Callbacks->setEmittedDirectiveOnThisLine();
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000686 }
687};
Chris Lattner5de858c2006-07-04 19:04:44 +0000688} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000689
Chris Lattner4418ce12007-07-23 06:09:34 +0000690
Chris Lattnerfc001b02009-02-06 05:56:11 +0000691static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
692 PrintPPOutputPPCallbacks *Callbacks,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000693 raw_ostream &OS) {
Jordan Rose67b66232013-03-05 23:54:55 +0000694 bool DropComments = PP.getLangOpts().TraditionalCPP &&
695 !PP.getCommentRetentionState();
696
Benjamin Kramer718f7222010-02-27 18:02:51 +0000697 char Buffer[256];
Chris Lattnerbba37f42010-06-15 21:06:38 +0000698 Token PrevPrevTok, PrevTok;
699 PrevPrevTok.startToken();
700 PrevTok.startToken();
Chris Lattner3ff2e692007-10-10 20:45:16 +0000701 while (1) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000702 if (Callbacks->hasEmittedDirectiveOnThisLine()) {
703 Callbacks->startNewLineIfNeeded();
704 Callbacks->MoveToLine(Tok.getLocation());
705 }
Mike Stump11289f42009-09-09 15:08:12 +0000706
Chris Lattner67c38482006-07-04 23:24:26 +0000707 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000708 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
709 // done.
Mike Stump11289f42009-09-09 15:08:12 +0000710 } else if (Tok.hasLeadingSpace() ||
Chris Lattner4418ce12007-07-23 06:09:34 +0000711 // If we haven't emitted a token on this line yet, PrevTok isn't
712 // useful to look at and no concatenation could happen anyway.
Chris Lattnerd63c8a52007-07-23 23:21:34 +0000713 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattner4418ce12007-07-23 06:09:34 +0000714 // Don't print "-" next to "-", it would form "--".
Chris Lattner0384e6352010-04-14 03:57:19 +0000715 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattner068529a2008-08-17 03:12:02 +0000716 OS << ' ';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000717 }
Mike Stump11289f42009-09-09 15:08:12 +0000718
Jordan Rose67b66232013-03-05 23:54:55 +0000719 if (DropComments && Tok.is(tok::comment)) {
720 // Skip comments. Normally the preprocessor does not generate
721 // tok::comment nodes at all when not keeping comments, but under
722 // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
723 SourceLocation StartLoc = Tok.getLocation();
724 Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
Reid Kleckner400a64e2017-10-16 23:07:15 +0000725 } else if (Tok.is(tok::eod)) {
726 // Don't print end of directive tokens, since they are typically newlines
727 // that mess up our line tracking. These come from unknown pre-processor
728 // directives or hash-prefixed comments in standalone assembly files.
729 PP.Lex(Tok);
730 continue;
Richard Smithd1386302017-05-04 00:29:54 +0000731 } else if (Tok.is(tok::annot_module_include)) {
Ben Langmuir5eb7cb72014-01-30 21:50:18 +0000732 // PrintPPOutputPPCallbacks::InclusionDirective handles producing
733 // appropriate output here. Ignore this token entirely.
Richard Smithce587f52013-11-15 04:24:58 +0000734 PP.Lex(Tok);
735 continue;
Richard Smithd1386302017-05-04 00:29:54 +0000736 } else if (Tok.is(tok::annot_module_begin)) {
737 // FIXME: We retrieve this token after the FileChanged callback, and
738 // retrieve the module_end token before the FileChanged callback, so
739 // we render this within the file and render the module end outside the
740 // file, but this is backwards from the token locations: the module_begin
741 // token is at the include location (outside the file) and the module_end
742 // token is at the EOF location (within the file).
743 Callbacks->BeginModule(
744 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
745 PP.Lex(Tok);
746 continue;
747 } else if (Tok.is(tok::annot_module_end)) {
748 Callbacks->EndModule(
749 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
750 PP.Lex(Tok);
751 continue;
David Blaikie1013fe72018-11-15 03:04:21 +0000752 } else if (Tok.isAnnotation()) {
753 // Ignore annotation tokens created by pragmas - the pragmas themselves
754 // will be reproduced in the preprocessed output.
755 PP.Lex(Tok);
756 continue;
Jordan Rose67b66232013-03-05 23:54:55 +0000757 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
Benjamin Kramer718f7222010-02-27 18:02:51 +0000758 OS << II->getName();
759 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
760 Tok.getLiteralData()) {
761 OS.write(Tok.getLiteralData(), Tok.getLength());
Paul Robinson4bb85ac2018-01-03 20:29:49 +0000762 } else if (Tok.getLength() < llvm::array_lengthof(Buffer)) {
Benjamin Kramer718f7222010-02-27 18:02:51 +0000763 const char *TokPtr = Buffer;
764 unsigned Len = PP.getSpelling(Tok, TokPtr);
765 OS.write(TokPtr, Len);
Mike Stump11289f42009-09-09 15:08:12 +0000766
Benjamin Kramer718f7222010-02-27 18:02:51 +0000767 // Tokens that can contain embedded newlines need to adjust our current
768 // line number.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000769 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramer718f7222010-02-27 18:02:51 +0000770 Callbacks->HandleNewlinesInToken(TokPtr, Len);
771 } else {
772 std::string S = PP.getSpelling(Tok);
773 OS.write(&S[0], S.size());
774
775 // Tokens that can contain embedded newlines need to adjust our current
776 // line number.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000777 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramer718f7222010-02-27 18:02:51 +0000778 Callbacks->HandleNewlinesInToken(&S[0], S.size());
779 }
Jordan Rose127f6ee2012-06-15 23:33:51 +0000780 Callbacks->setEmittedTokensOnThisLine();
Mike Stump11289f42009-09-09 15:08:12 +0000781
Chris Lattner3ff2e692007-10-10 20:45:16 +0000782 if (Tok.is(tok::eof)) break;
Mike Stump11289f42009-09-09 15:08:12 +0000783
Chris Lattner0384e6352010-04-14 03:57:19 +0000784 PrevPrevTok = PrevTok;
Chris Lattner3ff2e692007-10-10 20:45:16 +0000785 PrevTok = Tok;
786 PP.Lex(Tok);
787 }
Chris Lattnerfc001b02009-02-06 05:56:11 +0000788}
789
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000790typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
791static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
792 return LHS->first->getName().compare(RHS->first->getName());
793}
794
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000795static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
Daniel Dunbard839e772010-06-11 20:10:12 +0000796 // Ignore unknown pragmas.
Lubos Lunak576a0412014-05-01 12:54:03 +0000797 PP.IgnorePragmas();
Daniel Dunbard839e772010-06-11 20:10:12 +0000798
Eli Friedman26c672b2009-05-19 01:32:34 +0000799 // -dM mode just scans and ignores all tokens in the files, then dumps out
800 // the macro table at the end.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000801 PP.EnterMainSourceFile();
Eli Friedman26c672b2009-05-19 01:32:34 +0000802
803 Token Tok;
804 do PP.Lex(Tok);
805 while (Tok.isNot(tok::eof));
806
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000807 SmallVector<id_macro_pair, 128> MacrosByID;
808 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
809 I != E; ++I) {
Richard Smith20e883e2015-04-29 23:20:19 +0000810 auto *MD = I->second.getLatest();
811 if (MD && MD->isDefined())
812 MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000813 }
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000814 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedman26c672b2009-05-19 01:32:34 +0000815
816 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
817 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000818 // Ignore computed macros like __LINE__ and friends.
Eli Friedman26c672b2009-05-19 01:32:34 +0000819 if (MI.isBuiltinMacro()) continue;
820
821 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +0000822 *OS << '\n';
Eli Friedman26c672b2009-05-19 01:32:34 +0000823 }
824}
825
Chris Lattnerfc001b02009-02-06 05:56:11 +0000826/// DoPrintPreprocessedInput - This implements -E mode.
827///
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000828void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
Daniel Dunbar22bdabf2009-11-11 10:07:44 +0000829 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000830 // Show macros with no output is handled specially.
831 if (!Opts.ShowCPP) {
832 assert(Opts.ShowMacros && "Not yet implemented!");
833 DoPrintMacros(PP, OS);
834 return;
835 }
836
Chris Lattnerfc001b02009-02-06 05:56:11 +0000837 // Inform the preprocessor whether we want it to retain comments or not, due
838 // to -C or -CC.
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000839 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanfcb57d52009-05-19 01:02:07 +0000840
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000841 PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000842 PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
843 Opts.ShowIncludeDirectives, Opts.UseLineDirectives);
Samuel Antaoeab747b2015-06-15 23:44:27 +0000844
845 // Expand macros in pragmas with -fms-extensions. The assumption is that
846 // the majority of pragmas in such a file will be Microsoft pragmas.
Vassil Vassilev2b676cf2017-04-27 16:58:33 +0000847 // Remember the handlers we will add so that we can remove them later.
848 std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(
849 new UnknownPragmaHandler(
850 "#pragma", Callbacks,
851 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
852
853 std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(
854 "#pragma GCC", Callbacks,
Samuel Antaoeab747b2015-06-15 23:44:27 +0000855 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
Vassil Vassilev2b676cf2017-04-27 16:58:33 +0000856
857 std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(
858 "#pragma clang", Callbacks,
859 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
860
861 PP.AddPragmaHandler(MicrosoftExtHandler.get());
862 PP.AddPragmaHandler("GCC", GCCHandler.get());
863 PP.AddPragmaHandler("clang", ClangHandler.get());
Samuel Antaoeab747b2015-06-15 23:44:27 +0000864
865 // The tokens after pragma omp need to be expanded.
866 //
867 // OpenMP [2.1, Directive format]
868 // Preprocessing tokens following the #pragma omp are subject to macro
869 // replacement.
Vassil Vassilev2b676cf2017-04-27 16:58:33 +0000870 std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(
871 new UnknownPragmaHandler("#pragma omp", Callbacks,
872 /*RequireTokenExpansion=*/true));
873 PP.AddPragmaHandler("omp", OpenMPHandler.get());
Chris Lattnerfc001b02009-02-06 05:56:11 +0000874
Craig Topperb8a70532014-09-10 04:53:53 +0000875 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
Chris Lattnerfc001b02009-02-06 05:56:11 +0000876
Eli Friedman26c672b2009-05-19 01:32:34 +0000877 // After we have configured the preprocessor, enter the main file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000878 PP.EnterMainSourceFile();
Chris Lattnerfc001b02009-02-06 05:56:11 +0000879
Eli Friedman26c672b2009-05-19 01:32:34 +0000880 // Consume all of the tokens that come from the predefines buffer. Those
881 // should not be emitted into the output and are guaranteed to be at the
882 // start.
883 const SourceManager &SourceMgr = PP.getSourceManager();
884 Token Tok;
Douglas Gregor453b0122010-11-12 07:15:47 +0000885 do {
886 PP.Lex(Tok);
887 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
888 break;
889
890 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
891 if (PLoc.isInvalid())
892 break;
893
894 if (strcmp(PLoc.getFilename(), "<built-in>"))
895 break;
896 } while (true);
Chris Lattnerfc001b02009-02-06 05:56:11 +0000897
Eli Friedman26c672b2009-05-19 01:32:34 +0000898 // Read all the preprocessed tokens, printing them out to the stream.
899 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
900 *OS << '\n';
Vassil Vassilev2b676cf2017-04-27 16:58:33 +0000901
902 // Remove the handlers we just added to leave the preprocessor in a sane state
903 // so that it can be reused (for example by a clang::Parser instance).
904 PP.RemovePragmaHandler(MicrosoftExtHandler.get());
905 PP.RemovePragmaHandler("GCC", GCCHandler.get());
906 PP.RemovePragmaHandler("clang", ClangHandler.get());
907 PP.RemovePragmaHandler("omp", OpenMPHandler.get());
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000908}