blob: d63d9cbba989a15a7dd8735919a3c09fe6275ab0 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This code simply runs the preprocessor on the input file and prints out the
11// result. This is the traditional behavior of the -E option.
12//
13//===----------------------------------------------------------------------===//
14
Eli Friedmanb09f6e12009-05-19 04:14:29 +000015#include "clang/Frontend/Utils.h"
Chris Lattnerf73903a2009-02-06 06:45:26 +000016#include "clang/Lex/MacroInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/Lex/PPCallbacks.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Lex/Pragma.h"
Chris Lattnerd7038e12009-02-13 00:46:04 +000020#include "clang/Lex/TokenConcatenation.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner5db17c92008-04-08 04:16:20 +000022#include "clang/Basic/Diagnostic.h"
Chris Lattnerd8e30832007-07-24 06:57:14 +000023#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "llvm/ADT/StringExtras.h"
25#include "llvm/Config/config.h"
Chris Lattnerdceb6a72008-08-17 01:47:12 +000026#include "llvm/Support/raw_ostream.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include <cstdio>
28using namespace clang;
29
Chris Lattnerd82df3a2009-04-12 01:56:53 +000030/// PrintMacroDefinition - Print a macro definition in a form that will be
31/// properly accepted back as a definition.
32static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
33 Preprocessor &PP, llvm::raw_ostream &OS) {
34 OS << "#define " << II.getName();
35
36 if (MI.isFunctionLike()) {
37 OS << '(';
38 if (MI.arg_empty())
39 ;
40 else if (MI.getNumArgs() == 1)
41 OS << (*MI.arg_begin())->getName();
42 else {
43 MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
44 OS << (*AI++)->getName();
45 while (AI != E)
46 OS << ',' << (*AI++)->getName();
47 }
48
49 if (MI.isVariadic()) {
50 if (!MI.arg_empty())
51 OS << ',';
52 OS << "...";
53 }
54 OS << ')';
55 }
56
57 // GCC always emits a space, even if the macro body is empty. However, do not
58 // want to emit two spaces if the first token has a leading space.
59 if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
60 OS << ' ';
61
62 llvm::SmallVector<char, 128> SpellingBuffer;
63 for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end();
64 I != E; ++I) {
65 if (I->hasLeadingSpace())
66 OS << ' ';
67
68 // Make sure we have enough space in the spelling buffer.
69 if (I->getLength() < SpellingBuffer.size())
70 SpellingBuffer.resize(I->getLength());
Jay Foadbeaaccd2009-05-21 09:52:38 +000071 const char *Buffer = SpellingBuffer.data();
Chris Lattnerd82df3a2009-04-12 01:56:53 +000072 unsigned SpellingLen = PP.getSpelling(*I, Buffer);
73 OS.write(Buffer, SpellingLen);
74 }
75}
76
Reid Spencer5f016e22007-07-11 17:01:13 +000077//===----------------------------------------------------------------------===//
78// Preprocessed token printer
79//===----------------------------------------------------------------------===//
80
Reid Spencer5f016e22007-07-11 17:01:13 +000081namespace {
82class PrintPPOutputPPCallbacks : public PPCallbacks {
83 Preprocessor &PP;
Chris Lattnerd7038e12009-02-13 00:46:04 +000084 TokenConcatenation ConcatInfo;
Chris Lattnere96de3e2008-08-17 03:12:02 +000085public:
86 llvm::raw_ostream &OS;
87private:
Reid Spencer5f016e22007-07-11 17:01:13 +000088 unsigned CurLine;
Reid Spencer5f016e22007-07-11 17:01:13 +000089 bool EmittedTokensOnThisLine;
Eli Friedman3e753e22009-06-02 07:55:39 +000090 bool EmittedMacroOnThisLine;
Chris Lattner9d728512008-10-27 01:19:25 +000091 SrcMgr::CharacteristicKind FileType;
Chris Lattnerd8e30832007-07-24 06:57:14 +000092 llvm::SmallString<512> CurFilename;
Daniel Dunbar737bdb42008-09-05 03:22:57 +000093 bool Initialized;
Eli Friedman12d3b1d2009-05-19 03:06:47 +000094 bool DisableLineMarkers;
95 bool DumpDefines;
Reid Spencer5f016e22007-07-11 17:01:13 +000096public:
Eli Friedman12d3b1d2009-05-19 03:06:47 +000097 PrintPPOutputPPCallbacks(Preprocessor &pp, llvm::raw_ostream &os,
98 bool lineMarkers, bool defines)
99 : PP(pp), ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
100 DumpDefines(defines) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000101 CurLine = 0;
Chris Lattnerd8e30832007-07-24 06:57:14 +0000102 CurFilename += "<uninit>";
Reid Spencer5f016e22007-07-11 17:01:13 +0000103 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000104 EmittedMacroOnThisLine = false;
Chris Lattner0b9e7362008-09-26 21:18:42 +0000105 FileType = SrcMgr::C_User;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000106 Initialized = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 }
108
109 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000110 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Reid Spencer5f016e22007-07-11 17:01:13 +0000111
112 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +0000113 SrcMgr::CharacteristicKind FileType);
Reid Spencer5f016e22007-07-11 17:01:13 +0000114 virtual void Ident(SourceLocation Loc, const std::string &str);
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000115 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
116 const std::string &Str);
117
Reid Spencer5f016e22007-07-11 17:01:13 +0000118
Chris Lattner5f180322007-12-09 21:11:08 +0000119 bool HandleFirstTokOnLine(Token &Tok);
120 bool MoveToLine(SourceLocation Loc);
Chris Lattnerd7038e12009-02-13 00:46:04 +0000121 bool AvoidConcat(const Token &PrevTok, const Token &Tok) {
122 return ConcatInfo.AvoidConcat(PrevTok, Tok);
123 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000124 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000125
Chris Lattner3ee211f2009-06-15 01:25:23 +0000126 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
127
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000128 /// MacroDefined - This hook is called whenever a macro definition is seen.
129 void MacroDefined(const IdentifierInfo *II, const MacroInfo *MI);
130
Reid Spencer5f016e22007-07-11 17:01:13 +0000131};
Chris Lattner5db17c92008-04-08 04:16:20 +0000132} // end anonymous namespace
Reid Spencer5f016e22007-07-11 17:01:13 +0000133
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000134void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
135 const char *Extra,
136 unsigned ExtraLen) {
Eli Friedman3e753e22009-06-02 07:55:39 +0000137 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000138 OS << '\n';
139 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000140 EmittedMacroOnThisLine = false;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000141 }
142
143 OS << '#' << ' ' << LineNo << ' ' << '"';
144 OS.write(&CurFilename[0], CurFilename.size());
145 OS << '"';
146
147 if (ExtraLen)
148 OS.write(Extra, ExtraLen);
149
Chris Lattner0b9e7362008-09-26 21:18:42 +0000150 if (FileType == SrcMgr::C_System)
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000151 OS.write(" 3", 2);
Chris Lattner0b9e7362008-09-26 21:18:42 +0000152 else if (FileType == SrcMgr::C_ExternCSystem)
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000153 OS.write(" 3 4", 4);
154 OS << '\n';
155}
156
Reid Spencer5f016e22007-07-11 17:01:13 +0000157/// MoveToLine - Move the output to the source line specified by the location
158/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner5f180322007-12-09 21:11:08 +0000159/// #line directive. This returns false if already at the specified line, true
160/// if some newlines were emitted.
161bool PrintPPOutputPPCallbacks::MoveToLine(SourceLocation Loc) {
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000162 unsigned LineNo = PP.getSourceManager().getInstantiationLineNumber(Loc);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000163
Reid Spencer5f016e22007-07-11 17:01:13 +0000164 if (DisableLineMarkers) {
Chris Lattner5f180322007-12-09 21:11:08 +0000165 if (LineNo == CurLine) return false;
166
167 CurLine = LineNo;
168
Eli Friedman3e753e22009-06-02 07:55:39 +0000169 if (!EmittedTokensOnThisLine && !EmittedMacroOnThisLine)
Chris Lattner5f180322007-12-09 21:11:08 +0000170 return true;
171
Chris Lattnere96de3e2008-08-17 03:12:02 +0000172 OS << '\n';
Chris Lattner5f180322007-12-09 21:11:08 +0000173 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000174 EmittedMacroOnThisLine = false;
Chris Lattner5f180322007-12-09 21:11:08 +0000175 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000176 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000177
Reid Spencer5f016e22007-07-11 17:01:13 +0000178 // If this line is "close enough" to the original line, just print newlines,
179 // otherwise print a #line directive.
Daniel Dunbarfd966842008-09-26 01:13:35 +0000180 if (LineNo-CurLine <= 8) {
Chris Lattner822f9402007-07-23 05:14:05 +0000181 if (LineNo-CurLine == 1)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000182 OS << '\n';
Chris Lattner5f180322007-12-09 21:11:08 +0000183 else if (LineNo == CurLine)
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000184 return false; // Spelling line moved, but instantiation line didn't.
Chris Lattner822f9402007-07-23 05:14:05 +0000185 else {
186 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattnere96de3e2008-08-17 03:12:02 +0000187 OS.write(NewLines, LineNo-CurLine);
Chris Lattner822f9402007-07-23 05:14:05 +0000188 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000189 } else {
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000190 WriteLineInfo(LineNo, 0, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000192
193 CurLine = LineNo;
Chris Lattner5f180322007-12-09 21:11:08 +0000194 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000195}
196
197
198/// FileChanged - Whenever the preprocessor enters or exits a #include file
199/// it invokes this handler. Update our conception of the current source
200/// position.
201void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
202 FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +0000203 SrcMgr::CharacteristicKind NewFileType) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000204 // Unless we are exiting a #include, make sure to skip ahead to the line the
205 // #include directive was at.
206 SourceManager &SourceMgr = PP.getSourceManager();
207 if (Reason == PPCallbacks::EnterFile) {
Chris Lattner71d8bfb2009-01-30 18:44:17 +0000208 SourceLocation IncludeLoc = SourceMgr.getPresumedLoc(Loc).getIncludeLoc();
209 if (IncludeLoc.isValid())
210 MoveToLine(IncludeLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000211 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
212 MoveToLine(Loc);
213
214 // TODO GCC emits the # directive for this directive on the line AFTER the
215 // directive and emits a bunch of spaces that aren't needed. Emulate this
216 // strange behavior.
217 }
218
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000219 Loc = SourceMgr.getInstantiationLoc(Loc);
Chris Lattner16629382009-03-27 17:13:49 +0000220 // FIXME: Should use presumed line #!
Chris Lattner30fc9332009-02-04 01:06:56 +0000221 CurLine = SourceMgr.getInstantiationLineNumber(Loc);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000222
Chris Lattner5f180322007-12-09 21:11:08 +0000223 if (DisableLineMarkers) return;
224
Chris Lattnerd8e30832007-07-24 06:57:14 +0000225 CurFilename.clear();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000226 CurFilename += SourceMgr.getPresumedLoc(Loc).getFilename();
Chris Lattnerd8e30832007-07-24 06:57:14 +0000227 Lexer::Stringify(CurFilename);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000228 FileType = NewFileType;
229
230 if (!Initialized) {
231 WriteLineInfo(CurLine);
232 Initialized = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000233 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000234
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 switch (Reason) {
236 case PPCallbacks::EnterFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000237 WriteLineInfo(CurLine, " 1", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000238 break;
239 case PPCallbacks::ExitFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000240 WriteLineInfo(CurLine, " 2", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000241 break;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000242 case PPCallbacks::SystemHeaderPragma:
243 case PPCallbacks::RenameFile:
244 WriteLineInfo(CurLine);
245 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000246 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000247}
248
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000249/// Ident - Handle #ident directives when read by the preprocessor.
Reid Spencer5f016e22007-07-11 17:01:13 +0000250///
251void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
252 MoveToLine(Loc);
253
Chris Lattnere96de3e2008-08-17 03:12:02 +0000254 OS.write("#ident ", strlen("#ident "));
255 OS.write(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 EmittedTokensOnThisLine = true;
257}
258
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000259/// MacroDefined - This hook is called whenever a macro definition is seen.
260void PrintPPOutputPPCallbacks::MacroDefined(const IdentifierInfo *II,
261 const MacroInfo *MI) {
262 // Only print out macro definitions in -dD mode.
263 if (!DumpDefines ||
264 // Ignore __FILE__ etc.
265 MI->isBuiltinMacro()) return;
266
267 MoveToLine(MI->getDefinitionLoc());
268 PrintMacroDefinition(*II, *MI, PP, OS);
Eli Friedman3e753e22009-06-02 07:55:39 +0000269 EmittedMacroOnThisLine = true;
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000270}
271
272
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000273void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
274 const IdentifierInfo *Kind,
275 const std::string &Str) {
276 MoveToLine(Loc);
277 OS << "#pragma comment(" << Kind->getName();
278
279 if (!Str.empty()) {
280 OS << ", \"";
281
282 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
283 unsigned char Char = Str[i];
Chris Lattner52a3e9e2009-01-16 22:13:37 +0000284 if (isprint(Char) && Char != '\\' && Char != '"')
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000285 OS << (char)Char;
286 else // Output anything hard as an octal escape.
287 OS << '\\'
288 << (char)('0'+ ((Char >> 6) & 7))
289 << (char)('0'+ ((Char >> 3) & 7))
290 << (char)('0'+ ((Char >> 0) & 7));
291 }
292 OS << '"';
293 }
294
295 OS << ')';
296 EmittedTokensOnThisLine = true;
297}
298
299
Reid Spencer5f016e22007-07-11 17:01:13 +0000300/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner5f180322007-12-09 21:11:08 +0000301/// is called for the first token on each new line. If this really is the start
302/// of a new logical line, handle it and return true, otherwise return false.
303/// This may not be the start of a logical line because the "start of line"
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000304/// marker is set for spelling lines, not instantiation ones.
Chris Lattner5f180322007-12-09 21:11:08 +0000305bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000306 // Figure out what line we went to and insert the appropriate number of
307 // newline characters.
Chris Lattner5f180322007-12-09 21:11:08 +0000308 if (!MoveToLine(Tok.getLocation()))
309 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000310
311 // Print out space characters so that the first token on a line is
312 // indented for easy reading.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000313 const SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000314 unsigned ColNo = SourceMgr.getInstantiationColumnNumber(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000315
316 // This hack prevents stuff like:
317 // #define HASH #
318 // HASH define foo bar
319 // From having the # character end up at column 1, which makes it so it
320 // is not handled as a #define next time through the preprocessor if in
321 // -fpreprocessed mode.
Chris Lattner057aaf62007-10-09 18:03:42 +0000322 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattnere96de3e2008-08-17 03:12:02 +0000323 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000324
325 // Otherwise, indent the appropriate number of spaces.
326 for (; ColNo > 1; --ColNo)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000327 OS << ' ';
Chris Lattner5f180322007-12-09 21:11:08 +0000328
329 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000330}
331
Chris Lattner3ee211f2009-06-15 01:25:23 +0000332void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
333 unsigned Len) {
334 unsigned NumNewlines = 0;
335 for (; Len; --Len, ++TokStr) {
336 if (*TokStr != '\n' &&
337 *TokStr != '\r')
338 continue;
339
340 ++NumNewlines;
341
342 // If we have \n\r or \r\n, skip both and count as one line.
343 if (Len != 1 &&
344 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
345 TokStr[0] != TokStr[1])
346 ++TokStr, --Len;
347 }
348
349 if (NumNewlines == 0) return;
350
Chris Lattnered2d7c42009-06-15 04:08:28 +0000351 CurLine += NumNewlines;
Chris Lattner3ee211f2009-06-15 01:25:23 +0000352}
353
354
Reid Spencer5f016e22007-07-11 17:01:13 +0000355namespace {
356struct UnknownPragmaHandler : public PragmaHandler {
357 const char *Prefix;
358 PrintPPOutputPPCallbacks *Callbacks;
359
360 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
361 : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
Chris Lattnerd2177732007-07-20 16:59:19 +0000362 virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 // Figure out what line we went to and insert the appropriate number of
364 // newline characters.
365 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattnere96de3e2008-08-17 03:12:02 +0000366 Callbacks->OS.write(Prefix, strlen(Prefix));
Reid Spencer5f016e22007-07-11 17:01:13 +0000367
368 // Read and print all of the pragma tokens.
Chris Lattner057aaf62007-10-09 18:03:42 +0000369 while (PragmaTok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 if (PragmaTok.hasLeadingSpace())
Chris Lattnere96de3e2008-08-17 03:12:02 +0000371 Callbacks->OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000372 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000373 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000374 PP.LexUnexpandedToken(PragmaTok);
375 }
Chris Lattnere96de3e2008-08-17 03:12:02 +0000376 Callbacks->OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000377 }
378};
379} // end anonymous namespace
380
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000381
Chris Lattner59076ab2009-02-06 05:56:11 +0000382static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
383 PrintPPOutputPPCallbacks *Callbacks,
384 llvm::raw_ostream &OS) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000385 char Buffer[256];
Chris Lattner59076ab2009-02-06 05:56:11 +0000386 Token PrevTok;
Chris Lattner6f688e12007-10-10 20:45:16 +0000387 while (1) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000388
389 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner5f180322007-12-09 21:11:08 +0000390 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
391 // done.
Reid Spencer5f016e22007-07-11 17:01:13 +0000392 } else if (Tok.hasLeadingSpace() ||
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000393 // If we haven't emitted a token on this line yet, PrevTok isn't
394 // useful to look at and no concatenation could happen anyway.
Chris Lattnerb638a302007-07-23 23:21:34 +0000395 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000396 // Don't print "-" next to "-", it would form "--".
397 Callbacks->AvoidConcat(PrevTok, Tok))) {
Chris Lattnere96de3e2008-08-17 03:12:02 +0000398 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000399 }
400
Chris Lattner2933f412007-07-23 06:14:36 +0000401 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
Chris Lattner33116d62009-01-26 19:33:54 +0000402 OS.write(II->getName(), II->getLength());
403 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
404 Tok.getLiteralData()) {
405 OS.write(Tok.getLiteralData(), Tok.getLength());
Chris Lattner2933f412007-07-23 06:14:36 +0000406 } else if (Tok.getLength() < 256) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000407 const char *TokPtr = Buffer;
408 unsigned Len = PP.getSpelling(Tok, TokPtr);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000409 OS.write(TokPtr, Len);
Chris Lattner3ee211f2009-06-15 01:25:23 +0000410
411 // Tokens that can contain embedded newlines need to adjust our current
412 // line number.
413 if (Tok.getKind() == tok::comment)
414 Callbacks->HandleNewlinesInToken(TokPtr, Len);
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 } else {
416 std::string S = PP.getSpelling(Tok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000417 OS.write(&S[0], S.size());
Chris Lattner3ee211f2009-06-15 01:25:23 +0000418
419 // Tokens that can contain embedded newlines need to adjust our current
420 // line number.
421 if (Tok.getKind() == tok::comment)
422 Callbacks->HandleNewlinesInToken(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000423 }
424 Callbacks->SetEmittedTokensOnThisLine();
Chris Lattner6f688e12007-10-10 20:45:16 +0000425
426 if (Tok.is(tok::eof)) break;
Chris Lattner59076ab2009-02-06 05:56:11 +0000427
Chris Lattner6f688e12007-10-10 20:45:16 +0000428 PrevTok = Tok;
429 PP.Lex(Tok);
430 }
Chris Lattner59076ab2009-02-06 05:56:11 +0000431}
432
Chris Lattner2a2bb182009-02-10 22:28:19 +0000433namespace {
434 struct SortMacrosByID {
435 typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
436 bool operator()(const id_macro_pair &LHS, const id_macro_pair &RHS) const {
437 return strcmp(LHS.first->getName(), RHS.first->getName()) < 0;
438 }
439 };
440}
Chris Lattner59076ab2009-02-06 05:56:11 +0000441
Eli Friedmanf1db5852009-05-19 01:32:34 +0000442void clang::DoPrintMacros(Preprocessor &PP, llvm::raw_ostream *OS) {
443 // -dM mode just scans and ignores all tokens in the files, then dumps out
444 // the macro table at the end.
445 PP.EnterMainSourceFile();
446
447 Token Tok;
448 do PP.Lex(Tok);
449 while (Tok.isNot(tok::eof));
450
451 std::vector<std::pair<IdentifierInfo*, MacroInfo*> > MacrosByID;
452 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
453 I != E; ++I)
454 MacrosByID.push_back(*I);
455 std::sort(MacrosByID.begin(), MacrosByID.end(), SortMacrosByID());
456
457 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
458 MacroInfo &MI = *MacrosByID[i].second;
459 // Ignore computed macros like __LINE__ and friends.
460 if (MI.isBuiltinMacro()) continue;
461
462 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
463 *OS << "\n";
464 }
465}
466
Chris Lattner59076ab2009-02-06 05:56:11 +0000467/// DoPrintPreprocessedInput - This implements -E mode.
468///
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000469void clang::DoPrintPreprocessedInput(Preprocessor &PP, llvm::raw_ostream *OS,
470 bool EnableCommentOutput,
471 bool EnableMacroCommentOutput,
472 bool DisableLineMarkers,
473 bool DumpDefines) {
Chris Lattner59076ab2009-02-06 05:56:11 +0000474 // Inform the preprocessor whether we want it to retain comments or not, due
475 // to -C or -CC.
476 PP.SetCommentRetentionState(EnableCommentOutput, EnableMacroCommentOutput);
Eli Friedmanf54fce82009-05-19 01:02:07 +0000477
478 OS->SetBufferSize(64*1024);
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000479
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000480 PrintPPOutputPPCallbacks *Callbacks =
481 new PrintPPOutputPPCallbacks(PP, *OS, DisableLineMarkers, DumpDefines);
Eli Friedmanf1db5852009-05-19 01:32:34 +0000482 PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
483 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",
484 Callbacks));
Chris Lattner59076ab2009-02-06 05:56:11 +0000485
Eli Friedmanf1db5852009-05-19 01:32:34 +0000486 PP.setPPCallbacks(Callbacks);
Chris Lattner59076ab2009-02-06 05:56:11 +0000487
Eli Friedmanf1db5852009-05-19 01:32:34 +0000488 // After we have configured the preprocessor, enter the main file.
489 PP.EnterMainSourceFile();
Chris Lattner59076ab2009-02-06 05:56:11 +0000490
Eli Friedmanf1db5852009-05-19 01:32:34 +0000491 // Consume all of the tokens that come from the predefines buffer. Those
492 // should not be emitted into the output and are guaranteed to be at the
493 // start.
494 const SourceManager &SourceMgr = PP.getSourceManager();
495 Token Tok;
496 do PP.Lex(Tok);
497 while (Tok.isNot(tok::eof) && Tok.getLocation().isFileID() &&
498 !strcmp(SourceMgr.getPresumedLoc(Tok.getLocation()).getFilename(),
499 "<built-in>"));
Chris Lattner59076ab2009-02-06 05:56:11 +0000500
Eli Friedmanf1db5852009-05-19 01:32:34 +0000501 // Read all the preprocessed tokens, printing them out to the stream.
502 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
503 *OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000504}
505