blob: 720ed51c5f6524e21a77027af7f52b3f3746e0c8 [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;
Reid Kleckner0f56b222019-03-14 18:12:17 +0000146 void PragmaExecCharsetPush(SourceLocation Loc, StringRef Str) override;
147 void PragmaExecCharsetPop(SourceLocation Loc) override;
Eli Friedman16fee082017-09-27 23:29:37 +0000148 void PragmaAssumeNonNullBegin(SourceLocation Loc) override;
149 void PragmaAssumeNonNullEnd(SourceLocation Loc) override;
Chris Lattner87f267e2006-11-21 05:02:33 +0000150
Chris Lattner3ed83c12007-12-09 21:11:08 +0000151 bool HandleFirstTokOnLine(Token &Tok);
Hal Finkel2109f232013-01-28 04:37:37 +0000152
153 /// Move to the line of the provided source location. This will
154 /// return true if the output stream required adjustment or if
155 /// the requested location is on the first line.
Chris Lattner5dbefc62010-04-13 00:01:41 +0000156 bool MoveToLine(SourceLocation Loc) {
Douglas Gregor453b0122010-11-12 07:15:47 +0000157 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
158 if (PLoc.isInvalid())
159 return false;
Hal Finkel2109f232013-01-28 04:37:37 +0000160 return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
Chris Lattner5dbefc62010-04-13 00:01:41 +0000161 }
162 bool MoveToLine(unsigned LineNo);
163
Fangrui Song6907ce22018-07-30 19:24:48 +0000164 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
Chris Lattner0384e6352010-04-14 03:57:19 +0000165 const Token &Tok) {
166 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
Chris Lattner644d4522009-02-13 00:46:04 +0000167 }
Craig Topper49a27902014-05-22 04:46:25 +0000168 void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
169 unsigned ExtraLen=0);
Douglas Gregorc7d65762010-09-09 22:45:38 +0000170 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000171 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump11289f42009-09-09 15:08:12 +0000172
Chris Lattnercac63f32009-04-12 01:56:53 +0000173 /// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Topperafa7cb32014-03-13 06:07:04 +0000174 void MacroDefined(const Token &MacroNameTok,
175 const MacroDirective *MD) override;
Mike Stump11289f42009-09-09 15:08:12 +0000176
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000177 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
Craig Topperafa7cb32014-03-13 06:07:04 +0000178 void MacroUndefined(const Token &MacroNameTok,
Vedant Kumar349a6242017-04-26 21:05:44 +0000179 const MacroDefinition &MD,
180 const MacroDirective *Undef) override;
Richard Smithd1386302017-05-04 00:29:54 +0000181
182 void BeginModule(const Module *M);
183 void EndModule(const Module *M);
Chris Lattner87f267e2006-11-21 05:02:33 +0000184};
Chris Lattner21632652008-04-08 04:16:20 +0000185} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000186
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000187void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
188 const char *Extra,
189 unsigned ExtraLen) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000190 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000191
Chris Lattner76b44452009-12-07 01:42:56 +0000192 // Emit #line directives or GNU line markers depending on what mode we're in.
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000193 if (UseLineDirectives) {
Chris Lattner76b44452009-12-07 01:42:56 +0000194 OS << "#line" << ' ' << LineNo << ' ' << '"';
Eli Friedman80e45b82013-08-29 01:42:42 +0000195 OS.write_escaped(CurFilename);
Chris Lattner76b44452009-12-07 01:42:56 +0000196 OS << '"';
197 } else {
198 OS << '#' << ' ' << LineNo << ' ' << '"';
Eli Friedman80e45b82013-08-29 01:42:42 +0000199 OS.write_escaped(CurFilename);
Chris Lattner76b44452009-12-07 01:42:56 +0000200 OS << '"';
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +0000201
Steve Naroff66aaa392009-12-06 01:02:14 +0000202 if (ExtraLen)
203 OS.write(Extra, ExtraLen);
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000204
Steve Naroff66aaa392009-12-06 01:02:14 +0000205 if (FileType == SrcMgr::C_System)
206 OS.write(" 3", 2);
207 else if (FileType == SrcMgr::C_ExternCSystem)
208 OS.write(" 3 4", 4);
209 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000210 OS << '\n';
211}
212
Chris Lattner728b4dc2006-07-04 21:28:37 +0000213/// MoveToLine - Move the output to the source line specified by the location
214/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner3ed83c12007-12-09 21:11:08 +0000215/// #line directive. This returns false if already at the specified line, true
216/// if some newlines were emitted.
Chris Lattner5dbefc62010-04-13 00:01:41 +0000217bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000218 // If this line is "close enough" to the original line, just print newlines,
219 // otherwise print a #line directive.
Daniel Dunbare7781312008-09-26 01:13:35 +0000220 if (LineNo-CurLine <= 8) {
Chris Lattner5f075822007-07-23 05:14:05 +0000221 if (LineNo-CurLine == 1)
Chris Lattner068529a2008-08-17 03:12:02 +0000222 OS << '\n';
Chris Lattner3ed83c12007-12-09 21:11:08 +0000223 else if (LineNo == CurLine)
Chandler Carruth46a32c22011-07-14 16:14:52 +0000224 return false; // Spelling line moved, but expansion line didn't.
Chris Lattner5f075822007-07-23 05:14:05 +0000225 else {
226 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattner068529a2008-08-17 03:12:02 +0000227 OS.write(NewLines, LineNo-CurLine);
Chris Lattner5f075822007-07-23 05:14:05 +0000228 }
Chris Lattnerbc6bcab2010-06-12 16:20:56 +0000229 } else if (!DisableLineMarkers) {
230 // Emit a #line or line marker.
Craig Topper49a27902014-05-22 04:46:25 +0000231 WriteLineInfo(LineNo, nullptr, 0);
Chris Lattnerbc6bcab2010-06-12 16:20:56 +0000232 } else {
233 // Okay, we're in -P mode, which turns off line markers. However, we still
234 // need to emit a newline between tokens on different lines.
Jordan Rose127f6ee2012-06-15 23:33:51 +0000235 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Mike Stump11289f42009-09-09 15:08:12 +0000236 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000237
Mike Stump11289f42009-09-09 15:08:12 +0000238 CurLine = LineNo;
Chris Lattner3ed83c12007-12-09 21:11:08 +0000239 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000240}
241
Jordan Rose127f6ee2012-06-15 23:33:51 +0000242bool
243PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
244 if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
Douglas Gregorc7d65762010-09-09 22:45:38 +0000245 OS << '\n';
246 EmittedTokensOnThisLine = false;
Jordan Rose127f6ee2012-06-15 23:33:51 +0000247 EmittedDirectiveOnThisLine = false;
248 if (ShouldUpdateCurrentLine)
249 ++CurLine;
Douglas Gregorc7d65762010-09-09 22:45:38 +0000250 return true;
251 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000252
Douglas Gregorc7d65762010-09-09 22:45:38 +0000253 return false;
254}
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000255
256/// FileChanged - Whenever the preprocessor enters or exits a #include file
257/// it invokes this handler. Update our conception of the current source
258/// position.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000259void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
260 FileChangeReason Reason,
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000261 SrcMgr::CharacteristicKind NewFileType,
262 FileID PrevFID) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000263 // Unless we are exiting a #include, make sure to skip ahead to the line the
264 // #include directive was at.
Chris Lattner9d94f042010-04-13 00:06:42 +0000265 SourceManager &SourceMgr = SM;
Fangrui Song6907ce22018-07-30 19:24:48 +0000266
Chris Lattner5dbefc62010-04-13 00:01:41 +0000267 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Douglas Gregor453b0122010-11-12 07:15:47 +0000268 if (UserLoc.isInvalid())
269 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000270
Chris Lattnerc745cec2010-04-14 04:28:50 +0000271 unsigned NewLine = UserLoc.getLine();
Daniel Dunbard4352752010-08-24 22:44:13 +0000272
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000273 if (Reason == PPCallbacks::EnterFile) {
Douglas Gregor453b0122010-11-12 07:15:47 +0000274 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
Chris Lattnerd8cc8842009-01-30 18:44:17 +0000275 if (IncludeLoc.isValid())
276 MoveToLine(IncludeLoc);
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000277 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
Jordan Rose111c4a62013-04-17 19:09:18 +0000278 // GCC emits the # directive for this directive on the line AFTER the
279 // directive and emits a bunch of spaces that aren't needed. This is because
280 // otherwise we will emit a line marker for THIS line, which requires an
281 // extra blank line after the directive to avoid making all following lines
282 // off by one. We can do better by simply incrementing NewLine here.
283 NewLine += 1;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000284 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000285
Chris Lattner5dbefc62010-04-13 00:01:41 +0000286 CurLine = NewLine;
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000287
Chris Lattner4c4a2452007-07-24 06:57:14 +0000288 CurFilename.clear();
Chris Lattner5dbefc62010-04-13 00:01:41 +0000289 CurFilename += UserLoc.getFilename();
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000290 FileType = NewFileType;
291
Eli Friedmanc52435b2013-01-09 03:16:42 +0000292 if (DisableLineMarkers) {
293 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
294 return;
295 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000296
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000297 if (!Initialized) {
298 WriteLineInfo(CurLine);
299 Initialized = true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000300 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000301
Daniel Dunbar5d388752012-11-16 01:51:11 +0000302 // Do not emit an enter marker for the main file (which we expect is the first
303 // entered file). This matches gcc, and improves compatibility with some tools
304 // which track the # line markers as a way to determine when the preprocessed
305 // output is in the context of the main file.
306 if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
307 IsFirstFileEntered = true;
308 return;
309 }
310
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000311 switch (Reason) {
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000312 case PPCallbacks::EnterFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000313 WriteLineInfo(CurLine, " 1", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000314 break;
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000315 case PPCallbacks::ExitFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000316 WriteLineInfo(CurLine, " 2", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000317 break;
Mike Stump11289f42009-09-09 15:08:12 +0000318 case PPCallbacks::SystemHeaderPragma:
319 case PPCallbacks::RenameFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000320 WriteLineInfo(CurLine);
321 break;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000322 }
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000323}
324
Julie Hockett96fbe582018-05-10 19:05:36 +0000325void PrintPPOutputPPCallbacks::InclusionDirective(
326 SourceLocation HashLoc,
327 const Token &IncludeTok,
328 StringRef FileName,
329 bool IsAngled,
330 CharSourceRange FilenameRange,
331 const FileEntry *File,
332 StringRef SearchPath,
333 StringRef RelativePath,
334 const Module *Imported,
335 SrcMgr::CharacteristicKind FileType) {
Richard Smithc51c38b2017-04-29 00:34:47 +0000336 // In -dI mode, dump #include directives prior to dumping their content or
337 // interpretation.
338 if (DumpIncludeDirectives) {
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000339 startNewLineIfNeeded();
340 MoveToLine(HashLoc);
Richard Smithc51c38b2017-04-29 00:34:47 +0000341 const std::string TokenText = PP.getSpelling(IncludeTok);
342 assert(!TokenText.empty());
343 OS << "#" << TokenText << " "
344 << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
345 << " /* clang -E -dI */";
346 setEmittedDirectiveOnThisLine();
Ben Langmuir5418f402014-09-10 21:29:41 +0000347 startNewLineIfNeeded();
Richard Smithc51c38b2017-04-29 00:34:47 +0000348 }
349
350 // When preprocessing, turn implicit imports into module import pragmas.
351 if (Imported) {
352 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
353 case tok::pp_include:
354 case tok::pp_import:
355 case tok::pp_include_next:
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000356 startNewLineIfNeeded();
357 MoveToLine(HashLoc);
Richard Smith9565c75b2017-06-19 23:09:36 +0000358 OS << "#pragma clang module import " << Imported->getFullModuleName(true)
Richard Smithc51c38b2017-04-29 00:34:47 +0000359 << " /* clang -E: implicit import for "
360 << "#" << PP.getSpelling(IncludeTok) << " "
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000361 << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
Richard Smithc51c38b2017-04-29 00:34:47 +0000362 << " */";
363 // Since we want a newline after the pragma, but not a #<line>, start a
364 // new line immediately.
365 EmittedTokensOnThisLine = true;
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000366 startNewLineIfNeeded();
Richard Smithc51c38b2017-04-29 00:34:47 +0000367 break;
368
369 case tok::pp___include_macros:
370 // #__include_macros has no effect on a user of a preprocessed source
371 // file; the only effect is on preprocessing.
372 //
373 // FIXME: That's not *quite* true: it causes the module in question to
374 // be loaded, which can affect downstream diagnostics.
375 break;
376
377 default:
378 llvm_unreachable("unknown include directive kind");
379 break;
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000380 }
Argyrios Kyrtzidisa6444b12013-04-10 01:53:46 +0000381 }
382}
383
Richard Smithd1386302017-05-04 00:29:54 +0000384/// Handle entering the scope of a module during a module compilation.
385void PrintPPOutputPPCallbacks::BeginModule(const Module *M) {
386 startNewLineIfNeeded();
Richard Smith9565c75b2017-06-19 23:09:36 +0000387 OS << "#pragma clang module begin " << M->getFullModuleName(true);
Richard Smithd1386302017-05-04 00:29:54 +0000388 setEmittedDirectiveOnThisLine();
389}
390
391/// Handle leaving the scope of a module during a module compilation.
392void PrintPPOutputPPCallbacks::EndModule(const Module *M) {
393 startNewLineIfNeeded();
Richard Smith9565c75b2017-06-19 23:09:36 +0000394 OS << "#pragma clang module end /*" << M->getFullModuleName(true) << "*/";
Richard Smithd1386302017-05-04 00:29:54 +0000395 setEmittedDirectiveOnThisLine();
396}
397
Chris Lattner5eef5072009-01-16 19:25:54 +0000398/// Ident - Handle #ident directives when read by the preprocessor.
Chris Lattner728b4dc2006-07-04 21:28:37 +0000399///
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000400void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
Chris Lattner3338ba82006-07-04 21:19:39 +0000401 MoveToLine(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000402
Chris Lattner068529a2008-08-17 03:12:02 +0000403 OS.write("#ident ", strlen("#ident "));
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000404 OS.write(S.begin(), S.size());
Chris Lattner87f267e2006-11-21 05:02:33 +0000405 EmittedTokensOnThisLine = true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000406}
407
Chris Lattnercac63f32009-04-12 01:56:53 +0000408/// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000409void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000410 const MacroDirective *MD) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000411 const MacroInfo *MI = MD->getMacroInfo();
Chris Lattnercac63f32009-04-12 01:56:53 +0000412 // Only print out macro definitions in -dD mode.
413 if (!DumpDefines ||
414 // Ignore __FILE__ etc.
415 MI->isBuiltinMacro()) return;
Mike Stump11289f42009-09-09 15:08:12 +0000416
Chris Lattnercac63f32009-04-12 01:56:53 +0000417 MoveToLine(MI->getDefinitionLoc());
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000418 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
Jordan Rose127f6ee2012-06-15 23:33:51 +0000419 setEmittedDirectiveOnThisLine();
Chris Lattnercac63f32009-04-12 01:56:53 +0000420}
421
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000422void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
Vedant Kumar349a6242017-04-26 21:05:44 +0000423 const MacroDefinition &MD,
424 const MacroDirective *Undef) {
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000425 // Only print out macro definitions in -dD mode.
426 if (!DumpDefines) return;
427
Craig Silverstein1a9ca212010-11-19 21:33:15 +0000428 MoveToLine(MacroNameTok.getLocation());
429 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
Jordan Rose127f6ee2012-06-15 23:33:51 +0000430 setEmittedDirectiveOnThisLine();
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000431}
Chris Lattnercac63f32009-04-12 01:56:53 +0000432
Benjamin Kramer0772c422016-02-13 13:42:54 +0000433static void outputPrintable(raw_ostream &OS, StringRef Str) {
434 for (unsigned char Char : Str) {
435 if (isPrintable(Char) && Char != '\\' && Char != '"')
436 OS << (char)Char;
437 else // Output anything hard as an octal escape.
438 OS << '\\'
439 << (char)('0' + ((Char >> 6) & 7))
440 << (char)('0' + ((Char >> 3) & 7))
441 << (char)('0' + ((Char >> 0) & 7));
442 }
Aaron Ballman5d041be2013-06-04 02:07:14 +0000443}
444
Chris Lattner30c924b2010-06-26 17:11:39 +0000445void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000446 StringRef Namespace,
447 PragmaMessageKind Kind,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000448 StringRef Str) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000449 startNewLineIfNeeded();
Chris Lattner30c924b2010-06-26 17:11:39 +0000450 MoveToLine(Loc);
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000451 OS << "#pragma ";
452 if (!Namespace.empty())
453 OS << Namespace << ' ';
454 switch (Kind) {
455 case PMK_Message:
Andy Gibbsaa0b94a2013-04-19 17:13:17 +0000456 OS << "message(\"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000457 break;
458 case PMK_Warning:
Andy Gibbs96d93902013-04-18 16:49:37 +0000459 OS << "warning \"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000460 break;
461 case PMK_Error:
Andy Gibbs96d93902013-04-18 16:49:37 +0000462 OS << "error \"";
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000463 break;
464 }
Chris Lattner30c924b2010-06-26 17:11:39 +0000465
Aaron Ballman5d041be2013-06-04 02:07:14 +0000466 outputPrintable(OS, Str);
Chris Lattner30c924b2010-06-26 17:11:39 +0000467 OS << '"';
Andy Gibbsaa0b94a2013-04-19 17:13:17 +0000468 if (Kind == PMK_Message)
469 OS << ')';
Jordan Rose127f6ee2012-06-15 23:33:51 +0000470 setEmittedDirectiveOnThisLine();
Chris Lattner30c924b2010-06-26 17:11:39 +0000471}
472
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000473void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
474 StringRef DebugType) {
475 startNewLineIfNeeded();
476 MoveToLine(Loc);
477
478 OS << "#pragma clang __debug ";
479 OS << DebugType;
480
481 setEmittedDirectiveOnThisLine();
482}
483
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000484void PrintPPOutputPPCallbacks::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000485PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000486 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000487 MoveToLine(Loc);
488 OS << "#pragma " << Namespace << " diagnostic push";
Jordan Rose127f6ee2012-06-15 23:33:51 +0000489 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000490}
491
492void PrintPPOutputPPCallbacks::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000493PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000494 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000495 MoveToLine(Loc);
496 OS << "#pragma " << Namespace << " diagnostic pop";
Jordan Rose127f6ee2012-06-15 23:33:51 +0000497 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000498}
499
Alp Tokerc726c362014-06-10 09:31:37 +0000500void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
501 StringRef Namespace,
502 diag::Severity Map,
503 StringRef Str) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000504 startNewLineIfNeeded();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000505 MoveToLine(Loc);
506 OS << "#pragma " << Namespace << " diagnostic ";
Benjamin Kramer7ec12c92012-02-07 22:29:24 +0000507 switch (Map) {
Alp Toker46df1c02014-06-12 10:15:20 +0000508 case diag::Severity::Remark:
Tobias Grosser74160242014-02-28 09:11:08 +0000509 OS << "remark";
510 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000511 case diag::Severity::Warning:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000512 OS << "warning";
513 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000514 case diag::Severity::Error:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000515 OS << "error";
516 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000517 case diag::Severity::Ignored:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000518 OS << "ignored";
519 break;
Alp Toker46df1c02014-06-12 10:15:20 +0000520 case diag::Severity::Fatal:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000521 OS << "fatal";
522 break;
523 }
524 OS << " \"" << Str << '"';
Jordan Rose127f6ee2012-06-15 23:33:51 +0000525 setEmittedDirectiveOnThisLine();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000526}
Chris Lattner5eef5072009-01-16 19:25:54 +0000527
Reid Kleckner881dff32013-09-13 22:00:30 +0000528void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
529 StringRef WarningSpec,
530 ArrayRef<int> Ids) {
531 startNewLineIfNeeded();
532 MoveToLine(Loc);
533 OS << "#pragma warning(" << WarningSpec << ':';
534 for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
535 OS << ' ' << *I;
536 OS << ')';
537 setEmittedDirectiveOnThisLine();
538}
539
540void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
541 int Level) {
542 startNewLineIfNeeded();
543 MoveToLine(Loc);
544 OS << "#pragma warning(push";
Reid Kleckner4d185102013-10-02 15:19:23 +0000545 if (Level >= 0)
Reid Kleckner881dff32013-09-13 22:00:30 +0000546 OS << ", " << Level;
547 OS << ')';
548 setEmittedDirectiveOnThisLine();
549}
550
551void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
552 startNewLineIfNeeded();
553 MoveToLine(Loc);
554 OS << "#pragma warning(pop)";
555 setEmittedDirectiveOnThisLine();
556}
557
Reid Kleckner0f56b222019-03-14 18:12:17 +0000558void PrintPPOutputPPCallbacks::PragmaExecCharsetPush(SourceLocation Loc,
559 StringRef Str) {
560 startNewLineIfNeeded();
561 MoveToLine(Loc);
562 OS << "#pragma character_execution_set(push";
563 if (!Str.empty())
564 OS << ", " << Str;
565 OS << ')';
566 setEmittedDirectiveOnThisLine();
567}
568
569void PrintPPOutputPPCallbacks::PragmaExecCharsetPop(SourceLocation Loc) {
570 startNewLineIfNeeded();
571 MoveToLine(Loc);
572 OS << "#pragma character_execution_set(pop)";
573 setEmittedDirectiveOnThisLine();
574}
575
Eli Friedman16fee082017-09-27 23:29:37 +0000576void PrintPPOutputPPCallbacks::
577PragmaAssumeNonNullBegin(SourceLocation Loc) {
578 startNewLineIfNeeded();
579 MoveToLine(Loc);
580 OS << "#pragma clang assume_nonnull begin";
581 setEmittedDirectiveOnThisLine();
582}
583
584void PrintPPOutputPPCallbacks::
585PragmaAssumeNonNullEnd(SourceLocation Loc) {
586 startNewLineIfNeeded();
587 MoveToLine(Loc);
588 OS << "#pragma clang assume_nonnull end";
589 setEmittedDirectiveOnThisLine();
590}
591
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000592/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner3ed83c12007-12-09 21:11:08 +0000593/// is called for the first token on each new line. If this really is the start
594/// of a new logical line, handle it and return true, otherwise return false.
595/// This may not be the start of a logical line because the "start of line"
Chandler Carruth46a32c22011-07-14 16:14:52 +0000596/// marker is set for spelling lines, not expansion ones.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000597bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000598 // Figure out what line we went to and insert the appropriate number of
599 // newline characters.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000600 if (!MoveToLine(Tok.getLocation()))
601 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000602
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000603 // Print out space characters so that the first token on a line is
604 // indented for easy reading.
Chandler Carruth42f35f92011-07-25 20:57:57 +0000605 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000606
Richard Smith5b2f7c52014-02-24 20:50:36 +0000607 // The first token on a line can have a column number of 1, yet still expect
608 // leading white space, if a macro expansion in column 1 starts with an empty
609 // macro argument, or an empty nested macro expansion. In this case, move the
610 // token to column 2.
611 if (ColNo == 1 && Tok.hasLeadingSpace())
612 ColNo = 2;
613
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000614 // This hack prevents stuff like:
615 // #define HASH #
616 // HASH define foo bar
617 // From having the # character end up at column 1, which makes it so it
618 // is not handled as a #define next time through the preprocessor if in
619 // -fpreprocessed mode.
Chris Lattner3c69f122007-10-09 18:03:42 +0000620 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattner068529a2008-08-17 03:12:02 +0000621 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000622
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000623 // Otherwise, indent the appropriate number of spaces.
624 for (; ColNo > 1; --ColNo)
Chris Lattner068529a2008-08-17 03:12:02 +0000625 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000626
Chris Lattner3ed83c12007-12-09 21:11:08 +0000627 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000628}
629
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000630void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
631 unsigned Len) {
632 unsigned NumNewlines = 0;
633 for (; Len; --Len, ++TokStr) {
634 if (*TokStr != '\n' &&
635 *TokStr != '\r')
636 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000637
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000638 ++NumNewlines;
Mike Stump11289f42009-09-09 15:08:12 +0000639
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000640 // If we have \n\r or \r\n, skip both and count as one line.
641 if (Len != 1 &&
642 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
Richard Trieucc3949d2016-02-18 22:34:54 +0000643 TokStr[0] != TokStr[1]) {
644 ++TokStr;
645 --Len;
646 }
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000647 }
Mike Stump11289f42009-09-09 15:08:12 +0000648
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000649 if (NumNewlines == 0) return;
Mike Stump11289f42009-09-09 15:08:12 +0000650
Chris Lattnera5e67752009-06-15 04:08:28 +0000651 CurLine += NumNewlines;
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000652}
653
654
Chris Lattner5de858c2006-07-04 19:04:44 +0000655namespace {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000656struct UnknownPragmaHandler : public PragmaHandler {
657 const char *Prefix;
Chris Lattner87f267e2006-11-21 05:02:33 +0000658 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump11289f42009-09-09 15:08:12 +0000659
Samuel Antaoeab747b2015-06-15 23:44:27 +0000660 // Set to true if tokens should be expanded
661 bool ShouldExpandTokens;
662
663 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
664 bool RequireTokenExpansion)
665 : Prefix(prefix), Callbacks(callbacks),
666 ShouldExpandTokens(RequireTokenExpansion) {}
Craig Topperafa7cb32014-03-13 06:07:04 +0000667 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
668 Token &PragmaTok) override {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000669 // Figure out what line we went to and insert the appropriate number of
670 // newline characters.
Jordan Rose127f6ee2012-06-15 23:33:51 +0000671 Callbacks->startNewLineIfNeeded();
Chris Lattner87f267e2006-11-21 05:02:33 +0000672 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattner068529a2008-08-17 03:12:02 +0000673 Callbacks->OS.write(Prefix, strlen(Prefix));
Samuel Antaoeab747b2015-06-15 23:44:27 +0000674
Alexey Bataev56f5ad12016-02-09 11:01:58 +0000675 if (ShouldExpandTokens) {
676 // The first token does not have expanded macros. Expand them, if
677 // required.
David Blaikie2eabcc92016-02-09 18:52:09 +0000678 auto Toks = llvm::make_unique<Token[]>(1);
Alexey Bataev56f5ad12016-02-09 11:01:58 +0000679 Toks[0] = PragmaTok;
David Blaikie2eabcc92016-02-09 18:52:09 +0000680 PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
Ilya Biryukov929af672019-05-17 09:32:05 +0000681 /*DisableMacroExpansion=*/false,
682 /*IsReinject=*/false);
Alexey Bataev56f5ad12016-02-09 11:01:58 +0000683 PP.Lex(PragmaTok);
684 }
Samuel Antaoeab747b2015-06-15 23:44:27 +0000685 Token PrevToken;
686 Token PrevPrevToken;
687 PrevToken.startToken();
688 PrevPrevToken.startToken();
689
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000690 // Read and print all of the pragma tokens.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000691 while (PragmaTok.isNot(tok::eod)) {
Samuel Antaoeab747b2015-06-15 23:44:27 +0000692 if (PragmaTok.hasLeadingSpace() ||
693 Callbacks->AvoidConcat(PrevPrevToken, PrevToken, PragmaTok))
Chris Lattner068529a2008-08-17 03:12:02 +0000694 Callbacks->OS << ' ';
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000695 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattner068529a2008-08-17 03:12:02 +0000696 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Kleckner0e73ec42014-02-20 22:59:51 +0000697
Samuel Antaoeab747b2015-06-15 23:44:27 +0000698 PrevPrevToken = PrevToken;
699 PrevToken = PragmaTok;
700
701 if (ShouldExpandTokens)
Reid Kleckner0e73ec42014-02-20 22:59:51 +0000702 PP.Lex(PragmaTok);
703 else
704 PP.LexUnexpandedToken(PragmaTok);
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000705 }
Jordan Rose127f6ee2012-06-15 23:33:51 +0000706 Callbacks->setEmittedDirectiveOnThisLine();
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000707 }
708};
Chris Lattner5de858c2006-07-04 19:04:44 +0000709} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000710
Chris Lattner4418ce12007-07-23 06:09:34 +0000711
Chris Lattnerfc001b02009-02-06 05:56:11 +0000712static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
713 PrintPPOutputPPCallbacks *Callbacks,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000714 raw_ostream &OS) {
Jordan Rose67b66232013-03-05 23:54:55 +0000715 bool DropComments = PP.getLangOpts().TraditionalCPP &&
716 !PP.getCommentRetentionState();
717
Benjamin Kramer718f7222010-02-27 18:02:51 +0000718 char Buffer[256];
Chris Lattnerbba37f42010-06-15 21:06:38 +0000719 Token PrevPrevTok, PrevTok;
720 PrevPrevTok.startToken();
721 PrevTok.startToken();
Chris Lattner3ff2e692007-10-10 20:45:16 +0000722 while (1) {
Jordan Rose127f6ee2012-06-15 23:33:51 +0000723 if (Callbacks->hasEmittedDirectiveOnThisLine()) {
724 Callbacks->startNewLineIfNeeded();
725 Callbacks->MoveToLine(Tok.getLocation());
726 }
Mike Stump11289f42009-09-09 15:08:12 +0000727
Chris Lattner67c38482006-07-04 23:24:26 +0000728 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000729 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
730 // done.
Mike Stump11289f42009-09-09 15:08:12 +0000731 } else if (Tok.hasLeadingSpace() ||
Chris Lattner4418ce12007-07-23 06:09:34 +0000732 // If we haven't emitted a token on this line yet, PrevTok isn't
733 // useful to look at and no concatenation could happen anyway.
Chris Lattnerd63c8a52007-07-23 23:21:34 +0000734 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattner4418ce12007-07-23 06:09:34 +0000735 // Don't print "-" next to "-", it would form "--".
Chris Lattner0384e6352010-04-14 03:57:19 +0000736 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattner068529a2008-08-17 03:12:02 +0000737 OS << ' ';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000738 }
Mike Stump11289f42009-09-09 15:08:12 +0000739
Jordan Rose67b66232013-03-05 23:54:55 +0000740 if (DropComments && Tok.is(tok::comment)) {
741 // Skip comments. Normally the preprocessor does not generate
742 // tok::comment nodes at all when not keeping comments, but under
743 // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
744 SourceLocation StartLoc = Tok.getLocation();
745 Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
Reid Kleckner400a64e2017-10-16 23:07:15 +0000746 } else if (Tok.is(tok::eod)) {
747 // Don't print end of directive tokens, since they are typically newlines
748 // that mess up our line tracking. These come from unknown pre-processor
749 // directives or hash-prefixed comments in standalone assembly files.
750 PP.Lex(Tok);
751 continue;
Richard Smithd1386302017-05-04 00:29:54 +0000752 } else if (Tok.is(tok::annot_module_include)) {
Ben Langmuir5eb7cb72014-01-30 21:50:18 +0000753 // PrintPPOutputPPCallbacks::InclusionDirective handles producing
754 // appropriate output here. Ignore this token entirely.
Richard Smithce587f52013-11-15 04:24:58 +0000755 PP.Lex(Tok);
756 continue;
Richard Smithd1386302017-05-04 00:29:54 +0000757 } else if (Tok.is(tok::annot_module_begin)) {
758 // FIXME: We retrieve this token after the FileChanged callback, and
759 // retrieve the module_end token before the FileChanged callback, so
760 // we render this within the file and render the module end outside the
761 // file, but this is backwards from the token locations: the module_begin
762 // token is at the include location (outside the file) and the module_end
763 // token is at the EOF location (within the file).
764 Callbacks->BeginModule(
765 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
766 PP.Lex(Tok);
767 continue;
768 } else if (Tok.is(tok::annot_module_end)) {
769 Callbacks->EndModule(
770 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
771 PP.Lex(Tok);
772 continue;
Richard Smith8af8b862019-04-11 21:18:23 +0000773 } else if (Tok.is(tok::annot_header_unit)) {
774 // This is a header-name that has been (effectively) converted into a
775 // module-name.
776 // FIXME: The module name could contain non-identifier module name
777 // components. We don't have a good way to round-trip those.
778 Module *M = reinterpret_cast<Module *>(Tok.getAnnotationValue());
779 std::string Name = M->getFullModuleName();
780 OS.write(Name.data(), Name.size());
781 Callbacks->HandleNewlinesInToken(Name.data(), Name.size());
David Blaikie1013fe72018-11-15 03:04:21 +0000782 } else if (Tok.isAnnotation()) {
783 // Ignore annotation tokens created by pragmas - the pragmas themselves
784 // will be reproduced in the preprocessed output.
785 PP.Lex(Tok);
786 continue;
Jordan Rose67b66232013-03-05 23:54:55 +0000787 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
Benjamin Kramer718f7222010-02-27 18:02:51 +0000788 OS << II->getName();
789 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
790 Tok.getLiteralData()) {
791 OS.write(Tok.getLiteralData(), Tok.getLength());
Paul Robinson4bb85ac2018-01-03 20:29:49 +0000792 } else if (Tok.getLength() < llvm::array_lengthof(Buffer)) {
Benjamin Kramer718f7222010-02-27 18:02:51 +0000793 const char *TokPtr = Buffer;
794 unsigned Len = PP.getSpelling(Tok, TokPtr);
795 OS.write(TokPtr, Len);
Mike Stump11289f42009-09-09 15:08:12 +0000796
Benjamin Kramer718f7222010-02-27 18:02:51 +0000797 // Tokens that can contain embedded newlines need to adjust our current
798 // line number.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000799 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramer718f7222010-02-27 18:02:51 +0000800 Callbacks->HandleNewlinesInToken(TokPtr, Len);
801 } else {
802 std::string S = PP.getSpelling(Tok);
Richard Smith8af8b862019-04-11 21:18:23 +0000803 OS.write(S.data(), S.size());
Benjamin Kramer718f7222010-02-27 18:02:51 +0000804
805 // Tokens that can contain embedded newlines need to adjust our current
806 // line number.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000807 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Richard Smith8af8b862019-04-11 21:18:23 +0000808 Callbacks->HandleNewlinesInToken(S.data(), S.size());
Benjamin Kramer718f7222010-02-27 18:02:51 +0000809 }
Jordan Rose127f6ee2012-06-15 23:33:51 +0000810 Callbacks->setEmittedTokensOnThisLine();
Mike Stump11289f42009-09-09 15:08:12 +0000811
Chris Lattner3ff2e692007-10-10 20:45:16 +0000812 if (Tok.is(tok::eof)) break;
Mike Stump11289f42009-09-09 15:08:12 +0000813
Chris Lattner0384e6352010-04-14 03:57:19 +0000814 PrevPrevTok = PrevTok;
Chris Lattner3ff2e692007-10-10 20:45:16 +0000815 PrevTok = Tok;
816 PP.Lex(Tok);
817 }
Chris Lattnerfc001b02009-02-06 05:56:11 +0000818}
819
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000820typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
821static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
822 return LHS->first->getName().compare(RHS->first->getName());
823}
824
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000825static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
Daniel Dunbard839e772010-06-11 20:10:12 +0000826 // Ignore unknown pragmas.
Lubos Lunak576a0412014-05-01 12:54:03 +0000827 PP.IgnorePragmas();
Daniel Dunbard839e772010-06-11 20:10:12 +0000828
Eli Friedman26c672b2009-05-19 01:32:34 +0000829 // -dM mode just scans and ignores all tokens in the files, then dumps out
830 // the macro table at the end.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000831 PP.EnterMainSourceFile();
Eli Friedman26c672b2009-05-19 01:32:34 +0000832
833 Token Tok;
834 do PP.Lex(Tok);
835 while (Tok.isNot(tok::eof));
836
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000837 SmallVector<id_macro_pair, 128> MacrosByID;
838 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
839 I != E; ++I) {
Richard Smith20e883e2015-04-29 23:20:19 +0000840 auto *MD = I->second.getLatest();
841 if (MD && MD->isDefined())
842 MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000843 }
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000844 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedman26c672b2009-05-19 01:32:34 +0000845
846 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
847 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000848 // Ignore computed macros like __LINE__ and friends.
Eli Friedman26c672b2009-05-19 01:32:34 +0000849 if (MI.isBuiltinMacro()) continue;
850
851 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +0000852 *OS << '\n';
Eli Friedman26c672b2009-05-19 01:32:34 +0000853 }
854}
855
Chris Lattnerfc001b02009-02-06 05:56:11 +0000856/// DoPrintPreprocessedInput - This implements -E mode.
857///
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000858void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
Daniel Dunbar22bdabf2009-11-11 10:07:44 +0000859 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000860 // Show macros with no output is handled specially.
861 if (!Opts.ShowCPP) {
862 assert(Opts.ShowMacros && "Not yet implemented!");
863 DoPrintMacros(PP, OS);
864 return;
865 }
866
Chris Lattnerfc001b02009-02-06 05:56:11 +0000867 // Inform the preprocessor whether we want it to retain comments or not, due
868 // to -C or -CC.
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000869 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanfcb57d52009-05-19 01:02:07 +0000870
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000871 PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +0000872 PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
873 Opts.ShowIncludeDirectives, Opts.UseLineDirectives);
Samuel Antaoeab747b2015-06-15 23:44:27 +0000874
875 // Expand macros in pragmas with -fms-extensions. The assumption is that
876 // the majority of pragmas in such a file will be Microsoft pragmas.
Vassil Vassilev2b676cf2017-04-27 16:58:33 +0000877 // Remember the handlers we will add so that we can remove them later.
878 std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(
879 new UnknownPragmaHandler(
880 "#pragma", Callbacks,
881 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
882
883 std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(
884 "#pragma GCC", Callbacks,
Samuel Antaoeab747b2015-06-15 23:44:27 +0000885 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
Vassil Vassilev2b676cf2017-04-27 16:58:33 +0000886
887 std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(
888 "#pragma clang", Callbacks,
889 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
890
891 PP.AddPragmaHandler(MicrosoftExtHandler.get());
892 PP.AddPragmaHandler("GCC", GCCHandler.get());
893 PP.AddPragmaHandler("clang", ClangHandler.get());
Samuel Antaoeab747b2015-06-15 23:44:27 +0000894
895 // The tokens after pragma omp need to be expanded.
896 //
897 // OpenMP [2.1, Directive format]
898 // Preprocessing tokens following the #pragma omp are subject to macro
899 // replacement.
Vassil Vassilev2b676cf2017-04-27 16:58:33 +0000900 std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(
901 new UnknownPragmaHandler("#pragma omp", Callbacks,
902 /*RequireTokenExpansion=*/true));
903 PP.AddPragmaHandler("omp", OpenMPHandler.get());
Chris Lattnerfc001b02009-02-06 05:56:11 +0000904
Craig Topperb8a70532014-09-10 04:53:53 +0000905 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
Chris Lattnerfc001b02009-02-06 05:56:11 +0000906
Eli Friedman26c672b2009-05-19 01:32:34 +0000907 // After we have configured the preprocessor, enter the main file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000908 PP.EnterMainSourceFile();
Chris Lattnerfc001b02009-02-06 05:56:11 +0000909
Eli Friedman26c672b2009-05-19 01:32:34 +0000910 // Consume all of the tokens that come from the predefines buffer. Those
911 // should not be emitted into the output and are guaranteed to be at the
912 // start.
913 const SourceManager &SourceMgr = PP.getSourceManager();
914 Token Tok;
Douglas Gregor453b0122010-11-12 07:15:47 +0000915 do {
916 PP.Lex(Tok);
917 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
918 break;
919
920 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
921 if (PLoc.isInvalid())
922 break;
923
924 if (strcmp(PLoc.getFilename(), "<built-in>"))
925 break;
926 } while (true);
Chris Lattnerfc001b02009-02-06 05:56:11 +0000927
Eli Friedman26c672b2009-05-19 01:32:34 +0000928 // Read all the preprocessed tokens, printing them out to the stream.
929 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
930 *OS << '\n';
Vassil Vassilev2b676cf2017-04-27 16:58:33 +0000931
932 // Remove the handlers we just added to leave the preprocessor in a sane state
933 // so that it can be reused (for example by a clang::Parser instance).
934 PP.RemovePragmaHandler(MicrosoftExtHandler.get());
935 PP.RemovePragmaHandler("GCC", GCCHandler.get());
936 PP.RemovePragmaHandler("clang", ClangHandler.get());
937 PP.RemovePragmaHandler("omp", OpenMPHandler.get());
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000938}