blob: 8a61f968e67f433680b61a53a2216a3d3c82f473 [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/Config/config.h"
Chris Lattnerdceb6a72008-08-17 01:47:12 +000028#include "llvm/Support/raw_ostream.h"
Douglas Gregorc09ce122011-06-22 19:41:48 +000029#include "llvm/Support/ErrorHandling.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
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000066 llvm::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;
Eli Friedman3e753e22009-06-02 07:55:39 +000091 bool EmittedMacroOnThisLine;
Chris Lattner9d728512008-10-27 01:19:25 +000092 SrcMgr::CharacteristicKind FileType;
Chris Lattnerd8e30832007-07-24 06:57:14 +000093 llvm::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;
Reid Spencer5f016e22007-07-11 17:01:13 +000098public:
Chris Lattner5f9e2722011-07-23 10:55:15 +000099 PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os,
Daniel Dunbareef63e02011-02-02 15:41:17 +0000100 bool lineMarkers, bool defines)
Chris Lattnerdf721402010-04-13 00:06:42 +0000101 : PP(pp), SM(PP.getSourceManager()),
102 ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
Daniel Dunbareef63e02011-02-02 15:41:17 +0000103 DumpDefines(defines) {
104 CurLine = 0;
Chris Lattnerd8e30832007-07-24 06:57:14 +0000105 CurFilename += "<uninit>";
Reid Spencer5f016e22007-07-11 17:01:13 +0000106 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000107 EmittedMacroOnThisLine = false;
Chris Lattner0b9e7362008-09-26 21:18:42 +0000108 FileType = SrcMgr::C_User;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000109 Initialized = false;
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000110
Chris Lattnerf7449342009-12-07 01:42:56 +0000111 // If we're in microsoft mode, use normal #line instead of line markers.
Francois Pichet62ec1f22011-09-17 17:15:52 +0000112 UseLineDirective = PP.getLangOptions().MicrosoftExt;
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 }
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000116 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Mike Stump1eb44332009-09-09 15:08:12 +0000117
Douglas Gregor80c60f72010-09-09 22:45:38 +0000118 bool StartNewLineIfNeeded();
119
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
Argyrios Kyrtzidisc892c5f2011-10-11 17:29:44 +0000121 SrcMgr::CharacteristicKind FileType,
122 FileID PrevFID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 virtual void Ident(SourceLocation Loc, const std::string &str);
Mike Stump1eb44332009-09-09 15:08:12 +0000124 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000125 const std::string &Str);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000126 virtual void PragmaMessage(SourceLocation Loc, StringRef Str);
Douglas Gregorc09ce122011-06-22 19:41:48 +0000127 virtual void PragmaDiagnosticPush(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000128 StringRef Namespace);
Douglas Gregorc09ce122011-06-22 19:41:48 +0000129 virtual void PragmaDiagnosticPop(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000130 StringRef Namespace);
131 virtual void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
132 diag::Mapping Map, StringRef Str);
Reid Spencer5f016e22007-07-11 17:01:13 +0000133
Chris Lattner5f180322007-12-09 21:11:08 +0000134 bool HandleFirstTokOnLine(Token &Tok);
Chris Lattner88aae912010-04-13 00:01:41 +0000135 bool MoveToLine(SourceLocation Loc) {
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000136 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
137 if (PLoc.isInvalid())
138 return false;
139 return MoveToLine(PLoc.getLine());
Chris Lattner88aae912010-04-13 00:01:41 +0000140 }
141 bool MoveToLine(unsigned LineNo);
142
Chris Lattner88773212010-04-14 03:57:19 +0000143 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
144 const Token &Tok) {
145 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
Chris Lattnerd7038e12009-02-13 00:46:04 +0000146 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000147 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
Douglas Gregor80c60f72010-09-09 22:45:38 +0000148 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
Chris Lattner3ee211f2009-06-15 01:25:23 +0000149 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000151 /// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein2aa92672010-11-19 21:33:15 +0000152 void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000153
Benjamin Kramer2f054492010-08-07 22:27:00 +0000154 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
Craig Silverstein2aa92672010-11-19 21:33:15 +0000155 void MacroUndefined(const Token &MacroNameTok, const MacroInfo *MI);
Reid Spencer5f016e22007-07-11 17:01:13 +0000156};
Chris Lattner5db17c92008-04-08 04:16:20 +0000157} // end anonymous namespace
Reid Spencer5f016e22007-07-11 17:01:13 +0000158
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000159void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
160 const char *Extra,
161 unsigned ExtraLen) {
Eli Friedman3e753e22009-06-02 07:55:39 +0000162 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000163 OS << '\n';
164 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000165 EmittedMacroOnThisLine = false;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000166 }
167
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.
211 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
212 OS << '\n';
213 EmittedTokensOnThisLine = false;
214 EmittedMacroOnThisLine = false;
215 }
Mike Stump1eb44332009-09-09 15:08:12 +0000216 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000217
Mike Stump1eb44332009-09-09 15:08:12 +0000218 CurLine = LineNo;
Chris Lattner5f180322007-12-09 21:11:08 +0000219 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000220}
221
Douglas Gregor80c60f72010-09-09 22:45:38 +0000222bool PrintPPOutputPPCallbacks::StartNewLineIfNeeded() {
223 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
224 OS << '\n';
225 EmittedTokensOnThisLine = false;
226 EmittedMacroOnThisLine = false;
227 ++CurLine;
228 return true;
229 }
230
231 return false;
232}
Reid Spencer5f016e22007-07-11 17:01:13 +0000233
234/// FileChanged - Whenever the preprocessor enters or exits a #include file
235/// it invokes this handler. Update our conception of the current source
236/// position.
237void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
238 FileChangeReason Reason,
Argyrios Kyrtzidisc892c5f2011-10-11 17:29:44 +0000239 SrcMgr::CharacteristicKind NewFileType,
240 FileID PrevFID) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000241 // Unless we are exiting a #include, make sure to skip ahead to the line the
242 // #include directive was at.
Chris Lattnerdf721402010-04-13 00:06:42 +0000243 SourceManager &SourceMgr = SM;
Chris Lattner88aae912010-04-13 00:01:41 +0000244
245 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000246 if (UserLoc.isInvalid())
247 return;
248
Chris Lattner86d0ef72010-04-14 04:28:50 +0000249 unsigned NewLine = UserLoc.getLine();
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000250
Reid Spencer5f016e22007-07-11 17:01:13 +0000251 if (Reason == PPCallbacks::EnterFile) {
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000252 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
Chris Lattner71d8bfb2009-01-30 18:44:17 +0000253 if (IncludeLoc.isValid())
254 MoveToLine(IncludeLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000255 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
Chris Lattner88aae912010-04-13 00:01:41 +0000256 MoveToLine(NewLine);
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Reid Spencer5f016e22007-07-11 17:01:13 +0000258 // TODO GCC emits the # directive for this directive on the line AFTER the
259 // directive and emits a bunch of spaces that aren't needed. Emulate this
260 // strange behavior.
261 }
Chris Lattner88aae912010-04-13 00:01:41 +0000262
263 CurLine = NewLine;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000264
Chris Lattnerd8e30832007-07-24 06:57:14 +0000265 CurFilename.clear();
Chris Lattner88aae912010-04-13 00:01:41 +0000266 CurFilename += UserLoc.getFilename();
Chris Lattnerd8e30832007-07-24 06:57:14 +0000267 Lexer::Stringify(CurFilename);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000268 FileType = NewFileType;
269
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000270 if (DisableLineMarkers) return;
271
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000272 if (!Initialized) {
273 WriteLineInfo(CurLine);
274 Initialized = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000275 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000276
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 switch (Reason) {
278 case PPCallbacks::EnterFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000279 WriteLineInfo(CurLine, " 1", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000280 break;
281 case PPCallbacks::ExitFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000282 WriteLineInfo(CurLine, " 2", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000283 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000284 case PPCallbacks::SystemHeaderPragma:
285 case PPCallbacks::RenameFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000286 WriteLineInfo(CurLine);
287 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000288 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000289}
290
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000291/// Ident - Handle #ident directives when read by the preprocessor.
Reid Spencer5f016e22007-07-11 17:01:13 +0000292///
293void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
294 MoveToLine(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Chris Lattnere96de3e2008-08-17 03:12:02 +0000296 OS.write("#ident ", strlen("#ident "));
297 OS.write(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 EmittedTokensOnThisLine = true;
299}
300
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000301/// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein2aa92672010-11-19 21:33:15 +0000302void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000303 const MacroInfo *MI) {
304 // Only print out macro definitions in -dD mode.
305 if (!DumpDefines ||
306 // Ignore __FILE__ etc.
307 MI->isBuiltinMacro()) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000309 MoveToLine(MI->getDefinitionLoc());
Craig Silverstein2aa92672010-11-19 21:33:15 +0000310 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
Eli Friedman3e753e22009-06-02 07:55:39 +0000311 EmittedMacroOnThisLine = true;
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000312}
313
Craig Silverstein2aa92672010-11-19 21:33:15 +0000314void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
Benjamin Kramer2f054492010-08-07 22:27:00 +0000315 const MacroInfo *MI) {
316 // Only print out macro definitions in -dD mode.
317 if (!DumpDefines) return;
318
Craig Silverstein2aa92672010-11-19 21:33:15 +0000319 MoveToLine(MacroNameTok.getLocation());
320 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
Benjamin Kramer2f054492010-08-07 22:27:00 +0000321 EmittedMacroOnThisLine = true;
322}
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000323
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000324void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000325 const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000326 const std::string &Str) {
327 MoveToLine(Loc);
328 OS << "#pragma comment(" << Kind->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000330 if (!Str.empty()) {
331 OS << ", \"";
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000333 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
334 unsigned char Char = Str[i];
Chris Lattner52a3e9e2009-01-16 22:13:37 +0000335 if (isprint(Char) && Char != '\\' && Char != '"')
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000336 OS << (char)Char;
337 else // Output anything hard as an octal escape.
338 OS << '\\'
339 << (char)('0'+ ((Char >> 6) & 7))
340 << (char)('0'+ ((Char >> 3) & 7))
341 << (char)('0'+ ((Char >> 0) & 7));
342 }
343 OS << '"';
344 }
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000346 OS << ')';
347 EmittedTokensOnThisLine = true;
348}
349
Chris Lattnerabfe0942010-06-26 17:11:39 +0000350void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000351 StringRef Str) {
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 << ')';
370 EmittedTokensOnThisLine = true;
371}
372
Douglas Gregorc09ce122011-06-22 19:41:48 +0000373void PrintPPOutputPPCallbacks::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000374PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
Douglas Gregorc09ce122011-06-22 19:41:48 +0000375 MoveToLine(Loc);
376 OS << "#pragma " << Namespace << " diagnostic push";
377 EmittedTokensOnThisLine = true;
378}
379
380void PrintPPOutputPPCallbacks::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000381PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
Douglas Gregorc09ce122011-06-22 19:41:48 +0000382 MoveToLine(Loc);
383 OS << "#pragma " << Namespace << " diagnostic pop";
384 EmittedTokensOnThisLine = true;
385}
386
387void PrintPPOutputPPCallbacks::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000388PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
389 diag::Mapping Map, StringRef Str) {
Douglas Gregorc09ce122011-06-22 19:41:48 +0000390 MoveToLine(Loc);
391 OS << "#pragma " << Namespace << " diagnostic ";
392 switch (Map) {
393 default: llvm_unreachable("unexpected diagnostic kind");
394 case diag::MAP_WARNING:
395 OS << "warning";
396 break;
397 case diag::MAP_ERROR:
398 OS << "error";
399 break;
400 case diag::MAP_IGNORE:
401 OS << "ignored";
402 break;
403 case diag::MAP_FATAL:
404 OS << "fatal";
405 break;
406 }
407 OS << " \"" << Str << '"';
408 EmittedTokensOnThisLine = true;
409}
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000410
Reid Spencer5f016e22007-07-11 17:01:13 +0000411/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner5f180322007-12-09 21:11:08 +0000412/// is called for the first token on each new line. If this really is the start
413/// of a new logical line, handle it and return true, otherwise return false.
414/// This may not be the start of a logical line because the "start of line"
Chandler Carruth9f79a1f2011-07-14 16:14:52 +0000415/// marker is set for spelling lines, not expansion ones.
Chris Lattner5f180322007-12-09 21:11:08 +0000416bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 // Figure out what line we went to and insert the appropriate number of
418 // newline characters.
Chris Lattner5f180322007-12-09 21:11:08 +0000419 if (!MoveToLine(Tok.getLocation()))
420 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 // Print out space characters so that the first token on a line is
423 // indented for easy reading.
Chandler Carrutha77c0312011-07-25 20:57:57 +0000424 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Reid Spencer5f016e22007-07-11 17:01:13 +0000426 // This hack prevents stuff like:
427 // #define HASH #
428 // HASH define foo bar
429 // From having the # character end up at column 1, which makes it so it
430 // is not handled as a #define next time through the preprocessor if in
431 // -fpreprocessed mode.
Chris Lattner057aaf62007-10-09 18:03:42 +0000432 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattnere96de3e2008-08-17 03:12:02 +0000433 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Reid Spencer5f016e22007-07-11 17:01:13 +0000435 // Otherwise, indent the appropriate number of spaces.
436 for (; ColNo > 1; --ColNo)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000437 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Chris Lattner5f180322007-12-09 21:11:08 +0000439 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000440}
441
Chris Lattner3ee211f2009-06-15 01:25:23 +0000442void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
443 unsigned Len) {
444 unsigned NumNewlines = 0;
445 for (; Len; --Len, ++TokStr) {
446 if (*TokStr != '\n' &&
447 *TokStr != '\r')
448 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Chris Lattner3ee211f2009-06-15 01:25:23 +0000450 ++NumNewlines;
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Chris Lattner3ee211f2009-06-15 01:25:23 +0000452 // If we have \n\r or \r\n, skip both and count as one line.
453 if (Len != 1 &&
454 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
455 TokStr[0] != TokStr[1])
456 ++TokStr, --Len;
457 }
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Chris Lattner3ee211f2009-06-15 01:25:23 +0000459 if (NumNewlines == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Chris Lattnered2d7c42009-06-15 04:08:28 +0000461 CurLine += NumNewlines;
Chris Lattner3ee211f2009-06-15 01:25:23 +0000462}
463
464
Reid Spencer5f016e22007-07-11 17:01:13 +0000465namespace {
466struct UnknownPragmaHandler : public PragmaHandler {
467 const char *Prefix;
468 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000471 : Prefix(prefix), Callbacks(callbacks) {}
Douglas Gregor80c60f72010-09-09 22:45:38 +0000472 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
473 Token &PragmaTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 // Figure out what line we went to and insert the appropriate number of
475 // newline characters.
Douglas Gregorfe6834a2010-09-10 22:27:29 +0000476 Callbacks->StartNewLineIfNeeded();
Reid Spencer5f016e22007-07-11 17:01:13 +0000477 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattnere96de3e2008-08-17 03:12:02 +0000478 Callbacks->OS.write(Prefix, strlen(Prefix));
Douglas Gregor80c60f72010-09-09 22:45:38 +0000479 Callbacks->SetEmittedTokensOnThisLine();
Reid Spencer5f016e22007-07-11 17:01:13 +0000480 // Read and print all of the pragma tokens.
Peter Collingbourne84021552011-02-28 02:37:51 +0000481 while (PragmaTok.isNot(tok::eod)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000482 if (PragmaTok.hasLeadingSpace())
Chris Lattnere96de3e2008-08-17 03:12:02 +0000483 Callbacks->OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000485 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000486 PP.LexUnexpandedToken(PragmaTok);
487 }
Douglas Gregor80c60f72010-09-09 22:45:38 +0000488 Callbacks->StartNewLineIfNeeded();
Reid Spencer5f016e22007-07-11 17:01:13 +0000489 }
490};
491} // end anonymous namespace
492
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000493
Chris Lattner59076ab2009-02-06 05:56:11 +0000494static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
495 PrintPPOutputPPCallbacks *Callbacks,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000496 raw_ostream &OS) {
Benjamin Kramere3960072010-02-27 18:02:51 +0000497 char Buffer[256];
Chris Lattnerc54539c2010-06-15 21:06:38 +0000498 Token PrevPrevTok, PrevTok;
499 PrevPrevTok.startToken();
500 PrevTok.startToken();
Chris Lattner6f688e12007-10-10 20:45:16 +0000501 while (1) {
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Reid Spencer5f016e22007-07-11 17:01:13 +0000503 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner5f180322007-12-09 21:11:08 +0000504 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
505 // done.
Mike Stump1eb44332009-09-09 15:08:12 +0000506 } else if (Tok.hasLeadingSpace() ||
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000507 // If we haven't emitted a token on this line yet, PrevTok isn't
508 // useful to look at and no concatenation could happen anyway.
Chris Lattnerb638a302007-07-23 23:21:34 +0000509 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000510 // Don't print "-" next to "-", it would form "--".
Chris Lattner88773212010-04-14 03:57:19 +0000511 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattnere96de3e2008-08-17 03:12:02 +0000512 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000513 }
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Benjamin Kramere3960072010-02-27 18:02:51 +0000515 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
516 OS << II->getName();
517 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
518 Tok.getLiteralData()) {
519 OS.write(Tok.getLiteralData(), Tok.getLength());
520 } else if (Tok.getLength() < 256) {
521 const char *TokPtr = Buffer;
522 unsigned Len = PP.getSpelling(Tok, TokPtr);
523 OS.write(TokPtr, Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Benjamin Kramere3960072010-02-27 18:02:51 +0000525 // Tokens that can contain embedded newlines need to adjust our current
526 // line number.
527 if (Tok.getKind() == tok::comment)
528 Callbacks->HandleNewlinesInToken(TokPtr, Len);
529 } else {
530 std::string S = PP.getSpelling(Tok);
531 OS.write(&S[0], S.size());
532
533 // Tokens that can contain embedded newlines need to adjust our current
534 // line number.
535 if (Tok.getKind() == tok::comment)
536 Callbacks->HandleNewlinesInToken(&S[0], S.size());
537 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000538 Callbacks->SetEmittedTokensOnThisLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Chris Lattner6f688e12007-10-10 20:45:16 +0000540 if (Tok.is(tok::eof)) break;
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Chris Lattner88773212010-04-14 03:57:19 +0000542 PrevPrevTok = PrevTok;
Chris Lattner6f688e12007-10-10 20:45:16 +0000543 PrevTok = Tok;
544 PP.Lex(Tok);
545 }
Chris Lattner59076ab2009-02-06 05:56:11 +0000546}
547
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000548typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
549static int MacroIDCompare(const void* a, const void* b) {
550 const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
551 const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
552 return LHS->first->getName().compare(RHS->first->getName());
Chris Lattner2a2bb182009-02-10 22:28:19 +0000553}
Chris Lattner59076ab2009-02-06 05:56:11 +0000554
Chris Lattner5f9e2722011-07-23 10:55:15 +0000555static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000556 // Ignore unknown pragmas.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000557 PP.AddPragmaHandler(new EmptyPragmaHandler());
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000558
Eli Friedmanf1db5852009-05-19 01:32:34 +0000559 // -dM mode just scans and ignores all tokens in the files, then dumps out
560 // the macro table at the end.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000561 PP.EnterMainSourceFile();
Eli Friedmanf1db5852009-05-19 01:32:34 +0000562
563 Token Tok;
564 do PP.Lex(Tok);
565 while (Tok.isNot(tok::eof));
566
Chris Lattner5f9e2722011-07-23 10:55:15 +0000567 SmallVector<id_macro_pair, 128>
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000568 MacrosByID(PP.macro_begin(), PP.macro_end());
569 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedmanf1db5852009-05-19 01:32:34 +0000570
571 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
572 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000573 // Ignore computed macros like __LINE__ and friends.
Eli Friedmanf1db5852009-05-19 01:32:34 +0000574 if (MI.isBuiltinMacro()) continue;
575
576 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000577 *OS << '\n';
Eli Friedmanf1db5852009-05-19 01:32:34 +0000578 }
579}
580
Chris Lattner59076ab2009-02-06 05:56:11 +0000581/// DoPrintPreprocessedInput - This implements -E mode.
582///
Chris Lattner5f9e2722011-07-23 10:55:15 +0000583void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000584 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar775bee72009-11-11 10:07:22 +0000585 // Show macros with no output is handled specially.
586 if (!Opts.ShowCPP) {
587 assert(Opts.ShowMacros && "Not yet implemented!");
588 DoPrintMacros(PP, OS);
589 return;
590 }
591
Chris Lattner59076ab2009-02-06 05:56:11 +0000592 // Inform the preprocessor whether we want it to retain comments or not, due
593 // to -C or -CC.
Daniel Dunbar775bee72009-11-11 10:07:22 +0000594 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanf54fce82009-05-19 01:02:07 +0000595
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000596 PrintPPOutputPPCallbacks *Callbacks =
Daniel Dunbar775bee72009-11-11 10:07:22 +0000597 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
Daniel Dunbareef63e02011-02-02 15:41:17 +0000598 Opts.ShowMacros);
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000599 PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
Chris Lattner13973992010-11-10 01:00:49 +0000600 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
601 PP.AddPragmaHandler("clang",
602 new UnknownPragmaHandler("#pragma clang", Callbacks));
Chris Lattner59076ab2009-02-06 05:56:11 +0000603
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000604 PP.addPPCallbacks(Callbacks);
Chris Lattner59076ab2009-02-06 05:56:11 +0000605
Eli Friedmanf1db5852009-05-19 01:32:34 +0000606 // After we have configured the preprocessor, enter the main file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000607 PP.EnterMainSourceFile();
Chris Lattner59076ab2009-02-06 05:56:11 +0000608
Eli Friedmanf1db5852009-05-19 01:32:34 +0000609 // Consume all of the tokens that come from the predefines buffer. Those
610 // should not be emitted into the output and are guaranteed to be at the
611 // start.
612 const SourceManager &SourceMgr = PP.getSourceManager();
613 Token Tok;
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000614 do {
615 PP.Lex(Tok);
616 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
617 break;
618
619 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
620 if (PLoc.isInvalid())
621 break;
622
623 if (strcmp(PLoc.getFilename(), "<built-in>"))
624 break;
625 } while (true);
Chris Lattner59076ab2009-02-06 05:56:11 +0000626
Eli Friedmanf1db5852009-05-19 01:32:34 +0000627 // Read all the preprocessed tokens, printing them out to the stream.
628 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
629 *OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000630}