blob: 922d743adf4e96d4729e561a5c161ca238e3e7fd [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"
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,
35 Preprocessor &PP, llvm::raw_ostream &OS) {
36 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
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000065 llvm::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:
85 llvm::raw_ostream &OS;
86private:
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;
Eli Friedman3e753e22009-06-02 07:55:39 +000090 bool EmittedMacroOnThisLine;
Chris Lattner9d728512008-10-27 01:19:25 +000091 SrcMgr::CharacteristicKind FileType;
Chris Lattnerd8e30832007-07-24 06:57:14 +000092 llvm::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:
Eli Friedman12d3b1d2009-05-19 03:06:47 +000098 PrintPPOutputPPCallbacks(Preprocessor &pp, llvm::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;
Eli Friedman3e753e22009-06-02 07:55:39 +0000106 EmittedMacroOnThisLine = 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.
111 UseLineDirective = PP.getLangOptions().Microsoft;
Reid Spencer5f016e22007-07-11 17:01:13 +0000112 }
Mike Stump1eb44332009-09-09 15:08:12 +0000113
Reid Spencer5f016e22007-07-11 17:01:13 +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
Douglas Gregor80c60f72010-09-09 22:45:38 +0000117 bool StartNewLineIfNeeded();
118
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +0000120 SrcMgr::CharacteristicKind FileType);
Reid Spencer5f016e22007-07-11 17:01:13 +0000121 virtual void Ident(SourceLocation Loc, const std::string &str);
Mike Stump1eb44332009-09-09 15:08:12 +0000122 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000123 const std::string &Str);
Chris Lattnerabfe0942010-06-26 17:11:39 +0000124 virtual void PragmaMessage(SourceLocation Loc, llvm::StringRef Str);
Reid Spencer5f016e22007-07-11 17:01:13 +0000125
Chris Lattner5f180322007-12-09 21:11:08 +0000126 bool HandleFirstTokOnLine(Token &Tok);
Chris Lattner88aae912010-04-13 00:01:41 +0000127 bool MoveToLine(SourceLocation Loc) {
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000128 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
129 if (PLoc.isInvalid())
130 return false;
131 return MoveToLine(PLoc.getLine());
Chris Lattner88aae912010-04-13 00:01:41 +0000132 }
133 bool MoveToLine(unsigned LineNo);
134
Chris Lattner88773212010-04-14 03:57:19 +0000135 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
136 const Token &Tok) {
137 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
Chris Lattnerd7038e12009-02-13 00:46:04 +0000138 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000139 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
Douglas Gregor80c60f72010-09-09 22:45:38 +0000140 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
Chris Lattner3ee211f2009-06-15 01:25:23 +0000141 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000143 /// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein2aa92672010-11-19 21:33:15 +0000144 void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000145
Benjamin Kramer2f054492010-08-07 22:27:00 +0000146 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
Craig Silverstein2aa92672010-11-19 21:33:15 +0000147 void MacroUndefined(const Token &MacroNameTok, const MacroInfo *MI);
Reid Spencer5f016e22007-07-11 17:01:13 +0000148};
Chris Lattner5db17c92008-04-08 04:16:20 +0000149} // end anonymous namespace
Reid Spencer5f016e22007-07-11 17:01:13 +0000150
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000151void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
152 const char *Extra,
153 unsigned ExtraLen) {
Eli Friedman3e753e22009-06-02 07:55:39 +0000154 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000155 OS << '\n';
156 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000157 EmittedMacroOnThisLine = false;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000158 }
159
Chris Lattnerf7449342009-12-07 01:42:56 +0000160 // Emit #line directives or GNU line markers depending on what mode we're in.
161 if (UseLineDirective) {
162 OS << "#line" << ' ' << LineNo << ' ' << '"';
Ted Kremenek23465132010-09-17 00:41:18 +0000163 OS.write(CurFilename.data(), CurFilename.size());
Chris Lattnerf7449342009-12-07 01:42:56 +0000164 OS << '"';
165 } else {
166 OS << '#' << ' ' << LineNo << ' ' << '"';
Ted Kremenek23465132010-09-17 00:41:18 +0000167 OS.write(CurFilename.data(), CurFilename.size());
Chris Lattnerf7449342009-12-07 01:42:56 +0000168 OS << '"';
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000169
Steve Naroffd76fbda2009-12-06 01:02:14 +0000170 if (ExtraLen)
171 OS.write(Extra, ExtraLen);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000172
Steve Naroffd76fbda2009-12-06 01:02:14 +0000173 if (FileType == SrcMgr::C_System)
174 OS.write(" 3", 2);
175 else if (FileType == SrcMgr::C_ExternCSystem)
176 OS.write(" 3 4", 4);
177 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000178 OS << '\n';
179}
180
Reid Spencer5f016e22007-07-11 17:01:13 +0000181/// MoveToLine - Move the output to the source line specified by the location
182/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner5f180322007-12-09 21:11:08 +0000183/// #line directive. This returns false if already at the specified line, true
184/// if some newlines were emitted.
Chris Lattner88aae912010-04-13 00:01:41 +0000185bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 // If this line is "close enough" to the original line, just print newlines,
187 // otherwise print a #line directive.
Daniel Dunbarfd966842008-09-26 01:13:35 +0000188 if (LineNo-CurLine <= 8) {
Chris Lattner822f9402007-07-23 05:14:05 +0000189 if (LineNo-CurLine == 1)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000190 OS << '\n';
Chris Lattner5f180322007-12-09 21:11:08 +0000191 else if (LineNo == CurLine)
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000192 return false; // Spelling line moved, but instantiation line didn't.
Chris Lattner822f9402007-07-23 05:14:05 +0000193 else {
194 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattnere96de3e2008-08-17 03:12:02 +0000195 OS.write(NewLines, LineNo-CurLine);
Chris Lattner822f9402007-07-23 05:14:05 +0000196 }
Chris Lattner6133aeb2010-06-12 16:20:56 +0000197 } else if (!DisableLineMarkers) {
198 // Emit a #line or line marker.
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000199 WriteLineInfo(LineNo, 0, 0);
Chris Lattner6133aeb2010-06-12 16:20:56 +0000200 } else {
201 // Okay, we're in -P mode, which turns off line markers. However, we still
202 // need to emit a newline between tokens on different lines.
203 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
204 OS << '\n';
205 EmittedTokensOnThisLine = false;
206 EmittedMacroOnThisLine = false;
207 }
Mike Stump1eb44332009-09-09 15:08:12 +0000208 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000209
Mike Stump1eb44332009-09-09 15:08:12 +0000210 CurLine = LineNo;
Chris Lattner5f180322007-12-09 21:11:08 +0000211 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000212}
213
Douglas Gregor80c60f72010-09-09 22:45:38 +0000214bool PrintPPOutputPPCallbacks::StartNewLineIfNeeded() {
215 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
216 OS << '\n';
217 EmittedTokensOnThisLine = false;
218 EmittedMacroOnThisLine = false;
219 ++CurLine;
220 return true;
221 }
222
223 return false;
224}
Reid Spencer5f016e22007-07-11 17:01:13 +0000225
226/// FileChanged - Whenever the preprocessor enters or exits a #include file
227/// it invokes this handler. Update our conception of the current source
228/// position.
229void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
230 FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +0000231 SrcMgr::CharacteristicKind NewFileType) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000232 // Unless we are exiting a #include, make sure to skip ahead to the line the
233 // #include directive was at.
Chris Lattnerdf721402010-04-13 00:06:42 +0000234 SourceManager &SourceMgr = SM;
Chris Lattner88aae912010-04-13 00:01:41 +0000235
236 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000237 if (UserLoc.isInvalid())
238 return;
239
Chris Lattner86d0ef72010-04-14 04:28:50 +0000240 unsigned NewLine = UserLoc.getLine();
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000241
Reid Spencer5f016e22007-07-11 17:01:13 +0000242 if (Reason == PPCallbacks::EnterFile) {
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000243 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
Chris Lattner71d8bfb2009-01-30 18:44:17 +0000244 if (IncludeLoc.isValid())
245 MoveToLine(IncludeLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000246 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
Chris Lattner88aae912010-04-13 00:01:41 +0000247 MoveToLine(NewLine);
Mike Stump1eb44332009-09-09 15:08:12 +0000248
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 // TODO GCC emits the # directive for this directive on the line AFTER the
250 // directive and emits a bunch of spaces that aren't needed. Emulate this
251 // strange behavior.
252 }
Chris Lattner88aae912010-04-13 00:01:41 +0000253
254 CurLine = NewLine;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000255
Chris Lattnerd8e30832007-07-24 06:57:14 +0000256 CurFilename.clear();
Chris Lattner88aae912010-04-13 00:01:41 +0000257 CurFilename += UserLoc.getFilename();
Chris Lattnerd8e30832007-07-24 06:57:14 +0000258 Lexer::Stringify(CurFilename);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000259 FileType = NewFileType;
260
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000261 if (DisableLineMarkers) return;
262
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000263 if (!Initialized) {
264 WriteLineInfo(CurLine);
265 Initialized = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000266 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000267
Reid Spencer5f016e22007-07-11 17:01:13 +0000268 switch (Reason) {
269 case PPCallbacks::EnterFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000270 WriteLineInfo(CurLine, " 1", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000271 break;
272 case PPCallbacks::ExitFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000273 WriteLineInfo(CurLine, " 2", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000275 case PPCallbacks::SystemHeaderPragma:
276 case PPCallbacks::RenameFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000277 WriteLineInfo(CurLine);
278 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000280}
281
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000282/// Ident - Handle #ident directives when read by the preprocessor.
Reid Spencer5f016e22007-07-11 17:01:13 +0000283///
284void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
285 MoveToLine(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Chris Lattnere96de3e2008-08-17 03:12:02 +0000287 OS.write("#ident ", strlen("#ident "));
288 OS.write(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000289 EmittedTokensOnThisLine = true;
290}
291
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000292/// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein2aa92672010-11-19 21:33:15 +0000293void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000294 const MacroInfo *MI) {
295 // Only print out macro definitions in -dD mode.
296 if (!DumpDefines ||
297 // Ignore __FILE__ etc.
298 MI->isBuiltinMacro()) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000300 MoveToLine(MI->getDefinitionLoc());
Craig Silverstein2aa92672010-11-19 21:33:15 +0000301 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
Eli Friedman3e753e22009-06-02 07:55:39 +0000302 EmittedMacroOnThisLine = true;
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000303}
304
Craig Silverstein2aa92672010-11-19 21:33:15 +0000305void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
Benjamin Kramer2f054492010-08-07 22:27:00 +0000306 const MacroInfo *MI) {
307 // Only print out macro definitions in -dD mode.
308 if (!DumpDefines) return;
309
Craig Silverstein2aa92672010-11-19 21:33:15 +0000310 MoveToLine(MacroNameTok.getLocation());
311 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
Benjamin Kramer2f054492010-08-07 22:27:00 +0000312 EmittedMacroOnThisLine = true;
313}
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000314
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000315void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000316 const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000317 const std::string &Str) {
318 MoveToLine(Loc);
319 OS << "#pragma comment(" << Kind->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000321 if (!Str.empty()) {
322 OS << ", \"";
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000324 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
325 unsigned char Char = Str[i];
Chris Lattner52a3e9e2009-01-16 22:13:37 +0000326 if (isprint(Char) && Char != '\\' && Char != '"')
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000327 OS << (char)Char;
328 else // Output anything hard as an octal escape.
329 OS << '\\'
330 << (char)('0'+ ((Char >> 6) & 7))
331 << (char)('0'+ ((Char >> 3) & 7))
332 << (char)('0'+ ((Char >> 0) & 7));
333 }
334 OS << '"';
335 }
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000337 OS << ')';
338 EmittedTokensOnThisLine = true;
339}
340
Chris Lattnerabfe0942010-06-26 17:11:39 +0000341void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
342 llvm::StringRef Str) {
343 MoveToLine(Loc);
344 OS << "#pragma message(";
345
346 OS << '"';
347
348 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
349 unsigned char Char = Str[i];
350 if (isprint(Char) && Char != '\\' && Char != '"')
351 OS << (char)Char;
352 else // Output anything hard as an octal escape.
353 OS << '\\'
354 << (char)('0'+ ((Char >> 6) & 7))
355 << (char)('0'+ ((Char >> 3) & 7))
356 << (char)('0'+ ((Char >> 0) & 7));
357 }
358 OS << '"';
359
360 OS << ')';
361 EmittedTokensOnThisLine = true;
362}
363
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000364
Reid Spencer5f016e22007-07-11 17:01:13 +0000365/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner5f180322007-12-09 21:11:08 +0000366/// is called for the first token on each new line. If this really is the start
367/// of a new logical line, handle it and return true, otherwise return false.
368/// This may not be the start of a logical line because the "start of line"
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000369/// marker is set for spelling lines, not instantiation ones.
Chris Lattner5f180322007-12-09 21:11:08 +0000370bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 // Figure out what line we went to and insert the appropriate number of
372 // newline characters.
Chris Lattner5f180322007-12-09 21:11:08 +0000373 if (!MoveToLine(Tok.getLocation()))
374 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Reid Spencer5f016e22007-07-11 17:01:13 +0000376 // Print out space characters so that the first token on a line is
377 // indented for easy reading.
Chris Lattnerdf721402010-04-13 00:06:42 +0000378 unsigned ColNo = SM.getInstantiationColumnNumber(Tok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Reid Spencer5f016e22007-07-11 17:01:13 +0000380 // This hack prevents stuff like:
381 // #define HASH #
382 // HASH define foo bar
383 // From having the # character end up at column 1, which makes it so it
384 // is not handled as a #define next time through the preprocessor if in
385 // -fpreprocessed mode.
Chris Lattner057aaf62007-10-09 18:03:42 +0000386 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattnere96de3e2008-08-17 03:12:02 +0000387 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 // Otherwise, indent the appropriate number of spaces.
390 for (; ColNo > 1; --ColNo)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000391 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Chris Lattner5f180322007-12-09 21:11:08 +0000393 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000394}
395
Chris Lattner3ee211f2009-06-15 01:25:23 +0000396void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
397 unsigned Len) {
398 unsigned NumNewlines = 0;
399 for (; Len; --Len, ++TokStr) {
400 if (*TokStr != '\n' &&
401 *TokStr != '\r')
402 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Chris Lattner3ee211f2009-06-15 01:25:23 +0000404 ++NumNewlines;
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Chris Lattner3ee211f2009-06-15 01:25:23 +0000406 // If we have \n\r or \r\n, skip both and count as one line.
407 if (Len != 1 &&
408 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
409 TokStr[0] != TokStr[1])
410 ++TokStr, --Len;
411 }
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Chris Lattner3ee211f2009-06-15 01:25:23 +0000413 if (NumNewlines == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Chris Lattnered2d7c42009-06-15 04:08:28 +0000415 CurLine += NumNewlines;
Chris Lattner3ee211f2009-06-15 01:25:23 +0000416}
417
418
Reid Spencer5f016e22007-07-11 17:01:13 +0000419namespace {
420struct UnknownPragmaHandler : public PragmaHandler {
421 const char *Prefix;
422 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000425 : Prefix(prefix), Callbacks(callbacks) {}
Douglas Gregor80c60f72010-09-09 22:45:38 +0000426 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
427 Token &PragmaTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000428 // Figure out what line we went to and insert the appropriate number of
429 // newline characters.
Douglas Gregorfe6834a2010-09-10 22:27:29 +0000430 Callbacks->StartNewLineIfNeeded();
Reid Spencer5f016e22007-07-11 17:01:13 +0000431 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattnere96de3e2008-08-17 03:12:02 +0000432 Callbacks->OS.write(Prefix, strlen(Prefix));
Douglas Gregor80c60f72010-09-09 22:45:38 +0000433 Callbacks->SetEmittedTokensOnThisLine();
Reid Spencer5f016e22007-07-11 17:01:13 +0000434 // Read and print all of the pragma tokens.
Chris Lattner057aaf62007-10-09 18:03:42 +0000435 while (PragmaTok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000436 if (PragmaTok.hasLeadingSpace())
Chris Lattnere96de3e2008-08-17 03:12:02 +0000437 Callbacks->OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000438 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000439 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000440 PP.LexUnexpandedToken(PragmaTok);
441 }
Douglas Gregor80c60f72010-09-09 22:45:38 +0000442 Callbacks->StartNewLineIfNeeded();
Reid Spencer5f016e22007-07-11 17:01:13 +0000443 }
444};
445} // end anonymous namespace
446
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000447
Chris Lattner59076ab2009-02-06 05:56:11 +0000448static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
449 PrintPPOutputPPCallbacks *Callbacks,
450 llvm::raw_ostream &OS) {
Benjamin Kramere3960072010-02-27 18:02:51 +0000451 char Buffer[256];
Chris Lattnerc54539c2010-06-15 21:06:38 +0000452 Token PrevPrevTok, PrevTok;
453 PrevPrevTok.startToken();
454 PrevTok.startToken();
Chris Lattner6f688e12007-10-10 20:45:16 +0000455 while (1) {
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Reid Spencer5f016e22007-07-11 17:01:13 +0000457 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner5f180322007-12-09 21:11:08 +0000458 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
459 // done.
Mike Stump1eb44332009-09-09 15:08:12 +0000460 } else if (Tok.hasLeadingSpace() ||
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000461 // If we haven't emitted a token on this line yet, PrevTok isn't
462 // useful to look at and no concatenation could happen anyway.
Chris Lattnerb638a302007-07-23 23:21:34 +0000463 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000464 // Don't print "-" next to "-", it would form "--".
Chris Lattner88773212010-04-14 03:57:19 +0000465 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattnere96de3e2008-08-17 03:12:02 +0000466 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 }
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Benjamin Kramere3960072010-02-27 18:02:51 +0000469 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
470 OS << II->getName();
471 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
472 Tok.getLiteralData()) {
473 OS.write(Tok.getLiteralData(), Tok.getLength());
474 } else if (Tok.getLength() < 256) {
475 const char *TokPtr = Buffer;
476 unsigned Len = PP.getSpelling(Tok, TokPtr);
477 OS.write(TokPtr, Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Benjamin Kramere3960072010-02-27 18:02:51 +0000479 // Tokens that can contain embedded newlines need to adjust our current
480 // line number.
481 if (Tok.getKind() == tok::comment)
482 Callbacks->HandleNewlinesInToken(TokPtr, Len);
483 } else {
484 std::string S = PP.getSpelling(Tok);
485 OS.write(&S[0], S.size());
486
487 // Tokens that can contain embedded newlines need to adjust our current
488 // line number.
489 if (Tok.getKind() == tok::comment)
490 Callbacks->HandleNewlinesInToken(&S[0], S.size());
491 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 Callbacks->SetEmittedTokensOnThisLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Chris Lattner6f688e12007-10-10 20:45:16 +0000494 if (Tok.is(tok::eof)) break;
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Chris Lattner88773212010-04-14 03:57:19 +0000496 PrevPrevTok = PrevTok;
Chris Lattner6f688e12007-10-10 20:45:16 +0000497 PrevTok = Tok;
498 PP.Lex(Tok);
499 }
Chris Lattner59076ab2009-02-06 05:56:11 +0000500}
501
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000502typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
503static int MacroIDCompare(const void* a, const void* b) {
504 const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
505 const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
506 return LHS->first->getName().compare(RHS->first->getName());
Chris Lattner2a2bb182009-02-10 22:28:19 +0000507}
Chris Lattner59076ab2009-02-06 05:56:11 +0000508
Daniel Dunbar775bee72009-11-11 10:07:22 +0000509static void DoPrintMacros(Preprocessor &PP, llvm::raw_ostream *OS) {
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000510 // Ignore unknown pragmas.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000511 PP.AddPragmaHandler(new EmptyPragmaHandler());
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000512
Eli Friedmanf1db5852009-05-19 01:32:34 +0000513 // -dM mode just scans and ignores all tokens in the files, then dumps out
514 // the macro table at the end.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000515 PP.EnterMainSourceFile();
Eli Friedmanf1db5852009-05-19 01:32:34 +0000516
517 Token Tok;
518 do PP.Lex(Tok);
519 while (Tok.isNot(tok::eof));
520
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000521 llvm::SmallVector<id_macro_pair, 128>
522 MacrosByID(PP.macro_begin(), PP.macro_end());
523 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedmanf1db5852009-05-19 01:32:34 +0000524
525 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
526 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000527 // Ignore computed macros like __LINE__ and friends.
Eli Friedmanf1db5852009-05-19 01:32:34 +0000528 if (MI.isBuiltinMacro()) continue;
529
530 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000531 *OS << '\n';
Eli Friedmanf1db5852009-05-19 01:32:34 +0000532 }
533}
534
Chris Lattner59076ab2009-02-06 05:56:11 +0000535/// DoPrintPreprocessedInput - This implements -E mode.
536///
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000537void clang::DoPrintPreprocessedInput(Preprocessor &PP, llvm::raw_ostream *OS,
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000538 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar775bee72009-11-11 10:07:22 +0000539 // Show macros with no output is handled specially.
540 if (!Opts.ShowCPP) {
541 assert(Opts.ShowMacros && "Not yet implemented!");
542 DoPrintMacros(PP, OS);
543 return;
544 }
545
Chris Lattner59076ab2009-02-06 05:56:11 +0000546 // Inform the preprocessor whether we want it to retain comments or not, due
547 // to -C or -CC.
Daniel Dunbar775bee72009-11-11 10:07:22 +0000548 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanf54fce82009-05-19 01:02:07 +0000549
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000550 PrintPPOutputPPCallbacks *Callbacks =
Daniel Dunbar775bee72009-11-11 10:07:22 +0000551 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
Daniel Dunbareef63e02011-02-02 15:41:17 +0000552 Opts.ShowMacros);
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000553 PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
Chris Lattner13973992010-11-10 01:00:49 +0000554 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
555 PP.AddPragmaHandler("clang",
556 new UnknownPragmaHandler("#pragma clang", Callbacks));
Chris Lattner59076ab2009-02-06 05:56:11 +0000557
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000558 PP.addPPCallbacks(Callbacks);
Chris Lattner59076ab2009-02-06 05:56:11 +0000559
Eli Friedmanf1db5852009-05-19 01:32:34 +0000560 // After we have configured the preprocessor, enter the main file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000561 PP.EnterMainSourceFile();
Chris Lattner59076ab2009-02-06 05:56:11 +0000562
Eli Friedmanf1db5852009-05-19 01:32:34 +0000563 // Consume all of the tokens that come from the predefines buffer. Those
564 // should not be emitted into the output and are guaranteed to be at the
565 // start.
566 const SourceManager &SourceMgr = PP.getSourceManager();
567 Token Tok;
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000568 do {
569 PP.Lex(Tok);
570 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
571 break;
572
573 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
574 if (PLoc.isInvalid())
575 break;
576
577 if (strcmp(PLoc.getFilename(), "<built-in>"))
578 break;
579 } while (true);
Chris Lattner59076ab2009-02-06 05:56:11 +0000580
Eli Friedmanf1db5852009-05-19 01:32:34 +0000581 // Read all the preprocessed tokens, printing them out to the stream.
582 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
583 *OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000584}