blob: 7c1d9a568831c24589071edcac7c0aa0dc8b8ed3 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This code simply runs the preprocessor on the input file and prints out the
11// result. This is the traditional behavior of the -E option.
12//
13//===----------------------------------------------------------------------===//
14
Eli Friedmanb09f6e12009-05-19 04:14:29 +000015#include "clang/Frontend/Utils.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000016#include "clang/Basic/CharInfo.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000017#include "clang/Basic/Diagnostic.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Frontend/PreprocessorOutputOptions.h"
Chris Lattnerf73903a2009-02-06 06:45:26 +000020#include "clang/Lex/MacroInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/Lex/PPCallbacks.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Lex/Pragma.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000023#include "clang/Lex/Preprocessor.h"
Chris Lattnerd7038e12009-02-13 00:46:04 +000024#include "clang/Lex/TokenConcatenation.h"
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +000025#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "llvm/ADT/SmallString.h"
Chris Lattnerabfe0942010-06-26 17:11:39 +000027#include "llvm/ADT/StringRef.h"
Douglas Gregorc09ce122011-06-22 19:41:48 +000028#include "llvm/Support/ErrorHandling.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000029#include "llvm/Support/raw_ostream.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include <cstdio>
31using namespace clang;
32
Chris Lattnerd82df3a2009-04-12 01:56:53 +000033/// PrintMacroDefinition - Print a macro definition in a form that will be
34/// properly accepted back as a definition.
35static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
Chris Lattner5f9e2722011-07-23 10:55:15 +000036 Preprocessor &PP, raw_ostream &OS) {
Chris Lattnerd82df3a2009-04-12 01:56:53 +000037 OS << "#define " << II.getName();
Mike Stump1eb44332009-09-09 15:08:12 +000038
Chris Lattnerd82df3a2009-04-12 01:56:53 +000039 if (MI.isFunctionLike()) {
40 OS << '(';
Chris Lattner13d55582009-12-09 02:08:14 +000041 if (!MI.arg_empty()) {
Chris Lattnerd82df3a2009-04-12 01:56:53 +000042 MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
Chris Lattner13d55582009-12-09 02:08:14 +000043 for (; AI+1 != E; ++AI) {
44 OS << (*AI)->getName();
Chris Lattner807b93e2009-12-07 01:58:34 +000045 OS << ',';
Chris Lattner807b93e2009-12-07 01:58:34 +000046 }
Chris Lattner13d55582009-12-09 02:08:14 +000047
48 // Last argument.
49 if ((*AI)->getName() == "__VA_ARGS__")
50 OS << "...";
51 else
52 OS << (*AI)->getName();
Chris Lattnerd82df3a2009-04-12 01:56:53 +000053 }
Mike Stump1eb44332009-09-09 15:08:12 +000054
Chris Lattner807b93e2009-12-07 01:58:34 +000055 if (MI.isGNUVarargs())
56 OS << "..."; // #define foo(x...)
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +000057
Chris Lattnerd82df3a2009-04-12 01:56:53 +000058 OS << ')';
59 }
Mike Stump1eb44332009-09-09 15:08:12 +000060
Chris Lattnerd82df3a2009-04-12 01:56:53 +000061 // GCC always emits a space, even if the macro body is empty. However, do not
62 // want to emit two spaces if the first token has a leading space.
63 if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
64 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +000065
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +000066 SmallString<128> SpellingBuffer;
Chris Lattnerd82df3a2009-04-12 01:56:53 +000067 for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end();
68 I != E; ++I) {
69 if (I->hasLeadingSpace())
70 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +000071
Benjamin Kramerddeea562010-02-27 13:44:12 +000072 OS << PP.getSpelling(*I, SpellingBuffer);
Chris Lattnerd82df3a2009-04-12 01:56:53 +000073 }
74}
75
Reid Spencer5f016e22007-07-11 17:01:13 +000076//===----------------------------------------------------------------------===//
77// Preprocessed token printer
78//===----------------------------------------------------------------------===//
79
Reid Spencer5f016e22007-07-11 17:01:13 +000080namespace {
81class PrintPPOutputPPCallbacks : public PPCallbacks {
82 Preprocessor &PP;
Chris Lattnerdf721402010-04-13 00:06:42 +000083 SourceManager &SM;
Chris Lattnerd7038e12009-02-13 00:46:04 +000084 TokenConcatenation ConcatInfo;
Chris Lattnere96de3e2008-08-17 03:12:02 +000085public:
Chris Lattner5f9e2722011-07-23 10:55:15 +000086 raw_ostream &OS;
Chris Lattnere96de3e2008-08-17 03:12:02 +000087private:
Reid Spencer5f016e22007-07-11 17:01:13 +000088 unsigned CurLine;
Daniel Dunbarf7c16d92010-08-24 22:44:13 +000089
Reid Spencer5f016e22007-07-11 17:01:13 +000090 bool EmittedTokensOnThisLine;
Jordan Rose0cdd1fe2012-06-15 23:33:51 +000091 bool EmittedDirectiveOnThisLine;
Chris Lattner9d728512008-10-27 01:19:25 +000092 SrcMgr::CharacteristicKind FileType;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +000093 SmallString<512> CurFilename;
Daniel Dunbar737bdb42008-09-05 03:22:57 +000094 bool Initialized;
Eli Friedman12d3b1d2009-05-19 03:06:47 +000095 bool DisableLineMarkers;
96 bool DumpDefines;
Chris Lattnerf7449342009-12-07 01:42:56 +000097 bool UseLineDirective;
Daniel Dunbar2a9be3e2012-11-16 01:51:11 +000098 bool IsFirstFileEntered;
Reid Spencer5f016e22007-07-11 17:01:13 +000099public:
Chris Lattner5f9e2722011-07-23 10:55:15 +0000100 PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os,
Daniel Dunbareef63e02011-02-02 15:41:17 +0000101 bool lineMarkers, bool defines)
Chris Lattnerdf721402010-04-13 00:06:42 +0000102 : PP(pp), SM(PP.getSourceManager()),
103 ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
Daniel Dunbareef63e02011-02-02 15:41:17 +0000104 DumpDefines(defines) {
105 CurLine = 0;
Chris Lattnerd8e30832007-07-24 06:57:14 +0000106 CurFilename += "<uninit>";
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 EmittedTokensOnThisLine = false;
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000108 EmittedDirectiveOnThisLine = false;
Chris Lattner0b9e7362008-09-26 21:18:42 +0000109 FileType = SrcMgr::C_User;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000110 Initialized = false;
Daniel Dunbar2a9be3e2012-11-16 01:51:11 +0000111 IsFirstFileEntered = false;
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000112
Chris Lattnerf7449342009-12-07 01:42:56 +0000113 // If we're in microsoft mode, use normal #line instead of line markers.
David Blaikie4e4d0842012-03-11 07:00:24 +0000114 UseLineDirective = PP.getLangOpts().MicrosoftExt;
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 }
Mike Stump1eb44332009-09-09 15:08:12 +0000116
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000117 void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000118 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000120 void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
121 bool hasEmittedDirectiveOnThisLine() const {
122 return EmittedDirectiveOnThisLine;
123 }
124
125 bool startNewLineIfNeeded(bool ShouldUpdateCurrentLine = true);
Stephen Hines651f13c2014-04-23 16:59:28 -0700126
127 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
128 SrcMgr::CharacteristicKind FileType,
129 FileID PrevFID) override;
130 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
131 StringRef FileName, bool IsAngled,
132 CharSourceRange FilenameRange, const FileEntry *File,
133 StringRef SearchPath, StringRef RelativePath,
134 const Module *Imported) override;
135 void Ident(SourceLocation Loc, const std::string &str) override;
136 void PragmaMessage(SourceLocation Loc, StringRef Namespace,
137 PragmaMessageKind Kind, StringRef Str) override;
138 void PragmaDebug(SourceLocation Loc, StringRef DebugType) override;
139 void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override;
140 void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override;
141 void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700142 diag::Severity Map, StringRef Str) override;
Stephen Hines651f13c2014-04-23 16:59:28 -0700143 void PragmaWarning(SourceLocation Loc, StringRef WarningSpec,
144 ArrayRef<int> Ids) override;
145 void PragmaWarningPush(SourceLocation Loc, int Level) override;
146 void PragmaWarningPop(SourceLocation Loc) override;
Reid Spencer5f016e22007-07-11 17:01:13 +0000147
Chris Lattner5f180322007-12-09 21:11:08 +0000148 bool HandleFirstTokOnLine(Token &Tok);
Hal Finkel43bb45d2013-01-28 04:37:37 +0000149
150 /// Move to the line of the provided source location. This will
151 /// return true if the output stream required adjustment or if
152 /// the requested location is on the first line.
Chris Lattner88aae912010-04-13 00:01:41 +0000153 bool MoveToLine(SourceLocation Loc) {
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000154 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
155 if (PLoc.isInvalid())
156 return false;
Hal Finkel43bb45d2013-01-28 04:37:37 +0000157 return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
Chris Lattner88aae912010-04-13 00:01:41 +0000158 }
159 bool MoveToLine(unsigned LineNo);
160
Chris Lattner88773212010-04-14 03:57:19 +0000161 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
162 const Token &Tok) {
163 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
Chris Lattnerd7038e12009-02-13 00:46:04 +0000164 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700165 void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
166 unsigned ExtraLen=0);
Douglas Gregor80c60f72010-09-09 22:45:38 +0000167 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
Chris Lattner3ee211f2009-06-15 01:25:23 +0000168 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000170 /// MacroDefined - This hook is called whenever a macro definition is seen.
Stephen Hines651f13c2014-04-23 16:59:28 -0700171 void MacroDefined(const Token &MacroNameTok,
172 const MacroDirective *MD) override;
Mike Stump1eb44332009-09-09 15:08:12 +0000173
Benjamin Kramer2f054492010-08-07 22:27:00 +0000174 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
Stephen Hines651f13c2014-04-23 16:59:28 -0700175 void MacroUndefined(const Token &MacroNameTok,
176 const MacroDirective *MD) override;
Reid Spencer5f016e22007-07-11 17:01:13 +0000177};
Chris Lattner5db17c92008-04-08 04:16:20 +0000178} // end anonymous namespace
Reid Spencer5f016e22007-07-11 17:01:13 +0000179
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000180void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
181 const char *Extra,
182 unsigned ExtraLen) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000183 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000184
Chris Lattnerf7449342009-12-07 01:42:56 +0000185 // Emit #line directives or GNU line markers depending on what mode we're in.
186 if (UseLineDirective) {
187 OS << "#line" << ' ' << LineNo << ' ' << '"';
Eli Friedman3432b782013-08-29 01:42:42 +0000188 OS.write_escaped(CurFilename);
Chris Lattnerf7449342009-12-07 01:42:56 +0000189 OS << '"';
190 } else {
191 OS << '#' << ' ' << LineNo << ' ' << '"';
Eli Friedman3432b782013-08-29 01:42:42 +0000192 OS.write_escaped(CurFilename);
Chris Lattnerf7449342009-12-07 01:42:56 +0000193 OS << '"';
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000194
Steve Naroffd76fbda2009-12-06 01:02:14 +0000195 if (ExtraLen)
196 OS.write(Extra, ExtraLen);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000197
Steve Naroffd76fbda2009-12-06 01:02:14 +0000198 if (FileType == SrcMgr::C_System)
199 OS.write(" 3", 2);
200 else if (FileType == SrcMgr::C_ExternCSystem)
201 OS.write(" 3 4", 4);
202 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000203 OS << '\n';
204}
205
Reid Spencer5f016e22007-07-11 17:01:13 +0000206/// MoveToLine - Move the output to the source line specified by the location
207/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner5f180322007-12-09 21:11:08 +0000208/// #line directive. This returns false if already at the specified line, true
209/// if some newlines were emitted.
Chris Lattner88aae912010-04-13 00:01:41 +0000210bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000211 // If this line is "close enough" to the original line, just print newlines,
212 // otherwise print a #line directive.
Daniel Dunbarfd966842008-09-26 01:13:35 +0000213 if (LineNo-CurLine <= 8) {
Chris Lattner822f9402007-07-23 05:14:05 +0000214 if (LineNo-CurLine == 1)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000215 OS << '\n';
Chris Lattner5f180322007-12-09 21:11:08 +0000216 else if (LineNo == CurLine)
Chandler Carruth9f79a1f2011-07-14 16:14:52 +0000217 return false; // Spelling line moved, but expansion line didn't.
Chris Lattner822f9402007-07-23 05:14:05 +0000218 else {
219 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattnere96de3e2008-08-17 03:12:02 +0000220 OS.write(NewLines, LineNo-CurLine);
Chris Lattner822f9402007-07-23 05:14:05 +0000221 }
Chris Lattner6133aeb2010-06-12 16:20:56 +0000222 } else if (!DisableLineMarkers) {
223 // Emit a #line or line marker.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700224 WriteLineInfo(LineNo, nullptr, 0);
Chris Lattner6133aeb2010-06-12 16:20:56 +0000225 } else {
226 // Okay, we're in -P mode, which turns off line markers. However, we still
227 // need to emit a newline between tokens on different lines.
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000228 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000229 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000230
Mike Stump1eb44332009-09-09 15:08:12 +0000231 CurLine = LineNo;
Chris Lattner5f180322007-12-09 21:11:08 +0000232 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000233}
234
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000235bool
236PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
237 if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
Douglas Gregor80c60f72010-09-09 22:45:38 +0000238 OS << '\n';
239 EmittedTokensOnThisLine = false;
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000240 EmittedDirectiveOnThisLine = false;
241 if (ShouldUpdateCurrentLine)
242 ++CurLine;
Douglas Gregor80c60f72010-09-09 22:45:38 +0000243 return true;
244 }
245
246 return false;
247}
Reid Spencer5f016e22007-07-11 17:01:13 +0000248
249/// FileChanged - Whenever the preprocessor enters or exits a #include file
250/// it invokes this handler. Update our conception of the current source
251/// position.
252void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
253 FileChangeReason Reason,
Argyrios Kyrtzidisc892c5f2011-10-11 17:29:44 +0000254 SrcMgr::CharacteristicKind NewFileType,
255 FileID PrevFID) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 // Unless we are exiting a #include, make sure to skip ahead to the line the
257 // #include directive was at.
Chris Lattnerdf721402010-04-13 00:06:42 +0000258 SourceManager &SourceMgr = SM;
Chris Lattner88aae912010-04-13 00:01:41 +0000259
260 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000261 if (UserLoc.isInvalid())
262 return;
263
Chris Lattner86d0ef72010-04-14 04:28:50 +0000264 unsigned NewLine = UserLoc.getLine();
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000265
Reid Spencer5f016e22007-07-11 17:01:13 +0000266 if (Reason == PPCallbacks::EnterFile) {
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000267 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
Chris Lattner71d8bfb2009-01-30 18:44:17 +0000268 if (IncludeLoc.isValid())
269 MoveToLine(IncludeLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000270 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
Jordan Rose142b35e2013-04-17 19:09:18 +0000271 // GCC emits the # directive for this directive on the line AFTER the
272 // directive and emits a bunch of spaces that aren't needed. This is because
273 // otherwise we will emit a line marker for THIS line, which requires an
274 // extra blank line after the directive to avoid making all following lines
275 // off by one. We can do better by simply incrementing NewLine here.
276 NewLine += 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 }
Chris Lattner88aae912010-04-13 00:01:41 +0000278
279 CurLine = NewLine;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000280
Chris Lattnerd8e30832007-07-24 06:57:14 +0000281 CurFilename.clear();
Chris Lattner88aae912010-04-13 00:01:41 +0000282 CurFilename += UserLoc.getFilename();
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000283 FileType = NewFileType;
284
Eli Friedman086cc832013-01-09 03:16:42 +0000285 if (DisableLineMarkers) {
286 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
287 return;
288 }
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000289
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000290 if (!Initialized) {
291 WriteLineInfo(CurLine);
292 Initialized = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000294
Daniel Dunbar2a9be3e2012-11-16 01:51:11 +0000295 // Do not emit an enter marker for the main file (which we expect is the first
296 // entered file). This matches gcc, and improves compatibility with some tools
297 // which track the # line markers as a way to determine when the preprocessed
298 // output is in the context of the main file.
299 if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
300 IsFirstFileEntered = true;
301 return;
302 }
303
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 switch (Reason) {
305 case PPCallbacks::EnterFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000306 WriteLineInfo(CurLine, " 1", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000307 break;
308 case PPCallbacks::ExitFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000309 WriteLineInfo(CurLine, " 2", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000310 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000311 case PPCallbacks::SystemHeaderPragma:
312 case PPCallbacks::RenameFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000313 WriteLineInfo(CurLine);
314 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000315 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000316}
317
Argyrios Kyrtzidis15aa81a2013-04-10 01:53:46 +0000318void PrintPPOutputPPCallbacks::InclusionDirective(SourceLocation HashLoc,
319 const Token &IncludeTok,
320 StringRef FileName,
321 bool IsAngled,
322 CharSourceRange FilenameRange,
323 const FileEntry *File,
324 StringRef SearchPath,
325 StringRef RelativePath,
326 const Module *Imported) {
327 // When preprocessing, turn implicit imports into @imports.
328 // FIXME: This is a stop-gap until a more comprehensive "preprocessing with
329 // modules" solution is introduced.
330 if (Imported) {
331 startNewLineIfNeeded();
332 MoveToLine(HashLoc);
333 OS << "@import " << Imported->getFullModuleName() << ";"
334 << " /* clang -E: implicit import for \"" << File->getName() << "\" */";
Stephen Hines176edba2014-12-01 14:53:08 -0800335 // Since we want a newline after the @import, but not a #<line>, start a new
336 // line immediately.
Argyrios Kyrtzidis56f6e092013-04-29 17:26:22 +0000337 EmittedTokensOnThisLine = true;
Stephen Hines176edba2014-12-01 14:53:08 -0800338 startNewLineIfNeeded();
Argyrios Kyrtzidis15aa81a2013-04-10 01:53:46 +0000339 }
340}
341
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000342/// Ident - Handle #ident directives when read by the preprocessor.
Reid Spencer5f016e22007-07-11 17:01:13 +0000343///
344void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
345 MoveToLine(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Chris Lattnere96de3e2008-08-17 03:12:02 +0000347 OS.write("#ident ", strlen("#ident "));
348 OS.write(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000349 EmittedTokensOnThisLine = true;
350}
351
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000352/// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein2aa92672010-11-19 21:33:15 +0000353void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000354 const MacroDirective *MD) {
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +0000355 const MacroInfo *MI = MD->getMacroInfo();
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000356 // Only print out macro definitions in -dD mode.
357 if (!DumpDefines ||
358 // Ignore __FILE__ etc.
359 MI->isBuiltinMacro()) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000361 MoveToLine(MI->getDefinitionLoc());
Craig Silverstein2aa92672010-11-19 21:33:15 +0000362 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000363 setEmittedDirectiveOnThisLine();
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000364}
365
Craig Silverstein2aa92672010-11-19 21:33:15 +0000366void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000367 const MacroDirective *MD) {
Benjamin Kramer2f054492010-08-07 22:27:00 +0000368 // Only print out macro definitions in -dD mode.
369 if (!DumpDefines) return;
370
Craig Silverstein2aa92672010-11-19 21:33:15 +0000371 MoveToLine(MacroNameTok.getLocation());
372 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000373 setEmittedDirectiveOnThisLine();
Benjamin Kramer2f054492010-08-07 22:27:00 +0000374}
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000375
Aaron Ballmana7ff62f2013-06-04 02:07:14 +0000376static void outputPrintable(llvm::raw_ostream& OS,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000377 const std::string &Str) {
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000378 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
379 unsigned char Char = Str[i];
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000380 if (isPrintable(Char) && Char != '\\' && Char != '"')
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000381 OS << (char)Char;
382 else // Output anything hard as an octal escape.
383 OS << '\\'
384 << (char)('0'+ ((Char >> 6) & 7))
385 << (char)('0'+ ((Char >> 3) & 7))
386 << (char)('0'+ ((Char >> 0) & 7));
387 }
Aaron Ballmana7ff62f2013-06-04 02:07:14 +0000388}
389
Chris Lattnerabfe0942010-06-26 17:11:39 +0000390void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
Andy Gibbs076eea22013-04-17 16:16:16 +0000391 StringRef Namespace,
392 PragmaMessageKind Kind,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000393 StringRef Str) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000394 startNewLineIfNeeded();
Chris Lattnerabfe0942010-06-26 17:11:39 +0000395 MoveToLine(Loc);
Andy Gibbs076eea22013-04-17 16:16:16 +0000396 OS << "#pragma ";
397 if (!Namespace.empty())
398 OS << Namespace << ' ';
399 switch (Kind) {
400 case PMK_Message:
Andy Gibbsf5ae4dd2013-04-19 17:13:17 +0000401 OS << "message(\"";
Andy Gibbs076eea22013-04-17 16:16:16 +0000402 break;
403 case PMK_Warning:
Andy Gibbs688f2a12013-04-18 16:49:37 +0000404 OS << "warning \"";
Andy Gibbs076eea22013-04-17 16:16:16 +0000405 break;
406 case PMK_Error:
Andy Gibbs688f2a12013-04-18 16:49:37 +0000407 OS << "error \"";
Andy Gibbs076eea22013-04-17 16:16:16 +0000408 break;
409 }
Chris Lattnerabfe0942010-06-26 17:11:39 +0000410
Aaron Ballmana7ff62f2013-06-04 02:07:14 +0000411 outputPrintable(OS, Str);
Chris Lattnerabfe0942010-06-26 17:11:39 +0000412 OS << '"';
Andy Gibbsf5ae4dd2013-04-19 17:13:17 +0000413 if (Kind == PMK_Message)
414 OS << ')';
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000415 setEmittedDirectiveOnThisLine();
Chris Lattnerabfe0942010-06-26 17:11:39 +0000416}
417
Tareq A. Siraj85192c72013-04-16 18:41:26 +0000418void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
419 StringRef DebugType) {
420 startNewLineIfNeeded();
421 MoveToLine(Loc);
422
423 OS << "#pragma clang __debug ";
424 OS << DebugType;
425
426 setEmittedDirectiveOnThisLine();
427}
428
Douglas Gregorc09ce122011-06-22 19:41:48 +0000429void PrintPPOutputPPCallbacks::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000430PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000431 startNewLineIfNeeded();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000432 MoveToLine(Loc);
433 OS << "#pragma " << Namespace << " diagnostic push";
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000434 setEmittedDirectiveOnThisLine();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000435}
436
437void PrintPPOutputPPCallbacks::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000438PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000439 startNewLineIfNeeded();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000440 MoveToLine(Loc);
441 OS << "#pragma " << Namespace << " diagnostic pop";
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000442 setEmittedDirectiveOnThisLine();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000443}
444
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700445void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
446 StringRef Namespace,
447 diag::Severity Map,
448 StringRef Str) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000449 startNewLineIfNeeded();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000450 MoveToLine(Loc);
451 OS << "#pragma " << Namespace << " diagnostic ";
Benjamin Kramerd7a3e2c2012-02-07 22:29:24 +0000452 switch (Map) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700453 case diag::Severity::Remark:
Stephen Hines651f13c2014-04-23 16:59:28 -0700454 OS << "remark";
455 break;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700456 case diag::Severity::Warning:
Douglas Gregorc09ce122011-06-22 19:41:48 +0000457 OS << "warning";
458 break;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700459 case diag::Severity::Error:
Douglas Gregorc09ce122011-06-22 19:41:48 +0000460 OS << "error";
461 break;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700462 case diag::Severity::Ignored:
Douglas Gregorc09ce122011-06-22 19:41:48 +0000463 OS << "ignored";
464 break;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700465 case diag::Severity::Fatal:
Douglas Gregorc09ce122011-06-22 19:41:48 +0000466 OS << "fatal";
467 break;
468 }
469 OS << " \"" << Str << '"';
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000470 setEmittedDirectiveOnThisLine();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000471}
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000472
Reid Kleckner2ee042d2013-09-13 22:00:30 +0000473void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
474 StringRef WarningSpec,
475 ArrayRef<int> Ids) {
476 startNewLineIfNeeded();
477 MoveToLine(Loc);
478 OS << "#pragma warning(" << WarningSpec << ':';
479 for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
480 OS << ' ' << *I;
481 OS << ')';
482 setEmittedDirectiveOnThisLine();
483}
484
485void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
486 int Level) {
487 startNewLineIfNeeded();
488 MoveToLine(Loc);
489 OS << "#pragma warning(push";
Reid Kleckner72c26c02013-10-02 15:19:23 +0000490 if (Level >= 0)
Reid Kleckner2ee042d2013-09-13 22:00:30 +0000491 OS << ", " << Level;
492 OS << ')';
493 setEmittedDirectiveOnThisLine();
494}
495
496void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
497 startNewLineIfNeeded();
498 MoveToLine(Loc);
499 OS << "#pragma warning(pop)";
500 setEmittedDirectiveOnThisLine();
501}
502
Reid Spencer5f016e22007-07-11 17:01:13 +0000503/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner5f180322007-12-09 21:11:08 +0000504/// is called for the first token on each new line. If this really is the start
505/// of a new logical line, handle it and return true, otherwise return false.
506/// This may not be the start of a logical line because the "start of line"
Chandler Carruth9f79a1f2011-07-14 16:14:52 +0000507/// marker is set for spelling lines, not expansion ones.
Chris Lattner5f180322007-12-09 21:11:08 +0000508bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 // Figure out what line we went to and insert the appropriate number of
510 // newline characters.
Chris Lattner5f180322007-12-09 21:11:08 +0000511 if (!MoveToLine(Tok.getLocation()))
512 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Reid Spencer5f016e22007-07-11 17:01:13 +0000514 // Print out space characters so that the first token on a line is
515 // indented for easy reading.
Chandler Carrutha77c0312011-07-25 20:57:57 +0000516 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Stephen Hines651f13c2014-04-23 16:59:28 -0700518 // The first token on a line can have a column number of 1, yet still expect
519 // leading white space, if a macro expansion in column 1 starts with an empty
520 // macro argument, or an empty nested macro expansion. In this case, move the
521 // token to column 2.
522 if (ColNo == 1 && Tok.hasLeadingSpace())
523 ColNo = 2;
524
Reid Spencer5f016e22007-07-11 17:01:13 +0000525 // This hack prevents stuff like:
526 // #define HASH #
527 // HASH define foo bar
528 // From having the # character end up at column 1, which makes it so it
529 // is not handled as a #define next time through the preprocessor if in
530 // -fpreprocessed mode.
Chris Lattner057aaf62007-10-09 18:03:42 +0000531 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattnere96de3e2008-08-17 03:12:02 +0000532 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000533
Reid Spencer5f016e22007-07-11 17:01:13 +0000534 // Otherwise, indent the appropriate number of spaces.
535 for (; ColNo > 1; --ColNo)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000536 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Chris Lattner5f180322007-12-09 21:11:08 +0000538 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000539}
540
Chris Lattner3ee211f2009-06-15 01:25:23 +0000541void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
542 unsigned Len) {
543 unsigned NumNewlines = 0;
544 for (; Len; --Len, ++TokStr) {
545 if (*TokStr != '\n' &&
546 *TokStr != '\r')
547 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Chris Lattner3ee211f2009-06-15 01:25:23 +0000549 ++NumNewlines;
Mike Stump1eb44332009-09-09 15:08:12 +0000550
Chris Lattner3ee211f2009-06-15 01:25:23 +0000551 // If we have \n\r or \r\n, skip both and count as one line.
552 if (Len != 1 &&
553 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
554 TokStr[0] != TokStr[1])
555 ++TokStr, --Len;
556 }
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Chris Lattner3ee211f2009-06-15 01:25:23 +0000558 if (NumNewlines == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Chris Lattnered2d7c42009-06-15 04:08:28 +0000560 CurLine += NumNewlines;
Chris Lattner3ee211f2009-06-15 01:25:23 +0000561}
562
563
Reid Spencer5f016e22007-07-11 17:01:13 +0000564namespace {
565struct UnknownPragmaHandler : public PragmaHandler {
566 const char *Prefix;
567 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000570 : Prefix(prefix), Callbacks(callbacks) {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700571 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
572 Token &PragmaTok) override {
Reid Spencer5f016e22007-07-11 17:01:13 +0000573 // Figure out what line we went to and insert the appropriate number of
574 // newline characters.
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000575 Callbacks->startNewLineIfNeeded();
Reid Spencer5f016e22007-07-11 17:01:13 +0000576 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattnere96de3e2008-08-17 03:12:02 +0000577 Callbacks->OS.write(Prefix, strlen(Prefix));
Reid Spencer5f016e22007-07-11 17:01:13 +0000578 // Read and print all of the pragma tokens.
Peter Collingbourne84021552011-02-28 02:37:51 +0000579 while (PragmaTok.isNot(tok::eod)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000580 if (PragmaTok.hasLeadingSpace())
Chris Lattnere96de3e2008-08-17 03:12:02 +0000581 Callbacks->OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000583 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Stephen Hines651f13c2014-04-23 16:59:28 -0700584
585 // Expand macros in pragmas with -fms-extensions. The assumption is that
586 // the majority of pragmas in such a file will be Microsoft pragmas.
587 if (PP.getLangOpts().MicrosoftExt)
588 PP.Lex(PragmaTok);
589 else
590 PP.LexUnexpandedToken(PragmaTok);
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 }
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000592 Callbacks->setEmittedDirectiveOnThisLine();
Reid Spencer5f016e22007-07-11 17:01:13 +0000593 }
594};
595} // end anonymous namespace
596
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000597
Chris Lattner59076ab2009-02-06 05:56:11 +0000598static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
599 PrintPPOutputPPCallbacks *Callbacks,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000600 raw_ostream &OS) {
Jordan Rosecf2c2e92013-03-05 23:54:55 +0000601 bool DropComments = PP.getLangOpts().TraditionalCPP &&
602 !PP.getCommentRetentionState();
603
Benjamin Kramere3960072010-02-27 18:02:51 +0000604 char Buffer[256];
Chris Lattnerc54539c2010-06-15 21:06:38 +0000605 Token PrevPrevTok, PrevTok;
606 PrevPrevTok.startToken();
607 PrevTok.startToken();
Chris Lattner6f688e12007-10-10 20:45:16 +0000608 while (1) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000609 if (Callbacks->hasEmittedDirectiveOnThisLine()) {
610 Callbacks->startNewLineIfNeeded();
611 Callbacks->MoveToLine(Tok.getLocation());
612 }
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Reid Spencer5f016e22007-07-11 17:01:13 +0000614 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner5f180322007-12-09 21:11:08 +0000615 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
616 // done.
Mike Stump1eb44332009-09-09 15:08:12 +0000617 } else if (Tok.hasLeadingSpace() ||
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000618 // If we haven't emitted a token on this line yet, PrevTok isn't
619 // useful to look at and no concatenation could happen anyway.
Chris Lattnerb638a302007-07-23 23:21:34 +0000620 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000621 // Don't print "-" next to "-", it would form "--".
Chris Lattner88773212010-04-14 03:57:19 +0000622 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattnere96de3e2008-08-17 03:12:02 +0000623 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000624 }
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Jordan Rosecf2c2e92013-03-05 23:54:55 +0000626 if (DropComments && Tok.is(tok::comment)) {
627 // Skip comments. Normally the preprocessor does not generate
628 // tok::comment nodes at all when not keeping comments, but under
629 // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
630 SourceLocation StartLoc = Tok.getLocation();
631 Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
Stephen Hines651f13c2014-04-23 16:59:28 -0700632 } else if (Tok.is(tok::annot_module_include) ||
633 Tok.is(tok::annot_module_begin) ||
634 Tok.is(tok::annot_module_end)) {
Richard Smith26297f52013-11-15 04:24:58 +0000635 // PrintPPOutputPPCallbacks::InclusionDirective handles producing
636 // appropriate output here. Ignore this token entirely.
637 PP.Lex(Tok);
638 continue;
Jordan Rosecf2c2e92013-03-05 23:54:55 +0000639 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
Benjamin Kramere3960072010-02-27 18:02:51 +0000640 OS << II->getName();
641 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
642 Tok.getLiteralData()) {
643 OS.write(Tok.getLiteralData(), Tok.getLength());
644 } else if (Tok.getLength() < 256) {
645 const char *TokPtr = Buffer;
646 unsigned Len = PP.getSpelling(Tok, TokPtr);
647 OS.write(TokPtr, Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Benjamin Kramere3960072010-02-27 18:02:51 +0000649 // Tokens that can contain embedded newlines need to adjust our current
650 // line number.
Jordan Rose6aad4a32013-02-21 18:53:19 +0000651 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramere3960072010-02-27 18:02:51 +0000652 Callbacks->HandleNewlinesInToken(TokPtr, Len);
653 } else {
654 std::string S = PP.getSpelling(Tok);
655 OS.write(&S[0], S.size());
656
657 // Tokens that can contain embedded newlines need to adjust our current
658 // line number.
Jordan Rose6aad4a32013-02-21 18:53:19 +0000659 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramere3960072010-02-27 18:02:51 +0000660 Callbacks->HandleNewlinesInToken(&S[0], S.size());
661 }
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000662 Callbacks->setEmittedTokensOnThisLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000663
Chris Lattner6f688e12007-10-10 20:45:16 +0000664 if (Tok.is(tok::eof)) break;
Mike Stump1eb44332009-09-09 15:08:12 +0000665
Chris Lattner88773212010-04-14 03:57:19 +0000666 PrevPrevTok = PrevTok;
Chris Lattner6f688e12007-10-10 20:45:16 +0000667 PrevTok = Tok;
668 PP.Lex(Tok);
669 }
Chris Lattner59076ab2009-02-06 05:56:11 +0000670}
671
Dmitri Gribenkob3958472013-01-14 00:36:42 +0000672typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
Benjamin Kramer767b3d22013-09-22 14:10:29 +0000673static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000674 return LHS->first->getName().compare(RHS->first->getName());
Chris Lattner2a2bb182009-02-10 22:28:19 +0000675}
Chris Lattner59076ab2009-02-06 05:56:11 +0000676
Chris Lattner5f9e2722011-07-23 10:55:15 +0000677static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000678 // Ignore unknown pragmas.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700679 PP.IgnorePragmas();
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000680
Eli Friedmanf1db5852009-05-19 01:32:34 +0000681 // -dM mode just scans and ignores all tokens in the files, then dumps out
682 // the macro table at the end.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000683 PP.EnterMainSourceFile();
Eli Friedmanf1db5852009-05-19 01:32:34 +0000684
685 Token Tok;
686 do PP.Lex(Tok);
687 while (Tok.isNot(tok::eof));
688
Alexander Kornienko8a64bb52012-08-29 00:20:03 +0000689 SmallVector<id_macro_pair, 128> MacrosByID;
690 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
691 I != E; ++I) {
692 if (I->first->hasMacroDefinition())
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +0000693 MacrosByID.push_back(id_macro_pair(I->first, I->second->getMacroInfo()));
Alexander Kornienko8a64bb52012-08-29 00:20:03 +0000694 }
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000695 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedmanf1db5852009-05-19 01:32:34 +0000696
697 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
698 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000699 // Ignore computed macros like __LINE__ and friends.
Eli Friedmanf1db5852009-05-19 01:32:34 +0000700 if (MI.isBuiltinMacro()) continue;
701
702 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000703 *OS << '\n';
Eli Friedmanf1db5852009-05-19 01:32:34 +0000704 }
705}
706
Chris Lattner59076ab2009-02-06 05:56:11 +0000707/// DoPrintPreprocessedInput - This implements -E mode.
708///
Chris Lattner5f9e2722011-07-23 10:55:15 +0000709void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000710 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar775bee72009-11-11 10:07:22 +0000711 // Show macros with no output is handled specially.
712 if (!Opts.ShowCPP) {
713 assert(Opts.ShowMacros && "Not yet implemented!");
714 DoPrintMacros(PP, OS);
715 return;
716 }
717
Chris Lattner59076ab2009-02-06 05:56:11 +0000718 // Inform the preprocessor whether we want it to retain comments or not, due
719 // to -C or -CC.
Daniel Dunbar775bee72009-11-11 10:07:22 +0000720 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanf54fce82009-05-19 01:02:07 +0000721
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000722 PrintPPOutputPPCallbacks *Callbacks =
Daniel Dunbar775bee72009-11-11 10:07:22 +0000723 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
Daniel Dunbareef63e02011-02-02 15:41:17 +0000724 Opts.ShowMacros);
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000725 PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
Chris Lattner13973992010-11-10 01:00:49 +0000726 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
727 PP.AddPragmaHandler("clang",
728 new UnknownPragmaHandler("#pragma clang", Callbacks));
Chris Lattner59076ab2009-02-06 05:56:11 +0000729
Stephen Hines176edba2014-12-01 14:53:08 -0800730 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
Chris Lattner59076ab2009-02-06 05:56:11 +0000731
Eli Friedmanf1db5852009-05-19 01:32:34 +0000732 // After we have configured the preprocessor, enter the main file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000733 PP.EnterMainSourceFile();
Chris Lattner59076ab2009-02-06 05:56:11 +0000734
Eli Friedmanf1db5852009-05-19 01:32:34 +0000735 // Consume all of the tokens that come from the predefines buffer. Those
736 // should not be emitted into the output and are guaranteed to be at the
737 // start.
738 const SourceManager &SourceMgr = PP.getSourceManager();
739 Token Tok;
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000740 do {
741 PP.Lex(Tok);
742 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
743 break;
744
745 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
746 if (PLoc.isInvalid())
747 break;
748
749 if (strcmp(PLoc.getFilename(), "<built-in>"))
750 break;
751 } while (true);
Chris Lattner59076ab2009-02-06 05:56:11 +0000752
Eli Friedmanf1db5852009-05-19 01:32:34 +0000753 // Read all the preprocessed tokens, printing them out to the stream.
754 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
755 *OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000756}