blob: 429999cd5e3c31033582dd2ed6e7a5524ae24fcf [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;
Daniel Dunbarf7c16d92010-08-24 22:44:13 +000088
89 /// The current include nesting level, used by header include dumping (-H).
90 unsigned CurrentIncludeDepth;
91
Reid Spencer5f016e22007-07-11 17:01:13 +000092 bool EmittedTokensOnThisLine;
Eli Friedman3e753e22009-06-02 07:55:39 +000093 bool EmittedMacroOnThisLine;
Chris Lattner9d728512008-10-27 01:19:25 +000094 SrcMgr::CharacteristicKind FileType;
Chris Lattnerd8e30832007-07-24 06:57:14 +000095 llvm::SmallString<512> CurFilename;
Daniel Dunbar737bdb42008-09-05 03:22:57 +000096 bool Initialized;
Eli Friedman12d3b1d2009-05-19 03:06:47 +000097 bool DisableLineMarkers;
98 bool DumpDefines;
Daniel Dunbarf7c16d92010-08-24 22:44:13 +000099 bool DumpHeaderIncludes;
Chris Lattnerf7449342009-12-07 01:42:56 +0000100 bool UseLineDirective;
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000101 bool HasProcessedPredefines;
Reid Spencer5f016e22007-07-11 17:01:13 +0000102public:
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000103 PrintPPOutputPPCallbacks(Preprocessor &pp, llvm::raw_ostream &os,
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000104 bool lineMarkers, bool defines, bool headers)
Chris Lattnerdf721402010-04-13 00:06:42 +0000105 : PP(pp), SM(PP.getSourceManager()),
106 ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000107 DumpDefines(defines), DumpHeaderIncludes(headers) {
108 CurLine = CurrentIncludeDepth = 0;
Chris Lattnerd8e30832007-07-24 06:57:14 +0000109 CurFilename += "<uninit>";
Reid Spencer5f016e22007-07-11 17:01:13 +0000110 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000111 EmittedMacroOnThisLine = false;
Chris Lattner0b9e7362008-09-26 21:18:42 +0000112 FileType = SrcMgr::C_User;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000113 Initialized = false;
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000114 HasProcessedPredefines = false;
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000115
Chris Lattnerf7449342009-12-07 01:42:56 +0000116 // If we're in microsoft mode, use normal #line instead of line markers.
117 UseLineDirective = PP.getLangOptions().Microsoft;
Reid Spencer5f016e22007-07-11 17:01:13 +0000118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000121 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Mike Stump1eb44332009-09-09 15:08:12 +0000122
Douglas Gregor80c60f72010-09-09 22:45:38 +0000123 bool StartNewLineIfNeeded();
124
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +0000126 SrcMgr::CharacteristicKind FileType);
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 virtual void Ident(SourceLocation Loc, const std::string &str);
Mike Stump1eb44332009-09-09 15:08:12 +0000128 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000129 const std::string &Str);
Chris Lattnerabfe0942010-06-26 17:11:39 +0000130 virtual void PragmaMessage(SourceLocation Loc, llvm::StringRef Str);
Reid Spencer5f016e22007-07-11 17:01:13 +0000131
Chris Lattner5f180322007-12-09 21:11:08 +0000132 bool HandleFirstTokOnLine(Token &Tok);
Chris Lattner88aae912010-04-13 00:01:41 +0000133 bool MoveToLine(SourceLocation Loc) {
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000134 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
135 if (PLoc.isInvalid())
136 return false;
137 return MoveToLine(PLoc.getLine());
Chris Lattner88aae912010-04-13 00:01:41 +0000138 }
139 bool MoveToLine(unsigned LineNo);
140
Chris Lattner88773212010-04-14 03:57:19 +0000141 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
142 const Token &Tok) {
143 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
Chris Lattnerd7038e12009-02-13 00:46:04 +0000144 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000145 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
Douglas Gregor80c60f72010-09-09 22:45:38 +0000146 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
Chris Lattner3ee211f2009-06-15 01:25:23 +0000147 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000149 /// MacroDefined - This hook is called whenever a macro definition is seen.
150 void MacroDefined(const IdentifierInfo *II, const MacroInfo *MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Benjamin Kramer2f054492010-08-07 22:27:00 +0000152 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
153 void MacroUndefined(SourceLocation Loc, const IdentifierInfo *II,
154 const MacroInfo *MI);
Reid Spencer5f016e22007-07-11 17:01:13 +0000155};
Chris Lattner5db17c92008-04-08 04:16:20 +0000156} // end anonymous namespace
Reid Spencer5f016e22007-07-11 17:01:13 +0000157
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000158void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
159 const char *Extra,
160 unsigned ExtraLen) {
Eli Friedman3e753e22009-06-02 07:55:39 +0000161 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000162 OS << '\n';
163 EmittedTokensOnThisLine = false;
Eli Friedman3e753e22009-06-02 07:55:39 +0000164 EmittedMacroOnThisLine = false;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000165 }
166
Chris Lattnerf7449342009-12-07 01:42:56 +0000167 // Emit #line directives or GNU line markers depending on what mode we're in.
168 if (UseLineDirective) {
169 OS << "#line" << ' ' << LineNo << ' ' << '"';
Ted Kremenek23465132010-09-17 00:41:18 +0000170 OS.write(CurFilename.data(), CurFilename.size());
Chris Lattnerf7449342009-12-07 01:42:56 +0000171 OS << '"';
172 } else {
173 OS << '#' << ' ' << LineNo << ' ' << '"';
Ted Kremenek23465132010-09-17 00:41:18 +0000174 OS.write(CurFilename.data(), CurFilename.size());
Chris Lattnerf7449342009-12-07 01:42:56 +0000175 OS << '"';
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000176
Steve Naroffd76fbda2009-12-06 01:02:14 +0000177 if (ExtraLen)
178 OS.write(Extra, ExtraLen);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000179
Steve Naroffd76fbda2009-12-06 01:02:14 +0000180 if (FileType == SrcMgr::C_System)
181 OS.write(" 3", 2);
182 else if (FileType == SrcMgr::C_ExternCSystem)
183 OS.write(" 3 4", 4);
184 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000185 OS << '\n';
186}
187
Reid Spencer5f016e22007-07-11 17:01:13 +0000188/// MoveToLine - Move the output to the source line specified by the location
189/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner5f180322007-12-09 21:11:08 +0000190/// #line directive. This returns false if already at the specified line, true
191/// if some newlines were emitted.
Chris Lattner88aae912010-04-13 00:01:41 +0000192bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000193 // If this line is "close enough" to the original line, just print newlines,
194 // otherwise print a #line directive.
Daniel Dunbarfd966842008-09-26 01:13:35 +0000195 if (LineNo-CurLine <= 8) {
Chris Lattner822f9402007-07-23 05:14:05 +0000196 if (LineNo-CurLine == 1)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000197 OS << '\n';
Chris Lattner5f180322007-12-09 21:11:08 +0000198 else if (LineNo == CurLine)
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000199 return false; // Spelling line moved, but instantiation line didn't.
Chris Lattner822f9402007-07-23 05:14:05 +0000200 else {
201 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattnere96de3e2008-08-17 03:12:02 +0000202 OS.write(NewLines, LineNo-CurLine);
Chris Lattner822f9402007-07-23 05:14:05 +0000203 }
Chris Lattner6133aeb2010-06-12 16:20:56 +0000204 } else if (!DisableLineMarkers) {
205 // Emit a #line or line marker.
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000206 WriteLineInfo(LineNo, 0, 0);
Chris Lattner6133aeb2010-06-12 16:20:56 +0000207 } else {
208 // Okay, we're in -P mode, which turns off line markers. However, we still
209 // need to emit a newline between tokens on different lines.
210 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
211 OS << '\n';
212 EmittedTokensOnThisLine = false;
213 EmittedMacroOnThisLine = false;
214 }
Mike Stump1eb44332009-09-09 15:08:12 +0000215 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000216
Mike Stump1eb44332009-09-09 15:08:12 +0000217 CurLine = LineNo;
Chris Lattner5f180322007-12-09 21:11:08 +0000218 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000219}
220
Douglas Gregor80c60f72010-09-09 22:45:38 +0000221bool PrintPPOutputPPCallbacks::StartNewLineIfNeeded() {
222 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
223 OS << '\n';
224 EmittedTokensOnThisLine = false;
225 EmittedMacroOnThisLine = false;
226 ++CurLine;
227 return true;
228 }
229
230 return false;
231}
Reid Spencer5f016e22007-07-11 17:01:13 +0000232
233/// FileChanged - Whenever the preprocessor enters or exits a #include file
234/// it invokes this handler. Update our conception of the current source
235/// position.
236void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
237 FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +0000238 SrcMgr::CharacteristicKind NewFileType) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000239 // Unless we are exiting a #include, make sure to skip ahead to the line the
240 // #include directive was at.
Chris Lattnerdf721402010-04-13 00:06:42 +0000241 SourceManager &SourceMgr = SM;
Chris Lattner88aae912010-04-13 00:01:41 +0000242
243 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000244 if (UserLoc.isInvalid())
245 return;
246
Chris Lattner86d0ef72010-04-14 04:28:50 +0000247 unsigned NewLine = UserLoc.getLine();
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000248
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 if (Reason == PPCallbacks::EnterFile) {
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000250 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
Chris Lattner71d8bfb2009-01-30 18:44:17 +0000251 if (IncludeLoc.isValid())
252 MoveToLine(IncludeLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000253 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
Chris Lattner88aae912010-04-13 00:01:41 +0000254 MoveToLine(NewLine);
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 // TODO GCC emits the # directive for this directive on the line AFTER the
257 // directive and emits a bunch of spaces that aren't needed. Emulate this
258 // strange behavior.
259 }
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000260
261 // Adjust the current include depth.
262 if (Reason == PPCallbacks::EnterFile) {
263 ++CurrentIncludeDepth;
264 } else {
265 if (CurrentIncludeDepth)
266 --CurrentIncludeDepth;
267
268 // We track when we are done with the predefines by watching for the first
269 // place where we drop back to a nesting depth of 0.
270 if (CurrentIncludeDepth == 0 && !HasProcessedPredefines)
271 HasProcessedPredefines = true;
272 }
Chris Lattner88aae912010-04-13 00:01:41 +0000273
274 CurLine = NewLine;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000275
Chris Lattnerd8e30832007-07-24 06:57:14 +0000276 CurFilename.clear();
Chris Lattner88aae912010-04-13 00:01:41 +0000277 CurFilename += UserLoc.getFilename();
Chris Lattnerd8e30832007-07-24 06:57:14 +0000278 Lexer::Stringify(CurFilename);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000279 FileType = NewFileType;
280
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000281 // Dump the header include information, if enabled and we are past the
282 // predefines buffer.
283 if (DumpHeaderIncludes && HasProcessedPredefines &&
284 Reason == PPCallbacks::EnterFile) {
Daniel Dunbar4566d1a2010-09-08 18:19:55 +0000285 // Write to a temporary string to avoid unnecessary flushing on errs().
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000286 llvm::SmallString<256> Msg;
287 llvm::raw_svector_ostream OS(Msg);
288 for (unsigned i = 0; i != CurrentIncludeDepth; ++i)
289 OS << '.';
290 OS << ' ' << CurFilename << '\n';
291 llvm::errs() << OS.str();
292 }
293
294 if (DisableLineMarkers) return;
295
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000296 if (!Initialized) {
297 WriteLineInfo(CurLine);
298 Initialized = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000299 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000300
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 switch (Reason) {
302 case PPCallbacks::EnterFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000303 WriteLineInfo(CurLine, " 1", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 break;
305 case PPCallbacks::ExitFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000306 WriteLineInfo(CurLine, " 2", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000307 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000308 case PPCallbacks::SystemHeaderPragma:
309 case PPCallbacks::RenameFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000310 WriteLineInfo(CurLine);
311 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000313}
314
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000315/// Ident - Handle #ident directives when read by the preprocessor.
Reid Spencer5f016e22007-07-11 17:01:13 +0000316///
317void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
318 MoveToLine(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Chris Lattnere96de3e2008-08-17 03:12:02 +0000320 OS.write("#ident ", strlen("#ident "));
321 OS.write(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000322 EmittedTokensOnThisLine = true;
323}
324
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000325/// MacroDefined - This hook is called whenever a macro definition is seen.
326void PrintPPOutputPPCallbacks::MacroDefined(const IdentifierInfo *II,
327 const MacroInfo *MI) {
328 // Only print out macro definitions in -dD mode.
329 if (!DumpDefines ||
330 // Ignore __FILE__ etc.
331 MI->isBuiltinMacro()) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000333 MoveToLine(MI->getDefinitionLoc());
334 PrintMacroDefinition(*II, *MI, PP, OS);
Eli Friedman3e753e22009-06-02 07:55:39 +0000335 EmittedMacroOnThisLine = true;
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000336}
337
Benjamin Kramer2f054492010-08-07 22:27:00 +0000338void PrintPPOutputPPCallbacks::MacroUndefined(SourceLocation Loc,
339 const IdentifierInfo *II,
340 const MacroInfo *MI) {
341 // Only print out macro definitions in -dD mode.
342 if (!DumpDefines) return;
343
344 MoveToLine(Loc);
345 OS << "#undef " << II->getName();
346 EmittedMacroOnThisLine = true;
347}
Chris Lattnerd82df3a2009-04-12 01:56:53 +0000348
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000349void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000350 const IdentifierInfo *Kind,
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000351 const std::string &Str) {
352 MoveToLine(Loc);
353 OS << "#pragma comment(" << Kind->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000354
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000355 if (!Str.empty()) {
356 OS << ", \"";
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000358 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
359 unsigned char Char = Str[i];
Chris Lattner52a3e9e2009-01-16 22:13:37 +0000360 if (isprint(Char) && Char != '\\' && Char != '"')
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000361 OS << (char)Char;
362 else // Output anything hard as an octal escape.
363 OS << '\\'
364 << (char)('0'+ ((Char >> 6) & 7))
365 << (char)('0'+ ((Char >> 3) & 7))
366 << (char)('0'+ ((Char >> 0) & 7));
367 }
368 OS << '"';
369 }
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000371 OS << ')';
372 EmittedTokensOnThisLine = true;
373}
374
Chris Lattnerabfe0942010-06-26 17:11:39 +0000375void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
376 llvm::StringRef Str) {
377 MoveToLine(Loc);
378 OS << "#pragma message(";
379
380 OS << '"';
381
382 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
383 unsigned char Char = Str[i];
384 if (isprint(Char) && Char != '\\' && Char != '"')
385 OS << (char)Char;
386 else // Output anything hard as an octal escape.
387 OS << '\\'
388 << (char)('0'+ ((Char >> 6) & 7))
389 << (char)('0'+ ((Char >> 3) & 7))
390 << (char)('0'+ ((Char >> 0) & 7));
391 }
392 OS << '"';
393
394 OS << ')';
395 EmittedTokensOnThisLine = true;
396}
397
Chris Lattnerc7d945d2009-01-16 19:25:54 +0000398
Reid Spencer5f016e22007-07-11 17:01:13 +0000399/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner5f180322007-12-09 21:11:08 +0000400/// is called for the first token on each new line. If this really is the start
401/// of a new logical line, handle it and return true, otherwise return false.
402/// This may not be the start of a logical line because the "start of line"
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000403/// marker is set for spelling lines, not instantiation ones.
Chris Lattner5f180322007-12-09 21:11:08 +0000404bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000405 // Figure out what line we went to and insert the appropriate number of
406 // newline characters.
Chris Lattner5f180322007-12-09 21:11:08 +0000407 if (!MoveToLine(Tok.getLocation()))
408 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Reid Spencer5f016e22007-07-11 17:01:13 +0000410 // Print out space characters so that the first token on a line is
411 // indented for easy reading.
Chris Lattnerdf721402010-04-13 00:06:42 +0000412 unsigned ColNo = SM.getInstantiationColumnNumber(Tok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 // This hack prevents stuff like:
415 // #define HASH #
416 // HASH define foo bar
417 // From having the # character end up at column 1, which makes it so it
418 // is not handled as a #define next time through the preprocessor if in
419 // -fpreprocessed mode.
Chris Lattner057aaf62007-10-09 18:03:42 +0000420 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattnere96de3e2008-08-17 03:12:02 +0000421 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Reid Spencer5f016e22007-07-11 17:01:13 +0000423 // Otherwise, indent the appropriate number of spaces.
424 for (; ColNo > 1; --ColNo)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000425 OS << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Chris Lattner5f180322007-12-09 21:11:08 +0000427 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000428}
429
Chris Lattner3ee211f2009-06-15 01:25:23 +0000430void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
431 unsigned Len) {
432 unsigned NumNewlines = 0;
433 for (; Len; --Len, ++TokStr) {
434 if (*TokStr != '\n' &&
435 *TokStr != '\r')
436 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Chris Lattner3ee211f2009-06-15 01:25:23 +0000438 ++NumNewlines;
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Chris Lattner3ee211f2009-06-15 01:25:23 +0000440 // If we have \n\r or \r\n, skip both and count as one line.
441 if (Len != 1 &&
442 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
443 TokStr[0] != TokStr[1])
444 ++TokStr, --Len;
445 }
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Chris Lattner3ee211f2009-06-15 01:25:23 +0000447 if (NumNewlines == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Chris Lattnered2d7c42009-06-15 04:08:28 +0000449 CurLine += NumNewlines;
Chris Lattner3ee211f2009-06-15 01:25:23 +0000450}
451
452
Reid Spencer5f016e22007-07-11 17:01:13 +0000453namespace {
454struct UnknownPragmaHandler : public PragmaHandler {
455 const char *Prefix;
456 PrintPPOutputPPCallbacks *Callbacks;
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Reid Spencer5f016e22007-07-11 17:01:13 +0000458 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000459 : Prefix(prefix), Callbacks(callbacks) {}
Douglas Gregor80c60f72010-09-09 22:45:38 +0000460 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
461 Token &PragmaTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000462 // Figure out what line we went to and insert the appropriate number of
463 // newline characters.
Douglas Gregorfe6834a2010-09-10 22:27:29 +0000464 Callbacks->StartNewLineIfNeeded();
Reid Spencer5f016e22007-07-11 17:01:13 +0000465 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattnere96de3e2008-08-17 03:12:02 +0000466 Callbacks->OS.write(Prefix, strlen(Prefix));
Douglas Gregor80c60f72010-09-09 22:45:38 +0000467 Callbacks->SetEmittedTokensOnThisLine();
Reid Spencer5f016e22007-07-11 17:01:13 +0000468 // Read and print all of the pragma tokens.
Chris Lattner057aaf62007-10-09 18:03:42 +0000469 while (PragmaTok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 if (PragmaTok.hasLeadingSpace())
Chris Lattnere96de3e2008-08-17 03:12:02 +0000471 Callbacks->OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000473 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 PP.LexUnexpandedToken(PragmaTok);
475 }
Douglas Gregor80c60f72010-09-09 22:45:38 +0000476 Callbacks->StartNewLineIfNeeded();
Reid Spencer5f016e22007-07-11 17:01:13 +0000477 }
478};
479} // end anonymous namespace
480
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000481
Chris Lattner59076ab2009-02-06 05:56:11 +0000482static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
483 PrintPPOutputPPCallbacks *Callbacks,
484 llvm::raw_ostream &OS) {
Benjamin Kramere3960072010-02-27 18:02:51 +0000485 char Buffer[256];
Chris Lattnerc54539c2010-06-15 21:06:38 +0000486 Token PrevPrevTok, PrevTok;
487 PrevPrevTok.startToken();
488 PrevTok.startToken();
Chris Lattner6f688e12007-10-10 20:45:16 +0000489 while (1) {
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Reid Spencer5f016e22007-07-11 17:01:13 +0000491 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner5f180322007-12-09 21:11:08 +0000492 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
493 // done.
Mike Stump1eb44332009-09-09 15:08:12 +0000494 } else if (Tok.hasLeadingSpace() ||
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000495 // If we haven't emitted a token on this line yet, PrevTok isn't
496 // useful to look at and no concatenation could happen anyway.
Chris Lattnerb638a302007-07-23 23:21:34 +0000497 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000498 // Don't print "-" next to "-", it would form "--".
Chris Lattner88773212010-04-14 03:57:19 +0000499 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
Chris Lattnere96de3e2008-08-17 03:12:02 +0000500 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 }
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Benjamin Kramere3960072010-02-27 18:02:51 +0000503 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
504 OS << II->getName();
505 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
506 Tok.getLiteralData()) {
507 OS.write(Tok.getLiteralData(), Tok.getLength());
508 } else if (Tok.getLength() < 256) {
509 const char *TokPtr = Buffer;
510 unsigned Len = PP.getSpelling(Tok, TokPtr);
511 OS.write(TokPtr, Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Benjamin Kramere3960072010-02-27 18:02:51 +0000513 // Tokens that can contain embedded newlines need to adjust our current
514 // line number.
515 if (Tok.getKind() == tok::comment)
516 Callbacks->HandleNewlinesInToken(TokPtr, Len);
517 } else {
518 std::string S = PP.getSpelling(Tok);
519 OS.write(&S[0], S.size());
520
521 // Tokens that can contain embedded newlines need to adjust our current
522 // line number.
523 if (Tok.getKind() == tok::comment)
524 Callbacks->HandleNewlinesInToken(&S[0], S.size());
525 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000526 Callbacks->SetEmittedTokensOnThisLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Chris Lattner6f688e12007-10-10 20:45:16 +0000528 if (Tok.is(tok::eof)) break;
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Chris Lattner88773212010-04-14 03:57:19 +0000530 PrevPrevTok = PrevTok;
Chris Lattner6f688e12007-10-10 20:45:16 +0000531 PrevTok = Tok;
532 PP.Lex(Tok);
533 }
Chris Lattner59076ab2009-02-06 05:56:11 +0000534}
535
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000536typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
537static int MacroIDCompare(const void* a, const void* b) {
538 const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
539 const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
540 return LHS->first->getName().compare(RHS->first->getName());
Chris Lattner2a2bb182009-02-10 22:28:19 +0000541}
Chris Lattner59076ab2009-02-06 05:56:11 +0000542
Daniel Dunbar775bee72009-11-11 10:07:22 +0000543static void DoPrintMacros(Preprocessor &PP, llvm::raw_ostream *OS) {
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000544 // Ignore unknown pragmas.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000545 PP.AddPragmaHandler(new EmptyPragmaHandler());
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000546
Eli Friedmanf1db5852009-05-19 01:32:34 +0000547 // -dM mode just scans and ignores all tokens in the files, then dumps out
548 // the macro table at the end.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000549 PP.EnterMainSourceFile();
Eli Friedmanf1db5852009-05-19 01:32:34 +0000550
551 Token Tok;
552 do PP.Lex(Tok);
553 while (Tok.isNot(tok::eof));
554
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000555 llvm::SmallVector<id_macro_pair, 128>
556 MacrosByID(PP.macro_begin(), PP.macro_end());
557 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
Eli Friedmanf1db5852009-05-19 01:32:34 +0000558
559 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
560 MacroInfo &MI = *MacrosByID[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000561 // Ignore computed macros like __LINE__ and friends.
Eli Friedmanf1db5852009-05-19 01:32:34 +0000562 if (MI.isBuiltinMacro()) continue;
563
564 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
Benjamin Kramer3ff2a4b2010-01-19 17:42:20 +0000565 *OS << '\n';
Eli Friedmanf1db5852009-05-19 01:32:34 +0000566 }
567}
568
Chris Lattner59076ab2009-02-06 05:56:11 +0000569/// DoPrintPreprocessedInput - This implements -E mode.
570///
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000571void clang::DoPrintPreprocessedInput(Preprocessor &PP, llvm::raw_ostream *OS,
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000572 const PreprocessorOutputOptions &Opts) {
Daniel Dunbar775bee72009-11-11 10:07:22 +0000573 // Show macros with no output is handled specially.
574 if (!Opts.ShowCPP) {
575 assert(Opts.ShowMacros && "Not yet implemented!");
576 DoPrintMacros(PP, OS);
577 return;
578 }
579
Chris Lattner59076ab2009-02-06 05:56:11 +0000580 // Inform the preprocessor whether we want it to retain comments or not, due
581 // to -C or -CC.
Daniel Dunbar775bee72009-11-11 10:07:22 +0000582 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
Eli Friedmanf54fce82009-05-19 01:02:07 +0000583
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000584 PrintPPOutputPPCallbacks *Callbacks =
Daniel Dunbar775bee72009-11-11 10:07:22 +0000585 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
Daniel Dunbarf7c16d92010-08-24 22:44:13 +0000586 Opts.ShowMacros, Opts.ShowHeaderIncludes);
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000587 PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
Chris Lattner13973992010-11-10 01:00:49 +0000588 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
589 PP.AddPragmaHandler("clang",
590 new UnknownPragmaHandler("#pragma clang", Callbacks));
Chris Lattner59076ab2009-02-06 05:56:11 +0000591
Kovarththanan Rajaratnama5d10c42010-03-07 07:30:06 +0000592 PP.addPPCallbacks(Callbacks);
Chris Lattner59076ab2009-02-06 05:56:11 +0000593
Eli Friedmanf1db5852009-05-19 01:32:34 +0000594 // After we have configured the preprocessor, enter the main file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000595 PP.EnterMainSourceFile();
Chris Lattner59076ab2009-02-06 05:56:11 +0000596
Eli Friedmanf1db5852009-05-19 01:32:34 +0000597 // Consume all of the tokens that come from the predefines buffer. Those
598 // should not be emitted into the output and are guaranteed to be at the
599 // start.
600 const SourceManager &SourceMgr = PP.getSourceManager();
601 Token Tok;
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000602 do {
603 PP.Lex(Tok);
604 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
605 break;
606
607 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
608 if (PLoc.isInvalid())
609 break;
610
611 if (strcmp(PLoc.getFilename(), "<built-in>"))
612 break;
613 } while (true);
Chris Lattner59076ab2009-02-06 05:56:11 +0000614
Eli Friedmanf1db5852009-05-19 01:32:34 +0000615 // Read all the preprocessed tokens, printing them out to the stream.
616 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
617 *OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000618}
619