blob: 378cc05d34bad05b07ce2cdd46cb70c3b2ae2083 [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
Chris Lattnerd7038e12009-02-13 00:46:04 +000015#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang.h"
Chris Lattnerf73903a2009-02-06 06:45:26 +000017#include "clang/Lex/MacroInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/Lex/PPCallbacks.h"
19#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/Pragma.h"
Chris Lattnerd7038e12009-02-13 00:46:04 +000021#include "clang/Lex/TokenConcatenation.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner5db17c92008-04-08 04:16:20 +000023#include "clang/Basic/Diagnostic.h"
Chris Lattnerd8e30832007-07-24 06:57:14 +000024#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "llvm/ADT/StringExtras.h"
Chris Lattner5db17c92008-04-08 04:16:20 +000026#include "llvm/System/Path.h"
27#include "llvm/Support/CommandLine.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "llvm/Config/config.h"
Chris Lattnerdceb6a72008-08-17 01:47:12 +000029#include "llvm/Support/raw_ostream.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include <cstdio>
31using namespace clang;
32
Reid Spencer5f016e22007-07-11 17:01:13 +000033//===----------------------------------------------------------------------===//
34// Preprocessed token printer
35//===----------------------------------------------------------------------===//
36
37static llvm::cl::opt<bool>
38DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
39static llvm::cl::opt<bool>
40EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
41static llvm::cl::opt<bool>
42EnableMacroCommentOutput("CC",
43 llvm::cl::desc("Enable comment output in -E mode, "
44 "even from macro expansions"));
Chris Lattnerf73903a2009-02-06 06:45:26 +000045static llvm::cl::opt<bool>
46DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
47 " normal output"));
48
Reid Spencer5f016e22007-07-11 17:01:13 +000049
50namespace {
51class PrintPPOutputPPCallbacks : public PPCallbacks {
52 Preprocessor &PP;
Chris Lattnerd7038e12009-02-13 00:46:04 +000053 TokenConcatenation ConcatInfo;
Chris Lattnere96de3e2008-08-17 03:12:02 +000054public:
55 llvm::raw_ostream &OS;
56private:
Reid Spencer5f016e22007-07-11 17:01:13 +000057 unsigned CurLine;
Reid Spencer5f016e22007-07-11 17:01:13 +000058 bool EmittedTokensOnThisLine;
Chris Lattner9d728512008-10-27 01:19:25 +000059 SrcMgr::CharacteristicKind FileType;
Chris Lattnerd8e30832007-07-24 06:57:14 +000060 llvm::SmallString<512> CurFilename;
Daniel Dunbar737bdb42008-09-05 03:22:57 +000061 bool Initialized;
Reid Spencer5f016e22007-07-11 17:01:13 +000062public:
Chris Lattnere96de3e2008-08-17 03:12:02 +000063 PrintPPOutputPPCallbacks(Preprocessor &pp, llvm::raw_ostream &os)
Chris Lattnerd7038e12009-02-13 00:46:04 +000064 : PP(pp), ConcatInfo(PP), OS(os) {
Reid Spencer5f016e22007-07-11 17:01:13 +000065 CurLine = 0;
Chris Lattnerd8e30832007-07-24 06:57:14 +000066 CurFilename += "<uninit>";
Reid Spencer5f016e22007-07-11 17:01:13 +000067 EmittedTokensOnThisLine = false;
Chris Lattner0b9e7362008-09-26 21:18:42 +000068 FileType = SrcMgr::C_User;
Daniel Dunbar737bdb42008-09-05 03:22:57 +000069 Initialized = false;
Reid Spencer5f016e22007-07-11 17:01:13 +000070 }
71
72 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattnerf0f2b292007-07-23 06:09:34 +000073 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Reid Spencer5f016e22007-07-11 17:01:13 +000074
75 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +000076 SrcMgr::CharacteristicKind FileType);
Reid Spencer5f016e22007-07-11 17:01:13 +000077 virtual void Ident(SourceLocation Loc, const std::string &str);
Chris Lattnerc7d945d2009-01-16 19:25:54 +000078 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
79 const std::string &Str);
80
Reid Spencer5f016e22007-07-11 17:01:13 +000081
Chris Lattner5f180322007-12-09 21:11:08 +000082 bool HandleFirstTokOnLine(Token &Tok);
83 bool MoveToLine(SourceLocation Loc);
Chris Lattnerd7038e12009-02-13 00:46:04 +000084 bool AvoidConcat(const Token &PrevTok, const Token &Tok) {
85 return ConcatInfo.AvoidConcat(PrevTok, Tok);
86 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +000087 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
Reid Spencer5f016e22007-07-11 17:01:13 +000088};
Chris Lattner5db17c92008-04-08 04:16:20 +000089} // end anonymous namespace
Reid Spencer5f016e22007-07-11 17:01:13 +000090
Daniel Dunbar737bdb42008-09-05 03:22:57 +000091void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
92 const char *Extra,
93 unsigned ExtraLen) {
94 if (EmittedTokensOnThisLine) {
95 OS << '\n';
96 EmittedTokensOnThisLine = false;
97 }
98
99 OS << '#' << ' ' << LineNo << ' ' << '"';
100 OS.write(&CurFilename[0], CurFilename.size());
101 OS << '"';
102
103 if (ExtraLen)
104 OS.write(Extra, ExtraLen);
105
Chris Lattner0b9e7362008-09-26 21:18:42 +0000106 if (FileType == SrcMgr::C_System)
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000107 OS.write(" 3", 2);
Chris Lattner0b9e7362008-09-26 21:18:42 +0000108 else if (FileType == SrcMgr::C_ExternCSystem)
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000109 OS.write(" 3 4", 4);
110 OS << '\n';
111}
112
Reid Spencer5f016e22007-07-11 17:01:13 +0000113/// MoveToLine - Move the output to the source line specified by the location
114/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner5f180322007-12-09 21:11:08 +0000115/// #line directive. This returns false if already at the specified line, true
116/// if some newlines were emitted.
117bool PrintPPOutputPPCallbacks::MoveToLine(SourceLocation Loc) {
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000118 unsigned LineNo = PP.getSourceManager().getInstantiationLineNumber(Loc);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000119
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 if (DisableLineMarkers) {
Chris Lattner5f180322007-12-09 21:11:08 +0000121 if (LineNo == CurLine) return false;
122
123 CurLine = LineNo;
124
125 if (!EmittedTokensOnThisLine)
126 return true;
127
Chris Lattnere96de3e2008-08-17 03:12:02 +0000128 OS << '\n';
Chris Lattner5f180322007-12-09 21:11:08 +0000129 EmittedTokensOnThisLine = false;
130 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000131 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000132
Reid Spencer5f016e22007-07-11 17:01:13 +0000133 // If this line is "close enough" to the original line, just print newlines,
134 // otherwise print a #line directive.
Daniel Dunbarfd966842008-09-26 01:13:35 +0000135 if (LineNo-CurLine <= 8) {
Chris Lattner822f9402007-07-23 05:14:05 +0000136 if (LineNo-CurLine == 1)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000137 OS << '\n';
Chris Lattner5f180322007-12-09 21:11:08 +0000138 else if (LineNo == CurLine)
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000139 return false; // Spelling line moved, but instantiation line didn't.
Chris Lattner822f9402007-07-23 05:14:05 +0000140 else {
141 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattnere96de3e2008-08-17 03:12:02 +0000142 OS.write(NewLines, LineNo-CurLine);
Chris Lattner822f9402007-07-23 05:14:05 +0000143 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 } else {
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000145 WriteLineInfo(LineNo, 0, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000146 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000147
148 CurLine = LineNo;
Chris Lattner5f180322007-12-09 21:11:08 +0000149 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000150}
151
152
153/// FileChanged - Whenever the preprocessor enters or exits a #include file
154/// it invokes this handler. Update our conception of the current source
155/// position.
156void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
157 FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +0000158 SrcMgr::CharacteristicKind NewFileType) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 // Unless we are exiting a #include, make sure to skip ahead to the line the
160 // #include directive was at.
161 SourceManager &SourceMgr = PP.getSourceManager();
162 if (Reason == PPCallbacks::EnterFile) {
Chris Lattner71d8bfb2009-01-30 18:44:17 +0000163 SourceLocation IncludeLoc = SourceMgr.getPresumedLoc(Loc).getIncludeLoc();
164 if (IncludeLoc.isValid())
165 MoveToLine(IncludeLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000166 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
167 MoveToLine(Loc);
168
169 // TODO GCC emits the # directive for this directive on the line AFTER the
170 // directive and emits a bunch of spaces that aren't needed. Emulate this
171 // strange behavior.
172 }
173
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000174 Loc = SourceMgr.getInstantiationLoc(Loc);
Chris Lattner30fc9332009-02-04 01:06:56 +0000175 CurLine = SourceMgr.getInstantiationLineNumber(Loc);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000176
Chris Lattner5f180322007-12-09 21:11:08 +0000177 if (DisableLineMarkers) return;
178
Chris Lattnerd8e30832007-07-24 06:57:14 +0000179 CurFilename.clear();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000180 CurFilename += SourceMgr.getPresumedLoc(Loc).getFilename();
Chris Lattnerd8e30832007-07-24 06:57:14 +0000181 Lexer::Stringify(CurFilename);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000182 FileType = NewFileType;
183
184 if (!Initialized) {
185 WriteLineInfo(CurLine);
186 Initialized = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000188
Reid Spencer5f016e22007-07-11 17:01:13 +0000189 switch (Reason) {
190 case PPCallbacks::EnterFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000191 WriteLineInfo(CurLine, " 1", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 break;
193 case PPCallbacks::ExitFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000194 WriteLineInfo(CurLine, " 2", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000195 break;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000196 case PPCallbacks::SystemHeaderPragma:
197 case PPCallbacks::RenameFile:
198 WriteLineInfo(CurLine);
199 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000200 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000201}
202
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000203/// Ident - Handle #ident directives when read by the preprocessor.
Reid Spencer5f016e22007-07-11 17:01:13 +0000204///
205void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
206 MoveToLine(Loc);
207
Chris Lattnere96de3e2008-08-17 03:12:02 +0000208 OS.write("#ident ", strlen("#ident "));
209 OS.write(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000210 EmittedTokensOnThisLine = true;
211}
212
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000213void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
214 const IdentifierInfo *Kind,
215 const std::string &Str) {
216 MoveToLine(Loc);
217 OS << "#pragma comment(" << Kind->getName();
218
219 if (!Str.empty()) {
220 OS << ", \"";
221
222 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
223 unsigned char Char = Str[i];
Chris Lattner52a3e9e2009-01-16 22:13:37 +0000224 if (isprint(Char) && Char != '\\' && Char != '"')
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000225 OS << (char)Char;
226 else // Output anything hard as an octal escape.
227 OS << '\\'
228 << (char)('0'+ ((Char >> 6) & 7))
229 << (char)('0'+ ((Char >> 3) & 7))
230 << (char)('0'+ ((Char >> 0) & 7));
231 }
232 OS << '"';
233 }
234
235 OS << ')';
236 EmittedTokensOnThisLine = true;
237}
238
239
Reid Spencer5f016e22007-07-11 17:01:13 +0000240/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner5f180322007-12-09 21:11:08 +0000241/// is called for the first token on each new line. If this really is the start
242/// of a new logical line, handle it and return true, otherwise return false.
243/// This may not be the start of a logical line because the "start of line"
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000244/// marker is set for spelling lines, not instantiation ones.
Chris Lattner5f180322007-12-09 21:11:08 +0000245bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000246 // Figure out what line we went to and insert the appropriate number of
247 // newline characters.
Chris Lattner5f180322007-12-09 21:11:08 +0000248 if (!MoveToLine(Tok.getLocation()))
249 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000250
251 // Print out space characters so that the first token on a line is
252 // indented for easy reading.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000253 const SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000254 unsigned ColNo = SourceMgr.getInstantiationColumnNumber(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000255
256 // This hack prevents stuff like:
257 // #define HASH #
258 // HASH define foo bar
259 // From having the # character end up at column 1, which makes it so it
260 // is not handled as a #define next time through the preprocessor if in
261 // -fpreprocessed mode.
Chris Lattner057aaf62007-10-09 18:03:42 +0000262 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattnere96de3e2008-08-17 03:12:02 +0000263 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000264
265 // Otherwise, indent the appropriate number of spaces.
266 for (; ColNo > 1; --ColNo)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000267 OS << ' ';
Chris Lattner5f180322007-12-09 21:11:08 +0000268
269 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000270}
271
272namespace {
273struct UnknownPragmaHandler : public PragmaHandler {
274 const char *Prefix;
275 PrintPPOutputPPCallbacks *Callbacks;
276
277 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
278 : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
Chris Lattnerd2177732007-07-20 16:59:19 +0000279 virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000280 // Figure out what line we went to and insert the appropriate number of
281 // newline characters.
282 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattnere96de3e2008-08-17 03:12:02 +0000283 Callbacks->OS.write(Prefix, strlen(Prefix));
Reid Spencer5f016e22007-07-11 17:01:13 +0000284
285 // Read and print all of the pragma tokens.
Chris Lattner057aaf62007-10-09 18:03:42 +0000286 while (PragmaTok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000287 if (PragmaTok.hasLeadingSpace())
Chris Lattnere96de3e2008-08-17 03:12:02 +0000288 Callbacks->OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000289 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000290 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000291 PP.LexUnexpandedToken(PragmaTok);
292 }
Chris Lattnere96de3e2008-08-17 03:12:02 +0000293 Callbacks->OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000294 }
295};
296} // end anonymous namespace
297
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000298
Chris Lattner59076ab2009-02-06 05:56:11 +0000299static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
300 PrintPPOutputPPCallbacks *Callbacks,
301 llvm::raw_ostream &OS) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000302 char Buffer[256];
Chris Lattner59076ab2009-02-06 05:56:11 +0000303 Token PrevTok;
Chris Lattner6f688e12007-10-10 20:45:16 +0000304 while (1) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000305
306 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner5f180322007-12-09 21:11:08 +0000307 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
308 // done.
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 } else if (Tok.hasLeadingSpace() ||
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000310 // If we haven't emitted a token on this line yet, PrevTok isn't
311 // useful to look at and no concatenation could happen anyway.
Chris Lattnerb638a302007-07-23 23:21:34 +0000312 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000313 // Don't print "-" next to "-", it would form "--".
314 Callbacks->AvoidConcat(PrevTok, Tok))) {
Chris Lattnere96de3e2008-08-17 03:12:02 +0000315 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000316 }
317
Chris Lattner2933f412007-07-23 06:14:36 +0000318 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
Chris Lattner33116d62009-01-26 19:33:54 +0000319 OS.write(II->getName(), II->getLength());
320 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
321 Tok.getLiteralData()) {
322 OS.write(Tok.getLiteralData(), Tok.getLength());
Chris Lattner2933f412007-07-23 06:14:36 +0000323 } else if (Tok.getLength() < 256) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 const char *TokPtr = Buffer;
325 unsigned Len = PP.getSpelling(Tok, TokPtr);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000326 OS.write(TokPtr, Len);
Reid Spencer5f016e22007-07-11 17:01:13 +0000327 } else {
328 std::string S = PP.getSpelling(Tok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000329 OS.write(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000330 }
331 Callbacks->SetEmittedTokensOnThisLine();
Chris Lattner6f688e12007-10-10 20:45:16 +0000332
333 if (Tok.is(tok::eof)) break;
Chris Lattner59076ab2009-02-06 05:56:11 +0000334
Chris Lattner6f688e12007-10-10 20:45:16 +0000335 PrevTok = Tok;
336 PP.Lex(Tok);
337 }
Chris Lattner59076ab2009-02-06 05:56:11 +0000338}
339
Chris Lattnerf73903a2009-02-06 06:45:26 +0000340/// PrintMacroDefinition - Print a macro definition in a form that will be
341/// properly accepted back as a definition.
342static void PrintMacroDefinition(IdentifierInfo &II, const MacroInfo &MI,
343 Preprocessor &PP, llvm::raw_ostream &OS) {
344 // Ignore computed macros like __LINE__ and friends.
345 if (MI.isBuiltinMacro()) return;
346 OS << "#define " << II.getName();
347
348 if (MI.isFunctionLike()) {
349 OS << '(';
350 if (MI.arg_empty())
351 ;
352 else if (MI.getNumArgs() == 1)
353 OS << (*MI.arg_begin())->getName();
354 else {
355 MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
356 OS << (*AI++)->getName();
357 while (AI != E)
358 OS << ',' << (*AI++)->getName();
359 }
360
361 if (MI.isVariadic()) {
362 if (!MI.arg_empty())
363 OS << ',';
364 OS << "...";
365 }
366 OS << ')';
367 }
368
369 // GCC always emits a space, even if the macro body is empty. However, do not
370 // want to emit two spaces if the first token has a leading space.
371 if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
372 OS << ' ';
373
Chris Lattnereb213da2009-02-10 22:16:03 +0000374 llvm::SmallVector<char, 128> SpellingBuffer;
Chris Lattnerf73903a2009-02-06 06:45:26 +0000375 for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end();
376 I != E; ++I) {
377 if (I->hasLeadingSpace())
378 OS << ' ';
Chris Lattnereb213da2009-02-10 22:16:03 +0000379
380 // Make sure we have enough space in the spelling buffer.
381 if (I->getLength() < SpellingBuffer.size())
382 SpellingBuffer.resize(I->getLength());
383 const char *Buffer = &SpellingBuffer[0];
384 unsigned SpellingLen = PP.getSpelling(*I, Buffer);
385 OS.write(Buffer, SpellingLen);
Chris Lattnerf73903a2009-02-06 06:45:26 +0000386 }
387 OS << "\n";
388}
389
Chris Lattner2a2bb182009-02-10 22:28:19 +0000390namespace {
391 struct SortMacrosByID {
392 typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
393 bool operator()(const id_macro_pair &LHS, const id_macro_pair &RHS) const {
394 return strcmp(LHS.first->getName(), RHS.first->getName()) < 0;
395 }
396 };
397}
Chris Lattner59076ab2009-02-06 05:56:11 +0000398
399/// DoPrintPreprocessedInput - This implements -E mode.
400///
401void clang::DoPrintPreprocessedInput(Preprocessor &PP,
402 const std::string &OutFile) {
403 // Inform the preprocessor whether we want it to retain comments or not, due
404 // to -C or -CC.
405 PP.SetCommentRetentionState(EnableCommentOutput, EnableMacroCommentOutput);
Chris Lattner59076ab2009-02-06 05:56:11 +0000406
407 // Open the output buffer.
408 std::string Err;
409 llvm::raw_fd_ostream OS(OutFile.empty() ? "-" : OutFile.c_str(), false, Err);
410 if (!Err.empty()) {
411 fprintf(stderr, "%s\n", Err.c_str());
412 exit(1);
413 }
414
415 OS.SetBufferSize(64*1024);
416
Chris Lattnerf73903a2009-02-06 06:45:26 +0000417 if (DumpMacros) {
418 // -dM mode just scans and ignores all tokens in the files, then dumps out
419 // the macro table at the end.
420 PP.EnterMainSourceFile();
421
422 Token Tok;
423 do PP.Lex(Tok);
424 while (Tok.isNot(tok::eof));
425
Chris Lattner2a2bb182009-02-10 22:28:19 +0000426 std::vector<std::pair<IdentifierInfo*, MacroInfo*> > MacrosByID;
Chris Lattnerf73903a2009-02-06 06:45:26 +0000427 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
428 I != E; ++I)
Chris Lattner2a2bb182009-02-10 22:28:19 +0000429 MacrosByID.push_back(*I);
430 std::sort(MacrosByID.begin(), MacrosByID.end(), SortMacrosByID());
431
432 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i)
433 PrintMacroDefinition(*MacrosByID[i].first, *MacrosByID[i].second, PP, OS);
Chris Lattnerf73903a2009-02-06 06:45:26 +0000434
435 } else {
Chris Lattnerd7038e12009-02-13 00:46:04 +0000436 PrintPPOutputPPCallbacks *Callbacks
437 = new PrintPPOutputPPCallbacks(PP, OS);
Chris Lattnerf73903a2009-02-06 06:45:26 +0000438 PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
439 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",
440 Callbacks));
Chris Lattner59076ab2009-02-06 05:56:11 +0000441
Chris Lattnerf73903a2009-02-06 06:45:26 +0000442 PP.setPPCallbacks(Callbacks);
Chris Lattner59076ab2009-02-06 05:56:11 +0000443
Chris Lattnerf73903a2009-02-06 06:45:26 +0000444 // After we have configured the preprocessor, enter the main file.
445 PP.EnterMainSourceFile();
Chris Lattner59076ab2009-02-06 05:56:11 +0000446
Chris Lattnerf73903a2009-02-06 06:45:26 +0000447 // Consume all of the tokens that come from the predefines buffer. Those
448 // should not be emitted into the output and are guaranteed to be at the
449 // start.
450 const SourceManager &SourceMgr = PP.getSourceManager();
451 Token Tok;
452 do PP.Lex(Tok);
453 while (Tok.isNot(tok::eof) && Tok.getLocation().isFileID() &&
454 !strcmp(SourceMgr.getPresumedLoc(Tok.getLocation()).getFilename(),
455 "<predefines>"));
Chris Lattner59076ab2009-02-06 05:56:11 +0000456
Chris Lattnerf73903a2009-02-06 06:45:26 +0000457 // Read all the preprocessed tokens, printing them out to the stream.
458 PrintPreprocessedTokens(PP, Tok, Callbacks, OS);
459 OS << '\n';
460 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000461
Chris Lattner76b3a722008-08-17 07:07:01 +0000462 // Flush the ostream.
463 OS.flush();
Chris Lattnere96de3e2008-08-17 03:12:02 +0000464
465 // If an error occurred, remove the output file.
466 if (PP.getDiagnostics().hasErrorOccurred() && !OutFile.empty())
467 llvm::sys::Path(OutFile).eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +0000468}
469