blob: d9708d8bced4c5eaec5bbf25872cd39cc5c981fd [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 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...)
55
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
Chris Lattnerd82df3a2009-04-12 01:56:53 +000064 llvm::SmallVector<char, 128> SpellingBuffer;
65 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
Chris Lattnerd82df3a2009-04-12 01:56:53 +000070 // Make sure we have enough space in the spelling buffer.
Ted Kremenek3e27c012009-11-03 06:18:05 +000071 if (I->getLength() > SpellingBuffer.size())
Chris Lattnerd82df3a2009-04-12 01:56:53 +000072 SpellingBuffer.resize(I->getLength());
Jay Foadbeaaccd2009-05-21 09:52:38 +000073 const char *Buffer = SpellingBuffer.data();
Chris Lattnerd82df3a2009-04-12 01:56:53 +000074 unsigned SpellingLen = PP.getSpelling(*I, Buffer);
75 OS.write(Buffer, SpellingLen);
76 }
77}
78
Reid Spencer5f016e22007-07-11 17:01:13 +000079//===----------------------------------------------------------------------===//
80// Preprocessed token printer
81//===----------------------------------------------------------------------===//
82
Reid Spencer5f016e22007-07-11 17:01:13 +000083namespace {
84class PrintPPOutputPPCallbacks : public PPCallbacks {
85 Preprocessor &PP;
Chris Lattnerd7038e12009-02-13 00:46:04 +000086 TokenConcatenation ConcatInfo;
Chris Lattnere96de3e2008-08-17 03:12:02 +000087public:
88 llvm::raw_ostream &OS;
89private:
Reid Spencer5f016e22007-07-11 17:01:13 +000090 unsigned CurLine;
Reid Spencer5f016e22007-07-11 17:01:13 +000091 bool EmittedTokensOnThisLine;
Eli Friedman3e753e22009-06-02 07:55:39 +000092 bool EmittedMacroOnThisLine;
Chris Lattner9d728512008-10-27 01:19:25 +000093 SrcMgr::CharacteristicKind FileType;
Chris Lattnerd8e30832007-07-24 06:57:14 +000094 llvm::SmallString<512> CurFilename;
Daniel Dunbar737bdb42008-09-05 03:22:57 +000095 bool Initialized;
Eli Friedman12d3b1d2009-05-19 03:06:47 +000096 bool DisableLineMarkers;
97 bool DumpDefines;
Chris Lattnerf7449342009-12-07 01:42:56 +000098 bool UseLineDirective;
Reid Spencer5f016e22007-07-11 17:01:13 +000099public:
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000100 PrintPPOutputPPCallbacks(Preprocessor &pp, llvm::raw_ostream &os,
101 bool lineMarkers, bool defines)
102 : PP(pp), ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
103 DumpDefines(defines) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000104 CurLine = 0;
Chris Lattnerd8e30832007-07-24 06:57:14 +0000105 CurFilename += "<uninit>";
Reid Spencer5f016e22007-07-11 17:01:13 +0000106 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000107 EmittedMacroOnThisLine = false;
Chris Lattner0b9e7362008-09-26 21:18:42 +0000108 FileType = SrcMgr::C_User;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000109 Initialized = false;
Chris Lattnerf7449342009-12-07 01:42:56 +0000110
111 // If we're in microsoft mode, use normal #line instead of line markers.
112 UseLineDirective = PP.getLangOptions().Microsoft;
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 }
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000116 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Mike Stump1eb44332009-09-09 15:08:12 +0000117
Reid Spencer5f016e22007-07-11 17:01:13 +0000118 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +0000119 SrcMgr::CharacteristicKind FileType);
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 virtual void Ident(SourceLocation Loc, const std::string &str);
Mike Stump1eb44332009-09-09 15:08:12 +0000121 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000122 const std::string &Str);
123
Reid Spencer5f016e22007-07-11 17:01:13 +0000124
Chris Lattner5f180322007-12-09 21:11:08 +0000125 bool HandleFirstTokOnLine(Token &Tok);
126 bool MoveToLine(SourceLocation Loc);
Chris Lattnerd7038e12009-02-13 00:46:04 +0000127 bool AvoidConcat(const Token &PrevTok, const Token &Tok) {
128 return ConcatInfo.AvoidConcat(PrevTok, Tok);
129 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000130 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Chris Lattner3ee211f2009-06-15 01:25:23 +0000132 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000134 /// MacroDefined - This hook is called whenever a macro definition is seen.
135 void MacroDefined(const IdentifierInfo *II, const MacroInfo *MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000136
Reid Spencer5f016e22007-07-11 17:01:13 +0000137};
Chris Lattner5db17c92008-04-08 04:16:20 +0000138} // end anonymous namespace
Reid Spencer5f016e22007-07-11 17:01:13 +0000139
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000140void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
141 const char *Extra,
142 unsigned ExtraLen) {
Eli Friedman3e753e22009-06-02 07:55:39 +0000143 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000144 OS << '\n';
145 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000146 EmittedMacroOnThisLine = false;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000147 }
148
Chris Lattnerf7449342009-12-07 01:42:56 +0000149 // Emit #line directives or GNU line markers depending on what mode we're in.
150 if (UseLineDirective) {
151 OS << "#line" << ' ' << LineNo << ' ' << '"';
152 OS.write(&CurFilename[0], CurFilename.size());
153 OS << '"';
154 } else {
155 OS << '#' << ' ' << LineNo << ' ' << '"';
156 OS.write(&CurFilename[0], CurFilename.size());
157 OS << '"';
158
Steve Naroffd76fbda2009-12-06 01:02:14 +0000159 if (ExtraLen)
160 OS.write(Extra, ExtraLen);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000161
Steve Naroffd76fbda2009-12-06 01:02:14 +0000162 if (FileType == SrcMgr::C_System)
163 OS.write(" 3", 2);
164 else if (FileType == SrcMgr::C_ExternCSystem)
165 OS.write(" 3 4", 4);
166 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000167 OS << '\n';
168}
169
Reid Spencer5f016e22007-07-11 17:01:13 +0000170/// MoveToLine - Move the output to the source line specified by the location
171/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner5f180322007-12-09 21:11:08 +0000172/// #line directive. This returns false if already at the specified line, true
173/// if some newlines were emitted.
174bool PrintPPOutputPPCallbacks::MoveToLine(SourceLocation Loc) {
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000175 unsigned LineNo = PP.getSourceManager().getInstantiationLineNumber(Loc);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000176
Reid Spencer5f016e22007-07-11 17:01:13 +0000177 if (DisableLineMarkers) {
Chris Lattner5f180322007-12-09 21:11:08 +0000178 if (LineNo == CurLine) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Chris Lattner5f180322007-12-09 21:11:08 +0000180 CurLine = LineNo;
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Eli Friedman3e753e22009-06-02 07:55:39 +0000182 if (!EmittedTokensOnThisLine && !EmittedMacroOnThisLine)
Chris Lattner5f180322007-12-09 21:11:08 +0000183 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Chris Lattnere96de3e2008-08-17 03:12:02 +0000185 OS << '\n';
Chris Lattner5f180322007-12-09 21:11:08 +0000186 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000187 EmittedMacroOnThisLine = false;
Chris Lattner5f180322007-12-09 21:11:08 +0000188 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000189 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000190
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 // If this line is "close enough" to the original line, just print newlines,
192 // otherwise print a #line directive.
Daniel Dunbarfd966842008-09-26 01:13:35 +0000193 if (LineNo-CurLine <= 8) {
Chris Lattner822f9402007-07-23 05:14:05 +0000194 if (LineNo-CurLine == 1)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000195 OS << '\n';
Chris Lattner5f180322007-12-09 21:11:08 +0000196 else if (LineNo == CurLine)
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000197 return false; // Spelling line moved, but instantiation line didn't.
Chris Lattner822f9402007-07-23 05:14:05 +0000198 else {
199 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattnere96de3e2008-08-17 03:12:02 +0000200 OS.write(NewLines, LineNo-CurLine);
Chris Lattner822f9402007-07-23 05:14:05 +0000201 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000202 } else {
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000203 WriteLineInfo(LineNo, 0, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000204 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000205
Mike Stump1eb44332009-09-09 15:08:12 +0000206 CurLine = LineNo;
Chris Lattner5f180322007-12-09 21:11:08 +0000207 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000208}
209
210
211/// FileChanged - Whenever the preprocessor enters or exits a #include file
212/// it invokes this handler. Update our conception of the current source
213/// position.
214void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
215 FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +0000216 SrcMgr::CharacteristicKind NewFileType) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000217 // Unless we are exiting a #include, make sure to skip ahead to the line the
218 // #include directive was at.
219 SourceManager &SourceMgr = PP.getSourceManager();
220 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) {
225 MoveToLine(Loc);
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 }
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000232 Loc = SourceMgr.getInstantiationLoc(Loc);
Chris Lattner16629382009-03-27 17:13:49 +0000233 // FIXME: Should use presumed line #!
Chris Lattner30fc9332009-02-04 01:06:56 +0000234 CurLine = SourceMgr.getInstantiationLineNumber(Loc);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000235
Chris Lattner5f180322007-12-09 21:11:08 +0000236 if (DisableLineMarkers) return;
237
Chris Lattnerd8e30832007-07-24 06:57:14 +0000238 CurFilename.clear();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000239 CurFilename += SourceMgr.getPresumedLoc(Loc).getFilename();
Chris Lattnerd8e30832007-07-24 06:57:14 +0000240 Lexer::Stringify(CurFilename);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000241 FileType = NewFileType;
242
243 if (!Initialized) {
244 WriteLineInfo(CurLine);
245 Initialized = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000246 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000247
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 switch (Reason) {
249 case PPCallbacks::EnterFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000250 WriteLineInfo(CurLine, " 1", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000251 break;
252 case PPCallbacks::ExitFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000253 WriteLineInfo(CurLine, " 2", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000254 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000255 case PPCallbacks::SystemHeaderPragma:
256 case PPCallbacks::RenameFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000257 WriteLineInfo(CurLine);
258 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000259 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000260}
261
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000262/// Ident - Handle #ident directives when read by the preprocessor.
Reid Spencer5f016e22007-07-11 17:01:13 +0000263///
264void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
265 MoveToLine(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000266
Chris Lattnere96de3e2008-08-17 03:12:02 +0000267 OS.write("#ident ", strlen("#ident "));
268 OS.write(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000269 EmittedTokensOnThisLine = true;
270}
271
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000272/// MacroDefined - This hook is called whenever a macro definition is seen.
273void PrintPPOutputPPCallbacks::MacroDefined(const IdentifierInfo *II,
274 const MacroInfo *MI) {
275 // Only print out macro definitions in -dD mode.
276 if (!DumpDefines ||
277 // Ignore __FILE__ etc.
278 MI->isBuiltinMacro()) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000280 MoveToLine(MI->getDefinitionLoc());
281 PrintMacroDefinition(*II, *MI, PP, OS);
Eli Friedman3e753e22009-06-02 07:55:39 +0000282 EmittedMacroOnThisLine = true;
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000283}
284
285
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000286void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000287 const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000288 const std::string &Str) {
289 MoveToLine(Loc);
290 OS << "#pragma comment(" << Kind->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000291
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000292 if (!Str.empty()) {
293 OS << ", \"";
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000295 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
296 unsigned char Char = Str[i];
Chris Lattner52a3e9e2009-01-16 22:13:37 +0000297 if (isprint(Char) && Char != '\\' && Char != '"')
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000298 OS << (char)Char;
299 else // Output anything hard as an octal escape.
300 OS << '\\'
301 << (char)('0'+ ((Char >> 6) & 7))
302 << (char)('0'+ ((Char >> 3) & 7))
303 << (char)('0'+ ((Char >> 0) & 7));
304 }
305 OS << '"';
306 }
Mike Stump1eb44332009-09-09 15:08:12 +0000307
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000308 OS << ')';
309 EmittedTokensOnThisLine = true;
310}
311
312
Reid Spencer5f016e22007-07-11 17:01:13 +0000313/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner5f180322007-12-09 21:11:08 +0000314/// is called for the first token on each new line. If this really is the start
315/// of a new logical line, handle it and return true, otherwise return false.
316/// This may not be the start of a logical line because the "start of line"
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000317/// marker is set for spelling lines, not instantiation ones.
Chris Lattner5f180322007-12-09 21:11:08 +0000318bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 // Figure out what line we went to and insert the appropriate number of
320 // newline characters.
Chris Lattner5f180322007-12-09 21:11:08 +0000321 if (!MoveToLine(Tok.getLocation()))
322 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 // Print out space characters so that the first token on a line is
325 // indented for easy reading.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000326 const SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000327 unsigned ColNo = SourceMgr.getInstantiationColumnNumber(Tok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 // This hack prevents stuff like:
330 // #define HASH #
331 // HASH define foo bar
332 // From having the # character end up at column 1, which makes it so it
333 // is not handled as a #define next time through the preprocessor if in
334 // -fpreprocessed mode.
Chris Lattner057aaf62007-10-09 18:03:42 +0000335 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattnere96de3e2008-08-17 03:12:02 +0000336 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 // Otherwise, indent the appropriate number of spaces.
339 for (; ColNo > 1; --ColNo)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000340 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Chris Lattner5f180322007-12-09 21:11:08 +0000342 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000343}
344
Chris Lattner3ee211f2009-06-15 01:25:23 +0000345void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
346 unsigned Len) {
347 unsigned NumNewlines = 0;
348 for (; Len; --Len, ++TokStr) {
349 if (*TokStr != '\n' &&
350 *TokStr != '\r')
351 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Chris Lattner3ee211f2009-06-15 01:25:23 +0000353 ++NumNewlines;
Mike Stump1eb44332009-09-09 15:08:12 +0000354
Chris Lattner3ee211f2009-06-15 01:25:23 +0000355 // If we have \n\r or \r\n, skip both and count as one line.
356 if (Len != 1 &&
357 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
358 TokStr[0] != TokStr[1])
359 ++TokStr, --Len;
360 }
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Chris Lattner3ee211f2009-06-15 01:25:23 +0000362 if (NumNewlines == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000363
Chris Lattnered2d7c42009-06-15 04:08:28 +0000364 CurLine += NumNewlines;
Chris Lattner3ee211f2009-06-15 01:25:23 +0000365}
366
367
Reid Spencer5f016e22007-07-11 17:01:13 +0000368namespace {
369struct UnknownPragmaHandler : public PragmaHandler {
370 const char *Prefix;
371 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
374 : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
Chris Lattnerd2177732007-07-20 16:59:19 +0000375 virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000376 // Figure out what line we went to and insert the appropriate number of
377 // newline characters.
378 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattnere96de3e2008-08-17 03:12:02 +0000379 Callbacks->OS.write(Prefix, strlen(Prefix));
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 // Read and print all of the pragma tokens.
Chris Lattner057aaf62007-10-09 18:03:42 +0000382 while (PragmaTok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 if (PragmaTok.hasLeadingSpace())
Chris Lattnere96de3e2008-08-17 03:12:02 +0000384 Callbacks->OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000385 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000386 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 PP.LexUnexpandedToken(PragmaTok);
388 }
Chris Lattnere96de3e2008-08-17 03:12:02 +0000389 Callbacks->OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000390 }
391};
392} // end anonymous namespace
393
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000394
Chris Lattner59076ab2009-02-06 05:56:11 +0000395static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
396 PrintPPOutputPPCallbacks *Callbacks,
397 llvm::raw_ostream &OS) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 char Buffer[256];
Chris Lattner59076ab2009-02-06 05:56:11 +0000399 Token PrevTok;
Chris Lattner6f688e12007-10-10 20:45:16 +0000400 while (1) {
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner5f180322007-12-09 21:11:08 +0000403 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
404 // done.
Mike Stump1eb44332009-09-09 15:08:12 +0000405 } else if (Tok.hasLeadingSpace() ||
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000406 // If we haven't emitted a token on this line yet, PrevTok isn't
407 // useful to look at and no concatenation could happen anyway.
Chris Lattnerb638a302007-07-23 23:21:34 +0000408 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000409 // Don't print "-" next to "-", it would form "--".
410 Callbacks->AvoidConcat(PrevTok, Tok))) {
Chris Lattnere96de3e2008-08-17 03:12:02 +0000411 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 }
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Chris Lattner2933f412007-07-23 06:14:36 +0000414 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
Daniel Dunbar01eb9b92009-10-18 21:17:35 +0000415 OS << II->getName();
Chris Lattner33116d62009-01-26 19:33:54 +0000416 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
417 Tok.getLiteralData()) {
418 OS.write(Tok.getLiteralData(), Tok.getLength());
Chris Lattner2933f412007-07-23 06:14:36 +0000419 } else if (Tok.getLength() < 256) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000420 const char *TokPtr = Buffer;
421 unsigned Len = PP.getSpelling(Tok, TokPtr);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000422 OS.write(TokPtr, Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Chris Lattner3ee211f2009-06-15 01:25:23 +0000424 // Tokens that can contain embedded newlines need to adjust our current
Mike Stump1eb44332009-09-09 15:08:12 +0000425 // line number.
Chris Lattner3ee211f2009-06-15 01:25:23 +0000426 if (Tok.getKind() == tok::comment)
427 Callbacks->HandleNewlinesInToken(TokPtr, Len);
Reid Spencer5f016e22007-07-11 17:01:13 +0000428 } else {
429 std::string S = PP.getSpelling(Tok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000430 OS.write(&S[0], S.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Chris Lattner3ee211f2009-06-15 01:25:23 +0000432 // Tokens that can contain embedded newlines need to adjust our current
Mike Stump1eb44332009-09-09 15:08:12 +0000433 // line number.
Chris Lattner3ee211f2009-06-15 01:25:23 +0000434 if (Tok.getKind() == tok::comment)
435 Callbacks->HandleNewlinesInToken(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000436 }
437 Callbacks->SetEmittedTokensOnThisLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Chris Lattner6f688e12007-10-10 20:45:16 +0000439 if (Tok.is(tok::eof)) break;
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Chris Lattner6f688e12007-10-10 20:45:16 +0000441 PrevTok = Tok;
442 PP.Lex(Tok);
443 }
Chris Lattner59076ab2009-02-06 05:56:11 +0000444}
445
Chris Lattner2a2bb182009-02-10 22:28:19 +0000446namespace {
447 struct SortMacrosByID {
448 typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
449 bool operator()(const id_macro_pair &LHS, const id_macro_pair &RHS) const {
Daniel Dunbar01eb9b92009-10-18 21:17:35 +0000450 return LHS.first->getName() < RHS.first->getName();
Chris Lattner2a2bb182009-02-10 22:28:19 +0000451 }
452 };
453}
Chris Lattner59076ab2009-02-06 05:56:11 +0000454
Daniel Dunbar775bee72009-11-11 10:07:22 +0000455static void DoPrintMacros(Preprocessor &PP, llvm::raw_ostream *OS) {
Eli Friedmanf1db5852009-05-19 01:32:34 +0000456 // -dM mode just scans and ignores all tokens in the files, then dumps out
457 // the macro table at the end.
458 PP.EnterMainSourceFile();
459
460 Token Tok;
461 do PP.Lex(Tok);
462 while (Tok.isNot(tok::eof));
463
464 std::vector<std::pair<IdentifierInfo*, MacroInfo*> > MacrosByID;
465 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
466 I != E; ++I)
467 MacrosByID.push_back(*I);
468 std::sort(MacrosByID.begin(), MacrosByID.end(), SortMacrosByID());
469
470 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
471 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000472 // Ignore computed macros like __LINE__ and friends.
Eli Friedmanf1db5852009-05-19 01:32:34 +0000473 if (MI.isBuiltinMacro()) continue;
474
475 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
476 *OS << "\n";
477 }
478}
479
Chris Lattner59076ab2009-02-06 05:56:11 +0000480/// DoPrintPreprocessedInput - This implements -E mode.
481///
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000482void clang::DoPrintPreprocessedInput(Preprocessor &PP, llvm::raw_ostream *OS,
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000483 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar775bee72009-11-11 10:07:22 +0000484 // Show macros with no output is handled specially.
485 if (!Opts.ShowCPP) {
486 assert(Opts.ShowMacros && "Not yet implemented!");
487 DoPrintMacros(PP, OS);
488 return;
489 }
490
Chris Lattner59076ab2009-02-06 05:56:11 +0000491 // Inform the preprocessor whether we want it to retain comments or not, due
492 // to -C or -CC.
Daniel Dunbar775bee72009-11-11 10:07:22 +0000493 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanf54fce82009-05-19 01:02:07 +0000494
495 OS->SetBufferSize(64*1024);
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000496
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000497 PrintPPOutputPPCallbacks *Callbacks =
Daniel Dunbar775bee72009-11-11 10:07:22 +0000498 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
499 Opts.ShowMacros);
Eli Friedmanf1db5852009-05-19 01:32:34 +0000500 PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
501 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",
502 Callbacks));
Chris Lattner59076ab2009-02-06 05:56:11 +0000503
Eli Friedmanf1db5852009-05-19 01:32:34 +0000504 PP.setPPCallbacks(Callbacks);
Chris Lattner59076ab2009-02-06 05:56:11 +0000505
Eli Friedmanf1db5852009-05-19 01:32:34 +0000506 // After we have configured the preprocessor, enter the main file.
507 PP.EnterMainSourceFile();
Chris Lattner59076ab2009-02-06 05:56:11 +0000508
Eli Friedmanf1db5852009-05-19 01:32:34 +0000509 // Consume all of the tokens that come from the predefines buffer. Those
510 // should not be emitted into the output and are guaranteed to be at the
511 // start.
512 const SourceManager &SourceMgr = PP.getSourceManager();
513 Token Tok;
514 do PP.Lex(Tok);
515 while (Tok.isNot(tok::eof) && Tok.getLocation().isFileID() &&
516 !strcmp(SourceMgr.getPresumedLoc(Tok.getLocation()).getFilename(),
517 "<built-in>"));
Chris Lattner59076ab2009-02-06 05:56:11 +0000518
Eli Friedmanf1db5852009-05-19 01:32:34 +0000519 // Read all the preprocessed tokens, printing them out to the stream.
520 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
521 *OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000522}
523