blob: c23c6e3b9a803e734cf324e198a6c801b5b0da75 [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "llvm/ADT/StringExtras.h"
26#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 Lattner807b93e2009-12-07 01:58:34 +000031static void PrintArgName(const IdentifierInfo *II, llvm::raw_ostream &OS) {
32 if (II->getName() == "__VA_ARGS__")
33 OS << "...";
34 else
35 OS << II->getName();
36}
37
Chris Lattnerd82df3a2009-04-12 01:56:53 +000038/// PrintMacroDefinition - Print a macro definition in a form that will be
39/// properly accepted back as a definition.
40static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
41 Preprocessor &PP, llvm::raw_ostream &OS) {
42 OS << "#define " << II.getName();
Mike Stump1eb44332009-09-09 15:08:12 +000043
Chris Lattnerd82df3a2009-04-12 01:56:53 +000044 if (MI.isFunctionLike()) {
45 OS << '(';
46 if (MI.arg_empty())
47 ;
Mike Stump1eb44332009-09-09 15:08:12 +000048 else if (MI.getNumArgs() == 1)
Chris Lattner807b93e2009-12-07 01:58:34 +000049 PrintArgName(*MI.arg_begin(), OS);
Chris Lattnerd82df3a2009-04-12 01:56:53 +000050 else {
51 MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
52 OS << (*AI++)->getName();
Chris Lattner807b93e2009-12-07 01:58:34 +000053 while (AI != E) {
54 OS << ',';
55 PrintArgName(*AI++, OS);
56 }
Chris Lattnerd82df3a2009-04-12 01:56:53 +000057 }
Mike Stump1eb44332009-09-09 15:08:12 +000058
Chris Lattner807b93e2009-12-07 01:58:34 +000059 if (MI.isGNUVarargs())
60 OS << "..."; // #define foo(x...)
61
Chris Lattnerd82df3a2009-04-12 01:56:53 +000062 OS << ')';
63 }
Mike Stump1eb44332009-09-09 15:08:12 +000064
Chris Lattnerd82df3a2009-04-12 01:56:53 +000065 // GCC always emits a space, even if the macro body is empty. However, do not
66 // want to emit two spaces if the first token has a leading space.
67 if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
68 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattnerd82df3a2009-04-12 01:56:53 +000070 llvm::SmallVector<char, 128> SpellingBuffer;
71 for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end();
72 I != E; ++I) {
73 if (I->hasLeadingSpace())
74 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +000075
Chris Lattnerd82df3a2009-04-12 01:56:53 +000076 // Make sure we have enough space in the spelling buffer.
Ted Kremenek3e27c012009-11-03 06:18:05 +000077 if (I->getLength() > SpellingBuffer.size())
Chris Lattnerd82df3a2009-04-12 01:56:53 +000078 SpellingBuffer.resize(I->getLength());
Jay Foadbeaaccd2009-05-21 09:52:38 +000079 const char *Buffer = SpellingBuffer.data();
Chris Lattnerd82df3a2009-04-12 01:56:53 +000080 unsigned SpellingLen = PP.getSpelling(*I, Buffer);
81 OS.write(Buffer, SpellingLen);
82 }
83}
84
Reid Spencer5f016e22007-07-11 17:01:13 +000085//===----------------------------------------------------------------------===//
86// Preprocessed token printer
87//===----------------------------------------------------------------------===//
88
Reid Spencer5f016e22007-07-11 17:01:13 +000089namespace {
90class PrintPPOutputPPCallbacks : public PPCallbacks {
91 Preprocessor &PP;
Chris Lattnerd7038e12009-02-13 00:46:04 +000092 TokenConcatenation ConcatInfo;
Chris Lattnere96de3e2008-08-17 03:12:02 +000093public:
94 llvm::raw_ostream &OS;
95private:
Reid Spencer5f016e22007-07-11 17:01:13 +000096 unsigned CurLine;
Reid Spencer5f016e22007-07-11 17:01:13 +000097 bool EmittedTokensOnThisLine;
Eli Friedman3e753e22009-06-02 07:55:39 +000098 bool EmittedMacroOnThisLine;
Chris Lattner9d728512008-10-27 01:19:25 +000099 SrcMgr::CharacteristicKind FileType;
Chris Lattnerd8e30832007-07-24 06:57:14 +0000100 llvm::SmallString<512> CurFilename;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000101 bool Initialized;
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000102 bool DisableLineMarkers;
103 bool DumpDefines;
Chris Lattnerf7449342009-12-07 01:42:56 +0000104 bool UseLineDirective;
Reid Spencer5f016e22007-07-11 17:01:13 +0000105public:
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000106 PrintPPOutputPPCallbacks(Preprocessor &pp, llvm::raw_ostream &os,
107 bool lineMarkers, bool defines)
108 : PP(pp), ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
109 DumpDefines(defines) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000110 CurLine = 0;
Chris Lattnerd8e30832007-07-24 06:57:14 +0000111 CurFilename += "<uninit>";
Reid Spencer5f016e22007-07-11 17:01:13 +0000112 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000113 EmittedMacroOnThisLine = false;
Chris Lattner0b9e7362008-09-26 21:18:42 +0000114 FileType = SrcMgr::C_User;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000115 Initialized = false;
Chris Lattnerf7449342009-12-07 01:42:56 +0000116
117 // If we're in microsoft mode, use normal #line instead of line markers.
118 UseLineDirective = PP.getLangOptions().Microsoft;
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 }
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Reid Spencer5f016e22007-07-11 17:01:13 +0000121 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000122 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Mike Stump1eb44332009-09-09 15:08:12 +0000123
Reid Spencer5f016e22007-07-11 17:01:13 +0000124 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +0000125 SrcMgr::CharacteristicKind FileType);
Reid Spencer5f016e22007-07-11 17:01:13 +0000126 virtual void Ident(SourceLocation Loc, const std::string &str);
Mike Stump1eb44332009-09-09 15:08:12 +0000127 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000128 const std::string &Str);
129
Reid Spencer5f016e22007-07-11 17:01:13 +0000130
Chris Lattner5f180322007-12-09 21:11:08 +0000131 bool HandleFirstTokOnLine(Token &Tok);
132 bool MoveToLine(SourceLocation Loc);
Chris Lattnerd7038e12009-02-13 00:46:04 +0000133 bool AvoidConcat(const Token &PrevTok, const Token &Tok) {
134 return ConcatInfo.AvoidConcat(PrevTok, Tok);
135 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000136 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Chris Lattner3ee211f2009-06-15 01:25:23 +0000138 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000140 /// MacroDefined - This hook is called whenever a macro definition is seen.
141 void MacroDefined(const IdentifierInfo *II, const MacroInfo *MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Reid Spencer5f016e22007-07-11 17:01:13 +0000143};
Chris Lattner5db17c92008-04-08 04:16:20 +0000144} // end anonymous namespace
Reid Spencer5f016e22007-07-11 17:01:13 +0000145
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000146void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
147 const char *Extra,
148 unsigned ExtraLen) {
Eli Friedman3e753e22009-06-02 07:55:39 +0000149 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000150 OS << '\n';
151 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000152 EmittedMacroOnThisLine = false;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000153 }
154
Chris Lattnerf7449342009-12-07 01:42:56 +0000155 // Emit #line directives or GNU line markers depending on what mode we're in.
156 if (UseLineDirective) {
157 OS << "#line" << ' ' << LineNo << ' ' << '"';
158 OS.write(&CurFilename[0], CurFilename.size());
159 OS << '"';
160 } else {
161 OS << '#' << ' ' << LineNo << ' ' << '"';
162 OS.write(&CurFilename[0], CurFilename.size());
163 OS << '"';
164
Steve Naroffd76fbda2009-12-06 01:02:14 +0000165 if (ExtraLen)
166 OS.write(Extra, ExtraLen);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000167
Steve Naroffd76fbda2009-12-06 01:02:14 +0000168 if (FileType == SrcMgr::C_System)
169 OS.write(" 3", 2);
170 else if (FileType == SrcMgr::C_ExternCSystem)
171 OS.write(" 3 4", 4);
172 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000173 OS << '\n';
174}
175
Reid Spencer5f016e22007-07-11 17:01:13 +0000176/// MoveToLine - Move the output to the source line specified by the location
177/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner5f180322007-12-09 21:11:08 +0000178/// #line directive. This returns false if already at the specified line, true
179/// if some newlines were emitted.
180bool PrintPPOutputPPCallbacks::MoveToLine(SourceLocation Loc) {
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000181 unsigned LineNo = PP.getSourceManager().getInstantiationLineNumber(Loc);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000182
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 if (DisableLineMarkers) {
Chris Lattner5f180322007-12-09 21:11:08 +0000184 if (LineNo == CurLine) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Chris Lattner5f180322007-12-09 21:11:08 +0000186 CurLine = LineNo;
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Eli Friedman3e753e22009-06-02 07:55:39 +0000188 if (!EmittedTokensOnThisLine && !EmittedMacroOnThisLine)
Chris Lattner5f180322007-12-09 21:11:08 +0000189 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Chris Lattnere96de3e2008-08-17 03:12:02 +0000191 OS << '\n';
Chris Lattner5f180322007-12-09 21:11:08 +0000192 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000193 EmittedMacroOnThisLine = false;
Chris Lattner5f180322007-12-09 21:11:08 +0000194 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000195 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000196
Reid Spencer5f016e22007-07-11 17:01:13 +0000197 // If this line is "close enough" to the original line, just print newlines,
198 // otherwise print a #line directive.
Daniel Dunbarfd966842008-09-26 01:13:35 +0000199 if (LineNo-CurLine <= 8) {
Chris Lattner822f9402007-07-23 05:14:05 +0000200 if (LineNo-CurLine == 1)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000201 OS << '\n';
Chris Lattner5f180322007-12-09 21:11:08 +0000202 else if (LineNo == CurLine)
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000203 return false; // Spelling line moved, but instantiation line didn't.
Chris Lattner822f9402007-07-23 05:14:05 +0000204 else {
205 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattnere96de3e2008-08-17 03:12:02 +0000206 OS.write(NewLines, LineNo-CurLine);
Chris Lattner822f9402007-07-23 05:14:05 +0000207 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000208 } else {
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000209 WriteLineInfo(LineNo, 0, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000210 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000211
Mike Stump1eb44332009-09-09 15:08:12 +0000212 CurLine = LineNo;
Chris Lattner5f180322007-12-09 21:11:08 +0000213 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000214}
215
216
217/// FileChanged - Whenever the preprocessor enters or exits a #include file
218/// it invokes this handler. Update our conception of the current source
219/// position.
220void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
221 FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +0000222 SrcMgr::CharacteristicKind NewFileType) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000223 // Unless we are exiting a #include, make sure to skip ahead to the line the
224 // #include directive was at.
225 SourceManager &SourceMgr = PP.getSourceManager();
226 if (Reason == PPCallbacks::EnterFile) {
Chris Lattner71d8bfb2009-01-30 18:44:17 +0000227 SourceLocation IncludeLoc = SourceMgr.getPresumedLoc(Loc).getIncludeLoc();
228 if (IncludeLoc.isValid())
229 MoveToLine(IncludeLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000230 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
231 MoveToLine(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Reid Spencer5f016e22007-07-11 17:01:13 +0000233 // TODO GCC emits the # directive for this directive on the line AFTER the
234 // directive and emits a bunch of spaces that aren't needed. Emulate this
235 // strange behavior.
236 }
Mike Stump1eb44332009-09-09 15:08:12 +0000237
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000238 Loc = SourceMgr.getInstantiationLoc(Loc);
Chris Lattner16629382009-03-27 17:13:49 +0000239 // FIXME: Should use presumed line #!
Chris Lattner30fc9332009-02-04 01:06:56 +0000240 CurLine = SourceMgr.getInstantiationLineNumber(Loc);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000241
Chris Lattner5f180322007-12-09 21:11:08 +0000242 if (DisableLineMarkers) return;
243
Chris Lattnerd8e30832007-07-24 06:57:14 +0000244 CurFilename.clear();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000245 CurFilename += SourceMgr.getPresumedLoc(Loc).getFilename();
Chris Lattnerd8e30832007-07-24 06:57:14 +0000246 Lexer::Stringify(CurFilename);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000247 FileType = NewFileType;
248
249 if (!Initialized) {
250 WriteLineInfo(CurLine);
251 Initialized = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000252 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000253
Reid Spencer5f016e22007-07-11 17:01:13 +0000254 switch (Reason) {
255 case PPCallbacks::EnterFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000256 WriteLineInfo(CurLine, " 1", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000257 break;
258 case PPCallbacks::ExitFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000259 WriteLineInfo(CurLine, " 2", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000260 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000261 case PPCallbacks::SystemHeaderPragma:
262 case PPCallbacks::RenameFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000263 WriteLineInfo(CurLine);
264 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000265 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000266}
267
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000268/// Ident - Handle #ident directives when read by the preprocessor.
Reid Spencer5f016e22007-07-11 17:01:13 +0000269///
270void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
271 MoveToLine(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Chris Lattnere96de3e2008-08-17 03:12:02 +0000273 OS.write("#ident ", strlen("#ident "));
274 OS.write(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000275 EmittedTokensOnThisLine = true;
276}
277
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000278/// MacroDefined - This hook is called whenever a macro definition is seen.
279void PrintPPOutputPPCallbacks::MacroDefined(const IdentifierInfo *II,
280 const MacroInfo *MI) {
281 // Only print out macro definitions in -dD mode.
282 if (!DumpDefines ||
283 // Ignore __FILE__ etc.
284 MI->isBuiltinMacro()) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000286 MoveToLine(MI->getDefinitionLoc());
287 PrintMacroDefinition(*II, *MI, PP, OS);
Eli Friedman3e753e22009-06-02 07:55:39 +0000288 EmittedMacroOnThisLine = true;
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000289}
290
291
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000292void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000293 const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000294 const std::string &Str) {
295 MoveToLine(Loc);
296 OS << "#pragma comment(" << Kind->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000298 if (!Str.empty()) {
299 OS << ", \"";
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000301 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
302 unsigned char Char = Str[i];
Chris Lattner52a3e9e2009-01-16 22:13:37 +0000303 if (isprint(Char) && Char != '\\' && Char != '"')
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000304 OS << (char)Char;
305 else // Output anything hard as an octal escape.
306 OS << '\\'
307 << (char)('0'+ ((Char >> 6) & 7))
308 << (char)('0'+ ((Char >> 3) & 7))
309 << (char)('0'+ ((Char >> 0) & 7));
310 }
311 OS << '"';
312 }
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000314 OS << ')';
315 EmittedTokensOnThisLine = true;
316}
317
318
Reid Spencer5f016e22007-07-11 17:01:13 +0000319/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner5f180322007-12-09 21:11:08 +0000320/// is called for the first token on each new line. If this really is the start
321/// of a new logical line, handle it and return true, otherwise return false.
322/// This may not be the start of a logical line because the "start of line"
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000323/// marker is set for spelling lines, not instantiation ones.
Chris Lattner5f180322007-12-09 21:11:08 +0000324bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000325 // Figure out what line we went to and insert the appropriate number of
326 // newline characters.
Chris Lattner5f180322007-12-09 21:11:08 +0000327 if (!MoveToLine(Tok.getLocation()))
328 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Reid Spencer5f016e22007-07-11 17:01:13 +0000330 // Print out space characters so that the first token on a line is
331 // indented for easy reading.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000332 const SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000333 unsigned ColNo = SourceMgr.getInstantiationColumnNumber(Tok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 // This hack prevents stuff like:
336 // #define HASH #
337 // HASH define foo bar
338 // From having the # character end up at column 1, which makes it so it
339 // is not handled as a #define next time through the preprocessor if in
340 // -fpreprocessed mode.
Chris Lattner057aaf62007-10-09 18:03:42 +0000341 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattnere96de3e2008-08-17 03:12:02 +0000342 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Reid Spencer5f016e22007-07-11 17:01:13 +0000344 // Otherwise, indent the appropriate number of spaces.
345 for (; ColNo > 1; --ColNo)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000346 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Chris Lattner5f180322007-12-09 21:11:08 +0000348 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000349}
350
Chris Lattner3ee211f2009-06-15 01:25:23 +0000351void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
352 unsigned Len) {
353 unsigned NumNewlines = 0;
354 for (; Len; --Len, ++TokStr) {
355 if (*TokStr != '\n' &&
356 *TokStr != '\r')
357 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Chris Lattner3ee211f2009-06-15 01:25:23 +0000359 ++NumNewlines;
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Chris Lattner3ee211f2009-06-15 01:25:23 +0000361 // If we have \n\r or \r\n, skip both and count as one line.
362 if (Len != 1 &&
363 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
364 TokStr[0] != TokStr[1])
365 ++TokStr, --Len;
366 }
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Chris Lattner3ee211f2009-06-15 01:25:23 +0000368 if (NumNewlines == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Chris Lattnered2d7c42009-06-15 04:08:28 +0000370 CurLine += NumNewlines;
Chris Lattner3ee211f2009-06-15 01:25:23 +0000371}
372
373
Reid Spencer5f016e22007-07-11 17:01:13 +0000374namespace {
375struct UnknownPragmaHandler : public PragmaHandler {
376 const char *Prefix;
377 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
380 : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
Chris Lattnerd2177732007-07-20 16:59:19 +0000381 virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000382 // Figure out what line we went to and insert the appropriate number of
383 // newline characters.
384 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattnere96de3e2008-08-17 03:12:02 +0000385 Callbacks->OS.write(Prefix, strlen(Prefix));
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 // Read and print all of the pragma tokens.
Chris Lattner057aaf62007-10-09 18:03:42 +0000388 while (PragmaTok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 if (PragmaTok.hasLeadingSpace())
Chris Lattnere96de3e2008-08-17 03:12:02 +0000390 Callbacks->OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000392 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 PP.LexUnexpandedToken(PragmaTok);
394 }
Chris Lattnere96de3e2008-08-17 03:12:02 +0000395 Callbacks->OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 }
397};
398} // end anonymous namespace
399
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000400
Chris Lattner59076ab2009-02-06 05:56:11 +0000401static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
402 PrintPPOutputPPCallbacks *Callbacks,
403 llvm::raw_ostream &OS) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 char Buffer[256];
Chris Lattner59076ab2009-02-06 05:56:11 +0000405 Token PrevTok;
Chris Lattner6f688e12007-10-10 20:45:16 +0000406 while (1) {
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner5f180322007-12-09 21:11:08 +0000409 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
410 // done.
Mike Stump1eb44332009-09-09 15:08:12 +0000411 } else if (Tok.hasLeadingSpace() ||
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000412 // If we haven't emitted a token on this line yet, PrevTok isn't
413 // useful to look at and no concatenation could happen anyway.
Chris Lattnerb638a302007-07-23 23:21:34 +0000414 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000415 // Don't print "-" next to "-", it would form "--".
416 Callbacks->AvoidConcat(PrevTok, Tok))) {
Chris Lattnere96de3e2008-08-17 03:12:02 +0000417 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000418 }
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Chris Lattner2933f412007-07-23 06:14:36 +0000420 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
Daniel Dunbar01eb9b92009-10-18 21:17:35 +0000421 OS << II->getName();
Chris Lattner33116d62009-01-26 19:33:54 +0000422 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
423 Tok.getLiteralData()) {
424 OS.write(Tok.getLiteralData(), Tok.getLength());
Chris Lattner2933f412007-07-23 06:14:36 +0000425 } else if (Tok.getLength() < 256) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000426 const char *TokPtr = Buffer;
427 unsigned Len = PP.getSpelling(Tok, TokPtr);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000428 OS.write(TokPtr, Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Chris Lattner3ee211f2009-06-15 01:25:23 +0000430 // Tokens that can contain embedded newlines need to adjust our current
Mike Stump1eb44332009-09-09 15:08:12 +0000431 // line number.
Chris Lattner3ee211f2009-06-15 01:25:23 +0000432 if (Tok.getKind() == tok::comment)
433 Callbacks->HandleNewlinesInToken(TokPtr, Len);
Reid Spencer5f016e22007-07-11 17:01:13 +0000434 } else {
435 std::string S = PP.getSpelling(Tok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000436 OS.write(&S[0], S.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Chris Lattner3ee211f2009-06-15 01:25:23 +0000438 // Tokens that can contain embedded newlines need to adjust our current
Mike Stump1eb44332009-09-09 15:08:12 +0000439 // line number.
Chris Lattner3ee211f2009-06-15 01:25:23 +0000440 if (Tok.getKind() == tok::comment)
441 Callbacks->HandleNewlinesInToken(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000442 }
443 Callbacks->SetEmittedTokensOnThisLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Chris Lattner6f688e12007-10-10 20:45:16 +0000445 if (Tok.is(tok::eof)) break;
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Chris Lattner6f688e12007-10-10 20:45:16 +0000447 PrevTok = Tok;
448 PP.Lex(Tok);
449 }
Chris Lattner59076ab2009-02-06 05:56:11 +0000450}
451
Chris Lattner2a2bb182009-02-10 22:28:19 +0000452namespace {
453 struct SortMacrosByID {
454 typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
455 bool operator()(const id_macro_pair &LHS, const id_macro_pair &RHS) const {
Daniel Dunbar01eb9b92009-10-18 21:17:35 +0000456 return LHS.first->getName() < RHS.first->getName();
Chris Lattner2a2bb182009-02-10 22:28:19 +0000457 }
458 };
459}
Chris Lattner59076ab2009-02-06 05:56:11 +0000460
Daniel Dunbar775bee72009-11-11 10:07:22 +0000461static void DoPrintMacros(Preprocessor &PP, llvm::raw_ostream *OS) {
Eli Friedmanf1db5852009-05-19 01:32:34 +0000462 // -dM mode just scans and ignores all tokens in the files, then dumps out
463 // the macro table at the end.
464 PP.EnterMainSourceFile();
465
466 Token Tok;
467 do PP.Lex(Tok);
468 while (Tok.isNot(tok::eof));
469
470 std::vector<std::pair<IdentifierInfo*, MacroInfo*> > MacrosByID;
471 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
472 I != E; ++I)
473 MacrosByID.push_back(*I);
474 std::sort(MacrosByID.begin(), MacrosByID.end(), SortMacrosByID());
475
476 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
477 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000478 // Ignore computed macros like __LINE__ and friends.
Eli Friedmanf1db5852009-05-19 01:32:34 +0000479 if (MI.isBuiltinMacro()) continue;
480
481 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
482 *OS << "\n";
483 }
484}
485
Chris Lattner59076ab2009-02-06 05:56:11 +0000486/// DoPrintPreprocessedInput - This implements -E mode.
487///
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000488void clang::DoPrintPreprocessedInput(Preprocessor &PP, llvm::raw_ostream *OS,
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000489 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar775bee72009-11-11 10:07:22 +0000490 // Show macros with no output is handled specially.
491 if (!Opts.ShowCPP) {
492 assert(Opts.ShowMacros && "Not yet implemented!");
493 DoPrintMacros(PP, OS);
494 return;
495 }
496
Chris Lattner59076ab2009-02-06 05:56:11 +0000497 // Inform the preprocessor whether we want it to retain comments or not, due
498 // to -C or -CC.
Daniel Dunbar775bee72009-11-11 10:07:22 +0000499 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanf54fce82009-05-19 01:02:07 +0000500
501 OS->SetBufferSize(64*1024);
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000502
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000503 PrintPPOutputPPCallbacks *Callbacks =
Daniel Dunbar775bee72009-11-11 10:07:22 +0000504 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
505 Opts.ShowMacros);
Eli Friedmanf1db5852009-05-19 01:32:34 +0000506 PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
507 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",
508 Callbacks));
Chris Lattner59076ab2009-02-06 05:56:11 +0000509
Eli Friedmanf1db5852009-05-19 01:32:34 +0000510 PP.setPPCallbacks(Callbacks);
Chris Lattner59076ab2009-02-06 05:56:11 +0000511
Eli Friedmanf1db5852009-05-19 01:32:34 +0000512 // After we have configured the preprocessor, enter the main file.
513 PP.EnterMainSourceFile();
Chris Lattner59076ab2009-02-06 05:56:11 +0000514
Eli Friedmanf1db5852009-05-19 01:32:34 +0000515 // Consume all of the tokens that come from the predefines buffer. Those
516 // should not be emitted into the output and are guaranteed to be at the
517 // start.
518 const SourceManager &SourceMgr = PP.getSourceManager();
519 Token Tok;
520 do PP.Lex(Tok);
521 while (Tok.isNot(tok::eof) && Tok.getLocation().isFileID() &&
522 !strcmp(SourceMgr.getPresumedLoc(Tok.getLocation()).getFilename(),
523 "<built-in>"));
Chris Lattner59076ab2009-02-06 05:56:11 +0000524
Eli Friedmanf1db5852009-05-19 01:32:34 +0000525 // Read all the preprocessed tokens, printing them out to the stream.
526 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
527 *OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000528}
529