blob: e68fd583aa29ad6d92af09f16003e81ebd2d9b81 [file] [log] [blame]
Chris Lattner09e3cdf2006-07-04 19:04:05 +00001//===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner09e3cdf2006-07-04 19:04:05 +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 Friedman16b7b6f2009-05-19 04:14:29 +000015#include "clang/Frontend/Utils.h"
Daniel Dunbar531f6c62009-11-11 10:07:22 +000016#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/SourceManager.h"
18#include "clang/Frontend/PreprocessorOutputOptions.h"
Chris Lattner1630c3c2009-02-06 06:45:26 +000019#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000020#include "clang/Lex/PPCallbacks.h"
Chris Lattner09e3cdf2006-07-04 19:04:05 +000021#include "clang/Lex/Pragma.h"
Daniel Dunbar531f6c62009-11-11 10:07:22 +000022#include "clang/Lex/Preprocessor.h"
Chris Lattner644d4522009-02-13 00:46:04 +000023#include "clang/Lex/TokenConcatenation.h"
Chris Lattner4c4a2452007-07-24 06:57:14 +000024#include "llvm/ADT/SmallString.h"
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +000025#include "llvm/ADT/STLExtras.h"
Chris Lattner30c924b2010-06-26 17:11:39 +000026#include "llvm/ADT/StringRef.h"
Chris Lattnerf46be6c2006-07-04 22:19:33 +000027#include "llvm/Config/config.h"
Chris Lattnerb5a92f82008-08-17 01:47:12 +000028#include "llvm/Support/raw_ostream.h"
Chris Lattnerdeb37012006-07-04 19:24:06 +000029#include <cstdio>
Chris Lattner09e3cdf2006-07-04 19:04:05 +000030using namespace clang;
31
Chris Lattnercac63f32009-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 Stump11289f42009-09-09 15:08:12 +000037
Chris Lattnercac63f32009-04-12 01:56:53 +000038 if (MI.isFunctionLike()) {
39 OS << '(';
Chris Lattner53d80e22009-12-09 02:08:14 +000040 if (!MI.arg_empty()) {
Chris Lattnercac63f32009-04-12 01:56:53 +000041 MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
Chris Lattner53d80e22009-12-09 02:08:14 +000042 for (; AI+1 != E; ++AI) {
43 OS << (*AI)->getName();
Chris Lattner9dfed9f2009-12-07 01:58:34 +000044 OS << ',';
Chris Lattner9dfed9f2009-12-07 01:58:34 +000045 }
Chris Lattner53d80e22009-12-09 02:08:14 +000046
47 // Last argument.
48 if ((*AI)->getName() == "__VA_ARGS__")
49 OS << "...";
50 else
51 OS << (*AI)->getName();
Chris Lattnercac63f32009-04-12 01:56:53 +000052 }
Mike Stump11289f42009-09-09 15:08:12 +000053
Chris Lattner9dfed9f2009-12-07 01:58:34 +000054 if (MI.isGNUVarargs())
55 OS << "..."; // #define foo(x...)
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +000056
Chris Lattnercac63f32009-04-12 01:56:53 +000057 OS << ')';
58 }
Mike Stump11289f42009-09-09 15:08:12 +000059
Chris Lattnercac63f32009-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 Stump11289f42009-09-09 15:08:12 +000064
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000065 llvm::SmallString<128> SpellingBuffer;
Chris Lattnercac63f32009-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 Stump11289f42009-09-09 15:08:12 +000070
Benjamin Kramer0a1abd42010-02-27 13:44:12 +000071 OS << PP.getSpelling(*I, SpellingBuffer);
Chris Lattnercac63f32009-04-12 01:56:53 +000072 }
73}
74
Chris Lattnerf46be6c2006-07-04 22:19:33 +000075//===----------------------------------------------------------------------===//
76// Preprocessed token printer
77//===----------------------------------------------------------------------===//
78
Chris Lattner87f267e2006-11-21 05:02:33 +000079namespace {
80class PrintPPOutputPPCallbacks : public PPCallbacks {
81 Preprocessor &PP;
Chris Lattner9d94f042010-04-13 00:06:42 +000082 SourceManager &SM;
Chris Lattner644d4522009-02-13 00:46:04 +000083 TokenConcatenation ConcatInfo;
Chris Lattner068529a2008-08-17 03:12:02 +000084public:
85 llvm::raw_ostream &OS;
86private:
Chris Lattner87f267e2006-11-21 05:02:33 +000087 unsigned CurLine;
Chris Lattner87f267e2006-11-21 05:02:33 +000088 bool EmittedTokensOnThisLine;
Eli Friedmanfd80b2a2009-06-02 07:55:39 +000089 bool EmittedMacroOnThisLine;
Chris Lattner66a740e2008-10-27 01:19:25 +000090 SrcMgr::CharacteristicKind FileType;
Chris Lattner4c4a2452007-07-24 06:57:14 +000091 llvm::SmallString<512> CurFilename;
Daniel Dunbar98e0e532008-09-05 03:22:57 +000092 bool Initialized;
Eli Friedman6af494b2009-05-19 03:06:47 +000093 bool DisableLineMarkers;
94 bool DumpDefines;
Chris Lattner76b44452009-12-07 01:42:56 +000095 bool UseLineDirective;
Chris Lattner87f267e2006-11-21 05:02:33 +000096public:
Eli Friedman6af494b2009-05-19 03:06:47 +000097 PrintPPOutputPPCallbacks(Preprocessor &pp, llvm::raw_ostream &os,
98 bool lineMarkers, bool defines)
Chris Lattner9d94f042010-04-13 00:06:42 +000099 : PP(pp), SM(PP.getSourceManager()),
100 ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
Eli Friedman6af494b2009-05-19 03:06:47 +0000101 DumpDefines(defines) {
Chris Lattner87f267e2006-11-21 05:02:33 +0000102 CurLine = 0;
Chris Lattner4c4a2452007-07-24 06:57:14 +0000103 CurFilename += "<uninit>";
Chris Lattner87f267e2006-11-21 05:02:33 +0000104 EmittedTokensOnThisLine = false;
Eli Friedmanfd80b2a2009-06-02 07:55:39 +0000105 EmittedMacroOnThisLine = false;
Chris Lattnerb03dc762008-09-26 21:18:42 +0000106 FileType = SrcMgr::C_User;
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000107 Initialized = false;
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +0000108
Chris Lattner76b44452009-12-07 01:42:56 +0000109 // If we're in microsoft mode, use normal #line instead of line markers.
110 UseLineDirective = PP.getLangOptions().Microsoft;
Chris Lattner87f267e2006-11-21 05:02:33 +0000111 }
Mike Stump11289f42009-09-09 15:08:12 +0000112
Chris Lattner87f267e2006-11-21 05:02:33 +0000113 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattner4418ce12007-07-23 06:09:34 +0000114 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Mike Stump11289f42009-09-09 15:08:12 +0000115
Chris Lattner87f267e2006-11-21 05:02:33 +0000116 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
Chris Lattner66a740e2008-10-27 01:19:25 +0000117 SrcMgr::CharacteristicKind FileType);
Chris Lattner87f267e2006-11-21 05:02:33 +0000118 virtual void Ident(SourceLocation Loc, const std::string &str);
Mike Stump11289f42009-09-09 15:08:12 +0000119 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
Chris Lattner5eef5072009-01-16 19:25:54 +0000120 const std::string &Str);
Chris Lattner30c924b2010-06-26 17:11:39 +0000121 virtual void PragmaMessage(SourceLocation Loc, llvm::StringRef Str);
Chris Lattner87f267e2006-11-21 05:02:33 +0000122
Chris Lattner3ed83c12007-12-09 21:11:08 +0000123 bool HandleFirstTokOnLine(Token &Tok);
Chris Lattner5dbefc62010-04-13 00:01:41 +0000124 bool MoveToLine(SourceLocation Loc) {
Chris Lattner9d94f042010-04-13 00:06:42 +0000125 return MoveToLine(SM.getPresumedLoc(Loc).getLine());
Chris Lattner5dbefc62010-04-13 00:01:41 +0000126 }
127 bool MoveToLine(unsigned LineNo);
128
Chris Lattner0384e6352010-04-14 03:57:19 +0000129 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
130 const Token &Tok) {
131 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
Chris Lattner644d4522009-02-13 00:46:04 +0000132 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000133 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
Mike Stump11289f42009-09-09 15:08:12 +0000134
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000135 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump11289f42009-09-09 15:08:12 +0000136
Chris Lattnercac63f32009-04-12 01:56:53 +0000137 /// MacroDefined - This hook is called whenever a macro definition is seen.
138 void MacroDefined(const IdentifierInfo *II, const MacroInfo *MI);
Mike Stump11289f42009-09-09 15:08:12 +0000139
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000140 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
141 void MacroUndefined(SourceLocation Loc, const IdentifierInfo *II,
142 const MacroInfo *MI);
Chris Lattner87f267e2006-11-21 05:02:33 +0000143};
Chris Lattner21632652008-04-08 04:16:20 +0000144} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000145
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000146void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
147 const char *Extra,
148 unsigned ExtraLen) {
Eli Friedmanfd80b2a2009-06-02 07:55:39 +0000149 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000150 OS << '\n';
151 EmittedTokensOnThisLine = false;
Eli Friedmanfd80b2a2009-06-02 07:55:39 +0000152 EmittedMacroOnThisLine = false;
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000153 }
154
Chris Lattner76b44452009-12-07 01:42:56 +0000155 // Emit #line directives or GNU line markers depending on what mode we're in.
156 if (UseLineDirective) {
157 OS << "#line" << ' ' << LineNo << ' ' << '"';
158 OS.write(&CurFilename[0], CurFilename.size());
159 OS << '"';
160 } else {
161 OS << '#' << ' ' << LineNo << ' ' << '"';
162 OS.write(&CurFilename[0], CurFilename.size());
163 OS << '"';
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +0000164
Steve Naroff66aaa392009-12-06 01:02:14 +0000165 if (ExtraLen)
166 OS.write(Extra, ExtraLen);
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000167
Steve Naroff66aaa392009-12-06 01:02:14 +0000168 if (FileType == SrcMgr::C_System)
169 OS.write(" 3", 2);
170 else if (FileType == SrcMgr::C_ExternCSystem)
171 OS.write(" 3 4", 4);
172 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000173 OS << '\n';
174}
175
Chris Lattner728b4dc2006-07-04 21:28:37 +0000176/// MoveToLine - Move the output to the source line specified by the location
177/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner3ed83c12007-12-09 21:11:08 +0000178/// #line directive. This returns false if already at the specified line, true
179/// if some newlines were emitted.
Chris Lattner5dbefc62010-04-13 00:01:41 +0000180bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000181 // If this line is "close enough" to the original line, just print newlines,
182 // otherwise print a #line directive.
Daniel Dunbare7781312008-09-26 01:13:35 +0000183 if (LineNo-CurLine <= 8) {
Chris Lattner5f075822007-07-23 05:14:05 +0000184 if (LineNo-CurLine == 1)
Chris Lattner068529a2008-08-17 03:12:02 +0000185 OS << '\n';
Chris Lattner3ed83c12007-12-09 21:11:08 +0000186 else if (LineNo == CurLine)
Chris Lattner8a425862009-01-16 07:36:28 +0000187 return false; // Spelling line moved, but instantiation line didn't.
Chris Lattner5f075822007-07-23 05:14:05 +0000188 else {
189 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattner068529a2008-08-17 03:12:02 +0000190 OS.write(NewLines, LineNo-CurLine);
Chris Lattner5f075822007-07-23 05:14:05 +0000191 }
Chris Lattnerbc6bcab2010-06-12 16:20:56 +0000192 } else if (!DisableLineMarkers) {
193 // Emit a #line or line marker.
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000194 WriteLineInfo(LineNo, 0, 0);
Chris Lattnerbc6bcab2010-06-12 16:20:56 +0000195 } else {
196 // Okay, we're in -P mode, which turns off line markers. However, we still
197 // need to emit a newline between tokens on different lines.
198 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
199 OS << '\n';
200 EmittedTokensOnThisLine = false;
201 EmittedMacroOnThisLine = false;
202 }
Mike Stump11289f42009-09-09 15:08:12 +0000203 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000204
Mike Stump11289f42009-09-09 15:08:12 +0000205 CurLine = LineNo;
Chris Lattner3ed83c12007-12-09 21:11:08 +0000206 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000207}
208
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000209
210/// FileChanged - Whenever the preprocessor enters or exits a #include file
211/// it invokes this handler. Update our conception of the current source
212/// position.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000213void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
214 FileChangeReason Reason,
Chris Lattner66a740e2008-10-27 01:19:25 +0000215 SrcMgr::CharacteristicKind NewFileType) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000216 // Unless we are exiting a #include, make sure to skip ahead to the line the
217 // #include directive was at.
Chris Lattner9d94f042010-04-13 00:06:42 +0000218 SourceManager &SourceMgr = SM;
Chris Lattner5dbefc62010-04-13 00:01:41 +0000219
220 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Chris Lattnerc745cec2010-04-14 04:28:50 +0000221 unsigned NewLine = UserLoc.getLine();
Chris Lattner5dbefc62010-04-13 00:01:41 +0000222
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000223 if (Reason == PPCallbacks::EnterFile) {
Chris Lattnerd8cc8842009-01-30 18:44:17 +0000224 SourceLocation IncludeLoc = SourceMgr.getPresumedLoc(Loc).getIncludeLoc();
225 if (IncludeLoc.isValid())
226 MoveToLine(IncludeLoc);
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000227 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
Chris Lattner5dbefc62010-04-13 00:01:41 +0000228 MoveToLine(NewLine);
Mike Stump11289f42009-09-09 15:08:12 +0000229
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000230 // TODO GCC emits the # directive for this directive on the line AFTER the
231 // directive and emits a bunch of spaces that aren't needed. Emulate this
232 // strange behavior.
233 }
Chris Lattner5dbefc62010-04-13 00:01:41 +0000234
235 CurLine = NewLine;
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000236
Chris Lattner3ed83c12007-12-09 21:11:08 +0000237 if (DisableLineMarkers) return;
238
Chris Lattner4c4a2452007-07-24 06:57:14 +0000239 CurFilename.clear();
Chris Lattner5dbefc62010-04-13 00:01:41 +0000240 CurFilename += UserLoc.getFilename();
Chris Lattner4c4a2452007-07-24 06:57:14 +0000241 Lexer::Stringify(CurFilename);
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000242 FileType = NewFileType;
243
244 if (!Initialized) {
245 WriteLineInfo(CurLine);
246 Initialized = true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000247 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000248
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000249 switch (Reason) {
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000250 case PPCallbacks::EnterFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000251 WriteLineInfo(CurLine, " 1", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000252 break;
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000253 case PPCallbacks::ExitFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000254 WriteLineInfo(CurLine, " 2", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000255 break;
Mike Stump11289f42009-09-09 15:08:12 +0000256 case PPCallbacks::SystemHeaderPragma:
257 case PPCallbacks::RenameFile:
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000258 WriteLineInfo(CurLine);
259 break;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000260 }
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000261}
262
Chris Lattner5eef5072009-01-16 19:25:54 +0000263/// Ident - Handle #ident directives when read by the preprocessor.
Chris Lattner728b4dc2006-07-04 21:28:37 +0000264///
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000265void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
Chris Lattner3338ba82006-07-04 21:19:39 +0000266 MoveToLine(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000267
Chris Lattner068529a2008-08-17 03:12:02 +0000268 OS.write("#ident ", strlen("#ident "));
269 OS.write(&S[0], S.size());
Chris Lattner87f267e2006-11-21 05:02:33 +0000270 EmittedTokensOnThisLine = true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000271}
272
Chris Lattnercac63f32009-04-12 01:56:53 +0000273/// MacroDefined - This hook is called whenever a macro definition is seen.
274void PrintPPOutputPPCallbacks::MacroDefined(const IdentifierInfo *II,
275 const MacroInfo *MI) {
276 // Only print out macro definitions in -dD mode.
277 if (!DumpDefines ||
278 // Ignore __FILE__ etc.
279 MI->isBuiltinMacro()) return;
Mike Stump11289f42009-09-09 15:08:12 +0000280
Chris Lattnercac63f32009-04-12 01:56:53 +0000281 MoveToLine(MI->getDefinitionLoc());
282 PrintMacroDefinition(*II, *MI, PP, OS);
Eli Friedmanfd80b2a2009-06-02 07:55:39 +0000283 EmittedMacroOnThisLine = true;
Chris Lattnercac63f32009-04-12 01:56:53 +0000284}
285
Benjamin Kramerd05f31d2010-08-07 22:27:00 +0000286void PrintPPOutputPPCallbacks::MacroUndefined(SourceLocation Loc,
287 const IdentifierInfo *II,
288 const MacroInfo *MI) {
289 // Only print out macro definitions in -dD mode.
290 if (!DumpDefines) return;
291
292 MoveToLine(Loc);
293 OS << "#undef " << II->getName();
294 EmittedMacroOnThisLine = true;
295}
Chris Lattnercac63f32009-04-12 01:56:53 +0000296
Chris Lattner5eef5072009-01-16 19:25:54 +0000297void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000298 const IdentifierInfo *Kind,
Chris Lattner5eef5072009-01-16 19:25:54 +0000299 const std::string &Str) {
300 MoveToLine(Loc);
301 OS << "#pragma comment(" << Kind->getName();
Mike Stump11289f42009-09-09 15:08:12 +0000302
Chris Lattner5eef5072009-01-16 19:25:54 +0000303 if (!Str.empty()) {
304 OS << ", \"";
Mike Stump11289f42009-09-09 15:08:12 +0000305
Chris Lattner5eef5072009-01-16 19:25:54 +0000306 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
307 unsigned char Char = Str[i];
Chris Lattnerdde6eb32009-01-16 22:13:37 +0000308 if (isprint(Char) && Char != '\\' && Char != '"')
Chris Lattner5eef5072009-01-16 19:25:54 +0000309 OS << (char)Char;
310 else // Output anything hard as an octal escape.
311 OS << '\\'
312 << (char)('0'+ ((Char >> 6) & 7))
313 << (char)('0'+ ((Char >> 3) & 7))
314 << (char)('0'+ ((Char >> 0) & 7));
315 }
316 OS << '"';
317 }
Mike Stump11289f42009-09-09 15:08:12 +0000318
Chris Lattner5eef5072009-01-16 19:25:54 +0000319 OS << ')';
320 EmittedTokensOnThisLine = true;
321}
322
Chris Lattner30c924b2010-06-26 17:11:39 +0000323void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
324 llvm::StringRef Str) {
325 MoveToLine(Loc);
326 OS << "#pragma message(";
327
328 OS << '"';
329
330 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
331 unsigned char Char = Str[i];
332 if (isprint(Char) && Char != '\\' && Char != '"')
333 OS << (char)Char;
334 else // Output anything hard as an octal escape.
335 OS << '\\'
336 << (char)('0'+ ((Char >> 6) & 7))
337 << (char)('0'+ ((Char >> 3) & 7))
338 << (char)('0'+ ((Char >> 0) & 7));
339 }
340 OS << '"';
341
342 OS << ')';
343 EmittedTokensOnThisLine = true;
344}
345
Chris Lattner5eef5072009-01-16 19:25:54 +0000346
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000347/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner3ed83c12007-12-09 21:11:08 +0000348/// is called for the first token on each new line. If this really is the start
349/// of a new logical line, handle it and return true, otherwise return false.
350/// This may not be the start of a logical line because the "start of line"
Chris Lattner8a425862009-01-16 07:36:28 +0000351/// marker is set for spelling lines, not instantiation ones.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000352bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000353 // Figure out what line we went to and insert the appropriate number of
354 // newline characters.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000355 if (!MoveToLine(Tok.getLocation()))
356 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000357
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000358 // Print out space characters so that the first token on a line is
359 // indented for easy reading.
Chris Lattner9d94f042010-04-13 00:06:42 +0000360 unsigned ColNo = SM.getInstantiationColumnNumber(Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000361
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000362 // This hack prevents stuff like:
363 // #define HASH #
364 // HASH define foo bar
365 // From having the # character end up at column 1, which makes it so it
366 // is not handled as a #define next time through the preprocessor if in
367 // -fpreprocessed mode.
Chris Lattner3c69f122007-10-09 18:03:42 +0000368 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattner068529a2008-08-17 03:12:02 +0000369 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000370
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000371 // Otherwise, indent the appropriate number of spaces.
372 for (; ColNo > 1; --ColNo)
Chris Lattner068529a2008-08-17 03:12:02 +0000373 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000374
Chris Lattner3ed83c12007-12-09 21:11:08 +0000375 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000376}
377
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000378void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
379 unsigned Len) {
380 unsigned NumNewlines = 0;
381 for (; Len; --Len, ++TokStr) {
382 if (*TokStr != '\n' &&
383 *TokStr != '\r')
384 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000385
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000386 ++NumNewlines;
Mike Stump11289f42009-09-09 15:08:12 +0000387
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000388 // If we have \n\r or \r\n, skip both and count as one line.
389 if (Len != 1 &&
390 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
391 TokStr[0] != TokStr[1])
392 ++TokStr, --Len;
393 }
Mike Stump11289f42009-09-09 15:08:12 +0000394
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000395 if (NumNewlines == 0) return;
Mike Stump11289f42009-09-09 15:08:12 +0000396
Chris Lattnera5e67752009-06-15 04:08:28 +0000397 CurLine += NumNewlines;
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000398}
399
400
Chris Lattner5de858c2006-07-04 19:04:44 +0000401namespace {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000402struct UnknownPragmaHandler : public PragmaHandler {
403 const char *Prefix;
Chris Lattner87f267e2006-11-21 05:02:33 +0000404 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump11289f42009-09-09 15:08:12 +0000405
Chris Lattner87f267e2006-11-21 05:02:33 +0000406 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000407 : Prefix(prefix), Callbacks(callbacks) {}
Chris Lattner146762e2007-07-20 16:59:19 +0000408 virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000409 // Figure out what line we went to and insert the appropriate number of
410 // newline characters.
Chris Lattner87f267e2006-11-21 05:02:33 +0000411 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattner068529a2008-08-17 03:12:02 +0000412 Callbacks->OS.write(Prefix, strlen(Prefix));
Mike Stump11289f42009-09-09 15:08:12 +0000413
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000414 // Read and print all of the pragma tokens.
Chris Lattner3c69f122007-10-09 18:03:42 +0000415 while (PragmaTok.isNot(tok::eom)) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000416 if (PragmaTok.hasLeadingSpace())
Chris Lattner068529a2008-08-17 03:12:02 +0000417 Callbacks->OS << ' ';
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000418 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattner068529a2008-08-17 03:12:02 +0000419 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000420 PP.LexUnexpandedToken(PragmaTok);
421 }
Chris Lattner068529a2008-08-17 03:12:02 +0000422 Callbacks->OS << '\n';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000423 }
424};
Chris Lattner5de858c2006-07-04 19:04:44 +0000425} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000426
Chris Lattner4418ce12007-07-23 06:09:34 +0000427
Chris Lattnerfc001b02009-02-06 05:56:11 +0000428static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
429 PrintPPOutputPPCallbacks *Callbacks,
430 llvm::raw_ostream &OS) {
Benjamin Kramer718f7222010-02-27 18:02:51 +0000431 char Buffer[256];
Chris Lattnerbba37f42010-06-15 21:06:38 +0000432 Token PrevPrevTok, PrevTok;
433 PrevPrevTok.startToken();
434 PrevTok.startToken();
Chris Lattner3ff2e692007-10-10 20:45:16 +0000435 while (1) {
Mike Stump11289f42009-09-09 15:08:12 +0000436
Chris Lattner67c38482006-07-04 23:24:26 +0000437 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000438 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
439 // done.
Mike Stump11289f42009-09-09 15:08:12 +0000440 } else if (Tok.hasLeadingSpace() ||
Chris Lattner4418ce12007-07-23 06:09:34 +0000441 // If we haven't emitted a token on this line yet, PrevTok isn't
442 // useful to look at and no concatenation could happen anyway.
Chris Lattnerd63c8a52007-07-23 23:21:34 +0000443 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattner4418ce12007-07-23 06:09:34 +0000444 // Don't print "-" next to "-", it would form "--".
Chris Lattner0384e6352010-04-14 03:57:19 +0000445 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattner068529a2008-08-17 03:12:02 +0000446 OS << ' ';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000447 }
Mike Stump11289f42009-09-09 15:08:12 +0000448
Benjamin Kramer718f7222010-02-27 18:02:51 +0000449 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
450 OS << II->getName();
451 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
452 Tok.getLiteralData()) {
453 OS.write(Tok.getLiteralData(), Tok.getLength());
454 } else if (Tok.getLength() < 256) {
455 const char *TokPtr = Buffer;
456 unsigned Len = PP.getSpelling(Tok, TokPtr);
457 OS.write(TokPtr, Len);
Mike Stump11289f42009-09-09 15:08:12 +0000458
Benjamin Kramer718f7222010-02-27 18:02:51 +0000459 // Tokens that can contain embedded newlines need to adjust our current
460 // line number.
461 if (Tok.getKind() == tok::comment)
462 Callbacks->HandleNewlinesInToken(TokPtr, Len);
463 } else {
464 std::string S = PP.getSpelling(Tok);
465 OS.write(&S[0], S.size());
466
467 // Tokens that can contain embedded newlines need to adjust our current
468 // line number.
469 if (Tok.getKind() == tok::comment)
470 Callbacks->HandleNewlinesInToken(&S[0], S.size());
471 }
Chris Lattner87f267e2006-11-21 05:02:33 +0000472 Callbacks->SetEmittedTokensOnThisLine();
Mike Stump11289f42009-09-09 15:08:12 +0000473
Chris Lattner3ff2e692007-10-10 20:45:16 +0000474 if (Tok.is(tok::eof)) break;
Mike Stump11289f42009-09-09 15:08:12 +0000475
Chris Lattner0384e6352010-04-14 03:57:19 +0000476 PrevPrevTok = PrevTok;
Chris Lattner3ff2e692007-10-10 20:45:16 +0000477 PrevTok = Tok;
478 PP.Lex(Tok);
479 }
Chris Lattnerfc001b02009-02-06 05:56:11 +0000480}
481
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +0000482typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
483static int MacroIDCompare(const void* a, const void* b) {
484 const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
485 const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
486 return LHS->first->getName().compare(RHS->first->getName());
Chris Lattner1ec246d2009-02-10 22:28:19 +0000487}
Chris Lattnerfc001b02009-02-06 05:56:11 +0000488
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000489static void DoPrintMacros(Preprocessor &PP, llvm::raw_ostream *OS) {
Daniel Dunbard839e772010-06-11 20:10:12 +0000490 // Ignore unknown pragmas.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000491 PP.AddPragmaHandler(new EmptyPragmaHandler());
Daniel Dunbard839e772010-06-11 20:10:12 +0000492
Eli Friedman26c672b2009-05-19 01:32:34 +0000493 // -dM mode just scans and ignores all tokens in the files, then dumps out
494 // the macro table at the end.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000495 PP.EnterMainSourceFile();
Eli Friedman26c672b2009-05-19 01:32:34 +0000496
497 Token Tok;
498 do PP.Lex(Tok);
499 while (Tok.isNot(tok::eof));
500
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +0000501 llvm::SmallVector<id_macro_pair, 128>
502 MacrosByID(PP.macro_begin(), PP.macro_end());
503 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedman26c672b2009-05-19 01:32:34 +0000504
505 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
506 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000507 // Ignore computed macros like __LINE__ and friends.
Eli Friedman26c672b2009-05-19 01:32:34 +0000508 if (MI.isBuiltinMacro()) continue;
509
510 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +0000511 *OS << '\n';
Eli Friedman26c672b2009-05-19 01:32:34 +0000512 }
513}
514
Chris Lattnerfc001b02009-02-06 05:56:11 +0000515/// DoPrintPreprocessedInput - This implements -E mode.
516///
Eli Friedman6af494b2009-05-19 03:06:47 +0000517void clang::DoPrintPreprocessedInput(Preprocessor &PP, llvm::raw_ostream *OS,
Daniel Dunbar22bdabf2009-11-11 10:07:44 +0000518 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000519 // Show macros with no output is handled specially.
520 if (!Opts.ShowCPP) {
521 assert(Opts.ShowMacros && "Not yet implemented!");
522 DoPrintMacros(PP, OS);
523 return;
524 }
525
Chris Lattnerfc001b02009-02-06 05:56:11 +0000526 // Inform the preprocessor whether we want it to retain comments or not, due
527 // to -C or -CC.
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000528 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanfcb57d52009-05-19 01:02:07 +0000529
Eli Friedman6af494b2009-05-19 03:06:47 +0000530 PrintPPOutputPPCallbacks *Callbacks =
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000531 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
532 Opts.ShowMacros);
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000533 PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
Eli Friedman26c672b2009-05-19 01:32:34 +0000534 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",
535 Callbacks));
Chris Lattnerfc001b02009-02-06 05:56:11 +0000536
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +0000537 PP.addPPCallbacks(Callbacks);
Chris Lattnerfc001b02009-02-06 05:56:11 +0000538
Eli Friedman26c672b2009-05-19 01:32:34 +0000539 // After we have configured the preprocessor, enter the main file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000540 PP.EnterMainSourceFile();
Chris Lattnerfc001b02009-02-06 05:56:11 +0000541
Eli Friedman26c672b2009-05-19 01:32:34 +0000542 // Consume all of the tokens that come from the predefines buffer. Those
543 // should not be emitted into the output and are guaranteed to be at the
544 // start.
545 const SourceManager &SourceMgr = PP.getSourceManager();
546 Token Tok;
547 do PP.Lex(Tok);
548 while (Tok.isNot(tok::eof) && Tok.getLocation().isFileID() &&
549 !strcmp(SourceMgr.getPresumedLoc(Tok.getLocation()).getFilename(),
550 "<built-in>"));
Chris Lattnerfc001b02009-02-06 05:56:11 +0000551
Eli Friedman26c672b2009-05-19 01:32:34 +0000552 // Read all the preprocessed tokens, printing them out to the stream.
553 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
554 *OS << '\n';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000555}
556