blob: 7e0bc6bb2d043dbbbc7a65f710e574a5cd8bc982 [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"
Daniel Dunbar775bee72009-11-11 10:07:22 +000016#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/SourceManager.h"
18#include "clang/Frontend/PreprocessorOutputOptions.h"
Chris Lattnerf73903a2009-02-06 06:45:26 +000019#include "clang/Lex/MacroInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Lex/PPCallbacks.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/Lex/Pragma.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000022#include "clang/Lex/Preprocessor.h"
Chris Lattnerd7038e12009-02-13 00:46:04 +000023#include "clang/Lex/TokenConcatenation.h"
Chris Lattnerd8e30832007-07-24 06:57:14 +000024#include "llvm/ADT/SmallString.h"
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +000025#include "llvm/ADT/STLExtras.h"
Chris Lattnerabfe0942010-06-26 17:11:39 +000026#include "llvm/ADT/StringRef.h"
Chris Lattnerdceb6a72008-08-17 01:47:12 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregorc09ce122011-06-22 19:41:48 +000028#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include <cstdio>
30using namespace clang;
31
Chris Lattnerd82df3a2009-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 Lattner5f9e2722011-07-23 10:55:15 +000035 Preprocessor &PP, raw_ostream &OS) {
Chris Lattnerd82df3a2009-04-12 01:56:53 +000036 OS << "#define " << II.getName();
Mike Stump1eb44332009-09-09 15:08:12 +000037
Chris Lattnerd82df3a2009-04-12 01:56:53 +000038 if (MI.isFunctionLike()) {
39 OS << '(';
Chris Lattner13d55582009-12-09 02:08:14 +000040 if (!MI.arg_empty()) {
Chris Lattnerd82df3a2009-04-12 01:56:53 +000041 MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
Chris Lattner13d55582009-12-09 02:08:14 +000042 for (; AI+1 != E; ++AI) {
43 OS << (*AI)->getName();
Chris Lattner807b93e2009-12-07 01:58:34 +000044 OS << ',';
Chris Lattner807b93e2009-12-07 01:58:34 +000045 }
Chris Lattner13d55582009-12-09 02:08:14 +000046
47 // Last argument.
48 if ((*AI)->getName() == "__VA_ARGS__")
49 OS << "...";
50 else
51 OS << (*AI)->getName();
Chris Lattnerd82df3a2009-04-12 01:56:53 +000052 }
Mike Stump1eb44332009-09-09 15:08:12 +000053
Chris Lattner807b93e2009-12-07 01:58:34 +000054 if (MI.isGNUVarargs())
55 OS << "..."; // #define foo(x...)
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +000056
Chris Lattnerd82df3a2009-04-12 01:56:53 +000057 OS << ')';
58 }
Mike Stump1eb44332009-09-09 15:08:12 +000059
Chris Lattnerd82df3a2009-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 Stump1eb44332009-09-09 15:08:12 +000064
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +000065 SmallString<128> SpellingBuffer;
Chris Lattnerd82df3a2009-04-12 01:56:53 +000066 for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end();
67 I != E; ++I) {
68 if (I->hasLeadingSpace())
69 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +000070
Benjamin Kramerddeea562010-02-27 13:44:12 +000071 OS << PP.getSpelling(*I, SpellingBuffer);
Chris Lattnerd82df3a2009-04-12 01:56:53 +000072 }
73}
74
Reid Spencer5f016e22007-07-11 17:01:13 +000075//===----------------------------------------------------------------------===//
76// Preprocessed token printer
77//===----------------------------------------------------------------------===//
78
Reid Spencer5f016e22007-07-11 17:01:13 +000079namespace {
80class PrintPPOutputPPCallbacks : public PPCallbacks {
81 Preprocessor &PP;
Chris Lattnerdf721402010-04-13 00:06:42 +000082 SourceManager &SM;
Chris Lattnerd7038e12009-02-13 00:46:04 +000083 TokenConcatenation ConcatInfo;
Chris Lattnere96de3e2008-08-17 03:12:02 +000084public:
Chris Lattner5f9e2722011-07-23 10:55:15 +000085 raw_ostream &OS;
Chris Lattnere96de3e2008-08-17 03:12:02 +000086private:
Reid Spencer5f016e22007-07-11 17:01:13 +000087 unsigned CurLine;
Daniel Dunbarf7c16d92010-08-24 22:44:13 +000088
Reid Spencer5f016e22007-07-11 17:01:13 +000089 bool EmittedTokensOnThisLine;
Jordan Rose0cdd1fe2012-06-15 23:33:51 +000090 bool EmittedDirectiveOnThisLine;
Chris Lattner9d728512008-10-27 01:19:25 +000091 SrcMgr::CharacteristicKind FileType;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +000092 SmallString<512> CurFilename;
Daniel Dunbar737bdb42008-09-05 03:22:57 +000093 bool Initialized;
Eli Friedman12d3b1d2009-05-19 03:06:47 +000094 bool DisableLineMarkers;
95 bool DumpDefines;
Chris Lattnerf7449342009-12-07 01:42:56 +000096 bool UseLineDirective;
Reid Spencer5f016e22007-07-11 17:01:13 +000097public:
Chris Lattner5f9e2722011-07-23 10:55:15 +000098 PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os,
Daniel Dunbareef63e02011-02-02 15:41:17 +000099 bool lineMarkers, bool defines)
Chris Lattnerdf721402010-04-13 00:06:42 +0000100 : PP(pp), SM(PP.getSourceManager()),
101 ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
Daniel Dunbareef63e02011-02-02 15:41:17 +0000102 DumpDefines(defines) {
103 CurLine = 0;
Chris Lattnerd8e30832007-07-24 06:57:14 +0000104 CurFilename += "<uninit>";
Reid Spencer5f016e22007-07-11 17:01:13 +0000105 EmittedTokensOnThisLine = false;
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000106 EmittedDirectiveOnThisLine = false;
Chris Lattner0b9e7362008-09-26 21:18:42 +0000107 FileType = SrcMgr::C_User;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000108 Initialized = false;
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000109
Chris Lattnerf7449342009-12-07 01:42:56 +0000110 // If we're in microsoft mode, use normal #line instead of line markers.
David Blaikie4e4d0842012-03-11 07:00:24 +0000111 UseLineDirective = PP.getLangOpts().MicrosoftExt;
Reid Spencer5f016e22007-07-11 17:01:13 +0000112 }
Mike Stump1eb44332009-09-09 15:08:12 +0000113
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000114 void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000115 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Mike Stump1eb44332009-09-09 15:08:12 +0000116
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000117 void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
118 bool hasEmittedDirectiveOnThisLine() const {
119 return EmittedDirectiveOnThisLine;
120 }
121
122 bool startNewLineIfNeeded(bool ShouldUpdateCurrentLine = true);
Douglas Gregor80c60f72010-09-09 22:45:38 +0000123
Reid Spencer5f016e22007-07-11 17:01:13 +0000124 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
Argyrios Kyrtzidisc892c5f2011-10-11 17:29:44 +0000125 SrcMgr::CharacteristicKind FileType,
126 FileID PrevFID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 virtual void Ident(SourceLocation Loc, const std::string &str);
Mike Stump1eb44332009-09-09 15:08:12 +0000128 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000129 const std::string &Str);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000130 virtual void PragmaMessage(SourceLocation Loc, StringRef Str);
Douglas Gregorc09ce122011-06-22 19:41:48 +0000131 virtual void PragmaDiagnosticPush(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000132 StringRef Namespace);
Douglas Gregorc09ce122011-06-22 19:41:48 +0000133 virtual void PragmaDiagnosticPop(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000134 StringRef Namespace);
135 virtual void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
Benjamin Kramerd7a3e2c2012-02-07 22:29:24 +0000136 diag::Mapping Map, StringRef Str);
Reid Spencer5f016e22007-07-11 17:01:13 +0000137
Chris Lattner5f180322007-12-09 21:11:08 +0000138 bool HandleFirstTokOnLine(Token &Tok);
Chris Lattner88aae912010-04-13 00:01:41 +0000139 bool MoveToLine(SourceLocation Loc) {
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000140 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
141 if (PLoc.isInvalid())
142 return false;
143 return MoveToLine(PLoc.getLine());
Chris Lattner88aae912010-04-13 00:01:41 +0000144 }
145 bool MoveToLine(unsigned LineNo);
146
Chris Lattner88773212010-04-14 03:57:19 +0000147 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
148 const Token &Tok) {
149 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
Chris Lattnerd7038e12009-02-13 00:46:04 +0000150 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000151 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
Douglas Gregor80c60f72010-09-09 22:45:38 +0000152 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
Chris Lattner3ee211f2009-06-15 01:25:23 +0000153 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000155 /// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein2aa92672010-11-19 21:33:15 +0000156 void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Benjamin Kramer2f054492010-08-07 22:27:00 +0000158 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
Craig Silverstein2aa92672010-11-19 21:33:15 +0000159 void MacroUndefined(const Token &MacroNameTok, const MacroInfo *MI);
Reid Spencer5f016e22007-07-11 17:01:13 +0000160};
Chris Lattner5db17c92008-04-08 04:16:20 +0000161} // end anonymous namespace
Reid Spencer5f016e22007-07-11 17:01:13 +0000162
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000163void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
164 const char *Extra,
165 unsigned ExtraLen) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000166 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000167
Chris Lattnerf7449342009-12-07 01:42:56 +0000168 // Emit #line directives or GNU line markers depending on what mode we're in.
169 if (UseLineDirective) {
170 OS << "#line" << ' ' << LineNo << ' ' << '"';
Ted Kremenek23465132010-09-17 00:41:18 +0000171 OS.write(CurFilename.data(), CurFilename.size());
Chris Lattnerf7449342009-12-07 01:42:56 +0000172 OS << '"';
173 } else {
174 OS << '#' << ' ' << LineNo << ' ' << '"';
Ted Kremenek23465132010-09-17 00:41:18 +0000175 OS.write(CurFilename.data(), CurFilename.size());
Chris Lattnerf7449342009-12-07 01:42:56 +0000176 OS << '"';
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000177
Steve Naroffd76fbda2009-12-06 01:02:14 +0000178 if (ExtraLen)
179 OS.write(Extra, ExtraLen);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000180
Steve Naroffd76fbda2009-12-06 01:02:14 +0000181 if (FileType == SrcMgr::C_System)
182 OS.write(" 3", 2);
183 else if (FileType == SrcMgr::C_ExternCSystem)
184 OS.write(" 3 4", 4);
185 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000186 OS << '\n';
187}
188
Reid Spencer5f016e22007-07-11 17:01:13 +0000189/// MoveToLine - Move the output to the source line specified by the location
190/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner5f180322007-12-09 21:11:08 +0000191/// #line directive. This returns false if already at the specified line, true
192/// if some newlines were emitted.
Chris Lattner88aae912010-04-13 00:01:41 +0000193bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000194 // If this line is "close enough" to the original line, just print newlines,
195 // otherwise print a #line directive.
Daniel Dunbarfd966842008-09-26 01:13:35 +0000196 if (LineNo-CurLine <= 8) {
Chris Lattner822f9402007-07-23 05:14:05 +0000197 if (LineNo-CurLine == 1)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000198 OS << '\n';
Chris Lattner5f180322007-12-09 21:11:08 +0000199 else if (LineNo == CurLine)
Chandler Carruth9f79a1f2011-07-14 16:14:52 +0000200 return false; // Spelling line moved, but expansion line didn't.
Chris Lattner822f9402007-07-23 05:14:05 +0000201 else {
202 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattnere96de3e2008-08-17 03:12:02 +0000203 OS.write(NewLines, LineNo-CurLine);
Chris Lattner822f9402007-07-23 05:14:05 +0000204 }
Chris Lattner6133aeb2010-06-12 16:20:56 +0000205 } else if (!DisableLineMarkers) {
206 // Emit a #line or line marker.
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000207 WriteLineInfo(LineNo, 0, 0);
Chris Lattner6133aeb2010-06-12 16:20:56 +0000208 } else {
209 // Okay, we're in -P mode, which turns off line markers. However, we still
210 // need to emit a newline between tokens on different lines.
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000211 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000212 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000213
Mike Stump1eb44332009-09-09 15:08:12 +0000214 CurLine = LineNo;
Chris Lattner5f180322007-12-09 21:11:08 +0000215 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000216}
217
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000218bool
219PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
220 if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
Douglas Gregor80c60f72010-09-09 22:45:38 +0000221 OS << '\n';
222 EmittedTokensOnThisLine = false;
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000223 EmittedDirectiveOnThisLine = false;
224 if (ShouldUpdateCurrentLine)
225 ++CurLine;
Douglas Gregor80c60f72010-09-09 22:45:38 +0000226 return true;
227 }
228
229 return false;
230}
Reid Spencer5f016e22007-07-11 17:01:13 +0000231
232/// FileChanged - Whenever the preprocessor enters or exits a #include file
233/// it invokes this handler. Update our conception of the current source
234/// position.
235void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
236 FileChangeReason Reason,
Argyrios Kyrtzidisc892c5f2011-10-11 17:29:44 +0000237 SrcMgr::CharacteristicKind NewFileType,
238 FileID PrevFID) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000239 // Unless we are exiting a #include, make sure to skip ahead to the line the
240 // #include directive was at.
Chris Lattnerdf721402010-04-13 00:06:42 +0000241 SourceManager &SourceMgr = SM;
Chris Lattner88aae912010-04-13 00:01:41 +0000242
243 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000244 if (UserLoc.isInvalid())
245 return;
246
Chris Lattner86d0ef72010-04-14 04:28:50 +0000247 unsigned NewLine = UserLoc.getLine();
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000248
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 if (Reason == PPCallbacks::EnterFile) {
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000250 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
Chris Lattner71d8bfb2009-01-30 18:44:17 +0000251 if (IncludeLoc.isValid())
252 MoveToLine(IncludeLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000253 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
Chris Lattner88aae912010-04-13 00:01:41 +0000254 MoveToLine(NewLine);
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 // TODO GCC emits the # directive for this directive on the line AFTER the
257 // directive and emits a bunch of spaces that aren't needed. Emulate this
258 // strange behavior.
259 }
Chris Lattner88aae912010-04-13 00:01:41 +0000260
261 CurLine = NewLine;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000262
Chris Lattnerd8e30832007-07-24 06:57:14 +0000263 CurFilename.clear();
Chris Lattner88aae912010-04-13 00:01:41 +0000264 CurFilename += UserLoc.getFilename();
Chris Lattnerd8e30832007-07-24 06:57:14 +0000265 Lexer::Stringify(CurFilename);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000266 FileType = NewFileType;
267
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000268 if (DisableLineMarkers) return;
269
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000270 if (!Initialized) {
271 WriteLineInfo(CurLine);
272 Initialized = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000273 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000274
Reid Spencer5f016e22007-07-11 17:01:13 +0000275 switch (Reason) {
276 case PPCallbacks::EnterFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000277 WriteLineInfo(CurLine, " 1", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000278 break;
279 case PPCallbacks::ExitFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000280 WriteLineInfo(CurLine, " 2", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000282 case PPCallbacks::SystemHeaderPragma:
283 case PPCallbacks::RenameFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000284 WriteLineInfo(CurLine);
285 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000286 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000287}
288
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000289/// Ident - Handle #ident directives when read by the preprocessor.
Reid Spencer5f016e22007-07-11 17:01:13 +0000290///
291void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
292 MoveToLine(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Chris Lattnere96de3e2008-08-17 03:12:02 +0000294 OS.write("#ident ", strlen("#ident "));
295 OS.write(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000296 EmittedTokensOnThisLine = true;
297}
298
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000299/// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein2aa92672010-11-19 21:33:15 +0000300void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000301 const MacroInfo *MI) {
302 // Only print out macro definitions in -dD mode.
303 if (!DumpDefines ||
304 // Ignore __FILE__ etc.
305 MI->isBuiltinMacro()) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000307 MoveToLine(MI->getDefinitionLoc());
Craig Silverstein2aa92672010-11-19 21:33:15 +0000308 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000309 setEmittedDirectiveOnThisLine();
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000310}
311
Craig Silverstein2aa92672010-11-19 21:33:15 +0000312void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
Benjamin Kramer2f054492010-08-07 22:27:00 +0000313 const MacroInfo *MI) {
314 // Only print out macro definitions in -dD mode.
315 if (!DumpDefines) return;
316
Craig Silverstein2aa92672010-11-19 21:33:15 +0000317 MoveToLine(MacroNameTok.getLocation());
318 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000319 setEmittedDirectiveOnThisLine();
Benjamin Kramer2f054492010-08-07 22:27:00 +0000320}
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000321
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000322void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000323 const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000324 const std::string &Str) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000325 startNewLineIfNeeded();
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000326 MoveToLine(Loc);
327 OS << "#pragma comment(" << Kind->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000329 if (!Str.empty()) {
330 OS << ", \"";
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000332 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
333 unsigned char Char = Str[i];
Chris Lattner52a3e9e2009-01-16 22:13:37 +0000334 if (isprint(Char) && Char != '\\' && Char != '"')
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000335 OS << (char)Char;
336 else // Output anything hard as an octal escape.
337 OS << '\\'
338 << (char)('0'+ ((Char >> 6) & 7))
339 << (char)('0'+ ((Char >> 3) & 7))
340 << (char)('0'+ ((Char >> 0) & 7));
341 }
342 OS << '"';
343 }
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000345 OS << ')';
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000346 setEmittedDirectiveOnThisLine();
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000347}
348
Chris Lattnerabfe0942010-06-26 17:11:39 +0000349void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000350 StringRef Str) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000351 startNewLineIfNeeded();
Chris Lattnerabfe0942010-06-26 17:11:39 +0000352 MoveToLine(Loc);
353 OS << "#pragma message(";
354
355 OS << '"';
356
357 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
358 unsigned char Char = Str[i];
359 if (isprint(Char) && Char != '\\' && Char != '"')
360 OS << (char)Char;
361 else // Output anything hard as an octal escape.
362 OS << '\\'
363 << (char)('0'+ ((Char >> 6) & 7))
364 << (char)('0'+ ((Char >> 3) & 7))
365 << (char)('0'+ ((Char >> 0) & 7));
366 }
367 OS << '"';
368
369 OS << ')';
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000370 setEmittedDirectiveOnThisLine();
Chris Lattnerabfe0942010-06-26 17:11:39 +0000371}
372
Douglas Gregorc09ce122011-06-22 19:41:48 +0000373void PrintPPOutputPPCallbacks::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000374PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000375 startNewLineIfNeeded();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000376 MoveToLine(Loc);
377 OS << "#pragma " << Namespace << " diagnostic push";
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000378 setEmittedDirectiveOnThisLine();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000379}
380
381void PrintPPOutputPPCallbacks::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000382PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000383 startNewLineIfNeeded();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000384 MoveToLine(Loc);
385 OS << "#pragma " << Namespace << " diagnostic pop";
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000386 setEmittedDirectiveOnThisLine();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000387}
388
389void PrintPPOutputPPCallbacks::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000390PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
Benjamin Kramerd7a3e2c2012-02-07 22:29:24 +0000391 diag::Mapping Map, StringRef Str) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000392 startNewLineIfNeeded();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000393 MoveToLine(Loc);
394 OS << "#pragma " << Namespace << " diagnostic ";
Benjamin Kramerd7a3e2c2012-02-07 22:29:24 +0000395 switch (Map) {
Douglas Gregorc09ce122011-06-22 19:41:48 +0000396 case diag::MAP_WARNING:
397 OS << "warning";
398 break;
399 case diag::MAP_ERROR:
400 OS << "error";
401 break;
402 case diag::MAP_IGNORE:
403 OS << "ignored";
404 break;
405 case diag::MAP_FATAL:
406 OS << "fatal";
407 break;
408 }
409 OS << " \"" << Str << '"';
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000410 setEmittedDirectiveOnThisLine();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000411}
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000412
Reid Spencer5f016e22007-07-11 17:01:13 +0000413/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner5f180322007-12-09 21:11:08 +0000414/// is called for the first token on each new line. If this really is the start
415/// of a new logical line, handle it and return true, otherwise return false.
416/// This may not be the start of a logical line because the "start of line"
Chandler Carruth9f79a1f2011-07-14 16:14:52 +0000417/// marker is set for spelling lines, not expansion ones.
Chris Lattner5f180322007-12-09 21:11:08 +0000418bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000419 // Figure out what line we went to and insert the appropriate number of
420 // newline characters.
Chris Lattner5f180322007-12-09 21:11:08 +0000421 if (!MoveToLine(Tok.getLocation()))
422 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 // Print out space characters so that the first token on a line is
425 // indented for easy reading.
Chandler Carrutha77c0312011-07-25 20:57:57 +0000426 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Reid Spencer5f016e22007-07-11 17:01:13 +0000428 // This hack prevents stuff like:
429 // #define HASH #
430 // HASH define foo bar
431 // From having the # character end up at column 1, which makes it so it
432 // is not handled as a #define next time through the preprocessor if in
433 // -fpreprocessed mode.
Chris Lattner057aaf62007-10-09 18:03:42 +0000434 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattnere96de3e2008-08-17 03:12:02 +0000435 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Reid Spencer5f016e22007-07-11 17:01:13 +0000437 // Otherwise, indent the appropriate number of spaces.
438 for (; ColNo > 1; --ColNo)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000439 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Chris Lattner5f180322007-12-09 21:11:08 +0000441 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000442}
443
Chris Lattner3ee211f2009-06-15 01:25:23 +0000444void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
445 unsigned Len) {
446 unsigned NumNewlines = 0;
447 for (; Len; --Len, ++TokStr) {
448 if (*TokStr != '\n' &&
449 *TokStr != '\r')
450 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Chris Lattner3ee211f2009-06-15 01:25:23 +0000452 ++NumNewlines;
Mike Stump1eb44332009-09-09 15:08:12 +0000453
Chris Lattner3ee211f2009-06-15 01:25:23 +0000454 // If we have \n\r or \r\n, skip both and count as one line.
455 if (Len != 1 &&
456 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
457 TokStr[0] != TokStr[1])
458 ++TokStr, --Len;
459 }
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Chris Lattner3ee211f2009-06-15 01:25:23 +0000461 if (NumNewlines == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Chris Lattnered2d7c42009-06-15 04:08:28 +0000463 CurLine += NumNewlines;
Chris Lattner3ee211f2009-06-15 01:25:23 +0000464}
465
466
Reid Spencer5f016e22007-07-11 17:01:13 +0000467namespace {
468struct UnknownPragmaHandler : public PragmaHandler {
469 const char *Prefix;
470 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000473 : Prefix(prefix), Callbacks(callbacks) {}
Douglas Gregor80c60f72010-09-09 22:45:38 +0000474 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
475 Token &PragmaTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000476 // Figure out what line we went to and insert the appropriate number of
477 // newline characters.
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000478 Callbacks->startNewLineIfNeeded();
Reid Spencer5f016e22007-07-11 17:01:13 +0000479 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattnere96de3e2008-08-17 03:12:02 +0000480 Callbacks->OS.write(Prefix, strlen(Prefix));
Reid Spencer5f016e22007-07-11 17:01:13 +0000481 // Read and print all of the pragma tokens.
Peter Collingbourne84021552011-02-28 02:37:51 +0000482 while (PragmaTok.isNot(tok::eod)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000483 if (PragmaTok.hasLeadingSpace())
Chris Lattnere96de3e2008-08-17 03:12:02 +0000484 Callbacks->OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000485 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000486 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000487 PP.LexUnexpandedToken(PragmaTok);
488 }
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000489 Callbacks->setEmittedDirectiveOnThisLine();
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 }
491};
492} // end anonymous namespace
493
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000494
Chris Lattner59076ab2009-02-06 05:56:11 +0000495static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
496 PrintPPOutputPPCallbacks *Callbacks,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000497 raw_ostream &OS) {
Benjamin Kramere3960072010-02-27 18:02:51 +0000498 char Buffer[256];
Chris Lattnerc54539c2010-06-15 21:06:38 +0000499 Token PrevPrevTok, PrevTok;
500 PrevPrevTok.startToken();
501 PrevTok.startToken();
Chris Lattner6f688e12007-10-10 20:45:16 +0000502 while (1) {
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000503 if (Callbacks->hasEmittedDirectiveOnThisLine()) {
504 Callbacks->startNewLineIfNeeded();
505 Callbacks->MoveToLine(Tok.getLocation());
506 }
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner5f180322007-12-09 21:11:08 +0000509 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
510 // done.
Mike Stump1eb44332009-09-09 15:08:12 +0000511 } else if (Tok.hasLeadingSpace() ||
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000512 // If we haven't emitted a token on this line yet, PrevTok isn't
513 // useful to look at and no concatenation could happen anyway.
Chris Lattnerb638a302007-07-23 23:21:34 +0000514 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000515 // Don't print "-" next to "-", it would form "--".
Chris Lattner88773212010-04-14 03:57:19 +0000516 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattnere96de3e2008-08-17 03:12:02 +0000517 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000518 }
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Benjamin Kramere3960072010-02-27 18:02:51 +0000520 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
521 OS << II->getName();
522 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
523 Tok.getLiteralData()) {
524 OS.write(Tok.getLiteralData(), Tok.getLength());
525 } else if (Tok.getLength() < 256) {
526 const char *TokPtr = Buffer;
527 unsigned Len = PP.getSpelling(Tok, TokPtr);
528 OS.write(TokPtr, Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Benjamin Kramere3960072010-02-27 18:02:51 +0000530 // Tokens that can contain embedded newlines need to adjust our current
531 // line number.
532 if (Tok.getKind() == tok::comment)
533 Callbacks->HandleNewlinesInToken(TokPtr, Len);
534 } else {
535 std::string S = PP.getSpelling(Tok);
536 OS.write(&S[0], S.size());
537
538 // Tokens that can contain embedded newlines need to adjust our current
539 // line number.
540 if (Tok.getKind() == tok::comment)
541 Callbacks->HandleNewlinesInToken(&S[0], S.size());
542 }
Jordan Rose0cdd1fe2012-06-15 23:33:51 +0000543 Callbacks->setEmittedTokensOnThisLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Chris Lattner6f688e12007-10-10 20:45:16 +0000545 if (Tok.is(tok::eof)) break;
Mike Stump1eb44332009-09-09 15:08:12 +0000546
Chris Lattner88773212010-04-14 03:57:19 +0000547 PrevPrevTok = PrevTok;
Chris Lattner6f688e12007-10-10 20:45:16 +0000548 PrevTok = Tok;
549 PP.Lex(Tok);
550 }
Chris Lattner59076ab2009-02-06 05:56:11 +0000551}
552
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000553typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
554static int MacroIDCompare(const void* a, const void* b) {
555 const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
556 const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
557 return LHS->first->getName().compare(RHS->first->getName());
Chris Lattner2a2bb182009-02-10 22:28:19 +0000558}
Chris Lattner59076ab2009-02-06 05:56:11 +0000559
Chris Lattner5f9e2722011-07-23 10:55:15 +0000560static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000561 // Ignore unknown pragmas.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000562 PP.AddPragmaHandler(new EmptyPragmaHandler());
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000563
Eli Friedmanf1db5852009-05-19 01:32:34 +0000564 // -dM mode just scans and ignores all tokens in the files, then dumps out
565 // the macro table at the end.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000566 PP.EnterMainSourceFile();
Eli Friedmanf1db5852009-05-19 01:32:34 +0000567
568 Token Tok;
569 do PP.Lex(Tok);
570 while (Tok.isNot(tok::eof));
571
Chris Lattner5f9e2722011-07-23 10:55:15 +0000572 SmallVector<id_macro_pair, 128>
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000573 MacrosByID(PP.macro_begin(), PP.macro_end());
574 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedmanf1db5852009-05-19 01:32:34 +0000575
576 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
577 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000578 // Ignore computed macros like __LINE__ and friends.
Eli Friedmanf1db5852009-05-19 01:32:34 +0000579 if (MI.isBuiltinMacro()) continue;
580
581 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000582 *OS << '\n';
Eli Friedmanf1db5852009-05-19 01:32:34 +0000583 }
584}
585
Chris Lattner59076ab2009-02-06 05:56:11 +0000586/// DoPrintPreprocessedInput - This implements -E mode.
587///
Chris Lattner5f9e2722011-07-23 10:55:15 +0000588void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000589 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar775bee72009-11-11 10:07:22 +0000590 // Show macros with no output is handled specially.
591 if (!Opts.ShowCPP) {
592 assert(Opts.ShowMacros && "Not yet implemented!");
593 DoPrintMacros(PP, OS);
594 return;
595 }
596
Chris Lattner59076ab2009-02-06 05:56:11 +0000597 // Inform the preprocessor whether we want it to retain comments or not, due
598 // to -C or -CC.
Daniel Dunbar775bee72009-11-11 10:07:22 +0000599 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanf54fce82009-05-19 01:02:07 +0000600
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000601 PrintPPOutputPPCallbacks *Callbacks =
Daniel Dunbar775bee72009-11-11 10:07:22 +0000602 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
Daniel Dunbareef63e02011-02-02 15:41:17 +0000603 Opts.ShowMacros);
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000604 PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
Chris Lattner13973992010-11-10 01:00:49 +0000605 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
606 PP.AddPragmaHandler("clang",
607 new UnknownPragmaHandler("#pragma clang", Callbacks));
Chris Lattner59076ab2009-02-06 05:56:11 +0000608
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000609 PP.addPPCallbacks(Callbacks);
Chris Lattner59076ab2009-02-06 05:56:11 +0000610
Eli Friedmanf1db5852009-05-19 01:32:34 +0000611 // After we have configured the preprocessor, enter the main file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000612 PP.EnterMainSourceFile();
Chris Lattner59076ab2009-02-06 05:56:11 +0000613
Eli Friedmanf1db5852009-05-19 01:32:34 +0000614 // Consume all of the tokens that come from the predefines buffer. Those
615 // should not be emitted into the output and are guaranteed to be at the
616 // start.
617 const SourceManager &SourceMgr = PP.getSourceManager();
618 Token Tok;
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000619 do {
620 PP.Lex(Tok);
621 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
622 break;
623
624 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
625 if (PLoc.isInvalid())
626 break;
627
628 if (strcmp(PLoc.getFilename(), "<built-in>"))
629 break;
630 } while (true);
Chris Lattner59076ab2009-02-06 05:56:11 +0000631
Eli Friedmanf1db5852009-05-19 01:32:34 +0000632 // Read all the preprocessed tokens, printing them out to the stream.
633 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
634 *OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000635}