blob: 9fd36494358052de85df235d0618f0f56287a430 [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);
Douglas Gregor80c60f72010-09-09 22:45:38 +0000126
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
Argyrios Kyrtzidisc892c5f2011-10-11 17:29:44 +0000128 SrcMgr::CharacteristicKind FileType,
129 FileID PrevFID);
Argyrios Kyrtzidis15aa81a2013-04-10 01:53:46 +0000130 virtual void InclusionDirective(SourceLocation HashLoc,
131 const Token &IncludeTok,
132 StringRef FileName,
133 bool IsAngled,
134 CharSourceRange FilenameRange,
135 const FileEntry *File,
136 StringRef SearchPath,
137 StringRef RelativePath,
138 const Module *Imported);
Reid Spencer5f016e22007-07-11 17:01:13 +0000139 virtual void Ident(SourceLocation Loc, const std::string &str);
Tareq A. Siraj6afcf882013-04-16 19:37:38 +0000140 virtual void PragmaCaptured(SourceLocation Loc, StringRef Str);
Mike Stump1eb44332009-09-09 15:08:12 +0000141 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000142 const std::string &Str);
Andy Gibbs076eea22013-04-17 16:16:16 +0000143 virtual void PragmaMessage(SourceLocation Loc, StringRef Namespace,
144 PragmaMessageKind Kind, StringRef Str);
Tareq A. Siraj85192c72013-04-16 18:41:26 +0000145 virtual void PragmaDebug(SourceLocation Loc, StringRef DebugType);
Douglas Gregorc09ce122011-06-22 19:41:48 +0000146 virtual void PragmaDiagnosticPush(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000147 StringRef Namespace);
Douglas Gregorc09ce122011-06-22 19:41:48 +0000148 virtual void PragmaDiagnosticPop(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000149 StringRef Namespace);
150 virtual void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
Benjamin Kramerd7a3e2c2012-02-07 22:29:24 +0000151 diag::Mapping Map, StringRef Str);
Reid Spencer5f016e22007-07-11 17:01:13 +0000152
Chris Lattner5f180322007-12-09 21:11:08 +0000153 bool HandleFirstTokOnLine(Token &Tok);
Hal Finkel43bb45d2013-01-28 04:37:37 +0000154
155 /// Move to the line of the provided source location. This will
156 /// return true if the output stream required adjustment or if
157 /// the requested location is on the first line.
Chris Lattner88aae912010-04-13 00:01:41 +0000158 bool MoveToLine(SourceLocation Loc) {
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000159 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
160 if (PLoc.isInvalid())
161 return false;
Hal Finkel43bb45d2013-01-28 04:37:37 +0000162 return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
Chris Lattner88aae912010-04-13 00:01:41 +0000163 }
164 bool MoveToLine(unsigned LineNo);
165
Chris Lattner88773212010-04-14 03:57:19 +0000166 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
167 const Token &Tok) {
168 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
Chris Lattnerd7038e12009-02-13 00:46:04 +0000169 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000170 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
Douglas Gregor80c60f72010-09-09 22:45:38 +0000171 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
Chris Lattner3ee211f2009-06-15 01:25:23 +0000172 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000173
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000174 /// MacroDefined - This hook is called whenever a macro definition is seen.
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000175 void MacroDefined(const Token &MacroNameTok, const MacroDirective *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Benjamin Kramer2f054492010-08-07 22:27:00 +0000177 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000178 void MacroUndefined(const Token &MacroNameTok, const MacroDirective *MD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000179};
Chris Lattner5db17c92008-04-08 04:16:20 +0000180} // end anonymous namespace
Reid Spencer5f016e22007-07-11 17:01:13 +0000181
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000182void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
183 const char *Extra,
184 unsigned ExtraLen) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000185 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000186
Chris Lattnerf7449342009-12-07 01:42:56 +0000187 // Emit #line directives or GNU line markers depending on what mode we're in.
188 if (UseLineDirective) {
189 OS << "#line" << ' ' << LineNo << ' ' << '"';
Ted Kremenek23465132010-09-17 00:41:18 +0000190 OS.write(CurFilename.data(), CurFilename.size());
Chris Lattnerf7449342009-12-07 01:42:56 +0000191 OS << '"';
192 } else {
193 OS << '#' << ' ' << LineNo << ' ' << '"';
Ted Kremenek23465132010-09-17 00:41:18 +0000194 OS.write(CurFilename.data(), CurFilename.size());
Chris Lattnerf7449342009-12-07 01:42:56 +0000195 OS << '"';
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000196
Steve Naroffd76fbda2009-12-06 01:02:14 +0000197 if (ExtraLen)
198 OS.write(Extra, ExtraLen);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000199
Steve Naroffd76fbda2009-12-06 01:02:14 +0000200 if (FileType == SrcMgr::C_System)
201 OS.write(" 3", 2);
202 else if (FileType == SrcMgr::C_ExternCSystem)
203 OS.write(" 3 4", 4);
204 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000205 OS << '\n';
206}
207
Reid Spencer5f016e22007-07-11 17:01:13 +0000208/// MoveToLine - Move the output to the source line specified by the location
209/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner5f180322007-12-09 21:11:08 +0000210/// #line directive. This returns false if already at the specified line, true
211/// if some newlines were emitted.
Chris Lattner88aae912010-04-13 00:01:41 +0000212bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 // If this line is "close enough" to the original line, just print newlines,
214 // otherwise print a #line directive.
Daniel Dunbarfd966842008-09-26 01:13:35 +0000215 if (LineNo-CurLine <= 8) {
Chris Lattner822f9402007-07-23 05:14:05 +0000216 if (LineNo-CurLine == 1)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000217 OS << '\n';
Chris Lattner5f180322007-12-09 21:11:08 +0000218 else if (LineNo == CurLine)
Chandler Carruth9f79a1f2011-07-14 16:14:52 +0000219 return false; // Spelling line moved, but expansion line didn't.
Chris Lattner822f9402007-07-23 05:14:05 +0000220 else {
221 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattnere96de3e2008-08-17 03:12:02 +0000222 OS.write(NewLines, LineNo-CurLine);
Chris Lattner822f9402007-07-23 05:14:05 +0000223 }
Chris Lattner6133aeb2010-06-12 16:20:56 +0000224 } else if (!DisableLineMarkers) {
225 // Emit a #line or line marker.
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000226 WriteLineInfo(LineNo, 0, 0);
Chris Lattner6133aeb2010-06-12 16:20:56 +0000227 } else {
228 // Okay, we're in -P mode, which turns off line markers. However, we still
229 // need to emit a newline between tokens on different lines.
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000230 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000231 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000232
Mike Stump1eb44332009-09-09 15:08:12 +0000233 CurLine = LineNo;
Chris Lattner5f180322007-12-09 21:11:08 +0000234 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000235}
236
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000237bool
238PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
239 if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
Douglas Gregor80c60f72010-09-09 22:45:38 +0000240 OS << '\n';
241 EmittedTokensOnThisLine = false;
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000242 EmittedDirectiveOnThisLine = false;
243 if (ShouldUpdateCurrentLine)
244 ++CurLine;
Douglas Gregor80c60f72010-09-09 22:45:38 +0000245 return true;
246 }
247
248 return false;
249}
Reid Spencer5f016e22007-07-11 17:01:13 +0000250
251/// FileChanged - Whenever the preprocessor enters or exits a #include file
252/// it invokes this handler. Update our conception of the current source
253/// position.
254void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
255 FileChangeReason Reason,
Argyrios Kyrtzidisc892c5f2011-10-11 17:29:44 +0000256 SrcMgr::CharacteristicKind NewFileType,
257 FileID PrevFID) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000258 // Unless we are exiting a #include, make sure to skip ahead to the line the
259 // #include directive was at.
Chris Lattnerdf721402010-04-13 00:06:42 +0000260 SourceManager &SourceMgr = SM;
Chris Lattner88aae912010-04-13 00:01:41 +0000261
262 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000263 if (UserLoc.isInvalid())
264 return;
265
Chris Lattner86d0ef72010-04-14 04:28:50 +0000266 unsigned NewLine = UserLoc.getLine();
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000267
Reid Spencer5f016e22007-07-11 17:01:13 +0000268 if (Reason == PPCallbacks::EnterFile) {
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000269 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
Chris Lattner71d8bfb2009-01-30 18:44:17 +0000270 if (IncludeLoc.isValid())
271 MoveToLine(IncludeLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
Jordan Rose142b35e2013-04-17 19:09:18 +0000273 // GCC emits the # directive for this directive on the line AFTER the
274 // directive and emits a bunch of spaces that aren't needed. This is because
275 // otherwise we will emit a line marker for THIS line, which requires an
276 // extra blank line after the directive to avoid making all following lines
277 // off by one. We can do better by simply incrementing NewLine here.
278 NewLine += 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 }
Chris Lattner88aae912010-04-13 00:01:41 +0000280
281 CurLine = NewLine;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000282
Chris Lattnerd8e30832007-07-24 06:57:14 +0000283 CurFilename.clear();
Chris Lattner88aae912010-04-13 00:01:41 +0000284 CurFilename += UserLoc.getFilename();
Chris Lattnerd8e30832007-07-24 06:57:14 +0000285 Lexer::Stringify(CurFilename);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000286 FileType = NewFileType;
287
Eli Friedman086cc832013-01-09 03:16:42 +0000288 if (DisableLineMarkers) {
289 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
290 return;
291 }
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000292
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000293 if (!Initialized) {
294 WriteLineInfo(CurLine);
295 Initialized = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000296 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000297
Daniel Dunbar2a9be3e2012-11-16 01:51:11 +0000298 // Do not emit an enter marker for the main file (which we expect is the first
299 // entered file). This matches gcc, and improves compatibility with some tools
300 // which track the # line markers as a way to determine when the preprocessed
301 // output is in the context of the main file.
302 if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
303 IsFirstFileEntered = true;
304 return;
305 }
306
Reid Spencer5f016e22007-07-11 17:01:13 +0000307 switch (Reason) {
308 case PPCallbacks::EnterFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000309 WriteLineInfo(CurLine, " 1", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000310 break;
311 case PPCallbacks::ExitFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000312 WriteLineInfo(CurLine, " 2", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000314 case PPCallbacks::SystemHeaderPragma:
315 case PPCallbacks::RenameFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000316 WriteLineInfo(CurLine);
317 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000318 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000319}
320
Argyrios Kyrtzidis15aa81a2013-04-10 01:53:46 +0000321void PrintPPOutputPPCallbacks::InclusionDirective(SourceLocation HashLoc,
322 const Token &IncludeTok,
323 StringRef FileName,
324 bool IsAngled,
325 CharSourceRange FilenameRange,
326 const FileEntry *File,
327 StringRef SearchPath,
328 StringRef RelativePath,
329 const Module *Imported) {
330 // When preprocessing, turn implicit imports into @imports.
331 // FIXME: This is a stop-gap until a more comprehensive "preprocessing with
332 // modules" solution is introduced.
333 if (Imported) {
334 startNewLineIfNeeded();
335 MoveToLine(HashLoc);
336 OS << "@import " << Imported->getFullModuleName() << ";"
337 << " /* clang -E: implicit import for \"" << File->getName() << "\" */";
Argyrios Kyrtzidis56f6e092013-04-29 17:26:22 +0000338 EmittedTokensOnThisLine = true;
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
Tareq A. Siraj6afcf882013-04-16 19:37:38 +0000352void PrintPPOutputPPCallbacks::PragmaCaptured(SourceLocation Loc,
353 StringRef Str) {
354 startNewLineIfNeeded();
355 MoveToLine(Loc);
356 OS << "#pragma captured";
357
358 setEmittedDirectiveOnThisLine();
359}
360
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000361/// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein2aa92672010-11-19 21:33:15 +0000362void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000363 const MacroDirective *MD) {
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +0000364 const MacroInfo *MI = MD->getMacroInfo();
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000365 // Only print out macro definitions in -dD mode.
366 if (!DumpDefines ||
367 // Ignore __FILE__ etc.
368 MI->isBuiltinMacro()) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000370 MoveToLine(MI->getDefinitionLoc());
Craig Silverstein2aa92672010-11-19 21:33:15 +0000371 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000372 setEmittedDirectiveOnThisLine();
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000373}
374
Craig Silverstein2aa92672010-11-19 21:33:15 +0000375void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000376 const MacroDirective *MD) {
Benjamin Kramer2f054492010-08-07 22:27:00 +0000377 // Only print out macro definitions in -dD mode.
378 if (!DumpDefines) return;
379
Craig Silverstein2aa92672010-11-19 21:33:15 +0000380 MoveToLine(MacroNameTok.getLocation());
381 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000382 setEmittedDirectiveOnThisLine();
Benjamin Kramer2f054492010-08-07 22:27:00 +0000383}
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000384
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000385void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000386 const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000387 const std::string &Str) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000388 startNewLineIfNeeded();
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000389 MoveToLine(Loc);
390 OS << "#pragma comment(" << Kind->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000392 if (!Str.empty()) {
393 OS << ", \"";
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000395 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
396 unsigned char Char = Str[i];
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000397 if (isPrintable(Char) && Char != '\\' && Char != '"')
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000398 OS << (char)Char;
399 else // Output anything hard as an octal escape.
400 OS << '\\'
401 << (char)('0'+ ((Char >> 6) & 7))
402 << (char)('0'+ ((Char >> 3) & 7))
403 << (char)('0'+ ((Char >> 0) & 7));
404 }
405 OS << '"';
406 }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000408 OS << ')';
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000409 setEmittedDirectiveOnThisLine();
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000410}
411
Chris Lattnerabfe0942010-06-26 17:11:39 +0000412void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
Andy Gibbs076eea22013-04-17 16:16:16 +0000413 StringRef Namespace,
414 PragmaMessageKind Kind,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000415 StringRef Str) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000416 startNewLineIfNeeded();
Chris Lattnerabfe0942010-06-26 17:11:39 +0000417 MoveToLine(Loc);
Andy Gibbs076eea22013-04-17 16:16:16 +0000418 OS << "#pragma ";
419 if (!Namespace.empty())
420 OS << Namespace << ' ';
421 switch (Kind) {
422 case PMK_Message:
Andy Gibbsf5ae4dd2013-04-19 17:13:17 +0000423 OS << "message(\"";
Andy Gibbs076eea22013-04-17 16:16:16 +0000424 break;
425 case PMK_Warning:
Andy Gibbs688f2a12013-04-18 16:49:37 +0000426 OS << "warning \"";
Andy Gibbs076eea22013-04-17 16:16:16 +0000427 break;
428 case PMK_Error:
Andy Gibbs688f2a12013-04-18 16:49:37 +0000429 OS << "error \"";
Andy Gibbs076eea22013-04-17 16:16:16 +0000430 break;
431 }
Chris Lattnerabfe0942010-06-26 17:11:39 +0000432
433 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
434 unsigned char Char = Str[i];
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000435 if (isPrintable(Char) && Char != '\\' && Char != '"')
Chris Lattnerabfe0942010-06-26 17:11:39 +0000436 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 }
443 OS << '"';
Andy Gibbsf5ae4dd2013-04-19 17:13:17 +0000444 if (Kind == PMK_Message)
445 OS << ')';
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000446 setEmittedDirectiveOnThisLine();
Chris Lattnerabfe0942010-06-26 17:11:39 +0000447}
448
Tareq A. Siraj85192c72013-04-16 18:41:26 +0000449void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
450 StringRef DebugType) {
451 startNewLineIfNeeded();
452 MoveToLine(Loc);
453
454 OS << "#pragma clang __debug ";
455 OS << DebugType;
456
457 setEmittedDirectiveOnThisLine();
458}
459
Douglas Gregorc09ce122011-06-22 19:41:48 +0000460void PrintPPOutputPPCallbacks::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000461PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000462 startNewLineIfNeeded();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000463 MoveToLine(Loc);
464 OS << "#pragma " << Namespace << " diagnostic push";
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000465 setEmittedDirectiveOnThisLine();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000466}
467
468void PrintPPOutputPPCallbacks::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000469PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000470 startNewLineIfNeeded();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000471 MoveToLine(Loc);
472 OS << "#pragma " << Namespace << " diagnostic pop";
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000473 setEmittedDirectiveOnThisLine();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000474}
475
476void PrintPPOutputPPCallbacks::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000477PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
Benjamin Kramerd7a3e2c2012-02-07 22:29:24 +0000478 diag::Mapping Map, StringRef Str) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000479 startNewLineIfNeeded();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000480 MoveToLine(Loc);
481 OS << "#pragma " << Namespace << " diagnostic ";
Benjamin Kramerd7a3e2c2012-02-07 22:29:24 +0000482 switch (Map) {
Douglas Gregorc09ce122011-06-22 19:41:48 +0000483 case diag::MAP_WARNING:
484 OS << "warning";
485 break;
486 case diag::MAP_ERROR:
487 OS << "error";
488 break;
489 case diag::MAP_IGNORE:
490 OS << "ignored";
491 break;
492 case diag::MAP_FATAL:
493 OS << "fatal";
494 break;
495 }
496 OS << " \"" << Str << '"';
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000497 setEmittedDirectiveOnThisLine();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000498}
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000499
Reid Spencer5f016e22007-07-11 17:01:13 +0000500/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner5f180322007-12-09 21:11:08 +0000501/// is called for the first token on each new line. If this really is the start
502/// of a new logical line, handle it and return true, otherwise return false.
503/// This may not be the start of a logical line because the "start of line"
Chandler Carruth9f79a1f2011-07-14 16:14:52 +0000504/// marker is set for spelling lines, not expansion ones.
Chris Lattner5f180322007-12-09 21:11:08 +0000505bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000506 // Figure out what line we went to and insert the appropriate number of
507 // newline characters.
Chris Lattner5f180322007-12-09 21:11:08 +0000508 if (!MoveToLine(Tok.getLocation()))
509 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Reid Spencer5f016e22007-07-11 17:01:13 +0000511 // Print out space characters so that the first token on a line is
512 // indented for easy reading.
Chandler Carrutha77c0312011-07-25 20:57:57 +0000513 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Reid Spencer5f016e22007-07-11 17:01:13 +0000515 // This hack prevents stuff like:
516 // #define HASH #
517 // HASH define foo bar
518 // From having the # character end up at column 1, which makes it so it
519 // is not handled as a #define next time through the preprocessor if in
520 // -fpreprocessed mode.
Chris Lattner057aaf62007-10-09 18:03:42 +0000521 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattnere96de3e2008-08-17 03:12:02 +0000522 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Reid Spencer5f016e22007-07-11 17:01:13 +0000524 // Otherwise, indent the appropriate number of spaces.
525 for (; ColNo > 1; --ColNo)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000526 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Chris Lattner5f180322007-12-09 21:11:08 +0000528 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000529}
530
Chris Lattner3ee211f2009-06-15 01:25:23 +0000531void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
532 unsigned Len) {
533 unsigned NumNewlines = 0;
534 for (; Len; --Len, ++TokStr) {
535 if (*TokStr != '\n' &&
536 *TokStr != '\r')
537 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Chris Lattner3ee211f2009-06-15 01:25:23 +0000539 ++NumNewlines;
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Chris Lattner3ee211f2009-06-15 01:25:23 +0000541 // If we have \n\r or \r\n, skip both and count as one line.
542 if (Len != 1 &&
543 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
544 TokStr[0] != TokStr[1])
545 ++TokStr, --Len;
546 }
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Chris Lattner3ee211f2009-06-15 01:25:23 +0000548 if (NumNewlines == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Chris Lattnered2d7c42009-06-15 04:08:28 +0000550 CurLine += NumNewlines;
Chris Lattner3ee211f2009-06-15 01:25:23 +0000551}
552
553
Reid Spencer5f016e22007-07-11 17:01:13 +0000554namespace {
555struct UnknownPragmaHandler : public PragmaHandler {
556 const char *Prefix;
557 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000560 : Prefix(prefix), Callbacks(callbacks) {}
Douglas Gregor80c60f72010-09-09 22:45:38 +0000561 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
562 Token &PragmaTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000563 // Figure out what line we went to and insert the appropriate number of
564 // newline characters.
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000565 Callbacks->startNewLineIfNeeded();
Reid Spencer5f016e22007-07-11 17:01:13 +0000566 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattnere96de3e2008-08-17 03:12:02 +0000567 Callbacks->OS.write(Prefix, strlen(Prefix));
Reid Spencer5f016e22007-07-11 17:01:13 +0000568 // Read and print all of the pragma tokens.
Peter Collingbourne84021552011-02-28 02:37:51 +0000569 while (PragmaTok.isNot(tok::eod)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000570 if (PragmaTok.hasLeadingSpace())
Chris Lattnere96de3e2008-08-17 03:12:02 +0000571 Callbacks->OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000573 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000574 PP.LexUnexpandedToken(PragmaTok);
575 }
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000576 Callbacks->setEmittedDirectiveOnThisLine();
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 }
578};
579} // end anonymous namespace
580
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000581
Chris Lattner59076ab2009-02-06 05:56:11 +0000582static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
583 PrintPPOutputPPCallbacks *Callbacks,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000584 raw_ostream &OS) {
Jordan Rosecf2c2e92013-03-05 23:54:55 +0000585 bool DropComments = PP.getLangOpts().TraditionalCPP &&
586 !PP.getCommentRetentionState();
587
Benjamin Kramere3960072010-02-27 18:02:51 +0000588 char Buffer[256];
Chris Lattnerc54539c2010-06-15 21:06:38 +0000589 Token PrevPrevTok, PrevTok;
590 PrevPrevTok.startToken();
591 PrevTok.startToken();
Chris Lattner6f688e12007-10-10 20:45:16 +0000592 while (1) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000593 if (Callbacks->hasEmittedDirectiveOnThisLine()) {
594 Callbacks->startNewLineIfNeeded();
595 Callbacks->MoveToLine(Tok.getLocation());
596 }
Mike Stump1eb44332009-09-09 15:08:12 +0000597
Reid Spencer5f016e22007-07-11 17:01:13 +0000598 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner5f180322007-12-09 21:11:08 +0000599 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
600 // done.
Mike Stump1eb44332009-09-09 15:08:12 +0000601 } else if (Tok.hasLeadingSpace() ||
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000602 // If we haven't emitted a token on this line yet, PrevTok isn't
603 // useful to look at and no concatenation could happen anyway.
Chris Lattnerb638a302007-07-23 23:21:34 +0000604 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000605 // Don't print "-" next to "-", it would form "--".
Chris Lattner88773212010-04-14 03:57:19 +0000606 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattnere96de3e2008-08-17 03:12:02 +0000607 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000608 }
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Jordan Rosecf2c2e92013-03-05 23:54:55 +0000610 if (DropComments && Tok.is(tok::comment)) {
611 // Skip comments. Normally the preprocessor does not generate
612 // tok::comment nodes at all when not keeping comments, but under
613 // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
614 SourceLocation StartLoc = Tok.getLocation();
615 Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
616 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
Benjamin Kramere3960072010-02-27 18:02:51 +0000617 OS << II->getName();
618 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
619 Tok.getLiteralData()) {
620 OS.write(Tok.getLiteralData(), Tok.getLength());
621 } else if (Tok.getLength() < 256) {
622 const char *TokPtr = Buffer;
623 unsigned Len = PP.getSpelling(Tok, TokPtr);
624 OS.write(TokPtr, Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Benjamin Kramere3960072010-02-27 18:02:51 +0000626 // Tokens that can contain embedded newlines need to adjust our current
627 // line number.
Jordan Rose6aad4a32013-02-21 18:53:19 +0000628 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramere3960072010-02-27 18:02:51 +0000629 Callbacks->HandleNewlinesInToken(TokPtr, Len);
630 } else {
631 std::string S = PP.getSpelling(Tok);
632 OS.write(&S[0], S.size());
633
634 // Tokens that can contain embedded newlines need to adjust our current
635 // line number.
Jordan Rose6aad4a32013-02-21 18:53:19 +0000636 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
Benjamin Kramere3960072010-02-27 18:02:51 +0000637 Callbacks->HandleNewlinesInToken(&S[0], S.size());
638 }
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000639 Callbacks->setEmittedTokensOnThisLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Chris Lattner6f688e12007-10-10 20:45:16 +0000641 if (Tok.is(tok::eof)) break;
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Chris Lattner88773212010-04-14 03:57:19 +0000643 PrevPrevTok = PrevTok;
Chris Lattner6f688e12007-10-10 20:45:16 +0000644 PrevTok = Tok;
645 PP.Lex(Tok);
646 }
Chris Lattner59076ab2009-02-06 05:56:11 +0000647}
648
Dmitri Gribenkob3958472013-01-14 00:36:42 +0000649typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000650static int MacroIDCompare(const void* a, const void* b) {
651 const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
652 const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
653 return LHS->first->getName().compare(RHS->first->getName());
Chris Lattner2a2bb182009-02-10 22:28:19 +0000654}
Chris Lattner59076ab2009-02-06 05:56:11 +0000655
Chris Lattner5f9e2722011-07-23 10:55:15 +0000656static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000657 // Ignore unknown pragmas.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000658 PP.AddPragmaHandler(new EmptyPragmaHandler());
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000659
Eli Friedmanf1db5852009-05-19 01:32:34 +0000660 // -dM mode just scans and ignores all tokens in the files, then dumps out
661 // the macro table at the end.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000662 PP.EnterMainSourceFile();
Eli Friedmanf1db5852009-05-19 01:32:34 +0000663
664 Token Tok;
665 do PP.Lex(Tok);
666 while (Tok.isNot(tok::eof));
667
Alexander Kornienko8a64bb52012-08-29 00:20:03 +0000668 SmallVector<id_macro_pair, 128> MacrosByID;
669 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
670 I != E; ++I) {
671 if (I->first->hasMacroDefinition())
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +0000672 MacrosByID.push_back(id_macro_pair(I->first, I->second->getMacroInfo()));
Alexander Kornienko8a64bb52012-08-29 00:20:03 +0000673 }
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000674 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedmanf1db5852009-05-19 01:32:34 +0000675
676 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
677 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000678 // Ignore computed macros like __LINE__ and friends.
Eli Friedmanf1db5852009-05-19 01:32:34 +0000679 if (MI.isBuiltinMacro()) continue;
680
681 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000682 *OS << '\n';
Eli Friedmanf1db5852009-05-19 01:32:34 +0000683 }
684}
685
Chris Lattner59076ab2009-02-06 05:56:11 +0000686/// DoPrintPreprocessedInput - This implements -E mode.
687///
Chris Lattner5f9e2722011-07-23 10:55:15 +0000688void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000689 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar775bee72009-11-11 10:07:22 +0000690 // Show macros with no output is handled specially.
691 if (!Opts.ShowCPP) {
692 assert(Opts.ShowMacros && "Not yet implemented!");
693 DoPrintMacros(PP, OS);
694 return;
695 }
696
Chris Lattner59076ab2009-02-06 05:56:11 +0000697 // Inform the preprocessor whether we want it to retain comments or not, due
698 // to -C or -CC.
Daniel Dunbar775bee72009-11-11 10:07:22 +0000699 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanf54fce82009-05-19 01:02:07 +0000700
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000701 PrintPPOutputPPCallbacks *Callbacks =
Daniel Dunbar775bee72009-11-11 10:07:22 +0000702 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
Daniel Dunbareef63e02011-02-02 15:41:17 +0000703 Opts.ShowMacros);
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000704 PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
Chris Lattner13973992010-11-10 01:00:49 +0000705 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
706 PP.AddPragmaHandler("clang",
707 new UnknownPragmaHandler("#pragma clang", Callbacks));
Chris Lattner59076ab2009-02-06 05:56:11 +0000708
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000709 PP.addPPCallbacks(Callbacks);
Chris Lattner59076ab2009-02-06 05:56:11 +0000710
Eli Friedmanf1db5852009-05-19 01:32:34 +0000711 // After we have configured the preprocessor, enter the main file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000712 PP.EnterMainSourceFile();
Chris Lattner59076ab2009-02-06 05:56:11 +0000713
Eli Friedmanf1db5852009-05-19 01:32:34 +0000714 // Consume all of the tokens that come from the predefines buffer. Those
715 // should not be emitted into the output and are guaranteed to be at the
716 // start.
717 const SourceManager &SourceMgr = PP.getSourceManager();
718 Token Tok;
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000719 do {
720 PP.Lex(Tok);
721 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
722 break;
723
724 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
725 if (PLoc.isInvalid())
726 break;
727
728 if (strcmp(PLoc.getFilename(), "<built-in>"))
729 break;
730 } while (true);
Chris Lattner59076ab2009-02-06 05:56:11 +0000731
Eli Friedmanf1db5852009-05-19 01:32:34 +0000732 // Read all the preprocessed tokens, printing them out to the stream.
733 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
734 *OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000735}