blob: 7385ca6cfd4d12d73b79e06e3a5960aca74e54ef [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"
Chris Lattnerabfe0942010-06-26 17:11:39 +000026#include "llvm/ADT/StringRef.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/Config/config.h"
Chris Lattnerdceb6a72008-08-17 01:47:12 +000028#include "llvm/Support/raw_ostream.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include <cstdio>
30using namespace clang;
31
Chris Lattnerd82df3a2009-04-12 01:56:53 +000032/// PrintMacroDefinition - Print a macro definition in a form that will be
33/// properly accepted back as a definition.
34static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
35 Preprocessor &PP, llvm::raw_ostream &OS) {
36 OS << "#define " << II.getName();
Mike Stump1eb44332009-09-09 15:08:12 +000037
Chris Lattnerd82df3a2009-04-12 01:56:53 +000038 if (MI.isFunctionLike()) {
39 OS << '(';
Chris Lattner13d55582009-12-09 02:08:14 +000040 if (!MI.arg_empty()) {
Chris Lattnerd82df3a2009-04-12 01:56:53 +000041 MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
Chris Lattner13d55582009-12-09 02:08:14 +000042 for (; AI+1 != E; ++AI) {
43 OS << (*AI)->getName();
Chris Lattner807b93e2009-12-07 01:58:34 +000044 OS << ',';
Chris Lattner807b93e2009-12-07 01:58:34 +000045 }
Chris Lattner13d55582009-12-09 02:08:14 +000046
47 // Last argument.
48 if ((*AI)->getName() == "__VA_ARGS__")
49 OS << "...";
50 else
51 OS << (*AI)->getName();
Chris Lattnerd82df3a2009-04-12 01:56:53 +000052 }
Mike Stump1eb44332009-09-09 15:08:12 +000053
Chris Lattner807b93e2009-12-07 01:58:34 +000054 if (MI.isGNUVarargs())
55 OS << "..."; // #define foo(x...)
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +000056
Chris Lattnerd82df3a2009-04-12 01:56:53 +000057 OS << ')';
58 }
Mike Stump1eb44332009-09-09 15:08:12 +000059
Chris Lattnerd82df3a2009-04-12 01:56:53 +000060 // GCC always emits a space, even if the macro body is empty. However, do not
61 // want to emit two spaces if the first token has a leading space.
62 if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
63 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +000064
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000065 llvm::SmallString<128> SpellingBuffer;
Chris Lattnerd82df3a2009-04-12 01:56:53 +000066 for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end();
67 I != E; ++I) {
68 if (I->hasLeadingSpace())
69 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +000070
Benjamin Kramerddeea562010-02-27 13:44:12 +000071 OS << PP.getSpelling(*I, SpellingBuffer);
Chris Lattnerd82df3a2009-04-12 01:56:53 +000072 }
73}
74
Reid Spencer5f016e22007-07-11 17:01:13 +000075//===----------------------------------------------------------------------===//
76// Preprocessed token printer
77//===----------------------------------------------------------------------===//
78
Reid Spencer5f016e22007-07-11 17:01:13 +000079namespace {
80class PrintPPOutputPPCallbacks : public PPCallbacks {
81 Preprocessor &PP;
Chris Lattnerdf721402010-04-13 00:06:42 +000082 SourceManager &SM;
Chris Lattnerd7038e12009-02-13 00:46:04 +000083 TokenConcatenation ConcatInfo;
Chris Lattnere96de3e2008-08-17 03:12:02 +000084public:
85 llvm::raw_ostream &OS;
86private:
Reid Spencer5f016e22007-07-11 17:01:13 +000087 unsigned CurLine;
Reid Spencer5f016e22007-07-11 17:01:13 +000088 bool EmittedTokensOnThisLine;
Eli Friedman3e753e22009-06-02 07:55:39 +000089 bool EmittedMacroOnThisLine;
Chris Lattner9d728512008-10-27 01:19:25 +000090 SrcMgr::CharacteristicKind FileType;
Chris Lattnerd8e30832007-07-24 06:57:14 +000091 llvm::SmallString<512> CurFilename;
Daniel Dunbar737bdb42008-09-05 03:22:57 +000092 bool Initialized;
Eli Friedman12d3b1d2009-05-19 03:06:47 +000093 bool DisableLineMarkers;
94 bool DumpDefines;
Chris Lattnerf7449342009-12-07 01:42:56 +000095 bool UseLineDirective;
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)
Chris Lattnerdf721402010-04-13 00:06:42 +000099 : PP(pp), SM(PP.getSourceManager()),
100 ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000101 DumpDefines(defines) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 CurLine = 0;
Chris Lattnerd8e30832007-07-24 06:57:14 +0000103 CurFilename += "<uninit>";
Reid Spencer5f016e22007-07-11 17:01:13 +0000104 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000105 EmittedMacroOnThisLine = false;
Chris Lattner0b9e7362008-09-26 21:18:42 +0000106 FileType = SrcMgr::C_User;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000107 Initialized = false;
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000108
Chris Lattnerf7449342009-12-07 01:42:56 +0000109 // If we're in microsoft mode, use normal #line instead of line markers.
110 UseLineDirective = PP.getLangOptions().Microsoft;
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 }
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000114 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Mike Stump1eb44332009-09-09 15:08:12 +0000115
Reid Spencer5f016e22007-07-11 17:01:13 +0000116 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +0000117 SrcMgr::CharacteristicKind FileType);
Reid Spencer5f016e22007-07-11 17:01:13 +0000118 virtual void Ident(SourceLocation Loc, const std::string &str);
Mike Stump1eb44332009-09-09 15:08:12 +0000119 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000120 const std::string &Str);
Chris Lattnerabfe0942010-06-26 17:11:39 +0000121 virtual void PragmaMessage(SourceLocation Loc, llvm::StringRef Str);
Reid Spencer5f016e22007-07-11 17:01:13 +0000122
Chris Lattner5f180322007-12-09 21:11:08 +0000123 bool HandleFirstTokOnLine(Token &Tok);
Chris Lattner88aae912010-04-13 00:01:41 +0000124 bool MoveToLine(SourceLocation Loc) {
Chris Lattnerdf721402010-04-13 00:06:42 +0000125 return MoveToLine(SM.getPresumedLoc(Loc).getLine());
Chris Lattner88aae912010-04-13 00:01:41 +0000126 }
127 bool MoveToLine(unsigned LineNo);
128
Chris Lattner88773212010-04-14 03:57:19 +0000129 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
130 const Token &Tok) {
131 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
Chris Lattnerd7038e12009-02-13 00:46:04 +0000132 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000133 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
Mike Stump1eb44332009-09-09 15:08:12 +0000134
Chris Lattner3ee211f2009-06-15 01:25:23 +0000135 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000136
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000137 /// MacroDefined - This hook is called whenever a macro definition is seen.
138 void MacroDefined(const IdentifierInfo *II, const MacroInfo *MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Reid Spencer5f016e22007-07-11 17:01:13 +0000140};
Chris Lattner5db17c92008-04-08 04:16:20 +0000141} // end anonymous namespace
Reid Spencer5f016e22007-07-11 17:01:13 +0000142
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000143void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
144 const char *Extra,
145 unsigned ExtraLen) {
Eli Friedman3e753e22009-06-02 07:55:39 +0000146 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000147 OS << '\n';
148 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000149 EmittedMacroOnThisLine = false;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000150 }
151
Chris Lattnerf7449342009-12-07 01:42:56 +0000152 // Emit #line directives or GNU line markers depending on what mode we're in.
153 if (UseLineDirective) {
154 OS << "#line" << ' ' << LineNo << ' ' << '"';
155 OS.write(&CurFilename[0], CurFilename.size());
156 OS << '"';
157 } else {
158 OS << '#' << ' ' << LineNo << ' ' << '"';
159 OS.write(&CurFilename[0], CurFilename.size());
160 OS << '"';
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000161
Steve Naroffd76fbda2009-12-06 01:02:14 +0000162 if (ExtraLen)
163 OS.write(Extra, ExtraLen);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000164
Steve Naroffd76fbda2009-12-06 01:02:14 +0000165 if (FileType == SrcMgr::C_System)
166 OS.write(" 3", 2);
167 else if (FileType == SrcMgr::C_ExternCSystem)
168 OS.write(" 3 4", 4);
169 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000170 OS << '\n';
171}
172
Reid Spencer5f016e22007-07-11 17:01:13 +0000173/// MoveToLine - Move the output to the source line specified by the location
174/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner5f180322007-12-09 21:11:08 +0000175/// #line directive. This returns false if already at the specified line, true
176/// if some newlines were emitted.
Chris Lattner88aae912010-04-13 00:01:41 +0000177bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
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 }
Chris Lattner6133aeb2010-06-12 16:20:56 +0000189 } else if (!DisableLineMarkers) {
190 // Emit a #line or line marker.
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000191 WriteLineInfo(LineNo, 0, 0);
Chris Lattner6133aeb2010-06-12 16:20:56 +0000192 } else {
193 // Okay, we're in -P mode, which turns off line markers. However, we still
194 // need to emit a newline between tokens on different lines.
195 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
196 OS << '\n';
197 EmittedTokensOnThisLine = false;
198 EmittedMacroOnThisLine = false;
199 }
Mike Stump1eb44332009-09-09 15:08:12 +0000200 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000201
Mike Stump1eb44332009-09-09 15:08:12 +0000202 CurLine = LineNo;
Chris Lattner5f180322007-12-09 21:11:08 +0000203 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000204}
205
206
207/// FileChanged - Whenever the preprocessor enters or exits a #include file
208/// it invokes this handler. Update our conception of the current source
209/// position.
210void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
211 FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +0000212 SrcMgr::CharacteristicKind NewFileType) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 // Unless we are exiting a #include, make sure to skip ahead to the line the
214 // #include directive was at.
Chris Lattnerdf721402010-04-13 00:06:42 +0000215 SourceManager &SourceMgr = SM;
Chris Lattner88aae912010-04-13 00:01:41 +0000216
217 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Chris Lattner86d0ef72010-04-14 04:28:50 +0000218 unsigned NewLine = UserLoc.getLine();
Chris Lattner88aae912010-04-13 00:01:41 +0000219
Reid Spencer5f016e22007-07-11 17:01:13 +0000220 if (Reason == PPCallbacks::EnterFile) {
Chris Lattner71d8bfb2009-01-30 18:44:17 +0000221 SourceLocation IncludeLoc = SourceMgr.getPresumedLoc(Loc).getIncludeLoc();
222 if (IncludeLoc.isValid())
223 MoveToLine(IncludeLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000224 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
Chris Lattner88aae912010-04-13 00:01:41 +0000225 MoveToLine(NewLine);
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Reid Spencer5f016e22007-07-11 17:01:13 +0000227 // TODO GCC emits the # directive for this directive on the line AFTER the
228 // directive and emits a bunch of spaces that aren't needed. Emulate this
229 // strange behavior.
230 }
Chris Lattner88aae912010-04-13 00:01:41 +0000231
232 CurLine = NewLine;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000233
Chris Lattner5f180322007-12-09 21:11:08 +0000234 if (DisableLineMarkers) return;
235
Chris Lattnerd8e30832007-07-24 06:57:14 +0000236 CurFilename.clear();
Chris Lattner88aae912010-04-13 00:01:41 +0000237 CurFilename += UserLoc.getFilename();
Chris Lattnerd8e30832007-07-24 06:57:14 +0000238 Lexer::Stringify(CurFilename);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000239 FileType = NewFileType;
240
241 if (!Initialized) {
242 WriteLineInfo(CurLine);
243 Initialized = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000244 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000245
Reid Spencer5f016e22007-07-11 17:01:13 +0000246 switch (Reason) {
247 case PPCallbacks::EnterFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000248 WriteLineInfo(CurLine, " 1", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 break;
250 case PPCallbacks::ExitFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000251 WriteLineInfo(CurLine, " 2", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000252 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000253 case PPCallbacks::SystemHeaderPragma:
254 case PPCallbacks::RenameFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000255 WriteLineInfo(CurLine);
256 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000257 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000258}
259
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000260/// Ident - Handle #ident directives when read by the preprocessor.
Reid Spencer5f016e22007-07-11 17:01:13 +0000261///
262void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
263 MoveToLine(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Chris Lattnere96de3e2008-08-17 03:12:02 +0000265 OS.write("#ident ", strlen("#ident "));
266 OS.write(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000267 EmittedTokensOnThisLine = true;
268}
269
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000270/// MacroDefined - This hook is called whenever a macro definition is seen.
271void PrintPPOutputPPCallbacks::MacroDefined(const IdentifierInfo *II,
272 const MacroInfo *MI) {
273 // Only print out macro definitions in -dD mode.
274 if (!DumpDefines ||
275 // Ignore __FILE__ etc.
276 MI->isBuiltinMacro()) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000278 MoveToLine(MI->getDefinitionLoc());
279 PrintMacroDefinition(*II, *MI, PP, OS);
Eli Friedman3e753e22009-06-02 07:55:39 +0000280 EmittedMacroOnThisLine = true;
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000281}
282
283
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000284void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000285 const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000286 const std::string &Str) {
287 MoveToLine(Loc);
288 OS << "#pragma comment(" << Kind->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000290 if (!Str.empty()) {
291 OS << ", \"";
Mike Stump1eb44332009-09-09 15:08:12 +0000292
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000293 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
294 unsigned char Char = Str[i];
Chris Lattner52a3e9e2009-01-16 22:13:37 +0000295 if (isprint(Char) && Char != '\\' && Char != '"')
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000296 OS << (char)Char;
297 else // Output anything hard as an octal escape.
298 OS << '\\'
299 << (char)('0'+ ((Char >> 6) & 7))
300 << (char)('0'+ ((Char >> 3) & 7))
301 << (char)('0'+ ((Char >> 0) & 7));
302 }
303 OS << '"';
304 }
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000306 OS << ')';
307 EmittedTokensOnThisLine = true;
308}
309
Chris Lattnerabfe0942010-06-26 17:11:39 +0000310void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
311 llvm::StringRef Str) {
312 MoveToLine(Loc);
313 OS << "#pragma message(";
314
315 OS << '"';
316
317 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
318 unsigned char Char = Str[i];
319 if (isprint(Char) && Char != '\\' && Char != '"')
320 OS << (char)Char;
321 else // Output anything hard as an octal escape.
322 OS << '\\'
323 << (char)('0'+ ((Char >> 6) & 7))
324 << (char)('0'+ ((Char >> 3) & 7))
325 << (char)('0'+ ((Char >> 0) & 7));
326 }
327 OS << '"';
328
329 OS << ')';
330 EmittedTokensOnThisLine = true;
331}
332
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000333
Reid Spencer5f016e22007-07-11 17:01:13 +0000334/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner5f180322007-12-09 21:11:08 +0000335/// is called for the first token on each new line. If this really is the start
336/// of a new logical line, handle it and return true, otherwise return false.
337/// This may not be the start of a logical line because the "start of line"
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000338/// marker is set for spelling lines, not instantiation ones.
Chris Lattner5f180322007-12-09 21:11:08 +0000339bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 // Figure out what line we went to and insert the appropriate number of
341 // newline characters.
Chris Lattner5f180322007-12-09 21:11:08 +0000342 if (!MoveToLine(Tok.getLocation()))
343 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Reid Spencer5f016e22007-07-11 17:01:13 +0000345 // Print out space characters so that the first token on a line is
346 // indented for easy reading.
Chris Lattnerdf721402010-04-13 00:06:42 +0000347 unsigned ColNo = SM.getInstantiationColumnNumber(Tok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Reid Spencer5f016e22007-07-11 17:01:13 +0000349 // This hack prevents stuff like:
350 // #define HASH #
351 // HASH define foo bar
352 // From having the # character end up at column 1, which makes it so it
353 // is not handled as a #define next time through the preprocessor if in
354 // -fpreprocessed mode.
Chris Lattner057aaf62007-10-09 18:03:42 +0000355 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattnere96de3e2008-08-17 03:12:02 +0000356 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 // Otherwise, indent the appropriate number of spaces.
359 for (; ColNo > 1; --ColNo)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000360 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Chris Lattner5f180322007-12-09 21:11:08 +0000362 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000363}
364
Chris Lattner3ee211f2009-06-15 01:25:23 +0000365void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
366 unsigned Len) {
367 unsigned NumNewlines = 0;
368 for (; Len; --Len, ++TokStr) {
369 if (*TokStr != '\n' &&
370 *TokStr != '\r')
371 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Chris Lattner3ee211f2009-06-15 01:25:23 +0000373 ++NumNewlines;
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Chris Lattner3ee211f2009-06-15 01:25:23 +0000375 // If we have \n\r or \r\n, skip both and count as one line.
376 if (Len != 1 &&
377 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
378 TokStr[0] != TokStr[1])
379 ++TokStr, --Len;
380 }
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Chris Lattner3ee211f2009-06-15 01:25:23 +0000382 if (NumNewlines == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Chris Lattnered2d7c42009-06-15 04:08:28 +0000384 CurLine += NumNewlines;
Chris Lattner3ee211f2009-06-15 01:25:23 +0000385}
386
387
Reid Spencer5f016e22007-07-11 17:01:13 +0000388namespace {
389struct UnknownPragmaHandler : public PragmaHandler {
390 const char *Prefix;
391 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
394 : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
Chris Lattnerd2177732007-07-20 16:59:19 +0000395 virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 // Figure out what line we went to and insert the appropriate number of
397 // newline characters.
398 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattnere96de3e2008-08-17 03:12:02 +0000399 Callbacks->OS.write(Prefix, strlen(Prefix));
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 // Read and print all of the pragma tokens.
Chris Lattner057aaf62007-10-09 18:03:42 +0000402 while (PragmaTok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 if (PragmaTok.hasLeadingSpace())
Chris Lattnere96de3e2008-08-17 03:12:02 +0000404 Callbacks->OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000405 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000406 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000407 PP.LexUnexpandedToken(PragmaTok);
408 }
Chris Lattnere96de3e2008-08-17 03:12:02 +0000409 Callbacks->OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000410 }
411};
412} // end anonymous namespace
413
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000414
Chris Lattner59076ab2009-02-06 05:56:11 +0000415static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
416 PrintPPOutputPPCallbacks *Callbacks,
417 llvm::raw_ostream &OS) {
Benjamin Kramere3960072010-02-27 18:02:51 +0000418 char Buffer[256];
Chris Lattnerc54539c2010-06-15 21:06:38 +0000419 Token PrevPrevTok, PrevTok;
420 PrevPrevTok.startToken();
421 PrevTok.startToken();
Chris Lattner6f688e12007-10-10 20:45:16 +0000422 while (1) {
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner5f180322007-12-09 21:11:08 +0000425 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
426 // done.
Mike Stump1eb44332009-09-09 15:08:12 +0000427 } else if (Tok.hasLeadingSpace() ||
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000428 // If we haven't emitted a token on this line yet, PrevTok isn't
429 // useful to look at and no concatenation could happen anyway.
Chris Lattnerb638a302007-07-23 23:21:34 +0000430 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000431 // Don't print "-" next to "-", it would form "--".
Chris Lattner88773212010-04-14 03:57:19 +0000432 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattnere96de3e2008-08-17 03:12:02 +0000433 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000434 }
Mike Stump1eb44332009-09-09 15:08:12 +0000435
Benjamin Kramere3960072010-02-27 18:02:51 +0000436 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
437 OS << II->getName();
438 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
439 Tok.getLiteralData()) {
440 OS.write(Tok.getLiteralData(), Tok.getLength());
441 } else if (Tok.getLength() < 256) {
442 const char *TokPtr = Buffer;
443 unsigned Len = PP.getSpelling(Tok, TokPtr);
444 OS.write(TokPtr, Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Benjamin Kramere3960072010-02-27 18:02:51 +0000446 // Tokens that can contain embedded newlines need to adjust our current
447 // line number.
448 if (Tok.getKind() == tok::comment)
449 Callbacks->HandleNewlinesInToken(TokPtr, Len);
450 } else {
451 std::string S = PP.getSpelling(Tok);
452 OS.write(&S[0], S.size());
453
454 // Tokens that can contain embedded newlines need to adjust our current
455 // line number.
456 if (Tok.getKind() == tok::comment)
457 Callbacks->HandleNewlinesInToken(&S[0], S.size());
458 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000459 Callbacks->SetEmittedTokensOnThisLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Chris Lattner6f688e12007-10-10 20:45:16 +0000461 if (Tok.is(tok::eof)) break;
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Chris Lattner88773212010-04-14 03:57:19 +0000463 PrevPrevTok = PrevTok;
Chris Lattner6f688e12007-10-10 20:45:16 +0000464 PrevTok = Tok;
465 PP.Lex(Tok);
466 }
Chris Lattner59076ab2009-02-06 05:56:11 +0000467}
468
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000469typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
470static int MacroIDCompare(const void* a, const void* b) {
471 const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
472 const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
473 return LHS->first->getName().compare(RHS->first->getName());
Chris Lattner2a2bb182009-02-10 22:28:19 +0000474}
Chris Lattner59076ab2009-02-06 05:56:11 +0000475
Daniel Dunbar775bee72009-11-11 10:07:22 +0000476static void DoPrintMacros(Preprocessor &PP, llvm::raw_ostream *OS) {
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000477 // Ignore unknown pragmas.
478 PP.AddPragmaHandler(0, new EmptyPragmaHandler());
479
Eli Friedmanf1db5852009-05-19 01:32:34 +0000480 // -dM mode just scans and ignores all tokens in the files, then dumps out
481 // the macro table at the end.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000482 PP.EnterMainSourceFile();
Eli Friedmanf1db5852009-05-19 01:32:34 +0000483
484 Token Tok;
485 do PP.Lex(Tok);
486 while (Tok.isNot(tok::eof));
487
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000488 llvm::SmallVector<id_macro_pair, 128>
489 MacrosByID(PP.macro_begin(), PP.macro_end());
490 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedmanf1db5852009-05-19 01:32:34 +0000491
492 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
493 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000494 // Ignore computed macros like __LINE__ and friends.
Eli Friedmanf1db5852009-05-19 01:32:34 +0000495 if (MI.isBuiltinMacro()) continue;
496
497 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000498 *OS << '\n';
Eli Friedmanf1db5852009-05-19 01:32:34 +0000499 }
500}
501
Chris Lattner59076ab2009-02-06 05:56:11 +0000502/// DoPrintPreprocessedInput - This implements -E mode.
503///
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000504void clang::DoPrintPreprocessedInput(Preprocessor &PP, llvm::raw_ostream *OS,
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000505 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar775bee72009-11-11 10:07:22 +0000506 // Show macros with no output is handled specially.
507 if (!Opts.ShowCPP) {
508 assert(Opts.ShowMacros && "Not yet implemented!");
509 DoPrintMacros(PP, OS);
510 return;
511 }
512
Chris Lattner59076ab2009-02-06 05:56:11 +0000513 // Inform the preprocessor whether we want it to retain comments or not, due
514 // to -C or -CC.
Daniel Dunbar775bee72009-11-11 10:07:22 +0000515 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanf54fce82009-05-19 01:02:07 +0000516
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000517 PrintPPOutputPPCallbacks *Callbacks =
Daniel Dunbar775bee72009-11-11 10:07:22 +0000518 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
519 Opts.ShowMacros);
Eli Friedmanf1db5852009-05-19 01:32:34 +0000520 PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
521 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",
522 Callbacks));
Chris Lattner59076ab2009-02-06 05:56:11 +0000523
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000524 PP.addPPCallbacks(Callbacks);
Chris Lattner59076ab2009-02-06 05:56:11 +0000525
Eli Friedmanf1db5852009-05-19 01:32:34 +0000526 // After we have configured the preprocessor, enter the main file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000527 PP.EnterMainSourceFile();
Chris Lattner59076ab2009-02-06 05:56:11 +0000528
Eli Friedmanf1db5852009-05-19 01:32:34 +0000529 // Consume all of the tokens that come from the predefines buffer. Those
530 // should not be emitted into the output and are guaranteed to be at the
531 // start.
532 const SourceManager &SourceMgr = PP.getSourceManager();
533 Token Tok;
534 do PP.Lex(Tok);
535 while (Tok.isNot(tok::eof) && Tok.getLocation().isFileID() &&
536 !strcmp(SourceMgr.getPresumedLoc(Tok.getLocation()).getFilename(),
537 "<built-in>"));
Chris Lattner59076ab2009-02-06 05:56:11 +0000538
Eli Friedmanf1db5852009-05-19 01:32:34 +0000539 // Read all the preprocessed tokens, printing them out to the stream.
540 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
541 *OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000542}
543