blob: 6ac31a51242d6e4c6a2b3bfd008c4c7e0278a401 [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"
Ted Kremenekc2542b62009-03-31 18:58:14 +000016#include "clang-cc.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 Lattner16629382009-03-27 17:13:49 +0000175 // FIXME: Should use presumed line #!
Chris Lattner30fc9332009-02-04 01:06:56 +0000176 CurLine = SourceMgr.getInstantiationLineNumber(Loc);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000177
Chris Lattner5f180322007-12-09 21:11:08 +0000178 if (DisableLineMarkers) return;
179
Chris Lattnerd8e30832007-07-24 06:57:14 +0000180 CurFilename.clear();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000181 CurFilename += SourceMgr.getPresumedLoc(Loc).getFilename();
Chris Lattnerd8e30832007-07-24 06:57:14 +0000182 Lexer::Stringify(CurFilename);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000183 FileType = NewFileType;
184
185 if (!Initialized) {
186 WriteLineInfo(CurLine);
187 Initialized = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000188 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000189
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 switch (Reason) {
191 case PPCallbacks::EnterFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000192 WriteLineInfo(CurLine, " 1", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000193 break;
194 case PPCallbacks::ExitFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000195 WriteLineInfo(CurLine, " 2", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000196 break;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000197 case PPCallbacks::SystemHeaderPragma:
198 case PPCallbacks::RenameFile:
199 WriteLineInfo(CurLine);
200 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000201 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000202}
203
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000204/// Ident - Handle #ident directives when read by the preprocessor.
Reid Spencer5f016e22007-07-11 17:01:13 +0000205///
206void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
207 MoveToLine(Loc);
208
Chris Lattnere96de3e2008-08-17 03:12:02 +0000209 OS.write("#ident ", strlen("#ident "));
210 OS.write(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000211 EmittedTokensOnThisLine = true;
212}
213
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000214void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
215 const IdentifierInfo *Kind,
216 const std::string &Str) {
217 MoveToLine(Loc);
218 OS << "#pragma comment(" << Kind->getName();
219
220 if (!Str.empty()) {
221 OS << ", \"";
222
223 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
224 unsigned char Char = Str[i];
Chris Lattner52a3e9e2009-01-16 22:13:37 +0000225 if (isprint(Char) && Char != '\\' && Char != '"')
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000226 OS << (char)Char;
227 else // Output anything hard as an octal escape.
228 OS << '\\'
229 << (char)('0'+ ((Char >> 6) & 7))
230 << (char)('0'+ ((Char >> 3) & 7))
231 << (char)('0'+ ((Char >> 0) & 7));
232 }
233 OS << '"';
234 }
235
236 OS << ')';
237 EmittedTokensOnThisLine = true;
238}
239
240
Reid Spencer5f016e22007-07-11 17:01:13 +0000241/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner5f180322007-12-09 21:11:08 +0000242/// is called for the first token on each new line. If this really is the start
243/// of a new logical line, handle it and return true, otherwise return false.
244/// This may not be the start of a logical line because the "start of line"
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000245/// marker is set for spelling lines, not instantiation ones.
Chris Lattner5f180322007-12-09 21:11:08 +0000246bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000247 // Figure out what line we went to and insert the appropriate number of
248 // newline characters.
Chris Lattner5f180322007-12-09 21:11:08 +0000249 if (!MoveToLine(Tok.getLocation()))
250 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000251
252 // Print out space characters so that the first token on a line is
253 // indented for easy reading.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000254 const SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000255 unsigned ColNo = SourceMgr.getInstantiationColumnNumber(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000256
257 // This hack prevents stuff like:
258 // #define HASH #
259 // HASH define foo bar
260 // From having the # character end up at column 1, which makes it so it
261 // is not handled as a #define next time through the preprocessor if in
262 // -fpreprocessed mode.
Chris Lattner057aaf62007-10-09 18:03:42 +0000263 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattnere96de3e2008-08-17 03:12:02 +0000264 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000265
266 // Otherwise, indent the appropriate number of spaces.
267 for (; ColNo > 1; --ColNo)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000268 OS << ' ';
Chris Lattner5f180322007-12-09 21:11:08 +0000269
270 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000271}
272
273namespace {
274struct UnknownPragmaHandler : public PragmaHandler {
275 const char *Prefix;
276 PrintPPOutputPPCallbacks *Callbacks;
277
278 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
279 : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
Chris Lattnerd2177732007-07-20 16:59:19 +0000280 virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 // Figure out what line we went to and insert the appropriate number of
282 // newline characters.
283 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattnere96de3e2008-08-17 03:12:02 +0000284 Callbacks->OS.write(Prefix, strlen(Prefix));
Reid Spencer5f016e22007-07-11 17:01:13 +0000285
286 // Read and print all of the pragma tokens.
Chris Lattner057aaf62007-10-09 18:03:42 +0000287 while (PragmaTok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000288 if (PragmaTok.hasLeadingSpace())
Chris Lattnere96de3e2008-08-17 03:12:02 +0000289 Callbacks->OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000290 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000291 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000292 PP.LexUnexpandedToken(PragmaTok);
293 }
Chris Lattnere96de3e2008-08-17 03:12:02 +0000294 Callbacks->OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000295 }
296};
297} // end anonymous namespace
298
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000299
Chris Lattner59076ab2009-02-06 05:56:11 +0000300static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
301 PrintPPOutputPPCallbacks *Callbacks,
302 llvm::raw_ostream &OS) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 char Buffer[256];
Chris Lattner59076ab2009-02-06 05:56:11 +0000304 Token PrevTok;
Chris Lattner6f688e12007-10-10 20:45:16 +0000305 while (1) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000306
307 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner5f180322007-12-09 21:11:08 +0000308 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
309 // done.
Reid Spencer5f016e22007-07-11 17:01:13 +0000310 } else if (Tok.hasLeadingSpace() ||
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000311 // If we haven't emitted a token on this line yet, PrevTok isn't
312 // useful to look at and no concatenation could happen anyway.
Chris Lattnerb638a302007-07-23 23:21:34 +0000313 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000314 // Don't print "-" next to "-", it would form "--".
315 Callbacks->AvoidConcat(PrevTok, Tok))) {
Chris Lattnere96de3e2008-08-17 03:12:02 +0000316 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000317 }
318
Chris Lattner2933f412007-07-23 06:14:36 +0000319 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
Chris Lattner33116d62009-01-26 19:33:54 +0000320 OS.write(II->getName(), II->getLength());
321 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
322 Tok.getLiteralData()) {
323 OS.write(Tok.getLiteralData(), Tok.getLength());
Chris Lattner2933f412007-07-23 06:14:36 +0000324 } else if (Tok.getLength() < 256) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000325 const char *TokPtr = Buffer;
326 unsigned Len = PP.getSpelling(Tok, TokPtr);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000327 OS.write(TokPtr, Len);
Reid Spencer5f016e22007-07-11 17:01:13 +0000328 } else {
329 std::string S = PP.getSpelling(Tok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000330 OS.write(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000331 }
332 Callbacks->SetEmittedTokensOnThisLine();
Chris Lattner6f688e12007-10-10 20:45:16 +0000333
334 if (Tok.is(tok::eof)) break;
Chris Lattner59076ab2009-02-06 05:56:11 +0000335
Chris Lattner6f688e12007-10-10 20:45:16 +0000336 PrevTok = Tok;
337 PP.Lex(Tok);
338 }
Chris Lattner59076ab2009-02-06 05:56:11 +0000339}
340
Chris Lattnerf73903a2009-02-06 06:45:26 +0000341/// PrintMacroDefinition - Print a macro definition in a form that will be
342/// properly accepted back as a definition.
343static void PrintMacroDefinition(IdentifierInfo &II, const MacroInfo &MI,
344 Preprocessor &PP, llvm::raw_ostream &OS) {
345 // Ignore computed macros like __LINE__ and friends.
346 if (MI.isBuiltinMacro()) return;
347 OS << "#define " << II.getName();
348
349 if (MI.isFunctionLike()) {
350 OS << '(';
351 if (MI.arg_empty())
352 ;
353 else if (MI.getNumArgs() == 1)
354 OS << (*MI.arg_begin())->getName();
355 else {
356 MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
357 OS << (*AI++)->getName();
358 while (AI != E)
359 OS << ',' << (*AI++)->getName();
360 }
361
362 if (MI.isVariadic()) {
363 if (!MI.arg_empty())
364 OS << ',';
365 OS << "...";
366 }
367 OS << ')';
368 }
369
370 // GCC always emits a space, even if the macro body is empty. However, do not
371 // want to emit two spaces if the first token has a leading space.
372 if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
373 OS << ' ';
374
Chris Lattnereb213da2009-02-10 22:16:03 +0000375 llvm::SmallVector<char, 128> SpellingBuffer;
Chris Lattnerf73903a2009-02-06 06:45:26 +0000376 for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end();
377 I != E; ++I) {
378 if (I->hasLeadingSpace())
379 OS << ' ';
Chris Lattnereb213da2009-02-10 22:16:03 +0000380
381 // Make sure we have enough space in the spelling buffer.
382 if (I->getLength() < SpellingBuffer.size())
383 SpellingBuffer.resize(I->getLength());
384 const char *Buffer = &SpellingBuffer[0];
385 unsigned SpellingLen = PP.getSpelling(*I, Buffer);
386 OS.write(Buffer, SpellingLen);
Chris Lattnerf73903a2009-02-06 06:45:26 +0000387 }
388 OS << "\n";
389}
390
Chris Lattner2a2bb182009-02-10 22:28:19 +0000391namespace {
392 struct SortMacrosByID {
393 typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
394 bool operator()(const id_macro_pair &LHS, const id_macro_pair &RHS) const {
395 return strcmp(LHS.first->getName(), RHS.first->getName()) < 0;
396 }
397 };
398}
Chris Lattner59076ab2009-02-06 05:56:11 +0000399
400/// DoPrintPreprocessedInput - This implements -E mode.
401///
402void clang::DoPrintPreprocessedInput(Preprocessor &PP,
403 const std::string &OutFile) {
404 // Inform the preprocessor whether we want it to retain comments or not, due
405 // to -C or -CC.
406 PP.SetCommentRetentionState(EnableCommentOutput, EnableMacroCommentOutput);
Chris Lattner59076ab2009-02-06 05:56:11 +0000407
408 // Open the output buffer.
409 std::string Err;
410 llvm::raw_fd_ostream OS(OutFile.empty() ? "-" : OutFile.c_str(), false, Err);
411 if (!Err.empty()) {
412 fprintf(stderr, "%s\n", Err.c_str());
413 exit(1);
414 }
415
416 OS.SetBufferSize(64*1024);
417
Chris Lattnerf73903a2009-02-06 06:45:26 +0000418 if (DumpMacros) {
419 // -dM mode just scans and ignores all tokens in the files, then dumps out
420 // the macro table at the end.
421 PP.EnterMainSourceFile();
422
423 Token Tok;
424 do PP.Lex(Tok);
425 while (Tok.isNot(tok::eof));
426
Chris Lattner2a2bb182009-02-10 22:28:19 +0000427 std::vector<std::pair<IdentifierInfo*, MacroInfo*> > MacrosByID;
Chris Lattnerf73903a2009-02-06 06:45:26 +0000428 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
429 I != E; ++I)
Chris Lattner2a2bb182009-02-10 22:28:19 +0000430 MacrosByID.push_back(*I);
431 std::sort(MacrosByID.begin(), MacrosByID.end(), SortMacrosByID());
432
433 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i)
434 PrintMacroDefinition(*MacrosByID[i].first, *MacrosByID[i].second, PP, OS);
Chris Lattnerf73903a2009-02-06 06:45:26 +0000435
436 } else {
Chris Lattnerd7038e12009-02-13 00:46:04 +0000437 PrintPPOutputPPCallbacks *Callbacks
438 = new PrintPPOutputPPCallbacks(PP, OS);
Chris Lattnerf73903a2009-02-06 06:45:26 +0000439 PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
440 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",
441 Callbacks));
Chris Lattner59076ab2009-02-06 05:56:11 +0000442
Chris Lattnerf73903a2009-02-06 06:45:26 +0000443 PP.setPPCallbacks(Callbacks);
Chris Lattner59076ab2009-02-06 05:56:11 +0000444
Chris Lattnerf73903a2009-02-06 06:45:26 +0000445 // After we have configured the preprocessor, enter the main file.
446 PP.EnterMainSourceFile();
Chris Lattner59076ab2009-02-06 05:56:11 +0000447
Chris Lattnerf73903a2009-02-06 06:45:26 +0000448 // Consume all of the tokens that come from the predefines buffer. Those
449 // should not be emitted into the output and are guaranteed to be at the
450 // start.
451 const SourceManager &SourceMgr = PP.getSourceManager();
452 Token Tok;
453 do PP.Lex(Tok);
454 while (Tok.isNot(tok::eof) && Tok.getLocation().isFileID() &&
455 !strcmp(SourceMgr.getPresumedLoc(Tok.getLocation()).getFilename(),
Chris Lattner7d66ebb2009-03-20 21:23:42 +0000456 "<built-in>"));
Chris Lattner59076ab2009-02-06 05:56:11 +0000457
Chris Lattnerf73903a2009-02-06 06:45:26 +0000458 // Read all the preprocessed tokens, printing them out to the stream.
459 PrintPreprocessedTokens(PP, Tok, Callbacks, OS);
460 OS << '\n';
461 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000462
Chris Lattner76b3a722008-08-17 07:07:01 +0000463 // Flush the ostream.
464 OS.flush();
Chris Lattnere96de3e2008-08-17 03:12:02 +0000465
466 // If an error occurred, remove the output file.
467 if (PP.getDiagnostics().hasErrorOccurred() && !OutFile.empty())
468 llvm::sys::Path(OutFile).eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +0000469}
470