blob: 80e697daa0d74e61de3be375387ed519bcfc852a [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"
Daniel Dunbar775bee72009-11-11 10:07:22 +000016#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/SourceManager.h"
18#include "clang/Frontend/PreprocessorOutputOptions.h"
Chris Lattnerf73903a2009-02-06 06:45:26 +000019#include "clang/Lex/MacroInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Lex/PPCallbacks.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/Lex/Pragma.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000022#include "clang/Lex/Preprocessor.h"
Chris Lattnerd7038e12009-02-13 00:46:04 +000023#include "clang/Lex/TokenConcatenation.h"
Chris Lattnerd8e30832007-07-24 06:57:14 +000024#include "llvm/ADT/SmallString.h"
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +000025#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "llvm/Config/config.h"
Chris Lattnerdceb6a72008-08-17 01:47:12 +000027#include "llvm/Support/raw_ostream.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include <cstdio>
29using namespace clang;
30
Chris Lattnerd82df3a2009-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 Stump1eb44332009-09-09 15:08:12 +000036
Chris Lattnerd82df3a2009-04-12 01:56:53 +000037 if (MI.isFunctionLike()) {
38 OS << '(';
Chris Lattner13d55582009-12-09 02:08:14 +000039 if (!MI.arg_empty()) {
Chris Lattnerd82df3a2009-04-12 01:56:53 +000040 MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
Chris Lattner13d55582009-12-09 02:08:14 +000041 for (; AI+1 != E; ++AI) {
42 OS << (*AI)->getName();
Chris Lattner807b93e2009-12-07 01:58:34 +000043 OS << ',';
Chris Lattner807b93e2009-12-07 01:58:34 +000044 }
Chris Lattner13d55582009-12-09 02:08:14 +000045
46 // Last argument.
47 if ((*AI)->getName() == "__VA_ARGS__")
48 OS << "...";
49 else
50 OS << (*AI)->getName();
Chris Lattnerd82df3a2009-04-12 01:56:53 +000051 }
Mike Stump1eb44332009-09-09 15:08:12 +000052
Chris Lattner807b93e2009-12-07 01:58:34 +000053 if (MI.isGNUVarargs())
54 OS << "..."; // #define foo(x...)
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +000055
Chris Lattnerd82df3a2009-04-12 01:56:53 +000056 OS << ')';
57 }
Mike Stump1eb44332009-09-09 15:08:12 +000058
Chris Lattnerd82df3a2009-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 Stump1eb44332009-09-09 15:08:12 +000063
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000064 llvm::SmallString<128> SpellingBuffer;
Chris Lattnerd82df3a2009-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 Stump1eb44332009-09-09 15:08:12 +000069
Benjamin Kramerddeea562010-02-27 13:44:12 +000070 OS << PP.getSpelling(*I, SpellingBuffer);
Chris Lattnerd82df3a2009-04-12 01:56:53 +000071 }
72}
73
Reid Spencer5f016e22007-07-11 17:01:13 +000074//===----------------------------------------------------------------------===//
75// Preprocessed token printer
76//===----------------------------------------------------------------------===//
77
Reid Spencer5f016e22007-07-11 17:01:13 +000078namespace {
79class PrintPPOutputPPCallbacks : public PPCallbacks {
80 Preprocessor &PP;
Chris Lattnerdf721402010-04-13 00:06:42 +000081 SourceManager &SM;
Chris Lattnerd7038e12009-02-13 00:46:04 +000082 TokenConcatenation ConcatInfo;
Chris Lattnere96de3e2008-08-17 03:12:02 +000083public:
84 llvm::raw_ostream &OS;
85private:
Reid Spencer5f016e22007-07-11 17:01:13 +000086 unsigned CurLine;
Reid Spencer5f016e22007-07-11 17:01:13 +000087 bool EmittedTokensOnThisLine;
Eli Friedman3e753e22009-06-02 07:55:39 +000088 bool EmittedMacroOnThisLine;
Chris Lattner9d728512008-10-27 01:19:25 +000089 SrcMgr::CharacteristicKind FileType;
Chris Lattnerd8e30832007-07-24 06:57:14 +000090 llvm::SmallString<512> CurFilename;
Daniel Dunbar737bdb42008-09-05 03:22:57 +000091 bool Initialized;
Eli Friedman12d3b1d2009-05-19 03:06:47 +000092 bool DisableLineMarkers;
93 bool DumpDefines;
Chris Lattnerf7449342009-12-07 01:42:56 +000094 bool UseLineDirective;
Reid Spencer5f016e22007-07-11 17:01:13 +000095public:
Eli Friedman12d3b1d2009-05-19 03:06:47 +000096 PrintPPOutputPPCallbacks(Preprocessor &pp, llvm::raw_ostream &os,
97 bool lineMarkers, bool defines)
Chris Lattnerdf721402010-04-13 00:06:42 +000098 : PP(pp), SM(PP.getSourceManager()),
99 ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000100 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;
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000107
Chris Lattnerf7449342009-12-07 01:42:56 +0000108 // If we're in microsoft mode, use normal #line instead of line markers.
109 UseLineDirective = PP.getLangOptions().Microsoft;
Reid Spencer5f016e22007-07-11 17:01:13 +0000110 }
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Reid Spencer5f016e22007-07-11 17:01:13 +0000112 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000113 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +0000116 SrcMgr::CharacteristicKind FileType);
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 virtual void Ident(SourceLocation Loc, const std::string &str);
Mike Stump1eb44332009-09-09 15:08:12 +0000118 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000119 const std::string &Str);
120
Reid Spencer5f016e22007-07-11 17:01:13 +0000121
Chris Lattner5f180322007-12-09 21:11:08 +0000122 bool HandleFirstTokOnLine(Token &Tok);
Chris Lattner88aae912010-04-13 00:01:41 +0000123 bool MoveToLine(SourceLocation Loc) {
Chris Lattnerdf721402010-04-13 00:06:42 +0000124 return MoveToLine(SM.getPresumedLoc(Loc).getLine());
Chris Lattner88aae912010-04-13 00:01:41 +0000125 }
126 bool MoveToLine(unsigned LineNo);
127
Chris Lattner88773212010-04-14 03:57:19 +0000128 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
129 const Token &Tok) {
130 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
Chris Lattnerd7038e12009-02-13 00:46:04 +0000131 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000132 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Chris Lattner3ee211f2009-06-15 01:25:23 +0000134 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000136 /// MacroDefined - This hook is called whenever a macro definition is seen.
137 void MacroDefined(const IdentifierInfo *II, const MacroInfo *MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Reid Spencer5f016e22007-07-11 17:01:13 +0000139};
Chris Lattner5db17c92008-04-08 04:16:20 +0000140} // end anonymous namespace
Reid Spencer5f016e22007-07-11 17:01:13 +0000141
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000142void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
143 const char *Extra,
144 unsigned ExtraLen) {
Eli Friedman3e753e22009-06-02 07:55:39 +0000145 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000146 OS << '\n';
147 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000148 EmittedMacroOnThisLine = false;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000149 }
150
Chris Lattnerf7449342009-12-07 01:42:56 +0000151 // Emit #line directives or GNU line markers depending on what mode we're in.
152 if (UseLineDirective) {
153 OS << "#line" << ' ' << LineNo << ' ' << '"';
154 OS.write(&CurFilename[0], CurFilename.size());
155 OS << '"';
156 } else {
157 OS << '#' << ' ' << LineNo << ' ' << '"';
158 OS.write(&CurFilename[0], CurFilename.size());
159 OS << '"';
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000160
Steve Naroffd76fbda2009-12-06 01:02:14 +0000161 if (ExtraLen)
162 OS.write(Extra, ExtraLen);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000163
Steve Naroffd76fbda2009-12-06 01:02:14 +0000164 if (FileType == SrcMgr::C_System)
165 OS.write(" 3", 2);
166 else if (FileType == SrcMgr::C_ExternCSystem)
167 OS.write(" 3 4", 4);
168 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000169 OS << '\n';
170}
171
Reid Spencer5f016e22007-07-11 17:01:13 +0000172/// MoveToLine - Move the output to the source line specified by the location
173/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner5f180322007-12-09 21:11:08 +0000174/// #line directive. This returns false if already at the specified line, true
175/// if some newlines were emitted.
Chris Lattner88aae912010-04-13 00:01:41 +0000176bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000177 // If this line is "close enough" to the original line, just print newlines,
178 // otherwise print a #line directive.
Daniel Dunbarfd966842008-09-26 01:13:35 +0000179 if (LineNo-CurLine <= 8) {
Chris Lattner822f9402007-07-23 05:14:05 +0000180 if (LineNo-CurLine == 1)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000181 OS << '\n';
Chris Lattner5f180322007-12-09 21:11:08 +0000182 else if (LineNo == CurLine)
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000183 return false; // Spelling line moved, but instantiation line didn't.
Chris Lattner822f9402007-07-23 05:14:05 +0000184 else {
185 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattnere96de3e2008-08-17 03:12:02 +0000186 OS.write(NewLines, LineNo-CurLine);
Chris Lattner822f9402007-07-23 05:14:05 +0000187 }
Chris Lattner6133aeb2010-06-12 16:20:56 +0000188 } else if (!DisableLineMarkers) {
189 // Emit a #line or line marker.
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000190 WriteLineInfo(LineNo, 0, 0);
Chris Lattner6133aeb2010-06-12 16:20:56 +0000191 } else {
192 // Okay, we're in -P mode, which turns off line markers. However, we still
193 // need to emit a newline between tokens on different lines.
194 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
195 OS << '\n';
196 EmittedTokensOnThisLine = false;
197 EmittedMacroOnThisLine = false;
198 }
Mike Stump1eb44332009-09-09 15:08:12 +0000199 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000200
Mike Stump1eb44332009-09-09 15:08:12 +0000201 CurLine = LineNo;
Chris Lattner5f180322007-12-09 21:11:08 +0000202 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000203}
204
205
206/// FileChanged - Whenever the preprocessor enters or exits a #include file
207/// it invokes this handler. Update our conception of the current source
208/// position.
209void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
210 FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +0000211 SrcMgr::CharacteristicKind NewFileType) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000212 // Unless we are exiting a #include, make sure to skip ahead to the line the
213 // #include directive was at.
Chris Lattnerdf721402010-04-13 00:06:42 +0000214 SourceManager &SourceMgr = SM;
Chris Lattner88aae912010-04-13 00:01:41 +0000215
216 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Chris Lattner86d0ef72010-04-14 04:28:50 +0000217 unsigned NewLine = UserLoc.getLine();
Chris Lattner88aae912010-04-13 00:01:41 +0000218
Reid Spencer5f016e22007-07-11 17:01:13 +0000219 if (Reason == PPCallbacks::EnterFile) {
Chris Lattner71d8bfb2009-01-30 18:44:17 +0000220 SourceLocation IncludeLoc = SourceMgr.getPresumedLoc(Loc).getIncludeLoc();
221 if (IncludeLoc.isValid())
222 MoveToLine(IncludeLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000223 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
Chris Lattner88aae912010-04-13 00:01:41 +0000224 MoveToLine(NewLine);
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Reid Spencer5f016e22007-07-11 17:01:13 +0000226 // TODO GCC emits the # directive for this directive on the line AFTER the
227 // directive and emits a bunch of spaces that aren't needed. Emulate this
228 // strange behavior.
229 }
Chris Lattner88aae912010-04-13 00:01:41 +0000230
231 CurLine = NewLine;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000232
Chris Lattner5f180322007-12-09 21:11:08 +0000233 if (DisableLineMarkers) return;
234
Chris Lattnerd8e30832007-07-24 06:57:14 +0000235 CurFilename.clear();
Chris Lattner88aae912010-04-13 00:01:41 +0000236 CurFilename += UserLoc.getFilename();
Chris Lattnerd8e30832007-07-24 06:57:14 +0000237 Lexer::Stringify(CurFilename);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000238 FileType = NewFileType;
239
240 if (!Initialized) {
241 WriteLineInfo(CurLine);
242 Initialized = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000243 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000244
Reid Spencer5f016e22007-07-11 17:01:13 +0000245 switch (Reason) {
246 case PPCallbacks::EnterFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000247 WriteLineInfo(CurLine, " 1", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 break;
249 case PPCallbacks::ExitFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000250 WriteLineInfo(CurLine, " 2", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000251 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000252 case PPCallbacks::SystemHeaderPragma:
253 case PPCallbacks::RenameFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000254 WriteLineInfo(CurLine);
255 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000257}
258
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000259/// Ident - Handle #ident directives when read by the preprocessor.
Reid Spencer5f016e22007-07-11 17:01:13 +0000260///
261void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
262 MoveToLine(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Chris Lattnere96de3e2008-08-17 03:12:02 +0000264 OS.write("#ident ", strlen("#ident "));
265 OS.write(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000266 EmittedTokensOnThisLine = true;
267}
268
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000269/// MacroDefined - This hook is called whenever a macro definition is seen.
270void PrintPPOutputPPCallbacks::MacroDefined(const IdentifierInfo *II,
271 const MacroInfo *MI) {
272 // Only print out macro definitions in -dD mode.
273 if (!DumpDefines ||
274 // Ignore __FILE__ etc.
275 MI->isBuiltinMacro()) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000277 MoveToLine(MI->getDefinitionLoc());
278 PrintMacroDefinition(*II, *MI, PP, OS);
Eli Friedman3e753e22009-06-02 07:55:39 +0000279 EmittedMacroOnThisLine = true;
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000280}
281
282
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000283void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000284 const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000285 const std::string &Str) {
286 MoveToLine(Loc);
287 OS << "#pragma comment(" << Kind->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000288
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000289 if (!Str.empty()) {
290 OS << ", \"";
Mike Stump1eb44332009-09-09 15:08:12 +0000291
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000292 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
293 unsigned char Char = Str[i];
Chris Lattner52a3e9e2009-01-16 22:13:37 +0000294 if (isprint(Char) && Char != '\\' && Char != '"')
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000295 OS << (char)Char;
296 else // Output anything hard as an octal escape.
297 OS << '\\'
298 << (char)('0'+ ((Char >> 6) & 7))
299 << (char)('0'+ ((Char >> 3) & 7))
300 << (char)('0'+ ((Char >> 0) & 7));
301 }
302 OS << '"';
303 }
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000305 OS << ')';
306 EmittedTokensOnThisLine = true;
307}
308
309
Reid Spencer5f016e22007-07-11 17:01:13 +0000310/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner5f180322007-12-09 21:11:08 +0000311/// is called for the first token on each new line. If this really is the start
312/// of a new logical line, handle it and return true, otherwise return false.
313/// This may not be the start of a logical line because the "start of line"
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000314/// marker is set for spelling lines, not instantiation ones.
Chris Lattner5f180322007-12-09 21:11:08 +0000315bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000316 // Figure out what line we went to and insert the appropriate number of
317 // newline characters.
Chris Lattner5f180322007-12-09 21:11:08 +0000318 if (!MoveToLine(Tok.getLocation()))
319 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Reid Spencer5f016e22007-07-11 17:01:13 +0000321 // Print out space characters so that the first token on a line is
322 // indented for easy reading.
Chris Lattnerdf721402010-04-13 00:06:42 +0000323 unsigned ColNo = SM.getInstantiationColumnNumber(Tok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Reid Spencer5f016e22007-07-11 17:01:13 +0000325 // This hack prevents stuff like:
326 // #define HASH #
327 // HASH define foo bar
328 // From having the # character end up at column 1, which makes it so it
329 // is not handled as a #define next time through the preprocessor if in
330 // -fpreprocessed mode.
Chris Lattner057aaf62007-10-09 18:03:42 +0000331 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattnere96de3e2008-08-17 03:12:02 +0000332 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 // Otherwise, indent the appropriate number of spaces.
335 for (; ColNo > 1; --ColNo)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000336 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Chris Lattner5f180322007-12-09 21:11:08 +0000338 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000339}
340
Chris Lattner3ee211f2009-06-15 01:25:23 +0000341void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
342 unsigned Len) {
343 unsigned NumNewlines = 0;
344 for (; Len; --Len, ++TokStr) {
345 if (*TokStr != '\n' &&
346 *TokStr != '\r')
347 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Chris Lattner3ee211f2009-06-15 01:25:23 +0000349 ++NumNewlines;
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Chris Lattner3ee211f2009-06-15 01:25:23 +0000351 // If we have \n\r or \r\n, skip both and count as one line.
352 if (Len != 1 &&
353 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
354 TokStr[0] != TokStr[1])
355 ++TokStr, --Len;
356 }
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Chris Lattner3ee211f2009-06-15 01:25:23 +0000358 if (NumNewlines == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Chris Lattnered2d7c42009-06-15 04:08:28 +0000360 CurLine += NumNewlines;
Chris Lattner3ee211f2009-06-15 01:25:23 +0000361}
362
363
Reid Spencer5f016e22007-07-11 17:01:13 +0000364namespace {
365struct UnknownPragmaHandler : public PragmaHandler {
366 const char *Prefix;
367 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
370 : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
Chris Lattnerd2177732007-07-20 16:59:19 +0000371 virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000372 // Figure out what line we went to and insert the appropriate number of
373 // newline characters.
374 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattnere96de3e2008-08-17 03:12:02 +0000375 Callbacks->OS.write(Prefix, strlen(Prefix));
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Reid Spencer5f016e22007-07-11 17:01:13 +0000377 // Read and print all of the pragma tokens.
Chris Lattner057aaf62007-10-09 18:03:42 +0000378 while (PragmaTok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 if (PragmaTok.hasLeadingSpace())
Chris Lattnere96de3e2008-08-17 03:12:02 +0000380 Callbacks->OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000382 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 PP.LexUnexpandedToken(PragmaTok);
384 }
Chris Lattnere96de3e2008-08-17 03:12:02 +0000385 Callbacks->OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 }
387};
388} // end anonymous namespace
389
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000390
Chris Lattner59076ab2009-02-06 05:56:11 +0000391static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
392 PrintPPOutputPPCallbacks *Callbacks,
393 llvm::raw_ostream &OS) {
Benjamin Kramere3960072010-02-27 18:02:51 +0000394 char Buffer[256];
Chris Lattner88773212010-04-14 03:57:19 +0000395 Token PrevPrevTok;
Chris Lattner59076ab2009-02-06 05:56:11 +0000396 Token PrevTok;
Chris Lattner6f688e12007-10-10 20:45:16 +0000397 while (1) {
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Reid Spencer5f016e22007-07-11 17:01:13 +0000399 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner5f180322007-12-09 21:11:08 +0000400 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
401 // done.
Mike Stump1eb44332009-09-09 15:08:12 +0000402 } else if (Tok.hasLeadingSpace() ||
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000403 // If we haven't emitted a token on this line yet, PrevTok isn't
404 // useful to look at and no concatenation could happen anyway.
Chris Lattnerb638a302007-07-23 23:21:34 +0000405 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000406 // Don't print "-" next to "-", it would form "--".
Chris Lattner88773212010-04-14 03:57:19 +0000407 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattnere96de3e2008-08-17 03:12:02 +0000408 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 }
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Benjamin Kramere3960072010-02-27 18:02:51 +0000411 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
412 OS << II->getName();
413 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
414 Tok.getLiteralData()) {
415 OS.write(Tok.getLiteralData(), Tok.getLength());
416 } else if (Tok.getLength() < 256) {
417 const char *TokPtr = Buffer;
418 unsigned Len = PP.getSpelling(Tok, TokPtr);
419 OS.write(TokPtr, Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Benjamin Kramere3960072010-02-27 18:02:51 +0000421 // Tokens that can contain embedded newlines need to adjust our current
422 // line number.
423 if (Tok.getKind() == tok::comment)
424 Callbacks->HandleNewlinesInToken(TokPtr, Len);
425 } else {
426 std::string S = PP.getSpelling(Tok);
427 OS.write(&S[0], S.size());
428
429 // Tokens that can contain embedded newlines need to adjust our current
430 // line number.
431 if (Tok.getKind() == tok::comment)
432 Callbacks->HandleNewlinesInToken(&S[0], S.size());
433 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000434 Callbacks->SetEmittedTokensOnThisLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000435
Chris Lattner6f688e12007-10-10 20:45:16 +0000436 if (Tok.is(tok::eof)) break;
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Chris Lattner88773212010-04-14 03:57:19 +0000438 PrevPrevTok = PrevTok;
Chris Lattner6f688e12007-10-10 20:45:16 +0000439 PrevTok = Tok;
440 PP.Lex(Tok);
441 }
Chris Lattner59076ab2009-02-06 05:56:11 +0000442}
443
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000444typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
445static int MacroIDCompare(const void* a, const void* b) {
446 const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
447 const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
448 return LHS->first->getName().compare(RHS->first->getName());
Chris Lattner2a2bb182009-02-10 22:28:19 +0000449}
Chris Lattner59076ab2009-02-06 05:56:11 +0000450
Daniel Dunbar775bee72009-11-11 10:07:22 +0000451static void DoPrintMacros(Preprocessor &PP, llvm::raw_ostream *OS) {
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000452 // Ignore unknown pragmas.
453 PP.AddPragmaHandler(0, new EmptyPragmaHandler());
454
Eli Friedmanf1db5852009-05-19 01:32:34 +0000455 // -dM mode just scans and ignores all tokens in the files, then dumps out
456 // the macro table at the end.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000457 PP.EnterMainSourceFile();
Eli Friedmanf1db5852009-05-19 01:32:34 +0000458
459 Token Tok;
460 do PP.Lex(Tok);
461 while (Tok.isNot(tok::eof));
462
Benjamin Kramer3ff2a4b2010-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 Friedmanf1db5852009-05-19 01:32:34 +0000466
467 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
468 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000469 // Ignore computed macros like __LINE__ and friends.
Eli Friedmanf1db5852009-05-19 01:32:34 +0000470 if (MI.isBuiltinMacro()) continue;
471
472 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000473 *OS << '\n';
Eli Friedmanf1db5852009-05-19 01:32:34 +0000474 }
475}
476
Chris Lattner59076ab2009-02-06 05:56:11 +0000477/// DoPrintPreprocessedInput - This implements -E mode.
478///
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000479void clang::DoPrintPreprocessedInput(Preprocessor &PP, llvm::raw_ostream *OS,
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000480 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar775bee72009-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 Lattner59076ab2009-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 Dunbar775bee72009-11-11 10:07:22 +0000490 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanf54fce82009-05-19 01:02:07 +0000491
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000492 PrintPPOutputPPCallbacks *Callbacks =
Daniel Dunbar775bee72009-11-11 10:07:22 +0000493 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
494 Opts.ShowMacros);
Eli Friedmanf1db5852009-05-19 01:32:34 +0000495 PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
496 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",
497 Callbacks));
Chris Lattner59076ab2009-02-06 05:56:11 +0000498
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000499 PP.addPPCallbacks(Callbacks);
Chris Lattner59076ab2009-02-06 05:56:11 +0000500
Eli Friedmanf1db5852009-05-19 01:32:34 +0000501 // After we have configured the preprocessor, enter the main file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000502 PP.EnterMainSourceFile();
Chris Lattner59076ab2009-02-06 05:56:11 +0000503
Eli Friedmanf1db5852009-05-19 01:32:34 +0000504 // Consume all of the tokens that come from the predefines buffer. Those
505 // should not be emitted into the output and are guaranteed to be at the
506 // start.
507 const SourceManager &SourceMgr = PP.getSourceManager();
508 Token Tok;
509 do PP.Lex(Tok);
510 while (Tok.isNot(tok::eof) && Tok.getLocation().isFileID() &&
511 !strcmp(SourceMgr.getPresumedLoc(Tok.getLocation()).getFilename(),
512 "<built-in>"));
Chris Lattner59076ab2009-02-06 05:56:11 +0000513
Eli Friedmanf1db5852009-05-19 01:32:34 +0000514 // Read all the preprocessed tokens, printing them out to the stream.
515 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
516 *OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000517}
518