blob: 43b64b218696b776411907258ae936c550e3cdbc [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;
Eli Friedman3e753e22009-06-02 07:55:39 +000090 bool EmittedMacroOnThisLine;
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;
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.
Francois Pichet62ec1f22011-09-17 17:15:52 +0000111 UseLineDirective = PP.getLangOptions().MicrosoftExt;
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,
Argyrios Kyrtzidisc892c5f2011-10-11 17:29:44 +0000120 SrcMgr::CharacteristicKind FileType,
121 FileID PrevFID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 virtual void Ident(SourceLocation Loc, const std::string &str);
Mike Stump1eb44332009-09-09 15:08:12 +0000123 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000124 const std::string &Str);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000125 virtual void PragmaMessage(SourceLocation Loc, StringRef Str);
Douglas Gregorc09ce122011-06-22 19:41:48 +0000126 virtual void PragmaDiagnosticPush(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 StringRef Namespace);
Douglas Gregorc09ce122011-06-22 19:41:48 +0000128 virtual void PragmaDiagnosticPop(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000129 StringRef Namespace);
130 virtual void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
Benjamin Kramerfdd15602012-02-04 13:02:15 +0000131 unsigned Map, StringRef Str);
Reid Spencer5f016e22007-07-11 17:01:13 +0000132
Chris Lattner5f180322007-12-09 21:11:08 +0000133 bool HandleFirstTokOnLine(Token &Tok);
Chris Lattner88aae912010-04-13 00:01:41 +0000134 bool MoveToLine(SourceLocation Loc) {
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000135 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
136 if (PLoc.isInvalid())
137 return false;
138 return MoveToLine(PLoc.getLine());
Chris Lattner88aae912010-04-13 00:01:41 +0000139 }
140 bool MoveToLine(unsigned LineNo);
141
Chris Lattner88773212010-04-14 03:57:19 +0000142 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
143 const Token &Tok) {
144 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
Chris Lattnerd7038e12009-02-13 00:46:04 +0000145 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000146 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
Douglas Gregor80c60f72010-09-09 22:45:38 +0000147 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
Chris Lattner3ee211f2009-06-15 01:25:23 +0000148 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000150 /// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein2aa92672010-11-19 21:33:15 +0000151 void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Benjamin Kramer2f054492010-08-07 22:27:00 +0000153 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
Craig Silverstein2aa92672010-11-19 21:33:15 +0000154 void MacroUndefined(const Token &MacroNameTok, const MacroInfo *MI);
Reid Spencer5f016e22007-07-11 17:01:13 +0000155};
Chris Lattner5db17c92008-04-08 04:16:20 +0000156} // end anonymous namespace
Reid Spencer5f016e22007-07-11 17:01:13 +0000157
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000158void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
159 const char *Extra,
160 unsigned ExtraLen) {
Eli Friedman3e753e22009-06-02 07:55:39 +0000161 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000162 OS << '\n';
163 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000164 EmittedMacroOnThisLine = false;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000165 }
166
Chris Lattnerf7449342009-12-07 01:42:56 +0000167 // Emit #line directives or GNU line markers depending on what mode we're in.
168 if (UseLineDirective) {
169 OS << "#line" << ' ' << LineNo << ' ' << '"';
Ted Kremenek23465132010-09-17 00:41:18 +0000170 OS.write(CurFilename.data(), CurFilename.size());
Chris Lattnerf7449342009-12-07 01:42:56 +0000171 OS << '"';
172 } else {
173 OS << '#' << ' ' << LineNo << ' ' << '"';
Ted Kremenek23465132010-09-17 00:41:18 +0000174 OS.write(CurFilename.data(), CurFilename.size());
Chris Lattnerf7449342009-12-07 01:42:56 +0000175 OS << '"';
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000176
Steve Naroffd76fbda2009-12-06 01:02:14 +0000177 if (ExtraLen)
178 OS.write(Extra, ExtraLen);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000179
Steve Naroffd76fbda2009-12-06 01:02:14 +0000180 if (FileType == SrcMgr::C_System)
181 OS.write(" 3", 2);
182 else if (FileType == SrcMgr::C_ExternCSystem)
183 OS.write(" 3 4", 4);
184 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000185 OS << '\n';
186}
187
Reid Spencer5f016e22007-07-11 17:01:13 +0000188/// MoveToLine - Move the output to the source line specified by the location
189/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner5f180322007-12-09 21:11:08 +0000190/// #line directive. This returns false if already at the specified line, true
191/// if some newlines were emitted.
Chris Lattner88aae912010-04-13 00:01:41 +0000192bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000193 // If this line is "close enough" to the original line, just print newlines,
194 // otherwise print a #line directive.
Daniel Dunbarfd966842008-09-26 01:13:35 +0000195 if (LineNo-CurLine <= 8) {
Chris Lattner822f9402007-07-23 05:14:05 +0000196 if (LineNo-CurLine == 1)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000197 OS << '\n';
Chris Lattner5f180322007-12-09 21:11:08 +0000198 else if (LineNo == CurLine)
Chandler Carruth9f79a1f2011-07-14 16:14:52 +0000199 return false; // Spelling line moved, but expansion line didn't.
Chris Lattner822f9402007-07-23 05:14:05 +0000200 else {
201 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattnere96de3e2008-08-17 03:12:02 +0000202 OS.write(NewLines, LineNo-CurLine);
Chris Lattner822f9402007-07-23 05:14:05 +0000203 }
Chris Lattner6133aeb2010-06-12 16:20:56 +0000204 } else if (!DisableLineMarkers) {
205 // Emit a #line or line marker.
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000206 WriteLineInfo(LineNo, 0, 0);
Chris Lattner6133aeb2010-06-12 16:20:56 +0000207 } else {
208 // Okay, we're in -P mode, which turns off line markers. However, we still
209 // need to emit a newline between tokens on different lines.
210 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
211 OS << '\n';
212 EmittedTokensOnThisLine = false;
213 EmittedMacroOnThisLine = false;
214 }
Mike Stump1eb44332009-09-09 15:08:12 +0000215 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000216
Mike Stump1eb44332009-09-09 15:08:12 +0000217 CurLine = LineNo;
Chris Lattner5f180322007-12-09 21:11:08 +0000218 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000219}
220
Douglas Gregor80c60f72010-09-09 22:45:38 +0000221bool PrintPPOutputPPCallbacks::StartNewLineIfNeeded() {
222 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
223 OS << '\n';
224 EmittedTokensOnThisLine = false;
225 EmittedMacroOnThisLine = false;
226 ++CurLine;
227 return true;
228 }
229
230 return false;
231}
Reid Spencer5f016e22007-07-11 17:01:13 +0000232
233/// FileChanged - Whenever the preprocessor enters or exits a #include file
234/// it invokes this handler. Update our conception of the current source
235/// position.
236void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
237 FileChangeReason Reason,
Argyrios Kyrtzidisc892c5f2011-10-11 17:29:44 +0000238 SrcMgr::CharacteristicKind NewFileType,
239 FileID PrevFID) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000240 // Unless we are exiting a #include, make sure to skip ahead to the line the
241 // #include directive was at.
Chris Lattnerdf721402010-04-13 00:06:42 +0000242 SourceManager &SourceMgr = SM;
Chris Lattner88aae912010-04-13 00:01:41 +0000243
244 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000245 if (UserLoc.isInvalid())
246 return;
247
Chris Lattner86d0ef72010-04-14 04:28:50 +0000248 unsigned NewLine = UserLoc.getLine();
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000249
Reid Spencer5f016e22007-07-11 17:01:13 +0000250 if (Reason == PPCallbacks::EnterFile) {
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000251 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
Chris Lattner71d8bfb2009-01-30 18:44:17 +0000252 if (IncludeLoc.isValid())
253 MoveToLine(IncludeLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000254 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
Chris Lattner88aae912010-04-13 00:01:41 +0000255 MoveToLine(NewLine);
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Reid Spencer5f016e22007-07-11 17:01:13 +0000257 // TODO GCC emits the # directive for this directive on the line AFTER the
258 // directive and emits a bunch of spaces that aren't needed. Emulate this
259 // strange behavior.
260 }
Chris Lattner88aae912010-04-13 00:01:41 +0000261
262 CurLine = NewLine;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000263
Chris Lattnerd8e30832007-07-24 06:57:14 +0000264 CurFilename.clear();
Chris Lattner88aae912010-04-13 00:01:41 +0000265 CurFilename += UserLoc.getFilename();
Chris Lattnerd8e30832007-07-24 06:57:14 +0000266 Lexer::Stringify(CurFilename);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000267 FileType = NewFileType;
268
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000269 if (DisableLineMarkers) return;
270
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000271 if (!Initialized) {
272 WriteLineInfo(CurLine);
273 Initialized = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000275
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 switch (Reason) {
277 case PPCallbacks::EnterFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000278 WriteLineInfo(CurLine, " 1", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 break;
280 case PPCallbacks::ExitFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000281 WriteLineInfo(CurLine, " 2", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000282 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000283 case PPCallbacks::SystemHeaderPragma:
284 case PPCallbacks::RenameFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000285 WriteLineInfo(CurLine);
286 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000287 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000288}
289
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000290/// Ident - Handle #ident directives when read by the preprocessor.
Reid Spencer5f016e22007-07-11 17:01:13 +0000291///
292void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
293 MoveToLine(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Chris Lattnere96de3e2008-08-17 03:12:02 +0000295 OS.write("#ident ", strlen("#ident "));
296 OS.write(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 EmittedTokensOnThisLine = true;
298}
299
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000300/// MacroDefined - This hook is called whenever a macro definition is seen.
Craig Silverstein2aa92672010-11-19 21:33:15 +0000301void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000302 const MacroInfo *MI) {
303 // Only print out macro definitions in -dD mode.
304 if (!DumpDefines ||
305 // Ignore __FILE__ etc.
306 MI->isBuiltinMacro()) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000307
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000308 MoveToLine(MI->getDefinitionLoc());
Craig Silverstein2aa92672010-11-19 21:33:15 +0000309 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
Eli Friedman3e753e22009-06-02 07:55:39 +0000310 EmittedMacroOnThisLine = true;
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000311}
312
Craig Silverstein2aa92672010-11-19 21:33:15 +0000313void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
Benjamin Kramer2f054492010-08-07 22:27:00 +0000314 const MacroInfo *MI) {
315 // Only print out macro definitions in -dD mode.
316 if (!DumpDefines) return;
317
Craig Silverstein2aa92672010-11-19 21:33:15 +0000318 MoveToLine(MacroNameTok.getLocation());
319 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
Benjamin Kramer2f054492010-08-07 22:27:00 +0000320 EmittedMacroOnThisLine = true;
321}
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000322
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000323void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000324 const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000325 const std::string &Str) {
326 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 << ')';
346 EmittedTokensOnThisLine = true;
347}
348
Chris Lattnerabfe0942010-06-26 17:11:39 +0000349void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000350 StringRef Str) {
Chris Lattnerabfe0942010-06-26 17:11:39 +0000351 MoveToLine(Loc);
352 OS << "#pragma message(";
353
354 OS << '"';
355
356 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
357 unsigned char Char = Str[i];
358 if (isprint(Char) && Char != '\\' && Char != '"')
359 OS << (char)Char;
360 else // Output anything hard as an octal escape.
361 OS << '\\'
362 << (char)('0'+ ((Char >> 6) & 7))
363 << (char)('0'+ ((Char >> 3) & 7))
364 << (char)('0'+ ((Char >> 0) & 7));
365 }
366 OS << '"';
367
368 OS << ')';
369 EmittedTokensOnThisLine = true;
370}
371
Douglas Gregorc09ce122011-06-22 19:41:48 +0000372void PrintPPOutputPPCallbacks::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000373PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
Douglas Gregorc09ce122011-06-22 19:41:48 +0000374 MoveToLine(Loc);
375 OS << "#pragma " << Namespace << " diagnostic push";
376 EmittedTokensOnThisLine = true;
377}
378
379void PrintPPOutputPPCallbacks::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000380PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
Douglas Gregorc09ce122011-06-22 19:41:48 +0000381 MoveToLine(Loc);
382 OS << "#pragma " << Namespace << " diagnostic pop";
383 EmittedTokensOnThisLine = true;
384}
385
386void PrintPPOutputPPCallbacks::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000387PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
Benjamin Kramerfdd15602012-02-04 13:02:15 +0000388 unsigned Map, StringRef Str) {
Douglas Gregorc09ce122011-06-22 19:41:48 +0000389 MoveToLine(Loc);
390 OS << "#pragma " << Namespace << " diagnostic ";
Benjamin Kramerfdd15602012-02-04 13:02:15 +0000391 switch ((diag::Mapping)Map) {
Douglas Gregorc09ce122011-06-22 19:41:48 +0000392 case diag::MAP_WARNING:
393 OS << "warning";
394 break;
395 case diag::MAP_ERROR:
396 OS << "error";
397 break;
398 case diag::MAP_IGNORE:
399 OS << "ignored";
400 break;
401 case diag::MAP_FATAL:
402 OS << "fatal";
403 break;
404 }
405 OS << " \"" << Str << '"';
406 EmittedTokensOnThisLine = true;
407}
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000408
Reid Spencer5f016e22007-07-11 17:01:13 +0000409/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner5f180322007-12-09 21:11:08 +0000410/// is called for the first token on each new line. If this really is the start
411/// of a new logical line, handle it and return true, otherwise return false.
412/// This may not be the start of a logical line because the "start of line"
Chandler Carruth9f79a1f2011-07-14 16:14:52 +0000413/// marker is set for spelling lines, not expansion ones.
Chris Lattner5f180322007-12-09 21:11:08 +0000414bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 // Figure out what line we went to and insert the appropriate number of
416 // newline characters.
Chris Lattner5f180322007-12-09 21:11:08 +0000417 if (!MoveToLine(Tok.getLocation()))
418 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Reid Spencer5f016e22007-07-11 17:01:13 +0000420 // Print out space characters so that the first token on a line is
421 // indented for easy reading.
Chandler Carrutha77c0312011-07-25 20:57:57 +0000422 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 // This hack prevents stuff like:
425 // #define HASH #
426 // HASH define foo bar
427 // From having the # character end up at column 1, which makes it so it
428 // is not handled as a #define next time through the preprocessor if in
429 // -fpreprocessed mode.
Chris Lattner057aaf62007-10-09 18:03:42 +0000430 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattnere96de3e2008-08-17 03:12:02 +0000431 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 // Otherwise, indent the appropriate number of spaces.
434 for (; ColNo > 1; --ColNo)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000435 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Chris Lattner5f180322007-12-09 21:11:08 +0000437 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000438}
439
Chris Lattner3ee211f2009-06-15 01:25:23 +0000440void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
441 unsigned Len) {
442 unsigned NumNewlines = 0;
443 for (; Len; --Len, ++TokStr) {
444 if (*TokStr != '\n' &&
445 *TokStr != '\r')
446 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Chris Lattner3ee211f2009-06-15 01:25:23 +0000448 ++NumNewlines;
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Chris Lattner3ee211f2009-06-15 01:25:23 +0000450 // If we have \n\r or \r\n, skip both and count as one line.
451 if (Len != 1 &&
452 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
453 TokStr[0] != TokStr[1])
454 ++TokStr, --Len;
455 }
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Chris Lattner3ee211f2009-06-15 01:25:23 +0000457 if (NumNewlines == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Chris Lattnered2d7c42009-06-15 04:08:28 +0000459 CurLine += NumNewlines;
Chris Lattner3ee211f2009-06-15 01:25:23 +0000460}
461
462
Reid Spencer5f016e22007-07-11 17:01:13 +0000463namespace {
464struct UnknownPragmaHandler : public PragmaHandler {
465 const char *Prefix;
466 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Reid Spencer5f016e22007-07-11 17:01:13 +0000468 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000469 : Prefix(prefix), Callbacks(callbacks) {}
Douglas Gregor80c60f72010-09-09 22:45:38 +0000470 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
471 Token &PragmaTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 // Figure out what line we went to and insert the appropriate number of
473 // newline characters.
Douglas Gregorfe6834a2010-09-10 22:27:29 +0000474 Callbacks->StartNewLineIfNeeded();
Reid Spencer5f016e22007-07-11 17:01:13 +0000475 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattnere96de3e2008-08-17 03:12:02 +0000476 Callbacks->OS.write(Prefix, strlen(Prefix));
Douglas Gregor80c60f72010-09-09 22:45:38 +0000477 Callbacks->SetEmittedTokensOnThisLine();
Reid Spencer5f016e22007-07-11 17:01:13 +0000478 // Read and print all of the pragma tokens.
Peter Collingbourne84021552011-02-28 02:37:51 +0000479 while (PragmaTok.isNot(tok::eod)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000480 if (PragmaTok.hasLeadingSpace())
Chris Lattnere96de3e2008-08-17 03:12:02 +0000481 Callbacks->OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000482 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000483 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 PP.LexUnexpandedToken(PragmaTok);
485 }
Douglas Gregor80c60f72010-09-09 22:45:38 +0000486 Callbacks->StartNewLineIfNeeded();
Reid Spencer5f016e22007-07-11 17:01:13 +0000487 }
488};
489} // end anonymous namespace
490
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000491
Chris Lattner59076ab2009-02-06 05:56:11 +0000492static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
493 PrintPPOutputPPCallbacks *Callbacks,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000494 raw_ostream &OS) {
Benjamin Kramere3960072010-02-27 18:02:51 +0000495 char Buffer[256];
Chris Lattnerc54539c2010-06-15 21:06:38 +0000496 Token PrevPrevTok, PrevTok;
497 PrevPrevTok.startToken();
498 PrevTok.startToken();
Chris Lattner6f688e12007-10-10 20:45:16 +0000499 while (1) {
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner5f180322007-12-09 21:11:08 +0000502 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
503 // done.
Mike Stump1eb44332009-09-09 15:08:12 +0000504 } else if (Tok.hasLeadingSpace() ||
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000505 // If we haven't emitted a token on this line yet, PrevTok isn't
506 // useful to look at and no concatenation could happen anyway.
Chris Lattnerb638a302007-07-23 23:21:34 +0000507 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000508 // Don't print "-" next to "-", it would form "--".
Chris Lattner88773212010-04-14 03:57:19 +0000509 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattnere96de3e2008-08-17 03:12:02 +0000510 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000511 }
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Benjamin Kramere3960072010-02-27 18:02:51 +0000513 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
514 OS << II->getName();
515 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
516 Tok.getLiteralData()) {
517 OS.write(Tok.getLiteralData(), Tok.getLength());
518 } else if (Tok.getLength() < 256) {
519 const char *TokPtr = Buffer;
520 unsigned Len = PP.getSpelling(Tok, TokPtr);
521 OS.write(TokPtr, Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Benjamin Kramere3960072010-02-27 18:02:51 +0000523 // Tokens that can contain embedded newlines need to adjust our current
524 // line number.
525 if (Tok.getKind() == tok::comment)
526 Callbacks->HandleNewlinesInToken(TokPtr, Len);
527 } else {
528 std::string S = PP.getSpelling(Tok);
529 OS.write(&S[0], S.size());
530
531 // Tokens that can contain embedded newlines need to adjust our current
532 // line number.
533 if (Tok.getKind() == tok::comment)
534 Callbacks->HandleNewlinesInToken(&S[0], S.size());
535 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000536 Callbacks->SetEmittedTokensOnThisLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Chris Lattner6f688e12007-10-10 20:45:16 +0000538 if (Tok.is(tok::eof)) break;
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Chris Lattner88773212010-04-14 03:57:19 +0000540 PrevPrevTok = PrevTok;
Chris Lattner6f688e12007-10-10 20:45:16 +0000541 PrevTok = Tok;
542 PP.Lex(Tok);
543 }
Chris Lattner59076ab2009-02-06 05:56:11 +0000544}
545
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000546typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
547static int MacroIDCompare(const void* a, const void* b) {
548 const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
549 const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
550 return LHS->first->getName().compare(RHS->first->getName());
Chris Lattner2a2bb182009-02-10 22:28:19 +0000551}
Chris Lattner59076ab2009-02-06 05:56:11 +0000552
Chris Lattner5f9e2722011-07-23 10:55:15 +0000553static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000554 // Ignore unknown pragmas.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000555 PP.AddPragmaHandler(new EmptyPragmaHandler());
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000556
Eli Friedmanf1db5852009-05-19 01:32:34 +0000557 // -dM mode just scans and ignores all tokens in the files, then dumps out
558 // the macro table at the end.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000559 PP.EnterMainSourceFile();
Eli Friedmanf1db5852009-05-19 01:32:34 +0000560
561 Token Tok;
562 do PP.Lex(Tok);
563 while (Tok.isNot(tok::eof));
564
Chris Lattner5f9e2722011-07-23 10:55:15 +0000565 SmallVector<id_macro_pair, 128>
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000566 MacrosByID(PP.macro_begin(), PP.macro_end());
567 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedmanf1db5852009-05-19 01:32:34 +0000568
569 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
570 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000571 // Ignore computed macros like __LINE__ and friends.
Eli Friedmanf1db5852009-05-19 01:32:34 +0000572 if (MI.isBuiltinMacro()) continue;
573
574 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000575 *OS << '\n';
Eli Friedmanf1db5852009-05-19 01:32:34 +0000576 }
577}
578
Chris Lattner59076ab2009-02-06 05:56:11 +0000579/// DoPrintPreprocessedInput - This implements -E mode.
580///
Chris Lattner5f9e2722011-07-23 10:55:15 +0000581void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000582 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar775bee72009-11-11 10:07:22 +0000583 // Show macros with no output is handled specially.
584 if (!Opts.ShowCPP) {
585 assert(Opts.ShowMacros && "Not yet implemented!");
586 DoPrintMacros(PP, OS);
587 return;
588 }
589
Chris Lattner59076ab2009-02-06 05:56:11 +0000590 // Inform the preprocessor whether we want it to retain comments or not, due
591 // to -C or -CC.
Daniel Dunbar775bee72009-11-11 10:07:22 +0000592 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanf54fce82009-05-19 01:02:07 +0000593
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000594 PrintPPOutputPPCallbacks *Callbacks =
Daniel Dunbar775bee72009-11-11 10:07:22 +0000595 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
Daniel Dunbareef63e02011-02-02 15:41:17 +0000596 Opts.ShowMacros);
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000597 PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
Chris Lattner13973992010-11-10 01:00:49 +0000598 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
599 PP.AddPragmaHandler("clang",
600 new UnknownPragmaHandler("#pragma clang", Callbacks));
Chris Lattner59076ab2009-02-06 05:56:11 +0000601
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000602 PP.addPPCallbacks(Callbacks);
Chris Lattner59076ab2009-02-06 05:56:11 +0000603
Eli Friedmanf1db5852009-05-19 01:32:34 +0000604 // After we have configured the preprocessor, enter the main file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000605 PP.EnterMainSourceFile();
Chris Lattner59076ab2009-02-06 05:56:11 +0000606
Eli Friedmanf1db5852009-05-19 01:32:34 +0000607 // Consume all of the tokens that come from the predefines buffer. Those
608 // should not be emitted into the output and are guaranteed to be at the
609 // start.
610 const SourceManager &SourceMgr = PP.getSourceManager();
611 Token Tok;
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000612 do {
613 PP.Lex(Tok);
614 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
615 break;
616
617 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
618 if (PLoc.isInvalid())
619 break;
620
621 if (strcmp(PLoc.getFilename(), "<built-in>"))
622 break;
623 } while (true);
Chris Lattner59076ab2009-02-06 05:56:11 +0000624
Eli Friedmanf1db5852009-05-19 01:32:34 +0000625 // Read all the preprocessed tokens, printing them out to the stream.
626 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
627 *OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000628}