blob: a64f6e7c0c694b783ac1a76cd88109661c4920a0 [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 Lattnerf46be6c2006-07-04 22:19:33 +000026#include "llvm/Config/config.h"
Chris Lattnerb5a92f82008-08-17 01:47:12 +000027#include "llvm/Support/raw_ostream.h"
Chris Lattnerdeb37012006-07-04 19:24:06 +000028#include <cstdio>
Chris Lattner09e3cdf2006-07-04 19:04:05 +000029using namespace clang;
30
Chris Lattnercac63f32009-04-12 01:56:53 +000031/// PrintMacroDefinition - Print a macro definition in a form that will be
32/// properly accepted back as a definition.
33static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
34 Preprocessor &PP, llvm::raw_ostream &OS) {
35 OS << "#define " << II.getName();
Mike Stump11289f42009-09-09 15:08:12 +000036
Chris Lattnercac63f32009-04-12 01:56:53 +000037 if (MI.isFunctionLike()) {
38 OS << '(';
Chris Lattner53d80e22009-12-09 02:08:14 +000039 if (!MI.arg_empty()) {
Chris Lattnercac63f32009-04-12 01:56:53 +000040 MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
Chris Lattner53d80e22009-12-09 02:08:14 +000041 for (; AI+1 != E; ++AI) {
42 OS << (*AI)->getName();
Chris Lattner9dfed9f2009-12-07 01:58:34 +000043 OS << ',';
Chris Lattner9dfed9f2009-12-07 01:58:34 +000044 }
Chris Lattner53d80e22009-12-09 02:08:14 +000045
46 // Last argument.
47 if ((*AI)->getName() == "__VA_ARGS__")
48 OS << "...";
49 else
50 OS << (*AI)->getName();
Chris Lattnercac63f32009-04-12 01:56:53 +000051 }
Mike Stump11289f42009-09-09 15:08:12 +000052
Chris Lattner9dfed9f2009-12-07 01:58:34 +000053 if (MI.isGNUVarargs())
54 OS << "..."; // #define foo(x...)
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +000055
Chris Lattnercac63f32009-04-12 01:56:53 +000056 OS << ')';
57 }
Mike Stump11289f42009-09-09 15:08:12 +000058
Chris Lattnercac63f32009-04-12 01:56:53 +000059 // GCC always emits a space, even if the macro body is empty. However, do not
60 // want to emit two spaces if the first token has a leading space.
61 if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
62 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +000063
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000064 llvm::SmallString<128> SpellingBuffer;
Chris Lattnercac63f32009-04-12 01:56:53 +000065 for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end();
66 I != E; ++I) {
67 if (I->hasLeadingSpace())
68 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +000069
Benjamin Kramer0a1abd42010-02-27 13:44:12 +000070 OS << PP.getSpelling(*I, SpellingBuffer);
Chris Lattnercac63f32009-04-12 01:56:53 +000071 }
72}
73
Chris Lattnerf46be6c2006-07-04 22:19:33 +000074//===----------------------------------------------------------------------===//
75// Preprocessed token printer
76//===----------------------------------------------------------------------===//
77
Chris Lattner87f267e2006-11-21 05:02:33 +000078namespace {
79class PrintPPOutputPPCallbacks : public PPCallbacks {
80 Preprocessor &PP;
Chris Lattner9d94f042010-04-13 00:06:42 +000081 SourceManager &SM;
Chris Lattner644d4522009-02-13 00:46:04 +000082 TokenConcatenation ConcatInfo;
Chris Lattner068529a2008-08-17 03:12:02 +000083public:
84 llvm::raw_ostream &OS;
85private:
Chris Lattner87f267e2006-11-21 05:02:33 +000086 unsigned CurLine;
Chris Lattner87f267e2006-11-21 05:02:33 +000087 bool EmittedTokensOnThisLine;
Eli Friedmanfd80b2a2009-06-02 07:55:39 +000088 bool EmittedMacroOnThisLine;
Chris Lattner66a740e2008-10-27 01:19:25 +000089 SrcMgr::CharacteristicKind FileType;
Chris Lattner4c4a2452007-07-24 06:57:14 +000090 llvm::SmallString<512> CurFilename;
Daniel Dunbar98e0e532008-09-05 03:22:57 +000091 bool Initialized;
Eli Friedman6af494b2009-05-19 03:06:47 +000092 bool DisableLineMarkers;
93 bool DumpDefines;
Chris Lattner76b44452009-12-07 01:42:56 +000094 bool UseLineDirective;
Chris Lattner87f267e2006-11-21 05:02:33 +000095public:
Eli Friedman6af494b2009-05-19 03:06:47 +000096 PrintPPOutputPPCallbacks(Preprocessor &pp, llvm::raw_ostream &os,
97 bool lineMarkers, bool defines)
Chris Lattner9d94f042010-04-13 00:06:42 +000098 : PP(pp), SM(PP.getSourceManager()),
99 ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
Eli Friedman6af494b2009-05-19 03:06:47 +0000100 DumpDefines(defines) {
Chris Lattner87f267e2006-11-21 05:02:33 +0000101 CurLine = 0;
Chris Lattner4c4a2452007-07-24 06:57:14 +0000102 CurFilename += "<uninit>";
Chris Lattner87f267e2006-11-21 05:02:33 +0000103 EmittedTokensOnThisLine = false;
Eli Friedmanfd80b2a2009-06-02 07:55:39 +0000104 EmittedMacroOnThisLine = false;
Chris Lattnerb03dc762008-09-26 21:18:42 +0000105 FileType = SrcMgr::C_User;
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000106 Initialized = false;
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +0000107
Chris Lattner76b44452009-12-07 01:42:56 +0000108 // If we're in microsoft mode, use normal #line instead of line markers.
109 UseLineDirective = PP.getLangOptions().Microsoft;
Chris Lattner87f267e2006-11-21 05:02:33 +0000110 }
Mike Stump11289f42009-09-09 15:08:12 +0000111
Chris Lattner87f267e2006-11-21 05:02:33 +0000112 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattner4418ce12007-07-23 06:09:34 +0000113 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Mike Stump11289f42009-09-09 15:08:12 +0000114
Chris Lattner87f267e2006-11-21 05:02:33 +0000115 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
Chris Lattner66a740e2008-10-27 01:19:25 +0000116 SrcMgr::CharacteristicKind FileType);
Chris Lattner87f267e2006-11-21 05:02:33 +0000117 virtual void Ident(SourceLocation Loc, const std::string &str);
Mike Stump11289f42009-09-09 15:08:12 +0000118 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
Chris Lattner5eef5072009-01-16 19:25:54 +0000119 const std::string &Str);
120
Chris Lattner87f267e2006-11-21 05:02:33 +0000121
Chris Lattner3ed83c12007-12-09 21:11:08 +0000122 bool HandleFirstTokOnLine(Token &Tok);
Chris Lattner5dbefc62010-04-13 00:01:41 +0000123 bool MoveToLine(SourceLocation Loc) {
Chris Lattner9d94f042010-04-13 00:06:42 +0000124 return MoveToLine(SM.getPresumedLoc(Loc).getLine());
Chris Lattner5dbefc62010-04-13 00:01:41 +0000125 }
126 bool MoveToLine(unsigned LineNo);
127
Chris Lattner644d4522009-02-13 00:46:04 +0000128 bool AvoidConcat(const Token &PrevTok, const Token &Tok) {
129 return ConcatInfo.AvoidConcat(PrevTok, Tok);
130 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000131 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
Mike Stump11289f42009-09-09 15:08:12 +0000132
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000133 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump11289f42009-09-09 15:08:12 +0000134
Chris Lattnercac63f32009-04-12 01:56:53 +0000135 /// MacroDefined - This hook is called whenever a macro definition is seen.
136 void MacroDefined(const IdentifierInfo *II, const MacroInfo *MI);
Mike Stump11289f42009-09-09 15:08:12 +0000137
Chris Lattner87f267e2006-11-21 05:02:33 +0000138};
Chris Lattner21632652008-04-08 04:16:20 +0000139} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000140
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000141void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
142 const char *Extra,
143 unsigned ExtraLen) {
Eli Friedmanfd80b2a2009-06-02 07:55:39 +0000144 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000145 OS << '\n';
146 EmittedTokensOnThisLine = false;
Eli Friedmanfd80b2a2009-06-02 07:55:39 +0000147 EmittedMacroOnThisLine = false;
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000148 }
149
Chris Lattner76b44452009-12-07 01:42:56 +0000150 // Emit #line directives or GNU line markers depending on what mode we're in.
151 if (UseLineDirective) {
152 OS << "#line" << ' ' << LineNo << ' ' << '"';
153 OS.write(&CurFilename[0], CurFilename.size());
154 OS << '"';
155 } else {
156 OS << '#' << ' ' << LineNo << ' ' << '"';
157 OS.write(&CurFilename[0], CurFilename.size());
158 OS << '"';
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +0000159
Steve Naroff66aaa392009-12-06 01:02:14 +0000160 if (ExtraLen)
161 OS.write(Extra, ExtraLen);
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000162
Steve Naroff66aaa392009-12-06 01:02:14 +0000163 if (FileType == SrcMgr::C_System)
164 OS.write(" 3", 2);
165 else if (FileType == SrcMgr::C_ExternCSystem)
166 OS.write(" 3 4", 4);
167 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000168 OS << '\n';
169}
170
Chris Lattner728b4dc2006-07-04 21:28:37 +0000171/// MoveToLine - Move the output to the source line specified by the location
172/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner3ed83c12007-12-09 21:11:08 +0000173/// #line directive. This returns false if already at the specified line, true
174/// if some newlines were emitted.
Chris Lattner5dbefc62010-04-13 00:01:41 +0000175bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000176 if (DisableLineMarkers) {
Chris Lattner3ed83c12007-12-09 21:11:08 +0000177 if (LineNo == CurLine) return false;
Mike Stump11289f42009-09-09 15:08:12 +0000178
Chris Lattner3ed83c12007-12-09 21:11:08 +0000179 CurLine = LineNo;
Mike Stump11289f42009-09-09 15:08:12 +0000180
Eli Friedmanfd80b2a2009-06-02 07:55:39 +0000181 if (!EmittedTokensOnThisLine && !EmittedMacroOnThisLine)
Chris Lattner3ed83c12007-12-09 21:11:08 +0000182 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000183
Chris Lattner068529a2008-08-17 03:12:02 +0000184 OS << '\n';
Chris Lattner3ed83c12007-12-09 21:11:08 +0000185 EmittedTokensOnThisLine = false;
Eli Friedmanfd80b2a2009-06-02 07:55:39 +0000186 EmittedMacroOnThisLine = false;
Chris Lattner3ed83c12007-12-09 21:11:08 +0000187 return true;
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000188 }
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000189
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000190 // If this line is "close enough" to the original line, just print newlines,
191 // otherwise print a #line directive.
Daniel Dunbare7781312008-09-26 01:13:35 +0000192 if (LineNo-CurLine <= 8) {
Chris Lattner5f075822007-07-23 05:14:05 +0000193 if (LineNo-CurLine == 1)
Chris Lattner068529a2008-08-17 03:12:02 +0000194 OS << '\n';
Chris Lattner3ed83c12007-12-09 21:11:08 +0000195 else if (LineNo == CurLine)
Chris Lattner8a425862009-01-16 07:36:28 +0000196 return false; // Spelling line moved, but instantiation line didn't.
Chris Lattner5f075822007-07-23 05:14:05 +0000197 else {
198 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattner068529a2008-08-17 03:12:02 +0000199 OS.write(NewLines, LineNo-CurLine);
Chris Lattner5f075822007-07-23 05:14:05 +0000200 }
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000201 } else {
Daniel Dunbar98e0e532008-09-05 03:22:57 +0000202 WriteLineInfo(LineNo, 0, 0);
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);
221 unsigned NewLine = UserLoc.getLine()+1;
222
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
286
Chris Lattner5eef5072009-01-16 19:25:54 +0000287void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000288 const IdentifierInfo *Kind,
Chris Lattner5eef5072009-01-16 19:25:54 +0000289 const std::string &Str) {
290 MoveToLine(Loc);
291 OS << "#pragma comment(" << Kind->getName();
Mike Stump11289f42009-09-09 15:08:12 +0000292
Chris Lattner5eef5072009-01-16 19:25:54 +0000293 if (!Str.empty()) {
294 OS << ", \"";
Mike Stump11289f42009-09-09 15:08:12 +0000295
Chris Lattner5eef5072009-01-16 19:25:54 +0000296 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
297 unsigned char Char = Str[i];
Chris Lattnerdde6eb32009-01-16 22:13:37 +0000298 if (isprint(Char) && Char != '\\' && Char != '"')
Chris Lattner5eef5072009-01-16 19:25:54 +0000299 OS << (char)Char;
300 else // Output anything hard as an octal escape.
301 OS << '\\'
302 << (char)('0'+ ((Char >> 6) & 7))
303 << (char)('0'+ ((Char >> 3) & 7))
304 << (char)('0'+ ((Char >> 0) & 7));
305 }
306 OS << '"';
307 }
Mike Stump11289f42009-09-09 15:08:12 +0000308
Chris Lattner5eef5072009-01-16 19:25:54 +0000309 OS << ')';
310 EmittedTokensOnThisLine = true;
311}
312
313
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000314/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner3ed83c12007-12-09 21:11:08 +0000315/// is called for the first token on each new line. If this really is the start
316/// of a new logical line, handle it and return true, otherwise return false.
317/// This may not be the start of a logical line because the "start of line"
Chris Lattner8a425862009-01-16 07:36:28 +0000318/// marker is set for spelling lines, not instantiation ones.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000319bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000320 // Figure out what line we went to and insert the appropriate number of
321 // newline characters.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000322 if (!MoveToLine(Tok.getLocation()))
323 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000324
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000325 // Print out space characters so that the first token on a line is
326 // indented for easy reading.
Chris Lattner9d94f042010-04-13 00:06:42 +0000327 unsigned ColNo = SM.getInstantiationColumnNumber(Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000328
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000329 // This hack prevents stuff like:
330 // #define HASH #
331 // HASH define foo bar
332 // From having the # character end up at column 1, which makes it so it
333 // is not handled as a #define next time through the preprocessor if in
334 // -fpreprocessed mode.
Chris Lattner3c69f122007-10-09 18:03:42 +0000335 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattner068529a2008-08-17 03:12:02 +0000336 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000337
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000338 // Otherwise, indent the appropriate number of spaces.
339 for (; ColNo > 1; --ColNo)
Chris Lattner068529a2008-08-17 03:12:02 +0000340 OS << ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000341
Chris Lattner3ed83c12007-12-09 21:11:08 +0000342 return true;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000343}
344
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000345void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
346 unsigned Len) {
347 unsigned NumNewlines = 0;
348 for (; Len; --Len, ++TokStr) {
349 if (*TokStr != '\n' &&
350 *TokStr != '\r')
351 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000352
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000353 ++NumNewlines;
Mike Stump11289f42009-09-09 15:08:12 +0000354
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000355 // If we have \n\r or \r\n, skip both and count as one line.
356 if (Len != 1 &&
357 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
358 TokStr[0] != TokStr[1])
359 ++TokStr, --Len;
360 }
Mike Stump11289f42009-09-09 15:08:12 +0000361
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000362 if (NumNewlines == 0) return;
Mike Stump11289f42009-09-09 15:08:12 +0000363
Chris Lattnera5e67752009-06-15 04:08:28 +0000364 CurLine += NumNewlines;
Chris Lattnerf2d49da92009-06-15 01:25:23 +0000365}
366
367
Chris Lattner5de858c2006-07-04 19:04:44 +0000368namespace {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000369struct UnknownPragmaHandler : public PragmaHandler {
370 const char *Prefix;
Chris Lattner87f267e2006-11-21 05:02:33 +0000371 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump11289f42009-09-09 15:08:12 +0000372
Chris Lattner87f267e2006-11-21 05:02:33 +0000373 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
374 : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
Chris Lattner146762e2007-07-20 16:59:19 +0000375 virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000376 // Figure out what line we went to and insert the appropriate number of
377 // newline characters.
Chris Lattner87f267e2006-11-21 05:02:33 +0000378 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattner068529a2008-08-17 03:12:02 +0000379 Callbacks->OS.write(Prefix, strlen(Prefix));
Mike Stump11289f42009-09-09 15:08:12 +0000380
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000381 // Read and print all of the pragma tokens.
Chris Lattner3c69f122007-10-09 18:03:42 +0000382 while (PragmaTok.isNot(tok::eom)) {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000383 if (PragmaTok.hasLeadingSpace())
Chris Lattner068529a2008-08-17 03:12:02 +0000384 Callbacks->OS << ' ';
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000385 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattner068529a2008-08-17 03:12:02 +0000386 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000387 PP.LexUnexpandedToken(PragmaTok);
388 }
Chris Lattner068529a2008-08-17 03:12:02 +0000389 Callbacks->OS << '\n';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000390 }
391};
Chris Lattner5de858c2006-07-04 19:04:44 +0000392} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000393
Chris Lattner4418ce12007-07-23 06:09:34 +0000394
Chris Lattnerfc001b02009-02-06 05:56:11 +0000395static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
396 PrintPPOutputPPCallbacks *Callbacks,
397 llvm::raw_ostream &OS) {
Benjamin Kramer718f7222010-02-27 18:02:51 +0000398 char Buffer[256];
Chris Lattnerfc001b02009-02-06 05:56:11 +0000399 Token PrevTok;
Chris Lattner3ff2e692007-10-10 20:45:16 +0000400 while (1) {
Mike Stump11289f42009-09-09 15:08:12 +0000401
Chris Lattner67c38482006-07-04 23:24:26 +0000402 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner3ed83c12007-12-09 21:11:08 +0000403 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
404 // done.
Mike Stump11289f42009-09-09 15:08:12 +0000405 } else if (Tok.hasLeadingSpace() ||
Chris Lattner4418ce12007-07-23 06:09:34 +0000406 // If we haven't emitted a token on this line yet, PrevTok isn't
407 // useful to look at and no concatenation could happen anyway.
Chris Lattnerd63c8a52007-07-23 23:21:34 +0000408 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattner4418ce12007-07-23 06:09:34 +0000409 // Don't print "-" next to "-", it would form "--".
410 Callbacks->AvoidConcat(PrevTok, Tok))) {
Chris Lattner068529a2008-08-17 03:12:02 +0000411 OS << ' ';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000412 }
Mike Stump11289f42009-09-09 15:08:12 +0000413
Benjamin Kramer718f7222010-02-27 18:02:51 +0000414 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
415 OS << II->getName();
416 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
417 Tok.getLiteralData()) {
418 OS.write(Tok.getLiteralData(), Tok.getLength());
419 } else if (Tok.getLength() < 256) {
420 const char *TokPtr = Buffer;
421 unsigned Len = PP.getSpelling(Tok, TokPtr);
422 OS.write(TokPtr, Len);
Mike Stump11289f42009-09-09 15:08:12 +0000423
Benjamin Kramer718f7222010-02-27 18:02:51 +0000424 // Tokens that can contain embedded newlines need to adjust our current
425 // line number.
426 if (Tok.getKind() == tok::comment)
427 Callbacks->HandleNewlinesInToken(TokPtr, Len);
428 } else {
429 std::string S = PP.getSpelling(Tok);
430 OS.write(&S[0], S.size());
431
432 // Tokens that can contain embedded newlines need to adjust our current
433 // line number.
434 if (Tok.getKind() == tok::comment)
435 Callbacks->HandleNewlinesInToken(&S[0], S.size());
436 }
Chris Lattner87f267e2006-11-21 05:02:33 +0000437 Callbacks->SetEmittedTokensOnThisLine();
Mike Stump11289f42009-09-09 15:08:12 +0000438
Chris Lattner3ff2e692007-10-10 20:45:16 +0000439 if (Tok.is(tok::eof)) break;
Mike Stump11289f42009-09-09 15:08:12 +0000440
Chris Lattner3ff2e692007-10-10 20:45:16 +0000441 PrevTok = Tok;
442 PP.Lex(Tok);
443 }
Chris Lattnerfc001b02009-02-06 05:56:11 +0000444}
445
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +0000446typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
447static int MacroIDCompare(const void* a, const void* b) {
448 const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
449 const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
450 return LHS->first->getName().compare(RHS->first->getName());
Chris Lattner1ec246d2009-02-10 22:28:19 +0000451}
Chris Lattnerfc001b02009-02-06 05:56:11 +0000452
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000453static void DoPrintMacros(Preprocessor &PP, llvm::raw_ostream *OS) {
Eli Friedman26c672b2009-05-19 01:32:34 +0000454 // -dM mode just scans and ignores all tokens in the files, then dumps out
455 // the macro table at the end.
Douglas Gregor4ad3da22010-03-17 15:44:30 +0000456 if (PP.EnterMainSourceFile())
457 return;
Eli Friedman26c672b2009-05-19 01:32:34 +0000458
459 Token Tok;
460 do PP.Lex(Tok);
461 while (Tok.isNot(tok::eof));
462
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +0000463 llvm::SmallVector<id_macro_pair, 128>
464 MacrosByID(PP.macro_begin(), PP.macro_end());
465 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedman26c672b2009-05-19 01:32:34 +0000466
467 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
468 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000469 // Ignore computed macros like __LINE__ and friends.
Eli Friedman26c672b2009-05-19 01:32:34 +0000470 if (MI.isBuiltinMacro()) continue;
471
472 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramerfb5f40f2010-01-19 17:42:20 +0000473 *OS << '\n';
Eli Friedman26c672b2009-05-19 01:32:34 +0000474 }
475}
476
Chris Lattnerfc001b02009-02-06 05:56:11 +0000477/// DoPrintPreprocessedInput - This implements -E mode.
478///
Eli Friedman6af494b2009-05-19 03:06:47 +0000479void clang::DoPrintPreprocessedInput(Preprocessor &PP, llvm::raw_ostream *OS,
Daniel Dunbar22bdabf2009-11-11 10:07:44 +0000480 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000481 // Show macros with no output is handled specially.
482 if (!Opts.ShowCPP) {
483 assert(Opts.ShowMacros && "Not yet implemented!");
484 DoPrintMacros(PP, OS);
485 return;
486 }
487
Chris Lattnerfc001b02009-02-06 05:56:11 +0000488 // Inform the preprocessor whether we want it to retain comments or not, due
489 // to -C or -CC.
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000490 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanfcb57d52009-05-19 01:02:07 +0000491
492 OS->SetBufferSize(64*1024);
Chris Lattnercac63f32009-04-12 01:56:53 +0000493
Eli Friedman6af494b2009-05-19 03:06:47 +0000494 PrintPPOutputPPCallbacks *Callbacks =
Daniel Dunbar531f6c62009-11-11 10:07:22 +0000495 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
496 Opts.ShowMacros);
Eli Friedman26c672b2009-05-19 01:32:34 +0000497 PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
498 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",
499 Callbacks));
Chris Lattnerfc001b02009-02-06 05:56:11 +0000500
Kovarththanan Rajaratnam752a1242010-03-07 07:30:06 +0000501 PP.addPPCallbacks(Callbacks);
Chris Lattnerfc001b02009-02-06 05:56:11 +0000502
Eli Friedman26c672b2009-05-19 01:32:34 +0000503 // After we have configured the preprocessor, enter the main file.
Douglas Gregor4ad3da22010-03-17 15:44:30 +0000504 if (PP.EnterMainSourceFile())
505 return;
Chris Lattnerfc001b02009-02-06 05:56:11 +0000506
Eli Friedman26c672b2009-05-19 01:32:34 +0000507 // Consume all of the tokens that come from the predefines buffer. Those
508 // should not be emitted into the output and are guaranteed to be at the
509 // start.
510 const SourceManager &SourceMgr = PP.getSourceManager();
511 Token Tok;
512 do PP.Lex(Tok);
513 while (Tok.isNot(tok::eof) && Tok.getLocation().isFileID() &&
514 !strcmp(SourceMgr.getPresumedLoc(Tok.getLocation()).getFilename(),
515 "<built-in>"));
Chris Lattnerfc001b02009-02-06 05:56:11 +0000516
Eli Friedman26c672b2009-05-19 01:32:34 +0000517 // Read all the preprocessed tokens, printing them out to the stream.
518 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
519 *OS << '\n';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000520}
521